]> git.0d.be Git - panikweb-esperanzah.git/blob - panikweb_esperanzah/static/js/specifics.js
sync a bit of player with panik
[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         $('#streamSymbol').on('click keypress',function(e) {
236                 if (e.type === 'keypress' && !(e.key === ' ' || e.key === 'Enter'))
237                         return;
238                 e.preventDefault();
239                 var stream = $('#LiveStream').get(0);
240                 if (stream.paused == false){
241                         if ($(this).find('.player-stop')) {
242                                 $('#LiveStream').trigger('pause');  // icon change
243                                 stream.pause();
244                                 var par = $('#LiveStream').parent()
245                                 var dup = $('#LiveStream').clone();
246                                 $('#LiveStream').remove();
247                                 $(dup).appendTo($(par));
248                                 add_stream_handlers();
249                         } else {
250                                 stream.pause();
251                         }
252                 } else {
253                         if (typeof (_paq) == 'object') {
254                                 _paq.push(['trackEvent', 'Audio', 'Play Stream']);
255                         }
256                         stream.play();
257                 }
258                 return false;
259         });
260
261         function add_stream_handlers() {
262           $('#LiveStream').on('play',function(){
263                 $('audio:not(#LiveStream)').each(function(){this.pause();});
264                 $('#streamSymbol').removeClass('player-start').addClass('player-stop');
265           }).on('pause',function(){
266                 //$('audio:not(#LiveStream)').each(function(){this.pause();});
267                 $('#streamSymbol').addClass('player-start').removeClass('player-pause').removeClass('player-stop');
268           });
269         }
270         add_stream_handlers();
271
272         var $localList = $('#localList').playlist({
273                 controlContainer: $('<div>',{'class':"playListControls"}),
274                 playlistContainer: $('<ol>',{id:"myPlaylist",'class':"custom"}),
275                 onLoad:function(self){
276                         $('#toggleList').on('click',function(){ 
277                                 self.playlistContainer.toggleClass('deploy');
278                         });
279                         $('#emptyList').on('click',function(){ 
280                                 self._reset();
281                         });
282
283                         if(self.isActive){
284                                 self.isActive.find('audio').attr('preload',"preload")
285                         }
286                         self.controlButtons['playpause'].addClass('resymbol');
287                 },
288                 onPlay:function(self){
289                         $('#LiveStream')[0].pause();
290                 },
291                 onAdd:function(self){
292                         //self.isLastAdd[0].scrollIntoView();
293                         self.isLastAdd.find('a').ajaxifyClick();
294                         self.playlistContainer.clearQueue();
295
296                         if (typeof (_paq) == 'object') {
297                                 _paq.push(['trackEvent', 'Audio', 'Add to playlist']);
298                         }
299                 },
300                 onEnded: function(self) {
301                         self._reset();
302                 },
303                 onUpdate:function(self){
304                         //doLog(JSON.stringify(self.playlist, null, '\t'));     
305                         if(self.playlist.length >= 1){
306                                 $('#Player').addClass('withPlaylist').removeClass('withoutPlaylist');
307                                 self.element.show();
308                         }else{
309                                 $('#Player').removeClass('withPlaylist').addClass('withoutPlaylist');
310                                 self.element.hide();
311                         }
312                 }
313         });
314
315         init = function() {
316                 $("#All a, #All area").removeClass('loading');
317                 $("#All a, #All area").ajaxifyClick();
318                 $("#search-form").unbind('submit').on('submit', function(event) {
319                         event.preventDefault();
320                         $(this).addClass('loading');
321                         loadPage($(this).attr('action') + '?' + $(this).serialize());
322                 });
323                 // custom loading behaviour for week on homepage
324                 // (studioneau-only for now)
325                 $('#week .week-arrow a').unbind('click').on('click', function(event) {
326                         $.ajax({
327                                 url: $(this).attr('href'),
328                                 dataType: 'html',
329                                 success: function(html, textStatus, jqXhr) {
330                                         var $new_week = $(html);
331                                         var $new_program_tabs = $new_week.find('.program.tabs');
332                                         var $new_program_content = $new_week.find($new_program_tabs.attr('data-tab-about'));
333                                         var $old_program_content = $($('.program.tabs').attr('data-tab-about'));
334                                         $('.program.tabs').replaceWith($new_program_tabs);
335                                         $old_program_content.replaceWith($new_program_content);
336                                         init();
337                                         $(document).trigger('panikweb:week-change');
338                                 }
339                         });
340                         return false;
341                 });
342                 $(".tabs").each(function() {
343                         var self = $(this);
344                         var about = $($(this).attr("data-tab-about"));
345                         var current = $(this).find("[data-tab].active")[0];
346                         var dftShowSelector = current?".active":":first";
347                         var activeTab = $(this).find("[data-tab]"+dftShowSelector+"").addClass("active");
348                         $(this).find("[data-tab]").each(function() {
349                             $(this).on('click load',function (e) {
350                                 e.preventDefault();
351                                 self.find(".active").removeClass("active");
352                                 $(this).addClass("active");
353                                 var new_active = $($(this).attr("data-tab"));
354                                 if (! new_active.is(':visible')) {
355                                   about.find("[data-tabbed]").hide();
356                                   $($(this).attr("data-tab")).show();
357                                 }
358                             });
359                         });  
360                         activeTab.trigger('load');
361                 });
362                 // disable week tab buttons if there's nothing (but nonstop) on the day
363                 // (studioneau-only for now)
364                 $('.program div[data-tabbed]').each(function(idx, elem) {
365                         if ($(elem).find('a[href]').length == 0) {
366                                 // nothing this day
367                                 $('button[data-tab="#' + $(elem).attr('id') + '"]').attr('disabled', 'disabled');
368                         }
369                 });
370                 $('[data-player-action]').on('click',function(){
371                         var audio = $('#'+$(this).attr('data-player-audio'));
372                         var sound_id = audio.data('sound-id');
373                         if($(this).attr('data-player-action') == "registerAudio"){
374                                 $localList.playlist("registerAudio",audio);
375                         }else if($(this).attr('data-player-action') == "playAudio"){
376                                 if ($(this).hasClass('icon-play-sign') || $(this).hasClass('action-play')) {
377                                         $localList.playlist("registerAudio",audio);
378                                         $localList.playlist("playSoundId", sound_id);
379                                         if ($(this).parent().find('.icon-pause').length) {
380                                                 $(this).hide();
381                                                 $(this).parent().find('.icon-pause').show();
382                                         }
383                                 } else {
384                                         $localList.playlist('pauseSounds');
385                                 }
386                         }else if ($(this).attr('data-player-action') == "pauseSounds") {
387                                 if ($(this).parent().find('.icon-play-sign').length) {
388                                         $(this).hide();
389                                         $(this).parent().find('.icon-play-sign').show();
390                                 }
391                                 $localList.playlist($(this).attr('data-player-action'));
392                         }else{
393                                 $localList.playlist($(this).attr('data-player-action'));
394                         }
395                 });
396                 $('[data-player-control]').each(function(){
397                         var audio = $('#'+$(this).attr('data-player-audio'));
398                         $localList.playlist("bindControl",$(this).attr('data-player-control'),audio,$(this));
399                 });
400
401                 $('[data-highlight]').on('check',function(){
402                         $($(this).attr('data-about')).find($(this).attr('data-highlight')).addClass('highlighted').removeClass('normal');
403                 }).on('uncheck',function(){
404                         $($(this).attr('data-about')).find($(this).attr('data-highlight')).removeClass('highlighted').addClass('normal');
405                 }).on('click',function(){
406                         $(this).toggleClass('icon-check icon-check-empty');
407                         if($(this).hasClass('icon-check')){$(this).trigger('check');
408                         }else{  $(this).trigger('uncheck');}
409                 });
410                 $('[data-highlight].icon-check-empty').each(function(){
411                         $(this).trigger('uncheck');
412                 });
413                 $('[data-toggle]').on('check',function(){
414                         /* make sure all other unchecked items are hidden */
415                         $('[data-toggle].icon-check-empty').each(function() {
416                                 $($(this).attr('data-about')).find($(this).attr('data-toggle')).hide();
417                         });
418                         $($(this).attr('data-about')).find($(this).attr('data-toggle')).show();
419                 }).on('uncheck',function(){
420                         $($(this).attr('data-about')).find($(this).attr('data-toggle')).hide();
421                         if ($('[data-toggle].icon-check').length == 0) {
422                                 /* special case the situation where all toggles
423                                  * are unchecked, as we want that to mean
424                                  * "everything", not "nothing".
425                                  */
426                                 $('[data-toggle].icon-check-empty').each(function() {
427                                         $($(this).attr('data-about')).find($(this).attr('data-toggle')).show();
428                                 });
429                         }
430                 }).on('click',function(){
431                         $(this).toggleClass('icon-check icon-check-empty');
432                         if($(this).hasClass('icon-check')){$(this).trigger('check');
433                         }else{  $(this).trigger('uncheck');}
434                 });
435                 $('[data-toggle].icon-check-empty').each(function(){
436                         $(this).trigger('uncheck');
437                 });
438
439                 initial_enabled_toggles = {};
440                 if (typeof(urlParams.q) == 'string') {
441                         urlParams.q.split('|').forEach(function(a) { initial_enabled_toggles[a] = 1; })
442                 }
443                 $('[data-toggle]').each(function() {
444                         if ($(this).data('toggle').substring(1) in initial_enabled_toggles) {
445                                 $(this).trigger('click');
446                         }
447                 });
448
449                 $('[data-popup-href]').on('click', function() {
450                         $.ajax({
451                                 url: $(this).data('popup-href'),
452                                 success: function (html, textStatus, jqXhr) {
453                                         $(html).appendTo($('body'));
454                                 }
455                         });
456                         return false;
457                 });
458
459                 if ($('#search-form.big input#id_q').val() == '') {
460                         $('#search-form.big input#id_q').focus();
461                 }
462
463                 $('#ticker li:not(:first)');
464                 if (ticker_interval) clearInterval(ticker_interval);
465                 function tick(){
466                     $('#ticker li:first').animate({'opacity':0}, 200, function () {
467                         $(this).appendTo($('#ticker')).css('opacity', 1);
468                     });
469                 }
470                 $("#roller button").on('click',function(e){
471                     clearInterval(ticker_interval);
472                     e.preventDefault();
473                     $($(this).attr('data-about')).prependTo('#ticker');
474                     return false;
475                 });
476                 ticker_interval = setInterval(function(){tick();  }, 20000);/**/
477
478                 function navsearch_click(event) {
479                         event.preventDefault();
480                         var query = $('#nav-search input').val();
481                         var form = $('#nav-search form');
482                         var href = '';
483                         if (query == '') {
484                                 href = $(form).attr('action');
485                         } else {
486                                 href = $(form).attr('action') + '?' + $(form).serialize();
487                         }
488                         if (event.which == 2) {
489                                 window.open(href, '_blank');
490                         } else {
491                                 $(this).addClass('loading');
492                                 loadPage(href);
493                         }
494                         return false;
495                 }
496                 $('#nav-search a').unbind('click').on('click', navsearch_click);
497                 $('#nav-search form').unbind('submit').on('submit', navsearch_click);
498
499                 if ($('.bg-title').length) {
500                         var bg_title = $('<span id="bg-title" aria-hidden="true"></span>');
501                         bg_title.text($('.bg-title').text());
502                         $('#Changing').append(bg_title);
503                 }
504                 $('[data-toggle-img]').bind('click', function() {
505                         var src = $(this).data('toggle-img');
506                         $(this).data('toggle-img', $(this).attr('src'));
507                         $(this).attr('src', src);
508                         $(this).toggleClass('right marged');
509                 });
510
511                 $('#Main audio').each(function(index, audio) {
512                         var audio_src = $(audio).find('source')[0];
513                         var sound_id = $(audio).data('sound-id');
514                         var $waveform = $(audio).next();
515                         var waveform_url = audio_src.src.replace('.ogg', '.waveform.json').replace('.mp3', '.waveform.json');
516                         $.getJSON(waveform_url, function(data) {
517                                 $waveform.empty();
518                                 $waveform.append('<i class="duration">' + $waveform.data('duration-string') + '</i>');
519                                 $.each(data, function(k, val) {
520                                         var val = val * 0.5;
521                                         $waveform.append('<span data-tick-index="' + k + '" style="height: ' + val + 'px;"></span>');
522                                 });
523                                 $waveform.show();
524                                 $waveform.find('span').on('click', function() {
525                                         /* if there's been something loaded */
526                                         var matching_audio = $('audio[data-sound-id=' + sound_id + ']');
527                                         if (matching_audio.length == 0) return;
528                                         matching_audio = matching_audio[0];
529                                         if (matching_audio.paused || matching_audio.ended) {
530                                                 $(this).parents('.sound').find('.action-play').click();
531                                                 return;
532                                         }
533                                         /* try to set time */
534                                         var total_duration = parseFloat($waveform.data('duration'));
535                                         var nb_ticks = $(this).parent().find('span').length;
536                                         var tick_index = $(this).data('tick-index');
537                                         matching_audio.currentTime = total_duration * tick_index / nb_ticks;
538                                 });
539                         });
540                 });
541
542                 $('#nav-language span').click(function() {
543                         document.cookie = 'panikweb_language=' + $(this).data('lang') + '; path=/';
544                         window.location = window.location;
545                         return false;
546                 });
547
548                 if ($('.sound + .content .text  ').length) {
549                         var text_content = $('.sound + .content .text')[0];
550                         text_content.innerHTML = text_content.innerHTML.replace(
551                                 /[0-9][0-9]+:[0-9][0-9]/g,
552                                 function(x) { return '<span class="timestamp">' + x + "</span>"; });
553                         $(text_content).find('span.timestamp').on('click', function() {
554                                 var $waveform = $('div.waveform').first();
555                                 var sound_id = $waveform.prev().data('sound-id');
556                                 var total_duration = parseFloat($waveform.data('duration'));
557                                 var nb_ticks = $waveform.find('span').length;
558                                 var timestamp = $(this).text().split(':');
559                                 var timestamp_position = timestamp[0] * 60 + timestamp[1] * 1;
560                                 var tick_idx = parseInt(nb_ticks * timestamp_position / total_duration);
561                                 // play, then set rough position
562                                 $('.episode.detail .icon-play-sign').first().trigger('click');
563                                 var matching_audio = $('audio[data-sound-id=' + sound_id + ']');
564                                 matching_audio[0].currentTime = timestamp_position;
565                         });
566                 }
567
568                 if (document.cookie.indexOf('panikdb=on') != -1) {
569                         panikdb_path = null;
570                         if (window.location.pathname.indexOf('/emissions/') == 0) {
571                                 panikdb_path = window.location.pathname;
572                         } else if (window.location.pathname.indexOf('/news/') == 0) {
573                                 panikdb_path = '/emissions' + window.location.pathname;
574                         }
575                         if (panikdb_path) {
576                                 $('<a id="panikdb" href="http://panikdb.radiopanik.org' + panikdb_path + '">Voir dans PanikDB</a>').appendTo($main);
577                         }
578                 }
579
580                 $('.gallery').each(function() {
581                   var $gallery = $(this);
582                   $gallery.find('span.image').on('click', function() {
583                     if ($(this).find('img').hasClass('portrait')) {
584                         $(this).parents('.gallerycell').addClass('portrait');
585                     } else {
586                         $(this).parents('.gallerycell').removeClass('portrait');
587                     }
588                     $gallery.find('div.first img').attr('src', $(this).data('image-large'));
589                     $gallery.find('div.first span.gallery-legend').text($(this).find('img').attr('title') || '');
590                     $gallery.find('div.first').show('fade');
591                     return false;
592                   });
593                   $gallery.find('div.first').on('click', function() {
594                           window.getSelection().removeAllRanges();
595                           $(this).toggle('fade');
596                           return false;
597                   });
598                   $gallery.find('div.first').delegate('img', 'click', function(ev) {
599                           var e = $.Event('keydown');
600                           e.which = 39;
601                           $('body').trigger(e);
602                           return false;
603                   });
604                 });
605
606                 /* CHAT */
607                 if ($('#chat').length && ! $('#player.on-chat-page').length) {
608                     $('#player').addClass('on-chat-page');
609                     var $msg = $('input#msg');
610                     var $send = $('button#send');
611                     var chat_roster = Object();
612
613                     function enable_moderation() {
614                       $('#chat').addClass('moderation');
615                       $('#chat').on('click', 'span.from', function() {
616                         var name = $(this).text();
617                         if (confirm('Kick ' + name + ' ?')) {
618                           var muc = $('div#chat').data('chatroom');
619                           connection.muc.kick(muc + '@conf.panik', name,
620                                           'no reason',
621                                           function(iq) {
622                                           },
623                                           function(iq) {
624                                             doLog('error kicking', 'error');
625                                           }
626                           );
627                         }
628                       });
629                     }
630
631                     $('.nick input').on('keydown', function(ev) {
632                         if (ev.keyCode == 13) {
633                             $('.nick button').trigger('click');
634                             return false;
635                         }
636                         return true;
637                     });
638
639                     $('.nick button').on('click', function() {
640                       window.localStorage['pa-nick'] = $('.nick input').val();
641                       var nick = window.localStorage['pa-nick'];
642                       $('.commands .prompt').text(nick);
643
644                       connection = new Strophe.Connection("/http-bind");
645                       connection.connect('im.panik', null, function(status, error) {
646                         if (status == Strophe.Status.CONNECTING) {
647                             $('.nick').show();
648                             $('.commands').hide();
649                             //console.log('Strophe is connecting.');
650                         } else if (status == Strophe.Status.CONNFAIL) {
651                             $('.nick').show();
652                             $('.commands').hide();
653                             //console.log('Strophe failed to connect.');
654                         } else if (status == Strophe.Status.DISCONNECTING) {
655                             $('.nick').show();
656                             $('.commands').hide();
657                             //console.log('Strophe is disconnecting.');
658                         } else if (status == Strophe.Status.DISCONNECTED) {
659                             $('.nick').show();
660                             $('.commands').hide();
661                             //console.log('Strophe is disconnected.');
662                         } else if (status == Strophe.Status.CONNECTED) {
663                             //console.log('Strophe is connected');
664                             $('.nick').hide();
665                             $('.commands').show();
666                             var jid = nick;
667                             var muc = $('div#chat').data('chatroom');
668                             connection.muc.join(muc + '@conf.panik', jid,
669                                     function(msg) {
670                                         if (! msg.textContent) return true;
671                                         var from = msg.attributes.from.value.replace(/.*\//, '');
672                                         var klass = '';
673                                         if (from == jid) {
674                                             klass = 'msg-out';
675                                         } else {
676                                             klass = 'msg-in';
677                                         }
678                                         var new_msg = $('<div class="msg new ' + klass + '"><span class="from">' + from + '</span> <span class="content">' + msg.textContent + '</span></div>').prependTo($('#chat'));
679                                         new_msg[0].offsetHeight; /* trigger reflow */
680                                         new_msg.removeClass('new');
681                                         $('div#chat div:nth-child(20)').remove()
682                                         return true;
683                                     },
684                                     function(pres) {
685                                             var nick = $('.nick input').val()
686                                             var muc = $('div#chat').data('chatroom');
687                                             if (pres.getElementsByTagName('status').length &&
688                                                 pres.getElementsByTagName('status')[0].attributes &&
689                                                 pres.getElementsByTagName('status')[0].attributes.code &&
690                                                 pres.getElementsByTagName('status')[0].attributes.code.value == '307') {
691                                               /* kicked */
692                                               try {
693                                                 var kicked = pres.getElementsByTagName('item')[0].attributes.nick.value;
694                                               } catch (error) {
695                                                 var kicked = pres.attributes.from.value.split('/')[1];
696                                               }
697                                               if (kicked == nick) {
698                                                 connection.disconnect();
699                                                 $('div.nick').css('visibility', 'hidden');
700                                                 var new_msg = $('<div class="msg info new"><span class="content">You have been kicked out.</span></div>').prependTo($('#chat'));
701                                               } else {
702                                                 var new_msg = $('<div class="msg info new"><span class="content">' + kicked + ' a Ã©té mis dehors.</span></div>').prependTo($('#chat'));
703                                               }
704                                               new_msg[0].offsetHeight; /* trigger reflow */
705                                               new_msg.removeClass('new');
706                                             }
707                                             if (pres.getElementsByTagName('conflict').length == 1) {
708                                               $('.nick input').val(nick + '_');
709                                               connection.disconnect();
710                                               if (nic.indexOf('__') == -1) {
711                                                 // auto reconnect unless nick
712                                                 // has already been altered
713                                                 // after conflicts.
714                                                 $('.nick button').trigger('click');
715                                               }
716                                             }
717                                             return true;
718                                     },
719                                     function(roster) {
720                                             if (chat_roster[nick] == true) {
721                                                 for (contact in roster) {
722                                                         if (chat_roster[contact] !== true) {
723                                                                 var new_msg = $('<div class="msg info new joined"><span class="content">' + contact + ' est dans la place.</span></div>').prependTo($('#chat'));
724                                                                 new_msg[0].offsetHeight; /* trigger reflow */
725                                                                 new_msg.removeClass('new');
726                                                         }
727                                                 }
728                                             }
729                                             chat_roster = Object();
730                                             for (contact in roster) {
731                                                 chat_roster[contact] = true;
732                                             }
733                                             return true;
734                                     }
735                                     );
736                             }
737                          });
738
739                     });
740
741                     function send() {
742                         var text = $msg.val();
743                         if (! text) {
744                             $msg.focus();
745                             return true;
746                         }
747                         var muc = $('div#chat').data('chatroom');
748                         if (text.startsWith('/auth')) {
749                             $msg.val('');
750                             /* ideally it would trigger some code on the server
751                              * to check the password and elevate priviledges in
752                              * prosody. It doesn't, this is security theater.
753                              */
754                             $.getJSON('/media/chat.json', function(chat_info) {
755                               if (text.split(' ')[1] == chat_info.secret) {
756                                 enable_moderation();
757                               }
758                             });
759                             return true;
760                         }
761                         connection.muc.message(muc + '@conf.panik', null, text);
762                         $msg.val('');
763                         return true;
764                     }
765                     $send.click(send);
766                     $msg.keydown(function(ev) {
767                         if (ev.keyCode == 13) {
768                             send();
769                             return false;
770                         }
771                         return true;
772                     });
773
774                     if (window.localStorage['pa-nick'] !== undefined) {
775                       $('.nick input').val(window.localStorage['pa-nick']);
776                       if ($('#chat[data-global]').length == 0) {
777                         $('.nick button').click();
778                       }
779                     }
780
781                     $(window).on('beforeunload', function() {
782                         if (connection && $('#chat[data-global]').length == 0) { connection.disconnect(); }
783                     });
784
785                 } else if ($('#chat').length == 0) {
786                     $('#player').removeClass('on-chat-page');
787                 }
788         }
789         init();
790
791         if (! document.createElement('audio').canPlayType('audio/ogg') &&
792                 document.createElement('audio').canPlayType('audio/aac') ) {
793                 $('#ogg-m3u').hide().removeClass('resymbol');
794                 $('#aac-m3u').addClass('resymbol').show();
795         }
796
797         $(document).on('panik:play', function(ev, data) {
798                 var $page_audio_controls = $('#Main').find('div.audio[data-sound-id="' + data.sound_id + '"]');
799                 $page_audio_controls.find('.icon-play-sign').removeClass('icon-play-sign').addClass('icon-pause');
800                 $('.sound').addClass('playing');
801         });
802
803         $(document).on('panik:pause', function(ev, data) {
804                 var $page_audio_controls = $('#Main').find('div.audio[data-sound-id="' + data.sound_id + '"]');
805                 $page_audio_controls.find('.icon-pause').removeClass('icon-pause').addClass('icon-play-sign');
806                 $('.sound').removeClass('playing');
807         });
808
809         $(document).on('panik:timeupdate', function(ev, data) {
810                 var $page_audio_controls = $('#Main').find('div.audio[data-sound-id="' + data.sound_id + '"]');
811                 $page_audio_controls.find('.icon-play-sign').removeClass('icon-play-sign').addClass('icon-pause');
812                 $waveform = $('#Main div.waveform[data-sound-id="' + data.sound_id + '"]');
813                 $waveform.parents('.sound').addClass('playing');
814                 var elems = $waveform.find('span');
815                 var total_elems = elems.length;
816                 var done = total_elems * data.position;
817                 $waveform.find('span').each(function(k, elem) {
818                   if (k < done) {
819                         $(elem).addClass('done').removeClass('current');
820                   } else {
821                         $(elem).removeClass('done');
822                   }
823                 });
824                 $waveform.find('span.done:last').addClass('current');
825         });
826
827         $("body").keydown(function(e) {
828           var $visible_element = $('div.first:visible img');
829           if ($visible_element.length == 0) {
830             return true;
831           }
832           if ($visible_element.length > 1) {
833             /* remove all but last */
834             $visible_element.parent().find('img:not(:last)').remove();
835           }
836           var $visible_element = $('div.first:visible img');
837           var img_url = $visible_element.attr('src');
838           var all_img = $('div.gallery span[data-image-large] img');
839           var active_img = $('div.gallery span[data-image-large="' + img_url + '"] img');
840           var idx = all_img.index(active_img);
841           if (e.which == 37) { // left
842             idx--;
843             if (idx == -1) {
844               idx = all_img.length-1;
845             }
846           } else if (e.which == 39) { // right
847             idx++;
848             if (idx == all_img.length) {
849               idx = 0;
850             }
851           } else if (e.which == 27) { // escape
852             $visible_element.parent().toggle('fade');
853             return true;
854           } else {
855             return true;
856           }
857           /* create a new <img> with the new image but opacity 0, then display
858            * it using a css transition */
859           if (e.which == 37) { $visible_element.css('transform-origin', 'bottom right'); }
860           if (e.which == 39) { $visible_element.css('transform-origin', 'bottom left'); }
861           var new_img = $visible_element.clone().appendTo($visible_element.parent());
862           $(new_img).css('opacity', 0).attr('src', $(all_img[idx]).parent().data('image-large'));
863           $(new_img).css('transform', 'scale(0, 1)');
864           $(new_img)[0].offsetHeight; /* trigger reflow */
865           $(new_img).css('opacity', 1).css('transform', 'scale(1)');
866           $(new_img).parents('.gallery').find('span.gallery-legend').text($(all_img[idx]).attr('title') || '');
867           if ($(all_img[idx]).hasClass('portrait')) {
868             if (! $(new_img).parents('.gallerycell').hasClass('portrait')) {
869               $visible_element.parent().find('img:not(:last)').remove();
870               $(new_img).parents('.gallerycell').addClass('portrait');
871             }
872           } else {
873             if ($(new_img).parents('.gallerycell').hasClass('portrait')) {
874               $visible_element.parent().find('img:not(:last)').remove();
875               $(new_img).parents('.gallerycell').removeClass('portrait');
876             }
877           }
878           return false;
879         });
880 });