456416b28090d33a6a10546e915cd85315e29efa
[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
463     this.time  = item_ar[0];
464     this.usrid = item_ar[1];
465     this.table = item_ar[2];
466     this.name  = item_ar[3];
467     this.cont  = item_ar[4];
468
469     date = new Date();
470     date.setTime(this.time * 1000);
471
472     tr = document.createElement("tr");
473     td = document.createElement("td");
474     // FIXME a more readable date here
475     // td.innerHTML = date.xxxx;
476     td.innerHTML = this.time % 100000;
477     tr.appendChild(td);
478
479     td = document.createElement("td");
480     td.innerHTML = this.table;
481     tr.appendChild(td);
482
483     td = document.createElement("td");
484     td.innerHTML = this.usrid;
485     tr.appendChild(td);
486
487     td = document.createElement("td");
488     td.innerHTML = this.name;
489     tr.appendChild(td);
490
491     td = document.createElement("td");
492     td.innerHTML = this.cont;
493     tr.appendChild(td);
494
495     this.tr = tr;
496 }
497
498 ModerateItem.prototype = {
499     time: 0,
500     usrid: 0,
501     table: -1,
502     name: "",
503     cont: "",
504
505     tr: null,
506     sel: false,
507
508     tr_get: function () {
509         return this.tr;
510     },
511
512     sel_get: function () {
513         return this.sel;
514     },
515
516     sel_set: function (v) {
517         if (this.sel != v) {
518             this.sel = v;
519             this.tr.className = (v ? 'selected' : 'normal');
520         }
521     }
522 }
523
524 function Moderate()
525 {
526     this.item = new Array();
527 }
528
529 Moderate.prototype = {
530     win:  null,
531     table: null,
532     enabled: false,
533     item: null,
534
535     cur: -1,
536
537     disable: function () {
538         if (this.tout) {
539             clearTimeout(this.tout);
540             this.tout = 0;
541         }
542         if (this.win) {
543             this.win.onbeforeunload = null;
544             this.win.close();
545             this.win = null;
546         }
547     },
548
549     activate: function (enable) {
550         if (this.enabled == enable) {
551             return true;
552         }
553         if (enable) {
554             this.disable();
555
556             this.win = window.open("moderation.php", "_blank", "width=800,height=600,toolbar=no,location=no,menubar=no,status=no");
557             if (this.win == null) {
558                 this.disable();
559                 return false;
560             }
561             // to finish initialization we wait for popup page onload event ...
562             this.win_waitonload();
563         }
564         else {
565             this.disable();
566             this.enabled = false;
567         }
568
569     },
570
571     win_waitonload: function () {
572         if (typeof(this.win.is_loaded)  == 'undefined' || this.win.is_loaded != true) {
573             this.tout = setTimeout(function (obj) { obj.win_waitonload(); }, 250, this);
574         }
575         else {
576             this.post_onload();
577         }
578     },
579
580     post_onload: function() {
581         var tr, td, remtr;
582
583         this.win.anc = this;
584         this.table = $(this.win, 'moder_tab');
585
586         // for (i = 0 ; i < 3 ; i++) {
587         //     tr = document.createElement("tr");
588         //     for (e = 0 ; e < 2 ; e++) {
589         //         td = document.createElement("td");
590         //         td.innerHTML = "Content "+((i * 2)+e);
591         //         tr.appendChild(td);
592         //     }
593         //     this.table.appendChild(tr);
594         //     if (i == 0) 
595         //         remtr = tr;
596         // }
597         // this.table.removeChild(remtr);
598
599         this.enabled = true;
600     },
601
602     onunload: function() {
603         act_moderate();
604     },
605
606     is_enabled: function() {
607         return (this.enabled);
608     },
609
610     add: function(item) {
611         var mi;
612
613         mi = new ModerateItem(item);
614         mi.tr.className = 'normal';
615
616         var self;
617         self = this;
618         mi.tr.onclick = function () { self.row_select(mi); };
619
620         this.item.push(mi);
621         this.table.appendChild(mi.tr_get());
622     },
623
624     row_select: function(mi) {
625         for (idx in this.item) {
626             if (this.item[idx] == mi) {
627                 this.item[idx].sel_set(!this.item[idx].sel_get());
628             }
629             else {
630                 this.item[idx].sel_set(false);
631             }
632         }
633         // mi.tr.className = "selected";
634     }
635 }
636
637 function moderate(enable)
638 {
639     return (g_moder.activate(enable));
640 }
641
642 var g_moder = new Moderate();
643
644 function act_moderate()
645 {
646     send_mesg("moderate|"+(g_moder.is_enabled() ? "false" : "true"));
647 }
648
649
650
651 //         // build table with js
652         
653 //         g_moder.item = new Array;
654 //         g_moder.table = xxx;
655 //     }
656 //     else {
657 //         if (g_moder == null)
658 //             return true;
659
660 //         if (g_moder.win != null) {
661 //             g_moder.win.close();
662 //             g_moder.win = null;
663 //         }
664
665 //         if (g_moder.item != null) {
666 //             // TODO CLEANUP
667 //             ;
668 //         }
669 //         g_moder.cur = -1;
670 //     }
671 // }
672
673
674 function act_reloadroom()
675 {
676     if (g_moder.is_enabled()) {
677         g_moder.disable();
678     }
679     window.onunload = null;
680     window.onbeforeunload = null;
681     document.location.assign("index.php");
682 }
683
684
685 function act_shutdown()
686 {
687     var c = 0;
688
689     send_mesg("shutdown");
690     // while (xhr_wr.readyState != 4)
691     //  c++;
692 }
693
694 function postact_logout()
695 {
696     // alert("postact_logout");
697
698     if (g_moder.is_enabled()) {
699         g_moder.disable();
700     }
701
702     try { 
703         hstm.abort();
704     } catch (e) {}
705
706     // eraseCookie("sess");
707     document.location.assign("index.php");
708 }
709
710 /*
711   function slowimg(img,x1,y1,deltat,free,action,srcend)
712   img    - image to move
713   x1,y1  - destination coords
714   deltat - time for each frame (in msec)
715   free   - when the release the local block for other operations (range: 0 - 1)
716   action - function to run when the image is moved
717   srcend - image to switch when the image is moved
718 */
719
720 function sleep(st, delay)
721 {
722     // alert("LOC_NEW PRE: "+st.st_loc_new);
723
724     st.st_loc_new++;
725
726     setTimeout(function(obj){ if (obj.st_loc_new > obj.st_loc) { obj.st_loc++; }},
727                delay, st);
728 }
729
730 function slowimg(img,x1,y1,deltat,free,action,srcend) {
731     this.img = img;
732
733     // this.x0  = parseInt(document.defaultView.getComputedStyle(this.img, "").getPropertyValue("left"));
734     this.x0 = parseInt(getStyle(this.img,"left", "left"));
735 // alert("img.x0 = "+this.x0);
736     // this.y0  = parseInt(document.defaultView.getComputedStyle(this.img, "").getPropertyValue("top"));
737     this.y0  = parseInt(getStyle(this.img,"top", "top"));
738     this.x1  = x1;
739     this.y1  = y1;
740     this.deltat = deltat;
741     this.free = free;
742     this.action = action;
743     this.srcend = srcend;
744 }
745
746 slowimg.prototype = {
747     img: null, 
748     st: null,
749     x0: 0,
750     y0: 0,
751     x1: 0,
752     y1: 0,
753     dx: 0,
754     dy: 0,
755     free: 0,
756     step_n:    0,
757     step_cur:  0,
758     step_free: 0,
759     time:      0,
760     deltat:   40,
761     tout: 0,
762     action: null,
763     srcend: null,
764     
765     setstart: function(x0,y0)
766     {
767         this.x0 = x0;
768         this.y0 = y0;
769     },
770     
771     setaction: function(act)
772     {
773         this.action = act;
774     },
775     
776
777     settime: function(time) 
778     {
779         this.time = (time < this.deltat ? this.deltat : time);
780         this.step_n = parseInt(this.time / this.deltat);
781         this.dx = (this.x1 - this.x0) / this.step_n;
782         this.dy = (this.y1 - this.y0) / this.step_n;
783         if (this.step_n * this.deltat == this.time) {
784             this.step_n--;
785         }
786         if (this.free < 1) {
787             this.step_free = parseInt(this.step_n * this.free);
788         }
789     },
790     
791     start: function(st)
792     {
793         // $("logz").innerHTML += "               xxxxxxxxxxxxxxxxxxxxxSTART<br>";
794         this.st = st;
795         this.st.st_loc_new++;
796         
797         this.img.style.visibility = "visible";
798         setTimeout(function(obj){ obj.animate(); }, this.deltat, this);
799     },
800     
801     animate: function()
802     {
803         // $("log").innerHTML = "Val " + this.step_cur + " N: " + this.step_n + "<br>";
804         if (this.step_cur == 0) {
805             var date = new Date();
806             // $("logz").innerHTML = "Timestart: " + date + "<br>";
807         }
808         if (this.step_cur <= this.step_n) {
809             this.img.style.left = this.x0 + this.dx * this.step_cur;
810             this.img.style.top  = this.y0 + this.dy * this.step_cur;
811             this.step_cur++;
812             setTimeout(function(obj){ obj.animate(); }, this.deltat, this);
813             if (this.step_cur == this.step_free && this.st != null) {
814                 if (this.st.st_loc < this.st.st_loc_new) {
815                     // alert("QUI1  " + this.step_cur + "  ZZ  "+  this.step_free);
816                     this.st.st_loc++;
817                     this.st = null;
818                 }
819             }
820         }
821         else {
822             this.img.style.left = this.x1;
823             this.img.style.top  = this.y1;
824             // $("logz").innerHTML += "xxxxxxxxxxxxxxxCLEAR<br>";
825             var date = new Date();
826             // $("logz").innerHTML += "Timestop: " + date + "<br>";
827
828             if (this.action != null) {
829                 eval(this.action);
830             }
831
832             if (this.st != null && this.st.st_loc < this.st.st_loc_new) {
833                 // alert("QUI2");
834                 this.st.st_loc++;
835                 this.st = null;
836             }
837             if (this.srcend != null) {
838                 this.img.src = this.srcend;
839             }
840         }
841     }
842 }
843
844 function div_show(div)
845 {
846     div.style.top = parseInt((document.body.clientHeight - parseInt(getStyle(div,"height", "height"))) / 2) + document.body.scrollTop;
847     div.style.visibility = "visible";
848 }
849
850 function notify_ex(st, text, tout, butt, w, h, is_opa, block_time)
851 {
852     var clo, box;
853     var t = this;
854     
855     this.st = st;
856
857     this.ancestor = document.body;
858     
859     this.st.st_loc_new++;
860
861     clo = document.createElement("input");
862     clo.type = "submit";
863     clo.className = "button";
864     clo.style.bottom = "4px";
865     clo.obj = this;
866     if (block_time > 0) {
867         clo.value = "leggere, prego.";
868         this.butt = butt;
869     }
870     else {
871         clo.value = butt;
872         clo.onclick = this.input_hide;
873     }
874
875     clodiv = document.createElement("div");
876     clodiv.className = "notify_clo";
877     this.clo = clo;
878     this.clodiv = clodiv;
879
880     clodiv.appendChild(clo);
881
882     cont = document.createElement("div");
883
884     cont.style.borderBottomStyle = "solid";
885     cont.style.borderBottomWidth = "1px";
886     cont.style.borderBottomColor = "gray";
887     cont.style.height = (h - 30)+"px";
888     cont.style.overflow = "auto";
889     cont.innerHTML = text;
890
891     box =  document.createElement("div");
892     if (is_opa)
893         box.className = "notify_opaque";
894     else
895         box.className = "notify";
896
897     box.style.zIndex = 200;
898     box.style.width  = w+"px";
899     box.style.marginLeft  = -parseInt(w/2)+"px";
900     box.style.height = h+"px";
901     box.style.top = parseInt((document.body.clientHeight - h) / 2) + document.body.scrollTop;
902     box.appendChild(cont);
903     box.appendChild(clodiv);
904     box.style.visibility = "visible";
905
906     this.notitag = box;
907     
908     this.ancestor.appendChild(box);
909     
910     this.toutid = setTimeout(function(obj){ obj.unblock(); }, tout, this);
911
912     if (block_time != 0) {
913         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);
914     }
915     else {
916         formsub_hilite(clo);
917         clo.focus();
918     }
919
920 }
921
922
923 notify_ex.prototype = {
924     ancestor: null,
925     st: null,
926     notitag: null,
927     toutid: null,
928     clo: null,
929     clodiv: null, 
930     butt: null,
931     tblkid: null,
932
933     unblock: function()
934     {
935         if (this.st.st_loc < this.st.st_loc_new) {
936             this.st.st_loc++;
937         }
938     },
939     
940     hide: function()
941     {
942         clearTimeout(this.toutid);
943         this.ancestor.removeChild(this.notitag);
944         this.unblock();
945     },
946
947     input_hide: function()
948     {
949         clearTimeout(this.obj.toutid);
950         this.obj.ancestor.removeChild(this.obj.notitag);
951         this.obj.unblock();
952     }
953 }
954
955
956 notify.prototype = notify_ex.prototype;                // Define sub-class
957 notify.prototype.constructor = notify;
958 notify.baseConstructor = notify_ex;
959 notify.superClass = notify_ex.prototype;
960
961 function notify(st, text, tout, butt, w, h)
962 {
963     notify_ex.call(this, st, text, tout, butt, w, h, false, 0);
964 }
965
966 function globst() {
967     this.st = -1;
968     this.st_loc = -1;
969     this.st_loc_new = -1;
970     this.comms  = new Array;
971 }
972
973 globst.prototype = {
974     st: -1,
975     st_loc: -1,
976     st_loc_new: -1,
977     comms: null,
978     sleep_hdl: null,
979
980     sleep: function(delay) {
981         st.st_loc_new++;
982
983         if (!this.the_end) {
984             this.sleep_hdl = setTimeout(function(obj){ if (obj.st_loc_new > obj.st_loc) { obj.st_loc++; obj.sleep_hdl = null; }},
985                                         delay, this);
986         }
987     },
988
989     abort: function() {
990         if (this.sleep_hdl != null) {
991             clearTimeout(this.sleep_hdl);
992             this.sleep_hdl = null;
993         }
994     }
995 }
996
997 function remark_step()
998 {
999     var ct = $("remark").l_remct;
1000     
1001     if (ct != 0) {
1002         ct++;
1003         if (ct > 2)
1004             ct = 1;
1005         $("remark").className = "remark"+ct;
1006         $("remark").l_remct = ct;
1007         setTimeout(remark_step,500);
1008     }
1009     else
1010         $("remark").className = "remark0";
1011     
1012     return;
1013 }
1014
1015 function remark_on()
1016 {
1017     if ($("remark").l_remct == 0) {
1018         $("remark").l_remct = 1;
1019         setTimeout(remark_step,500);
1020     }
1021 }
1022
1023 function remark_off()
1024 {
1025     $("remark").l_remct = 0;
1026     $("remark").className = "remark0";
1027 }
1028
1029
1030 function italizer(ga)
1031 {
1032     var pre, pos;
1033     if (ga[0] & 2) 
1034         return "<i>"+ga[1]+"</i>";
1035     else
1036         return ga[1];
1037 }
1038
1039
1040 function exitlock_show(num, islock)
1041 {
1042     g_exitlock = num;
1043
1044     num = (num < 3 ? num : 3);
1045     $("exitlock").src = "img/exitlock"+num+(islock ? "n" : "y")+".png";
1046     // alert("EXITLOCK: "+$("exitlock").src);
1047     $("exitlock").style.visibility = "visible";
1048 }
1049
1050 var fin = 0;
1051
1052 //    exitlock_show(0, true);
1053
1054
1055 var chatt_lines = new Array();
1056 var chatt_lines_n = 0;
1057
1058 var CHATT_MAXLINES = 40;
1059
1060 function user_decorator(user)
1061 {
1062     var name;
1063     var flags = user[BSK_USER_FLAGS];
1064     var flags_vlt = user[BSK_USER_FLGVL];
1065     if ((flags & 0x03) != 0)
1066         name = "<span class='au" + (flags & 0x03) + "'>"+user[BSK_USER_NICK]+"</span>";
1067     else
1068         name = user[BSK_USER_NICK];
1069
1070     return (name);
1071 }
1072
1073 function user_dec_and_state(el)
1074 {
1075     var content = "";
1076     var val_el;
1077
1078     content = user_decorator(el);
1079     content += state_add(el[BSK_USER_FLAGS], el[BSK_USER_FLGVL],
1080                          (typeof(el[BSK_USER_SCOL]) != 'undefined' ? el[BSK_USER_SCOL] : null));
1081     
1082     return (content);
1083 }
1084
1085
1086 /* PRO CHATT */
1087 function chatt_sub(dt,data,str)
1088 {
1089     var must_scroll = false;
1090     var name;
1091     var flags;
1092     var isauth;
1093     var bolder = [ (data[BSK_USER_FLAGS] | 1), data[BSK_USER_FLGVL], data[BSK_USER_NICK] ];
1094     name = user_decorator(bolder);
1095
1096     if ($("txt").scrollTop + parseInt(getStyle($("txt"),"height", "height")) -  $("txt").scrollHeight >= 0)
1097         must_scroll = true;
1098
1099     // alert("ARRIVA NAME: "+ name + "  STR:"+str);
1100     if (chatt_lines_n == CHATT_MAXLINES) {
1101         $("txt").innerHTML = "";
1102         for (i = 0 ; i < (CHATT_MAXLINES - 1) ; i++) {
1103             chatt_lines[i] = chatt_lines[i+1];
1104             $("txt").innerHTML += chatt_lines[i];
1105         }
1106         chatt_lines[i] = dt+name+": "+str+ "<br>";
1107         $("txt").innerHTML += chatt_lines[i];
1108     }
1109     else {
1110         chatt_lines[chatt_lines_n] = dt+name+": "+str+ "<br>";
1111         $("txt").innerHTML += chatt_lines[chatt_lines_n];
1112         chatt_lines_n++;
1113     }
1114     // $("txt").innerHTML;
1115
1116     
1117     if (must_scroll) {
1118         $("txt").scrollTop = 10000000;
1119     }
1120     // alert("scTOP "+$("txt").scrollTop+"  scHEIGHT: "+$("txt").scrollHeight+" HEIGHT: "+getStyle($("txt"),"height", "height") );
1121 }
1122
1123 /*
1124  *  GESTIONE DEI COOKIES
1125  */
1126 function createCookie(name,value,hours,path) {
1127         if (hours) {
1128                 var date = new Date();
1129                 date.setTime(date.getTime()+(hours*60*60*1000));
1130                 var expires = "; expires="+date.toGMTString();
1131         }
1132         else var expires = "";
1133         document.cookie = name+"="+value+expires+"; path="+path;
1134 }
1135
1136 function readCookie(name) {
1137         var nameEQ = name + "=";
1138         var ca = document.cookie.split(';');
1139         for(var i=0;i < ca.length;i++) {
1140                 var c = ca[i];
1141                 while (c.charAt(0)==' ') c = c.substring(1,c.length);
1142                 if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
1143         }
1144         return null;
1145 }
1146
1147 function eraseCookie(name) {
1148         createCookie(name,"",-1);
1149 }
1150
1151 function onbeforeunload_cb () {
1152     return("");
1153 }
1154
1155 function onunload_cb () {
1156     
1157     if (typeof(hstm) != "undefined")
1158         hstm.the_end = true; 
1159
1160     act_shutdown();
1161     
1162     return(false);
1163 }
1164
1165 function room_checkspace(emme,tables,inpe)
1166 {
1167     nome = "<b>";
1168     for (i = 0 ; i < emme ; i++) 
1169         nome += "m";
1170     nome += "</b>";
1171
1172     alta = "";
1173     for (i = 0 ; i < 5 ; i++) 
1174         alta += nome+"<br>";
1175
1176     for (i = 0 ; i < tables ; i++) {
1177         $("table"+i).innerHTML = alta;
1178         // MLANG Mi siedo.
1179         $("table_act"+i).innerHTML = "<input type=\"button\" class=\"button\" name=\"xhenter"+i+"\"  value=\""+mlang_commons['btn_sit'][g_lang]+"\" onclick=\"act_sitdown(1);\">";
1180         }
1181
1182     stand = "<table class=\"table_standup\"><tbody><tr>";
1183     for (i = 0 ; i < inpe ; i++) {
1184         stand += "<td>"+nome+"</td>";
1185         if ((i+1) % 4 == 0) {
1186             stand += "</tr><tr>";
1187         }
1188     }
1189     stand += "</tr>";
1190     $("standup").innerHTML = stand;
1191
1192     // VERIFY: what is this button ?
1193     // MLANG Esco.
1194     $("esco").innerHTML = "<input class=\"button\" name=\"logout\" type=\"button\" value=\""+mlang_commons['btn_exit'][g_lang]+"\" onclick=\"act_logout();\" type=\"button\">";
1195 }
1196
1197 function  unescapeHTML(cont) {
1198     var div = document.createElement('div');
1199     var memo = "";
1200     var i;
1201
1202     div.innerHTML = cont;
1203     if (div.childNodes[0]) {
1204         if (div.childNodes.length > 1) {
1205             if (div.childNodes.toArray)
1206                 alert("si puo");
1207             else {
1208                 var length = div.childNodes.length, results = new Array(length);
1209             while (length--)
1210                 results[length] = div.childNodes[length];
1211                 
1212             for (i=0 ; i<results.length ; i++)
1213                 memo = memo + results[i].nodeValue;
1214             }
1215
1216             return (memo);
1217         }
1218         else {
1219             return (div.childNodes[0].nodeValue);
1220         }
1221     }
1222     else {
1223         return ('');
1224     }
1225 }
1226
1227 function playsound(tag, sound) {
1228    // g_withflash is a global var
1229    if (g_withflash) {
1230       $(tag).innerHTML = '<OBJECT classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" '+
1231 'codebase="http://active.macromedia.com/flash2/cabs/swflash.cab#version=4,0,0,0" id="mysound" WIDTH=1 HEIGHT=1>' +
1232 '<PARAM NAME="movie" VALUE="../playsound.swf"><PARAM NAME="PLAY" VALUE="true"><PARAM NAME="LOOP" VALUE="false">' +
1233 '<PARAM NAME=FlashVars VALUE="streamUrl='+sound+'">' +
1234 '<EMBED swliveconnect="true" name="mysound" src="../playsound.swf" FlashVars="streamUrl='+sound+'" PLAY="true" LOOP="false" '+
1235 ' WIDTH=1 HEIGHT=1 TYPE="application/x-shockwave-flash" PLUGINSPAGE="http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash"></OBJECT>';
1236    }
1237 }
1238
1239 function topbanner_init()
1240 {
1241     setInterval(topbanner_cb, 666);
1242 ;
1243 }
1244
1245 function topbanner_cb()
1246 {
1247     var a, b;
1248
1249     a = $('topbanner').style.backgroundColor;
1250     b = $('topbanner').style.borderLeftColor;
1251
1252     $('topbanner').style.backgroundColor = b;
1253     $('topbanner').style.borderColor = a+" "+a+" "+a+" "+a;
1254
1255     // console.log("A: "+a+"  B: "+b);
1256 }
1257
1258 function sidebanner_init()
1259 {
1260     setInterval(sidebanner_cb, 666);
1261 }
1262
1263 function sidebanner2_init()
1264 {
1265     setInterval(sidebanner2_cb, 666);
1266 }
1267
1268 function sidebanner_cb()
1269 {
1270     var a, b;
1271
1272     a = $('sidebanner').style.backgroundColor;
1273     b = $('sidebanner').style.borderLeftColor;
1274
1275     $('sidebanner').style.backgroundColor = b;
1276     $('sidebanner').style.borderColor = a+" "+a+" "+a+" "+a;
1277
1278     // console.log("A: "+a+"  B: "+b);
1279 }
1280
1281 function sidebanner2_cb()
1282 {
1283     var a, b;
1284
1285     a = $('sidebanner2').style.backgroundColor;
1286     b = $('sidebanner2').style.borderLeftColor;
1287
1288     $('sidebanner2').style.backgroundColor = b;
1289     $('sidebanner2').style.borderColor = a+" "+a+" "+a+" "+a;
1290
1291     // console.log("A: "+a+"  B: "+b);
1292 }
1293
1294
1295 function langtolng(lang)
1296 {
1297     if (lang == "en")
1298         return ("-en");
1299     else
1300         return ("");
1301 }
1302
1303 function formtext_hilite(obj)
1304 {
1305     obj.className = 'input_text';
1306     addEvent(obj, "focus", function () { this.className = 'input_text_hi'; });
1307     addEvent(obj, "blur",  function () { this.className = 'input_text'; });
1308 }
1309
1310 function formsub_hilite(obj)
1311 {
1312     obj.className = 'input_sub';
1313     addEvent(obj, "focus", function () { this.className = 'input_sub_hi'; });
1314     addEvent(obj, "blur",  function () { this.className = 'input_sub'; });
1315 }
1316
1317 // return the value of the radio button that is checked
1318 // return an empty string if none are checked, or
1319 // there are no radio buttons
1320 function get_checked_value(radioObj) {
1321         if(!radioObj)
1322                 return "";
1323         var radioLength = radioObj.length;
1324         if(radioLength == undefined)
1325                 if(radioObj.checked)
1326                         return radioObj.value;
1327                 else
1328                         return "";
1329         for(var i = 0; i < radioLength; i++) {
1330                 if(radioObj[i].checked) {
1331                         return radioObj[i].value;
1332                 }
1333         }
1334         return "";
1335 }
1336
1337 // set the radio button with the given value as being checked
1338 // do nothing if there are no radio buttons
1339 // if the given value does not exist, all the radio buttons
1340 // are reset to unchecked
1341 function set_checked_value(radioObj, newValue) {
1342         if(!radioObj)
1343                 return;
1344         var radioLength = radioObj.length;
1345         if(radioLength == undefined) {
1346                 radioObj.checked = (radioObj.value == newValue.toString());
1347                 return;
1348         }
1349         for(var i = 0; i < radioLength; i++) {
1350                 radioObj[i].checked = false;
1351                 if(radioObj[i].value == newValue.toString()) {
1352                         radioObj[i].checked = true;
1353                 }
1354         }
1355 }
1356
1357 function url_append_arg(url, name, value)
1358 {
1359     var pos, sep, pref, rest;
1360
1361     if ((pos = url.indexOf('?'+name+'=')) == -1) {
1362         pos = url.indexOf('&'+name+'=');
1363     }
1364     if (pos == -1) {
1365         if ((pos = url.indexOf('?')) != -1)
1366             sep = '&';
1367         else
1368             sep = '?';
1369
1370         return (url+sep+name+"="+encodeURIComponent(value));
1371     }
1372     else {
1373         pref = url.substring(0, pos+1);
1374         rest = url.substring(pos+1);
1375         // alert("rest: "+rest+"  pos: "+pos);
1376         if ((pos = rest.indexOf('&')) != -1) {
1377             rest = rest.substring(pos);
1378         }
1379         else {
1380             rest = "";
1381         }
1382         return (pref+name+"="+encodeURIComponent(value)+rest);
1383     }
1384 }
1385
1386 function url_append_args(url)
1387 {
1388     var i, ret;
1389
1390     ret = url;
1391     for (i = 1 ; i < arguments.length-1 ; i+= 2) {
1392         ret = url_append_arg(ret, arguments[i], arguments[i+1]);
1393     }
1394
1395     return (ret);
1396 }
1397
1398 function url_complete(parent, url)
1399 {
1400     var p, p2, rest;
1401     var host = "", path = "";
1402
1403     // host extraction
1404     p = parent.indexOf("://");
1405     if (p > -1) {
1406         rest = parent.substring(p+3);
1407         p2 = rest.indexOf("/");
1408         if (p2 > -1) {
1409             host = parent.substring(0, p+3+p2);
1410             rest = parent.substring(p+3+p2);
1411         }
1412         else {
1413             host = rest;
1414             rest = "";
1415         }
1416     }
1417     else {
1418         rest = parent;
1419     }
1420
1421     // path extraction
1422     p = rest.lastIndexOf("/");
1423     if (p > -1) {
1424         path = rest.substring(0, p+1);
1425     }
1426
1427     // alert("host: ["+host+"]  path: ["+path+"]");
1428     if (url.substring(0,6) == 'http:/' || url.substring(0,7) == 'https:/') {
1429         return (url);
1430     }
1431     else if (url.substring(0,1) == '/') {
1432         return (host+url);
1433     }
1434     else {
1435         return (host+path+url);
1436     }
1437 }