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