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