edit timer is now functional
[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_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                                 'repeated': timer.getRepeated(),
569                                 'justplay': timer.getJustplay(),
570                                 'color': colorTimerListEntry( timer.getState() )
571                         };
572                         listerHtml += RND(tplTimerListItem, namespace);
573                 }
574                 listerHtml += tplTimerListFooter;
575                 document.getElementById('BodyContentChannellist').innerHTML = listerHtml;
576                 setBodyMainContent('BodyContentChannellist');
577         }
578 }
579
580 function colorTimerListEntry (state) {
581         if (state == 0) {
582                 return "000000";
583         } else if(state == 1) {
584                 return "00BCBC";
585         } else if(state == 2) {
586                 return "9F1919";
587         } else {
588                 return "00BCBC";
589         }
590 }
591 function delTimer(serviceRef,begin,end){
592         debug("deleting timer with serviceRef="+serviceRef+" and start="+begin+"end="+end );
593         debug(url_timerdelete+"?serviceref="+serviceRef+"&begin="+begin+"&end="+end);
594         doRequest(url_timerdelete+"?serviceref="+serviceRef+"&begin="+begin+"&end="+end, incomingTimerDelResult);       
595 }
596
597 function incomingTimerDelResult(request){
598         debug("onTimerDeleted");
599         debug(request.readyState);
600         if(request.readyState == 4){
601                 var delresult = new TimerAddResult(getXML(request));
602                 debug("Lade liste");
603                 loadTimerList();
604         }               
605 }
606
607 // send Messages
608 function showMessageSendForm(){
609                 document.getElementById('BodyContentChannellist').innerHTML = tplMessageSendForm;
610 }
611 function sendMessage(messagetext,messagetype,messagetimeout){
612         if(!messagetext){
613                 messagetext = $('MessageSendFormText').value;
614         }       
615         if(!messagetimeout){
616                 messagetimeout = $('MessageSendFormTimeout').value;
617         }       
618         if(!messagetype){
619                 var index = $('MessageSendFormType').selectedIndex;
620                 messagetype = $('MessageSendFormType').options[index].value;
621         }       
622         doRequest(url_message+'?text='+messagetext+'&type='+messagetype+'&timeout='+messagetimeout, incomingMessageResult);
623 }
624 function incomingMessageResult(request){
625
626         if(request.readyState== 4){
627                 var b = getXML(request).getElementsByTagName("e2message");
628                 var result = b.item(0).getElementsByTagName('e2result').item(0).firstChild.data;
629                 var resulttext = b.item(0).getElementsByTagName('e2resulttext').item(0).firstChild.data;
630                 if (result=="True"){
631                         messageBox('message send','message send successfully! it appears on TV-Screen');
632                 }else{
633                         messageBox('message send failed',resulttext);
634                 }
635         }               
636 }
637
638 // PowerState Code
639 function showPowerStateSendForm(){
640                 document.getElementById('BodyContentChannellist').innerHTML = tplPowerStateSendForm;
641 }
642 function sendPowerState(newState){
643         doRequest(url_powerstate+'?newstate='+newState, incomingPowerStateResult);
644 }
645 function incomingPowerStateResult(request){
646         debug(request.readyState);
647         if(request.readyState == 4){
648                 var b = getXML(request).getElementsByTagName("e2powerstate");
649                 var result = b.item(0).getElementsByTagName('e2result').item(0).firstChild.data;
650                 var resulttext = b.item(0).getElementsByTagName('e2resulttext').item(0).firstChild.data;
651                 var tplPowerStateSendForm2 = '<h1>PowerState is changing to:'+resulttext+ '</h1>' + tplPowerStateSendForm;
652                 document.getElementById('BodyContentChannellist').innerHTML = tplPowerStateSendForm2;
653         } else {
654                 document.getElementById('BodyContentChannellist').innerHTML = "<h1>some unknown error</h1>" + tplPasswordSendForm;
655         }
656 }
657
658 // RemoteControl Code
659 function showRemoteControllSendForm(){
660                 document.getElementById('BodyContentChannellist').innerHTML = tplRemoteControlForm;
661 }
662 function sendRemoteControlRequest(command){
663         doRequest(url_remotecontrol+'?command='+command, incomingRemoteControlResult);
664 }
665 function incomingRemoteControlResult(request){
666         debug(request.readyState);
667         if(request.readyState == 4){
668                 var b = getXML(request).getElementsByTagName("e2remotecontrol");
669                 var result = b.item(0).getElementsByTagName('e2result').item(0).firstChild.data;
670                 var resulttext = b.item(0).getElementsByTagName('e2resulttext').item(0).firstChild.data;
671                 showRemoteControllSendForm();
672         } else {
673                 document.getElementById('BodyContentChannellist').innerHTML = "<h1>some unknown error</h1>" + tplRemoteControlForm;
674         }
675 }
676 var addTimerEditFormObject = new Object();
677 addTimerEditFormObject["deleteOldOnSave"] = 0;
678
679 function loadTimerFormNow() {
680         var now = new Date();
681         addTimerEditFormObject["syear"] = now.getFullYear();
682         addTimerEditFormObject["smonth"] = now.getMonth() + 1;
683         addTimerEditFormObject["sday"] = now.getDate();
684         addTimerEditFormObject["shour"] = now.getHours();
685         addTimerEditFormObject["smin"] = now.getMinutes();
686
687         var     plusTwoHours = new Date(now.getTime() + ((120 *60)*1000) );
688         addTimerEditFormObject["eyear"] = plusTwoHours.getFullYear();
689         addTimerEditFormObject["emonth"] = plusTwoHours.getMonth() + 1;
690         addTimerEditFormObject["eday"] = plusTwoHours.getDate();
691         addTimerEditFormObject["ehour"] = plusTwoHours.getHours();
692         addTimerEditFormObject["emin"] = plusTwoHours.getMinutes();
693                 
694         addTimerEditFormObject["record"] = "record";
695         addTimerEditFormObject["channel"] = "";
696         addTimerEditFormObject["channelSort"] = "tv";
697         addTimerEditFormObject["name"] = "";
698         addTimerEditFormObject["description"] = "";
699         addTimerEditFormObject["repeated"] = 0;
700         addTimerEditFormObject["afterEvent"] = "0";
701         
702         loadTimerFormChannels();
703 }
704
705 function loadTimerFormSeconds(action,begin,end,repeated,channel,name,description,afterEvent,deleteOldOnSave) {
706         var start = new Date(Number(begin)*1000);
707         addTimerEditFormObject["syear"] = start.getFullYear();
708         addTimerEditFormObject["smonth"] = start.getMonth() + 1;
709         addTimerEditFormObject["sday"] = start.getDate();
710         addTimerEditFormObject["shour"] = start.getHours();
711         addTimerEditFormObject["smin"] = start.getMinutes();
712         
713         var     stopp = new Date(Number(end)*1000);
714         addTimerEditFormObject["eyear"] = stopp.getFullYear();
715         addTimerEditFormObject["emonth"] = stopp.getMonth() + 1;
716         addTimerEditFormObject["eday"] = stopp.getDate();
717         addTimerEditFormObject["ehour"] = stopp.getHours();
718         addTimerEditFormObject["emin"] = stopp.getMinutes();
719         
720         debug(action+"|"+begin+"|"+end+"|"+repeated+"|"+channel+"|"+name+"|"+description+"|"+afterEvent);
721         addTimerEditFormObject["record"] = String(action);
722         addTimerEditFormObject["channel"] = decodeURIComponent(String(channel));
723         addTimerEditFormObject["channelSort"] = "";
724         addTimerEditFormObject["name"] = String(name);
725         addTimerEditFormObject["description"] = String(description);
726         addTimerEditFormObject["repeated"] = Number(repeated);
727         addTimerEditFormObject["afterEvent"] = String(afterEvent);
728
729         addTimerEditFormObject["deleteOldOnSave"] = deleteOldOnSave;
730         
731         loadTimerFormChannels();
732 }
733
734 // startin to load for TV
735 function loadTimerFormChannels() {
736         if(addTimerEditFormObject["TVListFilled"]) {
737                 // do nothing
738         } else {
739                 var favorites = '1%3A7%3A1%3A0%3A0%3A0%3A0%3A0%3A0%3A0%3AFROM%20BOUQUET%20%22userbouquet.favourites.tv%22%20ORDER%20BY%20bouquet'
740 //              var url = url_fetchchannels+encodeURIComponent(bouqet_tv);
741                 doRequest(url_fetchchannels+favorites, addTimerListFormatTV);
742         }
743 }
744
745 function addTimerListFormatTV(request) {
746         if(request.readyState == 4){
747                 var services = new ServiceList(getXML(request)).getArray();
748                 debug("addTimerListFormatTV got "+services.length+" Services");
749                 var tv = new Object();
750                 for ( var i = 0; i < services.length ; i++){
751                         var reference = services[i];
752                         tv[reference.servicereference] = reference.servicename;
753                 }
754                 addTimerEditFormObject["TVListFilled"] = true;
755                 addTimerEditFormObject["TVList"] = tv;
756         }
757         if(addTimerEditFormObject["RadioListFilled"]) {
758                 // do nothing
759         } else {
760                 var favorites = '1%3A7%3A1%3A0%3A0%3A0%3A0%3A0%3A0%3A0%3AFROM%20BOUQUET%20%22userbouquet.favourites.radio%22%20ORDER%20BY%20bouquet';
761 //              var url = url_fetchchannels+encodeURIComponent(bouqet_radio);
762                 doRequest(url_fetchchannels+favorites, addTimerListFormatRadio);
763         }
764 }
765 function addTimerListFormatRadio(request) {
766         if(request.readyState == 4){
767                 var services = new ServiceList(getXML(request)).getArray();
768                 debug("addTimerListFormatRadio got "+services.length+" Services");
769                 var radio = new Object();
770                 for ( var i = 0; i < services.length ; i++){
771                         var reference = services[i];
772                         radio[reference.servicereference] = reference.servicename;
773                 }
774                 addTimerEditFormObject["RadioListFilled"] = true;
775                 addTimerEditFormObject["RadioList"] = radio;
776         }
777         loadTimerForm();
778 }
779
780 function loadTimerForm(){
781 //action,syear,smonth,sday,shour,smin,eyear,emonth,eday,ehour,emin,repeated,channel,name,description,afterEvent 
782         var Action = new Object();
783         Action["record"] = "Record";
784         Action["zap"] = "Zap";
785         
786         var Repeated = new Object();
787         Repeated["1"] =  "mo";
788         Repeated["2"] = "tu";
789         Repeated["4"] =  "we";
790         Repeated["8"] =  "th";
791         Repeated["16"] = "fr";
792         Repeated["32"] = "sa";
793         Repeated["64"] = "su";
794         Repeated["31"] = "mf";
795         Repeated["127"] ="ms";
796         
797         var AfterEvent = new Object();
798         AfterEvent["0"] = "Nothing";
799         AfterEvent["1"] = "Standby";
800         AfterEvent["2"] = "Deepstandby/Shutdown";
801         
802         addTimerEditFormObject["name"] = (typeof(addTimerEditFormObject["name"]) != "undefined") ? addTimerEditFormObject["name"] : "";
803         addTimerEditFormObject["name"] = (addTimerEditFormObject["name"] == "") ? " " : addTimerEditFormObject["name"];
804
805         addTimerEditFormObject["description"] = (typeof(addTimerEditFormObject["description"]) != "undefined") ? addTimerEditFormObject["description"] : "";
806         addTimerEditFormObject["description"] = (addTimerEditFormObject["description"] == "") ? " " : addTimerEditFormObject["description"];
807
808         var channelObject = addTimerEditFormObject["TVList"];
809         if(     addTimerEditFormObject["channelSort"] == "tv") {
810                 // already set
811         } else if( addTimerEditFormObject["channelSort"] == "radio") {
812                 channelObject = addTimerEditFormObject["RadioList"];
813         } else {
814                 var found = 0;
815                 for( element in addTimerEditFormObject["TVList"]) {
816                         if( element = addTimerEditFormObject["channel"]) {
817                                 // already set
818                                 found = 1;
819                                 break;
820                         }
821                 }
822                 if(found == 0) {
823                         for( element in addTimerEditFormObject["RadioList"]) {
824                                 if( element = addTimerEditFormObject["channel"]) {
825                                         channelObject = addTimerEditFormObject["RadioList"];
826                                         found = 1;
827                                         break;
828                                 }
829                         }
830                 }
831                 if(found == 0) {
832                         addTimerEditFormObject["TVList"][addTimerEditFormObject["channel"]] = "Unknown selected Channel";
833                 }
834         }
835
836         var namespace = {       
837                                 'action': addTimerFormCreateOptionList(Action, addTimerEditFormObject["action"]),
838                                 'syear': addTimerFormCreateOptions(2007,2010,addTimerEditFormObject["syear"]),
839                                 'smonth': addTimerFormCreateOptions(1,12,addTimerEditFormObject["smonth"]),
840                                 'sday': addTimerFormCreateOptions(1,31,addTimerEditFormObject["sday"]),
841                                 'shour': addTimerFormCreateOptions(0,23,addTimerEditFormObject["shour"]),
842                                 'smin': addTimerFormCreateOptions(0,59,addTimerEditFormObject["smin"]),
843                                 'eyear': addTimerFormCreateOptions(2007,2010,addTimerEditFormObject["eyear"]),
844                                 'emonth': addTimerFormCreateOptions(1,12,addTimerEditFormObject["emonth"]),
845                                 'eday': addTimerFormCreateOptions(1,31,addTimerEditFormObject["eday"]),
846                                 'ehour': addTimerFormCreateOptions(0,23,addTimerEditFormObject["ehour"]),
847                                 'emin': addTimerFormCreateOptions(0,59,addTimerEditFormObject["emin"]),
848                                 'channel': addTimerFormCreateOptionList(channelObject, addTimerEditFormObject["channel"]),
849                                 'name': addTimerEditFormObject["name"],
850                                 'description': addTimerEditFormObject["description"],
851                                 'repeated': addTimerFormCreateOptionListRepeated(Repeated, addTimerEditFormObject["repeated"]),
852                                 'afterEvent': addTimerFormCreateOptionList(AfterEvent, addTimerEditFormObject["afterEvent"])
853                 };
854                 //.concat(addTimerRadioList)
855         var listerHtml = RND(tplAddTimerForm, namespace);
856         document.getElementById('BodyContentChannellist').innerHTML = listerHtml;
857 //      setBodyMainContent('BodyContentChannellist');
858 }
859
860 function addTimerFormCreateOptions(start,end,number) {
861         var html = '';
862         for(i = start; i <= end; i++) {
863                 var txt = (String(i).length == 1) ? "0" + String(i) : String(i);
864                 if (i == Number(number)) {
865                         html += '<option value="'+ i +'" selected>'+ txt + '</option>';
866                 } else {
867                         html += '<option value="'+ i +'">'+ txt + '</option>';
868                 }
869         }
870         return html;
871 }
872 function addTimerFormCreateOptionList(object,selected) {
873         html = '';
874         for(var element in object) {
875                 var txt = String(object[element]);
876                 if(element == selected) {
877 //                      var txt = (len( String(object[element]) ) == 1) ? "0"+String(object[element]) : String(object[element]);
878                         html += '<option value="'+ element +'" selected>'+ txt + '</option>';
879                 } else if(element == "extend") {
880                 // do nothing.
881                 }else {
882 //                      var txt = (len( String(object[element]) ) == 1) ? "0"+String(object[element]) : String(object[element]);
883                         html += '<option value="'+ element +'">'+ txt + '</option>';
884                 }
885         }
886         return html;
887 }
888
889 function addTimerFormChangeTime(type) {
890         var start = new Date( $('syear').value, $('smonth').value, $('sday').value, $('shour').value, $('smin').value, 0);
891         var end = new Date($('eyear').value, $('emonth').value, $('eday').value, $('ehour').value, $('emin').value, 0);
892         if(start.getTime() > end.getTime()) {
893                 if(type == 's') {
894                         $('eyear').value = $('syear').value;
895                         $('emonth').value = $('smonth').value;
896                         $('eday').value = $('sday').value;
897                         $('ehour').value = $('shour').value;
898                         $('emin').value = $('smin').value;
899                 } else {
900                         $('syear').value = $('eyear').value;
901                         $('smonth').value = $('emonth').value;
902                         $('sday').value = $('eday').value;
903                         $('shour').value = $('ehour').value;
904                         $('smin').value = $('emin').value;
905                 }
906         }
907 }
908 function addTimerFormChangeType() {
909         var selected = ($('tvradio').checked == true) ? addTimerEditFormObject["TVList"]: addTimerEditFormObject["RadioList"];
910         for (i = $('channel').options.length; i != 0; i--) {
911                 $('channel').options[i - 1] = null;
912         }
913         var i = -1;
914         for(element in selected) {
915                 if(element != "extend") {
916                         i++;
917                         $('channel').options[i] = new Option(selected[element]);
918                         $('channel').options[i].value = element;
919                 }
920         }
921 }
922 function addTimerFormCreateOptionListRepeated(Repeated,repeated) {
923         var num = Number(repeated);
924         var html = "";
925         var html2 = "";
926         var list = new Array(127, 64, 32, 31, 16, 8, 4, 2, 1);
927         for(i = 0; i < list.length; i++) {
928                 var txt = String(Repeated[String(list[i])]);
929                 if( String(Repeated[String(list[i])]) == "mf") {
930                         txt = "Mo-Fr";
931                 } else if( String(Repeated[String(list[i])]) == "ms") {
932                         txt = "Mo-Su";
933                 } else {
934                         txt = txt.substr(0,1).toUpperCase() + txt.substr(1,1);
935                 }
936                 if(num >=  list[i]) {
937                         num -= list[i];
938                         if(String(Repeated[String(list[i])]) == "mf" || String(Repeated[String(list[i])]) == "ms") {
939                                 html2 = '<input type="checkbox" id="'+ Repeated[String(list[i])] +'" name="'+ Repeated[String(list[i])] +'" value="'+ list[i] +'" checked>&nbsp;'+ txt +'&nbsp;&nbsp;' + html2;
940                         } else {
941                                 html = '<input type="checkbox" id="'+ Repeated[String(list[i])] +'" name="'+ Repeated[String(list[i])] +'" value="'+ list[i] +'" checked>&nbsp;'+ txt +'&nbsp;&nbsp;' + html;
942                         }
943                 } else {
944                         if(String(Repeated[String(list[i])]) == "mf" || String(Repeated[String(list[i])]) == "ms") {
945                                 html2 = '<input type="checkbox" id="'+ Repeated[String(list[i])] +'" name="'+ Repeated[String(list[i])] +'" value="'+ list[i] +'">&nbsp;'+ txt +'&nbsp;&nbsp;' + html2;
946                         } else {
947                                 html = '<input type="checkbox" id="'+ Repeated[String(list[i])] +'" name="'+ Repeated[String(list[i])] +'" value="'+ list[i] +'">&nbsp;'+ txt +'&nbsp;&nbsp;'  + html;
948                         }
949                 }
950         }
951         return html + html2;
952 }
953 function sendAddTimer() {
954 //action,begin,end,repeated,channel,name,description,afterEvent
955         var beginD = new Date(Number($('syear').value), Number($('smonth').value), Number($('sday').value), Number($('shour').value), Number($('smin').value));
956         var begin = beginD.getTime()/1000;
957         
958         var endD = new Date(Number($('eyear').value), Number($('emonth').value), Number($('eday').value), Number($('ehour').value), Number($('emin').value));
959         var end = endD.getTime()/1000;
960
961         var repeated = 0;
962         if( $('ms').checked ) {
963                 repeated = 127;
964         } else if($('mf').checked) {
965                 repeated = 31;
966                 if($('sa').checked) {
967                         repeated += Number($('sa').value);
968                 }
969                 if($('su').checked) {
970                         repeated += Number($('su').value);
971                 }
972         } else {
973                 var check = new Array('mo', 'tu', 'we', 'th', 'fr');
974                 for(i = 0; i < check.length; i++) {
975                         if($(check[i]).cheked) {
976                                 repeated += Number($(check[i]).value);
977                         }
978                 }
979         }
980
981         justplay = 0;
982         if($('action').value == "zap") {
983                 justplay = 1;
984         }
985         //serviceref,begin,end,name,description,eit,disabled,justplay,afterevent
986 //      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);
987         doRequest(url_timeradd+"?"+"serviceref="+$('channel').value+"&begin="+begin
988          +"&end="+end+"&name="+$('name').value+"&description="+$('descr').value
989          +"&afterevent="+$('after_event').value+"&eit=0&disabled=0"
990          +"&justplay="+justplay, incomingTimerAddResult);
991         
992         if(addTimerEditFormObject["deleteOldOnSave"] == 1) {
993                 delTimer($('channel').value,begin,end);
994         }
995 }