improve Mediaplayer control a little bit (you get responses about
[enigma2-plugins.git] / webinterface / src / web-data / tools.js
1 //$Header$
2
3 // replace ' with \' for in-html javascript
4 String.prototype.esc = function(){ return this.valueOf().gsub("'", "\\'"); };
5
6 var templates = {};
7 var loadedChannellist = {};
8
9 var epgListData = {};
10 var signalPanelData = {};
11
12 var mediaPlayerStarted = false; 
13 var popUpBlockerHinted = false;
14
15 var settings = null;
16 var parentControlList = null;
17
18 var requestcounter = 0;
19
20 var debugWin = '';
21 var signalWin = '';
22 var webRemoteWin = '';
23 var EPGListWin = '';
24
25 var currentBouquet = bouquetsTv;
26
27 var updateBouquetItemsPoller = '';
28 var updateCurrentPoller = '';
29 var signalPanelUpdatePoller = '';
30
31 var hideNotifierTimeout = '';
32
33 var isActive = {};
34 isActive.getCurrent = false;
35
36 var currentLocation = "/hdd/movie";
37 var locationsList = [];
38 var tagsList = [];
39
40 var boxtype = "";
41
42 function startUpdateCurrentPoller(){
43         clearInterval(updateCurrentPoller);
44         updateCurrentPoller = setInterval(updateItems, userprefs.data.updateCurrentInterval);
45 }
46
47 function stopUpdateCurrentPoller(){
48         clearInterval(updateCurrentPoller);
49 }
50
51 function getXML(request){
52         var xmlDoc = "";
53
54         if(window.ActiveXObject){ // we're on IE
55                 xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
56                 xmlDoc.async="false";
57                 xmlDoc.loadXML(request.responseText);
58         } else { //we're not on IE
59                 if (!window.google || !google.gears){
60                         xmlDoc = request.responseXML;
61                 } else { //no responseXML on gears
62                         xmlDoc = (new DOMParser()).parseFromString(request.responseText, "text/xml");
63                 }
64         }
65
66         return xmlDoc;
67 }
68 /*
69 * Set boxtype Variable for being able of determining model specific stuff correctly (like WebRemote)
70 */
71 function incomingDeviceInfoBoxtype(request){
72         debug("[incomingAboutBoxtype] returned");
73         boxtype = getXML(request).getElementsByTagName("e2devicename").item(0).firstChild.data;
74
75         debug("[incomingAboutBoxtype] Boxtype: " + boxtype);
76 }
77
78
79 function getBoxtype(){
80         doRequest(URL.deviceinfo, incomingDeviceInfoBoxtype, false);    
81 }
82
83 function toggleStandby(){
84         sendPowerState(0);
85 }
86
87 function incomingPowerState(request){
88         var standby = getXML(request).getElementsByTagName("e2instandby").item(0).firstChild.data;
89         
90         var signal = $('openSignalPanel');
91         var signalImg = $('openSignalPanelImg');
92         
93         if(standby.strip() == "false"){
94                 signal.stopObserving('click', openSignalPanel);
95                 signal.observe('click', openSignalPanel);
96                 
97                 signalImg.src = "/web-data/img/signal.png";
98                 signalImg.title = "Show Signal Panel";
99                 
100         } else {
101                 signal.stopObserving('click', openSignalPanel);         
102                 
103                 signalImg.src = "/web-data/img/signal_off.png";
104                 signalImg.title = "Please disable standby first";
105         }
106 }
107
108 function getPowerState(){
109         doRequest(URL.powerstate, incomingPowerState);  
110 }
111
112 function set(element, value){
113         element = parent.$(element);
114         if (element){
115                 element.update(value);
116         }
117 }
118
119 function hideNotifier(){
120         $('notification').fade({duration : 0.5 });
121 }
122
123 function notify(text, state){
124         notif = $('notification');
125
126         if(notif !== null){
127                 //clear possibly existing hideNotifier timeout of a previous notfication
128                 clearTimeout(hideNotifierTimeout);
129                 if(state === false){
130                         notif.style.background = "#C00";
131                 } else {
132                         notif.style.background = "#85C247";
133                 }                               
134
135                 set('notification', "<div>"+text+"</div>");
136                 notif.appear({duration : 0.5, to: 0.9 });
137                 hideNotifierTimeout = setTimeout(hideNotifier, 10000);
138         }
139 }
140
141
142 function simpleResultHandler(simpleResult){
143         notify(simpleResult.getStateText(), simpleResult.getState());
144 }
145
146
147 function startUpdateBouquetItemsPoller(){
148         debug("[startUpdateBouquetItemsPoller] called");
149         clearInterval(updateBouquetItemsPoller);
150         updateBouquetItemsPoller = setInterval(updateItemsLazy, userprefs.data.updateBouquetInterval);
151 }
152
153
154 function stopUpdateBouquetItemsPoller(){
155         debug("[stopUpdateBouquetItemsPoller] called");
156         clearInterval(updateBouquetItemsPoller);
157 }
158
159
160 //General Helpers
161 function parseNr(num) {
162         if(isNaN(num)){
163                 return 0;
164         } else {
165                 return parseInt(num);
166         }
167 }
168
169
170 function dec2hex(nr, len){
171
172         var hex = parseInt(nr, 10).toString(16).toUpperCase();
173         if(len > 0){
174                 try{
175                         while(hex.length < len){
176                                 hex = "0"+hex;
177                         }
178                 } 
179                 catch(e){
180                         //something went wrong, return -1
181                         hex = -1;
182                 }
183         }
184         
185         hex = '0x' + hex;
186         
187         return hex;
188 }
189
190
191 function quotes2html(txt) {
192         if(typeof(txt) != "undefined"){
193                 return txt.escapeHTML().replace('\n', '<br>');
194         } else {
195                 return "";
196         }
197 }
198
199 function addLeadingZero(nr){
200         if(nr < 10){
201                 return '0' + nr;
202         }
203         return nr;
204 }
205
206 function dateToString(date){
207
208         var dateString = "";
209
210         dateString += date.getFullYear();
211         dateString += "-" + addLeadingZero(date.getMonth()+1);
212         dateString += "-" + addLeadingZero(date.getDate());
213         dateString += " " + addLeadingZero(date.getHours());
214         dateString += ":" + addLeadingZero(date.getMinutes());
215
216         return dateString;
217 }
218
219
220 function showhide(id){
221         var s = $(id).style;
222         s.display = (s.display!="none")? "none":"";
223 }
224
225
226 function show(id){
227         try{
228                 $(id).style.display = "";
229         } catch(e) {
230                 debug("[show] Could not show element with id: " + id);
231         }
232 }
233
234
235 function hide(id){
236         try{
237                 $(id).style.display = "none";
238         } catch(e) {
239                 debug("[hide] Could not hide element with id: " + id);
240         }
241 }
242
243
244 /*
245 * Sets the Loading Notification to the given HTML Element
246 * @param targetElement - The element the Ajax-Loader should be set in
247 */
248 function setAjaxLoad(targetElement){
249         $(targetElement).update( getAjaxLoad() );
250 }
251
252
253 //Ajax Request Helpers
254 //requestindikator
255
256 function requestIndicatorUpdate(){
257         /*debug(requestcounter+" open requests");
258         if(requestcounter>=1){
259                 $('RequestIndicator').style.display = "inline";
260         }else{
261                 $('RequestIndicator').style.display = "none";
262         }*/
263 }
264
265 function requestStarted(){
266         requestcounter +=1;
267         requestIndicatorUpdate();
268 }
269
270 function requestFinished(){
271         requestcounter -= 1;
272         requestIndicatorUpdate();
273 }
274
275 //Popup And Messagebox Helpers
276 function messageBox(m){
277         alert(m);
278 }
279
280
281 function popUpBlockerHint(){
282         if(!popUpBlockerHinted){
283                 popUpBlockerHinted = true;
284                 messageBox("Please disable your Popup-Blocker for enigma2 WebControl to work flawlessly!");
285
286         }
287 }
288
289 function setWindowContent(window, html){
290         window.document.write(html);
291         window.document.close();
292 }
293
294 function openPopup(title, html, width, height, x, y){
295         try {
296                 var popup = window.open('about:blank',title,'scrollbars=yes, width='+width+',height='+height);          
297                 setWindowContent(popup, html);
298                 return popup;
299         } catch(e){
300                 popUpBlockerHint();
301                 return "";
302         }
303 }
304
305 function openPopupPage(title, uri, width, height, x, y){
306         try {
307                 var popup = window.open(uri,title,'scrollbars=yes, width='+width+',height='+height);
308                 return popup;
309         } catch(e){
310                 popUpBlockerHint();
311                 return "";
312         }
313 }
314
315 function debug(text){
316         var DBG = userprefs.data.debug || false;
317         
318         if(DBG){
319                 try{
320                         if(!debugWin.closed && debugWin.location){
321                                 var inner = debugWin.document.getElementById('debugContent').innerHTML;
322                                 debugWin.document.getElementById('debugContent').innerHTML = new Date().toLocaleString() + ": "+text+"<br>" + inner;
323                         } else {                        
324                                 openDebug();
325                                 
326                                 setTimeout(     function(){
327                                                                         var inner = debugWin.document.getElementById('debugContent').innerHTML;
328                                                                         debugWin.document.getElementById('debugContent').innerHTML = new Date().toLocaleString() + ": "+text+"<br>" + inner;
329                                                                 }, 
330                                                                 1000
331                                                         );
332                         }
333                 } catch (Exception) {}
334         }
335 }
336
337 function saveSettings(){
338         userprefs.load();
339         
340         var debug = $('enableDebug').checked;
341         var changed = false;
342         if(typeof(debug) != "undefined"){
343                 if( userprefs.data.debug != debug ){
344                         userprefs.data.debug = debug;
345                         changed = true;
346         
347                         if(debug){
348                                 openDebug();
349                         }
350                 }               
351         }
352         
353         var updateCurrentInterval = parseNr( $F('updateCurrentInterval') ) * 1000;
354         if( updateCurrentInterval < 10000){
355                 updateCurrentInterval = 120000;
356         }
357         
358         if( userprefs.data.updateCurrentInterval != updateCurrentInterval){
359                 userprefs.data.updateCurrentInterval = updateCurrentInterval;
360                 
361                 changed = true;
362                 startUpdateCurrentPoller();
363         }
364         
365         var updateBouquetInterval = parseNr( $F('updateBouquetInterval') )  * 1000;
366         if( updateBouquetInterval < 60000){
367                 updateBouquetInterval = 300000;
368         }
369         
370         if( userprefs.data.updateBouquetInterval != updateBouquetInterval){
371                 userprefs.data.updateBouquetInterval = updateBouquetInterval;
372                 
373                 changed = true;
374                 startUpdateBouquetItemsPoller();
375         }
376         
377         if(changed){
378                 userprefs.save();
379         }
380 }
381
382 //Template Helpers
383 function saveTpl(request, tplName){
384         debug("[saveTpl] saving template: " + tplName);
385         templates[tplName] = request.responseText;
386 }
387
388
389 function renderTpl(tpl, data, domElement) {     
390         var result = tpl.process(data);
391
392         try{
393                 $(domElement).update( result );
394         }catch(ex){
395                 //              debug("[renderTpl] exception: " + ex);
396         }
397 }
398
399
400 function fetchTpl(tplName, callback){
401         if(typeof(templates[tplName]) == "undefined") {
402                 var url = URL.tpl+tplName+".htm";
403                 
404                 doRequest(
405                                 url, 
406                                 function(transport){
407                                         saveTpl(transport, tplName);
408                                         if(typeof(callback) == 'function'){
409                                                 callback();
410                                         }
411                                 }
412                 );
413         } else {
414                 if(typeof(callback) == 'function'){
415                         callback();
416                 }
417         }
418 }
419
420 function incomingProcessTpl(request, data, domElement, callback){
421         if(request.readyState == 4){
422                 renderTpl(request.responseText, data, domElement);
423                 if(typeof(callback) == 'function') {
424                         callback();
425                 }
426         }
427 }
428
429 function processTpl(tplName, data, domElement, callback){
430         var url = URL.tpl+tplName+".htm";
431         
432         doRequest(url, 
433                         function(transport){
434                 incomingProcessTpl(transport, data, domElement, callback);
435         }
436         );
437 }
438
439 //Debugging Window
440
441
442 function openDebug(){
443         var uri = URL.tpl+'tplDebug.htm';
444         debugWin = openPopupPage("Debug", uri, 500, 300);
445 }
446
447 function requestFailed(transport){
448         var notifText = "Request failed for:  " + transport.request.url + "<br>Status: " + transport.status + " " + transport.statusText;
449         notify(notifText, false);
450 }
451
452 function doRequest(url, readyFunction){
453         requestStarted();
454         var request = '';
455         var parms = url.toQueryParams();
456         
457         // gears or not that's the question here
458         if (!window.google || !google.gears){ //no gears, how sad
459 //              debug("NO GEARS!!");            
460                 try{
461                         request = new Ajax.Request(url,
462                                         {
463                                                 asynchronous: true,
464                                                 method: 'POST',
465                                                 parameters: parms,
466                                                 onException: function(o,e){ throw(e); },
467                                                 onSuccess: function (transport, json) {                                         
468                                                         if(typeof(readyFunction) != "undefined"){
469                                                                 readyFunction(transport);
470                                                         }
471                                                 },
472                                                 onFailure: function(transport){
473                                                         requestFailed(transport);
474                                                 },
475                                                 onComplete: requestFinished 
476                                         });
477                 } catch(e) {}
478         } else { //we're on gears!
479                 try{
480                         request = google.gears.factory.create('beta.httprequest');
481                         request.open('GET', url);
482
483
484                         request.onreadystatechange = function(){                                
485                                 if(request.readyState == 4){
486                                         if(request.status == 200){
487                                                 if( typeof(readyFunction) != "undefined" ){
488                                                         readyFunction(request);
489                                                 }
490                                         } else {
491                                                 requestFailed(transport);
492                                         }
493                                 }
494                         };
495                         request.send();
496                 } catch(e) {}
497         }
498 }
499
500 //Parental Control
501 function incomingParentControl(request) {
502         if(request.readyState == 4){
503                 parentControlList = new ServiceList(getXML(request)).getArray();
504                 debug("[incomingParentControl] Got "+parentControlList.length + " services");
505         }
506 }
507
508 function getParentControl() {
509         doRequest(URL.parentcontrol, incomingParentControl, false);
510 }
511
512
513 function getParentControlByRef(txt) {
514         debug("[getParentControlByRef] ("+txt+")");
515         for(var i = 0; i < parentControlList.length; i++) {
516                 debug( "[getParentControlByRef] "+parentControlList[i].getClearServiceReference() );
517                 if(String(parentControlList[i].getClearServiceReference()) == String(txt)) {
518                         return parentControlList[i].getClearServiceReference();
519                 } 
520         }
521         return "";
522 }
523
524
525 //Settings
526 function getSettingByName(txt) {
527         debug("[getSettingByName] (" + txt + ")");
528         for(var i = 0; i < settings.length; i++) {
529                 debug("("+settings[i].getSettingName()+") (" +settings[i].getSettingValue()+")");
530                 if(String(settings[i].getSettingName()) == String(txt)) {
531                         return settings[i].getSettingValue().toLowerCase();
532                 } 
533         }
534         return "";
535 }
536
537 function parentPin(servicereference) {
538         debug("[parentPin] parentControlList");
539         servicereference = decodeURIComponent(servicereference);
540         if(parentControlList === null || String(getSettingByName("config.ParentalControl.configured")) != "true") {
541                 return true;
542         }
543         //debug("parentPin " + parentControlList.length);
544         if(getParentControlByRef(servicereference) == servicereference) {
545                 if(String(getSettingByName("config.ParentalControl.type.value")) == "whitelist") {
546                         debug("[parentPin] Channel in whitelist");
547                         return true;
548                 }
549         } else {
550                 debug("[parentPin] sRef differs ");
551                 return true;
552         }
553         debug("[parentPin] Asking for PIN");
554
555         var userInput = prompt('Parental Control is enabled!<br> Please enter the Parental Control PIN','PIN');
556         if (userInput !== '' && userInput !== null) {
557                 if(String(userInput) == String(getSettingByName("config.ParentalControl.servicepin.0")) ) {
558                         return true;
559                 } else {
560                         return parentPin(servicereference);
561                 }
562         } else {
563                 return false;
564         }
565 }
566
567
568 function incomingGetDreamboxSettings(request){
569         if(request.readyState == 4){
570                 settings = new Settings(getXML(request)).getArray();
571
572                 debug("[incomingGetDreamboxSettings] config.ParentalControl.configured="+ getSettingByName("config.ParentalControl.configured"));
573
574                 if(String(getSettingByName("config.ParentalControl.configured")) == "true") {
575                         getParentControl();
576                 }
577         }
578 }
579
580
581 function getDreamboxSettings(){
582         doRequest(URL.settings, incomingGetDreamboxSettings, false);
583 }
584
585
586 //Subservices
587 function incomingSubServiceRequest(request){
588         if(request.readyState == 4){
589                 var services = new ServiceList(getXML(request)).getArray();
590                 debug("[incomingSubServiceRequest] Got " + services.length + " SubServices");
591
592                 if(services.length > 1) {
593
594                         var first = services[0];
595
596                         // we already have the main service in our servicelist so we'll
597                         // start with the second element                        
598                         services.shift();
599                         
600                         var data = { subservices : services };
601                         
602
603                         var id = 'SUB'+first.servicereference;
604                         show('tr' + id);
605                         processTpl('tplSubServices', data, id);
606                 }
607         }
608 }
609
610
611 function getSubServices(bouquet) {
612         doRequest(URL.subservices, incomingSubServiceRequest, false);
613 }
614
615
616 function delayedGetSubservices(){
617         setTimeout(getSubServices, 5000);
618 }
619
620 //zap zap
621 function zap(servicereference){
622         doRequest("/web/zap?sRef=" + servicereference); 
623         setTimeout(updateItemsLazy, 7000); //reload epg and subservices
624         setTimeout(updateItems, 3000);
625 }
626
627 //SignalPanel
628
629 function updateSignalPanel(){   
630         var html = templates.tplSignalPanel.process(signalPanelData);
631
632         if (!signalWin.closed && signalWin.location) {
633                 setWindowContent(signalWin, html);
634         } else {
635                 clearInterval(signalPanelUpdatePoller);
636                 signalPanelUpdatePoller = '';
637         }
638 }
639
640 function incomingSignalPanel(request){
641         var namespace = {};
642
643         if (request.readyState == 4){
644                 var xml = getXML(request).getElementsByTagName("e2frontendstatus").item(0);
645                 namespace = {
646                                 snrdb : xml.getElementsByTagName('e2snrdb').item(0).firstChild.data,
647                                 snr : xml.getElementsByTagName('e2snr').item(0).firstChild.data,
648                                 ber : xml.getElementsByTagName('e2ber').item(0).firstChild.data,
649                                 acg : xml.getElementsByTagName('e2acg').item(0).firstChild.data
650                 };
651         }
652
653         signalPanelData = { signal : namespace };
654         fetchTpl('tplSignalPanel', updateSignalPanel);  
655 }
656
657 function reloadSignalPanel(){
658         doRequest(URL.signal, incomingSignalPanel, false);
659 }
660
661 function openSignalPanel(){
662         if (!(!signalWin.closed && signalWin.location)){
663                 signalWin = openPopup('SignalPanel', '', 220, 120);
664                 if(signalPanelUpdatePoller === ''){
665                         signalPanelUpdatePoller = setInterval(reloadSignalPanel, 5000);
666                 }
667         }
668         reloadSignalPanel();
669 }
670
671 //EPG functions
672
673
674 function showEpgList(){
675         var html = templates.tplEpgList.process(epgListData);
676
677         if (!EPGListWin.closed && EPGListWin.location) {
678                 setWindowContent(EPGListWin, html);
679         } else {
680                 EPGListWin = openPopup("EPG", html, 900, 500);
681         }
682 }
683
684 function incomingEPGrequest(request){
685         debug("[incomingEPGrequest] readyState" +request.readyState);           
686         if (request.readyState == 4){
687                 var EPGItems = new EPGList(getXML(request)).getArray();
688                 debug("[incomingEPGrequest] got "+EPGItems.length+" e2events");
689
690                 if( EPGItems.length > 0){
691                         epgListData = {epg : EPGItems};
692                         fetchTpl('tplEpgList', showEpgList);
693                 } else {
694                         messageBox('No Items found!', 'Sorry but I could not find any EPG Content containing your search value');
695                 }
696         }
697 }
698
699 function loadEPGBySearchString(string){
700         doRequest(URL.epgsearch+escape(string),incomingEPGrequest, false);
701 }
702
703 function loadEPGByServiceReference(servicereference){
704         doRequest(URL.epgservice+servicereference,incomingEPGrequest, false);
705 }
706
707 function buildServiceListEPGItem(epgevent, type){
708         var data = { epg : epgevent,
709                                  nownext: type
710                                 };
711
712         var id = type + epgevent.servicereference;
713
714         show('tr' + id);
715
716         if(typeof(templates.tplServiceListEPGItem) != "undefined"){
717                 renderTpl(templates.tplServiceListEPGItem, data, id, true);
718         } else {
719                 debug("[buildServiceListEPGItem] tplServiceListEPGItem N/A");
720         }
721 }
722
723 function incomingServiceEPGNowNext(request, type){
724         if(request.readyState == 4){
725                 var epgevents = getXML(request).getElementsByTagName("e2eventlist").item(0).getElementsByTagName("e2event");
726                 for (var c = 0; c < epgevents.length; c++){
727                         try{
728                                 var epgEvt = new EPGEvent(epgevents.item(c), c).toJSON();
729                         } catch (e){
730                                 debug("[incomingServiceEPGNowNext]" + e);
731                         }
732
733                         if (epgEvt.eventid != ''){
734                                 buildServiceListEPGItem(epgEvt, type);
735                         }
736                 }
737         }
738 }
739
740 function incomingServiceEPGNow(request){
741         incomingServiceEPGNowNext(request, 'NOW');
742 }
743
744 function incomingServiceEPGNext(request){
745         incomingServiceEPGNowNext(request, 'NEXT');
746 }
747
748 function loadServiceEPGNowNext(servicereference, next){
749         var url = URL.epgnow+servicereference;
750
751         if(typeof(next) == 'undefined'){
752                 doRequest(url, incomingServiceEPGNow, false);
753         } else {
754                 url = URL.epgnext+servicereference;
755                 doRequest(url, incomingServiceEPGNext, false);
756         }
757 }
758
759
760 function getBouquetEpg(){
761         loadServiceEPGNowNext(currentBouquet);
762         loadServiceEPGNowNext(currentBouquet, true);
763 }
764
765
766 function recordNowPopup(){
767         var result = confirm(   
768                         "OK: Record current event\n" +
769                         "Cancel: Start infinite recording"
770         );
771
772         if( result === true || result === false){
773                 recordNowDecision(result);
774         }
775 }
776
777
778 //+++++++++++++++++++++++++++++++++++++++++++++++++++++
779 //+++++++++++++++++++++++++++++++++++++++++++++++++++++
780 //++++ volume functions ++++
781 //+++++++++++++++++++++++++++++++++++++++++++++++++++++
782 //+++++++++++++++++++++++++++++++++++++++++++++++++++++
783 function handleVolumeRequest(request){
784         if (request.readyState == 4) {
785                 var b = getXML(request).getElementsByTagName("e2volume");
786                 var newvalue = b.item(0).getElementsByTagName('e2current').item(0).firstChild.data;
787                 var mute = b.item(0).getElementsByTagName('e2ismuted').item(0).firstChild.data;
788                 debug("[handleVolumeRequest] Volume " + newvalue + " | Mute: " + mute);
789
790                 for (var i = 1; i <= 10; i++)           {
791                         if ( (newvalue/10)>=i){
792                                 $("volume"+i).src = "/web-data/img/led_on.png";
793                         }else{
794                                 $("volume"+i).src = "/web-data/img/led_off.png";
795                         }
796                 }
797                 if (mute == "False"){
798                         $("speaker").src = "/web-data/img/speak_on.png";
799                 }else{
800                         $("speaker").src = "/web-data/img/speak_off.png";
801                 }
802         }       
803 }
804
805
806 function getVolume(){
807         doRequest(URL.getvolume, handleVolumeRequest, false);
808 }
809
810 function volumeSet(val){
811         doRequest(URL.setvolume+val, handleVolumeRequest, false);
812 }
813
814 function volumeUp(){
815         doRequest(URL.volumeup, handleVolumeRequest, false);
816 }
817
818 function volumeDown(){
819         doRequest(URL.volumedown, handleVolumeRequest, false);
820 }
821
822 function volumeMute(){
823         doRequest(URL.volumemute, handleVolumeRequest, false);
824 }
825
826 function initVolumePanel(){
827         getVolume(); 
828 }
829
830
831
832 //Channels and Bouquets
833
834 function incomingChannellist(request){
835         var serviceList = null;
836         if(typeof(loadedChannellist[currentBouquet]) != "undefined"){
837                 serviceList = loadedChannellist[currentBouquet];
838         } else if(request.readyState == 4) {
839                 serviceList = new ServiceList(getXML(request)).getArray();
840                 debug("[incomingChannellist] got "+serviceList.length+" Services");
841         }
842         if(serviceList !== null) {              
843                 var data = { services : serviceList };
844
845                 processTpl('tplServiceList', data, 'contentServices', getBouquetEpg);
846                 delayedGetSubservices();
847         } else {
848                 debug("[incomingChannellist] services is null");
849         }
850 }
851
852
853 function loadBouquet(servicereference, name){ 
854         debug("[loadBouquet] called");
855         setAjaxLoad('contentServices');
856         
857         currentBouquet = servicereference;
858
859         setContentHd(name);
860         
861         var input = new Element('input');
862         input.id = 'serviceSearch';
863         input.value = 'Search for service';
864         
865         $('contentHdExt').update(input);
866         
867         input.observe('focus', onServiceSearchFocus);
868         input.observe('keyup', serviceSearch);  
869
870         startUpdateBouquetItemsPoller();
871         doRequest(URL.getservices+servicereference, incomingChannellist, true);
872 }
873
874
875 function incomingBouquetListInitial(request){
876         if (request.readyState == 4) {
877                 var bouquetList = new ServiceList(getXML(request)).getArray();
878                 debug("[incomingBouquetListInitial] Got " + bouquetList.length + " TV Bouquets!");      
879         
880                 // loading first entry of TV Favorites as default for ServiceList
881                 incomingBouquetList(
882                                 request, 
883                                 function(){
884                                         loadBouquet(bouquetList[0].servicereference, bouquetList[0].servicename);;
885                                 }
886                         );
887         }
888 }
889
890
891 function incomingBouquetList(request, callback){
892         if (request.readyState == 4) {
893                 var bouquetList = new ServiceList(getXML(request)).getArray();
894                 debug("[incomingBouquetList] got " + bouquetList.length + " TV Bouquets!");     
895                 var data = { bouquets : bouquetList };
896                 
897                 if( $('contentBouquets') != "undefined" && $('contentBouquets') != null ){
898                         processTpl('tplBouquetList', data, 'contentBouquets');
899                         if(typeof(callback) == 'function')
900                                 callback();
901                 } else {
902                         processTpl(                                     
903                                         'tplBouquetsAndServices', 
904                                         null, 
905                                         'contentMain',
906                                         function(){
907                                                 processTpl('tplBouquetList', data, 'contentBouquets');
908                                                 if(typeof(callback) == 'function')
909                                                         callback();
910                                         }
911                         );
912                 }
913         }
914 }
915
916
917 function initChannelList(){
918         var url = URL.getservices+encodeURIComponent(bouquetsTv);
919         currentBouquet = bouquetsTv;
920
921         doRequest(url, incomingBouquetListInitial, true);
922 }
923
924
925
926 //Movies
927 function initMovieList(){
928         // get videodirs, last_videodir, and all tags
929         doRequest(URL.getcurrlocation, incomingMovieListCurrentLocation, false);
930 }
931
932 function incomingMovieListCurrentLocation(request){
933         if(request.readyState == 4){
934                 var result  = new SimpleXMLList(getXML(request), "e2location");
935                 currentLocation = result.getList()[0];
936                 debug("[incomingMovieListCurrentLocation].currentLocation" + currentLocation);
937                 doRequest(URL.getlocations, incomingMovieListLocations, false);
938         }
939 }
940
941 function incomingMovieListLocations(request){
942         if(request.readyState == 4){
943                 var result  = new SimpleXMLList(getXML(request), "e2location");
944                 locationsList = result.getList();
945
946                 if (locationsList.length === 0) {
947                         locationsList = ["/hdd/movie"];
948                 }
949                 doRequest(URL.gettags, incomingMovieListTags, false);
950         }
951 }
952
953 function incomingMovieListTags(request){
954         if(request.readyState == 4){
955                 var result  = new SimpleXMLList(getXML(request), "e2tag");
956                 tagsList = result.getList();
957         }
958 }
959
960 function createOptionListSimple(lst, selected) {
961         var namespace = Array();
962         var i = 0;
963         var found = false;
964
965         for (i = 0; i < lst.length; i++) {
966                 if (lst[i] == selected) {
967                         found = true;
968                 }
969         }
970
971         if (!found) {
972                 lst = [ selected ].concat(lst);
973         }
974
975         for (i = 0; i < lst.length; i++) {
976                 namespace[i] = {
977                                 'value': lst[i],
978                                 'txt': lst[i],
979                                 'selected': (lst[i] == selected ? "selected" : " ")};
980         }
981
982         return namespace;
983 }
984
985 function loadMovieNav(){
986         // fill in menus
987         var data = {
988                         dirname: createOptionListSimple(locationsList, currentLocation),
989                         tags: createOptionListSimple(tagsList, "")
990         };
991
992         processTpl('tplNavMovies', data, 'navContent');
993 }
994
995 function incomingMovieList(request){
996         if(request.readyState == 4){
997
998                 var movieList = new MovieList(getXML(request)).getArray();
999                 debug("[incomingMovieList] Got "+movieList.length+" movies");
1000
1001                 var data = { movies : movieList };
1002                 processTpl('tplMovieList', data, 'contentMain');
1003         }               
1004 }
1005
1006 function loadMovieList(loc, tag){
1007         if(typeof(loc) == 'undefined'){
1008                 loc = currentLocation;
1009         }
1010         if(typeof(tag) == 'undefined'){
1011                 tag = '';
1012         }
1013         debug("[loadMovieList] Loading movies in location '"+loc+"' with tag '"+tag+"'");
1014         doRequest(URL.movielist+"?dirname="+loc+"&tag="+tag, incomingMovieList, false);
1015 }
1016
1017
1018 function incomingDelMovieResult(request) {
1019         debug("[incomingDelMovieResult] called");
1020         if(request.readyState == 4){
1021                 var result = new SimpleXMLResult(getXML(request));
1022                 if(result.getState()){                  
1023                         loadMovieList();
1024                 }
1025                 simpleResultHandler(result);
1026         }               
1027 }
1028
1029
1030 function delMovie(sref ,servicename, title, description) {
1031         debug("[delMovie] File(" + unescape(sref) + "), servicename(" + servicename + ")," +
1032                         "title(" + unescape(title) + "), description(" + description + ")");
1033
1034         result = confirm( "Are you sure want to delete the Movie?\n" +
1035                         "Servicename: " + servicename + "\n" +
1036                         "Title: " + unescape(title) + "\n" + 
1037                         "Description: " + description + "\n");
1038
1039         if(result){
1040                 debug("[delMovie] ok confirm panel"); 
1041                 doRequest(URL.moviedelete+"?sRef="+unescape(sref), incomingDelMovieResult, false); 
1042                 return true;
1043         }
1044         else{
1045                 debug("[delMovie] cancel confirm panel");
1046                 return false;
1047         }
1048 }
1049
1050 //Send Messages and Receive the Answer
1051
1052
1053 function incomingMessageResult(request){
1054         if(request.readyState== 4){
1055                 var result = new SimpleXMLResult(getXML(request));
1056                 simpleResultHandler(result);
1057         }
1058 }
1059
1060 function getMessageAnswer() {
1061         doRequest(URL.messageanswer, incomingMessageResult, false);
1062 }
1063
1064 function sendMessage(messagetext, messagetype, messagetimeout){
1065         if(!messagetext){
1066                 messagetext = $('MessageSendFormText').value;
1067         }       
1068         if(!messagetimeout){
1069                 messagetimeout = $('MessageSendFormTimeout').value;
1070         }       
1071         if(!messagetype){
1072                 var index = $('MessageSendFormType').selectedIndex;
1073                 messagetype = $('MessageSendFormType').options[index].value;
1074         }       
1075         if(parseNr(messagetype) === 0){
1076                 doRequest(URL.message+'?text='+messagetext+'&type='+messagetype+'&timeout='+messagetimeout);
1077                 setTimeout(getMessageAnswer, parseNr(messagetimeout)*1000);
1078         } else {
1079                 doRequest(URL.message+'?text='+messagetext+'&type='+messagetype+'&timeout='+messagetimeout, incomingMessageResult, false);
1080         }
1081 }
1082
1083
1084 //Screenshots
1085 function getScreenShot(what) {
1086         debug("[getScreenShot] called");
1087
1088         var buffer = new Image();
1089         var downloadStart;
1090         var data = {};
1091
1092         buffer.onload = function () { 
1093                 debug("[getScreenShot] image assigned");
1094
1095                 data = { img : { src : buffer.src } };  
1096                 processTpl('tplGrab', data, 'contentMain');
1097
1098                 return true;
1099         };
1100
1101         buffer.onerror = function (meldung) { 
1102                 debug("[getScreenShot] Loading image failed"); 
1103                 return true;
1104         };
1105
1106         switch(what){
1107         case "o":
1108                 what = "&o=&n=";
1109                 break;
1110         case "v":
1111                 what = "&v=";
1112                 break;
1113         default:
1114                 what = "";
1115         break;
1116         }
1117
1118         downloadStart = new Date().getTime();
1119         buffer.src = '/grab?format=jpg&r=720&' + what + '&filename=/tmp/' + downloadStart;
1120 }
1121
1122 function getVideoShot() {
1123         getScreenShot("v");
1124 }
1125
1126 function getOsdShot(){
1127         getScreenShot("o");
1128 }
1129
1130 //RemoteControl Code
1131
1132 function incomingRemoteControlResult(request){
1133 //      if(request.readyState == 4){
1134 //              var b = getXML(request).getElementsByTagName("e2remotecontrol");
1135 //              var result = b.item(0).getElementsByTagName('e2result').item(0).firstChild.data;
1136 //              var resulttext = b.item(0).getElementsByTagName('e2resulttext').item(0).firstChild.data;
1137 //      }
1138 }
1139
1140 function openWebRemote(){
1141         var template = templates.tplWebRemoteOld;
1142
1143         if(boxtype == "dm8000"){
1144                 template = templates.tplWebRemote;
1145         }
1146
1147
1148         if (!webRemoteWin.closed && webRemoteWin.location) {
1149                 setWindowContent(webRemoteWin, template);
1150         } else {
1151                 webRemoteWin = openPopup('WebRemote', template, 250, 620);
1152         }
1153
1154 }
1155
1156
1157 function loadAndOpenWebRemote(){
1158         if(boxtype == "dm8000"){
1159                 fetchTpl('tplWebRemote', openWebRemote);
1160                 
1161         } else {
1162                 fetchTpl('tplWebRemoteOld', openWebRemote);
1163         }
1164 }
1165
1166
1167 function sendRemoteControlRequest(command){
1168         var long = webRemoteWin.document.getElementById('long');
1169         if(long.checked){
1170                 doRequest(URL.remotecontrol+'?command='+command+'&type=long', incomingRemoteControlResult, false);
1171                 long.checked = undefined;
1172         } else {
1173                 doRequest(URL.remotecontrol+'?command='+command, incomingRemoteControlResult, false);
1174         }
1175         
1176         if(webRemoteWin.document.getElementById('getScreen').checked) {
1177                 if(webRemoteWin.document.getElementById('getVideo').checked){
1178                         getScreenShot();
1179                 } else {
1180                         getScreenShot("o");
1181                 }
1182         }
1183 }
1184
1185
1186 // Array.insert( index, value ) - Insert value at index, without overwriting existing keys
1187 Array.prototype.insert = function( j, v ) {
1188         if( j>=0 ) {
1189                 var a = this.slice(), b = a.splice( j );
1190                 a[j] = v;
1191                 return a.concat( b );
1192         }
1193 };
1194
1195 //Array.splice() - Remove or replace several elements and return any deleted
1196 //elements
1197 if( typeof Array.prototype.splice==='undefined' ) {
1198         Array.prototype.splice = function( a, c ) {
1199                 var e = arguments, d = this.copy(), f = a, l = this.length;
1200
1201                 if( !c ) { 
1202                         c = l - a; 
1203                 }
1204
1205                 for( var i = 0; i < e.length - 2; i++ ) { 
1206                         this[a + i] = e[i + 2]; 
1207                 }
1208
1209
1210                 for( var j = a; j < l - c; j++ ) { 
1211                         this[j + e.length - 2] = d[j - c]; 
1212                 }
1213                 this.length -= c - e.length + 2;
1214
1215                 return d.slice( f, f + c );
1216         };
1217 }
1218
1219 function ifChecked(rObj) {
1220         if(rObj.checked) {
1221                 return rObj.value;
1222         } else {
1223                 return "";
1224         }
1225 }
1226
1227 //Device Info
1228 /*
1229  * Handles an incoming request for /web/deviceinfo Parses the Data, and calls
1230  * everything needed to render the Template using the parsed data and set the
1231  * result into contentMain @param request - the XHR
1232  */
1233 function incomingDeviceInfo(request) {
1234         if(request.readyState == 4){
1235                 debug("[incomingDeviceInfo] called");
1236                 var deviceInfo = new DeviceInfo(getXML(request));
1237
1238                 processTpl('tplDeviceInfo', deviceInfo, 'contentMain');
1239         }
1240 }
1241
1242
1243 /*
1244  * Show Device Info Information in contentMain
1245  */
1246 function showDeviceInfo() {
1247         doRequest(URL.deviceinfo, incomingDeviceInfo, false);
1248 }
1249
1250 function showGears(){
1251         var enabled = false;
1252         
1253         if (window.google && google.gears){
1254                 enabled = gearsEnabled();
1255         }
1256         
1257         data = { 'useGears' : enabled };
1258         processTpl('tplGears', data, 'contentMain');
1259 }
1260
1261 function showSettings(){
1262         var debug = userprefs.data.debug;
1263         var debugChecked = "";
1264         if(debug){
1265                 debugChecked = 'checked';
1266         }
1267         
1268         var updateCurrentInterval = userprefs.data.updateCurrentInterval / 1000;
1269         var updateBouquetInterval = userprefs.data.updateBouquetInterval / 1000;
1270         
1271
1272         data = {'debug' : debugChecked,
1273                         'updateCurrentInterval' : updateCurrentInterval,
1274                         'updateBouquetInterval' : updateBouquetInterval
1275         };
1276         processTpl('tplSettings', data, 'contentMain');
1277 }
1278
1279  
1280 // Spezial functions, mostly for testing purpose
1281 function openHiddenFunctions(){
1282         openPopup("Extra Hidden Functions",tplExtraHiddenFunctions,300,100,920,0);
1283 }
1284
1285
1286 function startDebugWindow() {
1287         DBG = true;
1288         debugWin = openPopup("DEBUG", "", 300, 300,920,140, "debugWindow");
1289 }
1290
1291
1292 function restartTwisted() {
1293         doRequest( "/web/restarttwisted" );
1294 }
1295
1296
1297 //MediaPlayer
1298 function mpOnCommandFinished(request){
1299         if(request.readyState== 4){
1300                 var result = new SimpleXMLResult(getXML(request));
1301                 simpleResultHandler(result);
1302         }
1303 }
1304
1305 function mpOnCommandFinishedReload(request){
1306         mpOnCommandFinished(request);
1307         mpPlaylist();
1308 }
1309
1310 function mpCommand(command) {
1311         debug("[mpCommand] called");
1312         doRequest( URL.mediaplayercmd + command, mpOnCommandFinished );
1313 }
1314
1315 function mpOnLoadFinished(request){
1316         if(request.readyState == 4){
1317                 var files = new FileList(getXML(request)).getArray();
1318
1319                 debug("[mpOnLoadFinished] Got "+files.length+" entries in mediaplayer filelist");
1320                 // listerHtml = tplMediaPlayerHeader;
1321
1322                 var namespace = { 'hasparent' : false };
1323
1324                 var root = files[0].getRoot();
1325                 debug("[mpOnLoadFinished] root= " + root );
1326                 if (root != "playlist") {
1327                         namespace = {
1328                                         'root': root,
1329                                         'hasparent' : false
1330                         };
1331                         if(root != '/') {
1332                                 var re = new RegExp(/(.*)\/(.*)\/$/);
1333                                 re.exec(root);
1334                                 var newroot = RegExp.$1+'/';
1335                                 if(newroot == '//') {
1336                                         newroot = '/';
1337                                 }
1338                                 namespace = {
1339                                                 'hasparent' : true,
1340                                                 'root': root,
1341                                                 'servicereference': newroot,
1342                                                 'newroot': newroot,
1343                                                 'name': '..'
1344                                 };      
1345                         }
1346                 }
1347
1348                 var itemnamespace = Array();
1349                 for ( var i = 0; i < files.length; i++){
1350                         var file = files[i];
1351                         debug("[mpOnLoadFinished] filename='" + file.getNameOnly() + "'" );
1352                         if(file.getNameOnly() == '' || file.getRoot().startsWith( file.getNameOnly() )) {
1353                                 continue;
1354                         }
1355                         var isdir = true;
1356
1357                         if (file.getIsDirectory() == "False") {
1358                                 isdir = false;
1359                         }
1360
1361                         itemnamespace[i] = {
1362                                         'isdir' : isdir,
1363                                         'servicereference': file.getServiceReference(),
1364                                         'root': file.getRoot(),
1365                                         'name': file.getNameOnly()
1366                         };
1367
1368                 }
1369
1370                 var data = { 
1371                         mp : namespace,
1372                         items: itemnamespace
1373                 };
1374
1375                 processTpl('tplMediaPlayer', data, 'contentMain');
1376         }               
1377 }
1378
1379
1380 function mpLoad(path){
1381         debug("[mpLoad] called");
1382         if(path == undefined){
1383                 path = 'Filesystems';
1384         }
1385         if( $('mpContent') != null){
1386                 debug("[mpLoad] setAjaxLoad");
1387                 setAjaxLoad('mpContent');
1388         }
1389         doRequest(URL.mediaplayerlist + path, mpOnLoadFinished, false);
1390 }
1391
1392
1393 /**
1394  * @pmpAddToPlaylistee
1395  * @param root
1396  */
1397 function mpAddToPlaylist(file, root, play) {
1398         debug("[mpAddToPlaylist] called");
1399         mediaPlayerStarted = true;
1400         if(play === true){
1401                 doRequest( URL.mediaplayerplay + file + "&root=" + root, mpOnCommandFinished );
1402         } else {
1403                 doRequest( URL.mediaplayeradd + file + "&root=" + root, mpOnCommandFinished );
1404         }
1405 }
1406
1407
1408 function mpRemoveFromPlaylist(sref) {
1409         debug("[mpRemoveFromPlaylist] called");
1410         mediaPlayerStarted = true;
1411         doRequest( URL.mediaplayerremove+sref, mpOnCommandFinishedReload );
1412 }
1413
1414
1415 function mpPlaylist() {
1416         debug("[mpPlaylist] called");
1417         if( $('mpContent') != null){
1418                 debug("[mpPlaylist] setAjaxLoad");
1419                 setAjaxLoad('mpContent');
1420         }
1421         
1422         doRequest(URL.mediaplayerlist+"playlist", mpOnLoadFinished );
1423 }
1424
1425
1426 function mpWritePlaylist() {
1427         debug("[mpWritePlaylist] called");
1428         var filename = '';
1429         filename = prompt("Please enter a name for the playlist", "");
1430
1431         if(filename !== "") {
1432                 doRequest( URL.mediaplayerwrite+filename, mpOnCommandFinished );
1433         }
1434 }
1435
1436 //Powerstate
1437 /*
1438  * Sets the Powerstate @param newState - the new Powerstate Possible Values
1439  * (also see WebComponents/Sources/PowerState.py) #-1: get current state # 0:
1440  * toggle standby # 1: poweroff/deepstandby # 2: rebootdreambox # 3:
1441  * rebootenigma
1442  */
1443 function sendPowerState(newState){
1444         doRequest( URL.powerstate+'?newstate='+newState, incomingPowerState);
1445 }
1446
1447
1448 //Currently Running Service
1449 function incomingCurrent(request){
1450         //      debug("[incomingCurrent called]");
1451         if(request.readyState == 4){
1452                 try{
1453                         var xml = getXML(request);
1454                         var epg = new EPGList(xml).getArray();
1455                         epg = epg[0];
1456                         
1457                         var service = new Service(xml).toJSON(); 
1458                         
1459                         var data = { 
1460                                                 'current' : epg,
1461                                                 'service' : service
1462                                         };
1463
1464                         if(typeof(templates.tplCurrent) != "undefined"){
1465                                 var display = 'none';
1466                                 try{
1467                                         var display = $('trExtCurrent').style.display;
1468                                 } catch(e){}
1469                                 
1470                                 renderTpl(templates.tplCurrent, data, "currentContent");
1471                                 $('trExtCurrent').style.display = display;
1472                         } else {
1473                                 debug("[incomingCurrent] tplCurrent N/A");
1474                         }
1475
1476                 } catch (e){}
1477                 
1478                 isActive.getCurrent = false;
1479         }
1480 }
1481
1482
1483 function getCurrent(){
1484         if(!isActive.getCurrent){
1485                 isActive.getCurrent = true;
1486                 doRequest(URL.getcurrent, incomingCurrent, false);
1487         }
1488 }
1489
1490
1491 //Navigation and Content Helper Functions
1492
1493 /*
1494  * Loads all Bouquets for the given enigma2 servicereference and sets the
1495  * according contentHeader @param sRef - the Servicereference for the bouquet to
1496  * load
1497  */
1498 function getBouquets(sRef){     
1499         var url = URL.getservices+encodeURIComponent(sRef);
1500         
1501         doRequest(url, incomingBouquetList, true);              
1502 }
1503
1504 /*
1505  * Loads another navigation template and sets the navigation header
1506  * @param template - The name of the template
1507  * @param title - The title to set for the navigation
1508  */
1509 function reloadNav(template, title){
1510         setAjaxLoad('navContent');
1511         processTpl(template, null, 'navContent');
1512         setNavHd(title);
1513 }
1514
1515 function reloadNavDynamic(fnc, title){
1516         setAjaxLoad('navContent');
1517         setNavHd(title);
1518         fnc();
1519 }
1520
1521 function getBouquetsTv(){
1522         getBouquets(bouquetsTv);
1523 }
1524
1525 function getProviderTv(){
1526         getBouquets(providerTv);
1527 }
1528
1529 function getSatellitesTv(){
1530         getBouquets(satellitesTv);
1531 }
1532
1533 function getAllTv(){
1534         loadBouquet(allTv, "All (TV)");
1535 }
1536
1537
1538 function getBouquetsRadio(){
1539         getBouquets(bouquetsRadio);
1540 }
1541
1542 function getProviderRadio(){
1543         getBouquets(providerRadio);
1544 }
1545
1546 function getSatellitesRadio(){
1547         getBouquets(satellitesRadio);
1548 }
1549
1550 function getAllRadio(){
1551         loadBouquet(allRadio, "All (Radio)");
1552 }
1553
1554 /*
1555  * Loads dynamic content to $(contentMain) by calling a execution function
1556  * @param fnc - The function used to load the content
1557  * @param title - The Title to set on the contentpanel
1558  */
1559 function loadContentDynamic(fnc, title, domid){
1560         if(typeof(domid) != "undefined" && $(domid) != null){
1561                 setAjaxLoad(domid);
1562         } else {
1563                 setAjaxLoad('contentMain');
1564         }
1565         setContentHd(title);
1566         stopUpdateBouquetItemsPoller();
1567
1568         fnc();
1569 }
1570
1571 /*
1572  * like loadContentDynamic but without the AjaxLoaderAnimation being shown
1573  */
1574 function reloadContentDynamic(fnc, title){
1575         setContentHd(title);
1576         fnc();
1577 }
1578
1579 /*
1580  * Loads a static template to $(contentMain)
1581  * @param template - Name of the Template
1582  * @param title - The Title to set on the Content-Panel
1583  */
1584 function loadContentStatic(template, title){
1585         setAjaxLoad('contentMain');
1586         setContentHd(title);
1587         stopUpdateBouquetItemsPoller();
1588         processTpl(template, null, 'contentMain');
1589 }
1590
1591
1592 /*
1593  * Opens the given Control
1594  * @param control - Control Page as String
1595  * Possible Values: power, extras, message, screenshot, videoshot, osdshot
1596  */
1597 function loadControl(control){
1598         switch(control){
1599         case "power":
1600                 loadContentStatic('tplPower', 'PowerControl');
1601                 break;
1602
1603         case "message":
1604                 loadContentStatic('tplSendMessage', 'Send a Message');
1605                 break;
1606
1607         case "remote":
1608                 loadAndOpenWebRemote();
1609                 break;
1610
1611         case "screenshot":
1612                 loadContentDynamic(getScreenShot, 'Screenshot');
1613                 break;
1614
1615         case "videoshot":
1616                 loadContentDynamic(getVideoShot, 'Videoshot');
1617                 break;
1618
1619         case "osdshot":
1620                 loadContentDynamic(getOsdShot, 'OSDshot');
1621                 break;
1622
1623         default:
1624                 break;
1625         }
1626 }
1627
1628
1629 function loadDeviceInfo(){
1630         loadContentDynamic(showDeviceInfo, 'Device Information');
1631 }
1632
1633 function loadTools(){
1634         loadContentStatic('tplTools', 'Tools');
1635 }
1636
1637 function loadAbout(){
1638         loadContentStatic('tplAbout', 'About');
1639 }
1640
1641 function loadSettings(){
1642         loadContentDynamic(showSettings, 'Settings');
1643 }
1644
1645 function loadGearsInfo(){
1646         loadContentDynamic(showGears, 'Google Gears');
1647 }
1648
1649 function reloadGearsInfo(){
1650         loadContentDynamic(showGears, 'Google Gears');
1651 }
1652
1653 var cachedServiceElements = null;
1654
1655 function onServiceSearchFocus(event){
1656         event.element().value = '';
1657         cachedServiceElements = null;
1658         serviceSearch(event);
1659 }
1660
1661 function serviceSearch(event){
1662         var needle = event.element().value.toLowerCase();
1663         
1664         if(cachedServiceElements == null){
1665                 cachedServiceElements = $$('.sListRow');
1666         }
1667         
1668         for(var i = 0; i < cachedServiceElements.length; i++){
1669                 var row = cachedServiceElements[i];
1670                 var serviceName = row.readAttribute('data-servicename').toLowerCase();
1671                 
1672                 if(serviceName.match(needle) != needle && serviceName != ""){
1673                         row.hide();
1674                 } else {                
1675                         row.show();
1676                 }
1677         }
1678         
1679         debug('serviceNames');
1680 }
1681
1682 /*
1683  * Switches Navigation Modes
1684  * @param mode - The Navigation Mode you want to switch to
1685  * Possible Values: TV, Radio, Movies, Timer, Extras
1686  */
1687 function switchMode(mode){
1688         switch(mode){
1689         case "TV":
1690                 reloadNav('tplNavTv', 'TeleVision');
1691                 break;
1692
1693         case "Radio":
1694                 reloadNav('tplNavRadio', 'Radio');
1695                 break;
1696
1697         case "Movies":
1698                 //The Navigation
1699                 reloadNavDynamic(loadMovieNav, 'Movies');
1700
1701                 // The Movie list
1702                 loadContentDynamic(loadMovieList, 'Movies');
1703                 break;
1704
1705         case "Timer":
1706                 //The Navigation
1707                 reloadNav('tplNavTimer', 'Timer');
1708
1709                 // The Timerlist
1710                 loadContentDynamic(loadTimerList, 'Timer');
1711                 break;
1712
1713         case "MediaPlayer":
1714                 loadContentDynamic(mpLoad, 'MediaPlayer');
1715                 break;
1716
1717         case "BoxControl":
1718                 reloadNav('tplNavBoxControl', 'BoxControl');
1719                 break;
1720
1721         case "Extras":
1722                 reloadNav('tplNavExtras', 'Extras');
1723                 break;
1724                 
1725         default:
1726                 break;
1727         }
1728 }
1729
1730 function openWebTV(){
1731         window.open('/web-data/streaminterface.html', 'WebTV', 'scrollbars=no, width=800, height=740');
1732 }
1733
1734 function clearSearch(){
1735         $('epgSearch').value = "";
1736         $('epgSearch').focus();
1737 }
1738
1739 function updateItems(){
1740         getCurrent();
1741         getPowerState();
1742 }
1743
1744 function updateItemsLazy(bouquet){
1745         getSubServices();
1746         getBouquetEpg();
1747 }
1748
1749 /*
1750  * Does the everything required on initial pageload
1751  */
1752
1753 function init(){
1754         var DBG = userprefs.data.debug || false;
1755         
1756         if(DBG){
1757                 openDebug();
1758         }
1759
1760         if( parseNr(userprefs.data.updateCurrentInterval) < 10000){
1761                 userprefs.data.updateCurrentInterval = 120000;
1762                 userprefs.save();
1763         }
1764         
1765         if( parseNr(userprefs.data.updateBouquetInterval) < 60000 ){
1766                 userprefs.data.updateBouquetInterval = 300000;
1767                 userprefs.save();
1768         }
1769         
1770         if (typeof document.body.style.maxHeight == "undefined") {
1771                 alert("Due to the tremendous amount of work needed to get everthing to " +
1772                 "work properly, there is (for now) no support for Internet Explorer Versions below 7");
1773         }
1774         
1775         getBoxtype();
1776
1777         setAjaxLoad('navContent');
1778         setAjaxLoad('contentMain');
1779
1780         fetchTpl('tplServiceListEPGItem');
1781         fetchTpl('tplBouquetsAndServices');
1782         fetchTpl('tplCurrent'); 
1783         reloadNav('tplNavTv', 'TeleVision');
1784
1785         initChannelList();
1786         initVolumePanel();
1787         initMovieList();
1788
1789         updateItems();
1790         startUpdateCurrentPoller();
1791 }