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