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