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