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