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