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