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