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