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