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