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