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