]> git.0d.be Git - panikweb.git/blob - panikweb_templates/static/js/specifics.js
construct on air string so that it can be checked against old value
[panikweb.git] / panikweb_templates / static / js / specifics.js
1 var urlParams;
2 (window.onpopstate = function () {
3     var match,
4         pl     = /\+/g,  // Regex for replacing addition symbol with a space
5         search = /([^&=]+)=?([^&]*)/g,
6         decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
7         query  = window.location.search.substring(1);
8
9     urlParams = {};
10     while (match = search.exec(query))
11        urlParams[decode(match[1])] = decode(match[2]);
12 })();
13
14 $(function() {
15
16         doLog = function(aTextToLog, type){
17                 var aLog = $('<div>',{'class':"log "+type,html:aTextToLog});
18                 aLog.hide().prependTo($log).show('fast').delay(3000).hide('fast', function() { 
19                         $(this).remove(); 
20                 });
21         }
22         var $main = $("#Changing");
23         var $metaNav = $("#metaNav");
24         var $log = $("#userLog");
25         tooltip_options = {
26                 position: {
27                         my: "center bottom-5",
28                         at: "center top",
29                         using: function( position, feedback ) {
30                                 $( this ).css( position );
31                                 $( "<div>" )
32                                 .addClass( "arrow" )
33                                 .addClass( feedback.vertical )
34                                 .addClass( feedback.horizontal )
35                                 .appendTo( this );
36                         }
37                 }
38         };
39
40         $('.newsRoll').tooltip(tooltip_options);
41         $('#metaNav').tooltip(tooltip_options);
42
43         $('body').css({'min-height':$(window).height() + $('#Commons').height()});
44         /****************************************************/
45         /**** AJAX UTILITIES FOR REQUESTS ****/
46         /****************************************************/
47         String.prototype.decodeHTML = function() {
48                 return $("<div>", {html: "" + this}).html();
49         };
50         var loadPage_request = null;
51         afterLoad = function(html, textStatus, XMLHttpRequest) {
52                 loadPage_request = null;
53                 if (textStatus == "error") {
54                         doLog('Sorry! And error occur when loading page content','error');
55                 }
56                 new_html = $.parseHTML(html);
57                 new_content = $(new_html).find('#Changing>*');
58                 $main.hide().empty().append(new_content).show();
59
60                 /* calling onpopstate here is necessary to get urlParams to be
61                  * updated */
62                 window.onpopstate();
63
64                 canonical_href_node = $.grep($(new_html), function(elem, idx) {
65                         return (elem.nodeName === "LINK" && elem.attributes['rel'].value == "canonical");
66                 })[0];
67                 if (canonical_href_node) {
68                         canonical_href = canonical_href_node.attributes['href'].value;
69                         history.replaceState({}, '', canonical_href);
70                 }
71
72                 new_menu = $($.parseHTML(html)).find('#metaNav>*');
73                 $metaNav.empty().append(new_menu);
74
75                 var newTitle = html?html.match(/<title>(.*?)<\/title>/):'';
76                 if(newTitle){document.title = newTitle[1].trim().decodeHTML();}
77
78                 /*
79                 Quite UGLY but needed for styling the whole body with ID
80                 Feel free to correct and find a better way
81                 According to this link the probles is that $(html).filter('body').Attr('id') will not work!
82                 http://www.devnetwork.net/viewtopic.php?f=13&t=117065
83                 */
84                 if(sectionName = $(html).find('[data-section]').attr('data-section')){
85                         $('body').attr('id',sectionName);
86                 }else{
87                         var bodyID = html.match(/<body id="(.*?)">/);   
88                         if(bodyID){$('body').attr('id',bodyID[1].trim());}      
89                 }
90                 $("#Changing").css({'min-height':$(window).height()});
91                 $.scrollTo('#Changing',1000,{offset:-$('#metaNav').height()+2});
92                 init();
93
94                 if (typeof (Piwik) == 'object') {
95                         piwikTracker = Piwik.getAsyncTracker();
96                         if (typeof (piwikTracker.trackPageView) == 'function') {
97                                 piwikTracker.setDocumentTitle(document.title);
98                                 piwikTracker.setCustomUrl(window.location.href);
99                                 piwikTracker.trackPageView();
100                                 $('.audio a').each(function() {
101                                         piwikTracker.addListener(this);
102                                 });
103                         }
104                 }
105
106         };
107
108         function afterLoadError(xhr, text, error) {
109                 afterLoad(xhr.responseText, 'error', xhr);
110         };
111
112         $(window).on("popstate", function(e) {
113                 if (e.originalEvent.state !== null) {loadPage(location.href, false);}
114         });
115
116         loadPage = function(href, push_state) {
117                 if (push_state !== false) {
118                         history.pushState({}, '', href);
119                 }
120                 if (loadPage_request !== null) {
121                         loadPage_request.abort();
122                 }
123                 loadPage_request = $.ajax({
124                         url: href,
125                         success: afterLoad,
126                         error: afterLoadError,
127                         dataType: 'html'});
128         };
129         $.fn.ajaxifyClick = function(params) {
130                 if ($('#df-wpr-sidebar').length > 0) {
131                         /* this is fiber sidebar, it doesn't work well with
132                          * seamless page loading */
133                         return;
134                 }
135                 this.each(function() {
136                         $(this).unbind('click');
137                         $(this).bind('click',function(e){
138                                 var href = $(this).attr("href");
139                                 if (href.match('\.(pdf|odt|ods|doc|xls|docx|xlsx|rtf)$')) {
140                                         /* open files */
141                                         window.open(href, '_blank');
142                                         return false;
143                                 }
144                                 if (e.which == 2) {
145                                         window.open(href, '_blank');
146                                         return false;
147                                 }
148                                 $(this).addClass('loading');
149                                 /* this checks the link points to a local document, be
150                                  * it because it's just a path, or because the server
151                                  * part points to the same domain */
152                                 if (!href) {
153                                         doLog('No href attributes, unable to load content','error');
154                                         $("#All a, #All area").removeClass('loading');
155                                         return false;
156                                 }else if (!$(this).attr('target') && (
157                                                 href.indexOf(document.domain) > -1 ||href.indexOf(':') === -1 || href.indexOf(':') > 5
158                                         )) {
159                                         loadPage(href);
160                                         return false;
161                                 }else{
162                                         $(this).attr('target','_blank');
163                                         $("#All a, #All area").removeClass('loading');
164                                         return true;
165                                 }
166                         });
167                 });
168         };
169         /****************************************************/
170         /**** AUDIOPLAYER ****/
171         /****************************************************/
172
173         var timer = null;
174         var refresh_onair_interval = 25000;
175         var ticker_interval = null;
176         /*
177         //TODO: mini icon version for player, (playpause only)
178         $('#togglePlayer').on('click',function(e) {
179                 e.preventDefault();
180                 if($(this).is('.icon-double-angle-left')){
181                         $("#player").fadeOut('fast',function(){
182                                 $("#player-container").toggleClass('minimized');                        
183                                 $('#togglePlayer').toggleClass('icon-double-angle-left icon-double-angle-right');
184                         });                     
185                 }else{
186                         $("#player").fadeIn('fast',function(){
187                                 $("#player-container").toggleClass('minimized');                        
188                                 $('#togglePlayer').toggleClass('icon-double-angle-left icon-double-angle-right');
189                         });     
190                 }
191                 return false;
192         });
193         */
194         $('#WhatsOnAir').on('load',function(){
195                 var WhatsOnAir = $(this);
196                 $('#RefreshWhatsOnAir').addClass('spinning');
197                 $.getJSON('/onair.json', function(onair) {
198                         setTimeout(function() { $('#RefreshWhatsOnAir').removeClass('spinning'); }, 5000);
199                         var onairContainer = $('<span>');
200                         if(onair.data.episode || onair.data.emission) {
201                                 if(onair.data.emission){
202                                         $('<a>',{href:onair.data.emission.url,html:onair.data.emission.title}).appendTo(onairContainer).ajaxifyClick();
203                                 }
204                                 if(onair.data.episode){
205                                         $('<span> - </span>').appendTo(onairContainer);
206                                         $('<a>',{href:onair.data.episode.url,html:onair.data.episode.title}).appendTo(onairContainer).ajaxifyClick();
207                                 }
208                         } else if (onair.data.nonstop) {
209                                 onairContainer = $('<span>' + onair.data.nonstop.title + '</span>');
210                                 if (onair.data.track_title) {
211                                         $('<span> - </span>').appendTo(onairContainer);
212                                         $('<span class="nonstop-track-title">' + onair.data.track_title + '</span>').appendTo(onairContainer);
213                                         if (onair.data.track_artist) {
214                                                 $('<span> </span>').appendTo(onairContainer)
215                                                 $('<span class="nonstop-track-artist">(' + onair.data.track_artist + ')</span>').appendTo(onairContainer);
216                                         }
217                                 }
218                         }
219                         else {
220                                 onairContainer = $('<span>Unknown (Probably Non-Stop)</span>');
221                         }
222                         var current_html = WhatsOnAir.html();
223                         var new_html = '<span>' + onairContainer.html() + '</span>';
224                         if (new_html !== current_html) {
225                                 WhatsOnAir.fadeOut();
226                                 WhatsOnAir.empty().append(onairContainer);
227                                 WhatsOnAir.fadeIn();
228                         }
229                 });
230         });
231         $('#RefreshWhatsOnAir').on('activate',function(e){
232                 $('#WhatsOnAir').trigger('load');
233                 timer = setInterval( "$('#WhatsOnAir').trigger('load');", refresh_onair_interval);
234         }).on('deactivate',function(e){
235                 $(this).removeClass('spinning');
236                 $('#WhatsOnAir').removeClass('active');
237                 clearInterval(timer);
238         }).on('click',function(e){
239                 $(this).toggleClass('active');
240                 if($(this).is('.active')){
241                         $(this).trigger('deactivate');
242                 }else{
243                         $(this).trigger('activate');
244                 }
245                 return false;
246         }).trigger('activate');
247         $("#DirectStreamPanikControler").on('click',function(e) {
248                 e.preventDefault();
249                 var stream = $('#DirectStreamPanik').get(0);
250                 if (stream.paused == false){
251                         stream.pause();
252                 }else{
253                         if (typeof (_paq) == 'object') {
254                                 _paq.push(['trackGoal', 1]);
255                         }
256                         stream.play();
257                 }
258                 return false;
259         });
260         $('#DirectStreamPanik').on('play',function(){
261                 $('audio:not(#DirectStreamPanik)').each(function(){this.pause();});
262                 $('#streamSymbol').removeClass('icon-volume-up').addClass('icon-pause');
263                 $('#RefreshWhatsOnAir').trigger('activate');
264         }).on('pause',function(){
265                 //$('audio:not(#DirectStreamPanik)').each(function(){this.pause();});
266                 $('#streamSymbol').addClass('icon-volume-up').removeClass('icon-pause');
267         });
268         if($('#player-container').offset()){
269                 var topPosition = 0;
270                 topPosition = $('#mainHeader > div').offset().top + $('#mainHeader > div').height();
271                 $(window).bind('scroll load',function (event) {
272                         //$('#player-container').removeClass('fixed');
273                         var y = $(this).scrollTop() + 40;
274                         if (topPosition!== 0 && y >= topPosition) {
275                                 $('#player-container').addClass('fixed').removeClass('normal');
276                         } else {
277                                 $('#player-container').removeClass('fixed').addClass('normal');
278                         }
279                 });
280         }
281
282         var $localList = $('#localList').playlist({
283                 controlContainer: $('<div>',{'class':"playListControls"}).sortable(),
284                 playlistContainer: $('<ol>',{id:"myPlaylist",'class':"custom"}).sortable(),
285                 onLoad:function(self){
286                         $('#toggleList').on('click',function(){ 
287                                 self.playlistContainer.toggleClass('deploy');
288                         });
289                         $('#emptyList').on('click',function(){ 
290                                 self._reset();
291                         });
292
293                         if(self.isActive){
294                                 self.playlistContainer.scrollTo(self.isActive, 800 );
295                                 self.isActive.find('audio').attr('preload',"preload")
296                         }
297                         self.controlButtons['playpause'].addClass('resymbol');
298                 },
299                 onPlay:function(self){
300                         $('#DirectStreamPanik')[0].pause();
301                         self.playlistContainer.scrollTo(self.isActive, 800 );
302                         if (typeof (_paq) == 'object') {
303                                 _paq.push(['trackGoal', 4]);
304                         }
305                 },
306                 onAdd:function(self){
307                         //self.isLastAdd[0].scrollIntoView();
308                         self.isLastAdd.find('a').ajaxifyClick();
309                         self.playlistContainer.scrollTo(self.isLastAdd, 800).delay(1000).scrollTo(self.isActive, 800 ).clearQueue();
310
311                         if (typeof (_paq) == 'object') {
312                                 _paq.push(['trackGoal', 3]);
313                         }
314                 },
315                 onUpdate:function(self){
316                         //doLog(JSON.stringify(self.playlist, null, '\t'));     
317                         if(self.playlist.length >= 1){
318                                 self.element.show();
319                                 $('#Player').addClass('withPlaylist').removeClass('withoutPlaylist');
320                         }else{
321                                 self.element.hide();
322                                 $('#Player').removeClass('withPlaylist').addClass('withoutPlaylist');
323                         }
324                 }
325         });
326
327         init = function() {
328                 $("#All a, #All area").removeClass('loading');
329                 $("#All a, #All area").ajaxifyClick();
330                 $("#search-form").unbind('submit').on('submit', function(event) {
331                         event.preventDefault();
332                         $(this).addClass('loading');
333                         loadPage($(this).attr('action') + '?' + $(this).serialize());
334                 });
335                 $(".tabs").each(function() {
336                         var self = $(this);
337                         var about= $($(this).attr("data-tab-about"));
338                         var current = $(this).find("[data-tab].active")[0];
339                         var dftShowSelector = current?".active":":first";
340                         var activeTab = $(this).find("[data-tab]"+dftShowSelector+"").addClass("active");
341                         $(this).find("[data-tab]").each(function() {
342                             $(this).on('click load',function (e) {  
343                                 e.preventDefault();
344                                 self.find(".active").removeClass("active");  
345                                 $(this).addClass("active");  
346                                 about.find("[data-tabbed]").hide();  
347                                 $($(this).attr("data-tab")).fadeIn();  
348                 
349                             });  
350                         });  
351                         activeTab.trigger('load');
352                 });
353                 $('[data-player-action]').on('click',function(){
354                         var audio = $('#'+$(this).attr('data-player-audio'));
355                         var sound_id = audio.data('sound-id');
356                         if($(this).attr('data-player-action') == "registerAudio"){
357                                 $localList.playlist("registerAudio",audio,doLog(audio.attr('title')+' has been added to your playlist.','ok'));
358                         }else if($(this).attr('data-player-action') == "playAudio"){
359                                 $localList.playlist("registerAudio",audio,doLog(audio.attr('title')+' will play soon.','ok'));
360                                 $localList.playlist("playSoundId", sound_id);
361                         }else{
362                                 $localList.playlist($(this).attr('data-player-action'));
363                         }
364                 });
365                 $('[data-player-control]').each(function(){
366                         var audio = $('#'+$(this).attr('data-player-audio'));
367                         $localList.playlist("bindControl",$(this).attr('data-player-control'),audio,$(this));
368                 });
369
370                 $('[data-highlight]').on('check',function(){
371                         $($(this).attr('data-about')).find($(this).attr('data-highlight')).addClass('highlighted').removeClass('normal');
372                 }).on('uncheck',function(){
373                         $($(this).attr('data-about')).find($(this).attr('data-highlight')).removeClass('highlighted').addClass('normal');
374                 }).on('click',function(){
375                         $(this).toggleClass('icon-check icon-check-empty');
376                         if($(this).hasClass('icon-check')){$(this).trigger('check');
377                         }else{  $(this).trigger('uncheck');}
378                 });
379                 $('[data-highlight].icon-check-empty').each(function(){
380                         $(this).trigger('uncheck');
381                 });
382                 $('[data-toggle]').on('check',function(){
383                         /* make sure all other unchecked items are hidden */
384                         $('[data-toggle].icon-check-empty').each(function() {
385                                 $($(this).attr('data-about')).find($(this).attr('data-toggle')).hide();
386                         });
387                         $($(this).attr('data-about')).find($(this).attr('data-toggle')).show();
388                 }).on('uncheck',function(){
389                         $($(this).attr('data-about')).find($(this).attr('data-toggle')).hide();
390                         if ($('[data-toggle].icon-check').length == 0) {
391                                 /* special case the situation where all toggles
392                                  * are unchecked, as we want that to mean
393                                  * "everything", not "nothing".
394                                  */
395                                 $('[data-toggle].icon-check-empty').each(function() {
396                                         $($(this).attr('data-about')).find($(this).attr('data-toggle')).show();
397                                 });
398                         }
399                 }).on('click',function(){
400                         $(this).toggleClass('icon-check icon-check-empty');
401                         if($(this).hasClass('icon-check')){$(this).trigger('check');
402                         }else{  $(this).trigger('uncheck');}
403                 });
404                 $('[data-toggle].icon-check-empty').each(function(){
405                         $(this).trigger('uncheck');
406                 });
407
408                 initial_enabled_toggles = {};
409                 if (typeof(urlParams.q) == 'string') {
410                         urlParams.q.split('|').forEach(function(a) { initial_enabled_toggles[a] = 1; })
411                 }
412                 $('[data-toggle]').each(function() {
413                         if ($(this).data('toggle').substring(1) in initial_enabled_toggles) {
414                                 $(this).trigger('click');
415                         }
416                 });
417
418                 if ($('input#id_q').val() == '') {
419                         $('input#id_q').focus();
420                 }
421
422                 $('#ticker li:not(:first)');
423                 if (ticker_interval) clearInterval(ticker_interval);
424                 function tick(){
425                     $('#ticker li:first').animate({'opacity':0}, 200, function () {
426                         $(this).appendTo($('#ticker')).css('opacity', 1);
427                     });
428                 }
429                 $("#roller button").on('click',function(e){
430                     clearInterval(ticker_interval);
431                     e.preventDefault();
432                     $($(this).attr('data-about')).prependTo('#ticker');
433                     return false;
434                 });
435                 ticker_interval = setInterval(function(){tick();  }, 20000);/**/
436
437                 function navsearch_click(event) {
438                         event.preventDefault();
439                         var query = $('#nav-search input').val();
440                         var form = $('#nav-search form');
441                         var href = '';
442                         if (query == '') {
443                                 href = $(form).attr('action');
444                         } else {
445                                 href = $(form).attr('action') + '?' + $(form).serialize();
446                         }
447                         if (event.which == 2) {
448                                 window.open(href, '_blank');
449                         } else {
450                                 $(this).addClass('loading');
451                                 loadPage(href);
452                         }
453                         return false;
454                 }
455                 $('#nav-search a').unbind('click').on('click', navsearch_click);
456                 $('#nav-search form').unbind('submit').on('submit', navsearch_click);
457
458                 $('[data-toggle-img]').bind('click', function() {
459                         var src = $(this).data('toggle-img');
460                         $(this).data('toggle-img', $(this).attr('src'));
461                         $(this).attr('src', src);
462                         $(this).toggleClass('right marged');
463                 });
464
465                 $('#Main #Emission-tabs-detail audio').each(function(index, audio) {
466                         var audio_src = $(audio).find('source')[0];
467                         var sound_id = $(audio).data('sound-id');
468                         var $waveform = $(audio).next();
469                         $.getJSON(audio_src.src.replace('.ogg', '.waveform.json'), function(data) {
470                                 $waveform.empty();
471                                 $waveform.append('<i class="duration">' + $waveform.data('duration-string') + '</i>');
472                                 $.each(data, function(k, val) {
473                                         var val = val * 0.5;
474                                         $waveform.append('<span data-tick-index="' + k + '" style="height: ' + val + 'px;"></span>');
475                                 });
476                                 $waveform.show();
477                                 $waveform.find('span').on('click', function() {
478                                         /* if there's been something loaded */
479                                         var matching_audio = $('audio[data-sound-id=' + sound_id + ']');
480                                         if (matching_audio.length == 0) return;
481                                         matching_audio = matching_audio[0];
482                                         if (matching_audio.paused || matching_audio.ended) {
483                                                 /* ignore */
484                                                 return;
485                                         }
486                                         /* try to set time */
487                                         var total_duration = parseFloat($waveform.data('duration'));
488                                         var nb_ticks = $(this).parent().find('span').length;
489                                         var tick_index = $(this).data('tick-index');
490                                         matching_audio.currentTime = total_duration * tick_index / nb_ticks;
491                                 });
492                         });
493                 });
494
495
496                 if (document.cookie.indexOf('panikdb=on') != -1) {
497                         panikdb_path = null;
498                         if (window.location.pathname.indexOf('/emissions/') == 0) {
499                                 panikdb_path = window.location.pathname;
500                         } else if (window.location.pathname.indexOf('/news/') == 0) {
501                                 panikdb_path = '/emissions' + window.location.pathname;
502                         }
503                         if (panikdb_path) {
504                                 $('<a id="panikdb" href="http://panikdb.radiopanik.org' + panikdb_path + '">Voir dans PanikDB</a>').appendTo($main);
505                         }
506                 }
507         }
508         init();
509
510         if (! document.createElement('audio').canPlayType('audio/ogg') &&
511                 document.createElement('audio').canPlayType('audio/aac') ) {
512                 $('#ogg-m3u').hide().removeClass('resymbol');
513                 $('#aac-m3u').addClass('resymbol').show();
514         }
515
516         var konami = new Konami('/party');
517
518         $(document).on('panik:timeupdate', function(ev, data) {
519                 $waveform = $('#Main div.waveform[data-sound-id="' + data.sound_id + '"]');
520                 var elems = $waveform.find('span');
521                 var total_elems = elems.length;
522                 var done = total_elems * data.position;
523                 $waveform.find('span').each(function(k, elem) {
524                   if (k < done) {
525                         $(elem).addClass('done').removeClass('current');
526                   } else {
527                         $(elem).removeClass('done');
528                   }
529                 });
530                 $waveform.find('span.done:last').addClass('current');
531         });
532 });