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