milestone 1 to move to an http_streaming object
[brisk.git] / web / commons.js
1 /*
2  *  brisk - commons.js
3  *
4  *  Copyright (C) 2006-2011 Matteo Nastasi
5  *                          mailto: nastasi@alternativeoutput.it 
6  *                                  matteo.nastasi@milug.org
7  *                          web: http://www.alternativeoutput.it
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful, but
15  * WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABLILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17  * General Public License for more details. You should have received a
18  * copy of the GNU General Public License along with this program; if
19  * not, write to the Free Software Foundation, Inc, 59 Temple Place -
20  * Suite 330, Boston, MA 02111-1307, USA.
21  *
22  */
23
24 var PLAYERS_N = 3;
25 var EXIT_BAN_TIME = 3600;
26 var cookiepath = "/brisk/";
27
28 var mlang_commons = { 'imgload_a' : { 'it' : 'Immagine caricate ', 
29                                       'en' : 'Loaded images ' },
30                       'imgload_b' : { 'it' : '%.', 
31                                       'en' : '%.' },
32                       'gamleav'   : { 'it' : 'Sei sicuro di volere lasciare questa mano?' ,
33                                       'en' : 'Are you sure to leave this game?' },
34                       'brileav'   : { 'it' : '    Vuoi veramente abbandonare la briscola ?\n(clicca annulla o cancel se vuoi ricaricare la briscola)',
35                                       'en' : '    Are you really sure to leave briscola ?\n(click cancel yo reload it)' },
36                       'brireco'   : { 'it' : 'Ripristino della briscola fallito, per non perdere la sessione ricaricare la pagina manualmente.',
37                                       'en' : 'Recovery of briscola failed, to keep the current session reload the page manually.' },
38                       'btn_sit'   : { 'it' : 'Mi siedo.',
39                                       'en' : 'Sit down.' },
40                       'btn_exit'  : { 'it' : 'Esco.',
41                                       'en' : 'Exit.' }
42                       
43                       };
44
45 function $(id) { return document.getElementById(id); }
46
47 function getStyle(x,IEstyleProp, MozStyleProp) 
48 {
49     if (x.currentStyle) {
50         var y = x.currentStyle[IEstyleProp];
51     } else if (window.getComputedStyle) {
52         var y = document.defaultView.getComputedStyle(x,null).getPropertyValue(MozStyleProp);
53     }
54     return y;
55 }
56
57 /* replacement of setInterval on IE */
58 (function(){
59     /*if not IE, do nothing*/
60     if(!document.uniqueID){return;};
61
62     /*Copy the default setInterval behavior*/
63     var nativeSetInterval = window.setInterval;
64     window.setInterval = function(fn,ms) {              
65         var param = [];
66         if(arguments.length <= 2)       {
67             return nativeSetInterval(fn,ms);
68         }
69         else {
70             for(var i=2;i<arguments.length;i+=1) {
71                 param[i-2] =  arguments[i];
72             }   
73         }
74         
75         if(typeof(fn)=='function') {
76             
77             return (function (fn,ms,param) {
78                 var fo = function () {                                                          
79                     fn.apply(window,param);
80                 };                      
81                 return nativeSetInterval(fo,ms); 
82             })(fn,ms,param);
83         }
84         else if(typeof(fn)=='string')
85         {
86             return  nativeSetInterval(fn,ms);
87         }
88         else
89         {
90             throw Error('setInterval Error\nInvalid function type');
91         };
92     };
93
94     /*Copy the default setTimeout behavior*/
95     var nativeSetTimeout = window.setTimeout;
96     window.setTimeout = function(fn,ms) {               
97         var param = [];
98         if(arguments.length <= 2)       {
99             return nativeSetTimeout(fn,ms);
100         }
101         else {
102             for(var i=2;i<arguments.length;i+=1) {
103                 param[i-2] =  arguments[i];
104             }   
105         }
106         
107         if(typeof(fn)=='function') {
108             
109             return (function (fn,ms,param) {
110                 var fo = function () {                                                          
111                     fn.apply(window,param);
112                 };                      
113                 return nativeSetTimeout(fo,ms); 
114             })(fn,ms,param);
115         }
116         else if(typeof(fn)=='string')
117         {
118             return  nativeSetTimeout(fn,ms);
119         }
120         else
121         {
122             throw Error('setTimeout Error\nInvalid function type');
123         };
124     };
125
126 })()
127
128 function addEvent(obj,type,fn)
129 {
130     if (obj.addEventListener) {
131         obj.addEventListener( type, fn, false);
132     }
133     else if (obj.attachEvent) {
134         obj["e"+type+fn] = fn;
135         obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
136         obj.attachEvent( "on"+type, obj[type+fn] );
137     }
138     else
139         throw new Error("Event registration not supported");
140 }
141
142 function removeEvent(obj,type,fn)
143 {
144     if (obj.removeEventListener) {
145         obj.removeEventListener( type, fn, false );
146     }
147     else if (obj.detachEvent) {
148         obj.detachEvent( "on"+type, obj[type+fn] );
149         obj[type+fn] = null;
150         obj["e"+type+fn] = null;
151     }
152 }
153
154     // var card_pos = RANGE 0 <= x < cards_ea_n
155
156 function show_bigpict(obj, act, x, y)
157 {
158    var big, sfx;
159
160    if (arguments.length > 4)
161        sfx = arguments[4];
162    else
163        sfx = '';
164
165    big = $(obj.id+"_big"+sfx);
166    if (act == "over") {
167        big.style.left = obj.offsetLeft + x+"px";
168        big.style.top  = obj.offsetTop  + y+"px";
169        big.style.visibility = "visible";
170        }
171    else {
172        big.style.visibility = "hidden";
173        }
174 }
175
176 function rnd_int(min, max) {
177   return Math.floor(Math.random() * (max - min + 1) + min);
178 }
179
180 function error_images()
181 {
182     // alert("GHESEMU!");
183     setTimeout(preload_images, 2000, g_preload_img_arr, g_imgct-1);
184 }
185
186 function abort_images()
187 {
188     // alert("ABORTAIMAGES");
189     setTimeout(preload_images, 2000, g_preload_img_arr, g_imgct-1);
190 }
191
192 function unload_images()
193 {
194     // alert("ABORTAIMAGES");
195     setTimeout(preload_images, 2000, g_preload_img_arr, g_imgct-1);
196 }
197
198 function reset_images()
199 {
200     // alert("ABORTAIMAGES");
201     setTimeout(preload_images, 2000, g_preload_img_arr, g_imgct-1);
202 }
203
204 function update_images()
205 {
206     // MLANG "Immagine caricate" + g_preload_imgsz_arr[g_imgct] + "%."
207     $("imgct").innerHTML = mlang_commons['imgload_a'][g_lang]+g_preload_imgsz_arr[g_imgct]+"%.";
208     if (g_imgct+1 < g_preload_img_arr.length) {
209         g_imgct++;
210         setTimeout(preload_images, 100, g_preload_img_arr, g_imgct-1);
211     }
212     // $("imgct").innerHTML += "U";
213 }
214
215 function preload_images(arr,idx)
216 {
217     var im = new Image;
218     
219     // $("imgct").innerHTML = "Stiamo caricando "+arr[idx]+"%.<br>";
220     im.onload =   update_images;
221     im.onerror =  error_images;
222     im.onabort =  abort_images;
223     im.onunload = unload_images;
224     im.onreset =  reset_images;
225     im.src =      arr[idx];
226     // $("imgct").innerHTML += "P";
227 }
228
229 function safestatus(a)
230 {
231     try{
232         return (a.status);
233     } catch(b)
234         { return (-1); }
235 }
236
237 function createXMLHttpRequest() {
238     try { return new ActiveXObject("Msxml2.XMLHTTP");    } catch(e) {}
239     try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {}
240     try { return new XMLHttpRequest();                   } catch(e) {}
241     alert("XMLHttpRequest not supported");
242     return null;
243 }
244
245 function send_mesg(mesg)
246 {
247     var xhr_wr = createXMLHttpRequest();
248     var is_conn = (sess == "not_connected" ? false : true);
249     
250     // alert("xhr_wr: "+xhr_wr+"  is_conn: "+is_conn);
251     xhr_wr.open('GET', 'index_wr.php?'+(is_conn ? 'sess='+sess+'&' : '')+'mesg='+mesg, (is_conn ? true : false));
252     xhr_wr.onreadystatechange = function() { return; };
253     if (typeof(console) == 'object') {
254         if (typeof(console.log) == 'function') {
255             var ldate = new Date();
256             console.log(ldate.getTime()+':MESG:'+mesg);
257         }
258     }
259     xhr_wr.send(null);
260
261     if (!is_conn) {
262         if (xhr_wr.responseText != null) {
263             eval(xhr_wr.responseText);
264         }
265     }
266 }
267
268 /*
269   request to server
270   server_request([arg0=arg1[, arg2=arg3[, ...]]])
271  */
272 function server_request()
273 {
274     var xhr_wr = createXMLHttpRequest();
275     var i, collect = "";
276
277     if (arguments.length > 0) {
278         for (i = 0 ; i < arguments.length ; i+= 2) {
279             collect += (i == 0 ? "" : "&") + arguments[i] + "=" + encodeURIComponent(arguments[i+1]);
280         }
281     }
282     // alert("Args: "+arguments.length);
283
284     var is_conn = (sess == "not_connected" ? false : true);
285     
286     // console.log("server_request:preresp: "+xhr_wr.responseText);
287
288     xhr_wr.open('GET', 'index_wr.php?'+(is_conn ? 'sess='+sess+'&' : '')+collect, false);
289     xhr_wr.onreadystatechange = function() { return; };
290     xhr_wr.send(null);
291     
292     if (xhr_wr.responseText != null) {
293         // console.log("server_request:resp: "+xhr_wr.responseText);
294         return (xhr_wr.responseText);
295     } 
296     else
297         return (null);
298 }
299
300 /* Stat: CHAT and TABLE */
301
302 function chatt_checksend(obj,e)
303 {
304     var keynum;
305     var keychar;
306     var numcheck;
307
308     if(window.event) { // IE
309         keynum = e.keyCode;
310     }
311     else if(e.which) { // Netscape/Firefox/Opera
312         keynum = e.which;
313     }
314     // alert("OBJ: "+obj);
315     if (keynum == 13 && obj.value != "") { // Enter
316         act_chatt(obj.value);
317         obj.value = "";
318     }
319 }
320 function act_chatt(value)
321 {
322     send_mesg("chatt|"+encodeURIComponent(value));
323     /*
324     obj.disabled = true;
325     obj.value = "";
326     obj.disabled = false;
327     obj.focus();
328     */
329     return false;
330 }
331
332 /* Stat: ROOM */
333 function act_sitdown(table)
334 {
335     send_mesg("sitdown|"+table);
336 }
337
338 function act_wakeup()
339 {
340     send_mesg("wakeup");
341 }
342
343 function act_splash()
344 {
345     send_mesg("splash");
346 }
347
348 function act_help()
349 {
350     send_mesg("help");
351 }
352
353 function act_passwdhowto()
354 {
355     send_mesg("passwdhowto");
356 }
357
358 function act_mesgtoadm()
359 {
360     send_mesg("mesgtoadm");
361 }
362
363 function act_tav()
364 {
365     act_chatt('/tav '+$('txt_in').value); 
366     $('txt_in').value = '';
367 }
368
369 function act_about()
370 {
371     send_mesg("about");
372 }
373
374 function act_placing()
375 {
376     send_mesg("placing");
377 }
378
379 function act_roadmap()
380 {
381     send_mesg("roadmap");
382 }
383
384 function act_whysupport()
385 {
386     send_mesg("whysupport");
387 }
388
389 function act_lascio()
390 {
391     send_mesg("lascio");
392 }
393
394 function safelascio()
395 {
396     var res;
397     // MLANG "Sei sicuro di volere lasciare questa mano?"
398     res = window.confirm(mlang_commons['gamleav'][g_lang]);
399     if (res)
400         act_lascio();
401 }
402
403 function act_logout(exitlock)
404 {
405     send_mesg("logout|"+exitlock);
406 }
407
408 function act_reloadroom()
409 {
410     window.onunload = null;
411     window.onbeforeunload = null;
412     document.location.assign("index.php");
413 }
414
415 function act_shutdown()
416 {
417     var c = 0;
418
419     send_mesg("shutdown");
420     // while (xhr_wr.readyState != 4)
421     //  c++;
422 }
423
424 function postact_logout()
425 {
426     // alert("postact_logout");
427     try { 
428         hstm.abort();
429     } catch (e) {}
430
431     // eraseCookie("sess");
432     document.location.assign("index.php");
433 }
434
435 /*
436   function slowimg(img,x1,y1,deltat,free,action,srcend)
437   img    - image to move
438   x1,y1  - destination coords
439   deltat - time for each frame (in msec)
440   free   - when the release the local block for other operations (range: 0 - 1)
441   action - function to run when the image is moved
442   srcend - image to switch when the image is moved
443 */
444
445 function sleep(st, delay)
446 {
447     // alert("LOC_NEW PRE: "+st.st_loc_new);
448
449     st.st_loc_new++;
450
451     setTimeout(function(obj){ if (obj.st_loc_new > obj.st_loc) { obj.st_loc++; }},
452                delay, st);
453 }
454
455 function slowimg(img,x1,y1,deltat,free,action,srcend) {
456     this.img = img;
457
458     // this.x0  = parseInt(document.defaultView.getComputedStyle(this.img, "").getPropertyValue("left"));
459     this.x0 = parseInt(getStyle(this.img,"left", "left"));
460 // alert("img.x0 = "+this.x0);
461     // this.y0  = parseInt(document.defaultView.getComputedStyle(this.img, "").getPropertyValue("top"));
462     this.y0  = parseInt(getStyle(this.img,"top", "top"));
463     this.x1  = x1;
464     this.y1  = y1;
465     this.deltat = deltat;
466     this.free = free;
467     this.action = action;
468     this.srcend = srcend;
469 }
470
471 slowimg.prototype = {
472     img: null, 
473     st: null,
474     x0: 0,
475     y0: 0,
476     x1: 0,
477     y1: 0,
478     dx: 0,
479     dy: 0,
480     free: 0,
481     step_n:    0,
482     step_cur:  0,
483     step_free: 0,
484     time:      0,
485     deltat:   40,
486     tout: 0,
487     action: null,
488     srcend: null,
489     
490     setstart: function(x0,y0)
491     {
492         this.x0 = x0;
493         this.y0 = y0;
494     },
495     
496     setaction: function(act)
497     {
498         this.action = act;
499     },
500     
501
502     settime: function(time) 
503     {
504         this.time = (time < this.deltat ? this.deltat : time);
505         this.step_n = parseInt(this.time / this.deltat);
506         this.dx = (this.x1 - this.x0) / this.step_n;
507         this.dy = (this.y1 - this.y0) / this.step_n;
508         if (this.step_n * this.deltat == this.time) {
509             this.step_n--;
510         }
511         if (this.free < 1) {
512             this.step_free = parseInt(this.step_n * this.free);
513         }
514     },
515     
516     start: function(st)
517     {
518         // $("logz").innerHTML += "               xxxxxxxxxxxxxxxxxxxxxSTART<br>";
519         this.st = st;
520         this.st.st_loc_new++;
521         
522         this.img.style.visibility = "visible";
523         setTimeout(function(obj){ obj.animate(); }, this.deltat, this);
524     },
525     
526     animate: function()
527     {
528         // $("log").innerHTML = "Val " + this.step_cur + " N: " + this.step_n + "<br>";
529         if (this.step_cur == 0) {
530             var date = new Date();
531             // $("logz").innerHTML = "Timestart: " + date + "<br>";
532         }
533         if (this.step_cur <= this.step_n) {
534             this.img.style.left = this.x0 + this.dx * this.step_cur;
535             this.img.style.top  = this.y0 + this.dy * this.step_cur;
536             this.step_cur++;
537             setTimeout(function(obj){ obj.animate(); }, this.deltat, this);
538             if (this.step_cur == this.step_free && this.st != null) {
539                 if (this.st.st_loc < this.st.st_loc_new) {
540                     // alert("QUI1  " + this.step_cur + "  ZZ  "+  this.step_free);
541                     this.st.st_loc++;
542                     this.st = null;
543                 }
544             }
545         }
546         else {
547             this.img.style.left = this.x1;
548             this.img.style.top  = this.y1;
549             // $("logz").innerHTML += "xxxxxxxxxxxxxxxCLEAR<br>";
550             var date = new Date();
551             // $("logz").innerHTML += "Timestop: " + date + "<br>";
552
553             if (this.action != null) {
554                 eval(this.action);
555             }
556
557             if (this.st != null && this.st.st_loc < this.st.st_loc_new) {
558                 // alert("QUI2");
559                 this.st.st_loc++;
560                 this.st = null;
561             }
562             if (this.srcend != null) {
563                 this.img.src = this.srcend;
564             }
565         }
566     }
567 }
568
569 function div_show(div)
570 {
571     div.style.top = parseInt((document.body.clientHeight - parseInt(getStyle(div,"height", "height"))) / 2) + document.body.scrollTop;
572     div.style.visibility = "visible";
573 }
574
575 function notify_ex(st, text, tout, butt, w, h, is_opa, block_time)
576 {
577     var clo, box;
578     var t = this;
579     
580     this.st = st;
581
582     this.ancestor = document.body;
583     
584     this.st.st_loc_new++;
585
586     clo = document.createElement("input");
587     clo.type = "submit";
588     clo.className = "button";
589     clo.style.bottom = "4px";
590     clo.obj = this;
591     if (block_time > 0) {
592         clo.value = "leggere, prego.";
593         this.butt = butt;
594     }
595     else {
596         clo.value = butt;
597         clo.onclick = this.input_hide;
598     }
599
600     clodiv = document.createElement("div");
601     clodiv.className = "notify_clo";
602     this.clo = clo;
603     this.clodiv = clodiv;
604
605     clodiv.appendChild(clo);
606
607     cont = document.createElement("div");
608
609     cont.style.borderBottomStyle = "solid";
610     cont.style.borderBottomWidth = "1px";
611     cont.style.borderBottomColor = "gray";
612     cont.style.height = (h - 30)+"px";
613     cont.style.overflow = "auto";
614     cont.innerHTML = text;
615
616     box =  document.createElement("div");
617     if (is_opa)
618         box.className = "notify_opaque";
619     else
620         box.className = "notify";
621
622     box.style.zIndex = 200;
623     box.style.width  = w+"px";
624     box.style.marginLeft  = -parseInt(w/2)+"px";
625     box.style.height = h+"px";
626     box.style.top = parseInt((document.body.clientHeight - h) / 2) + document.body.scrollTop;
627     box.appendChild(cont);
628     box.appendChild(clodiv);
629     box.style.visibility = "visible";
630
631     this.notitag = box;
632     
633     this.ancestor.appendChild(box);
634     
635     this.toutid = setTimeout(function(obj){ obj.unblock(); }, tout, this);
636
637     if (block_time != 0) {
638         this.tblkid = setTimeout(function(obj){ obj.clo.value = obj.butt; obj.clo.onclick = obj.input_hide; formsub_hilite(obj.clo); obj.clo.focus(); }, block_time, this);
639     }
640     else {
641         formsub_hilite(clo);
642         clo.focus();
643     }
644
645 }
646
647
648 notify_ex.prototype = {
649     ancestor: null,
650     st: null,
651     notitag: null,
652     toutid: null,
653     clo: null,
654     clodiv: null, 
655     butt: null,
656     tblkid: null,
657
658     unblock: function()
659     {
660         if (this.st.st_loc < this.st.st_loc_new) {
661             this.st.st_loc++;
662         }
663     },
664     
665     hide: function()
666     {
667         clearTimeout(this.toutid);
668         this.ancestor.removeChild(this.notitag);
669         this.unblock();
670     },
671
672     input_hide: function()
673     {
674         clearTimeout(this.obj.toutid);
675         this.obj.ancestor.removeChild(this.obj.notitag);
676         this.obj.unblock();
677     }
678 }
679
680
681 notify.prototype = notify_ex.prototype;                // Define sub-class
682 notify.prototype.constructor = notify;
683 notify.baseConstructor = notify_ex;
684 notify.superClass = notify_ex.prototype;
685
686 function notify(st, text, tout, butt, w, h)
687 {
688     notify_ex.call(this, st, text, tout, butt, w, h, false, 0);
689 }
690         
691
692 function $(id) { 
693     return document.getElementById(id); 
694 }
695
696 function globst() {
697     this.st = -1;
698     this.st_loc = -1;
699     this.st_loc_new = -1;
700     this.comms  = new Array;
701 }
702
703
704
705 function remark_step()
706 {
707     var ct = $("remark").l_remct;
708     
709     if (ct != 0) {
710         ct++;
711         if (ct > 2)
712             ct = 1;
713         $("remark").className = "remark"+ct;
714         $("remark").l_remct = ct;
715         setTimeout(remark_step,500);
716     }
717     else
718         $("remark").className = "remark0";
719     
720     return;
721 }
722
723 function remark_on()
724 {
725     if ($("remark").l_remct == 0) {
726         $("remark").l_remct = 1;
727         setTimeout(remark_step,500);
728     }
729 }
730
731 function remark_off()
732 {
733     $("remark").l_remct = 0;
734     $("remark").className = "remark0";
735 }
736
737
738 function italizer(ga)
739 {
740     var pre, pos;
741     if (ga[0] & 2) 
742         return "<i>"+ga[1]+"</i>";
743     else
744         return ga[1];
745 }
746
747
748 function exitlock_show(num, islock)
749 {
750     g_exitlock = num;
751
752     num = (num < 3 ? num : 3);
753     $("exitlock").src = "img/exitlock"+num+(islock ? "n" : "y")+".png";
754     // alert("EXITLOCK: "+$("exitlock").src);
755     $("exitlock").style.visibility = "visible";
756 }
757
758 var fin = 0;
759
760 //    exitlock_show(0, true);
761
762
763 var chatt_lines = new Array();
764 var chatt_lines_n = 0;
765
766 var CHATT_MAXLINES = 40;
767
768 function user_decorator(user)
769 {
770     var name;
771     var flags = user[0];
772     if ((flags & 0x03) != 0)
773         name = "<span class='au" + (flags & 0x03) + "'>"+user[1]+"</span>";
774     else
775         name = user[1];
776
777     return (name);
778 }
779
780 function user_dec_and_state(el)
781 {
782     var content = "";
783     var val_el;
784
785     content = user_decorator(el);
786     content += state_add(el[0]);
787     
788     return (content);
789 }
790
791
792 /* PRO CHATT */
793 function chatt_sub(dt,data,str)
794 {
795     var must_scroll = false;
796     var name;
797     var flags;
798     var isauth;
799     var bolder = [ (data[0] | 1), data[1] ];
800     name = user_decorator(bolder);
801
802     if ($("txt").scrollTop + parseInt(getStyle($("txt"),"height", "height")) -  $("txt").scrollHeight >= 0)
803         must_scroll = true;
804
805     // alert("ARRIVA NAME: "+ name + "  STR:"+str);
806     if (chatt_lines_n == CHATT_MAXLINES) {
807         $("txt").innerHTML = "";
808         for (i = 0 ; i < (CHATT_MAXLINES - 1) ; i++) {
809             chatt_lines[i] = chatt_lines[i+1];
810             $("txt").innerHTML += chatt_lines[i];
811         }
812         chatt_lines[i] = dt+name+": "+str+ "<br>";
813         $("txt").innerHTML += chatt_lines[i];
814     }
815     else {
816         chatt_lines[chatt_lines_n] = dt+name+": "+str+ "<br>";
817         $("txt").innerHTML += chatt_lines[chatt_lines_n];
818         chatt_lines_n++;
819     }
820     // $("txt").innerHTML;
821
822     
823     if (must_scroll) {
824         $("txt").scrollTop = 10000000;
825     }
826     // alert("scTOP "+$("txt").scrollTop+"  scHEIGHT: "+$("txt").scrollHeight+" HEIGHT: "+getStyle($("txt"),"height", "height") );
827 }
828
829 /*
830  *  GESTIONE DEI COOKIES
831  */
832 function createCookie(name,value,hours,path) {
833         if (hours) {
834                 var date = new Date();
835                 date.setTime(date.getTime()+(hours*60*60*1000));
836                 var expires = "; expires="+date.toGMTString();
837         }
838         else var expires = "";
839         document.cookie = name+"="+value+expires+"; path="+path;
840 }
841
842 function readCookie(name) {
843         var nameEQ = name + "=";
844         var ca = document.cookie.split(';');
845         for(var i=0;i < ca.length;i++) {
846                 var c = ca[i];
847                 while (c.charAt(0)==' ') c = c.substring(1,c.length);
848                 if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
849         }
850         return null;
851 }
852
853 function eraseCookie(name) {
854         createCookie(name,"",-1);
855 }
856
857 function onbeforeunload_cb () {
858     return("");
859 }
860
861 function onunload_cb () {
862     
863     if (typeof(hstm) != "undefined")
864         hstm.the_end = true; 
865
866     act_shutdown();
867     
868     return(false);
869 }
870
871 function room_checkspace(emme,tables,inpe)
872 {
873     nome = "<b>";
874     for (i = 0 ; i < emme ; i++) 
875         nome += "m";
876     nome += "</b>";
877
878     alta = "";
879     for (i = 0 ; i < 5 ; i++) 
880         alta += nome+"<br>";
881
882     for (i = 0 ; i < tables ; i++) {
883         $("table"+i).innerHTML = alta;
884         // MLANG Mi siedo.
885         $("table_act"+i).innerHTML = "<input type=\"button\" class=\"button\" name=\"xhenter"+i+"\"  value=\""+mlang_commons['btn_sit'][g_lang]+"\" onclick=\"act_sitdown(1);\">";
886         }
887
888     stand = "<table class=\"table_standup\"><tbody><tr>";
889     for (i = 0 ; i < inpe ; i++) {
890         stand += "<td>"+nome+"</td>";
891         if ((i+1) % 4 == 0) {
892             stand += "</tr><tr>";
893         }
894     }
895     stand += "</tr>";
896     $("standup").innerHTML = stand;
897
898     // VERIFY: what is this button ?
899     // MLANG Esco.
900     $("esco").innerHTML = "<input class=\"button\" name=\"logout\" type=\"button\" value=\""+mlang_commons['btn_exit'][g_lang]+"\" onclick=\"act_logout();\" type=\"button\">";
901 }
902
903 function  unescapeHTML(cont) {
904     var div = document.createElement('div');
905     var memo = "";
906     var i;
907
908     div.innerHTML = cont;
909     if (div.childNodes[0]) {
910         if (div.childNodes.length > 1) {
911             if (div.childNodes.toArray)
912                 alert("si puo");
913             else {
914                 var length = div.childNodes.length, results = new Array(length);
915             while (length--)
916                 results[length] = div.childNodes[length];
917                 
918             for (i=0 ; i<results.length ; i++)
919                 memo = memo + results[i].nodeValue;
920             }
921
922             return (memo);
923         }
924         else {
925             return (div.childNodes[0].nodeValue);
926         }
927     }
928     else {
929         return ('');
930     }
931 }
932
933 function playsound(tag, sound) {
934    // g_withflash is a global var
935    if (g_withflash) {
936       $(tag).innerHTML = '<OBJECT classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" '+
937 'codebase="http://active.macromedia.com/flash2/cabs/swflash.cab#version=4,0,0,0" id="mysound" WIDTH=1 HEIGHT=1>' +
938 '<PARAM NAME="movie" VALUE="../playsound.swf"><PARAM NAME="PLAY" VALUE="true"><PARAM NAME="LOOP" VALUE="false">' +
939 '<PARAM NAME=FlashVars VALUE="streamUrl='+sound+'">' +
940 '<EMBED swliveconnect="true" name="mysound" src="../playsound.swf" FlashVars="streamUrl='+sound+'" PLAY="true" LOOP="false" '+
941 ' WIDTH=1 HEIGHT=1 TYPE="application/x-shockwave-flash" PLUGINSPAGE="http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash"></OBJECT>';
942    }
943 }
944
945 function topbanner_init()
946 {
947     setInterval(topbanner_cb, 666);
948 ;
949 }
950
951 function topbanner_cb()
952 {
953     var a, b;
954
955     a = $('topbanner').style.backgroundColor;
956     b = $('topbanner').style.borderLeftColor;
957
958     $('topbanner').style.backgroundColor = b;
959     $('topbanner').style.borderColor = a+" "+a+" "+a+" "+a;
960
961     // console.log("A: "+a+"  B: "+b);
962 }
963
964 function sidebanner_init()
965 {
966     setInterval(sidebanner_cb, 666);
967 }
968
969 function sidebanner2_init()
970 {
971     setInterval(sidebanner2_cb, 666);
972 }
973
974 function sidebanner_cb()
975 {
976     var a, b;
977
978     a = $('sidebanner').style.backgroundColor;
979     b = $('sidebanner').style.borderLeftColor;
980
981     $('sidebanner').style.backgroundColor = b;
982     $('sidebanner').style.borderColor = a+" "+a+" "+a+" "+a;
983
984     // console.log("A: "+a+"  B: "+b);
985 }
986
987 function sidebanner2_cb()
988 {
989     var a, b;
990
991     a = $('sidebanner2').style.backgroundColor;
992     b = $('sidebanner2').style.borderLeftColor;
993
994     $('sidebanner2').style.backgroundColor = b;
995     $('sidebanner2').style.borderColor = a+" "+a+" "+a+" "+a;
996
997     // console.log("A: "+a+"  B: "+b);
998 }
999
1000
1001 function langtolng(lang)
1002 {
1003     if (lang == "en")
1004         return ("-en");
1005     else
1006         return ("");
1007 }
1008
1009 function formtext_hilite(obj)
1010 {
1011     obj.className = 'input_text';
1012     addEvent(obj, "focus", function () { this.className = 'input_text_hi'; });
1013     addEvent(obj, "blur",  function () { this.className = 'input_text'; });
1014 }
1015
1016 function formsub_hilite(obj)
1017 {
1018     obj.className = 'input_sub';
1019     addEvent(obj, "focus", function () { this.className = 'input_sub_hi'; });
1020     addEvent(obj, "blur",  function () { this.className = 'input_sub'; });
1021 }
1022
1023 // return the value of the radio button that is checked
1024 // return an empty string if none are checked, or
1025 // there are no radio buttons
1026 function get_checked_value(radioObj) {
1027         if(!radioObj)
1028                 return "";
1029         var radioLength = radioObj.length;
1030         if(radioLength == undefined)
1031                 if(radioObj.checked)
1032                         return radioObj.value;
1033                 else
1034                         return "";
1035         for(var i = 0; i < radioLength; i++) {
1036                 if(radioObj[i].checked) {
1037                         return radioObj[i].value;
1038                 }
1039         }
1040         return "";
1041 }
1042
1043 // set the radio button with the given value as being checked
1044 // do nothing if there are no radio buttons
1045 // if the given value does not exist, all the radio buttons
1046 // are reset to unchecked
1047 function set_checked_value(radioObj, newValue) {
1048         if(!radioObj)
1049                 return;
1050         var radioLength = radioObj.length;
1051         if(radioLength == undefined) {
1052                 radioObj.checked = (radioObj.value == newValue.toString());
1053                 return;
1054         }
1055         for(var i = 0; i < radioLength; i++) {
1056                 radioObj[i].checked = false;
1057                 if(radioObj[i].value == newValue.toString()) {
1058                         radioObj[i].checked = true;
1059                 }
1060         }
1061 }