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