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