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