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