Added functionality to wap-page timerlist aswell as a new page for powerstate
[enigma2-plugins.git] / webinterface / src / web-data / tools.js
1 Version = '$Header$';
2
3 var doRequestMemory = new Object();
4 var doRequestMemorySave = new Object();
5
6 // Get Settings
7 var settings = null;
8 var parentControlList = null;
9
10 // UpdateStreamReader
11 var UpdateStreamReaderNextReadPos = 0;
12 var UpdateStreamReaderPollTimer;
13 var UpdateStreamReaderPollTimerCounter = 0;
14 var UpdateStreamReaderPollTimerCounterTwisted = 0;
15 UpdateStreamReaderRequest = null;
16 function UpdateStreamReaderStart(){
17         var ua = navigator.userAgent;
18         if(navigator.userAgent.indexOf("MSIE") >=0) {
19                 debug("UpdateStreamReader IE Fix");
20
21                 var namespace = {       
22                                         'url_updates': url_updates
23                 };
24                 $('UpdateStreamReaderIEFixPanel').innerHTML = RND(tplUpdateStreamReaderIE, namespace);
25                 
26         }else {
27                 UpdateStreamReaderNextReadPos = 0;
28                 allMessages = "";
29                 UpdateStreamReaderRequest = new XMLHttpRequest();
30                 UpdateStreamReaderRequest.onload = UpdateStreamReaderOnLoad;
31                 UpdateStreamReaderRequest.onerror = UpdateStreamReaderOnError;
32                 UpdateStreamReaderRequest.open("GET", url_updates, true);
33                 UpdateStreamReaderRequest.send(null);
34                 UpdateStreamReaderPollTimer = setInterval(UpdateStreamReaderLatestResponse, 10000);
35         }
36 }
37   
38 function UpdateStreamReaderLatestResponse() {
39         UpdateStreamReaderPollTimerCounter++;
40         debug(UpdateStreamReaderPollTimerCounter);
41         if(UpdateStreamReaderPollTimerCounter > 6) {
42                 clearInterval(UpdateStreamReaderPollTimer);
43                 UpdateStreamReaderRequest.abort();
44                 UpdateStreamReaderRequest = null;
45                 UpdateStreamReaderPollTimerCounter = 0;
46                 UpdateStreamReaderStart();
47                 
48                 UpdateStreamReaderPollTimerCounterTwisted++;
49                 return;
50         }
51         var allMessages = UpdateStreamReaderRequest.responseText;
52         do {
53                 var unprocessed = allMessages.substring(UpdateStreamReaderNextReadPos);
54                 var messageXMLEndIndex = unprocessed.indexOf("\n");
55                 
56                 if (messageXMLEndIndex!=-1) {
57                         var endOfFirstMessageIndex = messageXMLEndIndex + "\n".length;
58                         var anUpdate = unprocessed.substring(0, endOfFirstMessageIndex);
59         
60                         var re = new RegExp("<script>parent\.(.*)</script>");
61                         anUpdate = re.exec(anUpdate);
62
63                         if(anUpdate != null){
64                                 if (anUpdate.length == 2){
65                                         eval(anUpdate[1]);
66                                 }
67                         }
68                         
69                         UpdateStreamReaderNextReadPos += endOfFirstMessageIndex;
70                 }
71                 if(UpdateStreamReaderNextReadPos > 65000){
72                         UpdateStreamReaderRequest.abort();
73                         UpdateStreamReaderRequest = null;
74                         UpdateStreamReaderPollTimerCounter = 0;
75                         UpdateStreamReaderStart();
76                         messageXMLEndIndex = -1;
77                 }
78         } while (messageXMLEndIndex != -1);
79 }
80
81 function UpdateStreamReaderOnLoad(){
82         window.clearInterval(UpdateStreamReaderPollTimer);
83         debug("UpdateStreamReaderOnLoad");
84         Dialog.confirm(
85                 "Live Update Stream ends!<br><br>You will not receive any Update from Enigma2.<br>Should I reconnect?",
86                  {windowParameters: {width:300, className: windowStyle},
87                         okLabel: "reconnect",
88                         buttonClass: "myButtonClass",
89                         cancel: function(win) {debug("cancel confirm panel")},
90                         ok: function(win) {UpdateStreamReaderStart(); return true;}
91                         }
92                 );
93 }
94 function UpdateStreamReaderOnError(){
95         // TODO: change this, because it will be called on 'PageUnload' while the request is still running
96         debug("UpdateStreamReaderOnError");
97         window.clearInterval(UpdateStreamReaderPollTimer);
98         Dialog.confirm(
99                 "Live Update Stream has an Error!<br><br>You will not receive any Update from Enigma2.<br>Should I try to reconnect?",
100                  {windowParameters: {width:300, className: windowStyle},
101                          okLabel: "reconnect",
102                          buttonClass: "myButtonClass",
103                          cancel: function(win) {debug("cancel confirm panel")},
104                          ok: function(win) {UpdateStreamReaderStart(); return true;}
105                         }
106                 );
107 }
108 //end UpdateStreamReader
109
110 function openWindow(title, inner, width, height, x, y, id){
111                         if(id == null) id = new Date().toUTCString();
112                         if(x == null) x = 460;
113                         if(y == null) y = 400;
114                         var win = new Window(id, {className: windowStyle, title: title, width: width, height: height});
115                         win.getContent().innerHTML = inner;
116                         win.setDestroyOnClose();
117                         win.showCenter();
118                         win.setLocation(y,x);//y=top,x=left
119                         debug("opening Window: "+title);
120                         return win;
121 }
122 function messageBox(t, m){
123         Dialog.alert(m, {windowParameters: {title: t, className: windowStyle, width:200}, okLabel: "Close"});
124 }
125
126 //RND Template Function (http://www.amix.dk)
127 function RND(tmpl, ns) {
128         var fn = function(w, g) {
129                 g = g.split("|");
130                 var cnt = ns[g[0]];
131                 //Support for filter functions
132                 for(var i=1; i < g.length; i++) {
133                         cnt = eval(g[i])(cnt);
134                 }
135                 return cnt || w;
136         };
137         return tmpl.replace(/%\(([A-Za-z0-9_|.]*)\)/g, fn);
138 }
139 function debug(text){
140         if(DBG){
141                 try{
142                         debugWin.getContent().innerHTML += "DEBUG: "+text+"<br>";
143                 } catch (windowNotPresent) {}
144         }
145 }
146 function showhide(id){
147         o = $(id).style;
148         o.display = (o.display!="none")? "none":"";
149 }
150 function set(element, value){
151         //debug(element+"-"+value);
152         element = parent.$(element);
153         if(value.length > 550) {
154                 value = value.substr(0,550) + "[...]";
155         }
156         if (element){
157                 element.innerHTML = value;
158         }
159         if(navigator.userAgent.indexOf("MSIE") >=0) {
160                 elementscript= $('UpdateStreamReaderIEFixIFrame').$('scriptzone');
161                 if(elementscript){
162                         elementscript.innerHTML = ""; // deleting set() from page, to keep the page short and to save memory                    
163                 }
164         }
165 }
166 function setComplete(element, value){
167         //debug(element+"-"+value);
168         element = parent.$(element);
169         if (element){
170                 element.innerHTML = value;
171         }
172         if(navigator.userAgent.indexOf("MSIE") >=0) {
173                 elementscript= $('UpdateStreamReaderIEFixIFrame').$('scriptzone');
174                 if(elementscript){
175                         elementscript.innerHTML = ""; // deleting set() from page, to keep the page short and to save memory                    
176                 }
177         }
178 }
179 // requestindikator
180 var requestcounter = 0;
181 function requestIndicatorUpdate(){
182         //debug(requestcounter+" open requests");
183         if(requestcounter>=1){
184                 $('RequestIndicator').style.display = "inline";
185         }else{
186                 $('RequestIndicator').style.display = "none";
187         }
188 }
189 function requestStarted(){
190         requestcounter +=1;
191         requestIndicatorUpdate();
192 }
193 function requestFinished(){
194         requestcounter -=1;
195         requestIndicatorUpdate();
196 }
197 // end requestindikator
198 function doRequest(url, readyFunction, save){
199         requestStarted();
200         doRequestMemorySave[url] = save;
201         debug("doRequest: Requesting: "+url);
202         if(save == true && typeof(doRequestMemory[url]) != "undefined") {
203                 readyFunction(doRequestMemory[url]);
204         } else {
205                 debug("doRequest: loading");
206                 new Ajax.Request(url,
207                         {
208                                 asynchronous: true,
209                                 method: 'GET',
210                                 requestHeaders: ['Pragma', 'no-cache', 'Cache-Control', 'must-revalidate', 'If-Modified-Since', 'Sat, 1 Jan 2000 00:00:00 GMT'],
211                                 onException: function(o,e){ throw(e); },                                
212                                 onSuccess: function (transport, json) {
213                                                         if(typeof(doRequestMemorySave[url]) != "undefined") {
214                                                                 if(doRequestMemorySave[url]) {
215                                                                         debug("doRequest: saving request"); 
216                                                                         doRequestMemory[url] = transport;
217                                                                 }
218                                                         }
219                                                         readyFunction(transport);
220                                                 },
221                                 onComplete: requestFinished 
222                         });
223         }
224 }
225
226 function getXML(request){
227         if (document.implementation && document.implementation.createDocument){
228                 var xmlDoc = request.responseXML
229         }
230         else if (window.ActiveXObject){
231                 var xmlInsert = document.createElement('xml');
232
233                 xmlInsert.setAttribute('innerHTML',request.responseText);
234                 xmlInsert.setAttribute('id','_MakeAUniqueID');
235                 document.body.appendChild(xmlInsert);
236                 xmlDoc = $('_MakeAUniqueID');
237                 document.body.removeChild($('_MakeAUniqueID'));
238         } else {
239                 debug("Your Browser Sucks!");
240         }
241         return xmlDoc;
242 }
243 function parentPin(servicereference) {
244         servicereference = decodeURIComponent(servicereference);
245         if(parentControlList == null || String(getSettingByName("config.ParentalControl.configured")) != "True") {
246                 return true;
247         }
248         debug("parentPin " + parentControlList.length);
249         if(getParentControlByRef(servicereference) == servicereference) {
250                 if(String(getSettingByName("config.ParentalControl.type.value")) == "whitelist") {
251                         debug("leaving here 1");
252                         return true;
253                 }
254         } else {
255                 debug("leaving here 2");
256                 return true;
257         }
258         debug("going to ask for PIN");
259
260         var userInput = prompt('ParentControll was switch on.<br> Please enter PIN','PIN');
261         if (userInput != '' && userInput != null) {
262                 if(String(userInput) == String(getSettingByName("config.ParentalControl.servicepin.0")) ) {
263                         return true;
264                 } else {
265                         return parentPin(servicereference);
266                 }
267         } else {
268                 return false;
269         }
270 }
271 var SubServicePoller;
272 var SubServicePollerCounter = 0;
273 var SubServicePollerRef = null;
274 function zap(servicereference){
275         if(parentPin(servicereference)) {
276                 new Ajax.Request( "/web/zap?sRef=" + servicereference, 
277                                                         {
278                                                                 asynchronous: true,
279                                                                 method: 'get'
280                                                         }
281                                                 );
282                 if(SubServicePoller != 0){
283                         clearInterval(SubServicePoller);
284                         SubServicePollerCounter = 0;
285                 }
286                 SubServicePollerRef = servicereference;
287                 SubServicePoller = setInterval(getSubServices, 10000);
288                 SubServicePollerCounter = 1;
289         }
290 }
291
292 //++++       SignalPanel                           ++++
293 function initSignalPanel(){
294         $('SignalPanel').innerHTML = tplSignalPanelButton;
295 }
296 function openSignalDialog(){
297         openWindow("Signal Info",tplSignalPanel, 215, 75,620,40);
298 }
299
300
301 //++++ EPG functions                               ++++
302 function loadEPGBySearchString(string){
303                 doRequest(url_epgsearch+escape(string),incomingEPGrequest, false);
304 }
305 function loadEPGByServiceReference(servicereference){
306                 doRequest(url_epgservice+servicereference,incomingEPGrequest, false);
307 }
308 function incomingEPGrequest(request){
309         debug("incoming request" +request.readyState);          
310         if (request.readyState == 4){
311                 var EPGItems = new EPGList(getXML(request)).getArray(true);
312                 debug("have "+EPGItems.length+" e2events");
313                 if(EPGItems.length > 0){                        
314                         var html = tplEPGListHeader;
315                         for (var i=0; i < EPGItems.length; i++){
316                                 try{
317                                         var item = EPGItems[i];                         
318                                         var namespace = {       
319                                                         'date': item.getTimeDay(),
320                                                         'eventid': item.getEventId(),
321                                                         'servicereference': item.getServiceReference(),
322                                                         'servicename': quotes2html(item.getServiceName()),
323                                                         'title': quotes2html(item.getTitle()),
324                                                         'titleESC': escape(item.getTitle()),
325                                                         'starttime': item.getTimeStartString(), 
326                                                         'duration': Math.ceil(item.getDuration()/60000), 
327                                                         'description': quotes2html(item.getDescription()),
328                                                         'endtime': item.getTimeEndString(), 
329                                                         'extdescription': quotes2html(item.getDescriptionExtended()),
330                                                         'number': String(i),
331                                                         'extdescriptionSmall': extdescriptionSmall(item.getDescriptionExtended(),String(i)),
332                                                         'start': item.getTimeBegin(),
333                                                         'end': item.getTimeEnd()
334                                                 };
335                                         //Fill template with data and add id to our result
336                                         html += RND(tplEPGListItem, namespace);
337                                 } catch (blubb) { debug("Error rendering: "+blubb);     }
338                         }
339                         html += tplEPGListFooter;
340                         openWindow("Electronic Program Guide", html, 900, 500,50,60);
341                 } else {
342                         messageBox('No Items found!', 'Sorry but i could not find any EPG Content containing your search value');
343                 }
344         }
345 }
346 function extdescriptionSmall(txt,num) {
347         if(txt.length > 410) {
348                 var shortTxt = txt.substr(0,410);
349                 txt = txt.replace(/\'\'/g, '&quot;');
350                 txt = txt.replace(/\\/g, '\\\\');
351                 txt = txt.replace(/\'/g, '\\\'');
352                 txt = txt.replace(/\"/g, '&quot;');
353                 var smallNamespace = { 'txt':txt,'number':num, 'shortTxt':shortTxt};
354                 return RND(tplEPGListItemExtend, smallNamespace);
355         } else {
356                 return txt;
357         }
358 }       
359
360 /////////////////////////
361
362 function loadServiceEPGNowNext(servicereference){
363         var url = url_epgnow+servicereference;
364         doRequest(url, incomingServiceEPGNowNext, false);       
365 }
366
367 function incomingServiceEPGNowNext(request){
368         if(request.readyState == 4){
369                 var epgevents = getXML(request).getElementsByTagName("e2eventlist").item(0).getElementsByTagName("e2event");
370                 for (var c =0; c < epgevents.length;c++){
371                         var eventnow = new EPGEvent(epgevents.item(c));
372                         
373                         if (eventnow.getEventId() != 'None'){
374                                 buildServiceListEPGItem(eventnow,"NOW");
375                         }
376                 }
377         }
378 }
379 function buildServiceListEPGItem(epgevent,nownext){
380         var e = $(epgevent.getServiceReference()+'EPG'+nownext);
381                 try{
382                         var namespace = {       
383                                 'starttime': epgevent.getTimeStartString(), 
384                                 'title': epgevent.getTitle(), 
385                                 'length': Math.ceil(epgevent.duration/60) 
386                         };
387                         e.innerHTML = RND(tplServiceListEPGItem, namespace);
388                 } catch (blubb) {
389                         debug("Error rendering: "+blubb);
390                 }       
391 }
392 ///////////////////
393
394
395 //+++++++++++++++++++++++++++++++++++++++++++++++++++++
396 //+++++++++++++++++++++++++++++++++++++++++++++++++++++
397 //++++ GUI functions                               ++++
398 //+++++++++++++++++++++++++++++++++++++++++++++++++++++
399 //+++++++++++++++++++++++++++++++++++++++++++++++++++++
400
401 var currentBodyMainElement = null
402
403 function setBodyMainContent(newelementname){
404         newelement =$(newelementname);
405         if(currentBodyMainElement != null){
406                 currentBodyMainElement.style.display = "none";
407                 
408         }
409         newelement.style.display = "";
410         currentBodyMainElement = newelement;
411 }
412
413 //+++++++++++++++++++++++++++++++++++++++++++++++++++++
414 //+++++++++++++++++++++++++++++++++++++++++++++++++++++
415 //++++ volume functions                            ++++
416 //+++++++++++++++++++++++++++++++++++++++++++++++++++++
417 //+++++++++++++++++++++++++++++++++++++++++++++++++++++
418
419 function initVolumePanel(){
420         $('VolumePanel').innerHTML = tplVolumePanel;
421         getVolume(); 
422 }
423 function getVolume(){
424         doRequest(url_getvolume,handleVolumeRequest, false);
425 }
426 function volumeSet(newvalue){
427         doRequest(url_setvolume+newvalue,handleVolumeRequest, false);
428 }
429 function volumeUp(){
430         doRequest(url_volumeup,handleVolumeRequest, false);
431 }
432 function volumeDown(){
433         doRequest(url_volumedown,handleVolumeRequest, false);   
434 }
435 function volumeMute(){
436         doRequest(url_volumemute,handleVolumeRequest, false);
437 }
438 function handleVolumeRequest(request){
439         if (request.readyState == 4) {
440                 var b = getXML(request).getElementsByTagName("e2volume");
441                 var newvalue = b.item(0).getElementsByTagName('e2current').item(0).firstChild.data;
442                 var mute = b.item(0).getElementsByTagName('e2ismuted').item(0).firstChild.data;
443                 debug("volume"+newvalue+";"+mute);
444                 
445                 for (var i = 1; i <= 10; i++)           {
446                         if ( (newvalue/10)>=i){
447                                 $("volume"+i).src = "/webdata/gfx/led_on.png";
448                         }else{
449                                 $("volume"+i).src = "/webdata/gfx/led_off.png";
450                         }
451                 }
452                 if (mute == "False"){
453                         $("speaker").src = "/webdata/gfx/speak_on.png";
454                 }else{
455                         $("speaker").src = "/webdata/gfx/speak_off.png";
456                 }
457         }       
458 }
459
460 var bouqetsMemory = new Object();
461
462 function initChannelList(){
463         //debug("init ChannelList");    
464         var url = url_getServices+encodeURIComponent(bouqet_tv);
465         doRequest(url, incomingTVBouquetList, true);
466
467         var url = url_getServices+encodeURIComponent(bouqet_radio);
468         doRequest(url, incomingRadioBouquetList, true);
469
470         var url = url_getServices+encodeURIComponent(bouqet_provider_tv);
471         doRequest(url, incomingProviderTVBouquetList, true);
472
473         var url = url_getServices+encodeURIComponent(bouqet_provider_radio);
474         doRequest(url, incomingProviderRadioBouquetList, true);
475         
476         getSettings();
477 }
478
479 var servicereftoloadepgnow = "";
480 var loadedChannellist = new Object();
481 function loadBouquet(servicereference){ 
482         debug("loading bouquet with "+servicereference);
483         servicereftoloadepgnow = servicereference;
484         debug("loadBouquet " + typeof(loadedChannellist[servicereftoloadepgnow]));
485         if(typeof(loadedChannellist[servicereftoloadepgnow]) == "undefined") {
486                 doRequest(url_getServices+servicereference, incomingChannellist, true);
487         } else {
488                 incomingChannellist();
489         }
490 }
491
492 function incomingTVBouquetList(request){
493         if (request.readyState == 4) {
494                 var list0 = new ServiceList(getXML(request)).getArray();
495                 debug("have "+list0.length+" TV Bouquet ");     
496                 $('accordionMenueBouquetContentTV').innerHTML = renderBouquetTable(list0,tplBouquetListHeader,tplBouquetListItem,tplBouquetListFooter);
497                 //loading first entry of TV Favorites as default for ServiceList
498                 loadBouquet(list0[0].getServiceReference());
499                 bouqetsMemory["bouqet_tv"] = list0;
500         }
501 }
502 function incomingRadioBouquetList(request){
503         if (request.readyState == 4) {
504                 var list1 = new ServiceList(getXML(request)).getArray();
505                 debug("have "+list1.length+" Radio Bouquet ");  
506                 $('accordionMenueBouquetContentRadio').innerHTML = renderBouquetTable(list1,tplBouquetListHeader,tplBouquetListItem,tplBouquetListFooter);
507         }       
508 }
509 function incomingProviderTVBouquetList(request){
510         if (request.readyState == 4) {
511                 var list2 = new ServiceList(getXML(request)).getArray();
512                 debug("have "+list2.length+" TV Provider Bouquet ");    
513                 $('accordionMenueBouquetContentProviderTV').innerHTML = renderBouquetTable(list2,tplBouquetListHeader,tplBouquetListItem,tplBouquetListFooter);
514         }       
515 }
516 function incomingProviderRadioBouquetList(request){
517         if (request.readyState == 4) {
518                 var list2 = new ServiceList(getXML(request)).getArray();
519                 debug("have "+list2.length+" Radio Provider Bouquet "); 
520                 $('accordionMenueBouquetContentProviderRadio').innerHTML = renderBouquetTable(list2,tplBouquetListHeader,tplBouquetListItem,tplBouquetListFooter);
521         }       
522 }
523
524 function renderBouquetTable(bouquet,templateHeader,templateItem,templateFooter){
525         debug("renderBouquetTable with "+bouquet.length+" Bouqet");     
526         var html = templateHeader;
527         for (var i=0; i < bouquet.length; i++){
528                 try{
529                         var namespace = {
530                                 'servicereference': bouquet[i].getServiceReference(), 
531                                 'bouquetname': bouquet[i].getServiceName()
532                         };
533                         html += RND(templateItem, namespace);
534                 } catch (blubb) {}
535         }
536         html += templateFooter;
537         return html;
538 }       
539
540 function incomingChannellist(request){
541         var services = null;
542         if(typeof(loadedChannellist[servicereftoloadepgnow]) != "undefined"){
543                 services = loadedChannellist[servicereftoloadepgnow];
544         } else if(request.readyState == 4) {
545                 services = new ServiceList(getXML(request)).getArray();
546                 loadedChannellist[servicereftoloadepgnow] = services;
547                 debug("got "+services.length+" Services");
548         }
549         if(services != null) {
550                 var smallNamespace = {'mainServiceRef': servicereftoloadepgnow };
551                 listerHtml = RND(tplServiceListHeader, smallNamespace);
552                 for ( var i = 0; i < services.length ; i++){
553                         var reference = services[i];
554                         var namespace = {       
555                                 'servicereference': reference.getServiceReference(),
556                                 'servicename': reference.getServiceName()
557                         };
558                         listerHtml += RND(tplServiceListItem, namespace);
559                 }               
560                 listerHtml += tplServiceListFooter;
561                 $('BodyContentChannellist').innerHTML = listerHtml;
562                 setBodyMainContent('BodyContentChannellist');
563                 loadServiceEPGNowNext(servicereftoloadepgnow);
564                 debug("incomingChannellist " + typeof(loadedChannellist[servicereftoloadepgnow]));
565         }
566 }
567 // Movies
568 function loadMovieList(tag){
569         debug("loading movies by tag '"+tag+"'");
570         doRequest(url_movielist+tag, incomingMovieList);        
571 }
572
573 function incomingMovieList(request){
574         if(request.readyState == 4){
575                 var movies = new MovieList(getXML(request)).getArray();
576                 debug("have "+movies.length+" movies");
577                 listerHtml      = tplMovieListHeader;           
578                 for ( var i = 0; i <movies.length; i++){
579                         var movie = movies[i];
580                         var namespace = {       
581                                 'servicereference': movie.getServiceReference(),
582                                 'servicename': movie.getServiceName() ,
583                                 'title': movie.getTitle(), 
584                                 'description': movie.getDescription(), 
585                                 'descriptionextended': movie.getDescriptionExtended(),
586                                 'filelink': String(movie.getFilename()).substr(17,movie.getFilename().length),
587                                 'filename': String(movie.getFilename()),
588                                 'tags': movie.getTags().join(', ') 
589                         };
590                         listerHtml += RND(tplMovieListItem, namespace);
591                 }
592                 listerHtml += tplMovieListFooter;
593                 $('BodyContentChannellist').innerHTML = listerHtml;
594                 setBodyMainContent('BodyContentChannellist');
595                 
596         }               
597 }
598 function delMovieFile(file,servicename,title,description) {
599         debug("delMovieFile: file("+file+"),servicename("+servicename+"),title("+title+"),description("+description+")");
600         Dialog.confirm(
601                 "Selected timer:<br>"
602                 +"Servicename: "+servicename+"<br>"
603                 +"Title: "+title+"<br>"
604                 +"Description: "+description+"<br>"
605                 +"Are you sure that you want to delete the Timer?",
606                  {windowParameters: {width:300, className: windowStyle},
607                         okLabel: "delete",
608                         buttonClass: "myButtonClass",
609                         cancel: function(win) {debug("delMovieFile cancel confirm panel")},
610                         ok: function(win) { debug("delMovieFile ok confirm panel"); doRequest(url_moviefiledelete+"?filename="+file, incomingDelMovieFileResult, false); return true; }
611                         }
612         );
613         
614 }
615 function incomingDelMovieFileResult(request) {
616         debug("incomingDelMovieFileResult");
617         if(request.readyState == 4){
618                 var delresult = new SimpleXMLResult(getXML(request));
619                 if(delresult.getState()){
620                         loadMovieList('');
621                 }else{
622                         messageBox("Deletion Error","Reason: "+delresult.getStateText());
623                 }
624         }               
625 }
626
627
628 // send Messages
629 function showMessageSendForm(){
630                 $('BodyContentChannellist').innerHTML = tplMessageSendForm;
631 }
632 function sendMessage(messagetext,messagetype,messagetimeout){
633         if(!messagetext){
634                 messagetext = $('MessageSendFormText').value;
635         }       
636         if(!messagetimeout){
637                 messagetimeout = $('MessageSendFormTimeout').value;
638         }       
639         if(!messagetype){
640                 var index = $('MessageSendFormType').selectedIndex;
641                 messagetype = $('MessageSendFormType').options[index].value;
642         }       
643         doRequest(url_message+'?text='+messagetext+'&type='+messagetype+'&timeout='+messagetimeout, incomingMessageResult, false);
644 }
645 function incomingMessageResult(request){
646
647         if(request.readyState== 4){
648                 var b = getXML(request).getElementsByTagName("e2message");
649                 var result = b.item(0).getElementsByTagName('e2result').item(0).firstChild.data;
650                 var resulttext = b.item(0).getElementsByTagName('e2resulttext').item(0).firstChild.data;
651                 if (result=="True"){
652                         messageBox('message send','message send successfully! it appears on TV-Screen');
653                 }else{
654                         messageBox('message send failed',resulttext);
655                 }
656         }               
657 }
658
659 // PowerState Code
660 function showPowerStateSendForm(){
661                 $('BodyContentChannellist').innerHTML = tplPowerStateSendForm;
662 }
663 function sendPowerState(newState){
664         doRequest(url_powerstate+'?newstate='+newState, incomingPowerStateResult, false);
665 }
666 function incomingPowerStateResult(request){
667         debug(request.readyState);
668         if(request.readyState == 4){
669                 var b = getXML(request).getElementsByTagName("e2powerstate");
670                 var result = b.item(0).getElementsByTagName('e2result').item(0).firstChild.data;
671                 var resulttext = b.item(0).getElementsByTagName('e2resulttext').item(0).firstChild.data;
672                 var tplPowerStateSendForm2 = '<h1>PowerState is changing to:'+resulttext+ '</h1>' + tplPowerStateSendForm;
673                 $('BodyContentChannellist').innerHTML = tplPowerStateSendForm2;
674         } else {
675                 $('BodyContentChannellist').innerHTML = "<h1>some unknown error</h1>" + tplPasswordSendForm;
676         }
677 }
678
679 // RemoteControl Code
680 function showRemoteControllSendForm(){
681         if(! $('rcWindow')){
682                 openWindow("Remote", tplRemoteControlForm, 220, 642, 920,0, "rcWindow");
683         }
684 }
685 function sendRemoteControlRequest(command){
686         doRequest(url_remotecontrol+'?command='+command, incomingRemoteControlResult, false);
687         if($('getScreen').checked) {
688                 openGrabPicture();
689         }
690 }
691 function openGrabPicture() {
692         if($('BodyContentChannellist').innerHTML != tplRCGrab) {
693                 $('BodyContentChannellist').innerHTML = tplRCGrab;
694         }
695         debug("openGrabPicture");
696         var buffer = new Image();
697         var downloadStart;
698
699         buffer.onload = function () { debug("image zugewiesen"); $('grabPageIMG').src = buffer.src; return true;};
700         buffer.onerror = function (meldung) { debug("reload grab image failed"); return true;};
701
702         downloadStart = new Date().getTime();
703         buffer.src = '/grab?' + downloadStart;
704         $('grabPageIMG').height(400);
705         tplRCGrab = $('BodyContentChannellist').innerHTML;
706 }
707 function incomingRemoteControlResult(request){
708         if(request.readyState == 4){
709                 var b = getXML(request).getElementsByTagName("e2remotecontrol");
710                 var result = b.item(0).getElementsByTagName('e2result').item(0).firstChild.data;
711                 var resulttext = b.item(0).getElementsByTagName('e2resulttext').item(0).firstChild.data;
712         } else {
713                 $('rcWindow').innerHTML = "<h1>some unknown error</h1>" + tplRemoteControlForm;
714         }
715 }
716
717 function getSettings(){
718         doRequest(url_settings, incomingGetSettings, false);
719 }
720
721 function incomingGetSettings(request){
722         if(request.readyState == 4){
723                 settings = new Settings(getXML(request)).getArray();
724         }
725         if(String(getSettingByName("config.ParentalControl.configured")) == "True") {
726                 getParentControl();
727         }
728 }
729 function getSettingByName(txt) {
730         debug("getSettingByName ("+txt+")");
731         for(i = 0; i < settings.length; i++) {
732                 debug("("+settings[i].getSettingName()+") (" +settings[i].getSettingValue()+")");
733                 if(String(settings[i].getSettingName()) == String(txt)) {
734                         return settings[i].getSettingValue();
735                 } 
736         }
737         return "";
738 }
739 function getParentControl() {
740         doRequest(url_parentcontrol, incomingParentControl, false);
741 }
742 function incomingParentControl(request) {
743         if(request.readyState == 4){
744                 parentControlList = new ServiceList(getXML(request)).getArray();
745                 debug("parentControlList got "+parentControlList.length + " services");
746         }
747 }
748 function getParentControlByRef(txt) {
749         debug("getParentControlByRef ("+txt+")");
750         for(i = 0; i < parentControlList.length; i++) {
751                 debug("("+parentControlList[i].getClearServiceReference()+")");
752                 if(String(parentControlList[i].getClearServiceReference()) == String(txt)) {
753                         return parentControlList[i].getClearServiceReference();
754                 } 
755         }
756         return "";
757 }
758 function ownLazyNumber(num) {
759         if(isNaN(num)){
760                 return 0;
761         } else {
762                 return Number(num);
763         }
764 }
765
766 var subServicesInsertedList = new Object();
767 function getSubServices(servicereference) {
768         clearInterval(SubServicePoller);
769         SubServicePollerCounter = 0;
770         doRequest(url_subservices,incomingSubServiceRequest, false);
771 }
772 function incomingSubServiceRequest(request){
773         if(request.readyState == 4){
774                 var services = new ServiceList(getXML(request)).getArray();
775                 listerHtml      = '';           
776                 debug("got "+services.length+" SubServices");
777                 if(services.length > 1) {
778                         
779                         first = services[0];
780                         var mainChannellist = loadedChannellist[String($('mainServiceRef').value)];
781                         
782                         var oldEntryPosition = -1;
783                         for(i = 0; i < mainChannellist.length; i++) {
784                                 var service = mainChannellist[i];
785                                 if(String(service.getServiceReference()) == String(first.getServiceReference())) {
786                                         oldEntryPosition = i + 1;
787                                         break;
788                                 }
789                         }
790                         if(typeof(subServicesInsertedList[String(first.getServiceReference())]) != "undefined") {
791                                 for ( var i = 1; i < subServicesInsertedList[String(first.getServiceReference())].length ; i++){
792                                         var reference = subServicesInsertedList[String(first.getServiceReference())][i];
793                                         $(reference.getServiceReference()+'extend').innerHTML = "";
794                                 }
795                                 for(i = oldEntryPosition; i < oldEntryPosition + subServicesInsertedList[String(first.getServiceReference())].length; i++) {
796                                         mainChannellist.splice(i);
797                                 }
798                         }
799                         for ( var i = 0; i < services.length ; i++){
800                                 var reference = services[i];
801                                 var namespace = {       
802                                         'servicereference': reference.getServiceReference(),
803                                         'servicename': reference.getServiceName()
804                                 };
805                                 listerHtml += RND(tplServiceListItem, namespace);
806                                 if(oldEntryPosition > -1) {
807                                         mainChannellist = mainChannellist.insert(oldEntryPosition++, reference);
808                                 }
809                         }
810                         $(first.getServiceReference()+'extend').innerHTML = listerHtml;
811                         subServicesInsertedList[String(first.getServiceReference())] = services;
812                         loadedChannellist[$('mainServiceRef').value] = mainChannellist;
813                 }
814         }
815 }
816 // Array.insert( index, value ) - Insert value at index, without overwriting existing keys
817 Array.prototype.insert = function( j, v ) {
818  if( j>=0 ) {
819   var a = this.slice(), b = a.splice( j );
820   a[j] = v;
821   return a.concat( b );
822  }
823 }
824 // Array.splice() - Remove or replace several elements and return any deleted elements
825 if( typeof Array.prototype.splice==='undefined' ) {
826  Array.prototype.splice = function( a, c ) {
827   var i = 0, e = arguments, d = this.copy(), f = a, l = this.length;
828   if( !c ) { c = l - a; }
829   for( i; i < e.length - 2; i++ ) { this[a + i] = e[i + 2]; }
830   for( a; a < l - c; a++ ) { this[a + e.length - 2] = d[a - c]; }
831   this.length -= c - e.length + 2;
832   return d.slice( f, f + c );
833  };
834 }
835 function writeTimerListNow() {
836         new Ajax.Request( url_timerlistwrite, { asynchronous: true, method: 'get' });
837 }
838 function recordingPushed() {
839         doRequest(url_timerlist, incomingRecordingPushed, false);
840 }
841 function incomingRecordingPushed(request) {
842         if(request.readyState == 4){
843                 var timers = new TimerList(getXML(request)).getArray();
844                 debug("have "+timers.length+" timer");
845                 
846                 var aftereventReadable = new Array ('Nothing', 'Standby', 'Deepstandby/Shutdown');
847                 var justplayReadable = new Array('record', 'zap');
848                 var OnOff = new Array('on', 'off');
849                 
850                 listerHtml = '';
851                 
852                 for ( var i = 0; i <timers.length; i++){
853                         var timer = timers[i];
854
855                         if(ownLazyNumber(timer.getDontSave()) == 1) {
856                                 var beginDate = new Date(Number(timer.getTimeBegin())*1000);
857                                 var endDate = new Date(Number(timer.getTimeEnd())*1000);
858                                 var namespace = {
859                                 'servicereference': timer.getServiceReference(),
860                                 'servicename': timer.getServiceName() ,
861                                 'title': timer.getName(), 
862                                 'description': timer.getDescription(), 
863                                 'descriptionextended': timer.getDescriptionExtended(), 
864                                 'begin': timer.getTimeBegin(),
865                                 'beginDate': beginDate.toLocaleString(),
866                                 'end': timer.getTimeEnd(),
867                                 'endDate': endDate.toLocaleString(),
868                                 'state': timer.getState(),
869                                 'duration': Math.ceil((timer.getDuration()/60)),
870                                 'repeated': timer.getRepeated(),
871                                 'repeatedReadable': repeatedReadable(timer.getRepeated()),
872                                 'justplay': timer.getJustplay(),
873                                 'justplayReadable': justplayReadable[Number(timer.getJustplay())],
874                                 'afterevent': timer.getAfterevent(),
875                                 'aftereventReadable': aftereventReadable[Number(timer.getAfterevent())],
876                                 'disabled': timer.getDisabled(),
877                                 'onOff': OnOff[Number(timer.getDisabled())],
878                                 'color': colorTimerListEntry( timer.getState() )
879                                 };
880                                 listerHtml += RND(tplTimerListItem, namespace);
881                         }
882                 }
883                 openWindow("Record Now", listerHtml+tplRecordingFooter, 900, 500, "Record now window");
884         }
885 }
886 function inserteSizes() {
887 /*      var screenW = 640, screenH = 480;
888         if (parseInt(navigator.appVersion)>3) { 
889                 screenW = screen.width;
890                 screenH = screen.height;
891         } else if (navigator.appName == "Netscape"
892            && parseInt(navigator.appVersion)==3
893            && navigator.javaEnabled() ) {
894                 var jToolkit = java.awt.Toolkit.getDefaultToolkit();
895                 var jScreenSize = jToolkit.getScreenSize();
896                 screenW = jScreenSize.width;
897                 screenH = jScreenSize.height;
898         }
899         debug("screenW:"+screenW+" screenH:"+screenH);
900         /* 640x480
901          * 800x600
902          * 1024x768
903          * 1280x1024
904          * 1600x1280
905         if(screenH == 800) {
906                 debug("size 1");
907                 $("BodyContentChannellist").style.height = '20%';
908         } else if(screenH == 1024) {
909                 debug("1024")
910                 $("BodyContentChannellist").style.height = '760px';
911                 
912         } else {
913                 alert("unsupported screensize");
914         }*/
915         
916 }
917 function recordingPushedDecision(recordNowNothing,recordNowUndefinitely,recordNowCurrent) {
918         var recordNow = recordNowNothing;
919         recordNow = (recordNow == "") ? recordNowUndefinitely: recordNow;
920         recordNow = (recordNow == "") ? recordNowCurrent: recordNow;
921         if(recordNow != "nothing" && recordNow != "") {
922                 doRequest(url_recordnow+"?recordnow="+recordNow, incomingTimerAddResult, false);
923         }
924 }
925
926 function ifChecked(rObj) {
927         if(rObj.checked) {
928                 return rObj.value;
929         } else {
930                 return "";
931         }
932 }
933 function showAbout() {
934         doRequest(url_about, incomingAbout, false);
935 }
936 function incomingAbout(request) {
937         if(request.readyState == 4){
938                 debug("incomingAbout returned");
939                 var aboutEntries = getXML(request).getElementsByTagName("e2abouts").item(0).getElementsByTagName("e2about");
940                 for (var c =0; c < aboutEntries.length;c++){
941                         var xml = aboutEntries.item(c);
942                         try{
943                                 var fptext = "V"+xml.getElementsByTagName('e2fpversion').item(0).firstChild.data;
944                                 var tunerinfo = "";
945                                 
946                                 var nims = xml.getElementsByTagName('e2tunerinfo').item(0).getElementsByTagName("e2nim");
947                                 for(var i=0;i< nims.length;i++){
948                                         tunerinfo += nims.item(i).firstChild.data+"<br>";
949                                 }
950                                 
951                                 var hdddata = xml.getElementsByTagName('e2hddinfo').item(0);
952                                 var hddinfo = "";
953                                 if(hdddata.firstChild.data != "None"){
954                                         hddinfo += "Model: "+hdddata.getElementsByTagName("model").item(0).firstChild.data;
955                                         hddinfo += "<br>Capacity: "+hdddata.getElementsByTagName("capacity").item(0).firstChild.data;
956                                         hddinfo += "<br>Free: "+hdddata.getElementsByTagName("free").item(0).firstChild.data;
957                                 }else{
958                                         hddinfo +="no Harddisc";
959                                 }
960
961                                 var namespace = {
962                                         'enigmaVersion': xml.getElementsByTagName('e2enigmaversion').item(0).firstChild.data
963 /*
964                                         ,'lanDHCP': xml.getElementsByTagName('e2landhcp').item(0).firstChild.data
965                                         ,'lanIP': xml.getElementsByTagName('e2lanip').item(0).firstChild.data
966                                         ,'lanMask': xml.getElementsByTagName('e2lanmask').item(0).firstChild.data
967                                         ,'lanGW': xml.getElementsByTagName('e2langw').item(0).firstChild.data
968                                         ,'lanDNS': xml.getElementsByTagName('e2landns').item(0).firstChild.data
969 */
970                                         ,'fpVersion': fptext
971                                         ,'webifversion': xml.getElementsByTagName('e2webifversion').item(0).firstChild.data
972                                         ,'tunerInfo': tunerinfo
973                                         ,'hddInfo': hddinfo
974                                         ,'serviceName': xml.getElementsByTagName('e2servicename').item(0).firstChild.data
975                                         ,'serviceProvider': xml.getElementsByTagName('e2serviceprovider').item(0).firstChild.data
976                                         ,'serviceAspect': xml.getElementsByTagName('e2serviceaspect').item(0).firstChild.data
977                                         ,'serviceNamespace': xml.getElementsByTagName('e2servicenamespace').item(0).firstChild.data
978                                         ,'vPID': xml.getElementsByTagName('e2vpid').item(0).firstChild.data
979                                          ,'vPIDh': parseInt(ownLazyNumber(xml.getElementsByTagName('e2vpid').item(0).firstChild.data),16)+" "
980                                         ,'aPID': xml.getElementsByTagName('e2apid').item(0).firstChild.data+" "
981                                          ,'aPIDh': parseInt(ownLazyNumber(xml.getElementsByTagName('e2apid').item(0).firstChild.data),16)+" "
982                                         ,'pcrID': xml.getElementsByTagName('e2pcrid').item(0).firstChild.data
983                                          ,'pcrIDh': parseInt(ownLazyNumber(xml.getElementsByTagName('e2pcrid').item(0).firstChild.data),16)+" "
984                                         ,'pmtPID': xml.getElementsByTagName('e2pmtpid').item(0).firstChild.data
985                                          ,'pmtPIDh': parseInt(ownLazyNumber(xml.getElementsByTagName('e2pmtpid').item(0).firstChild.data),16)+" "
986                                         ,'txtPID': xml.getElementsByTagName('e2txtpid').item(0).firstChild.data
987                                          ,'txtPIDh': parseInt(ownLazyNumber(xml.getElementsByTagName('e2txtpid').item(0).firstChild.data),16)+" "
988                                         ,'tsID': xml.getElementsByTagName('e2tsid').item(0).firstChild.data
989                                          ,'tsIDh': parseInt(ownLazyNumber(xml.getElementsByTagName('e2tsid').item(0).firstChild.data),16)+" "
990                                         ,'onID': xml.getElementsByTagName('e2onid').item(0).firstChild.data
991                                          ,'onIDh': parseInt(ownLazyNumber(xml.getElementsByTagName('e2onid').item(0).firstChild.data),16)+" "
992                                         ,'sid': xml.getElementsByTagName('e2sid').item(0).firstChild.data
993                                          ,'sidh': parseInt(ownLazyNumber(xml.getElementsByTagName('e2sid').item(0).firstChild.data),16)+" "
994                                   };                              
995                                 $('BodyContentChannellist').innerHTML = RND(tplAbout, namespace);
996                                 setBodyMainContent('BodyContentChannellist');
997                                 
998                         } catch (e) {
999                                 debug("About parsing Error" + e);
1000                         }       
1001                 }
1002         }
1003 }
1004 function quotes2html(txt) {
1005         txt = txt.replace(/"/g, '&quot;');
1006         return txt.replace(/'/g, '&#39;');
1007 }
1008
1009 // Spezial functions, mostly for testing purpose
1010 function openHiddenFunctions(){
1011         openWindow("Extra Hidden Functions",tplExtraHiddenFunctions,300,100,920,0);
1012 }
1013 function restartUpdateStream() {
1014         clearInterval(UpdateStreamReaderPollTimer);
1015         UpdateStreamReaderRequest.abort();
1016         UpdateStreamReaderRequest = null;
1017         UpdateStreamReaderPollTimerCounter = 0;
1018         UpdateStreamReaderStart();
1019 }
1020 function startDebugWindow() {
1021         DBG = true;
1022         debugWin = openWindow("DEBUG", "", 300, 300,920,140, "debugWindow");
1023 }
1024 function restartTwisted() {
1025         new Ajax.Request( "/web/restarttwisted", { asynchronous: true, method: "get" })
1026 }