485780692661ec869f4b23a0862d1e03b29ac233
[wolnelektury.git] / wolnelektury / static / js / catalogue.js
1 var STATIC = '/static/';
2 var LOCALE_TEXTS = {
3     "pl": {
4         "DELETE_SHELF": "Czy na pewno usunąć półkę",
5         "HIDE_DESCRIPTION": "Zwiń opis",
6         "EXPAND_DESCRIPTION": "Rozwiń opis",
7         "LOADING": "Ładowanie"
8     },
9     "de": {
10         "DELETE_SHELF": "Möchtest du wirklich dieses Bücherregal entfernen?",
11         "HIDE_DESCRIPTION": "Beschreibung zuklappen",
12         "EXPAND_DESCRIPTION": "Beschreibung aufklappen",
13         "LOADING": "Herunterladen"
14     },
15     "fr": {
16         "DELETE_SHELF": "Voulez-vous supprimer l'étagère  définitivement?",
17         "HIDE_DESCRIPTION": "Montrer la description",
18         "EXPAND_DESCRIPTION": "Cacher la description",
19         "LOADING": "Chargement"
20     },
21     "en": {
22         "DELETE_SHELF": "Are you sure you want to delete this shelf?",
23         "HIDE_DESCRIPTION": "Hide",
24         "EXPAND_DESCRIPTION": "Expand",
25         "LOADING": "Loading"
26     },
27     "ru": {
28         "DELETE_SHELF": "Уверены ли вы том, чтобы удалить полку?",
29         "HIDE_DESCRIPTION": "Свернуть описание",
30         "EXPAND_DESCRIPTION": "Раскрыть описание",
31         "LOADING": "Загрузка"
32     },
33     "es": {
34         "DELETE_SHELF": "¿Estás seguro que quieres borrar este estante?",
35         "HIDE_DESCRIPTION": "Esconder la descripción",
36         "EXPAND_DESCRIPTION": "Ampliar la descripción",
37         "LOADING": "Cargando"
38     },
39     "lt":{
40         "DELETE_SHELF": "Ar tikrai nori pašalinti lentną?",
41         "HIDE_DESCRIPTION": "Suvyniok aprašymą ",
42         "EXPAND_DESCRIPTION": "Išplėsk aprašymą",
43         "LOADING": "Krovimas"
44     },
45     "uk":{
46         "DELETE_SHELF": "Ви впевнені, що хочете видалити полицю?",
47         "HIDE_DESCRIPTION": "Сховати опис",
48         "EXPAND_DESCRIPTION": "Показати опис",
49         "LOADING": "Завантажується"
50     }
51 }
52 var BANNER_TEXTS = [
53     'Przekaż 1% żeby ukryć ten baner.',
54     'Jak dobrze wydać 1% swojego podatku? <strong>Poradnik dla opornych</strong>.',
55     'Wiadomość systemowa: wystąpił błąd brak funduszy. Wykonaj procedurę 1%.',
56     '<strong>FREE!</strong> Wygraj darmowe lektury!',
57     'Confidential business offer. Not scam! 1% for you.',
58     'Biblioteka Wolne Lektury wymaga aktualizacji. Kliknij dalej.',
59     '1000 lektur. <strong>1 procent</strong>.',
60     '1% dla biblioteki lektur szkolnych. 1% dla Twojej biblioteki.',
61     '1% na lektury szkolne.',
62     '1% dla wolności lektur szkolnych.',
63     'Podaruj Jeden Procent na rzecz szkolnej biblioteki internetowej.',
64     '1% podatku dla biblioteki szkolnej Wolne Lektury.',
65     '1% na rzecz darmowego dostępu do szkolnych lektur.',
66     'Żeby czytać teksty a nie skany. Przekaż 1%.',
67     'Czytaj teksty a nie skany. Przekaż 1%',
68     'Motyw artysty w literaturze - 47 cytatów. Pomóż znaleźć następne.',
69     'Twój 1% uwolni więcej lektur.',
70     'Ponad 400 motywów, blisko 10 000 000 cytatów. Pomóż znaleźć następne. Przekaż swój 1%.',
71     'Twój 1% uwolni lektury.',
72     'Rozlicz swój PIT z Wolnymi Lekturami. Skorzystaj z darmowego programu do rozliczania podatków.',
73     'Lektury 2010: Pan Tadeusz, Trylogia.',
74     'Pan Tadeusz też chce być w Internecie! Przekaż 1% swojego podatku.',
75     'Pomóż uwolnić 286 utworów z listy lektur szkolnych. Przekaż swój 1% na Wolne Lektury.'
76 ]
77
78 function changeBannerText() {
79     var index = Math.floor(Math.random() * BANNER_TEXTS.length);
80     if (BANNER_TEXTS[index] == $('#onepercent-text').html()) {
81         // try again
82         changeBannerText();
83     } else {
84         $('#onepercent-text').fadeOut('slow', function() {
85             $(this).html(BANNER_TEXTS[index]);
86             $(this).fadeIn('slow');
87         });
88
89         setTimeout(changeBannerText, 30 * 1000);
90     }
91 }
92
93 function autocomplete_format_item(ul, item) {
94     return $("<li></li>").data('item.autocomplete', item)
95     .append('<a href="'+item.url+'">'+item.label+ ' ('+item.category+')</a>')
96     .appendTo(ul);
97 }
98
99 function autocomplete_result_handler(event, ui) {
100     if (ui.item.url != undefined) {
101         location.href = ui.item.url;
102     } else {
103         $(event.target).closest('form').submit();
104     }
105 }
106
107 function serverTime() {
108     var time = null;
109     $.ajax({url: '/katalog/zegar/',
110         async: false, dataType: 'text',
111         success: function(text) {
112             time = new Date(text);
113         }, error: function(http, message, exc) {
114             time = new Date();
115     }});
116     return time;
117 }
118
119 (function($) {
120     $(function() {
121
122         $.fn.toggle_slide = function(p) {
123             cont = $(this);
124             short_el = p['short_el'] || $(':first-child', this);
125             long_el = p['long_el'] || short_el.next();
126             button = p['button'];
127             short_text = p['short_text'],
128             long_text = p['long_text'];
129
130             var toggle_fun = function(cont, short_el, long_el, button, short_text, long_text) {
131                 var toggle = function() {
132                     if (cont.hasClass('short')) {
133                         cont.animate({"height": long_el.attr("cont_h")+'px'}, {duration: "fast" }).removeClass('short');
134                         short_el.hide();
135                         long_el.show();
136                         if (button && long_text) button.html(long_text);
137                     } else {
138                         cont.animate({"height": short_el.attr("cont_h")+'px'}, {duration: "fast" }).addClass('short');
139                         long_el.hide();
140                         short_el.show();
141                         if (button && short_text) button.html(short_text);
142                     }
143                     return false;
144                 }
145                 return toggle;
146             }
147             if (long_el.html().length <= short_el.html().length)
148                 return;
149
150             // ensure long element shown first
151             long_el.show();short_el.hide();
152             long_el.attr("cont_h", $(this).height()).hide();
153             short_el.show().attr("cont_h", $(this).height());
154             $(this).addClass('short');
155
156             if (button && short_text) button.html(short_text);
157             if (button) button.hover(
158                 function() { $(this).css({background: '#F3F3F3', cursor: 'pointer'}); },
159                 function() { $(this).css({background: '#EEE'}); }
160             ).click(toggle_fun(cont, short_el, long_el, button, short_text, long_text));
161             short_el.hover(
162                 function() { $(this).css({background: '#F3F3F3', cursor: 'pointer'}); },
163                 function() { $(this).css({background: '#FFF'}); }
164             ).click(toggle_fun(cont, short_el, long_el, button, short_text, long_text));
165             long_el.hover(
166                 function() { $(this).css({background: '#F3F3F3', cursor: 'pointer'}); },
167                 function() { $(this).css({background: '#FFF'}); }
168             ).click(toggle_fun(cont, short_el, long_el, button, short_text, long_text));
169         };
170
171         $('form input').labelify({labelledClass: 'blur'});
172
173         target = $('#login-register-window div.target');
174
175         $('#show-registration-form').click(function() {
176             $('#login-form').hide();
177             $('#registration-form').show();
178         });
179
180         $('#show-login-form').click(function() {
181             $('#registration-form').hide();
182             $('#login-form').show();
183         });
184
185         // Fragments
186         $('.fragment-short-text').each(function() {
187             var fragment = $(this).closest('.fragment');
188             fragment.toggle_slide({
189                 short_el: $(this),
190                 long_el: fragment.find('.fragment-text')
191             })
192         });
193
194         $('.show-all-tags').click(function() {
195             $(this).parent().parent().fadeOut(function() {
196                 $(this).next().fadeIn();
197             });
198             return false;
199         });
200
201         $('.hide-all-tags').click(function() {
202            $(this).parent().parent().fadeOut(function() {
203                $(this).prev().fadeIn();
204            });
205            return false;
206         });
207
208         $('#registration-form').ajaxForm({
209             dataType: 'json',
210             beforeSubmit: function() {
211                 $('#registration-form input[type=submit]')
212                     .attr('disabled', 'disabled')
213                     .after('<img src="/static/img/indicator.gif" style="margin-left: 0.5em"/>');
214             },
215             success: function(response) {
216                 if (response.success) {
217                     location.reload(true);
218                 } else {
219                     $('#registration-form span.error').remove();
220                     $.each(response.errors, function(id, errors) {
221                         $('#id_registration-' + id).before('<span class="error">' + errors[0] + '</span>');
222                     });
223                     $('#registration-form input[type=submit]').removeAttr('disabled');
224                     $('#registration-form img').remove();
225                 }
226             }
227         });
228
229         $('#login-form').ajaxForm({
230             dataType: 'json',
231             beforeSubmit: function() {
232                 $('#login-form input[type=submit]')
233                     .attr('disabled', 'disabled')
234                     .after('<img src="/static/img/indicator.gif" style="margin-left: 0.5em"/>');
235             },
236             success: function(response) {
237                 if (response.success) {
238                     location.reload(true);
239                 } else {
240                     $('#login-form span.error').remove();
241                     $.each(response.errors, function(id, errors) {
242                         $('#id_login-' + id).before('<span class="error">' + errors[0] + '</span>');
243                     });
244                     $('#login-form input[type=submit]').removeAttr('disabled');
245                     $('#login-form img').remove();
246                 }
247             }
248         });
249
250         $('#login-register-window').jqm({
251             target: target[0],
252             overlay: 60,
253             trigger: '.login-register-link',
254             onShow: function(hash) {
255                 var offset = $(hash.t).offset();
256                 hash.w.css({position: 'absolute', left: offset.left - hash.w.width() + $(hash.t).width(), top: offset.top});
257                 $('div.header', hash.w).css({width: $(hash.t).width()});
258                 hash.w.show();
259             }
260         });
261
262         $('ul.shelf-list li').hover(function() {
263             $(this).css({background: '#EEE', cursor: 'pointer'});
264         }, function() {
265             $(this).css({background: 'transparent'});
266         }).click(function() {
267             location.href = $('a.visit-shelf', this).attr('href');
268         });
269
270         $('.delete-shelf').click(function() {
271             var link = $(this);
272             var shelf_name = $('.visit-shelf', link.parent()).text();
273             if (confirm(LOCALE_TEXTS[LANGUAGE_CODE]['DELETE_SHELF']+ ' '+ shelf_name + '?')) {
274                 $.post(link.attr('href'), function(data, textStatus) {
275                     link.parent().remove();
276                 });
277             }
278             return false;
279         });
280
281         var serverResponse;
282         $('#user-shelves-window').jqm({
283             ajax: '@href',
284             target: $('#user-shelves-window div.target')[0],
285             overlay: 60,
286             trigger: '#user-shelves-link',
287             onShow: function(hash) {
288                 var offset = $(hash.t).offset();
289                 hash.w.css({position: 'absolute', left: offset.left - hash.w.width() + $(hash.t).width(), top: offset.top});
290                 $('div.header', hash.w).css({width: $(hash.t).width()});
291                 hash.w.show();
292             },
293             onLoad: function(hash) {
294                 $('form', hash.w).ajaxForm({
295                     target: serverResponse,
296                     success: function(serverResponse) {
297                         var newShelf = $.parseJSON(serverResponse);
298                         $('#user-shelves-window div.target').html(newShelf.msg);
299                         setTimeout(function() { $('#user-shelves-window').jqmHide() }, 1000);
300                     }
301                 });
302
303                 $('input', hash.w).labelify({labelledClass: 'blur'});
304
305                 $('ul.shelf-list li', hash.w).hover(function() {
306                     $(this).css({background: '#EEE', cursor: 'pointer'});
307                 }, function() {
308                     $(this).css({background: 'transparent'});
309                 }).click(function() {
310                     location.href = $('a.visit-shelf', this).attr('href');
311                 });
312
313                 $('.delete-shelf').click(function() {
314                     var link = $(this);
315                     var shelf_name = $('.visit-shelf', link.parent()).text();
316                     if (confirm(LOCALE_TEXTS[LANGUAGE_CODE]['DELETE_SHELF'] + ' ' + shelf_name + '?')) {
317                         $.post(link.attr('href'), function(data, textStatus) {
318                             link.parent().remove();
319                         });
320                     }
321                     return false;
322                 });
323             }
324         });
325
326         $('#suggest-window').jqm({
327             ajax: '@href',
328             target: $('#suggest-window div.target')[0],
329             overlay: 60,
330             trigger: '#suggest-link',
331             onShow: function(hash) {
332                 var offset = $(hash.t).offset();
333                 hash.w.css({position: 'absolute', left: offset.left - hash.w.width() + $(hash.t).width(), top: offset.top});
334                 $('div.header', hash.w).css({width: $(hash.t).width()});
335                 hash.w.show();
336             },
337             onLoad: function(hash) {
338                 $('form', hash.w).ajaxForm({
339                     dataType: 'json',
340                     target: $('#suggest-window div.target'),
341                     success: function(response) {
342                         if (response.success) {
343                             $('#suggest-window div.target').text(response.message);
344                             setTimeout(function() { $('#suggest-window').jqmHide() }, 1000)
345                         }
346                         else {
347                             $('#suggest-form .error').remove();
348                             $.each(response.errors, function(id, errors) {
349                                 $('#suggest-form #id_' + id).before('<span class="error">' + errors[0] + '</span>');
350                             });
351                             $('#suggest-form input[type=submit]').removeAttr('disabled');
352                             return false;
353                         }
354                     }
355                 });
356             }
357         });
358
359         $('#suggest-publishing-window').jqm({
360             ajax: '@data-ajax',
361             target: $('#suggest-publishing-window div.target')[0],
362             overlay: 60,
363             trigger: '#suggest-publishing-link',
364             onShow: function(hash) {
365                 var offset = $(hash.t).offset();
366                 hash.w.css({position: 'absolute', left: offset.left - hash.w.width() + $(hash.t).width(), top: offset.top});
367                 $('div.header', hash.w).css({width: $(hash.t).width()});
368                 hash.w.show();
369             },
370             onLoad: function(hash) {
371                 $('form', hash.w).each(function() {this.action += '?ajax=1';});
372                 $('form', hash.w).ajaxForm({
373                     dataType: 'json',
374                     target: $('#suggest-publishing-window div.target'),
375                     success: function(response) {
376                         if (response.success) {
377                             $('#suggest-publishing-window div.target').text(response.message);
378                             setTimeout(function() { $('#suggest-publishing-window').jqmHide() }, 1000)
379                         }
380                         else {
381                             $('#suggest-publishing-form .error').remove();
382                             $.each(response.errors, function(id, errors) {
383                                 $('#suggest-publishing-form #id_' + id).before('<span class="error">' + errors[0] + '</span>');
384                             });
385                             $('#suggest-publishing-form input[type=submit]').removeAttr('disabled');
386                             return false;
387                         }
388                     }
389                 });
390             }
391         });
392
393         (function($this) {
394             $form = $('form', $this);
395             $form.each(function() {this.action += '?ajax=1';});
396             $form.ajaxForm({
397                 dataType: 'json',
398                 target: $this,
399                 success: function(response) {
400                     if (response.success) {
401                         $this.text(response.message);
402                     }
403                     else {
404                         $('.error', $form).remove();
405                         $.each(response.errors, function(id, errors) {
406                             $('#id_' + id, $form).before('<span class="error">' + errors[0] + '</span>');
407                         });
408                         $('input[type=submit]', $form).removeAttr('disabled');
409                         return false;
410                     }
411                 }
412             });
413         })($('.block-form'));
414         
415         $('#books-list .book').hover(
416             function() { $(this).css({background: '#F3F3F3', cursor: 'pointer'}); },
417             function() { $(this).css({background: '#FFF'}); }
418         ).click(function() {
419             location.href = $('h2 a', this).attr('href');
420         });
421
422         $('#description').each(function(){$(this).toggle_slide({
423             long_el: $('#description-long', this),
424             short_el: $('#description-short', this),
425             button: $(this).nextAll('#toggle-description').first().find('p'),
426             long_text: LOCALE_TEXTS[LANGUAGE_CODE]['HIDE_DESCRIPTION'] + ' ▲',
427             short_text: LOCALE_TEXTS[LANGUAGE_CODE]['EXPAND_DESCRIPTION'] + ' ▼'
428         })});
429
430         $('#toggle-share-shelf').hover(
431             function() { $(this).css({background: '#F3F3F3', cursor: 'pointer'}); },
432             function() { $(this).css({background: '#EEE'}); }
433         ).click(function() {
434             if ($('#share-shelf').hasClass('hidden')) {
435                 $('#share-shelf').slideDown('fast').removeClass('hidden');
436             } else {
437                 $('#share-shelf').slideUp('fast').addClass('hidden');
438             }
439         });
440
441         var target = $('#set-window div.target');
442
443         $('#set-window').jqm({
444             ajax: '@href',
445             target: target[0],
446             overlay: 60,
447             trigger: 'a.jqm-trigger',
448             onShow: function(hash) {
449                 var offset = $(hash.t).offset();
450                 target.html('<p><img src="/static/img/indicator.gif" />'+LOCALE_TEXTS[LANGUAGE_CODE]['DELETE_SHELF']+'</p>');
451                 hash.w.css({position: 'absolute', left: offset.left, top: offset.top}).show() },
452             onLoad: function(hash) {
453                 try {
454                         $('#createShelfTrigger').click(function(){
455                             // who cares it's not needed, but I was looking for it
456                             // that's why I want it to stay.. :) 
457                             // var slug = $(hash.t).attr('href').split("/")[3];
458                             $('#createNewShelf').show();
459                         });
460                 } catch (e){}
461                 var serverResponse;
462                 $('form', hash.w).ajaxForm({
463                     target: serverResponse,
464                     success: function(serverResponse) {
465                         var newShelf = $.parseJSON(serverResponse);
466                         // for live shelf adding
467                         if(newShelf.name){
468                             var noIds = $("#putOnShelf ol ul").children('li').length;
469                             $("#putOnShelf ol ul").prepend('<li><label for="id_set_ids_'+ noIds +'"><input name="set_ids" value="'+ newShelf.id +'" id="id_set_ids_'+ noIds +'" type="checkbox" checked="checked"> '+ newShelf.name +' (0)</label></li>');
470                             $("#createNewShelf ol input[name=name]").val("");
471                         }
472                         if(newShelf.after == "close"){
473                             setTimeout(function() {$('#set-window').jqmHide();}, 1000);
474                         }
475                     }
476                 });    
477             }
478         });
479
480         $('a.remove-from-shelf').click(function(event) {
481             event.preventDefault();
482             link = $(this);
483             $.post(link.attr('href'), function(data, textStatus) {
484                 link.parent().remove();
485             });
486         });
487
488         $('#share-shelf').hide().addClass('hidden');
489         $('#share-shelf input').focus(function(){this.select();});
490
491         $('#user-info').show();
492         changeBannerText();
493         $('#onepercent-banner').show();
494
495         var formatsDownloaded = false;
496         $('#download-shelf').click(function() {
497             $('#download-shelf-menu').slideDown('fast');
498
499             if (!formatsDownloaded) {
500                 // Get info about the formats
501                 formatsDownloaded = true;
502                 $.ajax({
503                     url: $('#download-formats-form').attr('data-formats-feed'),
504                     type: 'GET',
505                     dataType: 'json',
506                     complete: function() {
507                         $('#download-formats-form-submit').attr('disabled', null);
508                         $('#download-formats-form-submit-li img').remove();
509                         $('#updating-formats').fadeOut('fast', function() {
510                             $('#formats-updated').fadeIn('fast');
511                         });
512                     },
513                     success: function(data) {
514                         $('#download-formats-form li').each(function() {
515                             var item = $(this);
516                             if (!!item.attr('data-format') && !data[item.attr('data-format')]) {
517                                 item.fadeOut('fast', function() {
518                                     item.remove();
519                                 });
520                             }
521                         });
522                     }
523                 });
524             }
525             return false;
526         });
527
528         $('#download-formats-form-cancel').click(function() {
529             $('#download-shelf-menu').slideUp('fast');
530             return false;
531         });
532
533         $('.sponsor-logos').cycle({timeout: 3000});
534
535         $('.widget-code').focus(
536             function(){
537                 $(this).animate({rows: '11'}, 100, function(){
538                     this.select();
539                     $(this).click(function(){
540                         this.select();
541                     });
542                 })
543                 
544             } 
545         ).blur(
546             function(){
547                 $(this).animate({rows: '1'}, 300, function(){
548                     $(this).unbind('click');
549                 })
550             } 
551         );
552         
553         $('.book-list-index').click(function(){
554             $('.book-list-show-index').hide('slow');
555             if($(this).parent().next('ul:not(:hidden)').length == 0){
556                 $(this).parent().next('ul').toggle('slow');
557             }
558             return false;
559         });
560
561         // player for audiobooks
562  
563         // event handlers for playing different formats
564         $('.audiotabs span').click(function(){
565             $('.audiobook-list').hide();
566             $('.audiotabs .active').removeClass('active');
567             // we don't want to interact with "audiobook" label, just 'format' tabs
568             var $this = $(this);
569             $this.addClass("active");
570             $("#"+$this.attr('data-format')+"-files").show();
571         });
572
573         $('.audiobook-list').hide();
574         if($(".audiotabs .active").length > 0) {
575             $("#"+$(".audiotabs .active").html().toLowerCase()+"-files").show();
576         }
577         
578         /* this will be useful for javascript html player
579         var medias = $('.audiobook-list a');
580         var mp3List = [];
581         var oggList = [];
582         var daisyList = [];
583         var tmpExt;
584         if (medias.length > 0) {
585             // creating sources list for player
586             medias.each(function(index, item) {
587                 tmpExt = item.href.split(".").pop();    
588                 if(tmpExt == "mp3") {
589                     mp3List.push(item.href);
590                 } else if (tmpExt == "ogg") {
591                     oggList.push(item.href);
592                 } else if(tmpExt == "daisy") {
593                     daisyList.push(item.href);
594                 }
595             }); 
596         }*/       
597         $("#custom-pdf-link").toggle(
598             function(ev) { $(".custom-pdf").show(); return false; },
599             function(ev) { $(".custom-pdf").hide(); return false; }
600         );
601     });
602 })(jQuery)
603