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