fixed design problems
[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 /*              alert(document.getElementById('scrollContent').style.height);
627                 document.getElementById('scrollContent').style.height = '14.5%';
628                                 alert(document.getElementById('scrollContent').style.height);*/
629                 debug("incomingChannellist " + typeof(loadedChannellist[servicereftoloadepgnow]));
630         }
631 }
632 // Movies
633 function loadMovieList(){
634         debug("loading movies");
635         doRequest(url_movielist, incomingMovieList);    
636 }
637
638 function incomingMovieList(request){
639         if(request.readyState == 4){
640                 var movies = new MovieList(getXML(request)).getArray();
641                 debug("have "+movies.length+" movies");
642                 listerHtml      = tplMovieListHeader;           
643                 for ( var i = 0; i <movies.length; i++){
644                         var movie = movies[i];
645                         var namespace = {       
646                                 'servicereference': movie.getServiceReference(),
647                                 'servicename': movie.getServiceName() ,
648                                 'title': movie.getTitle(), 
649                                 'description': movie.getDescription(), 
650                                 'descriptionextended': movie.getDescriptionExtended(),
651                                 'filelink': String(movie.getFilename()).substr(17,movie.getFilename().length),
652                                 'filename': String(movie.getFilename()),
653                                 'tags': movie.getTags().join(', ') 
654                         };
655                         listerHtml += RND(tplMovieListItem, namespace);
656                 }
657                 listerHtml += tplMovieListFooter;
658                 document.getElementById('BodyContentChannellist').innerHTML = listerHtml;
659                 setBodyMainContent('BodyContentChannellist');
660                 
661         }               
662 }
663 function delMovieFile(file) {
664                 doRequest(url_moviefiledelete+"?filename="+file, incomingDelMovieFileResult, false);    
665 }
666 function incomingDelMovieFileResult(request) {
667         debug("incomingDelMovieFileResult");
668         if(request.readyState == 4){
669                 var delresult = new SimpleXMLResult(getXML(request));
670                 if(delresult.getState()){
671                         loadMovieList();
672                 }else{
673                         messageBox("Deletion Error","Reason: "+delresult.getStateText());
674                 }
675         }               
676 }
677 // Timer
678 function addTimerByID(serviceRef,eventID,justplay){
679         if(parentPin(serviceRef)) {
680                 doRequest(url_timeraddbyeventid+"?serviceref="+serviceRef+"&eventid="+eventID+"&justplay="+justplay, incomingTimerAddResult, false);    
681         }
682 }
683 function incomingTimerAddResult(request){
684         debug("onTimerAdded");
685         if(request.readyState == 4){
686                 var addresult = new SimpleXMLResult(getXML(request));
687                 if(addresult.getState()){
688                         //timer was add
689                         loadTimerList();
690                 }else{
691                         messageBox("Timer Error","your Timer could not be added!\nReason: "+addresult.getStateText());
692                 }
693         }               
694 }
695 function loadTimerList(){
696         doRequest(url_timerlist, incomingTimerList, false);     
697 }
698
699 function incomingTimerList(request){
700         if(request.readyState == 4){
701                 var timers = new TimerList(getXML(request)).getArray();
702                 debug("have "+timers.length+" timer");
703                 listerHtml      = tplTimerListHeader;
704                 
705                 var aftereventReadable = new Array ('Nothing', 'Standby', 'Deepstandby/Shutdown');
706                 var justplayReadable = new Array('record', 'zap');
707                 var OnOff = new Array('on', 'off');
708
709                 for ( var i = 0; i <timers.length; i++){
710                         var timer = timers[i];
711                         var beginDate = new Date(Number(timer.getTimeBegin())*1000);
712                         var endDate = new Date(Number(timer.getTimeEnd())*1000);
713                         debug(timer.getDisabled());
714                         debug(OnOff[Number(timer.getDisabled())]);
715                         var namespace = {       
716                                 'servicereference': timer.getServiceReference(),
717                                 'servicename': timer.getServiceName() ,
718                                 'title': timer.getName(), 
719                                 'description': timer.getDescription(), 
720                                 'descriptionextended': timer.getDescriptionExtended(), 
721                                 'begin': timer.getTimeBegin(),
722                                 'beginDate': beginDate.toLocaleString(),
723                                 'end': timer.getTimeEnd(),
724                                 'endDate': endDate.toLocaleString(),
725                                 'state': timer.getState(),
726                                 'duration': Math.ceil((timer.getDuration()/60)),
727                                 'repeated': timer.getRepeated(),
728                                 'repeatedReadable': repeatedReadable(timer.getRepeated()),
729                                 'justplay': timer.getJustplay(),
730                                 'justplayReadable': justplayReadable[Number(timer.getJustplay())],
731                                 'afterevent': timer.getAfterevent(),
732                                 'aftereventReadable': aftereventReadable[Number(timer.getAfterevent())],
733                                 'disabled': timer.getDisabled(),
734                                 'onOff': OnOff[Number(timer.getDisabled())],
735                                 'color': colorTimerListEntry( timer.getState() )
736                         };
737                         listerHtml += RND(tplTimerListItem, namespace);
738                 }
739                 listerHtml += tplTimerListFooter;
740                 document.getElementById('BodyContentChannellist').innerHTML = listerHtml;
741                 setBodyMainContent('BodyContentChannellist');
742         }
743 }
744 function repeatedReadable(num) {
745         num = Number(num);
746         
747         if(num == 0) {
748                 return "One Time";
749         }
750         
751         var html = "";
752         
753         var Repeated = new Object();
754         Repeated["Mo-Su"] =127;
755         Repeated["Su"] =    64;
756         Repeated["Sa"] =    32;
757         Repeated["Mo-Fr"] = 31;
758         Repeated["Fr"] =    16;
759         Repeated["Th"] =     8;
760         Repeated["We"] =     4;
761         Repeated["Tu"] =     2;
762         Repeated["Mo"] =     1;
763         
764         for(rep in Repeated) {
765                 if(rep.toString() != "extend") {
766                         var check = Number(Repeated[rep]);
767                         if(check <= num) {
768                                 num -= check;
769                                 if(html == "") {
770                                         html += rep.toString();
771                                 } else {
772                                         html += "," + rep.toString();
773                                 }
774                         }
775                 }
776         }
777         return html;
778 }
779
780 function colorTimerListEntry (state) {
781         if (state == 0) {
782                 return "000000";
783         } else if(state == 1) {
784                 return "00BCBC";
785         } else if(state == 2) {
786                 return "9F1919";
787         } else {
788                 return "00BCBC";
789         }
790 }
791 function delTimer(serviceRef,begin,end){
792         debug(url_timerdelete+"?serviceref="+serviceRef+"&begin="+begin+"&end="+end);
793         doRequest(url_timerdelete+"?serviceref="+serviceRef+"&begin="+begin+"&end="+end, incomingTimerDelResult, false);
794 }
795
796 function incomingTimerDelResult(request){
797         debug("onTimerDeleted");
798         if(request.readyState == 4){
799                 var delresult = new SimpleXMLResult(getXML(request));
800                 debug("Lade liste");
801                 loadTimerList();
802         }               
803 }
804
805 // send Messages
806 function showMessageSendForm(){
807                 document.getElementById('BodyContentChannellist').innerHTML = tplMessageSendForm;
808 }
809 function sendMessage(messagetext,messagetype,messagetimeout){
810         if(!messagetext){
811                 messagetext = $('MessageSendFormText').value;
812         }       
813         if(!messagetimeout){
814                 messagetimeout = $('MessageSendFormTimeout').value;
815         }       
816         if(!messagetype){
817                 var index = $('MessageSendFormType').selectedIndex;
818                 messagetype = $('MessageSendFormType').options[index].value;
819         }       
820         doRequest(url_message+'?text='+messagetext+'&type='+messagetype+'&timeout='+messagetimeout, incomingMessageResult, false);
821 }
822 function incomingMessageResult(request){
823
824         if(request.readyState== 4){
825                 var b = getXML(request).getElementsByTagName("e2message");
826                 var result = b.item(0).getElementsByTagName('e2result').item(0).firstChild.data;
827                 var resulttext = b.item(0).getElementsByTagName('e2resulttext').item(0).firstChild.data;
828                 if (result=="True"){
829                         messageBox('message send','message send successfully! it appears on TV-Screen');
830                 }else{
831                         messageBox('message send failed',resulttext);
832                 }
833         }               
834 }
835
836 // PowerState Code
837 function showPowerStateSendForm(){
838                 document.getElementById('BodyContentChannellist').innerHTML = tplPowerStateSendForm;
839 }
840 function sendPowerState(newState){
841         doRequest(url_powerstate+'?newstate='+newState, incomingPowerStateResult, false);
842 }
843 function incomingPowerStateResult(request){
844         debug(request.readyState);
845         if(request.readyState == 4){
846                 var b = getXML(request).getElementsByTagName("e2powerstate");
847                 var result = b.item(0).getElementsByTagName('e2result').item(0).firstChild.data;
848                 var resulttext = b.item(0).getElementsByTagName('e2resulttext').item(0).firstChild.data;
849                 var tplPowerStateSendForm2 = '<h1>PowerState is changing to:'+resulttext+ '</h1>' + tplPowerStateSendForm;
850                 document.getElementById('BodyContentChannellist').innerHTML = tplPowerStateSendForm2;
851         } else {
852                 document.getElementById('BodyContentChannellist').innerHTML = "<h1>some unknown error</h1>" + tplPasswordSendForm;
853         }
854 }
855
856 // RemoteControl Code
857 function showRemoteControllSendForm(){
858                 document.getElementById('BodyContentChannellist').innerHTML = tplRemoteControlForm;
859 }
860 function sendRemoteControlRequest(command){
861         doRequest(url_remotecontrol+'?command='+command, incomingRemoteControlResult, false);
862 }
863 function incomingRemoteControlResult(request){
864         if(request.readyState == 4){
865                 var b = getXML(request).getElementsByTagName("e2remotecontrol");
866                 var result = b.item(0).getElementsByTagName('e2result').item(0).firstChild.data;
867                 var resulttext = b.item(0).getElementsByTagName('e2resulttext').item(0).firstChild.data;
868                 showRemoteControllSendForm();
869         } else {
870                 document.getElementById('BodyContentChannellist').innerHTML = "<h1>some unknown error</h1>" + tplRemoteControlForm;
871         }
872 }
873
874 function loadTimerFormNow() {
875         var now = new Date();
876         addTimerEditFormObject["syear"] = now.getFullYear();
877         addTimerEditFormObject["smonth"] = now.getMonth() + 1;
878         addTimerEditFormObject["sday"] = now.getDate();
879         addTimerEditFormObject["shour"] = now.getHours();
880         addTimerEditFormObject["smin"] = now.getMinutes();
881
882         var     plusTwoHours = new Date(now.getTime() + ((120 *60)*1000) );
883         addTimerEditFormObject["eyear"] = plusTwoHours.getFullYear();
884         addTimerEditFormObject["emonth"] = plusTwoHours.getMonth() + 1;
885         addTimerEditFormObject["eday"] = plusTwoHours.getDate();
886         addTimerEditFormObject["ehour"] = plusTwoHours.getHours();
887         addTimerEditFormObject["emin"] = plusTwoHours.getMinutes();
888                 
889         addTimerEditFormObject["justplay"] = "record";
890         addTimerEditFormObject["channel"] = "";
891         addTimerEditFormObject["channelName"] = "";
892         addTimerEditFormObject["channelSort"] = "tv";
893         addTimerEditFormObject["name"] = "";
894         addTimerEditFormObject["description"] = "";
895         addTimerEditFormObject["repeated"] = 0;
896         addTimerEditFormObject["afterEvent"] = "0";
897         addTimerEditFormObject["deleteOldOnSave"] = 0;
898         
899         addTimerEditFormObject["beginOld"] = 0;
900         addTimerEditFormObject["endOld"] = 0;
901         
902         
903         debug("loadTimerFormNow 2");
904         loadTimerFormChannels();
905 }
906
907 function loadTimerFormSeconds(justplay,begin,end,repeated,channel,channelName,name,description,afterEvent,deleteOldOnSave) {
908         debug('justplay:'+justplay+' begin:'+begin+' end:'+end+' repeated:'+repeated+' channel:'+channel+' name:'+name+' description:'+description+' afterEvent:'+afterEvent+' deleteOldOnSave:'+deleteOldOnSave);
909         var start = new Date(Number(begin)*1000);
910         addTimerEditFormObject["syear"] = start.getFullYear();
911         addTimerEditFormObject["smonth"] = start.getMonth() + 1;
912         addTimerEditFormObject["sday"] = start.getDate();
913         addTimerEditFormObject["shour"] = start.getHours();
914         addTimerEditFormObject["smin"] = start.getMinutes();
915         
916         var     stopp = new Date(Number(end)*1000);
917         addTimerEditFormObject["eyear"] = stopp.getFullYear();
918         addTimerEditFormObject["emonth"] = stopp.getMonth() + 1;
919         addTimerEditFormObject["eday"] = stopp.getDate();
920         addTimerEditFormObject["ehour"] = stopp.getHours();
921         addTimerEditFormObject["emin"] = stopp.getMinutes();
922         
923         addTimerEditFormObject["justplay"] = String(justplay);
924         addTimerEditFormObject["channel"] = decodeURIComponent(String(channel));
925         addTimerEditFormObject["channelName"] = String(channelName);
926         addTimerEditFormObject["channelSort"] = "";
927         addTimerEditFormObject["name"] = String(name);
928         addTimerEditFormObject["description"] = String(description);
929         addTimerEditFormObject["repeated"] = Number(repeated);
930         addTimerEditFormObject["afterEvent"] = Number(afterEvent);
931         
932         debug(justplay+"|"+begin+"|"+end+"|"+repeated+"|"+channel+"|"+name+"|"+description+"|"+afterEvent);
933
934         addTimerEditFormObject["deleteOldOnSave"] = Number(deleteOldOnSave);
935         addTimerEditFormObject["beginOld"] = Number(begin);
936         addTimerEditFormObject["endOld"] = Number(end);
937         
938         loadTimerFormChannels();
939 }
940
941 // startin to load for TV
942 function loadTimerFormChannels() {
943         if(addTimerEditFormObject["TVListFilled"] == 1 && addTimerEditFormObject["RadioListFilled"] == 1) {
944                 loadTimerForm();
945         } else if(addTimerEditFormObject["TVListFilled"] == 1 && addTimerEditFormObject["RadioListFilled"] == 0) {
946                 addTimerListFormatTV();
947         } else {
948                 var favorites = '1%3A7%3A1%3A0%3A0%3A0%3A0%3A0%3A0%3A0%3AFROM%20BOUQUET%20%22userbouquet.favourites.tv%22%20ORDER%20BY%20bouquet'
949                 doRequest(url_fetchchannels+favorites, addTimerListFormatTV, false);
950         }
951 }
952
953 function addTimerListFormatTV(request) {
954         if(addTimerEditFormObject["RadioListFilled"] == 0) {
955                 if(request.readyState == 4){
956                         var services = new ServiceList(getXML(request)).getArray();
957                         var tv = new Object();
958                         for ( var i = 0; i < services.length ; i++){
959                                 var reference = services[i];
960                                 tv[reference.servicereference] = reference.servicename;
961                         }
962                         addTimerEditFormObject["TVListFilled"] = 1;
963                         addTimerEditFormObject["TVList"] = tv;
964                 }
965         }
966         if(addTimerEditFormObject["RadioListFilled"] == 1) {
967                 loadTimerForm()
968         } else {
969                 var favorites = '1%3A7%3A1%3A0%3A0%3A0%3A0%3A0%3A0%3A0%3AFROM%20BOUQUET%20%22userbouquet.favourites.radio%22%20ORDER%20BY%20bouquet';
970                 doRequest(url_fetchchannels+favorites, addTimerListFormatRadio, false);
971         }
972 }
973 function addTimerListFormatRadio(request) {
974         if(request.readyState == 4){
975                 var services = new ServiceList(getXML(request)).getArray();
976                 var radio = new Object();
977                 for ( var i = 0; i < services.length ; i++){
978                         var reference = services[i];
979                         radio[reference.servicereference] = reference.servicename;
980                 }
981                 addTimerEditFormObject["RadioListFilled"] = 1;
982                 addTimerEditFormObject["RadioList"] = radio;
983         }
984         loadTimerForm();
985 }
986
987 function loadTimerForm(){
988
989         var Action = new Object();
990         Action["0"] = "Record";
991         Action["1"] = "Zap";
992         
993         var Repeated = new Object();
994         Repeated["1"] =  "mo";
995         Repeated["2"] = "tu";
996         Repeated["4"] =  "we";
997         Repeated["8"] =  "th";
998         Repeated["16"] = "fr";
999         Repeated["32"] = "sa";
1000         Repeated["64"] = "su";
1001         Repeated["31"] = "mf";
1002         Repeated["127"] ="ms";
1003         
1004         var AfterEvent = new Object();
1005         AfterEvent["0"] = "Nothing";
1006         AfterEvent["1"] = "Standby";
1007         AfterEvent["2"] = "Deepstandby/Shutdown";
1008         
1009         addTimerEditFormObject["name"] = (typeof(addTimerEditFormObject["name"]) != "undefined") ? addTimerEditFormObject["name"] : "";
1010         addTimerEditFormObject["name"] = (addTimerEditFormObject["name"] == "") ? " " : addTimerEditFormObject["name"];
1011
1012         addTimerEditFormObject["description"] = (typeof(addTimerEditFormObject["description"]) != "undefined") ? addTimerEditFormObject["description"] : "";
1013         addTimerEditFormObject["description"] = (addTimerEditFormObject["description"] == "") ? " " : addTimerEditFormObject["description"];
1014
1015         var channelObject = addTimerEditFormObject["TVList"];
1016         if(     addTimerEditFormObject["channelSort"] == "tv") {
1017                 // already set
1018         } else if( addTimerEditFormObject["channelSort"] == "radio") {
1019                 channelObject = addTimerEditFormObject["RadioList"];
1020         } else {
1021                 var found = 0;
1022                 for( element in addTimerEditFormObject["TVList"]) {
1023                         if( element == addTimerEditFormObject["channel"]) {
1024                                 found = 1;
1025                                 break;
1026                         }
1027                 }
1028                 if(found == 0) {
1029                         for( element in addTimerEditFormObject["RadioList"]) {
1030                                 if( element == addTimerEditFormObject["channel"]) {
1031                                         channelObject = addTimerEditFormObject["RadioList"];
1032                                         found = 1;
1033                                         break;
1034                                 }
1035                         }
1036                 }
1037                 if(found == 0) {
1038                         addTimerEditFormObject["TVList"][addTimerEditFormObject["channel"]] = addTimerEditFormObject["channelName"];
1039                 }
1040         }
1041         var dashString = "------";
1042         channelObject[dashString] = "- Bouquets -";
1043         var listeNeu = new ServiceList(getXML(doRequestMemory[url_fetchchannels+encodeURIComponent(bouqet_tv)])).getArray();
1044         if(addTimerEditFormObject["channelSort"] == "radio") {
1045                 debug("weiter");
1046                 listeNeu = new ServiceList(getXML(doRequestMemory[url_fetchchannels+encodeURIComponent(bouqet_radio)])).getArray();
1047         }
1048         debug("hier" + listeNeu.length);
1049         for (i = 1; i < listeNeu.length; i++) {
1050                 var element = listeNeu[i];
1051                 channelObject[String(dashString+i)] = "---";
1052                 channelObject[element.getServiceReference()] = element.getServiceName();
1053         }
1054         debug("geklappt" + channelObject.length);
1055         var namespace = {       
1056                                 'justplay': addTimerFormCreateOptionList(Action, addTimerEditFormObject["justplay"]),
1057                                 'syear': addTimerFormCreateOptions(2007,2010,addTimerEditFormObject["syear"]),
1058                                 'smonth': addTimerFormCreateOptions(1,12,addTimerEditFormObject["smonth"]),
1059                                 'sday': addTimerFormCreateOptions(1,31,addTimerEditFormObject["sday"]),
1060                                 'shour': addTimerFormCreateOptions(0,23,addTimerEditFormObject["shour"]),
1061                                 'smin': addTimerFormCreateOptions(0,59,addTimerEditFormObject["smin"]),
1062                                 'eyear': addTimerFormCreateOptions(2007,2010,addTimerEditFormObject["eyear"]),
1063                                 'emonth': addTimerFormCreateOptions(1,12,addTimerEditFormObject["emonth"]),
1064                                 'eday': addTimerFormCreateOptions(1,31,addTimerEditFormObject["eday"]),
1065                                 'ehour': addTimerFormCreateOptions(0,23,addTimerEditFormObject["ehour"]),
1066                                 'emin': addTimerFormCreateOptions(0,59,addTimerEditFormObject["emin"]),
1067                                 'channel': addTimerFormCreateOptionList(channelObject, addTimerEditFormObject["channel"]),
1068                                 'name': addTimerEditFormObject["name"],
1069                                 'description': addTimerEditFormObject["description"],
1070                                 'repeated': addTimerFormCreateOptionListRepeated(Repeated, addTimerEditFormObject["repeated"]),
1071                                 'deleteOldOnSave': addTimerEditFormObject["deleteOldOnSave"],
1072                                 'channelOld': addTimerEditFormObject["channel"],
1073                                 'beginOld': addTimerEditFormObject["beginOld"],
1074                                 'endOld': addTimerEditFormObject["endOld"],
1075                                 'afterEvent': addTimerFormCreateOptionList(AfterEvent, addTimerEditFormObject["afterEvent"])
1076                 };
1077         var listerHtml = RND(tplAddTimerForm, namespace);
1078         document.getElementById('BodyContentChannellist').innerHTML = listerHtml;
1079
1080         // Empty some stuff, but keep others to have the performance
1081         var tmp1 = addTimerEditFormObject["RadioList"];
1082         var tmp2 = addTimerEditFormObject["TVList"];
1083         addTimerEditFormObject = new Object();
1084         addTimerEditFormObject["deleteOldOnSave"] = 0;
1085         addTimerEditFormObject["RadioList"] = tmp1;
1086         addTimerEditFormObject["TVList"] = tmp2;
1087         addTimerEditFormObject["TVListFilled"] = 1;
1088         addTimerEditFormObject["RadioListFilled"] = 1;
1089 }
1090
1091 function addTimerFormCreateOptions(start,end,number) {
1092         var html = '';
1093         for(i = start; i <= end; i++) {
1094                 var txt = (String(i).length == 1) ? "0" + String(i) : String(i);
1095                 var selected =  (i == Number(number)) ? "selected" : " ";
1096                 var namespace = {
1097                         'value': i,
1098                         'txt': txt,
1099                         'selected': selected };
1100                 html += RND(tplAddTimerFormOptions, namespace);
1101         }
1102         return html;
1103 }
1104 function addTimerFormCreateOptionList(object,selected) {
1105         html = '';
1106         var found = 0;
1107         for(var element in object) {
1108                 var txt = String(object[element]);
1109                 var sel = " ";
1110                 if(element == selected) {
1111                         found = 1;
1112                         sel = "selected";
1113                 }
1114                 var namespace = {
1115                         'value': element,
1116                         'txt': txt,
1117                         'selected': sel };
1118                 if(element != "extend") {
1119                         html += RND(tplAddTimerFormOptions, namespace);
1120                 }
1121         }
1122         if(found == 0) {
1123                 var namespace = {
1124                         'value': element,
1125                         'txt': txt,
1126                         'selected': sel };
1127         }
1128         return html;
1129 }
1130
1131 function timerFormExtendChannellist(bouqet) {
1132         var listeTV = new ServiceList(getXML(doRequestMemory[url_fetchchannels+encodeURIComponent(bouqet_tv)])).getArray();
1133         var listeRadio = new ServiceList(getXML(doRequestMemory[url_fetchchannels+encodeURIComponent(bouqet_radio)])).getArray();
1134         found = 0;
1135         for(i = 0; i < listeTV.length; i++) {
1136                 var element = listeTV[i];
1137                 if(String(element.getServiceReference()) == bouqet) {
1138                         found = 1;
1139                         break;
1140                 }
1141         }
1142         if(found == 0) {
1143                 for(i = 0; i < listeRadio.length; i++) {
1144                         var element = listeTV[i];
1145                         if(String(element.getServiceReference()) == bouqet) {
1146                                 found = 1;
1147                                 break;
1148                         }
1149                 }
1150         }
1151         if(found == 1) {
1152                 servicereftoloadepgnow = bouqet;
1153                 if(typeof(loadedChannellist[servicereftoloadepgnow]) == "undefined") {  
1154                         doRequest(url_fetchchannels+servicereftoloadepgnow, incomingTimerFormExtendChannellist, true);
1155                 } else {
1156                         incomingTimerFormExtendChannellist();
1157                 }
1158         }
1159 }
1160 function incomingTimerFormExtendChannellist(request) {
1161         var services = null;
1162         if(typeof(loadedChannellist[servicereftoloadepgnow]) != "undefined"){
1163                 services = loadedChannellist[servicereftoloadepgnow];
1164         } else if(request.readyState == 4) {
1165                 services = new ServiceList(getXML(request)).getArray();
1166                 loadedChannellist[servicereftoloadepgnow] = services;
1167                 debug("got "+services.length+" Services");
1168         }
1169         var attachLater = new Object();
1170         if(services != null) {
1171                 debug("incomingTimerFormExtendChannellist " + services.length);
1172                 var selected = $('channel').selectedIndex;
1173                 for(j = selected; j < $('channel').options.length; j++) {
1174                         if($('channel').options[j].value == servicereftoloadepgnow) {
1175                                 j++;
1176                                 for(var i = 0; i < services.length ; i++) {
1177                                         var reference = services[i];
1178                                         var newEntry = new Option(reference.getServiceName(), reference.getServiceReference(), false, true);
1179                                         if(typeof($('channel').options[j]) != "undefined") {
1180                                                 attachLater[String($('channel').options[j].value)] = $('channel').options[j].text;
1181                                         }
1182                                         $('channel').options[j] = newEntry;
1183                                         j++;
1184                                 }
1185                         }
1186                         break;
1187                 }
1188                 for(x in attachLater) {
1189                         var newEntry = new Option(attachLater[x], x, false, true);
1190                         if(x != "extend") {
1191                                 $('channel').options[$('channel').options.length] = newEntry;
1192                         }
1193                 }
1194                 $('channel').options[selected].selected = true;
1195                 
1196         }
1197 }
1198 //doRequest(url_fetchchannels+servicereference, incomingChannellist, true);
1199
1200 function addTimerFormChangeTime(which) {
1201         var start = new Date( $('syear').value, ($('smonth').value -1), $('sday').value, $('shour').value, $('smin').value, 0);
1202         var end = new Date($('eyear').value, ($('emonth').value -1), $('eday').value, $('ehour').value, $('emin').value, 0);
1203 //      debug("("+start+")(" + end+")");
1204
1205         if(start.getTime() > end.getTime()) {
1206                 opponent = (which.substr(0,1) == 's') ? 'e' +  which.substr(1, which.length -1) : 's' +  which.substr(1, which.length -1) ;
1207                 $(opponent).value = $(which).value;
1208         }
1209         var all = new Array('year','month','day','hour','min');
1210         for(i=0; i < all.length; i++) {
1211                 if(which.substr(1, which.length -1) == all[i]) {
1212                         addTimerFormChangeTime(which.substr(0,1) + all[i+1] );
1213                         break;
1214                 }
1215         }
1216 }
1217 function addTimerFormChangeType() {
1218         var selected = ($('tvradio').checked == true) ? addTimerEditFormObject["TVList"]: addTimerEditFormObject["RadioList"];
1219         for (i = $('channel').options.length; i != 0; i--) {
1220                 $('channel').options[i - 1] = null;
1221         }
1222         var i = -1;
1223         for(element in selected) {
1224                 if(element != "extend") {
1225                         i++;
1226                         $('channel').options[i] = new Option(selected[element]);
1227                         $('channel').options[i].value = element;
1228                 }
1229         }
1230 }
1231 function addTimerFormCreateOptionListRepeated(Repeated,repeated) {
1232         var num = Number(repeated);
1233         var html = "";
1234         var html2 = "";
1235         var list = new Array(127, 64, 32, 31, 16, 8, 4, 2, 1);
1236         for(i = 0; i < list.length; i++) {
1237                 var txt = String(Repeated[String(list[i])]);
1238                 if( String(Repeated[String(list[i])]) == "mf") {
1239                         txt = "Mo-Fr";
1240                 } else if( String(Repeated[String(list[i])]) == "ms") {
1241                         txt = "Mo-Su";
1242                 } else {
1243                         txt = txt.substr(0,1).toUpperCase() + txt.substr(1,1);
1244                 }
1245                 var checked = " ";
1246                 if(num >=  list[i]) {
1247                         num -= list[i];
1248                         checked = "checked";
1249                 }
1250                 var namespace = {
1251                         'id': Repeated[String(list[i])],
1252                         'name': Repeated[String(list[i])],
1253                         'value': list[i],
1254                         'txt': txt,
1255                         'checked': checked };
1256                 if(String(Repeated[String(list[i])]) == "mf" || String(Repeated[String(list[i])]) == "ms") {
1257                         html2 = RND(tplAddTimerFormCheckbox, namespace) + html2;
1258                 } else {
1259                         html = RND(tplAddTimerFormCheckbox, namespace) + html;
1260                 }
1261         }
1262         return html + html2;
1263 }
1264 function sendAddTimer() {
1265         debug("sendAddTimer" + "parentChannel:" +$('channel').value);
1266         
1267         if(parentPin($('channel').value)) {
1268                 var beginD = new Date(ownLazyNumber($('syear').value), (ownLazyNumber($('smonth').value) - 1), ownLazyNumber($('sday').value), ownLazyNumber($('shour').value), ownLazyNumber($('smin').value));
1269                 var begin = beginD.getTime()/1000;
1270                 
1271                 var endD = new Date(ownLazyNumber($('eyear').value), (ownLazyNumber($('emonth').value) - 1), ownLazyNumber($('eday').value), ownLazyNumber($('ehour').value), ownLazyNumber($('emin').value));
1272                 var end = endD.getTime()/1000;
1273
1274                 var repeated = 0;
1275                 if( $('ms').checked ) {
1276                         repeated = 127;
1277                 } else if($('mf').checked) {
1278                         repeated = 31;
1279                         if($('sa').checked) {
1280                                 repeated += ownLazyNumber($('sa').value);
1281                         }
1282                         if($('su').checked) {
1283                                 repeated += ownLazyNumber($('su').value);
1284                         }
1285                 } else {
1286                         var check = new Array('mo', 'tu', 'we', 'th', 'fr');
1287                         for(i = 0; i < check.length; i++) {
1288                                 if($(check[i]).cheked) {
1289                                         repeated += Number($(check[i]).value);
1290                                 }
1291                         }
1292                 }
1293         
1294                 var descriptionClean = ($('descr').value == " " || $('descr').value == "N/A") ? "" : $('descr').value;
1295                 var nameClean = ($('name').value == " " || $('name').value == "N/A") ? "" : $('name').value;
1296         
1297                 var repeated = 0;
1298                 if($('ms').checked) {
1299                         repeated = ownLazyNumber($('ms').value);
1300                 } else if($('mf').checked) {
1301                         repeated = ownLazyNumber($('mf').value);
1302                         if($('su').checked) {
1303                                 repeated += ownLazyNumber($('su').value);
1304                         }
1305                         if($('sa').checked) {
1306                                 repeated += ownLazyNumber($('sa').value);
1307                         }
1308                 } else {
1309                         if($('mo').checked) {
1310                                 repeated += ownLazyNumber($('mo').value);
1311                         }
1312                         if($('tu').checked) {
1313                                 repeated += ownLazyNumber($('tu').value);
1314                         }
1315                         if($('we').checked) {
1316                                 repeated += ownLazyNumber($('we').value);
1317                         }
1318                         if($('th').checked) {
1319                                 repeated += ownLazyNumber($('th').value);
1320                         }
1321                         if($('fr').checked) {
1322                                 repeated += ownLazyNumber($('fr').value);
1323                         }
1324                         if($('sa').checked) {
1325                                 repeated += ownLazyNumber($('sa').value);
1326                         }
1327                         if($('su').checked) {
1328                                 repeated += ownLazyNumber($('su').value);
1329                         }
1330                 }
1331                 doRequest(url_timerchange+"?"+"serviceref="+$('channel').value+"&begin="+begin
1332                   +"&end="+end+"&name="+escape(nameClean)+"&description="+escape(descriptionClean)
1333                   +"&afterevent="+$('after_event').value+"&eit=0&disabled=0"
1334                   +"&justplay="+ownLazyNumber($('justplay').value)+"&repeated="+repeated
1335                   +"&channelOld="+$('channelOld').value
1336                   +"&beginOld="+$('beginOld').value+"&endOld="+$('endOld').value
1337                   +"&deleteOldOnSave="+ownLazyNumber($('deleteOldOnSave').value), incomingTimerAddResult, false);       
1338         }
1339 }
1340 function getSettings(){
1341         doRequest(url_settings, incomingGetSettings, false);
1342 }
1343
1344 function incomingGetSettings(request){
1345         if(request.readyState == 4){
1346                 settings = new Settings(getXML(request)).getArray();
1347         }
1348         if(String(getSettingByName("config.ParentalControl.configured")) == "True") {
1349                 getParentControl();
1350         }
1351 }
1352 function getSettingByName(txt) {
1353         debug("getSettingByName ("+txt+")");
1354         for(i = 0; i < settings.length; i++) {
1355                 debug("("+settings[i].getSettingName()+") (" +settings[i].getSettingValue()+")");
1356                 if(String(settings[i].getSettingName()) == String(txt)) {
1357                         return settings[i].getSettingValue();
1358                 } 
1359         }
1360         return "";
1361 }
1362 function getParentControl() {
1363         doRequest(url_parentcontrol, incomingParentControl, false);
1364 }
1365 function incomingParentControl(request) {
1366         if(request.readyState == 4){
1367                 parentControlList = new ServiceList(getXML(request)).getArray();
1368                 debug("parentControlList got "+parentControlList.length + " services");
1369         }
1370 }
1371 function getParentControlByRef(txt) {
1372         debug("getParentControlByRef ("+txt+")");
1373         for(i = 0; i < parentControlList.length; i++) {
1374                 debug("("+parentControlList[i].getClearServiceReference()+")");
1375                 if(String(parentControlList[i].getClearServiceReference()) == String(txt)) {
1376                         return parentControlList[i].getClearServiceReference();
1377                 } 
1378         }
1379         return "";
1380 }
1381 function sendToggleTimerDisable(justplay,begin,end,repeated,channel,name,description,afterEvent,disabled){
1382         disabled = (ownLazyNumber(disabled) == 0) ? 1 : 0;
1383         
1384         var descriptionClean = (description == " " || description == "N/A") ? "" : description;
1385         var nameClean = (name == " " || name == "N/A") ? "" : name;
1386
1387         doRequest(url_timerchange+"?"+"serviceref="+channel+"&begin="+begin
1388          +"&end="+end+"&name="+escape(nameClean)+"&description="+escape(descriptionClean)
1389          +"&afterevent="+afterEvent+"&eit=0&disabled="+disabled
1390          +"&justplay="+justplay+"&repeated="+repeated
1391          +"&channelOld="+channel
1392          +"&beginOld="+begin+"&endOld="+end
1393          +"&deleteOldOnSave=1", incomingTimerAddResult, false);
1394 }
1395 function ownLazyNumber(num) {
1396         if(isNaN(num)){
1397                 return 0;
1398         } else {
1399                 return Number(num);
1400         }
1401 }
1402
1403 var subServicesInsertedList = new Object();
1404
1405 function getSubServices(servicereference) {
1406                 doRequest(url_subservices,incomingSubServiceRequest, false);
1407 }
1408 function incomingSubServiceRequest(request){
1409         if(request.readyState == 4){
1410                 var services = new ServiceList(getXML(request)).getArray();
1411                 listerHtml      = '';           
1412                 debug("got "+services.length+" SubServices");
1413                 if(services.length > 1) {
1414
1415                         first = services[0];
1416                         var mainChannellist = loadedChannellist[String($('mainServiceRef').value)];
1417                         
1418                         var oldEntryPosition = -1;
1419                         for(i = 0; i < mainChannellist.length; i++) {
1420                                 var service = mainChannellist[i];
1421                                 if(String(service.getServiceReference()) == String(first.getServiceReference())) {
1422                                         oldEntryPosition = i + 1;
1423                                         break;
1424                                 }
1425                         }
1426                         if(typeof(subServicesInsertedList[String(first.getServiceReference())]) != "undefined") {
1427                                 for ( var i = 1; i < subServicesInsertedList[String(first.getServiceReference())].length ; i++){
1428                                         var reference = subServicesInsertedList[String(first.getServiceReference())][i];
1429                                         document.getElementById(reference.getServiceReference()+'extend').innerHTML = "";
1430                                 }
1431                                 for(i = oldEntryPosition; i < oldEntryPosition + subServicesInsertedList[String(first.getServiceReference())].length; i++) {
1432                                         mainChannellist.splice(i);
1433                                 }
1434                         }
1435
1436                         for ( var i = 0; i < services.length ; i++){
1437                                 var reference = services[i];
1438                                 var namespace = {       
1439                                         'servicereference': reference.getServiceReference(),
1440                                         'servicename': reference.getServiceName()
1441                                 };
1442                                 listerHtml += RND(tplServiceListItem, namespace);
1443                                 if(oldEntryPosition > -1) {
1444                                         mainChannellist = mainChannellist.insert(oldEntryPosition++, reference);
1445                                 }
1446                         }
1447
1448                         document.getElementById(first.getServiceReference()+'extend').innerHTML = listerHtml;
1449                         subServicesInsertedList[String(first.getServiceReference())] = services;
1450                         loadedChannellist[$('mainServiceRef').value] = mainChannellist;
1451                 }
1452         }
1453 }
1454 // Array.insert( index, value ) - Insert value at index, without overwriting existing keys
1455 Array.prototype.insert = function( j, v ) {
1456  if( j>=0 ) {
1457   var a = this.slice(), b = a.splice( j );
1458   a[j] = v;
1459   return a.concat( b );
1460  }
1461 }
1462 // Array.splice() - Remove or replace several elements and return any deleted elements
1463 if( typeof Array.prototype.splice==='undefined' ) {
1464  Array.prototype.splice = function( a, c ) {
1465   var i = 0, e = arguments, d = this.copy(), f = a, l = this.length;
1466   if( !c ) { c = l - a; }
1467   for( i; i < e.length - 2; i++ ) { this[a + i] = e[i + 2]; }
1468   for( a; a < l - c; a++ ) { this[a + e.length - 2] = d[a - c]; }
1469   this.length -= c - e.length + 2;
1470   return d.slice( f, f + c );
1471  };
1472 }
1473 function writeTimerListNow() {
1474         new Ajax.Request( url_timerlistwrite, { method: 'get' });
1475 }
1476 function recordingPushed() {
1477         doRequest(url_timerlist, incomingRecordingPushed, false);       
1478 }
1479 function incomingRecordingPushed(request) {
1480         if(request.readyState == 4){
1481                 var timers = new TimerList(getXML(request)).getArray();
1482                 debug("have "+timers.length+" timer");
1483                 
1484                 var aftereventReadable = new Array ('Nothing', 'Standby', 'Deepstandby/Shutdown');
1485                 var justplayReadable = new Array('record', 'zap');
1486                 var OnOff = new Array('on', 'off');
1487                 
1488                 listerHtml = '';
1489                 
1490                 for ( var i = 0; i <timers.length; i++){
1491                         var timer = timers[i];
1492
1493                         if(ownLazyNumber(timer.getDontSave()) == 1) {
1494                                 var beginDate = new Date(Number(timer.getTimeBegin())*1000);
1495                                 var endDate = new Date(Number(timer.getTimeEnd())*1000);
1496                                 var namespace = {
1497                                 'servicereference': timer.getServiceReference(),
1498                                 'servicename': timer.getServiceName() ,
1499                                 'title': timer.getName(), 
1500                                 'description': timer.getDescription(), 
1501                                 'descriptionextended': timer.getDescriptionExtended(), 
1502                                 'begin': timer.getTimeBegin(),
1503                                 'beginDate': beginDate.toLocaleString(),
1504                                 'end': timer.getTimeEnd(),
1505                                 'endDate': endDate.toLocaleString(),
1506                                 'state': timer.getState(),
1507                                 'duration': Math.ceil((timer.getDuration()/60)),
1508                                 'repeated': timer.getRepeated(),
1509                                 'repeatedReadable': repeatedReadable(timer.getRepeated()),
1510                                 'justplay': timer.getJustplay(),
1511                                 'justplayReadable': justplayReadable[Number(timer.getJustplay())],
1512                                 'afterevent': timer.getAfterevent(),
1513                                 'aftereventReadable': aftereventReadable[Number(timer.getAfterevent())],
1514                                 'disabled': timer.getDisabled(),
1515                                 'onOff': OnOff[Number(timer.getDisabled())],
1516                                 'color': colorTimerListEntry( timer.getState() )
1517                                 };
1518                                 listerHtml += RND(tplTimerListItem, namespace);
1519                         }
1520                 }
1521                 openWindow("Record Now", listerHtml+tplRecordingFooter, 900, 500, "Record now window");
1522         }
1523 }
1524 function inserteSizes() {
1525 /*      var screenW = 640, screenH = 480;
1526         if (parseInt(navigator.appVersion)>3) { 
1527                 screenW = screen.width;
1528                 screenH = screen.height;
1529         } else if (navigator.appName == "Netscape"
1530            && parseInt(navigator.appVersion)==3
1531            && navigator.javaEnabled() ) {
1532                 var jToolkit = java.awt.Toolkit.getDefaultToolkit();
1533                 var jScreenSize = jToolkit.getScreenSize();
1534                 screenW = jScreenSize.width;
1535                 screenH = jScreenSize.height;
1536         }
1537         debug("screenW:"+screenW+" screenH:"+screenH);
1538         /* 640x480
1539          * 800x600
1540          * 1024x768
1541          * 1280x1024
1542          * 1600x1280
1543         if(screenH == 800) {
1544                 debug("size 1");
1545                 document.getElementById("BodyContentChannellist").style.height = '20%';
1546         } else if(screenH == 1024) {
1547                 debug("1024")
1548                 document.getElementById("BodyContentChannellist").style.height = '760px';
1549                 
1550         } else {
1551                 alert("unsupported screensize");
1552         }*/
1553         
1554 }
1555 function recordingPushedDecision(recordNowNothing,recordNowUndefinitely,recordNowCurrent) {
1556         var recordNow = recordNowNothing;
1557         recordNow = (recordNow == "") ? recordNowUndefinitely: recordNow;
1558         recordNow = (recordNow == "") ? recordNowCurrent: recordNow;
1559         if(recordNow != "nothing" && recordNow != "") {
1560                 doRequest(url_recordnow+"?recordnow="+recordNow, incomingTimerAddResult, false);
1561         }
1562 }
1563
1564 function ifChecked(rObj) {
1565         if(rObj.checked) {
1566                 return rObj.value;
1567         } else {
1568                 return "";
1569         }
1570 }