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