]> git.0d.be Git - panikweb.git/blob - panikweb_templates/static/js/specifics.js
Naima + Simon Session... big refactoring (WIP)
[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                 window.onpopstate();
59
60                 new_menu = $($.parseHTML(html)).find('#metaNav>*');
61                 $metaNav.empty().append(new_menu);
62
63                 var newTitle = html?html.match(/<title>(.*?)<\/title>/):'';
64                 if(newTitle){document.title = newTitle[1].trim().decodeHTML();}
65
66                 /*
67                 Quite UGLY but needed for styling the whole body with ID
68                 Feel free to correct and find a better way
69                 According to this link the probles is that $(html).filter('body').Attr('id') will not work!
70                 http://www.devnetwork.net/viewtopic.php?f=13&t=117065
71                 */
72                 if(sectionName = $(html).find('[data-section]').attr('data-section')){
73                         $('body').attr('id',sectionName);
74                 }else{
75                         var bodyID = html.match(/<body id="(.*?)">/);   
76                         if(bodyID){$('body').attr('id',bodyID[1].trim());}      
77                 }
78                 $("#Changing").css({'min-height':$(window).height()});
79                 $.scrollTo('#Changing',1000,{offset:-$('#metaNav').height()+2});
80                 init();
81
82                 if (typeof (Piwik) == 'object') {
83                         piwikTracker = Piwik.getAsyncTracker();
84                         if (typeof (piwikTracker.trackPageView) == 'function') {
85                                 piwikTracker.setDocumentTitle(document.title);
86                                 piwikTracker.setCustomUrl(window.location.href);
87                                 piwikTracker.trackPageView();
88                         }
89                 }
90
91         };
92
93         function afterLoadError(xhr, text, error) {
94                 afterLoad(xhr.responseText, 'error', xhr);
95         };
96
97         $(window).on("popstate", function(e) {
98                 if (e.originalEvent.state !== null) {loadPage(location.href);}
99         });
100
101         loadPage = function(href) {
102                 history.pushState({}, '', href);
103                 if (loadPage_request !== null) {
104                         loadPage_request.abort();
105                 }
106                 loadPage_request = $.ajax({
107                         url: href,
108                         success: afterLoad,
109                         error: afterLoadError,
110                         dataType: 'html'});
111         };
112         $.fn.ajaxifyClick = function(params) {
113                 this.each(function() {
114                         $(this).unbind('click');
115                         $(this).bind('click',function(e){
116                                 var href = $(this).attr("href");
117                                 if (e.which == 2) {
118                                         window.open(href, '_blank');
119                                         return false;
120                                 }
121                                 $(this).addClass('loading');
122                                 /* this checks the link points to a local document, be
123                                  * it because it's just a path, or because the server
124                                  * part points to the same domain */
125                                 if (!href) {
126                                         doLog('No href attributes, unable to load content','error');
127                                         $("#All a, #All area").removeClass('loading');
128                                         return false;
129                                 }else if (!$(this).attr('target') && (
130                                                 href.indexOf(document.domain) > -1 ||href.indexOf(':') === -1 || href.indexOf(':') > 5
131                                         )) {
132                                         loadPage(href);
133                                         return false;
134                                 }else{
135                                         $(this).attr('target','_blanck');
136                                         $("#All a, #All area").removeClass('loading');
137                                         return true;
138                                 }
139                         });
140                 });
141         };
142         /****************************************************/
143         /**** AUDIOPLAYER ****/
144         /****************************************************/
145
146         var timer = null, 
147         interval = 5000;
148         /*
149         //TODO: mini icon version for player, (playpause only)
150         $('#togglePlayer').on('click',function(e) {
151                 e.preventDefault();
152                 if($(this).is('.icon-double-angle-left')){
153                         $("#player").fadeOut('fast',function(){
154                                 $("#player-container").toggleClass('minimized');                        
155                                 $('#togglePlayer').toggleClass('icon-double-angle-left icon-double-angle-right');
156                         });                     
157                 }else{
158                         $("#player").fadeIn('fast',function(){
159                                 $("#player-container").toggleClass('minimized');                        
160                                 $('#togglePlayer').toggleClass('icon-double-angle-left icon-double-angle-right');
161                         });     
162                 }
163                 return false;
164         });
165         */
166         $('#WhatsOnAir').on('load',function(){
167                 var WhatsOnAir = $(this);
168                 $.getJSON('/onair.json', function(onair) {
169                         WhatsOnAir.fadeOut();
170                         if(onair.data.episode || onair.data.emission){
171                                 var onairContainer = $('<span>');
172                                 if(onair.data.emission){
173                                         $('<a>',{href:onair.data.emission.url,html:onair.data.emission.title}).appendTo(onairContainer).ajaxifyClick();
174                                 }
175                                 if(onair.data.episode){
176                                         $('<span> - </span>').appendTo(onairContainer);
177                                         $('<a>',{href:onair.data.episode.url,html:onair.data.episode.title}).appendTo(onairContainer).ajaxifyClick();
178                                 }
179                                 WhatsOnAir.empty().append(onairContainer);
180                         } else if (onair.data.nonstop) {
181                                 result = onair.data.nonstop.title;
182                                 WhatsOnAir.html('<span>' + result + '</span>');
183                         }
184                         else{WhatsOnAir.html('<span>Unknown (Probably Non-Stop)</span>');}
185                         WhatsOnAir.fadeIn();
186                 });
187         }).trigger('load');
188         $('#RefreshWhatsOnAir').on('activate',function(e){
189                 $(this).addClass('spinning');
190                 $('#WhatsOnAir').addClass('active');
191                 $('#WhatsOnAir').trigger('load');
192                 timer = setInterval( "$('#WhatsOnAir').trigger('load');", interval);
193         }).on('deactivate',function(e){
194                 $(this).removeClass('spinning');
195                 $('#WhatsOnAir').removeClass('active');
196                 clearInterval(timer);
197         }).on('click',function(e){
198                 $(this).toggleClass('spinning');
199                 if($(this).is('.spinning')){
200                         $(this).trigger('activate');                                            
201                 }else{$(this).trigger('deactivate');}
202                 return false;
203         });
204         $("#DirectStreamPanikControler").on('click',function(e) {
205                 e.preventDefault();
206                 var stream = $('#DirectStreamPanik').get(0);
207                 if (stream.paused == false){
208                         stream.pause();
209                 }else{
210                         stream.play();
211                 }
212                 return false;
213         });
214         $('#DirectStreamPanik').on('play',function(){
215                 $('audio:not(#DirectStreamPanik)').each(function(){this.pause();});
216                 $('#streamSymbol').removeClass('icon-volume-up').addClass('icon-pause');
217                 $('#RefreshWhatsOnAir').trigger('activate');
218         }).on('pause',function(){
219                 //$('audio:not(#DirectStreamPanik)').each(function(){this.pause();});
220                 $('#streamSymbol').addClass('icon-volume-up').removeClass('icon-pause');
221                 $('#RefreshWhatsOnAir').trigger('deactivate');
222         });
223         if($('#player-container').offset()){
224                 var topPosition = 0;
225                 topPosition = $('#player-container').offset().top;
226                 $(window).bind('scroll load',function (event) {
227                         //$('#player-container').removeClass('fixed');
228                         var y = $(this).scrollTop() + $('#metaNav').height() - $('#Player').height() + 10;
229                         if (topPosition!== 0 && y >= topPosition) {
230                                 $('#Player').css({'min-height':$('#Player').height()});
231                                 $('#player-container').addClass('fixed').removeClass('normal');
232                         } else {
233                                 $('#Player').css({'min-height':'auto'});        
234                                 $('#player-container').removeClass('fixed').addClass('normal');
235                         }
236                 });
237         }
238
239         var $localList = $('#localList').playlist({
240                 controlContainer: $('<div>',{class:"playListControls"}).sortable(),
241                 playlistContainer: $('<ol>',{id:"myPlaylist",class:"custom"}).sortable(),
242                 onLoad:function(self){
243                         $('#toggleList').on('click',function(){ 
244                                 self.playlistContainer.toggleClass('deploy');
245                         });
246                         $('#emptyList').on('click',function(){ 
247                                 self._reset();
248                         });
249
250                         if(self.isActive){
251                                 self.playlistContainer.scrollTo(self.isActive, 800 );
252                                 self.isActive.find('audio').attr('preload',"preload")
253                         }
254                         self.controlButtons['playpause'].addClass('resymbol');
255                 },
256                 onPlay:function(self){
257                         $('#DirectStreamPanik')[0].pause();
258                         self.playlistContainer.scrollTo(self.isActive, 800 );
259                 },
260                 onAdd:function(self){
261                         //self.isLastAdd[0].scrollIntoView();
262                         self.isLastAdd.find('a').ajaxifyClick();
263                         self.playlistContainer.scrollTo(self.isLastAdd, 800).delay(1000).scrollTo(self.isActive, 800 ).clearQueue();
264
265                 },
266                 onUpdate:function(self){
267                         //doLog(JSON.stringify(self.playlist, null, '\t'));     
268                         if(self.playlist.length >= 1){
269                                 self.element.show();
270                                 $('#Player').addClass('withPlaylist').removeClass('withoutPlaylist');
271                         }else{
272                                 self.element.hide();
273                                 $('#Player').removeClass('withPlaylist').addClass('withoutPlaylist');
274                         }
275                 }
276         });
277
278         init = function() {
279                 $("#All a, #All area").removeClass('loading');
280                 $("#All a, #All area").ajaxifyClick();
281                 $("#search-form").unbind('submit').on('submit', function(event) {
282                         event.preventDefault();
283                         $(this).addClass('loading');
284                         loadPage($(this).attr('action') + '/?' + $(this).serialize());
285                 });
286                 $(".tabs").each(function() {
287                         var self = $(this);
288                         var about= $($(this).attr("data-tab-about"));
289                         var current = $(this).find("[data-tab].active")[0];
290                         var dftShowSelector = current?".active":":first";
291                         var activeTab = $(this).find("[data-tab]"+dftShowSelector+"").addClass("active");
292                         $(this).find("[data-tab]").each(function() {
293                             $(this).on('click load',function (e) {  
294                                 e.preventDefault();
295                                 self.find(".active").removeClass("active");  
296                                 $(this).addClass("active");  
297                                 about.find("[data-tabbed]").hide();  
298                                 $($(this).attr("data-tab")).fadeIn();  
299                 
300                             });  
301                         });  
302                         activeTab.trigger('load');
303                 });
304                 $('[data-player-action]').on('click',function(){
305                         var audio = $('#'+$(this).attr('data-player-audio'));
306                         if($(this).attr('data-player-action') == "registerAudio"){
307                                 $localList.playlist("registerAudio",audio,doLog(audio.attr('title')+' has been added to your playlist.','ok'));
308                         }else if($(this).attr('data-player-action') == "playAudio"){
309                                 $localList.playlist("registerAudio",audio,doLog(audio.attr('title')+' will play soon.','ok'));
310                                 $localList.playlist("playLast");
311                         }else{
312                                 $localList.playlist($(this).attr('data-player-action'));
313                         }
314                 });
315                 $('[data-player-control]').each(function(){
316                         var audio = $('#'+$(this).attr('data-player-audio'));
317                         $localList.playlist("bindControl",$(this).attr('data-player-control'),audio,$(this));
318                 });
319
320                 $('[data-highlight]').on('check',function(){
321                         $($(this).attr('data-about')).find($(this).attr('data-highlight')).addClass('highlighted').removeClass('normal');
322                 }).on('uncheck',function(){
323                         $($(this).attr('data-about')).find($(this).attr('data-highlight')).removeClass('highlighted').addClass('normal');
324                 }).on('click',function(){
325                         $(this).toggleClass('icon-check icon-check-empty');
326                         if($(this).hasClass('icon-check')){$(this).trigger('check');
327                         }else{  $(this).trigger('uncheck');}
328                 });
329                 $('[data-highlight].icon-check-empty').each(function(){
330                         $(this).trigger('uncheck');
331                 });
332                 $('[data-toggle]').on('check',function(){
333                         /* make sure all other unchecked items are hidden */
334                         $('[data-toggle].icon-check-empty').each(function() {
335                                 $($(this).attr('data-about')).find($(this).attr('data-toggle')).hide();
336                         });
337                         $($(this).attr('data-about')).find($(this).attr('data-toggle')).show();
338                 }).on('uncheck',function(){
339                         $($(this).attr('data-about')).find($(this).attr('data-toggle')).hide();
340                         if ($('[data-toggle].icon-check').length == 0) {
341                                 /* special case the situation where all toggles
342                                  * are unchecked, as we want that to mean
343                                  * "everything", not "nothing".
344                                  */
345                                 $('[data-toggle].icon-check-empty').each(function() {
346                                         $($(this).attr('data-about')).find($(this).attr('data-toggle')).show();
347                                 });
348                         }
349                 }).on('click',function(){
350                         $(this).toggleClass('icon-check icon-check-empty');
351                         if($(this).hasClass('icon-check')){$(this).trigger('check');
352                         }else{  $(this).trigger('uncheck');}
353                 });
354                 $('[data-toggle].icon-check-empty').each(function(){
355                         $(this).trigger('uncheck');
356                 });
357
358                 initial_enabled_toggles = {};
359                 if (typeof(urlParams.q) == 'string') {
360                         urlParams.q.split('|').forEach(function(a) { initial_enabled_toggles[a] = 1; })
361                 }
362                 $('[data-toggle]').each(function() {
363                         if ($(this).data('toggle').substring(1) in initial_enabled_toggles) {
364                                 $(this).trigger('click');
365                         }
366                 });
367
368                 if ($('input#id_q').val() == '') {
369                         $('input#id_q').focus();
370                 }
371         }
372         init();
373 });