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