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