]> git.0d.be Git - panikweb-esperanzah.git/blob - panikweb_esperanzah/static/js/specifics.js
b1f62771d92a5fece40d89ca2381a2f95af4aab5
[panikweb-esperanzah.git] / panikweb_esperanzah / static / js / specifics.js
1 var urlParams;
2 var connection;
3
4 (window.onpopstate = function () {
5     var match,
6         pl     = /\+/g,  // Regex for replacing addition symbol with a space
7         search = /([^&=]+)=?([^&]*)/g,
8         decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
9         query  = window.location.search.substring(1);
10
11     urlParams = {};
12     while (match = search.exec(query))
13        urlParams[decode(match[1])] = decode(match[2]);
14 })();
15
16 $(function() {
17
18         doLog = function(aTextToLog, type){
19                 var aLog = $('<div>',{'class':"log "+type,html:aTextToLog});
20                 aLog.hide().prependTo($log).show('fast').delay(3000).hide('fast', function() { 
21                         $(this).remove(); 
22                 });
23         }
24         var $main = $("#Changing");
25         var $metaNav = $("#metaNav");
26         var $log = $("#userLog");
27
28         /****************************************************/
29         /**** AJAX UTILITIES FOR REQUESTS ****/
30         /****************************************************/
31         String.prototype.decodeHTML = function() {
32                 return $("<div>", {html: "" + this}).html();
33         };
34         var loadPage_request = null;
35         afterLoad = function(html, textStatus, XMLHttpRequest) {
36                 $('#loading-page').addClass('fade');
37                 loadPage_request = null;
38                 if (textStatus == "error") {
39                         doLog('Sorry! And error occur when loading page content','error');
40                 }
41                 if (connection) { connection.disconnect(); }
42                 new_html = $.parseHTML(html);
43                 new_content = $(new_html).find('#Changing>*');
44                 $main.hide().empty().append(new_content).show();
45
46                 /* calling onpopstate here is necessary to get urlParams to be
47                  * updated */
48                 window.onpopstate();
49
50                 canonical_href_node = $.grep($(new_html), function(elem, idx) {
51                         return (elem.nodeName === "LINK" && elem.attributes['rel'].value == "canonical");
52                 })[0];
53                 if (canonical_href_node) {
54                         canonical_href = canonical_href_node.attributes['href'].value;
55                         try { history.replaceState({}, '', canonical_href); } catch(ex) {};
56                 }
57
58                 new_menu = $($.parseHTML(html)).find('#metaNav>*');
59                 $metaNav.empty().append(new_menu);
60
61                 var newTitle = html?html.match(/<title>(.*?)<\/title>/):'';
62                 if(newTitle){document.title = newTitle[1].trim().decodeHTML();}
63
64                 /*
65                 Quite UGLY but needed for styling the whole body with ID
66                 Feel free to correct and find a better way
67                 According to this link the probles is that $(html).filter('body').Attr('id') will not work!
68                 http://www.devnetwork.net/viewtopic.php?f=13&t=117065
69                 */
70                 if(sectionName = $(html).find('[data-section]').attr('data-section')){
71                         $('body').attr('id',sectionName);
72                 }else{
73                         var bodyID = html.match(/<body id="(.*?)">/);   
74                         if(bodyID){$('body').attr('id',bodyID[1].trim());}      
75                 }
76                 init();
77                 document.documentElement.scrollTop = document.body.scrollTop = 0;
78
79                 if (typeof (Piwik) == 'object') {
80                         piwikTracker = Piwik.getAsyncTracker();
81                         if (typeof (piwikTracker.trackPageView) == 'function') {
82                                 piwikTracker.setDocumentTitle(document.title);
83                                 piwikTracker.setCustomUrl(window.location.href);
84                                 piwikTracker.trackPageView();
85                                 $('.audio a').each(function() {
86                                         piwikTracker.addListener(this);
87                                 });
88                         }
89                 }
90
91         };
92
93         function afterLoadError(xhr, text, error) {
94                 afterLoad(xhr.responseText, 'error', xhr);
95         };
96
97         $(window).on("popstate", function(e) {
98                 loadPage(location.href, false);
99         });
100
101         loadPage = function(href, push_state) {
102                 if (push_state !== false) {
103                         history.pushState({}, '', href);
104                 }
105                 if (loadPage_request !== null) {
106                         loadPage_request.abort();
107                 }
108                 $('#loading-page').remove();
109                 $('<div id="loading-page"></div>').prependTo($('#All'));
110                 loadPage_request = $.ajax({
111                         url: href,
112                         success: afterLoad,
113                         error: afterLoadError,
114                         dataType: 'html'});
115         };
116         $.fn.ajaxifyClick = function(params) {
117                 if ($('#df-wpr-sidebar').length > 0) {
118                         /* this is fiber sidebar, it doesn't work well with
119                          * seamless page loading */
120                         return;
121                 }
122                 this.each(function() {
123                         if ($(this).parents('.leaflet-control').length) {
124                                 // don't touch leaflet control links
125                                 return;
126                         }
127                         var href = $(this).attr("href");
128                         if (!href || href.match('\.(ogg|mp3|pdf|odt|ods|doc|xls|docx|xlsx|rtf|zip|rss|atom)$')) {
129                                 // don't touch empty <a> or links to downloadable files
130                                 return;
131                         }
132                         if ($(this).attr('target')) {
133                                 // don't touch links with an explicit target
134                                 return;
135                         }
136                         $(this).unbind('click');
137                         $(this).bind('click',function(e){
138                                 var href = $(this).attr("href");
139                                 if (e.which == 2) {
140                                         window.open(href, '_blank');
141                                         return false;
142                                 }
143                                 $(this).addClass('loading');
144                                 /* this checks the link points to a local document, be
145                                  * it because it's just a path, or because the server
146                                  * part points to the same domain */
147                                 if (!href) {
148                                         doLog('No href attributes, unable to load content','error');
149                                         $("#All a, #All area").removeClass('loading');
150                                         return false;
151                                 }else if (!$(this).attr('target') && (
152                                                 href.indexOf(document.domain) > -1 ||href.indexOf(':') === -1 || href.indexOf(':') > 5
153                                         )) {
154                                         if ($(this).data('replace')) {
155                                                 loadPage(href, false, $(this).data('replace'));
156                                         } else {
157                                                 loadPage(href);
158                                         }
159                                         return false;
160                                 }else{
161                                         $(this).attr('target','_blank');
162                                         $(this).attr('rel', 'noopener');
163                                         $("#All a, #All area").removeClass('loading');
164                                         return true;
165                                 }
166                         });
167                 });
168         };
169         /****************************************************/
170         /**** AUDIOPLAYER ****/
171         /****************************************************/
172
173         var timer = null;
174         var ticker_interval = null;
175         $('#WhatsOnAir').on('load',function(){
176                 var WhatsOnAir = $(this);
177                 $.getJSON('/onair.json', function(onair) {
178                         var onairContainer = $('<span>');
179                         if(onair.data.episode || onair.data.emission) {
180                                 $('body').removeClass('nothing-playing');
181                                 if(onair.data.emission){
182                                         $('<a>',{href:onair.data.emission.url,html:onair.data.emission.title}).appendTo(onairContainer).ajaxifyClick();
183                                 }
184                                 if(onair.data.episode){
185                                         $('<span> - </span>').appendTo(onairContainer);
186                                         $('<a>',{href:onair.data.episode.url,html:onair.data.episode.title}).appendTo(onairContainer).ajaxifyClick();
187                                 }
188                         } else if (onair.data.nonstop) {
189                                 $('body').removeClass('nothing-playing');
190                                 if (onair.data.nonstop.url) {
191                                         onairContainer = $('<a href="' + onair.data.nonstop.url + '">' + onair.data.nonstop.title + '</a>');
192                                 } else {
193                                         onairContainer = $('<span>' + onair.data.nonstop.title + '</span>');
194                                 }
195                                 if (onair.data.track_title) {
196                                         $('<span> - </span>').appendTo(onairContainer);
197                                         $('<span class="nonstop-track-title">' + onair.data.track_title + '</span>').appendTo(onairContainer);
198                                         if (onair.data.track_artist) {
199                                                 $('<span> </span>').appendTo(onairContainer)
200                                                 $('<span class="nonstop-track-artist">(' + onair.data.track_artist + ')</span>').appendTo(onairContainer);
201                                         }
202                                 }
203                         }
204                         else {
205                                 $('body').addClass('nothing-playing');
206                                 onairContainer = $('<span>Toute la musique du festival</span>');
207                         }
208                         if (onair.data.emission && onair.data.emission.chat) {
209                                 $('#CurrentlyChatting a').attr('href', onair.data.emission.chat);
210                                 $('#CurrentlyChatting').show();
211                         } else {
212                                 $('#CurrentlyChatting').hide();
213                         }
214                         var current_html = WhatsOnAir.html();
215                         var new_html = '<span>' + onairContainer.html() + '</span>';
216                         if (new_html !== current_html) {
217                                 WhatsOnAir.fadeOut();
218                                 WhatsOnAir.empty().append(onairContainer);
219                                 WhatsOnAir.fadeIn();
220                         }
221                         // update grid
222                         var cell_slug = (onair.data.emission && onair.data.emission.slug) || (
223                                 onair.data.nonstop && onair.data.nonstop.slug);
224                         var $current_cell = $('.program li.current');
225                         if ($current_cell.data('program-slug') !== cell_slug &&
226                             $current_cell.next().data('program-slug') === cell_slug) {
227                                 $current_cell.removeClass('current').addClass('past');
228                                 $current_cell.next().removeClass('future').addClass('current');
229                         }
230                 });
231         });
232         $('#WhatsOnAir').trigger('load');
233         var refresh_onair_interval = 25000;
234         setInterval("$('#WhatsOnAir').trigger('load');", refresh_onair_interval);
235         $("#DirectStreamPanikControler").on('click',function(e) {
236                 e.preventDefault();
237                 var stream = $('#DirectStreamPanik').get(0);
238                 if (stream.paused == false){
239                         if ($(this).find('.player-stop')) {
240                                 $('#DirectStreamPanik').trigger('pause');  // icon change
241                                 stream.pause();
242                                 var par = $('#DirectStreamPanik').parent()
243                                 var dup = $('#DirectStreamPanik').clone();
244                                 $('#DirectStreamPanik').remove();
245                                 $(dup).appendTo($(par));
246                                 add_stream_handlers();
247                         } else {
248                                 stream.pause();
249                         }
250                 } else {
251                         if (typeof (_paq) == 'object') {
252                                 _paq.push(['trackEvent', 'Audio', 'Play Stream']);
253                         }
254                         stream.play();
255                 }
256                 return false;
257         });
258
259         function add_stream_handlers() {
260           $('#DirectStreamPanik').on('play',function(){
261                 $('audio:not(#DirectStreamPanik)').each(function(){this.pause();});
262                 $('#streamSymbol').removeClass('player-start').addClass('player-stop');
263           }).on('pause',function(){
264                 //$('audio:not(#DirectStreamPanik)').each(function(){this.pause();});
265                 $('#streamSymbol').addClass('player-start').removeClass('player-pause').removeClass('player-stop');
266           });
267         }
268         add_stream_handlers();
269
270         var $localList = $('#localList').playlist({
271                 controlContainer: $('<div>',{'class':"playListControls"}),
272                 playlistContainer: $('<ol>',{id:"myPlaylist",'class':"custom"}),
273                 onLoad:function(self){
274                         $('#toggleList').on('click',function(){ 
275                                 self.playlistContainer.toggleClass('deploy');
276                         });
277                         $('#emptyList').on('click',function(){ 
278                                 self._reset();
279                         });
280
281                         if(self.isActive){
282                                 self.isActive.find('audio').attr('preload',"preload")
283                         }
284                         self.controlButtons['playpause'].addClass('resymbol');
285                 },
286                 onPlay:function(self){
287                         $('#DirectStreamPanik')[0].pause();
288                 },
289                 onAdd:function(self){
290                         //self.isLastAdd[0].scrollIntoView();
291                         self.isLastAdd.find('a').ajaxifyClick();
292                         self.playlistContainer.clearQueue();
293
294                         if (typeof (_paq) == 'object') {
295                                 _paq.push(['trackEvent', 'Audio', 'Add to playlist']);
296                         }
297                 },
298                 onEnded: function(self) {
299                         self._reset();
300                 },
301                 onUpdate:function(self){
302                         //doLog(JSON.stringify(self.playlist, null, '\t'));     
303                         if(self.playlist.length >= 1){
304                                 $('#Player').addClass('withPlaylist').removeClass('withoutPlaylist');
305                                 self.element.show();
306                         }else{
307                                 $('#Player').removeClass('withPlaylist').addClass('withoutPlaylist');
308                                 self.element.hide();
309                         }
310                 }
311         });
312
313         init = function() {
314                 $("#All a, #All area").removeClass('loading');
315                 $("#All a, #All area").ajaxifyClick();
316                 $("#search-form").unbind('submit').on('submit', function(event) {
317                         event.preventDefault();
318                         $(this).addClass('loading');
319                         loadPage($(this).attr('action') + '?' + $(this).serialize());
320                 });
321                 // custom loading behaviour for week on homepage
322                 // (studioneau-only for now)
323                 $('#week .week-arrow a').unbind('click').on('click', function(event) {
324                         $.ajax({
325                                 url: $(this).attr('href'),
326                                 dataType: 'html',
327                                 success: function(html, textStatus, jqXhr) {
328                                         var $new_week = $(html);
329                                         var $new_program_tabs = $new_week.find('.program.tabs');
330                                         var $new_program_content = $new_week.find($new_program_tabs.attr('data-tab-about'));
331                                         var $old_program_content = $($('.program.tabs').attr('data-tab-about'));
332                                         $('.program.tabs').replaceWith($new_program_tabs);
333                                         $old_program_content.replaceWith($new_program_content);
334                                         init();
335                                         $(document).trigger('panikweb:week-change');
336                                 }
337                         });
338                         return false;
339                 });
340                 $(".tabs").each(function() {
341                         var self = $(this);
342                         var about = $($(this).attr("data-tab-about"));
343                         var current = $(this).find("[data-tab].active")[0];
344                         var dftShowSelector = current?".active":":first";
345                         var activeTab = $(this).find("[data-tab]"+dftShowSelector+"").addClass("active");
346                         $(this).find("[data-tab]").each(function() {
347                             $(this).on('click load',function (e) {
348                                 e.preventDefault();
349                                 self.find(".active").removeClass("active");
350                                 $(this).addClass("active");
351                                 var new_active = $($(this).attr("data-tab"));
352                                 if (! new_active.is(':visible')) {
353                                   about.find("[data-tabbed]").hide();
354                                   $($(this).attr("data-tab")).show();
355                                 }
356                             });
357                         });  
358                         activeTab.trigger('load');
359                 });
360                 // disable week tab buttons if there's nothing (but nonstop) on the day
361                 // (studioneau-only for now)
362                 $('.program div[data-tabbed]').each(function(idx, elem) {
363                         if ($(elem).find('a[href]').length == 0) {
364                                 // nothing this day
365                                 $('button[data-tab="#' + $(elem).attr('id') + '"]').attr('disabled', 'disabled');
366                         }
367                 });
368                 $('[data-player-action]').on('click',function(){
369                         var audio = $('#'+$(this).attr('data-player-audio'));
370                         var sound_id = audio.data('sound-id');
371                         if($(this).attr('data-player-action') == "registerAudio"){
372                                 $localList.playlist("registerAudio",audio);
373                         }else if($(this).attr('data-player-action') == "playAudio"){
374                                 if ($(this).hasClass('icon-play-sign') || $(this).hasClass('action-play')) {
375                                         $localList.playlist("registerAudio",audio);
376                                         $localList.playlist("playSoundId", sound_id);
377                                         if ($(this).parent().find('.icon-pause').length) {
378                                                 $(this).hide();
379                                                 $(this).parent().find('.icon-pause').show();
380                                         }
381                                 } else {
382                                         $localList.playlist('pauseSounds');
383                                 }
384                         }else if ($(this).attr('data-player-action') == "pauseSounds") {
385                                 if ($(this).parent().find('.icon-play-sign').length) {
386                                         $(this).hide();
387                                         $(this).parent().find('.icon-play-sign').show();
388                                 }
389                                 $localList.playlist($(this).attr('data-player-action'));
390                         }else{
391                                 $localList.playlist($(this).attr('data-player-action'));
392                         }
393                 });
394                 $('[data-player-control]').each(function(){
395                         var audio = $('#'+$(this).attr('data-player-audio'));
396                         $localList.playlist("bindControl",$(this).attr('data-player-control'),audio,$(this));
397                 });
398
399                 $('[data-highlight]').on('check',function(){
400                         $($(this).attr('data-about')).find($(this).attr('data-highlight')).addClass('highlighted').removeClass('normal');
401                 }).on('uncheck',function(){
402                         $($(this).attr('data-about')).find($(this).attr('data-highlight')).removeClass('highlighted').addClass('normal');
403                 }).on('click',function(){
404                         $(this).toggleClass('icon-check icon-check-empty');
405                         if($(this).hasClass('icon-check')){$(this).trigger('check');
406                         }else{  $(this).trigger('uncheck');}
407                 });
408                 $('[data-highlight].icon-check-empty').each(function(){
409                         $(this).trigger('uncheck');
410                 });
411                 $('[data-toggle]').on('check',function(){
412                         /* make sure all other unchecked items are hidden */
413                         $('[data-toggle].icon-check-empty').each(function() {
414                                 $($(this).attr('data-about')).find($(this).attr('data-toggle')).hide();
415                         });
416                         $($(this).attr('data-about')).find($(this).attr('data-toggle')).show();
417                 }).on('uncheck',function(){
418                         $($(this).attr('data-about')).find($(this).attr('data-toggle')).hide();
419                         if ($('[data-toggle].icon-check').length == 0) {
420                                 /* special case the situation where all toggles
421                                  * are unchecked, as we want that to mean
422                                  * "everything", not "nothing".
423                                  */
424                                 $('[data-toggle].icon-check-empty').each(function() {
425                                         $($(this).attr('data-about')).find($(this).attr('data-toggle')).show();
426                                 });
427                         }
428                 }).on('click',function(){
429                         $(this).toggleClass('icon-check icon-check-empty');
430                         if($(this).hasClass('icon-check')){$(this).trigger('check');
431                         }else{  $(this).trigger('uncheck');}
432                 });
433                 $('[data-toggle].icon-check-empty').each(function(){
434                         $(this).trigger('uncheck');
435                 });
436
437                 initial_enabled_toggles = {};
438                 if (typeof(urlParams.q) == 'string') {
439                         urlParams.q.split('|').forEach(function(a) { initial_enabled_toggles[a] = 1; })
440                 }
441                 $('[data-toggle]').each(function() {
442                         if ($(this).data('toggle').substring(1) in initial_enabled_toggles) {
443                                 $(this).trigger('click');
444                         }
445                 });
446
447                 $('[data-popup-href]').on('click', function() {
448                         $.ajax({
449                                 url: $(this).data('popup-href'),
450                                 success: function (html, textStatus, jqXhr) {
451                                         $(html).appendTo($('body'));
452                                 }
453                         });
454                         return false;
455                 });
456
457                 if ($('#search-form.big input#id_q').val() == '') {
458                         $('#search-form.big input#id_q').focus();
459                 }
460
461                 $('#ticker li:not(:first)');
462                 if (ticker_interval) clearInterval(ticker_interval);
463                 function tick(){
464                     $('#ticker li:first').animate({'opacity':0}, 200, function () {
465                         $(this).appendTo($('#ticker')).css('opacity', 1);
466                     });
467                 }
468                 $("#roller button").on('click',function(e){
469                     clearInterval(ticker_interval);
470                     e.preventDefault();
471                     $($(this).attr('data-about')).prependTo('#ticker');
472                     return false;
473                 });
474                 ticker_interval = setInterval(function(){tick();  }, 20000);/**/
475
476                 function navsearch_click(event) {
477                         event.preventDefault();
478                         var query = $('#nav-search input').val();
479                         var form = $('#nav-search form');
480                         var href = '';
481                         if (query == '') {
482                                 href = $(form).attr('action');
483                         } else {
484                                 href = $(form).attr('action') + '?' + $(form).serialize();
485                         }
486                         if (event.which == 2) {
487                                 window.open(href, '_blank');
488                         } else {
489                                 $(this).addClass('loading');
490                                 loadPage(href);
491                         }
492                         return false;
493                 }
494                 $('#nav-search a').unbind('click').on('click', navsearch_click);
495                 $('#nav-search form').unbind('submit').on('submit', navsearch_click);
496
497                 if ($('.bg-title').length) {
498                         var bg_title = $('<span id="bg-title" aria-hidden="true"></span>');
499                         bg_title.text($('.bg-title').text());
500                         $('#Changing').append(bg_title);
501                 }
502                 $('[data-toggle-img]').bind('click', function() {
503                         var src = $(this).data('toggle-img');
504                         $(this).data('toggle-img', $(this).attr('src'));
505                         $(this).attr('src', src);
506                         $(this).toggleClass('right marged');
507                 });
508
509                 $('#Main audio').each(function(index, audio) {
510                         var audio_src = $(audio).find('source')[0];
511                         var sound_id = $(audio).data('sound-id');
512                         var $waveform = $(audio).next();
513                         var waveform_url = audio_src.src.replace('.ogg', '.waveform.json').replace('.mp3', '.waveform.json');
514                         $.getJSON(waveform_url, function(data) {
515                                 $waveform.empty();
516                                 $waveform.append('<i class="duration">' + $waveform.data('duration-string') + '</i>');
517                                 $.each(data, function(k, val) {
518                                         var val = val * 0.5;
519                                         $waveform.append('<span data-tick-index="' + k + '" style="height: ' + val + 'px;"></span>');
520                                 });
521                                 $waveform.show();
522                                 $waveform.find('span').on('click', function() {
523                                         /* if there's been something loaded */
524                                         var matching_audio = $('audio[data-sound-id=' + sound_id + ']');
525                                         if (matching_audio.length == 0) return;
526                                         matching_audio = matching_audio[0];
527                                         if (matching_audio.paused || matching_audio.ended) {
528                                                 $(this).parents('.sound').find('.action-play').click();
529                                                 return;
530                                         }
531                                         /* try to set time */
532                                         var total_duration = parseFloat($waveform.data('duration'));
533                                         var nb_ticks = $(this).parent().find('span').length;
534                                         var tick_index = $(this).data('tick-index');
535                                         matching_audio.currentTime = total_duration * tick_index / nb_ticks;
536                                 });
537                         });
538                 });
539
540                 $('#nav-language span').click(function() {
541                         document.cookie = 'panikweb_language=' + $(this).data('lang') + '; path=/';
542                         window.location = window.location;
543                         return false;
544                 });
545
546                 if ($('.sound + .content .text  ').length) {
547                         var text_content = $('.sound + .content .text')[0];
548                         text_content.innerHTML = text_content.innerHTML.replace(
549                                 /[0-9][0-9]+:[0-9][0-9]/g,
550                                 function(x) { return '<span class="timestamp">' + x + "</span>"; });
551                         $(text_content).find('span.timestamp').on('click', function() {
552                                 var $waveform = $('div.waveform').first();
553                                 var sound_id = $waveform.prev().data('sound-id');
554                                 var total_duration = parseFloat($waveform.data('duration'));
555                                 var nb_ticks = $waveform.find('span').length;
556                                 var timestamp = $(this).text().split(':');
557                                 var timestamp_position = timestamp[0] * 60 + timestamp[1] * 1;
558                                 var tick_idx = parseInt(nb_ticks * timestamp_position / total_duration);
559                                 // play, then set rough position
560                                 $('.episode.detail .icon-play-sign').first().trigger('click');
561                                 var matching_audio = $('audio[data-sound-id=' + sound_id + ']');
562                                 matching_audio[0].currentTime = timestamp_position;
563                         });
564                 }
565
566                 if (document.cookie.indexOf('panikdb=on') != -1) {
567                         panikdb_path = null;
568                         if (window.location.pathname.indexOf('/emissions/') == 0) {
569                                 panikdb_path = window.location.pathname;
570                         } else if (window.location.pathname.indexOf('/news/') == 0) {
571                                 panikdb_path = '/emissions' + window.location.pathname;
572                         }
573                         if (panikdb_path) {
574                                 $('<a id="panikdb" href="http://panikdb.radiopanik.org' + panikdb_path + '">Voir dans PanikDB</a>').appendTo($main);
575                         }
576                 }
577
578                 $('.gallery').each(function() {
579                   var $gallery = $(this);
580                   $gallery.find('span.image').on('click', function() {
581                     if ($(this).find('img').hasClass('portrait')) {
582                         $(this).parents('.gallerycell').addClass('portrait');
583                     } else {
584                         $(this).parents('.gallerycell').removeClass('portrait');
585                     }
586                     $gallery.find('div.first img').attr('src', $(this).data('image-large'));
587                     $gallery.find('div.first span.gallery-legend').text($(this).find('img').attr('title') || '');
588                     $gallery.find('div.first').show('fade');
589                     return false;
590                   });
591                   $gallery.find('div.first').on('click', function() {
592                           window.getSelection().removeAllRanges();
593                           $(this).toggle('fade');
594                           return false;
595                   });
596                   $gallery.find('div.first').delegate('img', 'click', function(ev) {
597                           var e = $.Event('keydown');
598                           e.which = 39;
599                           $('body').trigger(e);
600                           return false;
601                   });
602                 });
603
604                 /* CHAT */
605                 if ($('#chat').length && ! $('#player.on-chat-page').length) {
606                     $('#player').addClass('on-chat-page');
607                     var $msg = $('input#msg');
608                     var $send = $('button#send');
609                     var chat_roster = Object();
610
611                     function enable_moderation() {
612                       $('#chat').addClass('moderation');
613                       $('#chat').on('click', 'span.from', function() {
614                         var name = $(this).text();
615                         if (confirm('Kick ' + name + ' ?')) {
616                           var muc = $('div#chat').data('chatroom');
617                           connection.muc.kick(muc + '@conf.panik', name,
618                                           'no reason',
619                                           function(iq) {
620                                           },
621                                           function(iq) {
622                                             doLog('error kicking', 'error');
623                                           }
624                           );
625                         }
626                       });
627                     }
628
629                     $('.nick input').on('keydown', function(ev) {
630                         if (ev.keyCode == 13) {
631                             $('.nick button').trigger('click');
632                             return false;
633                         }
634                         return true;
635                     });
636
637                     $('.nick button').on('click', function() {
638                       window.localStorage['pa-nick'] = $('.nick input').val();
639                       var nick = window.localStorage['pa-nick'];
640                       $('.commands .prompt').text(nick);
641
642                       connection = new Strophe.Connection("/http-bind");
643                       connection.connect('im.panik', null, function(status, error) {
644                         if (status == Strophe.Status.CONNECTING) {
645                             $('.nick').show();
646                             $('.commands').hide();
647                             //console.log('Strophe is connecting.');
648                         } else if (status == Strophe.Status.CONNFAIL) {
649                             $('.nick').show();
650                             $('.commands').hide();
651                             //console.log('Strophe failed to connect.');
652                         } else if (status == Strophe.Status.DISCONNECTING) {
653                             $('.nick').show();
654                             $('.commands').hide();
655                             //console.log('Strophe is disconnecting.');
656                         } else if (status == Strophe.Status.DISCONNECTED) {
657                             $('.nick').show();
658                             $('.commands').hide();
659                             //console.log('Strophe is disconnected.');
660                         } else if (status == Strophe.Status.CONNECTED) {
661                             //console.log('Strophe is connected');
662                             $('.nick').hide();
663                             $('.commands').show();
664                             var jid = nick;
665                             var muc = $('div#chat').data('chatroom');
666                             connection.muc.join(muc + '@conf.panik', jid,
667                                     function(msg) {
668                                         if (! msg.textContent) return true;
669                                         var from = msg.attributes.from.value.replace(/.*\//, '');
670                                         var klass = '';
671                                         if (from == jid) {
672                                             klass = 'msg-out';
673                                         } else {
674                                             klass = 'msg-in';
675                                         }
676                                         var new_msg = $('<div class="msg new ' + klass + '"><span class="from">' + from + '</span> <span class="content">' + msg.textContent + '</span></div>').prependTo($('#chat'));
677                                         new_msg[0].offsetHeight; /* trigger reflow */
678                                         new_msg.removeClass('new');
679                                         $('div#chat div:nth-child(20)').remove()
680                                         return true;
681                                     },
682                                     function(pres) {
683                                             var nick = $('.nick input').val()
684                                             var muc = $('div#chat').data('chatroom');
685                                             if (pres.getElementsByTagName('status').length &&
686                                                 pres.getElementsByTagName('status')[0].attributes &&
687                                                 pres.getElementsByTagName('status')[0].attributes.code &&
688                                                 pres.getElementsByTagName('status')[0].attributes.code.value == '307') {
689                                               /* kicked */
690                                               try {
691                                                 var kicked = pres.getElementsByTagName('item')[0].attributes.nick.value;
692                                               } catch (error) {
693                                                 var kicked = pres.attributes.from.value.split('/')[1];
694                                               }
695                                               if (kicked == nick) {
696                                                 connection.disconnect();
697                                                 $('div.nick').css('visibility', 'hidden');
698                                                 var new_msg = $('<div class="msg info new"><span class="content">You have been kicked out.</span></div>').prependTo($('#chat'));
699                                               } else {
700                                                 var new_msg = $('<div class="msg info new"><span class="content">' + kicked + ' a Ã©té mis dehors.</span></div>').prependTo($('#chat'));
701                                               }
702                                               new_msg[0].offsetHeight; /* trigger reflow */
703                                               new_msg.removeClass('new');
704                                             }
705                                             if (pres.getElementsByTagName('conflict').length == 1) {
706                                               $('.nick input').val(nick + '_');
707                                               connection.disconnect();
708                                               if (nic.indexOf('__') == -1) {
709                                                 // auto reconnect unless nick
710                                                 // has already been altered
711                                                 // after conflicts.
712                                                 $('.nick button').trigger('click');
713                                               }
714                                             }
715                                             return true;
716                                     },
717                                     function(roster) {
718                                             if (chat_roster[nick] == true) {
719                                                 for (contact in roster) {
720                                                         if (chat_roster[contact] !== true) {
721                                                                 var new_msg = $('<div class="msg info new joined"><span class="content">' + contact + ' est dans la place.</span></div>').prependTo($('#chat'));
722                                                                 new_msg[0].offsetHeight; /* trigger reflow */
723                                                                 new_msg.removeClass('new');
724                                                         }
725                                                 }
726                                             }
727                                             chat_roster = Object();
728                                             for (contact in roster) {
729                                                 chat_roster[contact] = true;
730                                             }
731                                             return true;
732                                     }
733                                     );
734                             }
735                          });
736
737                     });
738
739                     function send() {
740                         var text = $msg.val();
741                         if (! text) {
742                             $msg.focus();
743                             return true;
744                         }
745                         var muc = $('div#chat').data('chatroom');
746                         if (text.startsWith('/auth')) {
747                             $msg.val('');
748                             /* ideally it would trigger some code on the server
749                              * to check the password and elevate priviledges in
750                              * prosody. It doesn't, this is security theater.
751                              */
752                             $.getJSON('/media/chat.json', function(chat_info) {
753                               if (text.split(' ')[1] == chat_info.secret) {
754                                 enable_moderation();
755                               }
756                             });
757                             return true;
758                         }
759                         connection.muc.message(muc + '@conf.panik', null, text);
760                         $msg.val('');
761                         return true;
762                     }
763                     $send.click(send);
764                     $msg.keydown(function(ev) {
765                         if (ev.keyCode == 13) {
766                             send();
767                             return false;
768                         }
769                         return true;
770                     });
771
772                     if (window.localStorage['pa-nick'] !== undefined) {
773                       $('.nick input').val(window.localStorage['pa-nick']);
774                       if ($('#chat[data-global]').length == 0) {
775                         $('.nick button').click();
776                       }
777                     }
778
779                     $(window).on('beforeunload', function() {
780                         if (connection && $('#chat[data-global]').length == 0) { connection.disconnect(); }
781                     });
782
783                 } else if ($('#chat').length == 0) {
784                     $('#player').removeClass('on-chat-page');
785                 }
786         }
787         init();
788
789         if (! document.createElement('audio').canPlayType('audio/ogg') &&
790                 document.createElement('audio').canPlayType('audio/aac') ) {
791                 $('#ogg-m3u').hide().removeClass('resymbol');
792                 $('#aac-m3u').addClass('resymbol').show();
793         }
794
795         $(document).on('panik:play', function(ev, data) {
796                 var $page_audio_controls = $('#Main').find('div.audio[data-sound-id="' + data.sound_id + '"]');
797                 $page_audio_controls.find('.icon-play-sign').removeClass('icon-play-sign').addClass('icon-pause');
798                 $('.sound').addClass('playing');
799         });
800
801         $(document).on('panik:pause', function(ev, data) {
802                 var $page_audio_controls = $('#Main').find('div.audio[data-sound-id="' + data.sound_id + '"]');
803                 $page_audio_controls.find('.icon-pause').removeClass('icon-pause').addClass('icon-play-sign');
804                 $('.sound').removeClass('playing');
805         });
806
807         $(document).on('panik:timeupdate', function(ev, data) {
808                 var $page_audio_controls = $('#Main').find('div.audio[data-sound-id="' + data.sound_id + '"]');
809                 $page_audio_controls.find('.icon-play-sign').removeClass('icon-play-sign').addClass('icon-pause');
810                 $waveform = $('#Main div.waveform[data-sound-id="' + data.sound_id + '"]');
811                 $waveform.parents('.sound').addClass('playing');
812                 var elems = $waveform.find('span');
813                 var total_elems = elems.length;
814                 var done = total_elems * data.position;
815                 $waveform.find('span').each(function(k, elem) {
816                   if (k < done) {
817                         $(elem).addClass('done').removeClass('current');
818                   } else {
819                         $(elem).removeClass('done');
820                   }
821                 });
822                 $waveform.find('span.done:last').addClass('current');
823         });
824
825         $("body").keydown(function(e) {
826           var $visible_element = $('div.first:visible img');
827           if ($visible_element.length == 0) {
828             return true;
829           }
830           if ($visible_element.length > 1) {
831             /* remove all but last */
832             $visible_element.parent().find('img:not(:last)').remove();
833           }
834           var $visible_element = $('div.first:visible img');
835           var img_url = $visible_element.attr('src');
836           var all_img = $('div.gallery span[data-image-large] img');
837           var active_img = $('div.gallery span[data-image-large="' + img_url + '"] img');
838           var idx = all_img.index(active_img);
839           if (e.which == 37) { // left
840             idx--;
841             if (idx == -1) {
842               idx = all_img.length-1;
843             }
844           } else if (e.which == 39) { // right
845             idx++;
846             if (idx == all_img.length) {
847               idx = 0;
848             }
849           } else if (e.which == 27) { // escape
850             $visible_element.parent().toggle('fade');
851             return true;
852           } else {
853             return true;
854           }
855           /* create a new <img> with the new image but opacity 0, then display
856            * it using a css transition */
857           if (e.which == 37) { $visible_element.css('transform-origin', 'bottom right'); }
858           if (e.which == 39) { $visible_element.css('transform-origin', 'bottom left'); }
859           var new_img = $visible_element.clone().appendTo($visible_element.parent());
860           $(new_img).css('opacity', 0).attr('src', $(all_img[idx]).parent().data('image-large'));
861           $(new_img).css('transform', 'scale(0, 1)');
862           $(new_img)[0].offsetHeight; /* trigger reflow */
863           $(new_img).css('opacity', 1).css('transform', 'scale(1)');
864           $(new_img).parents('.gallery').find('span.gallery-legend').text($(all_img[idx]).attr('title') || '');
865           if ($(all_img[idx]).hasClass('portrait')) {
866             if (! $(new_img).parents('.gallerycell').hasClass('portrait')) {
867               $visible_element.parent().find('img:not(:last)').remove();
868               $(new_img).parents('.gallerycell').addClass('portrait');
869             }
870           } else {
871             if ($(new_img).parents('.gallerycell').hasClass('portrait')) {
872               $visible_element.parent().find('img:not(:last)').remove();
873               $(new_img).parents('.gallerycell').removeClass('portrait');
874             }
875           }
876           return false;
877         });
878 });