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