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