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