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