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