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