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