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