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