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