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