]> git.0d.be Git - panikweb.git/blob - panikweb_templates/static/js/specifics.js
8768ea905302556d2da88a4e8cc67bd7cba04995
[panikweb.git] / panikweb_templates / 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                         $(this).unbind('click');
124                         $(this).bind('click',function(e){
125                                 var href = $(this).attr("href");
126                                 if (e.which == 2) {
127                                         window.open(href, '_blank');
128                                         return false;
129                                 }
130                                 if (href.match('\.(ogg|mp3|pdf|odt|ods|doc|xls|docx|xlsx|rtf|zip|rss|atom)$')) {
131                                         /* open files */
132                                         window.location = href;
133                                         return false;
134                                 }
135                                 $(this).addClass('loading');
136                                 /* this checks the link points to a local document, be
137                                  * it because it's just a path, or because the server
138                                  * part points to the same domain */
139                                 if (!href) {
140                                         doLog('No href attributes, unable to load content','error');
141                                         $("#All a, #All area").removeClass('loading');
142                                         return false;
143                                 }else if (!$(this).attr('target') && (
144                                                 href.indexOf(document.domain) > -1 ||href.indexOf(':') === -1 || href.indexOf(':') > 5
145                                         )) {
146                                         loadPage(href);
147                                         return false;
148                                 }else{
149                                         $(this).attr('target','_blank');
150                                         $("#All a, #All area").removeClass('loading');
151                                         return true;
152                                 }
153                         });
154                 });
155         };
156         /****************************************************/
157         /**** AUDIOPLAYER ****/
158         /****************************************************/
159
160         var timer = null;
161         var refresh_onair_interval = 25000;
162         var ticker_interval = null;
163         /*
164         //TODO: mini icon version for player, (playpause only)
165         $('#togglePlayer').on('click',function(e) {
166                 e.preventDefault();
167                 if($(this).is('.icon-double-angle-left')){
168                         $("#player").fadeOut('fast',function(){
169                                 $("#player-container").toggleClass('minimized');                        
170                                 $('#togglePlayer').toggleClass('icon-double-angle-left icon-double-angle-right');
171                         });                     
172                 }else{
173                         $("#player").fadeIn('fast',function(){
174                                 $("#player-container").toggleClass('minimized');                        
175                                 $('#togglePlayer').toggleClass('icon-double-angle-left icon-double-angle-right');
176                         });     
177                 }
178                 return false;
179         });
180         */
181         $('#WhatsOnAir').on('load',function(){
182                 var WhatsOnAir = $(this);
183                 $('#RefreshWhatsOnAir').addClass('spinning');
184                 $.getJSON('/onair.json', function(onair) {
185                         setTimeout(function() { $('#RefreshWhatsOnAir').removeClass('spinning'); }, 5000);
186                         var onairContainer = $('<span>');
187                         if(onair.data.episode || onair.data.emission) {
188                                 if(onair.data.emission){
189                                         $('<a>',{href:onair.data.emission.url,html:onair.data.emission.title}).appendTo(onairContainer).ajaxifyClick();
190                                 }
191                                 if(onair.data.episode){
192                                         $('<span> - </span>').appendTo(onairContainer);
193                                         $('<a>',{href:onair.data.episode.url,html:onair.data.episode.title}).appendTo(onairContainer).ajaxifyClick();
194                                 }
195                         } else if (onair.data.nonstop) {
196                                 onairContainer = $('<span>' + onair.data.nonstop.title + '</span>');
197                                 if (onair.data.track_title) {
198                                         $('<span> - </span>').appendTo(onairContainer);
199                                         $('<span class="nonstop-track-title">' + onair.data.track_title + '</span>').appendTo(onairContainer);
200                                         if (onair.data.track_artist) {
201                                                 $('<span> </span>').appendTo(onairContainer)
202                                                 $('<span class="nonstop-track-artist">(' + onair.data.track_artist + ')</span>').appendTo(onairContainer);
203                                         }
204                                 }
205                         }
206                         else {
207                                 onairContainer = $('<span>Toute la musique du festival</span>');
208                         }
209                         if (onair.data.emission && onair.data.emission.chat) {
210                                 $('#CurrentlyChatting a').attr('href', onair.data.emission.chat);
211                                 $('#CurrentlyChatting').show();
212                         } else {
213                                 $('#CurrentlyChatting').hide();
214                         }
215                         var current_html = WhatsOnAir.html();
216                         var new_html = '<span>' + onairContainer.html() + '</span>';
217                         if (new_html !== current_html) {
218                                 WhatsOnAir.fadeOut();
219                                 WhatsOnAir.empty().append(onairContainer);
220                                 WhatsOnAir.fadeIn();
221                         }
222                 });
223         });
224         $('#RefreshWhatsOnAir').on('activate',function(e){
225                 $('#WhatsOnAir').trigger('load');
226                 timer = setInterval( "$('#WhatsOnAir').trigger('load');", refresh_onair_interval);
227         }).on('deactivate',function(e){
228                 $(this).removeClass('spinning');
229                 $('#WhatsOnAir').removeClass('active');
230                 clearInterval(timer);
231         }).on('click',function(e){
232                 $(this).toggleClass('active');
233                 if($(this).is('.active')){
234                         $(this).trigger('deactivate');
235                 }else{
236                         $(this).trigger('activate');
237                 }
238                 return false;
239         }).trigger('activate');
240         $("#DirectStreamPanikControler").on('click',function(e) {
241                 e.preventDefault();
242                 var stream = $('#DirectStreamPanik').get(0);
243                 if (stream.paused == false){
244                         stream.pause();
245                 }else{
246                         if (typeof (_paq) == 'object') {
247                                 _paq.push(['trackEvent', 'Audio', 'Play Stream']);
248                         }
249                         stream.play();
250                 }
251                 return false;
252         });
253         $('#DirectStreamPanik').on('play',function(){
254                 $('audio:not(#DirectStreamPanik)').each(function(){this.pause();});
255                 $('#streamSymbol').removeClass('player-start').addClass('player-pause');
256                 $('#RefreshWhatsOnAir').trigger('activate');
257         }).on('pause',function(){
258                 //$('audio:not(#DirectStreamPanik)').each(function(){this.pause();});
259                 $('#streamSymbol').addClass('player-start').removeClass('player-pause');
260         });
261
262         var $localList = $('#localList').playlist({
263                 controlContainer: $('<div>',{'class':"playListControls"}),
264                 playlistContainer: $('<ol>',{id:"myPlaylist",'class':"custom"}),
265                 onLoad:function(self){
266                         $('#toggleList').on('click',function(){ 
267                                 self.playlistContainer.toggleClass('deploy');
268                         });
269                         $('#emptyList').on('click',function(){ 
270                                 self._reset();
271                         });
272
273                         if(self.isActive){
274                                 self.isActive.find('audio').attr('preload',"preload")
275                         }
276                         self.controlButtons['playpause'].addClass('resymbol');
277                 },
278                 onPlay:function(self){
279                         $('#DirectStreamPanik')[0].pause();
280                 },
281                 onAdd:function(self){
282                         //self.isLastAdd[0].scrollIntoView();
283                         self.isLastAdd.find('a').ajaxifyClick();
284                         self.playlistContainer.clearQueue();
285
286                         if (typeof (_paq) == 'object') {
287                                 _paq.push(['trackEvent', 'Audio', 'Add to playlist']);
288                         }
289                 },
290                 onEnded: function(self) {
291                         self._reset();
292                 },
293                 onUpdate:function(self){
294                         //doLog(JSON.stringify(self.playlist, null, '\t'));     
295                         if(self.playlist.length >= 1){
296                                 $('#Player').addClass('withPlaylist').removeClass('withoutPlaylist');
297                                 self.element.show();
298                         }else{
299                                 $('#Player').removeClass('withPlaylist').addClass('withoutPlaylist');
300                                 self.element.hide();
301                         }
302                 }
303         });
304
305         init = function() {
306                 $("#All a, #All area").removeClass('loading');
307                 $("#All a, #All area").ajaxifyClick();
308                 $("#search-form").unbind('submit').on('submit', function(event) {
309                         event.preventDefault();
310                         $(this).addClass('loading');
311                         loadPage($(this).attr('action') + '?' + $(this).serialize());
312                 });
313                 $(".tabs").each(function() {
314                         var self = $(this);
315                         var about= $($(this).attr("data-tab-about"));
316                         var current = $(this).find("[data-tab].active")[0];
317                         var dftShowSelector = current?".active":":first";
318                         var activeTab = $(this).find("[data-tab]"+dftShowSelector+"").addClass("active");
319                         $(this).find("[data-tab]").each(function() {
320                             $(this).on('click load',function (e) {  
321                                 e.preventDefault();
322                                 self.find(".active").removeClass("active");  
323                                 $(this).addClass("active");  
324                                 about.find("[data-tabbed]").hide();  
325                                 $($(this).attr("data-tab")).fadeIn();  
326                 
327                             });  
328                         });  
329                         activeTab.trigger('load');
330                 });
331                 $('[data-player-action]').on('click',function(){
332                         var audio = $('#'+$(this).attr('data-player-audio'));
333                         var sound_id = audio.data('sound-id');
334                         if($(this).attr('data-player-action') == "registerAudio"){
335                                 $localList.playlist("registerAudio",audio);
336                         }else if($(this).attr('data-player-action') == "playAudio"){
337                                 $localList.playlist("reset");
338                                 $localList.playlist("registerAudio",audio);
339                                 $localList.playlist("playSoundId", sound_id);
340                                 if ($(this).parent().find('.icon-pause').length) {
341                                         $(this).hide();
342                                         $(this).parent().find('.icon-pause').show();
343                                 }
344                         }else if ($(this).attr('data-player-action') == "pauseSounds") {
345                                 if ($(this).parent().find('.icon-play-sign').length) {
346                                         $(this).hide();
347                                         $(this).parent().find('.icon-play-sign').show();
348                                 }
349                                 $localList.playlist($(this).attr('data-player-action'));
350                         }else{
351                                 $localList.playlist($(this).attr('data-player-action'));
352                         }
353                 });
354                 $('[data-player-control]').each(function(){
355                         var audio = $('#'+$(this).attr('data-player-audio'));
356                         $localList.playlist("bindControl",$(this).attr('data-player-control'),audio,$(this));
357                 });
358
359                 $('[data-highlight]').on('check',function(){
360                         $($(this).attr('data-about')).find($(this).attr('data-highlight')).addClass('highlighted').removeClass('normal');
361                 }).on('uncheck',function(){
362                         $($(this).attr('data-about')).find($(this).attr('data-highlight')).removeClass('highlighted').addClass('normal');
363                 }).on('click',function(){
364                         $(this).toggleClass('icon-check icon-check-empty');
365                         if($(this).hasClass('icon-check')){$(this).trigger('check');
366                         }else{  $(this).trigger('uncheck');}
367                 });
368                 $('[data-highlight].icon-check-empty').each(function(){
369                         $(this).trigger('uncheck');
370                 });
371                 $('[data-toggle]').on('check',function(){
372                         /* make sure all other unchecked items are hidden */
373                         $('[data-toggle].icon-check-empty').each(function() {
374                                 $($(this).attr('data-about')).find($(this).attr('data-toggle')).hide();
375                         });
376                         $($(this).attr('data-about')).find($(this).attr('data-toggle')).show();
377                 }).on('uncheck',function(){
378                         $($(this).attr('data-about')).find($(this).attr('data-toggle')).hide();
379                         if ($('[data-toggle].icon-check').length == 0) {
380                                 /* special case the situation where all toggles
381                                  * are unchecked, as we want that to mean
382                                  * "everything", not "nothing".
383                                  */
384                                 $('[data-toggle].icon-check-empty').each(function() {
385                                         $($(this).attr('data-about')).find($(this).attr('data-toggle')).show();
386                                 });
387                         }
388                 }).on('click',function(){
389                         $(this).toggleClass('icon-check icon-check-empty');
390                         if($(this).hasClass('icon-check')){$(this).trigger('check');
391                         }else{  $(this).trigger('uncheck');}
392                 });
393                 $('[data-toggle].icon-check-empty').each(function(){
394                         $(this).trigger('uncheck');
395                 });
396
397                 initial_enabled_toggles = {};
398                 if (typeof(urlParams.q) == 'string') {
399                         urlParams.q.split('|').forEach(function(a) { initial_enabled_toggles[a] = 1; })
400                 }
401                 $('[data-toggle]').each(function() {
402                         if ($(this).data('toggle').substring(1) in initial_enabled_toggles) {
403                                 $(this).trigger('click');
404                         }
405                 });
406
407                 $('[data-popup-href]').on('click', function() {
408                         $.ajax({
409                                 url: $(this).data('popup-href'),
410                                 success: function (html, textStatus, jqXhr) {
411                                         $(html).appendTo($('body'));
412                                 }
413                         });
414                         return false;
415                 });
416
417                 if ($('input#id_q').val() == '') {
418                         $('input#id_q').focus();
419                 }
420
421                 $('#ticker li:not(:first)');
422                 if (ticker_interval) clearInterval(ticker_interval);
423                 function tick(){
424                     $('#ticker li:first').animate({'opacity':0}, 200, function () {
425                         $(this).appendTo($('#ticker')).css('opacity', 1);
426                     });
427                 }
428                 $("#roller button").on('click',function(e){
429                     clearInterval(ticker_interval);
430                     e.preventDefault();
431                     $($(this).attr('data-about')).prependTo('#ticker');
432                     return false;
433                 });
434                 ticker_interval = setInterval(function(){tick();  }, 20000);/**/
435
436                 function navsearch_click(event) {
437                         event.preventDefault();
438                         var query = $('#nav-search input').val();
439                         var form = $('#nav-search form');
440                         var href = '';
441                         if (query == '') {
442                                 href = $(form).attr('action');
443                         } else {
444                                 href = $(form).attr('action') + '?' + $(form).serialize();
445                         }
446                         if (event.which == 2) {
447                                 window.open(href, '_blank');
448                         } else {
449                                 $(this).addClass('loading');
450                                 loadPage(href);
451                         }
452                         return false;
453                 }
454                 $('#nav-search a').unbind('click').on('click', navsearch_click);
455                 $('#nav-search form').unbind('submit').on('submit', navsearch_click);
456
457                 if ($('.bg-title').length) {
458                         var bg_title = $('<span id="bg-title" aria-hidden="true"></span>');
459                         bg_title.text($('.bg-title').text());
460                         $('#Changing').append(bg_title);
461                 }
462                 $('[data-toggle-img]').bind('click', function() {
463                         var src = $(this).data('toggle-img');
464                         $(this).data('toggle-img', $(this).attr('src'));
465                         $(this).attr('src', src);
466                         $(this).toggleClass('right marged');
467                 });
468
469                 $('#Main audio').each(function(index, audio) {
470                         var audio_src = $(audio).find('source')[0];
471                         var sound_id = $(audio).data('sound-id');
472                         var $waveform = $(audio).next();
473                         $.getJSON(audio_src.src.replace('.ogg', '.waveform.json'), function(data) {
474                                 $waveform.empty();
475                                 $waveform.append('<i class="duration">' + $waveform.data('duration-string') + '</i>');
476                                 $.each(data, function(k, val) {
477                                         var val = val * 0.5;
478                                         $waveform.append('<span data-tick-index="' + k + '" style="height: ' + val + 'px;"></span>');
479                                 });
480                                 $waveform.show();
481                                 $waveform.find('span').on('click', function() {
482                                         /* if there's been something loaded */
483                                         var matching_audio = $('audio[data-sound-id=' + sound_id + ']');
484                                         if (matching_audio.length == 0) return;
485                                         matching_audio = matching_audio[0];
486                                         if (matching_audio.paused || matching_audio.ended) {
487                                                 $(this).parents('.sound').find('.action-play').click();
488                                                 return;
489                                         }
490                                         /* try to set time */
491                                         var total_duration = parseFloat($waveform.data('duration'));
492                                         var nb_ticks = $(this).parent().find('span').length;
493                                         var tick_index = $(this).data('tick-index');
494                                         matching_audio.currentTime = total_duration * tick_index / nb_ticks;
495                                 });
496                         });
497                 });
498
499                 $('#nav-language span').click(function() {
500                         document.cookie = 'panikweb_language=' + $(this).data('lang') + '; path=/';
501                         window.location = window.location;
502                         return false;
503                 });
504
505                 if ($('.sound + .content .text  ').length) {
506                         var text_content = $('.sound + .content .text')[0];
507                         text_content.innerHTML = text_content.innerHTML.replace(
508                                 /[0-9][0-9]+:[0-9][0-9]/g,
509                                 function(x) { return '<span class="timestamp">' + x + "</span>"; });
510                         $(text_content).find('span.timestamp').on('click', function() {
511                                 var $waveform = $('div.waveform');
512                                 var total_duration = parseFloat($waveform.data('duration'));
513                                 var nb_ticks = $waveform.find('span').length;
514                                 var timestamp = $(this).text().split(':');
515                                 var timestamp_position = timestamp[0] * 60 + timestamp[1] * 1;
516                                 var tick_idx = parseInt(nb_ticks * timestamp_position / total_duration);
517                                 // twice to get play then set position
518                                 $('span[data-tick-index=' + tick_idx + ']').trigger('click');
519                                 $('span[data-tick-index=' + tick_idx + ']').trigger('click');
520                         });
521                 }
522
523                 if (document.cookie.indexOf('panikdb=on') != -1) {
524                         panikdb_path = null;
525                         if (window.location.pathname.indexOf('/emissions/') == 0) {
526                                 panikdb_path = window.location.pathname;
527                         } else if (window.location.pathname.indexOf('/news/') == 0) {
528                                 panikdb_path = '/emissions' + window.location.pathname;
529                         }
530                         if (panikdb_path) {
531                                 $('<a id="panikdb" href="http://panikdb.radiopanik.org' + panikdb_path + '">Voir dans PanikDB</a>').appendTo($main);
532                         }
533                 }
534
535                 $('.gallery').each(function() {
536                   var $gallery = $(this);
537                   $gallery.find('span.image').on('click', function() {
538                     if ($(this).find('img').hasClass('portrait')) {
539                         $(this).parents('.gallerycell').addClass('portrait');
540                     } else {
541                         $(this).parents('.gallerycell').removeClass('portrait');
542                     }
543                     $gallery.find('div.first img').attr('src', $(this).data('image-large'));
544                     $gallery.find('div.first span.gallery-legend').text($(this).find('img').attr('title') || '');
545                     $gallery.find('div.first').show('fade');
546                     return false;
547                   });
548                   $gallery.find('div.first').on('click', function() {
549                           window.getSelection().removeAllRanges();
550                           $(this).toggle('fade');
551                           return false;
552                   });
553                   $gallery.find('div.first').delegate('img', 'click', function(ev) {
554                           var e = $.Event('keydown');
555                           e.which = 39;
556                           $('body').trigger(e);
557                           return false;
558                   });
559                 });
560
561                 /* CHAT */
562                 if ($('#chat').length) {
563                     $('#player').addClass('on-chat-page');
564                     var moderator = ($('#panikdb').length > 0);
565                     var $msg = $('input#msg');
566                     var $send = $('button#send');
567                     var chat_roster = Object();
568
569                     if (moderator) {
570                       $('#chat').addClass('moderation');
571                       $('#chat').on('click', 'span.from', function() {
572                         var name = $(this).text();
573                         if (confirm('Kick ' + name + ' ?')) {
574                           var muc = $('div#chat').data('chatroom');
575                           connection.muc.kick(muc + '@conf.panik', name,
576                                           'no reason',
577                                           function(iq) {
578                                           },
579                                           function(iq) {
580                                             doLog('error kicking', 'error');
581                                           }
582                           );
583                         }
584                       });
585                     }
586
587                     $('.nick input').on('keydown', function(ev) {
588                         if (ev.keyCode == 13) {
589                             $('.nick button').trigger('click');
590                             return false;
591                         }
592                         return true;
593                     });
594
595                     $('.nick button').on('click', function() {
596                       window.localStorage['pa-nick'] = $('.nick input').val();
597                       var nick = window.localStorage['pa-nick'];
598                       $('.commands .prompt').text(nick + '>');
599
600                       connection = new Strophe.Connection("/http-bind");
601                       connection.connect('im.panik', null, function(status, error) {
602                         if (status == Strophe.Status.CONNECTING) {
603                             $('.nick').show();
604                             $('.commands').hide();
605                             //console.log('Strophe is connecting.');
606                         } else if (status == Strophe.Status.CONNFAIL) {
607                             $('.nick').show();
608                             $('.commands').hide();
609                             //console.log('Strophe failed to connect.');
610                         } else if (status == Strophe.Status.DISCONNECTING) {
611                             $('.nick').show();
612                             $('.commands').hide();
613                             //console.log('Strophe is disconnecting.');
614                         } else if (status == Strophe.Status.DISCONNECTED) {
615                             $('.nick').show();
616                             $('.commands').hide();
617                             //console.log('Strophe is disconnected.');
618                         } else if (status == Strophe.Status.CONNECTED) {
619                             //console.log('Strophe is connected');
620                             $('.nick').hide();
621                             $('.commands').show();
622                             var jid = nick;
623                             var muc = $('div#chat').data('chatroom');
624                             connection.muc.join(muc + '@conf.panik', jid,
625                                     function(msg) {
626                                         var from = msg.attributes.from.value.replace(/.*\//, '');
627                                         var klass = '';
628                                         if (from == jid) {
629                                             klass = 'msg-out';
630                                         } else {
631                                             klass = 'msg-in';
632                                         }
633                                         var new_msg = $('<div class="msg new ' + klass + '"><span class="from">' + from + '</span> <span class="content">' + msg.textContent + '</span></div>').prependTo($('#chat'));
634                                         new_msg[0].offsetHeight; /* trigger reflow */
635                                         new_msg.removeClass('new');
636                                         $('div#chat div:nth-child(20)').remove()
637                                         return true;
638                                     },
639                                     function(pres) {
640                                             var nick = $('.nick input').val()
641                                             var muc = $('div#chat').data('chatroom');
642                                             if (pres.getElementsByTagName('status').length == 1 &&
643                                                 pres.getElementsByTagName('status')[0].attributes &&
644                                                 pres.getElementsByTagName('status')[0].attributes.code &&
645                                                 pres.getElementsByTagName('status')[0].attributes.code.value == '307') {
646                                               /* kicked */
647                                               var kicked = pres.getElementsByTagName('item')[0].attributes.nick.value;
648                                               var new_msg = $('<div class="msg info new"><span class="content">' + kicked + ' a été mis dehors.</span></div>').prependTo($('#chat'));
649                                               new_msg[0].offsetHeight; /* trigger reflow */
650                                               new_msg.removeClass('new');
651                                               if (kicked == nick) {
652                                                 connection.disconnect();
653                                                 $('div.nick').css('visibility', 'hidden');
654                                               }
655                                             }
656                                             if (pres.getElementsByTagName('conflict').length == 1) {
657                                               $('.nick input').val(nick + '_');
658                                               connection.disconnect();
659                                               $('.nick button').trigger('click');
660                                             }
661                                             return true;
662                                     },
663                                     function(roster) {
664                                             if (chat_roster[nick] == true) {
665                                                 for (contact in roster) {
666                                                         if (chat_roster[contact] !== true) {
667                                                                 var new_msg = $('<div class="msg info new"><span class="content">' + contact + ' est dans la place.</span></div>').prependTo($('#chat'));
668                                                                 new_msg[0].offsetHeight; /* trigger reflow */
669                                                                 new_msg.removeClass('new');
670                                                         }
671                                                 }
672                                             }
673                                             chat_roster = Object();
674                                             for (contact in roster) {
675                                                 chat_roster[contact] = true;
676                                             }
677                                             return true;
678                                     }
679                                     );
680                             }
681                          });
682
683                     });
684
685                     function send() {
686                         var text = $msg.val();
687                         var muc = $('div#chat').data('chatroom');
688                         connection.muc.message(muc + '@conf.panik', null, text);
689                         $msg.val('');
690                         return true;
691                     }
692                     $send.click(send);
693                     $msg.keydown(function(ev) {
694                         if (ev.keyCode == 13) {
695                             send();
696                             return false;
697                         }
698                         return true;
699                     });
700
701                     if (window.localStorage['pa-nick'] !== undefined) {
702                       $('.nick input').val(window.localStorage['pa-nick']);
703                       $('.nick button').click();
704                     }
705
706                     $(window).on('beforeunload', function() {
707                         if (connection) { connection.disconnect(); }
708                     });
709
710                 } else {
711                     $('#player').removeClass('on-chat-page');
712                 }
713         }
714         init();
715
716         if (! document.createElement('audio').canPlayType('audio/ogg') &&
717                 document.createElement('audio').canPlayType('audio/aac') ) {
718                 $('#ogg-m3u').hide().removeClass('resymbol');
719                 $('#aac-m3u').addClass('resymbol').show();
720         }
721
722         $(document).on('panik:timeupdate', function(ev, data) {
723                 $waveform = $('#Main div.waveform[data-sound-id="' + data.sound_id + '"]');
724                 var elems = $waveform.find('span');
725                 var total_elems = elems.length;
726                 var done = total_elems * data.position;
727                 $waveform.find('span').each(function(k, elem) {
728                   if (k < done) {
729                         $(elem).addClass('done').removeClass('current');
730                   } else {
731                         $(elem).removeClass('done');
732                   }
733                 });
734                 $waveform.find('span.done:last').addClass('current');
735         });
736
737         $("body").keydown(function(e) {
738           var $visible_element = $('div.first:visible img');
739           if ($visible_element.length == 0) {
740             return true;
741           }
742           if ($visible_element.length > 1) {
743             /* remove all but last */
744             $visible_element.parent().find('img:not(:last)').remove();
745           }
746           var $visible_element = $('div.first:visible img');
747           var img_url = $visible_element.attr('src');
748           var all_img = $('div.gallery span[data-image-large] img');
749           var active_img = $('div.gallery span[data-image-large="' + img_url + '"] img');
750           var idx = all_img.index(active_img);
751           if (e.which == 37) { // left
752             idx--;
753             if (idx == -1) {
754               idx = all_img.length-1;
755             }
756           } else if (e.which == 39) { // right
757             idx++;
758             if (idx == all_img.length) {
759               idx = 0;
760             }
761           } else if (e.which == 27) { // escape
762             $visible_element.parent().toggle('fade');
763             return true;
764           } else {
765             return true;
766           }
767           /* create a new <img> with the new image but opacity 0, then display
768            * it using a css transition */
769           if (e.which == 37) { $visible_element.css('transform-origin', 'bottom right'); }
770           if (e.which == 39) { $visible_element.css('transform-origin', 'bottom left'); }
771           var new_img = $visible_element.clone().appendTo($visible_element.parent());
772           $(new_img).css('opacity', 0).attr('src', $(all_img[idx]).parent().data('image-large'));
773           $(new_img).css('transform', 'scale(0, 1)');
774           $(new_img)[0].offsetHeight; /* trigger reflow */
775           $(new_img).css('opacity', 1).css('transform', 'scale(1)');
776           $(new_img).parents('.gallery').find('span.gallery-legend').text($(all_img[idx]).attr('title') || '');
777           if ($(all_img[idx]).hasClass('portrait')) {
778             if (! $(new_img).parents('.gallerycell').hasClass('portrait')) {
779               $visible_element.parent().find('img:not(:last)').remove();
780               $(new_img).parents('.gallerycell').addClass('portrait');
781             }
782           } else {
783             if ($(new_img).parents('.gallerycell').hasClass('portrait')) {
784               $visible_element.parent().find('img:not(:last)').remove();
785               $(new_img).parents('.gallerycell').removeClass('portrait');
786             }
787           }
788           return false;
789         });
790 });