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