]> git.0d.be Git - panikweb.git/blob - panikweb_templates/static/js/specifics.js
js: add tracking for goals related to podcasts and playlist (#1133, #1134)
[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_content = $($.parseHTML(html)).find('#Changing>*');
57                 $main.hide().empty().append(new_content).show();
58
59                 /* calling onpopstate here is necessary to get urlParams to be
60                  * updated */
61                 window.onpopstate();
62
63                 new_menu = $($.parseHTML(html)).find('#metaNav>*');
64                 $metaNav.empty().append(new_menu);
65
66                 var newTitle = html?html.match(/<title>(.*?)<\/title>/):'';
67                 if(newTitle){document.title = newTitle[1].trim().decodeHTML();}
68
69                 /*
70                 Quite UGLY but needed for styling the whole body with ID
71                 Feel free to correct and find a better way
72                 According to this link the probles is that $(html).filter('body').Attr('id') will not work!
73                 http://www.devnetwork.net/viewtopic.php?f=13&t=117065
74                 */
75                 if(sectionName = $(html).find('[data-section]').attr('data-section')){
76                         $('body').attr('id',sectionName);
77                 }else{
78                         var bodyID = html.match(/<body id="(.*?)">/);   
79                         if(bodyID){$('body').attr('id',bodyID[1].trim());}      
80                 }
81                 $("#Changing").css({'min-height':$(window).height()});
82                 $.scrollTo('#Changing',1000,{offset:-$('#metaNav').height()+2});
83                 init();
84
85                 if (typeof (Piwik) == 'object') {
86                         piwikTracker = Piwik.getAsyncTracker();
87                         if (typeof (piwikTracker.trackPageView) == 'function') {
88                                 piwikTracker.setDocumentTitle(document.title);
89                                 piwikTracker.setCustomUrl(window.location.href);
90                                 piwikTracker.trackPageView();
91                                 $('.audio a').each(function() {
92                                         piwikTracker.addListener(this);
93                                 });
94                         }
95                 }
96
97         };
98
99         function afterLoadError(xhr, text, error) {
100                 afterLoad(xhr.responseText, 'error', xhr);
101         };
102
103         $(window).on("popstate", function(e) {
104                 if (e.originalEvent.state !== null) {loadPage(location.href, false);}
105         });
106
107         loadPage = function(href, push_state) {
108                 if (push_state !== false) {
109                         history.pushState({}, '', href);
110                 }
111                 if (loadPage_request !== null) {
112                         loadPage_request.abort();
113                 }
114                 loadPage_request = $.ajax({
115                         url: href,
116                         success: afterLoad,
117                         error: afterLoadError,
118                         dataType: 'html'});
119         };
120         $.fn.ajaxifyClick = function(params) {
121                 if ($('#df-wpr-sidebar').length > 0) {
122                         /* this is fiber sidebar, it doesn't work well with
123                          * seamless page loading */
124                         return;
125                 }
126                 this.each(function() {
127                         $(this).unbind('click');
128                         $(this).bind('click',function(e){
129                                 var href = $(this).attr("href");
130                                 if (href.match('\.(pdf|odt|ods|doc|xls|docx|xlsx|rtf)$')) {
131                                         /* open files */
132                                         window.open(href, '_blank');
133                                         return false;
134                                 }
135                                 if (e.which == 2) {
136                                         window.open(href, '_blank');
137                                         return false;
138                                 }
139                                 $(this).addClass('loading');
140                                 /* this checks the link points to a local document, be
141                                  * it because it's just a path, or because the server
142                                  * part points to the same domain */
143                                 if (!href) {
144                                         doLog('No href attributes, unable to load content','error');
145                                         $("#All a, #All area").removeClass('loading');
146                                         return false;
147                                 }else if (!$(this).attr('target') && (
148                                                 href.indexOf(document.domain) > -1 ||href.indexOf(':') === -1 || href.indexOf(':') > 5
149                                         )) {
150                                         loadPage(href);
151                                         return false;
152                                 }else{
153                                         $(this).attr('target','_blank');
154                                         $("#All a, #All area").removeClass('loading');
155                                         return true;
156                                 }
157                         });
158                 });
159         };
160         /****************************************************/
161         /**** AUDIOPLAYER ****/
162         /****************************************************/
163
164         var timer = null;
165         var refresh_onair_interval = 25000;
166         var ticker_interval = null;
167         /*
168         //TODO: mini icon version for player, (playpause only)
169         $('#togglePlayer').on('click',function(e) {
170                 e.preventDefault();
171                 if($(this).is('.icon-double-angle-left')){
172                         $("#player").fadeOut('fast',function(){
173                                 $("#player-container").toggleClass('minimized');                        
174                                 $('#togglePlayer').toggleClass('icon-double-angle-left icon-double-angle-right');
175                         });                     
176                 }else{
177                         $("#player").fadeIn('fast',function(){
178                                 $("#player-container").toggleClass('minimized');                        
179                                 $('#togglePlayer').toggleClass('icon-double-angle-left icon-double-angle-right');
180                         });     
181                 }
182                 return false;
183         });
184         */
185         $('#WhatsOnAir').on('load',function(){
186                 var WhatsOnAir = $(this);
187                 $('#RefreshWhatsOnAir').addClass('spinning');
188                 $.getJSON('/onair.json', function(onair) {
189                         setTimeout(function() { $('#RefreshWhatsOnAir').removeClass('spinning'); }, 5000);
190                         var onairContainer = $('<span>');
191                         if(onair.data.episode || onair.data.emission) {
192                                 if(onair.data.emission){
193                                         $('<a>',{href:onair.data.emission.url,html:onair.data.emission.title}).appendTo(onairContainer).ajaxifyClick();
194                                 }
195                                 if(onair.data.episode){
196                                         $('<span> - </span>').appendTo(onairContainer);
197                                         $('<a>',{href:onair.data.episode.url,html:onair.data.episode.title}).appendTo(onairContainer).ajaxifyClick();
198                                 }
199                         } else if (onair.data.nonstop) {
200                                 onairContainer = $('<span>' + onair.data.nonstop.title + '</span>');
201                         }
202                         else {
203                                 onairContainer = $('<span>Unknown (Probably Non-Stop)</span>');
204                         }
205                         var current_html = WhatsOnAir.html();
206                         var new_html = '<span>' + onairContainer.html() + '</span>';
207                         if (new_html !== current_html) {
208                                 WhatsOnAir.fadeOut();
209                                 WhatsOnAir.empty().append(onairContainer);
210                                 WhatsOnAir.fadeIn();
211                         }
212                 });
213         });
214         $('#RefreshWhatsOnAir').on('activate',function(e){
215                 $('#WhatsOnAir').trigger('load');
216                 timer = setInterval( "$('#WhatsOnAir').trigger('load');", refresh_onair_interval);
217         }).on('deactivate',function(e){
218                 $(this).removeClass('spinning');
219                 $('#WhatsOnAir').removeClass('active');
220                 clearInterval(timer);
221         }).on('click',function(e){
222                 $(this).toggleClass('active');
223                 if($(this).is('.active')){
224                         $(this).trigger('deactivate');
225                 }else{
226                         $(this).trigger('activate');
227                 }
228                 return false;
229         }).trigger('activate');
230         $("#DirectStreamPanikControler").on('click',function(e) {
231                 e.preventDefault();
232                 var stream = $('#DirectStreamPanik').get(0);
233                 if (stream.paused == false){
234                         stream.pause();
235                 }else{
236                         if (typeof (_paq) == 'object') {
237                                 _paq.push(['trackGoal', 1]);
238                         }
239                         stream.play();
240                 }
241                 return false;
242         });
243         $('#DirectStreamPanik').on('play',function(){
244                 $('audio:not(#DirectStreamPanik)').each(function(){this.pause();});
245                 $('#streamSymbol').removeClass('icon-volume-up').addClass('icon-pause');
246                 $('#RefreshWhatsOnAir').trigger('activate');
247         }).on('pause',function(){
248                 //$('audio:not(#DirectStreamPanik)').each(function(){this.pause();});
249                 $('#streamSymbol').addClass('icon-volume-up').removeClass('icon-pause');
250         });
251         if($('#player-container').offset()){
252                 var topPosition = 0;
253                 topPosition = $('#mainHeader > div').offset().top + $('#mainHeader > div').height();
254                 $(window).bind('scroll load',function (event) {
255                         //$('#player-container').removeClass('fixed');
256                         var y = $(this).scrollTop() + 40;
257                         if (topPosition!== 0 && y >= topPosition) {
258                                 $('#player-container').addClass('fixed').removeClass('normal');
259                         } else {
260                                 $('#player-container').removeClass('fixed').addClass('normal');
261                         }
262                 });
263         }
264
265         var $localList = $('#localList').playlist({
266                 controlContainer: $('<div>',{'class':"playListControls"}).sortable(),
267                 playlistContainer: $('<ol>',{id:"myPlaylist",'class':"custom"}).sortable(),
268                 onLoad:function(self){
269                         $('#toggleList').on('click',function(){ 
270                                 self.playlistContainer.toggleClass('deploy');
271                         });
272                         $('#emptyList').on('click',function(){ 
273                                 self._reset();
274                         });
275
276                         if(self.isActive){
277                                 self.playlistContainer.scrollTo(self.isActive, 800 );
278                                 self.isActive.find('audio').attr('preload',"preload")
279                         }
280                         self.controlButtons['playpause'].addClass('resymbol');
281                 },
282                 onPlay:function(self){
283                         $('#DirectStreamPanik')[0].pause();
284                         self.playlistContainer.scrollTo(self.isActive, 800 );
285                         if (typeof (_paq) == 'object') {
286                                 _paq.push(['trackGoal', 4]);
287                         }
288                 },
289                 onAdd:function(self){
290                         //self.isLastAdd[0].scrollIntoView();
291                         self.isLastAdd.find('a').ajaxifyClick();
292                         self.playlistContainer.scrollTo(self.isLastAdd, 800).delay(1000).scrollTo(self.isActive, 800 ).clearQueue();
293
294                         if (typeof (_paq) == 'object') {
295                                 _paq.push(['trackGoal', 3]);
296                         }
297                 },
298                 onUpdate:function(self){
299                         //doLog(JSON.stringify(self.playlist, null, '\t'));     
300                         if(self.playlist.length >= 1){
301                                 self.element.show();
302                                 $('#Player').addClass('withPlaylist').removeClass('withoutPlaylist');
303                         }else{
304                                 self.element.hide();
305                                 $('#Player').removeClass('withPlaylist').addClass('withoutPlaylist');
306                         }
307                 }
308         });
309
310         init = function() {
311                 $("#All a, #All area").removeClass('loading');
312                 $("#All a, #All area").ajaxifyClick();
313                 $("#search-form").unbind('submit').on('submit', function(event) {
314                         event.preventDefault();
315                         $(this).addClass('loading');
316                         loadPage($(this).attr('action') + '?' + $(this).serialize());
317                 });
318                 $(".tabs").each(function() {
319                         var self = $(this);
320                         var about= $($(this).attr("data-tab-about"));
321                         var current = $(this).find("[data-tab].active")[0];
322                         var dftShowSelector = current?".active":":first";
323                         var activeTab = $(this).find("[data-tab]"+dftShowSelector+"").addClass("active");
324                         $(this).find("[data-tab]").each(function() {
325                             $(this).on('click load',function (e) {  
326                                 e.preventDefault();
327                                 self.find(".active").removeClass("active");  
328                                 $(this).addClass("active");  
329                                 about.find("[data-tabbed]").hide();  
330                                 $($(this).attr("data-tab")).fadeIn();  
331                 
332                             });  
333                         });  
334                         activeTab.trigger('load');
335                 });
336                 $('[data-player-action]').on('click',function(){
337                         var audio = $('#'+$(this).attr('data-player-audio'));
338                         if($(this).attr('data-player-action') == "registerAudio"){
339                                 $localList.playlist("registerAudio",audio,doLog(audio.attr('title')+' has been added to your playlist.','ok'));
340                         }else if($(this).attr('data-player-action') == "playAudio"){
341                                 $localList.playlist("registerAudio",audio,doLog(audio.attr('title')+' will play soon.','ok'));
342                                 $localList.playlist("playLast");
343                         }else{
344                                 $localList.playlist($(this).attr('data-player-action'));
345                         }
346                 });
347                 $('[data-player-control]').each(function(){
348                         var audio = $('#'+$(this).attr('data-player-audio'));
349                         $localList.playlist("bindControl",$(this).attr('data-player-control'),audio,$(this));
350                 });
351
352                 $('[data-highlight]').on('check',function(){
353                         $($(this).attr('data-about')).find($(this).attr('data-highlight')).addClass('highlighted').removeClass('normal');
354                 }).on('uncheck',function(){
355                         $($(this).attr('data-about')).find($(this).attr('data-highlight')).removeClass('highlighted').addClass('normal');
356                 }).on('click',function(){
357                         $(this).toggleClass('icon-check icon-check-empty');
358                         if($(this).hasClass('icon-check')){$(this).trigger('check');
359                         }else{  $(this).trigger('uncheck');}
360                 });
361                 $('[data-highlight].icon-check-empty').each(function(){
362                         $(this).trigger('uncheck');
363                 });
364                 $('[data-toggle]').on('check',function(){
365                         /* make sure all other unchecked items are hidden */
366                         $('[data-toggle].icon-check-empty').each(function() {
367                                 $($(this).attr('data-about')).find($(this).attr('data-toggle')).hide();
368                         });
369                         $($(this).attr('data-about')).find($(this).attr('data-toggle')).show();
370                 }).on('uncheck',function(){
371                         $($(this).attr('data-about')).find($(this).attr('data-toggle')).hide();
372                         if ($('[data-toggle].icon-check').length == 0) {
373                                 /* special case the situation where all toggles
374                                  * are unchecked, as we want that to mean
375                                  * "everything", not "nothing".
376                                  */
377                                 $('[data-toggle].icon-check-empty').each(function() {
378                                         $($(this).attr('data-about')).find($(this).attr('data-toggle')).show();
379                                 });
380                         }
381                 }).on('click',function(){
382                         $(this).toggleClass('icon-check icon-check-empty');
383                         if($(this).hasClass('icon-check')){$(this).trigger('check');
384                         }else{  $(this).trigger('uncheck');}
385                 });
386                 $('[data-toggle].icon-check-empty').each(function(){
387                         $(this).trigger('uncheck');
388                 });
389
390                 initial_enabled_toggles = {};
391                 if (typeof(urlParams.q) == 'string') {
392                         urlParams.q.split('|').forEach(function(a) { initial_enabled_toggles[a] = 1; })
393                 }
394                 $('[data-toggle]').each(function() {
395                         if ($(this).data('toggle').substring(1) in initial_enabled_toggles) {
396                                 $(this).trigger('click');
397                         }
398                 });
399
400                 if ($('input#id_q').val() == '') {
401                         $('input#id_q').focus();
402                 }
403
404                 $('#ticker li:not(:first)');
405                 if (ticker_interval) clearInterval(ticker_interval);
406                 function tick(){
407                     $('#ticker li:first').animate({'opacity':0}, 200, function () {
408                         $(this).appendTo($('#ticker')).css('opacity', 1);
409                     });
410                 }
411                 $("#roller button").on('click',function(e){
412                     clearInterval(ticker_interval);
413                     e.preventDefault();
414                     $($(this).attr('data-about')).prependTo('#ticker');
415                     return false;
416                 });
417                 ticker_interval = setInterval(function(){tick();  }, 20000);/**/
418
419                 function navsearch_click(event) {
420                         event.preventDefault();
421                         var query = $('#nav-search input').val();
422                         var form = $('#nav-search form');
423                         var href = '';
424                         if (query == '') {
425                                 href = $(form).attr('action');
426                         } else {
427                                 href = $(form).attr('action') + '?' + $(form).serialize();
428                         }
429                         if (event.which == 2) {
430                                 window.open(href, '_blank');
431                         } else {
432                                 $(this).addClass('loading');
433                                 loadPage(href);
434                         }
435                         return false;
436                 }
437                 $('#nav-search a').unbind('click').on('click', navsearch_click);
438                 $('#nav-search form').unbind('submit').on('submit', navsearch_click);
439
440                 $('[data-toggle-img]').bind('click', function() {
441                         var src = $(this).data('toggle-img');
442                         $(this).data('toggle-img', $(this).attr('src'));
443                         $(this).attr('src', src);
444                         $(this).toggleClass('right marged');
445                 });
446
447                 if (document.cookie.indexOf('panikdb=on') != -1) {
448                         panikdb_path = null;
449                         if (window.location.pathname.indexOf('/emissions/') == 0) {
450                                 panikdb_path = window.location.pathname;
451                         } else if (window.location.pathname.indexOf('/news/') == 0) {
452                                 panikdb_path = '/emissions' + window.location.pathname;
453                         }
454                         if (panikdb_path) {
455                                 $('<a id="panikdb" href="http://panikdb.radiopanik.org' + panikdb_path + '">Voir dans PanikDB</a>').appendTo($main);
456                         }
457                 }
458         }
459         init();
460
461         if (! document.createElement('audio').canPlayType('audio/ogg') &&
462                 document.createElement('audio').canPlayType('audio/aac') ) {
463                 $('#ogg-m3u').hide().removeClass('resymbol');
464                 $('#aac-m3u').addClass('resymbol').show();
465         }
466
467         var konami = new Konami('/party');
468 });