code cleanup and better onclick callback management
[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' : 'Immagini 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                       'tit_list'  : { '0'  : { 'it' : '',
43                                                'en' : '' },
44                                       '1'  : { 'it' : '(solo aut.)',
45                                                'en' : '(only aut.)' },
46                                       '2'  : { 'it' : '(isolam.to)',
47                                                'en' : '(isolation)' } }
48                     };
49
50 function $(id) { return document.getElementById(id); }
51
52 function dec2hex(d, padding)
53 {
54     var hex = Number(d).toString(16);
55     padding = typeof (padding) === "undefined" || padding === null ? padding = 2 : padding;
56
57     while (hex.length < padding) {
58         hex = "0" + hex;
59     }
60
61     return hex;
62 }
63
64 function getStyle(x,IEstyleProp, MozStyleProp) 
65 {
66     if (x.currentStyle) {
67         var y = x.currentStyle[IEstyleProp];
68     } else if (window.getComputedStyle) {
69         var y = document.defaultView.getComputedStyle(x,null).getPropertyValue(MozStyleProp);
70     }
71     return y;
72 }
73
74 /* replacement of setInterval on IE */
75 (function(){
76     /*if not IE, do nothing*/
77     if(!document.uniqueID){return;};
78
79     /*Copy the default setInterval behavior*/
80     var nativeSetInterval = window.setInterval;
81     window.setInterval = function(fn,ms) {              
82         var param = [];
83         if(arguments.length <= 2)       {
84             return nativeSetInterval(fn,ms);
85         }
86         else {
87             for(var i=2;i<arguments.length;i+=1) {
88                 param[i-2] =  arguments[i];
89             }   
90         }
91         
92         if(typeof(fn)=='function') {
93             
94             return (function (fn,ms,param) {
95                 var fo = function () {                                                          
96                     fn.apply(window,param);
97                 };                      
98                 return nativeSetInterval(fo,ms); 
99             })(fn,ms,param);
100         }
101         else if(typeof(fn)=='string')
102         {
103             return  nativeSetInterval(fn,ms);
104         }
105         else
106         {
107             throw Error('setInterval Error\nInvalid function type');
108         };
109     };
110
111     /*Copy the default setTimeout behavior*/
112     var nativeSetTimeout = window.setTimeout;
113     window.setTimeout = function(fn,ms) {               
114         var param = [];
115         if(arguments.length <= 2)       {
116             return nativeSetTimeout(fn,ms);
117         }
118         else {
119             for(var i=2;i<arguments.length;i+=1) {
120                 param[i-2] =  arguments[i];
121             }   
122         }
123         
124         if(typeof(fn)=='function') {
125             
126             return (function (fn,ms,param) {
127                 var fo = function () {                                                          
128                     fn.apply(window,param);
129                 };                      
130                 return nativeSetTimeout(fo,ms); 
131             })(fn,ms,param);
132         }
133         else if(typeof(fn)=='string')
134         {
135             return  nativeSetTimeout(fn,ms);
136         }
137         else
138         {
139             throw Error('setTimeout Error\nInvalid function type');
140         };
141     };
142
143 })()
144
145 function addEvent(obj,type,fn)
146 {
147     if (obj.addEventListener) {
148         obj.addEventListener( type, fn, false);
149     }
150     else if (obj.attachEvent) {
151         obj["e"+type+fn] = fn;
152         obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
153         obj.attachEvent( "on"+type, obj[type+fn] );
154     }
155     else
156         throw new Error("Event registration not supported");
157 }
158
159 function removeEvent(obj,type,fn)
160 {
161     if (obj.removeEventListener) {
162         obj.removeEventListener( type, fn, false );
163     }
164     else if (obj.detachEvent) {
165         obj.detachEvent( "on"+type, obj[type+fn] );
166         obj[type+fn] = null;
167         obj["e"+type+fn] = null;
168     }
169 }
170
171     // var card_pos = RANGE 0 <= x < cards_ea_n
172
173 function show_bigpict(obj, act, x, y)
174 {
175    var big, sfx;
176
177    if (arguments.length > 4)
178        sfx = arguments[4];
179    else
180        sfx = '';
181
182    big = $(obj.id+"_big"+sfx);
183    if (act == "over") {
184        big.style.left = obj.offsetLeft + x+"px";
185        big.style.top  = obj.offsetTop  + y+"px";
186        big.style.visibility = "visible";
187        }
188    else {
189        big.style.visibility = "hidden";
190        }
191 }
192
193 function rnd_int(min, max) {
194   return Math.floor(Math.random() * (max - min + 1) + min);
195 }
196
197 function error_images()
198 {
199     // alert("GHESEMU!");
200     setTimeout(preload_images, 2000, g_preload_img_arr, g_imgct-1);
201 }
202
203 function abort_images()
204 {
205     // alert("ABORTAIMAGES");
206     setTimeout(preload_images, 2000, g_preload_img_arr, g_imgct-1);
207 }
208
209 function unload_images()
210 {
211     // alert("ABORTAIMAGES");
212     setTimeout(preload_images, 2000, g_preload_img_arr, g_imgct-1);
213 }
214
215 function reset_images()
216 {
217     // alert("ABORTAIMAGES");
218     setTimeout(preload_images, 2000, g_preload_img_arr, g_imgct-1);
219 }
220
221 function update_images()
222 {
223     // MLANG "Immagine caricate" + g_preload_imgsz_arr[g_imgct] + "%."
224     $("imgct").innerHTML = mlang_commons['imgload_a'][g_lang]+g_preload_imgsz_arr[g_imgct]+"%.";
225     if (g_imgct+1 < g_preload_img_arr.length) {
226         g_imgct++;
227         setTimeout(preload_images, 100, g_preload_img_arr, g_imgct-1);
228     }
229     // $("imgct").innerHTML += "U";
230 }
231
232 function preload_images(arr,idx)
233 {
234     var im = new Image;
235     
236     // $("imgct").innerHTML = "Stiamo caricando "+arr[idx]+"%.<br>";
237     im.onload =   update_images;
238     im.onerror =  error_images;
239     im.onabort =  abort_images;
240     im.onunload = unload_images;
241     im.onreset =  reset_images;
242     im.src =      arr[idx];
243     // $("imgct").innerHTML += "P";
244 }
245
246 function safestatus(a)
247 {
248     try{
249         return (a.status);
250     } catch(b)
251         { return (-1); }
252 }
253
254 function createXMLHttpRequest() {
255     if (typeof(ActiveXObject) != 'undefined') { // Konqueror complain as unknown object
256         try { return new ActiveXObject("Msxml2.XMLHTTP");    } catch(e) {}
257         try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {}
258     }
259     try { return new XMLHttpRequest();                   } catch(e) {}
260     alert("XMLHttpRequest not supported");
261     return null;
262 }
263
264 function send_mesg(mesg)
265 {
266     var xhr_wr = createXMLHttpRequest();
267     var is_conn = (sess == "not_connected" ? false : true);
268     
269     // alert("xhr_wr: "+xhr_wr+"  is_conn: "+is_conn);
270     xhr_wr.open('GET', 'index_wr.php?'+(is_conn ? 'sess='+sess+'&' : '')+'mesg='+mesg, (is_conn ? true : false));
271     xhr_wr.setRequestHeader("If-Modified-Since", new Date().toUTCString());
272     xhr_wr.onreadystatechange = function() { return; };
273     if (typeof(g_debug) == 'number' && g_debug > 0
274         && typeof(console) == 'object' && typeof(console.log) == 'function') {
275             var ldate = new Date();
276             console.log(ldate.getTime()+':MESG:'+mesg);
277     }
278     xhr_wr.send(null);
279
280     if (!is_conn) {
281         if (xhr_wr.responseText != null) {
282             eval(xhr_wr.responseText);
283         }
284     }
285 }
286
287 /*
288   sync request to server
289   server_request([arg0=arg1[, arg2=arg3[, ...]]])
290   if var name == '__POST__' than all other vars will be managed as POST content
291                                  and the call will be a POST
292  */
293 function server_request()
294 {
295     var xhr_wr = createXMLHttpRequest();
296     var i, collect = "", post_collect = null, is_post = false;
297
298     if (arguments.length > 0) {
299         for (i = 0 ; i < arguments.length ; i+= 2) {
300             if (arguments[i] == "__POST__") {
301                 is_post = true;
302                 post_collect = "";
303                 i -= 1;
304                 continue;
305             }
306             if (is_post)
307                 post_collect += (post_collect == "" ? "" : "&") + arguments[i] + "=" + encodeURIComponent(arguments[i+1]);
308             else
309                 collect += (i == 0 ? "" : "&") + arguments[i] + "=" + encodeURIComponent(arguments[i+1]);
310         }
311     }
312     // alert("Args: "+arguments.length);
313
314     var is_conn = (sess == "not_connected" ? false : true);
315     
316     // console.log("server_request:preresp: "+xhr_wr.responseText);
317
318     if (is_post) {
319         xhr_wr.open('POST', 'index_wr.php?'+(is_conn ? 'sess='+sess+'&' : '')+collect, false);
320         xhr_wr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
321     }
322     else {
323         xhr_wr.open('GET', 'index_wr.php?'+(is_conn ? 'sess='+sess+'&' : '')+collect, false);
324     }
325     xhr_wr.onreadystatechange = function() { return; };
326     xhr_wr.send(post_collect);
327     
328     if (xhr_wr.responseText != null) {
329         // console.log("server_request:resp: "+xhr_wr.responseText);
330         return (xhr_wr.responseText);
331     } 
332     else
333         return (null);
334 }
335
336 /* Stat: CHAT and TABLE */
337
338 function chatt_checksend(obj,e)
339 {
340     var keynum;
341     var keychar;
342     var numcheck;
343
344     if(window.event) { // IE
345         keynum = e.keyCode;
346     }
347     else if(e.which) { // Netscape/Firefox/Opera
348         keynum = e.which;
349     }
350     // alert("OBJ: "+obj);
351     if (keynum == 13 && obj.value != "") { // Enter
352         act_chatt(obj.value);
353         obj.value = "";
354     }
355 }
356 function act_chatt(value)
357 {
358     send_mesg("chatt|"+encodeURIComponent(value));
359     /*
360     obj.disabled = true;
361     obj.value = "";
362     obj.disabled = false;
363     obj.focus();
364     */
365     return false;
366 }
367
368 /* Stat: ROOM */
369 function act_ping()
370 {
371     send_mesg("ping");
372 }
373
374 function act_sitdown(table)
375 {
376     send_mesg("sitdown|"+table);
377 }
378
379 function act_wakeup()
380 {
381     send_mesg("wakeup");
382 }
383
384 function act_splash()
385 {
386     send_mesg("splash");
387 }
388
389 function act_help()
390 {
391     send_mesg("help");
392 }
393
394 function act_passwdhowto()
395 {
396     send_mesg("passwdhowto");
397 }
398
399 function act_mesgtoadm()
400 {
401     send_mesg("mesgtoadm");
402 }
403
404 function act_tav()
405 {
406     act_chatt('/tav '+$('txt_in').value); 
407     $('txt_in').value = '';
408 }
409
410 function act_about()
411 {
412     send_mesg("about");
413 }
414
415 function act_placing()
416 {
417     send_mesg("placing");
418 }
419
420 function act_roadmap()
421 {
422     send_mesg("roadmap");
423 }
424
425 function act_whysupport()
426 {
427     send_mesg("whysupport");
428 }
429
430 function act_lascio()
431 {
432     send_mesg("lascio");
433 }
434
435 function safelascio()
436 {
437     var res;
438     // MLANG "Sei sicuro di volere lasciare questa mano?"
439     res = window.confirm(mlang_commons['gamleav'][g_lang]);
440     if (res)
441         act_lascio();
442 }
443
444 function act_logout(exitlock)
445 {
446     send_mesg("logout|"+exitlock);
447 }
448
449 function act_reloadroom()
450 {
451     window.onunload = null;
452     window.onbeforeunload = null;
453     document.location.assign("index.php");
454 }
455
456 function act_shutdown()
457 {
458     var c = 0;
459
460     send_mesg("shutdown");
461     // while (xhr_wr.readyState != 4)
462     //  c++;
463 }
464
465 function postact_logout()
466 {
467     // alert("postact_logout");
468     try { 
469         hstm.abort();
470     } catch (e) {}
471
472     // eraseCookie("sess");
473     document.location.assign("index.php");
474 }
475
476 /*
477   function slowimg(img,x1,y1,deltat,free,action,srcend)
478   img    - image to move
479   x1,y1  - destination coords
480   deltat - time for each frame (in msec)
481   free   - when the release the local block for other operations (range: 0 - 1)
482   action - function to run when the image is moved
483   srcend - image to switch when the image is moved
484 */
485
486 function sleep(st, delay)
487 {
488     // alert("LOC_NEW PRE: "+st.st_loc_new);
489
490     st.st_loc_new++;
491
492     setTimeout(function(obj){ if (obj.st_loc_new > obj.st_loc) { obj.st_loc++; }},
493                delay, st);
494 }
495
496 function slowimg(img,x1,y1,deltat,free,action,srcend) {
497     this.img = img;
498
499     // this.x0  = parseInt(document.defaultView.getComputedStyle(this.img, "").getPropertyValue("left"));
500     this.x0 = parseInt(getStyle(this.img,"left", "left"));
501 // alert("img.x0 = "+this.x0);
502     // this.y0  = parseInt(document.defaultView.getComputedStyle(this.img, "").getPropertyValue("top"));
503     this.y0  = parseInt(getStyle(this.img,"top", "top"));
504     this.x1  = x1;
505     this.y1  = y1;
506     this.deltat = deltat;
507     this.free = free;
508     this.action = action;
509     this.srcend = srcend;
510 }
511
512 slowimg.prototype = {
513     img: null, 
514     st: null,
515     x0: 0,
516     y0: 0,
517     x1: 0,
518     y1: 0,
519     dx: 0,
520     dy: 0,
521     free: 0,
522     step_n:    0,
523     step_cur:  0,
524     step_free: 0,
525     time:      0,
526     deltat:   40,
527     tout: 0,
528     action: null,
529     srcend: null,
530     
531     setstart: function(x0,y0)
532     {
533         this.x0 = x0;
534         this.y0 = y0;
535     },
536     
537     setaction: function(act)
538     {
539         this.action = act;
540     },
541     
542
543     settime: function(time) 
544     {
545         this.time = (time < this.deltat ? this.deltat : time);
546         this.step_n = parseInt(this.time / this.deltat);
547         this.dx = (this.x1 - this.x0) / this.step_n;
548         this.dy = (this.y1 - this.y0) / this.step_n;
549         if (this.step_n * this.deltat == this.time) {
550             this.step_n--;
551         }
552         if (this.free < 1) {
553             this.step_free = parseInt(this.step_n * this.free);
554         }
555     },
556     
557     start: function(st)
558     {
559         // $("logz").innerHTML += "               xxxxxxxxxxxxxxxxxxxxxSTART<br>";
560         this.st = st;
561         this.st.st_loc_new++;
562         
563         this.img.style.visibility = "visible";
564         setTimeout(function(obj){ obj.animate(); }, this.deltat, this);
565     },
566     
567     animate: function()
568     {
569         // $("log").innerHTML = "Val " + this.step_cur + " N: " + this.step_n + "<br>";
570         if (this.step_cur == 0) {
571             var date = new Date();
572             // $("logz").innerHTML = "Timestart: " + date + "<br>";
573         }
574         if (this.step_cur <= this.step_n) {
575             this.img.style.left = this.x0 + this.dx * this.step_cur;
576             this.img.style.top  = this.y0 + this.dy * this.step_cur;
577             this.step_cur++;
578             setTimeout(function(obj){ obj.animate(); }, this.deltat, this);
579             if (this.step_cur == this.step_free && this.st != null) {
580                 if (this.st.st_loc < this.st.st_loc_new) {
581                     // alert("QUI1  " + this.step_cur + "  ZZ  "+  this.step_free);
582                     this.st.st_loc++;
583                     this.st = null;
584                 }
585             }
586         }
587         else {
588             this.img.style.left = this.x1;
589             this.img.style.top  = this.y1;
590             // $("logz").innerHTML += "xxxxxxxxxxxxxxxCLEAR<br>";
591             var date = new Date();
592             // $("logz").innerHTML += "Timestop: " + date + "<br>";
593
594             if (this.action != null) {
595                 eval(this.action);
596             }
597
598             if (this.st != null && this.st.st_loc < this.st.st_loc_new) {
599                 // alert("QUI2");
600                 this.st.st_loc++;
601                 this.st = null;
602             }
603             if (this.srcend != null) {
604                 this.img.src = this.srcend;
605             }
606         }
607     }
608 }
609
610 function div_show(div)
611 {
612     div.style.top = parseInt((document.body.clientHeight - parseInt(getStyle(div,"height", "height"))) / 2) + document.body.scrollTop;
613     div.style.visibility = "visible";
614 }
615
616 function notify_document(st, text, tout, butt, w, h, is_opa, block_time)
617 {
618     var i, clo, clodiv_ctx, clodiv_wai, box;
619
620     this.st = st;
621
622     this.ancestor = document.body;
623
624     this.st.st_loc_new++;
625
626     clodiv_ctx = document.createElement("div");
627     clodiv_ctx.className = "notify_clo";
628
629     for (i = 0 ; i < butt.length ; i++) {
630         this.input_add(butt[i], i, this.hide, clodiv_ctx);
631     }
632
633     if (block_time > 0) {
634         clodiv_wai = document.createElement("div");
635         clodiv_wai.className = "notify_clo";
636
637         this.input_add("leggere, prego.", 0, null, clodiv_wai);
638         this.clodiv = clodiv_wai;
639         this.clodiv_pkg = clodiv_ctx;
640         clodiv_ctx.style.display = 'none';
641     }
642     else {
643         this.clodiv = clodiv_ctx;
644     }
645
646     cont = document.createElement("div");
647
648     cont.style.borderBottomStyle = "solid";
649     cont.style.borderBottomWidth = "1px";
650     cont.style.borderBottomColor = "gray";
651     cont.style.height = (h - 30)+"px";
652     cont.style.overflow = "auto";
653     cont.innerHTML = text;
654
655     box =  document.createElement("div");
656     if (is_opa)
657         box.className = "notify_opaque";
658     else
659         box.className = "notify";
660
661     box.style.zIndex = 200;
662     box.style.width  = w+"px";
663     box.style.marginLeft  = -parseInt(w/2)+"px";
664     box.style.height = h+"px";
665     box.style.top = parseInt((document.body.clientHeight - h) / 2) + document.body.scrollTop;
666     box.appendChild(cont);
667     box.appendChild(this.clodiv);
668     box.style.visibility = "visible";
669
670     this.notitag = box;
671
672     this.ancestor.appendChild(box);
673
674     this.toutid = setTimeout(function(obj){ obj.unblock(); }, tout, this);
675
676     if (block_time != 0) {
677         this.tblkid = setTimeout(function(obj){ obj.notitag.removeChild(obj.clodiv); obj.clodiv = obj.clodiv_pkg; obj.clodiv.style.display = '';  obj.notitag.appendChild(obj.clodiv); }, block_time, this);
678     }
679 }
680
681 notify_document.prototype = {
682     ancestor: null,
683     st: null,
684     notitag: null,
685     toutid: null,
686     clo: null,
687
688     clodiv: null,
689     clodiv_pkg: null,
690
691     butt: null,
692     tblkid: null,
693
694     ret: -1,
695
696     /*
697       s:          button string
698       idx:        button index
699       onclick_cb: name of the onclick callback (with signature f(idx) ) or null
700       anc:        parent dom object
701
702       return new button dom object
703       */
704     input_add: function(s, idx, onclick_cb, anc)
705     {
706         var clo;
707
708         clo = document.createElement("input");
709         clo.type    = "submit";
710         clo.className = "button";
711         clo.style.bottom = "4px";
712         clo.style.margin = "2px";
713         clo.obj     = this;
714         clo.obj_idx = idx;
715         clo.value   = s;
716         if (onclick_cb)
717             clo.onclick = function () { onclick_cb.call(this.obj, this.obj_idx); };
718
719         formsub_hilite(clo);
720         anc.appendChild(clo);
721
722         return (clo);
723     },
724
725     ret_get: function()
726     {
727         // alert("quiz: "+this.rett);
728         return this.ret;
729     },
730
731     unblock: function()
732     {
733         if (this.st.st_loc < this.st.st_loc_new) {
734             this.st.st_loc++;
735         }
736     },
737
738     hide: function(val)
739     {
740         this.ret = val;
741         clearTimeout(this.toutid);
742         this.ancestor.removeChild(this.notitag);
743         this.unblock();
744     }
745 }
746
747
748
749
750 function notify_ex(st, text, tout, butt, w, h, is_opa, block_time)
751 {
752     var clo, box;
753     var t = this;
754     
755     this.st = st;
756
757     this.ancestor = document.body;
758     
759     this.st.st_loc_new++;
760
761     clo = document.createElement("input");
762     clo.type = "submit";
763     clo.className = "button";
764     clo.style.bottom = "4px";
765     clo.obj = this;
766     if (block_time > 0) {
767         clo.value = "leggere, prego.";
768         this.butt = butt;
769     }
770     else {
771         clo.value = butt;
772         clo.onclick = function () { this.obj.hide() };
773     }
774
775     clodiv = document.createElement("div");
776     clodiv.className = "notify_clo";
777     this.clo = clo;
778     this.clodiv = clodiv;
779
780     clodiv.appendChild(clo);
781
782     cont = document.createElement("div");
783
784     cont.style.borderBottomStyle = "solid";
785     cont.style.borderBottomWidth = "1px";
786     cont.style.borderBottomColor = "gray";
787     cont.style.height = (h - 30)+"px";
788     cont.style.overflow = "auto";
789     cont.innerHTML = text;
790
791     box =  document.createElement("div");
792     if (is_opa)
793         box.className = "notify_opaque";
794     else
795         box.className = "notify";
796
797     box.style.zIndex = 200;
798     box.style.width  = w+"px";
799     box.style.marginLeft  = -parseInt(w/2)+"px";
800     box.style.height = h+"px";
801     box.style.top = parseInt((document.body.clientHeight - h) / 2) + document.body.scrollTop;
802     box.appendChild(cont);
803     box.appendChild(clodiv);
804     box.style.visibility = "visible";
805
806     this.notitag = box;
807     
808     this.ancestor.appendChild(box);
809     
810     this.toutid = setTimeout(function(obj){ obj.unblock(); }, tout, this);
811
812     if (block_time != 0) {
813         this.tblkid = setTimeout(function(obj){ obj.clo.value = obj.butt; obj.clo.onclick = function () { this.obj.hide() }; formsub_hilite(obj.clo); obj.clo.focus(); }, block_time, this);
814     }
815     else {
816         formsub_hilite(clo);
817         clo.focus();
818     }
819
820 }
821
822
823 notify_ex.prototype = {
824     ancestor: null,
825     st: null,
826     notitag: null,
827     toutid: null,
828     clo: null,
829     clodiv: null, 
830     butt: null,
831     tblkid: null,
832
833     unblock: function()
834     {
835         if (this.st.st_loc < this.st.st_loc_new) {
836             this.st.st_loc++;
837         }
838     },
839     
840     hide: function()
841     {
842         clearTimeout(this.toutid);
843         this.ancestor.removeChild(this.notitag);
844         this.unblock();
845     }
846 }
847
848
849 notify.prototype = notify_ex.prototype;                // Define sub-class
850 notify.prototype.constructor = notify;
851 notify.baseConstructor = notify_ex;
852 notify.superClass = notify_ex.prototype;
853
854 function notify(st, text, tout, butt, w, h)
855 {
856     notify_ex.call(this, st, text, tout, butt, w, h, false, 0);
857 }
858         
859
860 function $(id) { 
861     return document.getElementById(id); 
862 }
863
864
865 function globst() {
866     this.st = -1;
867     this.st_loc = -1;
868     this.st_loc_new = -1;
869     this.comms  = new Array;
870 }
871
872 globst.prototype = {
873     st: -1,
874     st_loc: -1,
875     st_loc_new: -1,
876     comms: null,
877     sleep_hdl: null,
878
879     sleep: function(delay) {
880         st.st_loc_new++;
881
882         if (!this.the_end) {
883             this.sleep_hdl = setTimeout(function(obj){ if (obj.st_loc_new > obj.st_loc) { obj.st_loc++; obj.sleep_hdl = null; }},
884                                         delay, this);
885         }
886     },
887
888     abort: function() {
889         if (this.sleep_hdl != null) {
890             clearTimeout(this.sleep_hdl);
891             this.sleep_hdl = null;
892         }
893     }
894 }
895
896 function remark_step()
897 {
898     var ct = $("remark").l_remct;
899     
900     if (ct != 0) {
901         ct++;
902         if (ct > 2)
903             ct = 1;
904         $("remark").className = "remark"+ct;
905         $("remark").l_remct = ct;
906         setTimeout(remark_step,500);
907     }
908     else
909         $("remark").className = "remark0";
910     
911     return;
912 }
913
914 function remark_on()
915 {
916     if ($("remark").l_remct == 0) {
917         $("remark").l_remct = 1;
918         setTimeout(remark_step,500);
919     }
920 }
921
922 function remark_off()
923 {
924     $("remark").l_remct = 0;
925     $("remark").className = "remark0";
926 }
927
928
929 function italizer(ga)
930 {
931     var pre, pos;
932     if (ga[0] & 2) 
933         return "<i>"+ga[1]+"</i>";
934     else
935         return ga[1];
936 }
937
938
939 function exitlock_show(num, islock)
940 {
941     g_exitlock = num;
942
943     num = (num < 3 ? num : 3);
944     $("exitlock").src = "img/exitlock"+num+(islock ? "n" : "y")+".png";
945     // alert("EXITLOCK: "+$("exitlock").src);
946     $("exitlock").style.visibility = "visible";
947 }
948
949 var fin = 0;
950
951 //    exitlock_show(0, true);
952
953
954 var chatt_lines = new Array();
955 var chatt_lines_n = 0;
956
957 var CHATT_MAXLINES = 40;
958
959 function user_decorator(user)
960 {
961     var name;
962     var flags = user[0];
963     if ((flags & 0x03) != 0)
964         name = "<span class='au" + (flags & 0x03) + "'>"+user[1]+"</span>";
965     else
966         name = user[1];
967
968     return (name);
969 }
970
971 function user_dec_and_state(el)
972 {
973     var content = "";
974     var val_el;
975
976     content = user_decorator(el);
977     content += state_add(el[0],(typeof(el[2]) != 'undefined' ? el[2] : null));
978     
979     return (content);
980 }
981
982
983 /* PRO CHATT */
984 function chatt_sub(dt,data,str)
985 {
986     var must_scroll = false;
987     var name;
988     var flags;
989     var isauth;
990     var bolder = [ (data[0] | 1), data[1] ];
991     name = user_decorator(bolder);
992
993     if ($("txt").scrollTop + parseInt(getStyle($("txt"),"height", "height")) -  $("txt").scrollHeight >= 0)
994         must_scroll = true;
995
996     // alert("ARRIVA NAME: "+ name + "  STR:"+str);
997     if (chatt_lines_n == CHATT_MAXLINES) {
998         $("txt").innerHTML = "";
999         for (i = 0 ; i < (CHATT_MAXLINES - 1) ; i++) {
1000             chatt_lines[i] = chatt_lines[i+1];
1001             $("txt").innerHTML += chatt_lines[i];
1002         }
1003         chatt_lines[i] = dt+name+": "+str+ "<br>";
1004         $("txt").innerHTML += chatt_lines[i];
1005     }
1006     else {
1007         chatt_lines[chatt_lines_n] = dt+name+": "+str+ "<br>";
1008         $("txt").innerHTML += chatt_lines[chatt_lines_n];
1009         chatt_lines_n++;
1010     }
1011     // $("txt").innerHTML;
1012
1013     
1014     if (must_scroll) {
1015         $("txt").scrollTop = 10000000;
1016     }
1017     // alert("scTOP "+$("txt").scrollTop+"  scHEIGHT: "+$("txt").scrollHeight+" HEIGHT: "+getStyle($("txt"),"height", "height") );
1018 }
1019
1020 /*
1021  *  GESTIONE DEI COOKIES
1022  */
1023 function createCookie(name,value,hours,path) {
1024         if (hours) {
1025                 var date = new Date();
1026                 date.setTime(date.getTime()+(hours*60*60*1000));
1027                 var expires = "; expires="+date.toGMTString();
1028         }
1029         else var expires = "";
1030         document.cookie = name+"="+value+expires+"; path="+path;
1031 }
1032
1033 function readCookie(name) {
1034         var nameEQ = name + "=";
1035         var ca = document.cookie.split(';');
1036         for(var i=0;i < ca.length;i++) {
1037                 var c = ca[i];
1038                 while (c.charAt(0)==' ') c = c.substring(1,c.length);
1039                 if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
1040         }
1041         return null;
1042 }
1043
1044 function eraseCookie(name) {
1045         createCookie(name,"",-1);
1046 }
1047
1048 function onbeforeunload_cb () {
1049     return("");
1050 }
1051
1052 function onunload_cb () {
1053     
1054     if (typeof(hstm) != "undefined")
1055         hstm.the_end = true; 
1056
1057     act_shutdown();
1058     
1059     return(false);
1060 }
1061
1062 function room_checkspace(emme,tables,inpe)
1063 {
1064     nome = "<b>";
1065     for (i = 0 ; i < emme ; i++) 
1066         nome += "m";
1067     nome += "</b>";
1068
1069     alta = "";
1070     for (i = 0 ; i < 5 ; i++) 
1071         alta += nome+"<br>";
1072
1073     for (i = 0 ; i < tables ; i++) {
1074         $("table"+i).innerHTML = alta;
1075         // MLANG Mi siedo.
1076         $("table_act"+i).innerHTML = "<input type=\"button\" class=\"button\" name=\"xhenter"+i+"\"  value=\""+mlang_commons['btn_sit'][g_lang]+"\" onclick=\"act_sitdown(1);\">";
1077         }
1078
1079     stand = "<table class=\"table_standup\"><tbody><tr>";
1080     for (i = 0 ; i < inpe ; i++) {
1081         stand += "<td>"+nome+"</td>";
1082         if ((i+1) % 4 == 0) {
1083             stand += "</tr><tr>";
1084         }
1085     }
1086     stand += "</tr>";
1087     $("standup").innerHTML = stand;
1088
1089     // VERIFY: what is this button ?
1090     // MLANG Esco.
1091     $("esco").innerHTML = "<input class=\"button\" name=\"logout\" type=\"button\" value=\""+mlang_commons['btn_exit'][g_lang]+"\" onclick=\"act_logout();\" type=\"button\">";
1092 }
1093
1094 function  unescapeHTML(cont) {
1095     var div = document.createElement('div');
1096     var memo = "";
1097     var i;
1098
1099     div.innerHTML = cont;
1100     if (div.childNodes[0]) {
1101         if (div.childNodes.length > 1) {
1102             if (div.childNodes.toArray)
1103                 alert("si puo");
1104             else {
1105                 var length = div.childNodes.length, results = new Array(length);
1106             while (length--)
1107                 results[length] = div.childNodes[length];
1108                 
1109             for (i=0 ; i<results.length ; i++)
1110                 memo = memo + results[i].nodeValue;
1111             }
1112
1113             return (memo);
1114         }
1115         else {
1116             return (div.childNodes[0].nodeValue);
1117         }
1118     }
1119     else {
1120         return ('');
1121     }
1122 }
1123
1124 function playsound(tag, sound) {
1125    // g_withflash is a global var
1126    if (g_withflash) {
1127       $(tag).innerHTML = '<OBJECT classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" '+
1128 'codebase="http://active.macromedia.com/flash2/cabs/swflash.cab#version=4,0,0,0" id="mysound" WIDTH=1 HEIGHT=1>' +
1129 '<PARAM NAME="movie" VALUE="../playsound.swf"><PARAM NAME="PLAY" VALUE="true"><PARAM NAME="LOOP" VALUE="false">' +
1130 '<PARAM NAME=FlashVars VALUE="streamUrl='+sound+'">' +
1131 '<EMBED swliveconnect="true" name="mysound" src="../playsound.swf" FlashVars="streamUrl='+sound+'" PLAY="true" LOOP="false" '+
1132 ' WIDTH=1 HEIGHT=1 TYPE="application/x-shockwave-flash" PLUGINSPAGE="http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash"></OBJECT>';
1133    }
1134 }
1135
1136 function topbanner_init()
1137 {
1138     setInterval(topbanner_cb, 666);
1139 ;
1140 }
1141
1142 function topbanner_cb()
1143 {
1144     var a, b;
1145
1146     a = $('topbanner').style.backgroundColor;
1147     b = $('topbanner').style.borderLeftColor;
1148
1149     $('topbanner').style.backgroundColor = b;
1150     $('topbanner').style.borderColor = a+" "+a+" "+a+" "+a;
1151
1152     // console.log("A: "+a+"  B: "+b);
1153 }
1154
1155 function sidebanner_init()
1156 {
1157     setInterval(sidebanner_cb, 666);
1158 }
1159
1160 function sidebanner2_init()
1161 {
1162     setInterval(sidebanner2_cb, 666);
1163 }
1164
1165 function sidebanner_cb()
1166 {
1167     var a, b;
1168
1169     a = $('sidebanner').style.backgroundColor;
1170     b = $('sidebanner').style.borderLeftColor;
1171
1172     $('sidebanner').style.backgroundColor = b;
1173     $('sidebanner').style.borderColor = a+" "+a+" "+a+" "+a;
1174
1175     // console.log("A: "+a+"  B: "+b);
1176 }
1177
1178 function sidebanner2_cb()
1179 {
1180     var a, b;
1181
1182     a = $('sidebanner2').style.backgroundColor;
1183     b = $('sidebanner2').style.borderLeftColor;
1184
1185     $('sidebanner2').style.backgroundColor = b;
1186     $('sidebanner2').style.borderColor = a+" "+a+" "+a+" "+a;
1187
1188     // console.log("A: "+a+"  B: "+b);
1189 }
1190
1191
1192 function langtolng(lang)
1193 {
1194     if (lang == "en")
1195         return ("-en");
1196     else
1197         return ("");
1198 }
1199
1200 function formtext_hilite(obj)
1201 {
1202     obj.className = 'input_text';
1203     addEvent(obj, "focus", function () { this.className = 'input_text_hi'; });
1204     addEvent(obj, "blur",  function () { this.className = 'input_text'; });
1205 }
1206
1207 function formsub_hilite(obj)
1208 {
1209     obj.className = 'input_sub';
1210     addEvent(obj, "focus", function () { this.className = 'input_sub_hi'; });
1211     addEvent(obj, "blur",  function () { this.className = 'input_sub'; });
1212 }
1213
1214 // return the value of the radio button that is checked
1215 // return an empty string if none are checked, or
1216 // there are no radio buttons
1217 function get_checked_value(radioObj) {
1218         if(!radioObj)
1219                 return "";
1220         var radioLength = radioObj.length;
1221         if(radioLength == undefined)
1222                 if(radioObj.checked)
1223                         return radioObj.value;
1224                 else
1225                         return "";
1226         for(var i = 0; i < radioLength; i++) {
1227                 if(radioObj[i].checked) {
1228                         return radioObj[i].value;
1229                 }
1230         }
1231         return "";
1232 }
1233
1234 // set the radio button with the given value as being checked
1235 // do nothing if there are no radio buttons
1236 // if the given value does not exist, all the radio buttons
1237 // are reset to unchecked
1238 function set_checked_value(radioObj, newValue) {
1239         if(!radioObj)
1240                 return;
1241         var radioLength = radioObj.length;
1242         if(radioLength == undefined) {
1243                 radioObj.checked = (radioObj.value == newValue.toString());
1244                 return;
1245         }
1246         for(var i = 0; i < radioLength; i++) {
1247                 radioObj[i].checked = false;
1248                 if(radioObj[i].value == newValue.toString()) {
1249                         radioObj[i].checked = true;
1250                 }
1251         }
1252 }
1253
1254 function url_append_arg(url, name, value)
1255 {
1256     var pos, sep, pref, rest;
1257
1258     if ((pos = url.indexOf('?'+name+'=')) == -1) {
1259         pos = url.indexOf('&'+name+'=');
1260     }
1261     if (pos == -1) {
1262         if ((pos = url.indexOf('?')) != -1)
1263             sep = '&';
1264         else
1265             sep = '?';
1266
1267         return (url+sep+name+"="+encodeURIComponent(value));
1268     }
1269     else {
1270         pref = url.substring(0, pos+1);
1271         rest = url.substring(pos+1);
1272         // alert("rest: "+rest+"  pos: "+pos);
1273         if ((pos = rest.indexOf('&')) != -1) {
1274             rest = rest.substring(pos);
1275         }
1276         else {
1277             rest = "";
1278         }
1279         return (pref+name+"="+encodeURIComponent(value)+rest);
1280     }
1281 }
1282
1283 function url_append_args(url)
1284 {
1285     var i, ret;
1286
1287     ret = url;
1288     for (i = 1 ; i < arguments.length-1 ; i+= 2) {
1289         ret = url_append_arg(ret, arguments[i], arguments[i+1]);
1290     }
1291
1292     return (ret);
1293 }
1294
1295 function url_complete(parent, url)
1296 {
1297     var p, p2, rest;
1298     var host = "", path = "";
1299
1300     // host extraction
1301     p = parent.indexOf("://");
1302     if (p > -1) {
1303         rest = parent.substring(p+3);
1304         p2 = rest.indexOf("/");
1305         if (p2 > -1) {
1306             host = parent.substring(0, p+3+p2);
1307             rest = parent.substring(p+3+p2);
1308         }
1309         else {
1310             host = rest;
1311             rest = "";
1312         }
1313     }
1314     else {
1315         rest = parent;
1316     }
1317
1318     // path extraction
1319     p = rest.lastIndexOf("/");
1320     if (p > -1) {
1321         path = rest.substring(0, p+1);
1322     }
1323
1324     // alert("host: ["+host+"]  path: ["+path+"]");
1325     if (url.substring(0,6) == 'http:/' || url.substring(0,7) == 'https:/' || url.substring(0,4) == 'ws:/') {
1326         return (url);
1327     }
1328     else if (url.substring(0,1) == '/') {
1329         return (host+url);
1330     }
1331     else {
1332         return (host+path+url);
1333     }
1334 }