app level keepalive (new ping message) added
[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(g_debug) == 'number' && g_debug > 0
254         && typeof(console) == 'object' && typeof(console.log) == 'function') {
255             var ldate = new Date();
256             console.log(ldate.getTime()+':MESG:'+mesg);
257     }
258     xhr_wr.send(null);
259
260     if (!is_conn) {
261         if (xhr_wr.responseText != null) {
262             eval(xhr_wr.responseText);
263         }
264     }
265 }
266
267 /*
268   request to server
269   server_request([arg0=arg1[, arg2=arg3[, ...]]])
270  */
271 function server_request()
272 {
273     var xhr_wr = createXMLHttpRequest();
274     var i, collect = "";
275
276     if (arguments.length > 0) {
277         for (i = 0 ; i < arguments.length ; i+= 2) {
278             collect += (i == 0 ? "" : "&") + arguments[i] + "=" + encodeURIComponent(arguments[i+1]);
279         }
280     }
281     // alert("Args: "+arguments.length);
282
283     var is_conn = (sess == "not_connected" ? false : true);
284     
285     // console.log("server_request:preresp: "+xhr_wr.responseText);
286
287     xhr_wr.open('GET', 'index_wr.php?'+(is_conn ? 'sess='+sess+'&' : '')+collect, false);
288     xhr_wr.onreadystatechange = function() { return; };
289     xhr_wr.send(null);
290     
291     if (xhr_wr.responseText != null) {
292         // console.log("server_request:resp: "+xhr_wr.responseText);
293         return (xhr_wr.responseText);
294     } 
295     else
296         return (null);
297 }
298
299 /* Stat: CHAT and TABLE */
300
301 function chatt_checksend(obj,e)
302 {
303     var keynum;
304     var keychar;
305     var numcheck;
306
307     if(window.event) { // IE
308         keynum = e.keyCode;
309     }
310     else if(e.which) { // Netscape/Firefox/Opera
311         keynum = e.which;
312     }
313     // alert("OBJ: "+obj);
314     if (keynum == 13 && obj.value != "") { // Enter
315         act_chatt(obj.value);
316         obj.value = "";
317     }
318 }
319 function act_chatt(value)
320 {
321     send_mesg("chatt|"+encodeURIComponent(value));
322     /*
323     obj.disabled = true;
324     obj.value = "";
325     obj.disabled = false;
326     obj.focus();
327     */
328     return false;
329 }
330
331 /* Stat: ROOM */
332 function act_ping()
333 {
334     send_mesg("ping");
335 }
336
337 function act_sitdown(table)
338 {
339     send_mesg("sitdown|"+table);
340 }
341
342 function act_wakeup()
343 {
344     send_mesg("wakeup");
345 }
346
347 function act_splash()
348 {
349     send_mesg("splash");
350 }
351
352 function act_help()
353 {
354     send_mesg("help");
355 }
356
357 function act_passwdhowto()
358 {
359     send_mesg("passwdhowto");
360 }
361
362 function act_mesgtoadm()
363 {
364     send_mesg("mesgtoadm");
365 }
366
367 function act_tav()
368 {
369     act_chatt('/tav '+$('txt_in').value); 
370     $('txt_in').value = '';
371 }
372
373 function act_about()
374 {
375     send_mesg("about");
376 }
377
378 function act_placing()
379 {
380     send_mesg("placing");
381 }
382
383 function act_roadmap()
384 {
385     send_mesg("roadmap");
386 }
387
388 function act_whysupport()
389 {
390     send_mesg("whysupport");
391 }
392
393 function act_lascio()
394 {
395     send_mesg("lascio");
396 }
397
398 function safelascio()
399 {
400     var res;
401     // MLANG "Sei sicuro di volere lasciare questa mano?"
402     res = window.confirm(mlang_commons['gamleav'][g_lang]);
403     if (res)
404         act_lascio();
405 }
406
407 function act_logout(exitlock)
408 {
409     send_mesg("logout|"+exitlock);
410 }
411
412 function act_reloadroom()
413 {
414     window.onunload = null;
415     window.onbeforeunload = null;
416     document.location.assign("index.php");
417 }
418
419 function act_shutdown()
420 {
421     var c = 0;
422
423     send_mesg("shutdown");
424     // while (xhr_wr.readyState != 4)
425     //  c++;
426 }
427
428 function postact_logout()
429 {
430     // alert("postact_logout");
431     try { 
432         hstm.abort();
433     } catch (e) {}
434
435     // eraseCookie("sess");
436     document.location.assign("index.php");
437 }
438
439 /*
440   function slowimg(img,x1,y1,deltat,free,action,srcend)
441   img    - image to move
442   x1,y1  - destination coords
443   deltat - time for each frame (in msec)
444   free   - when the release the local block for other operations (range: 0 - 1)
445   action - function to run when the image is moved
446   srcend - image to switch when the image is moved
447 */
448
449 function sleep(st, delay)
450 {
451     // alert("LOC_NEW PRE: "+st.st_loc_new);
452
453     st.st_loc_new++;
454
455     setTimeout(function(obj){ if (obj.st_loc_new > obj.st_loc) { obj.st_loc++; }},
456                delay, st);
457 }
458
459 function slowimg(img,x1,y1,deltat,free,action,srcend) {
460     this.img = img;
461
462     // this.x0  = parseInt(document.defaultView.getComputedStyle(this.img, "").getPropertyValue("left"));
463     this.x0 = parseInt(getStyle(this.img,"left", "left"));
464 // alert("img.x0 = "+this.x0);
465     // this.y0  = parseInt(document.defaultView.getComputedStyle(this.img, "").getPropertyValue("top"));
466     this.y0  = parseInt(getStyle(this.img,"top", "top"));
467     this.x1  = x1;
468     this.y1  = y1;
469     this.deltat = deltat;
470     this.free = free;
471     this.action = action;
472     this.srcend = srcend;
473 }
474
475 slowimg.prototype = {
476     img: null, 
477     st: null,
478     x0: 0,
479     y0: 0,
480     x1: 0,
481     y1: 0,
482     dx: 0,
483     dy: 0,
484     free: 0,
485     step_n:    0,
486     step_cur:  0,
487     step_free: 0,
488     time:      0,
489     deltat:   40,
490     tout: 0,
491     action: null,
492     srcend: null,
493     
494     setstart: function(x0,y0)
495     {
496         this.x0 = x0;
497         this.y0 = y0;
498     },
499     
500     setaction: function(act)
501     {
502         this.action = act;
503     },
504     
505
506     settime: function(time) 
507     {
508         this.time = (time < this.deltat ? this.deltat : time);
509         this.step_n = parseInt(this.time / this.deltat);
510         this.dx = (this.x1 - this.x0) / this.step_n;
511         this.dy = (this.y1 - this.y0) / this.step_n;
512         if (this.step_n * this.deltat == this.time) {
513             this.step_n--;
514         }
515         if (this.free < 1) {
516             this.step_free = parseInt(this.step_n * this.free);
517         }
518     },
519     
520     start: function(st)
521     {
522         // $("logz").innerHTML += "               xxxxxxxxxxxxxxxxxxxxxSTART<br>";
523         this.st = st;
524         this.st.st_loc_new++;
525         
526         this.img.style.visibility = "visible";
527         setTimeout(function(obj){ obj.animate(); }, this.deltat, this);
528     },
529     
530     animate: function()
531     {
532         // $("log").innerHTML = "Val " + this.step_cur + " N: " + this.step_n + "<br>";
533         if (this.step_cur == 0) {
534             var date = new Date();
535             // $("logz").innerHTML = "Timestart: " + date + "<br>";
536         }
537         if (this.step_cur <= this.step_n) {
538             this.img.style.left = this.x0 + this.dx * this.step_cur;
539             this.img.style.top  = this.y0 + this.dy * this.step_cur;
540             this.step_cur++;
541             setTimeout(function(obj){ obj.animate(); }, this.deltat, this);
542             if (this.step_cur == this.step_free && this.st != null) {
543                 if (this.st.st_loc < this.st.st_loc_new) {
544                     // alert("QUI1  " + this.step_cur + "  ZZ  "+  this.step_free);
545                     this.st.st_loc++;
546                     this.st = null;
547                 }
548             }
549         }
550         else {
551             this.img.style.left = this.x1;
552             this.img.style.top  = this.y1;
553             // $("logz").innerHTML += "xxxxxxxxxxxxxxxCLEAR<br>";
554             var date = new Date();
555             // $("logz").innerHTML += "Timestop: " + date + "<br>";
556
557             if (this.action != null) {
558                 eval(this.action);
559             }
560
561             if (this.st != null && this.st.st_loc < this.st.st_loc_new) {
562                 // alert("QUI2");
563                 this.st.st_loc++;
564                 this.st = null;
565             }
566             if (this.srcend != null) {
567                 this.img.src = this.srcend;
568             }
569         }
570     }
571 }
572
573 function div_show(div)
574 {
575     div.style.top = parseInt((document.body.clientHeight - parseInt(getStyle(div,"height", "height"))) / 2) + document.body.scrollTop;
576     div.style.visibility = "visible";
577 }
578
579 function notify_ex(st, text, tout, butt, w, h, is_opa, block_time)
580 {
581     var clo, box;
582     var t = this;
583     
584     this.st = st;
585
586     this.ancestor = document.body;
587     
588     this.st.st_loc_new++;
589
590     clo = document.createElement("input");
591     clo.type = "submit";
592     clo.className = "button";
593     clo.style.bottom = "4px";
594     clo.obj = this;
595     if (block_time > 0) {
596         clo.value = "leggere, prego.";
597         this.butt = butt;
598     }
599     else {
600         clo.value = butt;
601         clo.onclick = this.input_hide;
602     }
603
604     clodiv = document.createElement("div");
605     clodiv.className = "notify_clo";
606     this.clo = clo;
607     this.clodiv = clodiv;
608
609     clodiv.appendChild(clo);
610
611     cont = document.createElement("div");
612
613     cont.style.borderBottomStyle = "solid";
614     cont.style.borderBottomWidth = "1px";
615     cont.style.borderBottomColor = "gray";
616     cont.style.height = (h - 30)+"px";
617     cont.style.overflow = "auto";
618     cont.innerHTML = text;
619
620     box =  document.createElement("div");
621     if (is_opa)
622         box.className = "notify_opaque";
623     else
624         box.className = "notify";
625
626     box.style.zIndex = 200;
627     box.style.width  = w+"px";
628     box.style.marginLeft  = -parseInt(w/2)+"px";
629     box.style.height = h+"px";
630     box.style.top = parseInt((document.body.clientHeight - h) / 2) + document.body.scrollTop;
631     box.appendChild(cont);
632     box.appendChild(clodiv);
633     box.style.visibility = "visible";
634
635     this.notitag = box;
636     
637     this.ancestor.appendChild(box);
638     
639     this.toutid = setTimeout(function(obj){ obj.unblock(); }, tout, this);
640
641     if (block_time != 0) {
642         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);
643     }
644     else {
645         formsub_hilite(clo);
646         clo.focus();
647     }
648
649 }
650
651
652 notify_ex.prototype = {
653     ancestor: null,
654     st: null,
655     notitag: null,
656     toutid: null,
657     clo: null,
658     clodiv: null, 
659     butt: null,
660     tblkid: null,
661
662     unblock: function()
663     {
664         if (this.st.st_loc < this.st.st_loc_new) {
665             this.st.st_loc++;
666         }
667     },
668     
669     hide: function()
670     {
671         clearTimeout(this.toutid);
672         this.ancestor.removeChild(this.notitag);
673         this.unblock();
674     },
675
676     input_hide: function()
677     {
678         clearTimeout(this.obj.toutid);
679         this.obj.ancestor.removeChild(this.obj.notitag);
680         this.obj.unblock();
681     }
682 }
683
684
685 notify.prototype = notify_ex.prototype;                // Define sub-class
686 notify.prototype.constructor = notify;
687 notify.baseConstructor = notify_ex;
688 notify.superClass = notify_ex.prototype;
689
690 function notify(st, text, tout, butt, w, h)
691 {
692     notify_ex.call(this, st, text, tout, butt, w, h, false, 0);
693 }
694         
695
696 function $(id) { 
697     return document.getElementById(id); 
698 }
699
700
701 function globst() {
702     this.st = -1;
703     this.st_loc = -1;
704     this.st_loc_new = -1;
705     this.comms  = new Array;
706 }
707
708 globst.prototype = {
709     st: -1,
710     st_loc: -1,
711     st_loc_new: -1,
712     comms: null,
713     sleep_hdl: null,
714
715     sleep: function(delay) {
716         st.st_loc_new++;
717
718         if (!this.the_end) {
719             this.sleep_hdl = setTimeout(function(obj){ if (obj.st_loc_new > obj.st_loc) { obj.st_loc++; obj.sleep_hdl = null; }},
720                                         delay, this);
721         }
722     },
723
724     abort: function() {
725         if (this.sleep_hdl != null) {
726             clearTimeout(this.sleep_hdl);
727             this.sleep_hdl = null;
728         }
729     }
730 }
731
732 function remark_step()
733 {
734     var ct = $("remark").l_remct;
735     
736     if (ct != 0) {
737         ct++;
738         if (ct > 2)
739             ct = 1;
740         $("remark").className = "remark"+ct;
741         $("remark").l_remct = ct;
742         setTimeout(remark_step,500);
743     }
744     else
745         $("remark").className = "remark0";
746     
747     return;
748 }
749
750 function remark_on()
751 {
752     if ($("remark").l_remct == 0) {
753         $("remark").l_remct = 1;
754         setTimeout(remark_step,500);
755     }
756 }
757
758 function remark_off()
759 {
760     $("remark").l_remct = 0;
761     $("remark").className = "remark0";
762 }
763
764
765 function italizer(ga)
766 {
767     var pre, pos;
768     if (ga[0] & 2) 
769         return "<i>"+ga[1]+"</i>";
770     else
771         return ga[1];
772 }
773
774
775 function exitlock_show(num, islock)
776 {
777     g_exitlock = num;
778
779     num = (num < 3 ? num : 3);
780     $("exitlock").src = "img/exitlock"+num+(islock ? "n" : "y")+".png";
781     // alert("EXITLOCK: "+$("exitlock").src);
782     $("exitlock").style.visibility = "visible";
783 }
784
785 var fin = 0;
786
787 //    exitlock_show(0, true);
788
789
790 var chatt_lines = new Array();
791 var chatt_lines_n = 0;
792
793 var CHATT_MAXLINES = 40;
794
795 function user_decorator(user)
796 {
797     var name;
798     var flags = user[0];
799     if ((flags & 0x03) != 0)
800         name = "<span class='au" + (flags & 0x03) + "'>"+user[1]+"</span>";
801     else
802         name = user[1];
803
804     return (name);
805 }
806
807 function user_dec_and_state(el)
808 {
809     var content = "";
810     var val_el;
811
812     content = user_decorator(el);
813     content += state_add(el[0]);
814     
815     return (content);
816 }
817
818
819 /* PRO CHATT */
820 function chatt_sub(dt,data,str)
821 {
822     var must_scroll = false;
823     var name;
824     var flags;
825     var isauth;
826     var bolder = [ (data[0] | 1), data[1] ];
827     name = user_decorator(bolder);
828
829     if ($("txt").scrollTop + parseInt(getStyle($("txt"),"height", "height")) -  $("txt").scrollHeight >= 0)
830         must_scroll = true;
831
832     // alert("ARRIVA NAME: "+ name + "  STR:"+str);
833     if (chatt_lines_n == CHATT_MAXLINES) {
834         $("txt").innerHTML = "";
835         for (i = 0 ; i < (CHATT_MAXLINES - 1) ; i++) {
836             chatt_lines[i] = chatt_lines[i+1];
837             $("txt").innerHTML += chatt_lines[i];
838         }
839         chatt_lines[i] = dt+name+": "+str+ "<br>";
840         $("txt").innerHTML += chatt_lines[i];
841     }
842     else {
843         chatt_lines[chatt_lines_n] = dt+name+": "+str+ "<br>";
844         $("txt").innerHTML += chatt_lines[chatt_lines_n];
845         chatt_lines_n++;
846     }
847     // $("txt").innerHTML;
848
849     
850     if (must_scroll) {
851         $("txt").scrollTop = 10000000;
852     }
853     // alert("scTOP "+$("txt").scrollTop+"  scHEIGHT: "+$("txt").scrollHeight+" HEIGHT: "+getStyle($("txt"),"height", "height") );
854 }
855
856 /*
857  *  GESTIONE DEI COOKIES
858  */
859 function createCookie(name,value,hours,path) {
860         if (hours) {
861                 var date = new Date();
862                 date.setTime(date.getTime()+(hours*60*60*1000));
863                 var expires = "; expires="+date.toGMTString();
864         }
865         else var expires = "";
866         document.cookie = name+"="+value+expires+"; path="+path;
867 }
868
869 function readCookie(name) {
870         var nameEQ = name + "=";
871         var ca = document.cookie.split(';');
872         for(var i=0;i < ca.length;i++) {
873                 var c = ca[i];
874                 while (c.charAt(0)==' ') c = c.substring(1,c.length);
875                 if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
876         }
877         return null;
878 }
879
880 function eraseCookie(name) {
881         createCookie(name,"",-1);
882 }
883
884 function onbeforeunload_cb () {
885     return("");
886 }
887
888 function onunload_cb () {
889     
890     if (typeof(hstm) != "undefined")
891         hstm.the_end = true; 
892
893     act_shutdown();
894     
895     return(false);
896 }
897
898 function room_checkspace(emme,tables,inpe)
899 {
900     nome = "<b>";
901     for (i = 0 ; i < emme ; i++) 
902         nome += "m";
903     nome += "</b>";
904
905     alta = "";
906     for (i = 0 ; i < 5 ; i++) 
907         alta += nome+"<br>";
908
909     for (i = 0 ; i < tables ; i++) {
910         $("table"+i).innerHTML = alta;
911         // MLANG Mi siedo.
912         $("table_act"+i).innerHTML = "<input type=\"button\" class=\"button\" name=\"xhenter"+i+"\"  value=\""+mlang_commons['btn_sit'][g_lang]+"\" onclick=\"act_sitdown(1);\">";
913         }
914
915     stand = "<table class=\"table_standup\"><tbody><tr>";
916     for (i = 0 ; i < inpe ; i++) {
917         stand += "<td>"+nome+"</td>";
918         if ((i+1) % 4 == 0) {
919             stand += "</tr><tr>";
920         }
921     }
922     stand += "</tr>";
923     $("standup").innerHTML = stand;
924
925     // VERIFY: what is this button ?
926     // MLANG Esco.
927     $("esco").innerHTML = "<input class=\"button\" name=\"logout\" type=\"button\" value=\""+mlang_commons['btn_exit'][g_lang]+"\" onclick=\"act_logout();\" type=\"button\">";
928 }
929
930 function  unescapeHTML(cont) {
931     var div = document.createElement('div');
932     var memo = "";
933     var i;
934
935     div.innerHTML = cont;
936     if (div.childNodes[0]) {
937         if (div.childNodes.length > 1) {
938             if (div.childNodes.toArray)
939                 alert("si puo");
940             else {
941                 var length = div.childNodes.length, results = new Array(length);
942             while (length--)
943                 results[length] = div.childNodes[length];
944                 
945             for (i=0 ; i<results.length ; i++)
946                 memo = memo + results[i].nodeValue;
947             }
948
949             return (memo);
950         }
951         else {
952             return (div.childNodes[0].nodeValue);
953         }
954     }
955     else {
956         return ('');
957     }
958 }
959
960 function playsound(tag, sound) {
961    // g_withflash is a global var
962    if (g_withflash) {
963       $(tag).innerHTML = '<OBJECT classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" '+
964 'codebase="http://active.macromedia.com/flash2/cabs/swflash.cab#version=4,0,0,0" id="mysound" WIDTH=1 HEIGHT=1>' +
965 '<PARAM NAME="movie" VALUE="../playsound.swf"><PARAM NAME="PLAY" VALUE="true"><PARAM NAME="LOOP" VALUE="false">' +
966 '<PARAM NAME=FlashVars VALUE="streamUrl='+sound+'">' +
967 '<EMBED swliveconnect="true" name="mysound" src="../playsound.swf" FlashVars="streamUrl='+sound+'" PLAY="true" LOOP="false" '+
968 ' WIDTH=1 HEIGHT=1 TYPE="application/x-shockwave-flash" PLUGINSPAGE="http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash"></OBJECT>';
969    }
970 }
971
972 function topbanner_init()
973 {
974     setInterval(topbanner_cb, 666);
975 ;
976 }
977
978 function topbanner_cb()
979 {
980     var a, b;
981
982     a = $('topbanner').style.backgroundColor;
983     b = $('topbanner').style.borderLeftColor;
984
985     $('topbanner').style.backgroundColor = b;
986     $('topbanner').style.borderColor = a+" "+a+" "+a+" "+a;
987
988     // console.log("A: "+a+"  B: "+b);
989 }
990
991 function sidebanner_init()
992 {
993     setInterval(sidebanner_cb, 666);
994 }
995
996 function sidebanner2_init()
997 {
998     setInterval(sidebanner2_cb, 666);
999 }
1000
1001 function sidebanner_cb()
1002 {
1003     var a, b;
1004
1005     a = $('sidebanner').style.backgroundColor;
1006     b = $('sidebanner').style.borderLeftColor;
1007
1008     $('sidebanner').style.backgroundColor = b;
1009     $('sidebanner').style.borderColor = a+" "+a+" "+a+" "+a;
1010
1011     // console.log("A: "+a+"  B: "+b);
1012 }
1013
1014 function sidebanner2_cb()
1015 {
1016     var a, b;
1017
1018     a = $('sidebanner2').style.backgroundColor;
1019     b = $('sidebanner2').style.borderLeftColor;
1020
1021     $('sidebanner2').style.backgroundColor = b;
1022     $('sidebanner2').style.borderColor = a+" "+a+" "+a+" "+a;
1023
1024     // console.log("A: "+a+"  B: "+b);
1025 }
1026
1027
1028 function langtolng(lang)
1029 {
1030     if (lang == "en")
1031         return ("-en");
1032     else
1033         return ("");
1034 }
1035
1036 function formtext_hilite(obj)
1037 {
1038     obj.className = 'input_text';
1039     addEvent(obj, "focus", function () { this.className = 'input_text_hi'; });
1040     addEvent(obj, "blur",  function () { this.className = 'input_text'; });
1041 }
1042
1043 function formsub_hilite(obj)
1044 {
1045     obj.className = 'input_sub';
1046     addEvent(obj, "focus", function () { this.className = 'input_sub_hi'; });
1047     addEvent(obj, "blur",  function () { this.className = 'input_sub'; });
1048 }
1049
1050 // return the value of the radio button that is checked
1051 // return an empty string if none are checked, or
1052 // there are no radio buttons
1053 function get_checked_value(radioObj) {
1054         if(!radioObj)
1055                 return "";
1056         var radioLength = radioObj.length;
1057         if(radioLength == undefined)
1058                 if(radioObj.checked)
1059                         return radioObj.value;
1060                 else
1061                         return "";
1062         for(var i = 0; i < radioLength; i++) {
1063                 if(radioObj[i].checked) {
1064                         return radioObj[i].value;
1065                 }
1066         }
1067         return "";
1068 }
1069
1070 // set the radio button with the given value as being checked
1071 // do nothing if there are no radio buttons
1072 // if the given value does not exist, all the radio buttons
1073 // are reset to unchecked
1074 function set_checked_value(radioObj, newValue) {
1075         if(!radioObj)
1076                 return;
1077         var radioLength = radioObj.length;
1078         if(radioLength == undefined) {
1079                 radioObj.checked = (radioObj.value == newValue.toString());
1080                 return;
1081         }
1082         for(var i = 0; i < radioLength; i++) {
1083                 radioObj[i].checked = false;
1084                 if(radioObj[i].value == newValue.toString()) {
1085                         radioObj[i].checked = true;
1086                 }
1087         }
1088 }
1089
1090 function url_append_arg(url, name, value)
1091 {
1092     var pos, sep, pref, rest;
1093
1094     if ((pos = url.indexOf('?'+name+'=')) == -1) {
1095         pos = url.indexOf('&'+name+'=');
1096     }
1097     if (pos == -1) {
1098         if ((pos = url.indexOf('?')) != -1)
1099             sep = '&';
1100         else
1101             sep = '?';
1102
1103         return (url+sep+name+"="+encodeURIComponent(value));
1104     }
1105     else {
1106         pref = url.substring(0, pos+1);
1107         rest = url.substring(pos+1);
1108         // alert("rest: "+rest+"  pos: "+pos);
1109         if ((pos = rest.indexOf('&')) != -1) {
1110             rest = rest.substring(pos);
1111         }
1112         else {
1113             rest = "";
1114         }
1115         return (pref+name+"="+encodeURIComponent(value)+rest);
1116     }
1117 }
1118
1119 function url_append_args(url)
1120 {
1121     var i, ret;
1122
1123     ret = url;
1124     for (i = 1 ; i < arguments.length-1 ; i+= 2) {
1125         ret = url_append_arg(ret, arguments[i], arguments[i+1]);
1126     }
1127
1128     return (ret);
1129 }
1130
1131 function url_complete(parent, url)
1132 {
1133     var p, p2, rest;
1134     var host = "", path = "";
1135
1136     // host extraction
1137     p = parent.indexOf("://");
1138     if (p > -1) {
1139         rest = parent.substring(p+3);
1140         p2 = rest.indexOf("/");
1141         if (p2 > -1) {
1142             host = parent.substring(0, p+3+p2);
1143             rest = parent.substring(p+3+p2);
1144         }
1145         else {
1146             host = rest;
1147             rest = "";
1148         }
1149     }
1150     else {
1151         rest = parent;
1152     }
1153
1154     // path extraction
1155     p = rest.lastIndexOf("/");
1156     if (p > -1) {
1157         path = rest.substring(0, p+1);
1158     }
1159
1160     // alert("host: ["+host+"]  path: ["+path+"]");
1161     if (url.substring(0,6) == 'http:/' || url.substring(0,7) == 'https:/') {
1162         return (url);
1163     }
1164     else if (url.substring(0,1) == '/') {
1165         return (host+url);
1166     }
1167     else {
1168         return (host+path+url);
1169     }
1170 }