editTimer is now changing a existing timer
[enigma2-plugins.git] / webinterface / src / web-data / tools.js
1 var DBG = false;
2
3 var url_getvolume = '/web/vol?set=state'; 
4 var url_setvolume = '/web/vol?set=set'; // plus new value eq. set=set15
5 var url_volumeup = '/web/vol?set=up';
6 var url_volumedown = '/web/vol?set=down';
7 var url_volumemute = '/web/vol?set=mute';
8
9 var url_epgservice = "/web/epgservice?ref="; // plus serviceRev
10 var url_epgsearch = "/web/epgsearch?search="; // plus serviceRev
11 var url_epgnow = "/web/epgnow?bref="; // plus bouqetRev
12
13 var url_fetchchannels = "/web/fetchchannels?ServiceListBrowse="; // plus encoded serviceref
14
15 var url_updates= "/web/updates.html";
16
17 var url_movielist= "/web/movielist";
18
19 var url_settings= "/web/settings";
20
21 var url_timerlist= "/web/timerlist";
22 var url_timeradd= "/web/timeradd"; // plus serviceref,begin,end,name,description,eit,disabled,justplay,afterevent
23 var url_timerchange= "/web/timerchange"; // plus serviceref,begin,end,name,description,eit,disabled,justplay,afterevent
24 var url_timeraddbyeventid= "/web/timeraddbyeventid"; // plus serviceref,eventid
25 var url_timerdelete= "/web/timerdelete"; // plus serviceref,bedin,end
26
27 var url_message = "/web/message"; // plus text,type,timeout
28
29 var url_powerstate = "/web/powerstate"; // plus new powerstate
30 var url_remotecontrol = "/web/remotecontrol"; // plus command
31
32 var bouqet_tv = '1:7:1:0:0:0:0:0:0:0:(type == 1) || (type == 17) || (type == 195) || (type == 25)FROM BOUQUET "bouquets.tv" ORDER BY bouquet';
33 var bouqet_radio = '1:7:2:0:0:0:0:0:0:0:(type == 2)FROM BOUQUET "bouquets.radio" ORDER BY bouquet';
34 var bouqet_provider_tv = '1:7:1:0:0:0:0:0:0:0:(type == 1) || (type == 17) || (type == 195) || (type == 25) FROM PROVIDERS ORDER BY name';
35 var bouqet_provider_radio ='1:7:2:0:0:0:0:0:0:0:(type == 2) FROM PROVIDERS ORDER BY name';
36
37 var windowStyle = "alphacube";
38
39 // TimerEdit variables:
40 var addTimerEditFormObject = new Object();
41 addTimerEditFormObject["TVListFilled"] = 0;
42 addTimerEditFormObject["RadioListFilled"] = 0;
43 addTimerEditFormObject["deleteOldOnSave"] = 0;
44
45 // Get Settings
46 var settings;
47
48 // UpdateStreamReader
49 var UpdateStreamReaderNextReadPos = 0;
50 var UpdateStreamReaderPollTimer;
51 UpdateStreamReaderRequest = null;
52 function UpdateStreamReaderStart(){
53         var ua = navigator.userAgent;
54         if(navigator.userAgent.indexOf("MSIE") >=0) {
55                 debug("UpdateStreamReader IE Fix");
56
57                 var namespace = {       
58                                         'url_updates': url_updates
59                 };
60                 $('UpdateStreamReaderIEFixPanel').innerHTML = RND(tplUpdateStreamReaderIE, namespace);
61                 
62         }else {
63                 UpdateStreamReaderNextReadPos = 0;
64                 allMessages = "";
65                 UpdateStreamReaderRequest = new XMLHttpRequest();
66                 UpdateStreamReaderRequest.onload = UpdateStreamReaderOnLoad;
67                 UpdateStreamReaderRequest.onerror = UpdateStreamReaderOnError;
68                 UpdateStreamReaderRequest.open("GET", url_updates, true);
69                 UpdateStreamReaderRequest.send(null);
70                 UpdateStreamReaderPollTimer = setInterval(UpdateStreamReaderLatestResponse, 500);
71         }
72 }
73   
74 function UpdateStreamReaderLatestResponse() {
75         var allMessages = UpdateStreamReaderRequest.responseText;
76         do {
77                 var unprocessed = allMessages.substring(UpdateStreamReaderNextReadPos);
78                 var messageXMLEndIndex = unprocessed.indexOf("\n");
79                 
80                 if (messageXMLEndIndex!=-1) {
81                         var endOfFirstMessageIndex = messageXMLEndIndex + "\n".length;
82                         var anUpdate = unprocessed.substring(0, endOfFirstMessageIndex);
83         
84                         var re = new RegExp("<script>parent\.(.*)</script>");
85                         anUpdate = re.exec(anUpdate);
86
87                         if(anUpdate != null){
88                                 if (anUpdate.length == 2){
89                                         eval(anUpdate[1]);
90                                 }
91                         }
92                         
93                         UpdateStreamReaderNextReadPos += endOfFirstMessageIndex;
94                 }
95                 if(UpdateStreamReaderNextReadPos > 65000){
96                         UpdateStreamReaderRequest.abort();
97                         UpdateStreamReaderStart();
98                         messageXMLEndIndex = -1;
99                 }
100         } while (messageXMLEndIndex != -1);
101 }
102
103 function UpdateStreamReaderOnLoad(){
104         window.clearInterval(UpdateStreamReaderPollTimer);
105         debug("UpdateStreamReaderOnLoad");
106         Dialog.confirm(
107                 "Live Update Stream ends!<br><br>You will not receive any Update from Enigma2.<br>Should I reconnect?",
108                  {windowParameters: {width:300, className: windowStyle},
109                         okLabel: "reconnect",
110                         buttonClass: "myButtonClass",
111                         cancel: function(win) {debug("cancel confirm panel")},
112                         ok: function(win) {UpdateStreamReaderStart(); return true;}
113                         }
114                 );
115 }
116 function UpdateStreamReaderOnError(){
117         // TODO: change this, because it will be called on 'PageUnload' while the request is still running
118         debug("UpdateStreamReaderOnError");
119         window.clearInterval(UpdateStreamReaderPollTimer);
120         Dialog.confirm(
121                 "Live Update Stream has an Error!<br><br>You will not receive any Update from Enigma2.<br>Should I try to reconnect?",
122                  {windowParameters: {width:300, className: windowStyle},
123                          okLabel: "reconnect",
124                          buttonClass: "myButtonClass",
125                          cancel: function(win) {debug("cancel confirm panel")},
126                          ok: function(win) {UpdateStreamReaderStart(); return true;}
127                         }
128                 );
129 }
130
131 //end UpdateStreamReader
132
133 function openWindow(title, inner, width, height, id){
134                         if(id == null) id = new Date().toUTCString();
135                         
136                         //debug(id);
137                         var win = new Window(id, {className: windowStyle, title: title, width: width, height: height});
138                         win.getContent().innerHTML = inner;
139                         win.setDestroyOnClose();
140                         win.showCenter();
141                         debug("opening Window: "+title);
142                         return win;
143 }
144
145 function messageBox(t, m){
146         Dialog.alert(m, {windowParameters: {title: t, className: windowStyle, width:200}, okLabel: "Close"});
147 }
148
149 //RND Template Function (http://www.amix.dk)
150
151 function RND(tmpl, ns) {
152         var fn = function(w, g) {
153                 g = g.split("|");
154                 var cnt = ns[g[0]];
155
156                 //Support for filter functions
157                 for(var i=1; i < g.length; i++) {
158                         cnt = eval(g[i])(cnt);
159                 }
160                 return cnt || w;
161         };
162         return tmpl.replace(/%\(([A-Za-z0-9_|.]*)\)/g, fn);
163 }
164
165 function debug(text){
166         if(DBG){
167                 try{
168                         debugWin.getContent().innerHTML += "DEBUG: "+text+"<br>";
169                 } catch (windowNotPresent) {}
170         }
171 }
172
173 function showhide(id){
174         o = document.getElementById(id).style;
175         o.display = (o.display!="none")? "none":"";
176 }
177
178 function set(what, value){
179         //debug(what+"-"+value);
180         element = parent.document.getElementById(what);
181         if (element){
182                 element.innerHTML = value;
183         }
184         if(navigator.userAgent.indexOf("MSIE") >=0) {
185                 elementscript= $('UpdateStreamReaderIEFixIFrame').document.getElementById('scriptzone');
186                 if(elementscript){
187                         elementscript.innerHTML = ""; // deleting set() from page, to keep the page short and to save memory                    
188                 }
189         }
190 }
191 // requestindikator
192 var requestcounter = 0;
193
194 function requestIndicatorUpdate(){
195         //debug(requestcounter+" open requests");
196         if(requestcounter>=1){
197                 $('RequestIndicator').style.display = "inline";
198         }else{
199                 $('RequestIndicator').style.display = "none";
200         }
201 }
202 function requestStarted(){
203         requestcounter +=1;
204         requestIndicatorUpdate();
205 }
206 function requestFinished(){
207         requestcounter -=1;
208         requestIndicatorUpdate();
209 }
210 // end requestindikator
211
212 function doRequest(url, readyFunction){
213         requestStarted();
214         //var password = "";
215         //var username = "";
216         debug(url);
217         new Ajax.Request(url,
218                 {
219                         method: 'get',
220                         requestHeaders: ['Pragma', 'no-cache', 'Cache-Control', 'must-revalidate', 'If-Modified-Since', 'Sat, 1 Jan 2000 00:00:00 GMT'],
221                         onSuccess: readyFunction,
222                         onComplete: requestFinished 
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 = document.getElementById('_MakeAUniqueID');
237                 document.body.removeChild(document.getElementById('_MakeAUniqueID'));
238         } else {
239                 debug("Your Browser Sucks!");
240         }
241         return xmlDoc;
242 }
243
244 function zap(servicereference){
245         var url = "/web/zap?ZapTo=" + servicereference;
246         new Ajax.Request( url,
247                 {
248                         method: 'get'                           
249                 });
250 }
251 //+++++++++++++++++++++++++++++++++++++++++++++++++++++
252 //+++++++++++++++++++++++++++++++++++++++++++++++++++++
253 //++++       SignalPanel                           ++++
254 //+++++++++++++++++++++++++++++++++++++++++++++++++++++
255 //+++++++++++++++++++++++++++++++++++++++++++++++++++++
256
257 function initSignalPanel(){
258         $('SignalPanel').innerHTML = tplSignalPanelButton;
259 }
260 function openSignalDialog(){
261         openWindow("Signal Info",tplSignalPanel, 215, 75);
262 }
263
264 //+++++++++++++++++++++++++++++++++++++++++++++++++++++
265 //+++++++++++++++++++++++++++++++++++++++++++++++++++++
266 //++++ EPG functions                               ++++
267 //+++++++++++++++++++++++++++++++++++++++++++++++++++++
268 //+++++++++++++++++++++++++++++++++++++++++++++++++++++
269 function loadEPGBySearchString(string){
270                 doRequest(url_epgsearch+string,incomingEPGrequest);
271 }
272 function loadEPGByServiceReference(servicereference){
273                 doRequest(url_epgservice+servicereference,incomingEPGrequest);
274 }
275 function incomingEPGrequest(request){
276         debug("incoming request" +request.readyState);          
277         if (request.readyState == 4){
278                 var EPGItems = new EPGList(getXML(request)).getArray(true);
279                 debug("have "+EPGItems.length+" e2events");
280                 if(EPGItems.length > 0){                        
281                         var html = tplEPGListHeader;
282                         for (var i=0; i < EPGItems.length; i++){
283                                 try{
284                                         var item = EPGItems[i];                         
285                                         //Create JSON Object for Template
286                                         var namespace = {       
287                                                         'date': item.getTimeDay(), 
288                                                         'eventid': item.getEventId(), 
289                                                         'servicereference': item.getServiceReference(), 
290                                                         'servicename': item.getServiceName(), 
291                                                         'title': item.getTitle(),
292                                                         'titleESC': escape(item.getTitle()),
293                                                         'starttime': item.getTimeStartString(), 
294                                                         'duration': Math.ceil(item.getDuration()/60000), 
295                                                         'description': item.getDescription(), 
296                                                         'endtime': item.getTimeEndString(), 
297                                                         'extdescription': item.getDescriptionExtended()
298                                                 };
299                                         //Fill template with data and add id to our result
300                                         html += RND(tplEPGListItem, namespace);
301                                 } catch (blubb) { debug("Error rendering: "+blubb);     }
302                         }               
303                         html += tplEPGListFooter;
304                         openWindow("Electronic Program Guide", html, 900, 500);
305                 } else {
306                         messageBox('No Items found!', 'Sorry but i could not find any EPG Content containing your search value');
307                 }
308         }
309 }
310         
311
312 /////////////////////////
313
314 function loadServiceEPGNowNext(servicereference){
315         var url = url_epgnow+servicereference;
316         doRequest(url, incomingServiceEPGNowNext);      
317 }
318
319 function incomingServiceEPGNowNext(request){
320         if(request.readyState == 4){
321                 var epgevents = getXML(request).getElementsByTagName("e2eventlist").item(0).getElementsByTagName("e2event");
322                 for (var c =0; c < epgevents.length;c++){
323                         var eventnow = new EPGEvent(epgevents.item(c));
324                         
325                         if (eventnow.getEventId() != 'None'){
326                                 buildServiceListEPGItem(eventnow,"NOW");
327                         }
328                 }
329         }
330 }
331 function buildServiceListEPGItem(epgevent,nownext){
332         var e = $(epgevent.getServiceReference()+'EPG'+nownext);
333                 try{
334                         var namespace = {       
335                                 'starttime': epgevent.getTimeStartString(), 
336                                 'title': epgevent.getTitle(), 
337                                 'length': Math.ceil(epgevent.duration/60) 
338                         };
339                         e.innerHTML = RND(tplServiceListEPGItem, namespace);
340                 } catch (blubb) {
341                         debug("Error rendering: "+blubb);
342                 }       
343 }
344 ///////////////////
345
346
347 //+++++++++++++++++++++++++++++++++++++++++++++++++++++
348 //+++++++++++++++++++++++++++++++++++++++++++++++++++++
349 //++++ GUI functions                               ++++
350 //+++++++++++++++++++++++++++++++++++++++++++++++++++++
351 //+++++++++++++++++++++++++++++++++++++++++++++++++++++
352
353 var currentBodyMainElement = null
354
355 function setBodyMainContent(newelementname){
356         newelement =document.getElementById(newelementname);
357         if(currentBodyMainElement != null){
358                 currentBodyMainElement.style.display = "none";
359                 
360         }
361         newelement.style.display = "";
362         currentBodyMainElement = newelement;
363 }
364
365 //+++++++++++++++++++++++++++++++++++++++++++++++++++++
366 //+++++++++++++++++++++++++++++++++++++++++++++++++++++
367 //++++ volume functions                            ++++
368 //+++++++++++++++++++++++++++++++++++++++++++++++++++++
369 //+++++++++++++++++++++++++++++++++++++++++++++++++++++
370
371 function initVolumePanel(){
372         document.getElementById('VolumePanel').innerHTML = tplVolumePanel;
373         getVolume(); 
374 }
375 function getVolume()
376 {
377         doRequest(url_getvolume,handleVolumeRequest);
378 }
379 function volumeSet(newvalue)
380 {
381         doRequest(url_setvolume+newvalue,handleVolumeRequest);
382 }
383 function volumeUp()
384 {
385         doRequest(url_volumeup,handleVolumeRequest);
386 }
387 function volumeDown()
388 {
389         doRequest(url_volumedown,handleVolumeRequest);  
390 }
391 function volumeMute()
392 {
393         doRequest(url_volumemute,handleVolumeRequest);
394 }
395 function handleVolumeRequest(request){
396         if (request.readyState == 4) {
397                 var b = getXML(request).getElementsByTagName("e2volume");
398                 var newvalue = b.item(0).getElementsByTagName('e2current').item(0).firstChild.data;
399                 var mute = b.item(0).getElementsByTagName('e2ismuted').item(0).firstChild.data;
400                 debug("volume"+newvalue+";"+mute);
401                 
402                 for (var i = 1; i <= 10; i++)
403                 {
404                         if ( (newvalue/10)>=i){
405                                 $("volume"+i).src = "/webdata/gfx/led_on.png";
406                         }else{
407                                 $("volume"+i).src = "/webdata/gfx/led_off.png";
408                         }
409                 }
410                 if (mute == "False"){
411                         $("speaker").src = "/webdata/gfx/speak_on.png";
412                 }else{
413                         $("speaker").src = "/webdata/gfx/speak_off.png";
414                 }
415         }       
416 }
417 //+++++++++++++++++++++++++++++++++++++++++++++++++++++
418 //+++++++++++++++++++++++++++++++++++++++++++++++++++++
419 //++++ bouquet managing functions                  ++++
420 //+++++++++++++++++++++++++++++++++++++++++++++++++++++
421 //+++++++++++++++++++++++++++++++++++++++++++++++++++++
422 function initChannelList(){
423         //debug("init ChannelList");    
424         var url = url_fetchchannels+encodeURIComponent(bouqet_tv);
425         doRequest(url, incomingTVBouquetList);
426
427         var url = url_fetchchannels+encodeURIComponent(bouqet_radio);
428         doRequest(url, incomingRadioBouquetList);
429
430         var url = url_fetchchannels+encodeURIComponent(bouqet_provider_tv);
431         doRequest(url, incomingProviderTVBouquetList);
432
433         var url = url_fetchchannels+encodeURIComponent(bouqet_provider_radio);
434         doRequest(url, incomingProviderRadioBouquetList);
435         
436         //getSettings();
437 }
438
439 var servicereftoloadepgnow="";
440 function loadBouquet(servicereference){ 
441         debug("loading bouquet with "+servicereference);
442         servicereftoloadepgnow = servicereference;
443         doRequest(url_fetchchannels+servicereference, incomingChannellist);
444 }
445
446 function incomingTVBouquetList(request){
447         if (request.readyState == 4) {
448                 var list0 = new ServiceList(getXML(request)).getArray();
449                 debug("have "+list0.length+" TV Bouquet ");     
450                 $('accordionMenueBouquetContentTV').innerHTML = renderBouquetTable(list0,tplBouquetListHeader,tplBouquetListItem,tplBouquetListFooter);
451                 //loading first entry of TV Favorites as default for ServiceList
452                 loadBouquet(list0[0].getServiceReference());
453         }
454 }
455 function incomingRadioBouquetList(request){
456         if (request.readyState == 4) {
457                 var list1 = new ServiceList(getXML(request)).getArray();
458                 debug("have "+list1.length+" Radio Bouquet ");  
459                 $('accordionMenueBouquetContentRadio').innerHTML = renderBouquetTable(list1,tplBouquetListHeader,tplBouquetListItem,tplBouquetListFooter);
460         }       
461 }
462 function incomingProviderTVBouquetList(request){
463         if (request.readyState == 4) {
464                 var list2 = new ServiceList(getXML(request)).getArray();
465                 debug("have "+list2.length+" TV Provider Bouquet ");    
466                 $('accordionMenueBouquetContentProviderTV').innerHTML = renderBouquetTable(list2,tplBouquetListHeader,tplBouquetListItem,tplBouquetListFooter);
467         }       
468 }
469 function incomingProviderRadioBouquetList(request){
470         if (request.readyState == 4) {
471                 var list2 = new ServiceList(getXML(request)).getArray();
472                 debug("have "+list2.length+" Radio Provider Bouquet "); 
473                 $('accordionMenueBouquetContentProviderRadio').innerHTML = renderBouquetTable(list2,tplBouquetListHeader,tplBouquetListItem,tplBouquetListFooter);
474         }       
475 }
476
477 function renderBouquetTable(bouquet,templateHeader,templateItem,templateFooter){
478         debug("renderBouquetTable with "+bouquet.length+" Bouqet");     
479         var html = templateHeader;
480         for (var i=0; i < bouquet.length; i++){
481                 try{
482                         var namespace = {
483                                 'servicereference': bouquet[i].getServiceReference(), 
484                                 'bouquetname': bouquet[i].getServiceName()
485                         };
486                         html += RND(templateItem, namespace);
487                 } catch (blubb) {}
488         }
489         html += templateFooter;
490         return html;
491 }       
492
493 function incomingChannellist(request){
494         if(request.readyState == 4){
495                 var services = new ServiceList(getXML(request)).getArray();
496                 listerHtml      = tplServiceListHeader;         
497                 debug("got "+services.length+" Services");
498                 for ( var i = 0; i < services.length ; i++){
499                         var reference = services[i];
500                         var namespace = {       
501                                 'servicereference': reference.getServiceReference(),
502                                 'servicename': reference.getServiceName() 
503                         };
504                         listerHtml += RND(tplServiceListItem, namespace);
505                 }               
506                 listerHtml += tplServiceListFooter;
507                 document.getElementById('BodyContentChannellist').innerHTML = listerHtml;
508                 setBodyMainContent('BodyContentChannellist');
509                 loadServiceEPGNowNext(servicereftoloadepgnow);
510         }
511 }
512 // Movies
513 function loadMovieList(){
514         debug("loading movies");
515         doRequest(url_movielist, incomingMovieList);    
516 }
517
518 function incomingMovieList(request){
519         if(request.readyState == 4){
520                 var movies = new MovieList(getXML(request)).getArray();
521                 debug("have "+movies.length+" movies");
522                 listerHtml      = tplMovieListHeader;           
523                 for ( var i = 0; i <movies.length; i++){
524                         var movie = movies[i];
525                         var namespace = {       
526                                 'servicereference': movie.getServiceReference(),
527                                 'servicename': movie.getServiceName() ,
528                                 'title': movie.getTitle(), 
529                                 'description': movie.getDescription(), 
530                                 'descriptionextended': movie.getDescriptionExtended(), 
531                                 'tags': movie.getTags().join(', ') 
532                         };
533                         debug(movie.getServiceReference());
534                         listerHtml += RND(tplMovieListItem, namespace);
535                 }
536                 listerHtml += tplMovieListFooter;
537                 document.getElementById('BodyContentChannellist').innerHTML = listerHtml;
538                 setBodyMainContent('BodyContentChannellist');
539                 
540         }               
541 }
542
543 // Timer
544 function addTimerByID(serviceRef,eventID,justplay){
545         debug("adding timer by eventid="+eventID+" for "+serviceRef);justplay
546         doRequest(url_timeraddbyeventid+"?serviceref="+serviceRef+"&eventid="+eventID+"&justplay="+justplay, incomingTimerAddResult);   
547 }
548 function incomingTimerAddResult(request){
549         debug("onTimerAdded");
550         if(request.readyState == 4){
551                 var addresult = new TimerAddResult(getXML(request));
552                 if(addresult.getState()){
553                         //timer was add
554                         loadTimerList();
555                 }else{
556                         messageBox("Timer Error","your Timer could not be added!\nReason: "+addresult.getStateText());
557                 }
558         }               
559 }
560 function loadTimerList(){
561         debug("loading timers");
562         doRequest(url_timerlist, incomingTimerList);    
563 }
564
565 function incomingTimerList(request){
566         if(request.readyState == 4){
567                 var timers = new TimerList(getXML(request)).getArray();
568                 debug("have "+timers.length+" timer");
569                 listerHtml      = tplTimerListHeader;
570                 
571                 var aftereventReadable = new Array ('Nothing', 'Standby', 'Deepstandby/Shutdown');
572                 var justplayReadable = new Array('record', 'zap');
573
574                 for ( var i = 0; i <timers.length; i++){
575                         var timer = timers[i];
576                         var beginDate = new Date(Number(timer.getTimeBegin())*1000);
577                         var endDate = new Date(Number(timer.getTimeEnd())*1000);
578                         debug("justplay("+timer.getJustplay()+")");
579                         var namespace = {       
580                                 'servicereference': timer.getServiceReference(),
581                                 'servicename': timer.getServiceName() ,
582                                 'title': timer.getName(), 
583                                 'description': timer.getDescription(), 
584                                 'descriptionextended': timer.getDescriptionExtended(), 
585                                 'begin': timer.getTimeBegin(),
586                                 'beginDate': beginDate.toLocaleString(),
587                                 'end': timer.getTimeEnd(),
588                                 'endDate': endDate.toLocaleString(),
589                                 'state': timer.getState(),
590                                 'duration': Math.ceil((timer.getDuration()/60)),
591                                 'repeated': timer.getRepeated(),
592                                 'repeatedReadable': repeatedReadable(timer.getRepeated()),
593                                 'justplay': timer.getJustplay(),
594                                 'justplayReadable': justplayReadable[Number(timer.getJustplay())],
595                                 'afterevent': timer.getAfterevent(),
596                                 'aftereventReadable': aftereventReadable[Number(timer.getAfterevent())],
597                                 'color': colorTimerListEntry( timer.getState() )
598                         };
599                         listerHtml += RND(tplTimerListItem, namespace);
600                 }
601                 listerHtml += tplTimerListFooter;
602                 document.getElementById('BodyContentChannellist').innerHTML = listerHtml;
603                 setBodyMainContent('BodyContentChannellist');
604         }
605 }
606 function repeatedReadable(num) {
607         num = Number(num);
608         
609         if(num == 0) {
610                 return "One Time";
611         }
612         
613         var html = "";
614         
615         var Repeated = new Object();
616         Repeated["Mo-Su"] =127;
617         Repeated["Su"] =    64;
618         Repeated["Sa"] =    32;
619         Repeated["Mo-Fr"] = 31;
620         Repeated["Fr"] =    16;
621         Repeated["Th"] =     8;
622         Repeated["We"] =     4;
623         Repeated["Tu"] =     2;
624         Repeated["Mo"] =     1;
625         
626         for(rep in Repeated) {
627                 if(rep.toString() != "extend") {
628                         var check = Number(Repeated[rep]);
629                         if(check <= num) {
630                                 num -= check;
631                                 if(html == "") {
632                                         html += rep.toString();
633                                 } else {
634                                         html += "," + rep.toString();
635                                 }
636                         }
637                 }
638         }
639         return html;
640 }
641
642 function colorTimerListEntry (state) {
643         if (state == 0) {
644                 return "000000";
645         } else if(state == 1) {
646                 return "00BCBC";
647         } else if(state == 2) {
648                 return "9F1919";
649         } else {
650                 return "00BCBC";
651         }
652 }
653 function delTimer(serviceRef,begin,end){
654         debug(url_timerdelete+"?serviceref="+serviceRef+"&begin="+begin+"&end="+end);
655         doRequest(url_timerdelete+"?serviceref="+serviceRef+"&begin="+begin+"&end="+end, incomingTimerDelResult);       
656 }
657
658 function incomingTimerDelResult(request){
659         debug("onTimerDeleted");
660         if(request.readyState == 4){
661                 var delresult = new TimerAddResult(getXML(request));
662                 debug("Lade liste");
663                 loadTimerList();
664         }               
665 }
666
667 // send Messages
668 function showMessageSendForm(){
669                 document.getElementById('BodyContentChannellist').innerHTML = tplMessageSendForm;
670 }
671 function sendMessage(messagetext,messagetype,messagetimeout){
672         if(!messagetext){
673                 messagetext = $('MessageSendFormText').value;
674         }       
675         if(!messagetimeout){
676                 messagetimeout = $('MessageSendFormTimeout').value;
677         }       
678         if(!messagetype){
679                 var index = $('MessageSendFormType').selectedIndex;
680                 messagetype = $('MessageSendFormType').options[index].value;
681         }       
682         doRequest(url_message+'?text='+messagetext+'&type='+messagetype+'&timeout='+messagetimeout, incomingMessageResult);
683 }
684 function incomingMessageResult(request){
685
686         if(request.readyState== 4){
687                 var b = getXML(request).getElementsByTagName("e2message");
688                 var result = b.item(0).getElementsByTagName('e2result').item(0).firstChild.data;
689                 var resulttext = b.item(0).getElementsByTagName('e2resulttext').item(0).firstChild.data;
690                 if (result=="True"){
691                         messageBox('message send','message send successfully! it appears on TV-Screen');
692                 }else{
693                         messageBox('message send failed',resulttext);
694                 }
695         }               
696 }
697
698 // PowerState Code
699 function showPowerStateSendForm(){
700                 document.getElementById('BodyContentChannellist').innerHTML = tplPowerStateSendForm;
701 }
702 function sendPowerState(newState){
703         doRequest(url_powerstate+'?newstate='+newState, incomingPowerStateResult);
704 }
705 function incomingPowerStateResult(request){
706         debug(request.readyState);
707         if(request.readyState == 4){
708                 var b = getXML(request).getElementsByTagName("e2powerstate");
709                 var result = b.item(0).getElementsByTagName('e2result').item(0).firstChild.data;
710                 var resulttext = b.item(0).getElementsByTagName('e2resulttext').item(0).firstChild.data;
711                 var tplPowerStateSendForm2 = '<h1>PowerState is changing to:'+resulttext+ '</h1>' + tplPowerStateSendForm;
712                 document.getElementById('BodyContentChannellist').innerHTML = tplPowerStateSendForm2;
713         } else {
714                 document.getElementById('BodyContentChannellist').innerHTML = "<h1>some unknown error</h1>" + tplPasswordSendForm;
715         }
716 }
717
718 // RemoteControl Code
719 function showRemoteControllSendForm(){
720                 document.getElementById('BodyContentChannellist').innerHTML = tplRemoteControlForm;
721 }
722 function sendRemoteControlRequest(command){
723         doRequest(url_remotecontrol+'?command='+command, incomingRemoteControlResult);
724 }
725 function incomingRemoteControlResult(request){
726         if(request.readyState == 4){
727                 var b = getXML(request).getElementsByTagName("e2remotecontrol");
728                 var result = b.item(0).getElementsByTagName('e2result').item(0).firstChild.data;
729                 var resulttext = b.item(0).getElementsByTagName('e2resulttext').item(0).firstChild.data;
730                 showRemoteControllSendForm();
731         } else {
732                 document.getElementById('BodyContentChannellist').innerHTML = "<h1>some unknown error</h1>" + tplRemoteControlForm;
733         }
734 }
735
736 function loadTimerFormNow() {
737         var now = new Date();
738         addTimerEditFormObject["syear"] = now.getFullYear();
739         addTimerEditFormObject["smonth"] = now.getMonth() + 1;
740         addTimerEditFormObject["sday"] = now.getDate();
741         addTimerEditFormObject["shour"] = now.getHours();
742         addTimerEditFormObject["smin"] = now.getMinutes();
743
744         var     plusTwoHours = new Date(now.getTime() + ((120 *60)*1000) );
745         addTimerEditFormObject["eyear"] = plusTwoHours.getFullYear();
746         addTimerEditFormObject["emonth"] = plusTwoHours.getMonth() + 1;
747         addTimerEditFormObject["eday"] = plusTwoHours.getDate();
748         addTimerEditFormObject["ehour"] = plusTwoHours.getHours();
749         addTimerEditFormObject["emin"] = plusTwoHours.getMinutes();
750                 
751         addTimerEditFormObject["justplay"] = "record";
752         addTimerEditFormObject["channel"] = "";
753         addTimerEditFormObject["channelSort"] = "tv";
754         addTimerEditFormObject["name"] = "";
755         addTimerEditFormObject["description"] = "";
756         addTimerEditFormObject["repeated"] = 0;
757         addTimerEditFormObject["afterEvent"] = "0";
758         addTimerEditFormObject["deleteOldOnSave"] = 0;
759         
760         addTimerEditFormObject["beginOld"] = 0;
761         addTimerEditFormObject["endOld"] = 0;
762         
763         
764         debug("loadTimerFormNow 2");
765         loadTimerFormChannels();
766 }
767
768 function loadTimerFormSeconds(justplay,begin,end,repeated,channel,name,description,afterEvent,deleteOldOnSave) {
769
770         var start = new Date(Number(begin)*1000);
771         addTimerEditFormObject["syear"] = start.getFullYear();
772         addTimerEditFormObject["smonth"] = start.getMonth() + 1;
773         addTimerEditFormObject["sday"] = start.getDate();
774         addTimerEditFormObject["shour"] = start.getHours();
775         addTimerEditFormObject["smin"] = start.getMinutes();
776         
777         var     stopp = new Date(Number(end)*1000);
778         addTimerEditFormObject["eyear"] = stopp.getFullYear();
779         addTimerEditFormObject["emonth"] = stopp.getMonth() + 1;
780         addTimerEditFormObject["eday"] = stopp.getDate();
781         addTimerEditFormObject["ehour"] = stopp.getHours();
782         addTimerEditFormObject["emin"] = stopp.getMinutes();
783         
784         addTimerEditFormObject["justplay"] = String(justplay);
785         addTimerEditFormObject["channel"] = decodeURIComponent(String(channel));
786         addTimerEditFormObject["channelSort"] = "";
787         addTimerEditFormObject["name"] = String(name);
788         addTimerEditFormObject["description"] = String(description);
789         addTimerEditFormObject["repeated"] = Number(repeated);
790         addTimerEditFormObject["afterEvent"] = Number(afterEvent);
791         
792         debug(justplay+"|"+begin+"|"+end+"|"+repeated+"|"+channel+"|"+name+"|"+description+"|"+afterEvent);
793
794         addTimerEditFormObject["deleteOldOnSave"] = Number(deleteOldOnSave);
795         addTimerEditFormObject["beginOld"] = Number(begin);
796         addTimerEditFormObject["endOld"] = Number(end);
797         
798         loadTimerFormChannels();
799 }
800
801 // startin to load for TV
802 function loadTimerFormChannels() {
803         if(addTimerEditFormObject["TVListFilled"] == 1 && addTimerEditFormObject["RadioListFilled"] == 1) {
804                 loadTimerForm();
805         } else if(addTimerEditFormObject["TVListFilled"] == 1 && addTimerEditFormObject["RadioListFilled"] == 0) {
806                 addTimerListFormatTV();
807         } else {
808                 var favorites = '1%3A7%3A1%3A0%3A0%3A0%3A0%3A0%3A0%3A0%3AFROM%20BOUQUET%20%22userbouquet.favourites.tv%22%20ORDER%20BY%20bouquet'
809                 doRequest(url_fetchchannels+favorites, addTimerListFormatTV);
810         }
811 }
812
813 function addTimerListFormatTV(request) {
814         if(addTimerEditFormObject["RadioListFilled"] == 0) {
815                 if(request.readyState == 4){
816                         var services = new ServiceList(getXML(request)).getArray();
817                         var tv = new Object();
818                         for ( var i = 0; i < services.length ; i++){
819                                 var reference = services[i];
820                                 tv[reference.servicereference] = reference.servicename;
821                         }
822                         addTimerEditFormObject["TVListFilled"] = 1;
823                         addTimerEditFormObject["TVList"] = tv;
824                 }
825         }
826         if(addTimerEditFormObject["RadioListFilled"] == 1) {
827                 loadTimerForm()
828         } else {
829                 var favorites = '1%3A7%3A1%3A0%3A0%3A0%3A0%3A0%3A0%3A0%3AFROM%20BOUQUET%20%22userbouquet.favourites.radio%22%20ORDER%20BY%20bouquet';
830                 doRequest(url_fetchchannels+favorites, addTimerListFormatRadio);
831         }
832 }
833 function addTimerListFormatRadio(request) {
834         if(request.readyState == 4){
835                 var services = new ServiceList(getXML(request)).getArray();
836                 var radio = new Object();
837                 for ( var i = 0; i < services.length ; i++){
838                         var reference = services[i];
839                         radio[reference.servicereference] = reference.servicename;
840                 }
841                 addTimerEditFormObject["RadioListFilled"] = 1;
842                 addTimerEditFormObject["RadioList"] = radio;
843         }
844         loadTimerForm();
845 }
846
847 function loadTimerForm(){
848
849         var Action = new Object();
850         Action["0"] = "Record";
851         Action["1"] = "Zap";
852         
853         var Repeated = new Object();
854         Repeated["1"] =  "mo";
855         Repeated["2"] = "tu";
856         Repeated["4"] =  "we";
857         Repeated["8"] =  "th";
858         Repeated["16"] = "fr";
859         Repeated["32"] = "sa";
860         Repeated["64"] = "su";
861         Repeated["31"] = "mf";
862         Repeated["127"] ="ms";
863         
864         var AfterEvent = new Object();
865         AfterEvent["0"] = "Nothing";
866         AfterEvent["1"] = "Standby";
867         AfterEvent["2"] = "Deepstandby/Shutdown";
868         
869         addTimerEditFormObject["name"] = (typeof(addTimerEditFormObject["name"]) != "undefined") ? addTimerEditFormObject["name"] : "";
870         addTimerEditFormObject["name"] = (addTimerEditFormObject["name"] == "") ? " " : addTimerEditFormObject["name"];
871
872         addTimerEditFormObject["description"] = (typeof(addTimerEditFormObject["description"]) != "undefined") ? addTimerEditFormObject["description"] : "";
873         addTimerEditFormObject["description"] = (addTimerEditFormObject["description"] == "") ? " " : addTimerEditFormObject["description"];
874
875         var channelObject = addTimerEditFormObject["TVList"];
876         if(     addTimerEditFormObject["channelSort"] == "tv") {
877                 // already set
878         } else if( addTimerEditFormObject["channelSort"] == "radio") {
879                 channelObject = addTimerEditFormObject["RadioList"];
880         } else {
881                 var found = 0;
882                 for( element in addTimerEditFormObject["TVList"]) {
883                         if( element = addTimerEditFormObject["channel"]) {
884                                 // already set
885                                 found = 1;
886                                 break;
887                         }
888                 }
889                 if(found == 0) {
890                         for( element in addTimerEditFormObject["RadioList"]) {
891                                 if( element = addTimerEditFormObject["channel"]) {
892                                         channelObject = addTimerEditFormObject["RadioList"];
893                                         found = 1;
894                                         break;
895                                 }
896                         }
897                 }
898                 if(found == 0) {
899                         addTimerEditFormObject["TVList"][addTimerEditFormObject["channel"]] = "Unknown selected Channel";
900                 }
901         }
902
903         var namespace = {       
904                                 'justplay': addTimerFormCreateOptionList(Action, addTimerEditFormObject["justplay"]),
905                                 'syear': addTimerFormCreateOptions(2007,2010,addTimerEditFormObject["syear"]),
906                                 'smonth': addTimerFormCreateOptions(1,12,addTimerEditFormObject["smonth"]),
907                                 'sday': addTimerFormCreateOptions(1,31,addTimerEditFormObject["sday"]),
908                                 'shour': addTimerFormCreateOptions(0,23,addTimerEditFormObject["shour"]),
909                                 'smin': addTimerFormCreateOptions(0,59,addTimerEditFormObject["smin"]),
910                                 'eyear': addTimerFormCreateOptions(2007,2010,addTimerEditFormObject["eyear"]),
911                                 'emonth': addTimerFormCreateOptions(1,12,addTimerEditFormObject["emonth"]),
912                                 'eday': addTimerFormCreateOptions(1,31,addTimerEditFormObject["eday"]),
913                                 'ehour': addTimerFormCreateOptions(0,23,addTimerEditFormObject["ehour"]),
914                                 'emin': addTimerFormCreateOptions(0,59,addTimerEditFormObject["emin"]),
915                                 'channel': addTimerFormCreateOptionList(channelObject, addTimerEditFormObject["channel"]),
916                                 'name': addTimerEditFormObject["name"],
917                                 'description': addTimerEditFormObject["description"],
918                                 'repeated': addTimerFormCreateOptionListRepeated(Repeated, addTimerEditFormObject["repeated"]),
919                                 'deleteOldOnSave': addTimerEditFormObject["deleteOldOnSave"],
920                                 'channelOld': addTimerEditFormObject["channel"],
921                                 'beginOld': addTimerEditFormObject["beginOld"],
922                                 'endOld': addTimerEditFormObject["endOld"],
923                                 'afterEvent': addTimerFormCreateOptionList(AfterEvent, addTimerEditFormObject["afterEvent"])
924                 };
925         var listerHtml = RND(tplAddTimerForm, namespace);
926         document.getElementById('BodyContentChannellist').innerHTML = listerHtml;
927
928         // Empty some stuff, but keep others to have the performance
929         var tmp1 = addTimerEditFormObject["RadioList"];
930         var tmp2 = addTimerEditFormObject["TVList"];
931         addTimerEditFormObject = new Object();
932         addTimerEditFormObject["deleteOldOnSave"] = 0;
933         addTimerEditFormObject["RadioList"] = tmp1;
934         addTimerEditFormObject["TVList"] = tmp2;
935         addTimerEditFormObject["TVListFilled"] = 1;
936         addTimerEditFormObject["RadioListFilled"] = 1;
937 }
938
939 function addTimerFormCreateOptions(start,end,number) {
940         var html = '';
941         for(i = start; i <= end; i++) {
942                 var txt = (String(i).length == 1) ? "0" + String(i) : String(i);
943                 var selected =  (i == Number(number)) ? "selected" : " ";
944                 var namespace = {
945                         'value': i,
946                         'txt': txt,
947                         'selected': selected };
948                 html += RND(tplAddTimerFormOptions, namespace);
949         }
950         return html;
951 }
952 function addTimerFormCreateOptionList(object,selected) {
953         html = '';
954         for(var element in object) {
955                 var txt = String(object[element]);
956                 var sel = (element == selected) ? "selected" : " ";
957                 var namespace = {
958                         'value': element,
959                         'txt': txt,
960                         'selected': sel };
961                 if(element != "extend") {
962                         html += RND(tplAddTimerFormOptions, namespace);
963                 }
964         }
965         return html;
966 }
967
968 function addTimerFormChangeTime(which) {
969         var start = new Date( $('syear').value, ($('smonth').value -1), $('sday').value, $('shour').value, $('smin').value, 0);
970         var end = new Date($('eyear').value, ($('emonth').value -1), $('eday').value, $('ehour').value, $('emin').value, 0);
971 //      debug("("+start+")(" + end+")");
972
973         if(start.getTime() > end.getTime()) {
974                 opponent = (which.substr(0,1) == 's') ? 'e' +  which.substr(1, which.length -1) : 's' +  which.substr(1, which.length -1) ;
975                 $(opponent).value = $(which).value;
976         }
977         var all = new Array('year','month','day','hour','min');
978         for(i=0; i < all.length; i++) {
979                 if(which.substr(1, which.length -1) == all[i]) {
980                         addTimerFormChangeTime(which.substr(0,1) + all[i+1] );
981                         break;
982                 }
983         }
984 }
985 function addTimerFormChangeType() {
986         var selected = ($('tvradio').checked == true) ? addTimerEditFormObject["TVList"]: addTimerEditFormObject["RadioList"];
987         for (i = $('channel').options.length; i != 0; i--) {
988                 $('channel').options[i - 1] = null;
989         }
990         var i = -1;
991         for(element in selected) {
992                 if(element != "extend") {
993                         i++;
994                         $('channel').options[i] = new Option(selected[element]);
995                         $('channel').options[i].value = element;
996                 }
997         }
998 }
999 function addTimerFormCreateOptionListRepeated(Repeated,repeated) {
1000         var num = Number(repeated);
1001         var html = "";
1002         var html2 = "";
1003         var list = new Array(127, 64, 32, 31, 16, 8, 4, 2, 1);
1004         for(i = 0; i < list.length; i++) {
1005                 var txt = String(Repeated[String(list[i])]);
1006                 if( String(Repeated[String(list[i])]) == "mf") {
1007                         txt = "Mo-Fr";
1008                 } else if( String(Repeated[String(list[i])]) == "ms") {
1009                         txt = "Mo-Su";
1010                 } else {
1011                         txt = txt.substr(0,1).toUpperCase() + txt.substr(1,1);
1012                 }
1013                 var checked = " ";
1014                 if(num >=  list[i]) {
1015                         num -= list[i];
1016                         checked = "checked";
1017                 }
1018                 var namespace = {
1019                         'id': Repeated[String(list[i])],
1020                         'name': Repeated[String(list[i])],
1021                         'value': list[i],
1022                         'txt': txt,
1023                         'checked': checked };
1024                 if(String(Repeated[String(list[i])]) == "mf" || String(Repeated[String(list[i])]) == "ms") {
1025                         html2 = RND(tplAddTimerFormCheckbox, namespace) + html2;
1026                 } else {
1027                         html = RND(tplAddTimerFormCheckbox, namespace) + html;
1028                 }
1029         }
1030         return html + html2;
1031 }
1032 function sendAddTimer() {
1033         var beginD = new Date(ownLazyNumber($('syear').value), (ownLazyNumber($('smonth').value) - 1), ownLazyNumber($('sday').value), ownLazyNumber($('shour').value), ownLazyNumber($('smin').value));
1034         var begin = beginD.getTime()/1000;
1035         
1036         var endD = new Date(ownLazyNumber($('eyear').value), (ownLazyNumber($('emonth').value) - 1), ownLazyNumber($('eday').value), ownLazyNumber($('ehour').value), ownLazyNumber($('emin').value));
1037         var end = endD.getTime()/1000;
1038
1039         var repeated = 0;
1040         if( $('ms').checked ) {
1041                 repeated = 127;
1042         } else if($('mf').checked) {
1043                 repeated = 31;
1044                 if($('sa').checked) {
1045                         repeated += ownLazyNumber($('sa').value);
1046                 }
1047                 if($('su').checked) {
1048                         repeated += ownLazyNumber($('su').value);
1049                 }
1050         } else {
1051                 var check = new Array('mo', 'tu', 'we', 'th', 'fr');
1052                 for(i = 0; i < check.length; i++) {
1053                         if($(check[i]).cheked) {
1054                                 repeated += Number($(check[i]).value);
1055                         }
1056                 }
1057         }
1058         
1059         /*if(ownLazyNumber($('deleteOldOnSave').value) == 1) {
1060                 delTimer($('channelOld').value,$('beginOld').value,$('endOld').value);
1061         }*/
1062         var descriptionClean = ($('descr').value == " " || $('descr').value == "N/A") ? "" : $('descr').value;
1063         var nameClean = ($('name').value == " " || $('name').value == "N/A") ? "" : $('name').value;
1064         
1065         var repeated = 0;
1066         if($('ms').checked) {
1067                 repeated = ownLazyNumber($('ms').value);
1068         } else if($('mf').checked) {
1069                 repeated = ownLazyNumber($('mf').value);
1070                 if($('su').checked) {
1071                         repeated += ownLazyNumber($('su').value);
1072                 }
1073                 if($('sa').checked) {
1074                         repeated += ownLazyNumber($('sa').value);
1075                 }
1076         } else {
1077                 if($('mo').checked) {
1078                         repeated += ownLazyNumber($('mo').value);
1079                 }
1080                 if($('tu').checked) {
1081                         repeated += ownLazyNumber($('tu').value);
1082                 }
1083                 if($('we').checked) {
1084                         repeated += ownLazyNumber($('we').value);
1085                 }
1086                 if($('th').checked) {
1087                         repeated += ownLazyNumber($('th').value);
1088                 }
1089                 if($('fr').checked) {
1090                         repeated += ownLazyNumber($('fr').value);
1091                 }
1092                 if($('sa').checked) {
1093                         repeated += ownLazyNumber($('sa').value);
1094                 }
1095                 if($('su').checked) {
1096                         repeated += ownLazyNumber($('su').value);
1097                 }
1098         }
1099         debug(repeated);
1100         doRequest(url_timerchange+"?"+"serviceref="+$('channel').value+"&begin="+begin
1101          +"&end="+end+"&name="+nameClean+"&description="+descriptionClean
1102          +"&afterevent="+$('after_event').value+"&eit=0&disabled=0"
1103          +"&justplay="+ownLazyNumber($('justplay').value)+"&repeated="+repeated
1104          +"&channelOld="+$('channelOld').value
1105          +"&beginOld="+$('beginOld').value+"&endOld="+$('endOld').value
1106          +"&deleteOldOnSave="+ownLazyNumber($('deleteOldOnSave').value), incomingTimerAddResult);
1107         
1108 }
1109
1110 function getSettings(){
1111         doRequest(url_settings, incomingGetSettings);
1112 }
1113
1114 function incomingGetSettings(request){
1115         if(request.readyState == 4){
1116                 settings = new Settings(getXML(request)).getArray();
1117 /*              for ( var i = 0; i <settings.length; i++){
1118                         var setting = settings[i];
1119                         debug(setting.getSettingValue() +":" + setting.getSettingName());
1120                 }*/
1121                 
1122         }               
1123 }
1124 function ownLazyNumber(num) {
1125         if(isNaN(num)){
1126                 return 0;
1127         } else {
1128                 return Number(num);
1129         }
1130 }