]> git.0d.be Git - panikweb.git/blob - panikweb_templates/static/js/specifics.js
add panikombo dependency, for the soundfile cell type
[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         /*
176         //TODO: mini icon version for player, (playpause only)
177         $('#togglePlayer').on('click',function(e) {
178                 e.preventDefault();
179                 if($(this).is('.icon-double-angle-left')){
180                         $("#player").fadeOut('fast',function(){
181                                 $("#player-container").toggleClass('minimized');                        
182                                 $('#togglePlayer').toggleClass('icon-double-angle-left icon-double-angle-right');
183                         });                     
184                 }else{
185                         $("#player").fadeIn('fast',function(){
186                                 $("#player-container").toggleClass('minimized');                        
187                                 $('#togglePlayer').toggleClass('icon-double-angle-left icon-double-angle-right');
188                         });     
189                 }
190                 return false;
191         });
192         */
193         $('#WhatsOnAir').on('load',function(){
194                 var WhatsOnAir = $(this);
195                 $('#RefreshWhatsOnAir').addClass('spinning');
196                 $.getJSON('/onair.json', function(onair) {
197                         setTimeout(function() { $('#RefreshWhatsOnAir').removeClass('spinning'); }, 5000);
198                         var onairContainer = $('<span>');
199                         if(onair.data.episode || onair.data.emission) {
200                                 if(onair.data.emission){
201                                         $('<a>',{href:onair.data.emission.url,html:onair.data.emission.title}).appendTo(onairContainer).ajaxifyClick();
202                                 }
203                                 if(onair.data.episode){
204                                         $('<span> - </span>').appendTo(onairContainer);
205                                         $('<a>',{href:onair.data.episode.url,html:onair.data.episode.title}).appendTo(onairContainer).ajaxifyClick();
206                                 }
207                         } else if (onair.data.nonstop) {
208                                 onairContainer = $('<span>' + onair.data.nonstop.title + '</span>');
209                                 if (onair.data.track_title) {
210                                         $('<span> - </span>').appendTo(onairContainer);
211                                         $('<span class="nonstop-track-title">' + onair.data.track_title + '</span>').appendTo(onairContainer);
212                                         if (onair.data.track_artist) {
213                                                 $('<span> </span>').appendTo(onairContainer)
214                                                 $('<span class="nonstop-track-artist">(' + onair.data.track_artist + ')</span>').appendTo(onairContainer);
215                                         }
216                                 }
217                         }
218                         else {
219                                 onairContainer = $('<span>Unknown (Probably Non-Stop)</span>');
220                         }
221                         var current_html = WhatsOnAir.html();
222                         var new_html = '<span>' + onairContainer.html() + '</span>';
223                         if (new_html !== current_html) {
224                                 WhatsOnAir.fadeOut();
225                                 WhatsOnAir.empty().append(onairContainer);
226                                 WhatsOnAir.fadeIn();
227                         }
228                 });
229         });
230         $('#RefreshWhatsOnAir').on('activate',function(e){
231                 $('#WhatsOnAir').trigger('load');
232                 timer = setInterval( "$('#WhatsOnAir').trigger('load');", refresh_onair_interval);
233         }).on('deactivate',function(e){
234                 $(this).removeClass('spinning');
235                 $('#WhatsOnAir').removeClass('active');
236                 clearInterval(timer);
237         }).on('click',function(e){
238                 $(this).toggleClass('active');
239                 if($(this).is('.active')){
240                         $(this).trigger('deactivate');
241                 }else{
242                         $(this).trigger('activate');
243                 }
244                 return false;
245         }).trigger('activate');
246         $("#DirectStreamPanikControler").on('click',function(e) {
247                 e.preventDefault();
248                 var stream = $('#DirectStreamPanik').get(0);
249                 if (stream.paused == false){
250                         stream.pause();
251                 }else{
252                         if (typeof (_paq) == 'object') {
253                                 _paq.push(['trackGoal', 1]);
254                         }
255                         stream.play();
256                 }
257                 return false;
258         });
259         $('#DirectStreamPanik').on('play',function(){
260                 $('audio:not(#DirectStreamPanik)').each(function(){this.pause();});
261                 $('#streamSymbol').removeClass('icon-volume-up').addClass('icon-pause');
262                 $('#RefreshWhatsOnAir').trigger('activate');
263         }).on('pause',function(){
264                 //$('audio:not(#DirectStreamPanik)').each(function(){this.pause();});
265                 $('#streamSymbol').addClass('icon-volume-up').removeClass('icon-pause');
266         });
267         if($('#player-container').offset()){
268                 var topPosition = 0;
269                 topPosition = $('#mainHeader > div').offset().top + $('#mainHeader > div').height();
270                 $(window).bind('scroll load',function (event) {
271                         //$('#player-container').removeClass('fixed');
272                         var y = $(this).scrollTop() + 40;
273                         if (topPosition!== 0 && y >= topPosition) {
274                                 $('#player-container').addClass('fixed').removeClass('normal');
275                         } else {
276                                 $('#player-container').removeClass('fixed').addClass('normal');
277                         }
278                 });
279         }
280
281         var $localList = $('#localList').playlist({
282                 controlContainer: $('<div>',{'class':"playListControls"}).sortable(),
283                 playlistContainer: $('<ol>',{id:"myPlaylist",'class':"custom"}).sortable(),
284                 onLoad:function(self){
285                         $('#toggleList').on('click',function(){ 
286                                 self.playlistContainer.toggleClass('deploy');
287                         });
288                         $('#emptyList').on('click',function(){ 
289                                 self._reset();
290                         });
291
292                         if(self.isActive){
293                                 self.playlistContainer.scrollTo(self.isActive, 800 );
294                                 self.isActive.find('audio').attr('preload',"preload")
295                         }
296                         self.controlButtons['playpause'].addClass('resymbol');
297                 },
298                 onPlay:function(self){
299                         $('#DirectStreamPanik')[0].pause();
300                         self.playlistContainer.scrollTo(self.isActive, 800 );
301                         if (typeof (_paq) == 'object') {
302                                 _paq.push(['trackGoal', 4]);
303                         }
304                 },
305                 onAdd:function(self){
306                         //self.isLastAdd[0].scrollIntoView();
307                         self.isLastAdd.find('a').ajaxifyClick();
308                         self.playlistContainer.scrollTo(self.isLastAdd, 800).delay(1000).scrollTo(self.isActive, 800 ).clearQueue();
309
310                         if (typeof (_paq) == 'object') {
311                                 _paq.push(['trackGoal', 3]);
312                         }
313                 },
314                 onUpdate:function(self){
315                         //doLog(JSON.stringify(self.playlist, null, '\t'));     
316                         if(self.playlist.length >= 1){
317                                 self.element.show();
318                                 $('#Player').addClass('withPlaylist').removeClass('withoutPlaylist');
319                         }else{
320                                 self.element.hide();
321                                 $('#Player').removeClass('withPlaylist').addClass('withoutPlaylist');
322                         }
323                 }
324         });
325
326         init = function() {
327                 $("#All a, #All area").removeClass('loading');
328                 $("#All a, #All area").ajaxifyClick();
329                 $("#search-form").unbind('submit').on('submit', function(event) {
330                         event.preventDefault();
331                         $(this).addClass('loading');
332                         loadPage($(this).attr('action') + '?' + $(this).serialize());
333                 });
334                 $(".tabs").each(function() {
335                         var self = $(this);
336                         var about= $($(this).attr("data-tab-about"));
337                         var current = $(this).find("[data-tab].active")[0];
338                         var dftShowSelector = current?".active":":first";
339                         var activeTab = $(this).find("[data-tab]"+dftShowSelector+"").addClass("active");
340                         $(this).find("[data-tab]").each(function() {
341                             $(this).on('click load',function (e) {  
342                                 e.preventDefault();
343                                 self.find(".active").removeClass("active");  
344                                 $(this).addClass("active");  
345                                 about.find("[data-tabbed]").hide();  
346                                 $($(this).attr("data-tab")).fadeIn();  
347                 
348                             });  
349                         });  
350                         activeTab.trigger('load');
351                 });
352                 $('[data-player-action]').on('click',function(){
353                         var audio = $('#'+$(this).attr('data-player-audio'));
354                         var sound_id = audio.data('sound-id');
355                         if($(this).attr('data-player-action') == "registerAudio"){
356                                 $localList.playlist("registerAudio",audio,doLog(audio.attr('title')+' has been added to your playlist.','ok'));
357                         }else if($(this).attr('data-player-action') == "playAudio"){
358                                 $localList.playlist("registerAudio",audio,doLog(audio.attr('title')+' will play soon.','ok'));
359                                 $localList.playlist("playSoundId", sound_id);
360                         }else{
361                                 $localList.playlist($(this).attr('data-player-action'));
362                         }
363                 });
364                 $('[data-player-control]').each(function(){
365                         var audio = $('#'+$(this).attr('data-player-audio'));
366                         $localList.playlist("bindControl",$(this).attr('data-player-control'),audio,$(this));
367                 });
368
369                 $('[data-highlight]').on('check',function(){
370                         $($(this).attr('data-about')).find($(this).attr('data-highlight')).addClass('highlighted').removeClass('normal');
371                 }).on('uncheck',function(){
372                         $($(this).attr('data-about')).find($(this).attr('data-highlight')).removeClass('highlighted').addClass('normal');
373                 }).on('click',function(){
374                         $(this).toggleClass('icon-check icon-check-empty');
375                         if($(this).hasClass('icon-check')){$(this).trigger('check');
376                         }else{  $(this).trigger('uncheck');}
377                 });
378                 $('[data-highlight].icon-check-empty').each(function(){
379                         $(this).trigger('uncheck');
380                 });
381                 $('[data-toggle]').on('check',function(){
382                         /* make sure all other unchecked items are hidden */
383                         $('[data-toggle].icon-check-empty').each(function() {
384                                 $($(this).attr('data-about')).find($(this).attr('data-toggle')).hide();
385                         });
386                         $($(this).attr('data-about')).find($(this).attr('data-toggle')).show();
387                 }).on('uncheck',function(){
388                         $($(this).attr('data-about')).find($(this).attr('data-toggle')).hide();
389                         if ($('[data-toggle].icon-check').length == 0) {
390                                 /* special case the situation where all toggles
391                                  * are unchecked, as we want that to mean
392                                  * "everything", not "nothing".
393                                  */
394                                 $('[data-toggle].icon-check-empty').each(function() {
395                                         $($(this).attr('data-about')).find($(this).attr('data-toggle')).show();
396                                 });
397                         }
398                 }).on('click',function(){
399                         $(this).toggleClass('icon-check icon-check-empty');
400                         if($(this).hasClass('icon-check')){$(this).trigger('check');
401                         }else{  $(this).trigger('uncheck');}
402                 });
403                 $('[data-toggle].icon-check-empty').each(function(){
404                         $(this).trigger('uncheck');
405                 });
406
407                 initial_enabled_toggles = {};
408                 if (typeof(urlParams.q) == 'string') {
409                         urlParams.q.split('|').forEach(function(a) { initial_enabled_toggles[a] = 1; })
410                 }
411                 $('[data-toggle]').each(function() {
412                         if ($(this).data('toggle').substring(1) in initial_enabled_toggles) {
413                                 $(this).trigger('click');
414                         }
415                 });
416
417                 if ($('input#id_q').val() == '') {
418                         $('input#id_q').focus();
419                 }
420
421                 function navsearch_click(event) {
422                         event.preventDefault();
423                         var query = $('#nav-search input').val();
424                         var form = $('#nav-search form');
425                         var href = '';
426                         if (query == '') {
427                                 href = $(form).attr('action');
428                         } else {
429                                 href = $(form).attr('action') + '?' + $(form).serialize();
430                         }
431                         if (event.which == 2) {
432                                 window.open(href, '_blank');
433                         } else {
434                                 $(this).addClass('loading');
435                                 loadPage(href);
436                         }
437                         return false;
438                 }
439                 $('#nav-search a').unbind('click').on('click', navsearch_click);
440                 $('#nav-search form').unbind('submit').on('submit', navsearch_click);
441
442                 $('[data-toggle-img]').bind('click', function() {
443                         var src = $(this).data('toggle-img');
444                         $(this).data('toggle-img', $(this).attr('src'));
445                         $(this).attr('src', src);
446                         $(this).toggleClass('right marged');
447                 });
448
449                 $('#Main #Emission-tabs-detail audio, div.soundcell audio').each(function(index, audio) {
450                         var audio_src = $(audio).find('source')[0];
451                         var sound_id = $(audio).data('sound-id');
452                         var $waveform = $(audio).next();
453                         $.getJSON(audio_src.src.replace('.ogg', '.waveform.json'), function(data) {
454                                 $waveform.empty();
455                                 $waveform.append('<i class="duration">' + $waveform.data('duration-string') + '</i>');
456                                 $.each(data, function(k, val) {
457                                         var val = val * 0.5;
458                                         $waveform.append('<span data-tick-index="' + k + '" style="height: ' + val + 'px;"></span>');
459                                 });
460                                 $waveform.show();
461                                 $waveform.find('span').on('click', function() {
462                                         /* if there's been something loaded */
463                                         var matching_audio = $('audio[data-sound-id=' + sound_id + ']');
464                                         if (matching_audio.length == 0) return;
465                                         matching_audio = matching_audio[0];
466                                         if (matching_audio.paused || matching_audio.ended) {
467                                                 /* ignore */
468                                                 return;
469                                         }
470                                         /* try to set time */
471                                         var total_duration = parseFloat($waveform.data('duration'));
472                                         var nb_ticks = $(this).parent().find('span').length;
473                                         var tick_index = $(this).data('tick-index');
474                                         matching_audio.currentTime = total_duration * tick_index / nb_ticks;
475                                 });
476                         });
477                 });
478
479
480                 if (document.cookie.indexOf('panikdb=on') != -1) {
481                         panikdb_path = null;
482                         if (window.location.pathname.indexOf('/emissions/') == 0) {
483                                 panikdb_path = window.location.pathname;
484                         } else if (window.location.pathname.indexOf('/news/') == 0) {
485                                 panikdb_path = '/emissions' + window.location.pathname;
486                         }
487                         if (panikdb_path) {
488                                 $('<a id="panikdb" href="http://panikdb.radiopanik.org' + panikdb_path + '">Voir dans PanikDB</a>').appendTo($main);
489                         }
490                 }
491         }
492         init();
493
494         if (! document.createElement('audio').canPlayType('audio/ogg') &&
495                 document.createElement('audio').canPlayType('audio/aac') ) {
496                 $('#ogg-m3u').hide().removeClass('resymbol');
497                 $('#aac-m3u').addClass('resymbol').show();
498         }
499
500         var konami = new Konami('/party');
501
502         $(document).on('panik:timeupdate', function(ev, data) {
503                 $waveform = $('#Main div.waveform[data-sound-id="' + data.sound_id + '"]');
504                 var elems = $waveform.find('span');
505                 var total_elems = elems.length;
506                 var done = total_elems * data.position;
507                 $waveform.find('span').each(function(k, elem) {
508                   if (k < done) {
509                         $(elem).addClass('done').removeClass('current');
510                   } else {
511                         $(elem).removeClass('done');
512                   }
513                 });
514                 $waveform.find('span.done:last').addClass('current');
515         });
516 });