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