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