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