bbeccf1011eee803056f66a8c0d571c47e497edb
[brisk.git] / web / commons.js
1 /*
2  *  brisk - commons.js
3  *
4  *  Copyright (C) 2006-2008 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  * $Id$
23  *
24  */
25
26 var PLAYERS_N = 3;
27 var EXIT_BAN_TIME = 900;
28 var cookiepath = "/brisk/";
29
30 function $(id) { return document.getElementById(id); }
31
32 function getStyle(x,IEstyleProp, MozStyleProp) 
33 {
34     if (x.currentStyle) {
35         var y = x.currentStyle[IEstyleProp];
36     } else if (window.getComputedStyle) {
37         var y = document.defaultView.getComputedStyle(x,null).getPropertyValue(MozStyleProp);
38     }
39     return y;
40 }
41
42 /* replacement of setInterval on IE */
43 (function(){
44     /*if not IE, do nothing*/
45     if(!document.uniqueID){return;};
46
47     /*Copy the default setInterval behavior*/
48     var nativeSetInterval = window.setInterval;
49     window.setInterval = function(fn,ms) {              
50         var param = [];
51         if(arguments.length <= 2)       {
52             return nativeSetInterval(fn,ms);
53         }
54         else {
55             for(var i=2;i<arguments.length;i+=1) {
56                 param[i-2] =  arguments[i];
57             }   
58         }
59         
60         if(typeof(fn)=='function') {
61             
62             return (function (fn,ms,param) {
63                 var fo = function () {                                                          
64                     fn.apply(window,param);
65                 };                      
66                 return nativeSetInterval(fo,ms); 
67             })(fn,ms,param);
68         }
69         else if(typeof(fn)=='string')
70         {
71             return  nativeSetInterval(fn,ms);
72         }
73         else
74         {
75             throw Error('setInterval Error\nInvalid function type');
76         };
77     };
78
79     /*Copy the default setTimeout behavior*/
80     var nativeSetTimeout = window.setTimeout;
81     window.setTimeout = function(fn,ms) {               
82         var param = [];
83         if(arguments.length <= 2)       {
84             return nativeSetTimeout(fn,ms);
85         }
86         else {
87             for(var i=2;i<arguments.length;i+=1) {
88                 param[i-2] =  arguments[i];
89             }   
90         }
91         
92         if(typeof(fn)=='function') {
93             
94             return (function (fn,ms,param) {
95                 var fo = function () {                                                          
96                     fn.apply(window,param);
97                 };                      
98                 return nativeSetTimeout(fo,ms); 
99             })(fn,ms,param);
100         }
101         else if(typeof(fn)=='string')
102         {
103             return  nativeSetTimeout(fn,ms);
104         }
105         else
106         {
107             throw Error('setTimeout Error\nInvalid function type');
108         };
109     };
110
111 })()
112
113 function addEvent(obj,type,fn)
114 {
115     if (obj.addEventListener) {
116         obj.addEventListener( type, fn, false);
117     }
118     else if (obj.attachEvent) {
119         obj["e"+type+fn] = fn;
120         obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
121         obj.attachEvent( "on"+type, obj[type+fn] );
122     }
123     else
124         throw new Error("Event registration not supported");
125 }
126
127 function removeEvent(obj,type,fn)
128 {
129     if (obj.removeEventListener) {
130         obj.removeEventListener( type, fn, false );
131     }
132     else if (obj.detachEvent) {
133         obj.detachEvent( "on"+type, obj[type+fn] );
134         obj[type+fn] = null;
135         obj["e"+type+fn] = null;
136     }
137 }
138
139     // var card_pos = RANGE 0 <= x < cards_ea_n
140
141 function show_bigpict(obj, act, x, y)
142 {
143    var big;
144
145    // alert("offsetTop: "+obj.offsetTop+"  offsetLeft: "+obj.offsetLeft+"obj.id: "+obj.id);
146    big = $(obj.id+"_big");
147    if (act == "over") {
148        big.style.left = obj.offsetLeft + x+"px";
149        big.style.top  = obj.offsetTop  + y+"px";
150        big.style.visibility = "visible";
151        }
152    else {
153        big.style.visibility = "hidden";
154        }
155 }
156
157 function rnd_int(min, max) {
158   return Math.floor(Math.random() * (max - min + 1) + min);
159 }
160
161 function error_images()
162 {
163     alert("GHESEMU!");
164 }
165
166 function abort_images()
167 {
168     alert("ABORTAIMAGES");
169 }
170
171 function unload_images()
172 {
173     alert("ABORTAIMAGES");
174 }
175
176 function reset_images()
177 {
178     alert("ABORTAIMAGES");
179 }
180
181 function update_images()
182 {
183     //    if (g_imgct % 10 == 0) alert("g_imgct: "+g_imgct+" xx "+g_preload_img_arr[g_imgct]);
184     $("imgct").innerHTML = "Immagini caricate "+g_preload_imgsz_arr[g_imgct]+"%.";
185     if (g_imgct+1 < g_preload_img_arr.length) {
186         g_imgct++;
187         setTimeout(preload_images, 100, g_preload_img_arr, g_imgct-1);
188     }
189     // $("imgct").innerHTML += "U";
190 }
191
192 function preload_images(arr,idx)
193 {
194     var im = new Image;
195     
196     // $("imgct").innerHTML = "Stiamo caricando "+arr[idx]+"%.<br>";
197     im.onload =   update_images;
198     im.onerror =  error_images;
199     im.onabort =  abort_images;
200     im.onunload = unload_images;
201     im.onreset =  reset_images;
202     im.src =      arr[idx];
203     // $("imgct").innerHTML += "P";
204 }
205
206 function safestatus(a)
207 {
208     try{
209         return (a.status);
210     } catch(b)
211         { return (-1); }
212 }
213
214 function createXMLHttpRequest() {
215     try { return new ActiveXObject("Msxml2.XMLHTTP");    } catch(e) {}
216     try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {}
217     try { return new XMLHttpRequest();                   } catch(e) {}
218     alert("XMLHttpRequest not supported");
219     return null;
220 }
221
222 function send_mesg(mesg)
223 {
224     var xhr_wr = createXMLHttpRequest();
225
226     
227     xhr_wr.open('GET', 'index_wr.php?sess='+sess+'&mesg='+mesg, true);
228     xhr_wr.onreadystatechange = function() { return; };
229     xhr_wr.send(null);
230
231 }
232
233 /* Stat: CHAT and TABLE */
234
235 function chatt_checksend(obj,e)
236 {
237     var keynum;
238     var keychar;
239     var numcheck;
240
241     if(window.event) { // IE
242         keynum = e.keyCode;
243     }
244     else if(e.which) { // Netscape/Firefox/Opera
245         keynum = e.which;
246     }
247     // alert("OBJ: "+obj);
248     if (keynum == 13 && obj.value != "") { // Enter
249         act_chatt(obj.value);
250         obj.value = "";
251     }
252 }
253 function act_chatt(value)
254 {
255     send_mesg("chatt|"+encodeURIComponent(value));
256     /*
257     obj.disabled = true;
258     obj.value = "";
259     obj.disabled = false;
260     obj.focus();
261     */
262     return false;
263 }
264
265 /* Stat: ROOM */
266 function act_sitdown(table)
267 {
268     send_mesg("sitdown|"+table);
269 }
270
271 function act_wakeup()
272 {
273     send_mesg("wakeup");
274 }
275
276 /* Stat: TABLE  Subst: ASTA */
277 function act_asta(card,pnt)
278 {
279     send_mesg("asta|"+card+"|"+pnt);
280 }
281
282 function act_choose(card)
283 {
284     // alert("sitdown");
285     send_mesg("choose|"+card);
286 }
287
288 /* Stat: TABLE  Subst: GAME */
289 function act_play(card,x,y)
290 {
291     // alert("sitdown");
292     send_mesg("play|"+card+"|"+x+"|"+y);
293 }
294
295 function act_tableinfo()
296 {
297     send_mesg("tableinfo");
298 }
299
300 function act_help()
301 {
302     send_mesg("help");
303 }
304
305 function act_tav()
306 {
307     act_chatt('/tav '+$('txt_in').value); 
308     $('txt_in').value = '';
309 }
310
311 function act_about()
312 {
313     send_mesg("about");
314 }
315
316 function act_roadmap()
317 {
318     send_mesg("roadmap");
319 }
320
321 function act_whysupport()
322 {
323     send_mesg("whysupport");
324 }
325
326 function act_exitlock()
327 {
328     send_mesg("exitlock");
329 }
330
331 function safelogout()
332 {
333     var res;
334     
335     if (g_exitlock < 2) 
336         res = window.confirm("Sei sicuro di volere abbandonare la partita?\nATTENZIONE: se esci adesso senza il consenso degli altri giocatori non potrai sederti ai tavoli per "+(Math.floor(EXIT_BAN_TIME/60))+" minuti.");    
337     else 
338         res = window.confirm("Sei sicuro di volere abbandonare la partita?");
339     if (res)
340         act_logout(g_exitlock);
341 }
342
343 function act_lascio()
344 {
345     send_mesg("lascio");
346 }
347
348 function safelascio()
349 {
350     var res;
351
352     res = window.confirm("Sei sicuro di volere lasciare questa mano?");
353     if (res)
354         act_lascio();
355 }
356
357 function act_logout(exitlock)
358 {
359     send_mesg("logout|"+exitlock);
360 }
361
362 function act_reload()
363 {
364     window.onunload = null;
365     document.location.reload();
366 }
367
368 function act_shutdown()
369 {
370     var c = 0;
371
372     send_mesg("shutdown");
373     while (xhr_wr.readyState != 4)
374         c++;
375 }
376
377 function postact_logout()
378 {
379     // alert("postact_logout");
380     try { 
381         xhr_rd.abort();
382     } catch (e) {}
383
384     // eraseCookie("sess");
385     document.location.assign("index.php");
386 }
387
388 /*
389   function slowimg(img,x1,y1,deltat,free,action,srcend)
390   img    - image to move
391   x1,y1  - destination coords
392   deltat - time for each frame (in msec)
393   free   - when the release the local block for other operations (range: 0 - 1)
394   action - function to run when the image is moved
395   srcend - image to switch when the image is moved
396 */
397
398 function sleep(st, delay)
399 {
400     // alert("LOC_NEW PRE: "+st.st_loc_new);
401
402     st.st_loc_new++;
403
404     setTimeout(function(obj){ if (obj.st_loc_new > obj.st_loc) { obj.st_loc++; }},
405                delay, st);
406 }
407
408 function slowimg(img,x1,y1,deltat,free,action,srcend) {
409     this.img = img;
410
411     // this.x0  = parseInt(document.defaultView.getComputedStyle(this.img, "").getPropertyValue("left"));
412     this.x0 = parseInt(getStyle(this.img,"left", "left"));
413 // alert("img.x0 = "+this.x0);
414     // this.y0  = parseInt(document.defaultView.getComputedStyle(this.img, "").getPropertyValue("top"));
415     this.y0  = parseInt(getStyle(this.img,"top", "top"));
416     this.x1  = x1;
417     this.y1  = y1;
418     this.deltat = deltat;
419     this.free = free;
420     this.action = action;
421     this.srcend = srcend;
422 }
423
424 slowimg.prototype = {
425     img: null, 
426     st: null,
427     x0: 0,
428     y0: 0,
429     x1: 0,
430     y1: 0,
431     dx: 0,
432     dy: 0,
433     free: 0,
434     step_n:    0,
435     step_cur:  0,
436     step_free: 0,
437     time:      0,
438     deltat:   40,
439     tout: 0,
440     action: null,
441     srcend: null,
442     
443     setstart: function(x0,y0)
444     {
445         this.x0 = x0;
446         this.y0 = y0;
447     },
448     
449     setaction: function(act)
450     {
451         this.action = act;
452     },
453     
454
455     settime: function(time) 
456     {
457         this.time = (time < this.deltat ? this.deltat : time);
458         this.step_n = parseInt(this.time / this.deltat);
459         this.dx = (this.x1 - this.x0) / this.step_n;
460         this.dy = (this.y1 - this.y0) / this.step_n;
461         if (this.step_n * this.deltat == this.time) {
462             this.step_n--;
463         }
464         if (this.free < 1) {
465             this.step_free = parseInt(this.step_n * this.free);
466         }
467     },
468     
469     start: function(st)
470     {
471         // $("logz").innerHTML += "               xxxxxxxxxxxxxxxxxxxxxSTART<br>";
472         this.st = st;
473         this.st.st_loc_new++;
474         
475         this.img.style.visibility = "visible";
476         setTimeout(function(obj){ obj.animate(); }, this.deltat, this);
477     },
478     
479     animate: function()
480     {
481         // $("log").innerHTML = "Val " + this.step_cur + " N: " + this.step_n + "<br>";
482         if (this.step_cur == 0) {
483             var date = new Date();
484             // $("logz").innerHTML = "Timestart: " + date + "<br>";
485         }
486         if (this.step_cur <= this.step_n) {
487             this.img.style.left = this.x0 + this.dx * this.step_cur;
488             this.img.style.top  = this.y0 + this.dy * this.step_cur;
489             this.step_cur++;
490             setTimeout(function(obj){ obj.animate(); }, this.deltat, this);
491             if (this.step_cur == this.step_free && this.st != null) {
492                 if (this.st.st_loc < this.st.st_loc_new) {
493                     // alert("QUI1  " + this.step_cur + "  ZZ  "+  this.step_free);
494                     this.st.st_loc++;
495                     this.st = null;
496                 }
497             }
498         }
499         else {
500             this.img.style.left = this.x1;
501             this.img.style.top  = this.y1;
502             // $("logz").innerHTML += "xxxxxxxxxxxxxxxCLEAR<br>";
503             var date = new Date();
504             // $("logz").innerHTML += "Timestop: " + date + "<br>";
505
506             if (this.action != null) {
507                 eval(this.action);
508             }
509
510             if (this.st != null && this.st.st_loc < this.st.st_loc_new) {
511                 // alert("QUI2");
512                 this.st.st_loc++;
513                 this.st = null;
514             }
515             if (this.srcend != null) {
516                 this.img.src = this.srcend;
517             }
518         }
519     }
520 }
521
522 var asta_xarr = new Array(0,66,132);
523
524 /* TODO: impostare gli onclick */
525 function dispose_asta(idx, pnt, nopoint)
526 {
527     var i, btn, pass;
528     var btn;
529
530     for (i = 0 ; i < 10 ; i++) {
531         btn = $("asta"+i);
532         if (i < idx) {
533             btn.src = "img/astapasso"+(pnt >= 0 ? "" : "_ro")+".png";
534             btn.style.cursor = (pnt >= 0 ? "pointer" : "default");
535             pass = -1;
536         }
537         else {
538             btn.src = "img/asta"+i+(pnt >= 0 ? "" : "_ro")+".png";
539             btn.style.cursor = (pnt >= 0 ? "pointer" : "default");
540             pass = i;
541         }
542         if (i < 19)
543             btn.style.left = asta_xarr[i % 3];
544         else
545             btn.style.left = asta_xarr[(i+1) % 3];
546         
547         btn.style.top  = parseInt(i / 3) * 50 + (i == 9 ? 0 : 1);
548
549         if (pnt >= 0) {
550             eval("btn.onclick = function () { act_asta("+pass+",61); }");
551             btn.style.cursor = "pointer";
552         }
553         else {
554             btn.onclick = null;
555             btn.style.cursor = "default";
556         }
557     }
558     
559     
560     btn = $("astaptdiv");
561     btn.style.left = asta_xarr[i % 3];
562     btn.style.top = parseInt(i / 3) * 50 - 2;
563     // btn.style.visibility  = "visible";
564     
565     btn = $("astapt");
566     var rpnt = (pnt < 0 ? -pnt : pnt);
567     btn.value = (rpnt < 61 ? 61 : (rpnt > 120 ? 120 : rpnt));
568     
569     btn = $("astaptsub");
570     btn.style.left = asta_xarr[i % 3];
571     btn.style.top = 25 + parseInt(i / 3) * 50 - 1;
572     btn.src = "img/astaptsub"+(pnt >= 0 ? "" : "_ro")+".png";
573     btn.style.cursor = (pnt >= 0 ? "pointer" : "default");
574     if (pnt >= 0) {
575         btn.onclick = function () { act_asta(9,$("astapt").value); };
576         btn.style.cursor = "pointer";
577     }
578     else {
579         btn.onclick = null;
580         btn.style.cursor = "default";
581     }
582     
583     i+=1;
584     if (nopoint) {
585         btn = $("astapasso");
586         btn.style.left = asta_xarr[i % 3];
587         btn.style.top = parseInt(i / 3) * 50;
588         btn.src = "img/astapashalf"+(pnt >= 0 ? "" : "_ro")+".png";
589         btn.style.cursor = (pnt >= 0 ? "pointer" : "default");
590         if (pnt >= 0) {
591             btn.onclick = function () { act_asta(-1,0); };
592         }
593         else {          
594             btn.onclick = null;
595         }
596
597         btn = $("astalascio");
598         btn.style.left = asta_xarr[i % 3];
599         btn.style.top = parseInt(i / 3) * 50 + 24;
600         btn.src = "img/astalascio.png";
601         btn.style.visibility = "visible";
602         btn.onclick = function () { safelascio(); };
603         }
604     else {
605         btn = $("astapasso");
606         btn.style.left = asta_xarr[i % 3];
607         btn.style.top = parseInt(i / 3) * 50;;
608         btn.src = "img/astapasso"+(pnt >= 0 ? "" : "_ro")+".png";
609         btn.style.cursor = (pnt >= 0 ? "pointer" : "default");
610         if (pnt >= 0) {
611             btn.onclick = function () { act_asta(-1,0); };
612         }
613         else {
614             btn.onclick = null;
615         }
616
617         btn = $("astalascio");
618         btn.style.visibility = "hidden";
619         btn.onclick = null;
620     }
621     // btn.style.visibility  = "visible";
622     $("asta").style.visibility = "visible";
623 }
624
625 function asta_pnt_set(pnt)
626 {
627     btn = $("astapt");
628     var rpnt = (pnt < 0 ? -pnt : pnt);
629     btn.value = (rpnt < 61 ? 61 : (rpnt > 120 ? 120 : rpnt));
630 }
631
632 function hide_asta()
633 {
634     $("asta").style.visibility = "hidden"; 
635 }
636
637
638 function notify(st, text, tout, butt, w, h)
639 {
640     var clo, box;
641     var t = this;
642     
643     this.st = st;
644
645     this.ancestor = document.body;
646     
647     this.st.st_loc_new++;
648
649     clo = document.createElement("input");
650     clo.type = "submit";
651     clo.className = "button";
652     clo.style.bottom = "4px";
653     clo.value = butt;
654     clo.obj = this;
655     clo.onclick = this.input_hide;
656     
657     clodiv = document.createElement("div");
658     clodiv.className = "notify_clo";
659     clodiv.appendChild(clo);
660
661     box = document.createElement("div");
662     box.className = "notify";
663     box.innerHTML = text;
664     box.style.zIndex = 200;
665     box.style.width  = w+"px";
666     box.style.marginLeft  = -parseInt(w/2)+"px";
667     box.style.height = h+"px";
668     box.appendChild(clodiv);
669     box.style.visibility = "visible";
670
671     this.notitag = box;
672     
673     this.ancestor.appendChild(box);
674     
675     this.toutid = setTimeout(function(obj){ obj.unblock(); }, tout, this);
676 }
677
678 notify.prototype = {
679     ancestor: null,
680     st: null,
681     notitag: null,
682     toutid: null,
683     
684     unblock: function()
685     {
686         if (this.st.st_loc < this.st.st_loc_new) {
687             this.st.st_loc++;
688         }
689     },
690     
691     hide: function()
692     {
693         clearTimeout(this.toutid);
694         this.ancestor.removeChild(this.notitag);
695         this.unblock();
696     },
697
698     input_hide: function()
699     {
700         clearTimeout(this.obj.toutid);
701         this.obj.ancestor.removeChild(this.obj.notitag);
702         this.obj.unblock();
703     }
704 }
705         
706
707 function $(id) { 
708     return document.getElementById(id); 
709 }
710
711 function globst() {
712     this.st = -1;
713     this.st_loc = -1;
714     this.st_loc_new = -1;
715     this.comms  = new Array;
716 }
717
718
719
720 function remark_step()
721 {
722     var ct = $("remark").l_remct;
723     
724     if (ct != 0) {
725         ct++;
726         if (ct > 2)
727             ct = 1;
728         $("remark").className = "remark"+ct;
729         $("remark").l_remct = ct;
730         setTimeout(remark_step,500);
731     }
732     else
733         $("remark").className = "remark0";
734     
735     return;
736 }
737
738 function remark_on()
739 {
740     if ($("remark").l_remct == 0) {
741         $("remark").l_remct = 1;
742         setTimeout(remark_step,500);
743     }
744 }
745
746 function remark_off()
747 {
748     $("remark").l_remct = 0;
749     $("remark").className = "remark0";
750 }
751
752
753 function choose_seed(card)
754 {
755     var i;
756
757     $("chooseed").style.visibility = "visible";
758     for (i = 0 ; i < 4 ; i++) {
759         $("seed"+i).src = "img/"+i+""+card+".png";
760         seed=$("seed"+i);
761         eval("seed.onclick = function () { act_choose("+i+""+card+"); };");
762     }
763 }
764
765 function set_names(so,ea,ne,nw,we)
766 {
767 //    alert("EA: "+ea);
768     $("name").innerHTML = so; 
769     $("name").title = unescapeHTML(so); 
770     $("name_ea").innerHTML = ea;
771     $("name_ea").title = unescapeHTML(ea);
772     $("name_ne").innerHTML = ne;
773     $("name_ne").title = unescapeHTML(ne);
774     $("name_nw").innerHTML = nw;
775     $("name_nw").title = unescapeHTML(nw);
776     $("name_we").innerHTML = we;
777     $("name_we").title = unescapeHTML(we);
778
779     return;
780 }
781
782 var astat_suffix = new Array("","_ea","_ne","_nw","_we");
783
784 function show_astat(zer,uno,due,tre,qua)
785 {
786     var astat = new Array(zer,uno,due,tre,qua);
787
788     for (i = 0 ; i < PLAYERS_N ; i++) {
789         idx = (PLAYERS_N + i - table_pos) % PLAYERS_N;
790
791         if (astat[i] == -2) {
792             $("public"+astat_suffix[idx]).style.visibility = "hidden";
793         }
794         else if (astat[i] == -1) {
795             $("public"+astat_suffix[idx]).style.visibility = "visible";
796             $("pubacard"+astat_suffix[idx]).src = "img/astapasso.png";
797             $("pubapnt"+astat_suffix[idx]).innerHTML = "";
798             $("pubapnt"+astat_suffix[idx]).style.visibility = "hidden";
799         }
800         else if (astat[i] <= 10) {
801             $("public"+astat_suffix[idx]).style.visibility = "visible";
802             $("pubacard"+astat_suffix[idx]).src = "img/asta"+astat[i]+".png";
803             $("pubapnt"+astat_suffix[idx]).style.visibility = "hidden";
804         }
805         else if (astat[i] <= 120) {
806             $("public"+astat_suffix[idx]).style.visibility = "visible";
807             $("pubacard"+astat_suffix[idx]).src = "img/asta9.png";
808             $("pubapnt"+astat_suffix[idx]).style.visibility = "inherit"; // XXX VISIBLE
809             $("pubapnt"+astat_suffix[idx]).innerHTML = astat[i];
810         }
811     }
812 }
813
814 function exitlock_show(num, islock)
815 {
816     g_exitlock = num;
817
818     num = (num < 3 ? num : 3);
819     $("exitlock").src = "img/exitlock"+num+(islock ? "n" : "y")+".png";
820     // alert("EXITLOCK: "+$("exitlock").src);
821     $("exitlock").style.visibility = "visible";
822 }
823
824 var fin = 0;
825
826 //    exitlock_show(0, true);
827
828 function table_init() {
829     var sux = new Array("", "_ea", "_ne", "_nw", "_we");
830
831     // console.log("table_init");
832
833     remark_off();
834     $("asta").style.visibility = "hidden";
835     $("caller").style.visibility = "hidden";
836     show_astat(-2,-2,-2,-2,-2);
837     for (i=0 ; i < 8 ; i++) {
838         Drag.init($("card" + i), card_mouseup_cb);
839         for (e = 0 ; e < PLAYERS_N ; e++)
840             $("card"+sux[e]+i).style.visibility = "hidden";
841     }
842     for (i=0 ; i < PLAYERS_N ; i++) {
843         // console.log("shut: "+"takes"+sux[i]);
844         $("takes"+sux[i]).style.visibility = "hidden";
845         }
846
847     for (i = 0 ; i < 8 ; i++) {
848         cards_pos[i] = i;
849         cards_ea_pos[i] = i;
850         cards_ne_pos[i] = i;
851         cards_nw_pos[i] = i;
852         cards_we_pos[i] = i;
853     }
854
855 }
856   
857
858
859 var chatt_lines = new Array();
860 var chatt_lines_n = 0;
861
862 var CHATT_MAXLINES = 40;
863
864 /* PRO CHATT */
865 function chatt_sub(name,str)
866 {
867     var must_scroll = false;
868
869     // alert ($("txt").scrollTop + parseInt(getStyle($("txt"),"height", "height")) -  $("txt").scrollHeight);
870
871   if ($("txt").scrollTop + parseInt(getStyle($("txt"),"height", "height")) -  $("txt").scrollHeight >= 0)
872       must_scroll = true;
873
874   // alert("ARRIVA NAME: "+ name + "  STR:"+str);
875   if (chatt_lines_n == CHATT_MAXLINES) {
876     $("txt").innerHTML = "";
877     for (i = 0 ; i < (CHATT_MAXLINES - 1) ; i++) {
878       chatt_lines[i] = chatt_lines[i+1];
879       $("txt").innerHTML += chatt_lines[i];
880     }
881     chatt_lines[i] = "<b>"+name+"</b> "+str+ "<br>";
882     $("txt").innerHTML += chatt_lines[i];
883   }
884   else {
885     chatt_lines[chatt_lines_n] = "<b>"+name+"</b> "+str+ "<br>";
886     $("txt").innerHTML += chatt_lines[chatt_lines_n];
887     chatt_lines_n++;
888   }
889   // $("txt").innerHTML;
890
891
892   if (must_scroll) {
893       $("txt").scrollTop = 10000000;
894   }
895   // alert("scTOP "+$("txt").scrollTop+"  scHEIGHT: "+$("txt").scrollHeight+" HEIGHT: "+getStyle($("txt"),"height", "height") );
896 }
897
898 /*
899  *  GESTIONE DEI COOKIES
900  */
901 function createCookie(name,value,hours,path) {
902         if (hours) {
903                 var date = new Date();
904                 date.setTime(date.getTime()+(hours*60*60*1000));
905                 var expires = "; expires="+date.toGMTString();
906         }
907         else var expires = "";
908         document.cookie = name+"="+value+expires+"; path="+path;
909 }
910
911 function readCookie(name) {
912         var nameEQ = name + "=";
913         var ca = document.cookie.split(';');
914         for(var i=0;i < ca.length;i++) {
915                 var c = ca[i];
916                 while (c.charAt(0)==' ') c = c.substring(1,c.length);
917                 if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
918         }
919         return null;
920 }
921
922 function eraseCookie(name) {
923         createCookie(name,"",-1);
924 }
925
926 var onunload_times = 0;
927
928
929 function onunload_cb () {
930     var u = 0;
931     if (onunload_times == 0) {
932         var res = window.confirm("    Vuoi veramente abbandonare la briscola ?\n(clicca annulla o cancel se vuoi ricaricare la briscola)");
933         if (res == true) {
934             the_end = true; 
935             act_shutdown();
936             while (1) 
937                 u++;
938         }
939         else {
940             try {
941                 location = self.location;
942             } catch (e) {
943                 alert("Ripristino della briscola fallito, per non perdere la sessione ricaricare la pagina manualmente.");
944             }
945         }
946         onunload_times++;
947     }
948     
949     return(false);
950 }
951
952
953 function room_checkspace(emme,tables,inpe)
954 {
955     nome = "<b>";
956     for (i = 0 ; i < emme ; i++) 
957         nome += "m";
958     nome += "</b>";
959
960     alta = "";
961     for (i = 0 ; i < 5 ; i++) 
962         alta += nome+"<br>";
963
964     for (i = 0 ; i < tables ; i++) {
965         $("table"+i).innerHTML = alta;
966         $("table_act"+i).innerHTML = "<input type=\"button\" class=\"button\" name=\"xhenter"+i+"\"  value=\"Mi siedo.\" onclick=\"act_sitdown(1);\">";
967         }
968
969     stand = "<table class=\"table_standup\"><tbody><tr>";
970     for (i = 0 ; i < inpe ; i++) {
971         stand += "<td>"+nome+"</td>";
972         if ((i+1) % 4 == 0) {
973             stand += "</tr><tr>";
974         }
975     }
976     stand += "</tr>";
977     $("standup").innerHTML = stand;
978
979     $("esco").innerHTML = "<input class=\"button\" name=\"logout\" type=\"button\" value=\"Esco.\" onclick=\"window.onunload = null; act_logout();\" type=\"button\">";
980 }
981
982 function  unescapeHTML(cont) {
983     var div = document.createElement('div');
984     var memo = "";
985     var i;
986
987     div.innerHTML = cont;
988     if (div.childNodes[0]) {
989         if (div.childNodes.length > 1) {
990             if (div.childNodes.toArray)
991                 alert("si puo");
992             else {
993                 var length = div.childNodes.length, results = new Array(length);
994             while (length--)
995                 results[length] = div.childNodes[length];
996                 
997             for (i=0 ; i<results.length ; i++)
998                 memo = memo + results[i].nodeValue;
999             }
1000
1001             return (memo);
1002         }
1003         else {
1004             return (div.childNodes[0].nodeValue);
1005         }
1006     }
1007     else {
1008         return ('');
1009     }
1010 }
1011
1012 function playsound(tag, sound) {
1013    // g_withflash is a global var
1014    if (g_withflash) {
1015       $(tag).innerHTML = '<OBJECT classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" '+
1016 'codebase="http://active.macromedia.com/flash2/cabs/swflash.cab#version=4,0,0,0" id="mysound" WIDTH=1 HEIGHT=1>' +
1017 '<PARAM NAME="movie" VALUE="../playsound.swf"><PARAM NAME="PLAY" VALUE="true"><PARAM NAME="LOOP" VALUE="false">' +
1018 '<PARAM NAME=FlashVars VALUE="streamUrl='+sound+'">' +
1019 '<EMBED swliveconnect="true" name="mysound" src="../playsound.swf" FlashVars="streamUrl='+sound+'" PLAY="true" LOOP="false" '+
1020 ' WIDTH=1 HEIGHT=1 TYPE="application/x-shockwave-flash" PLUGINSPAGE="http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash"></OBJECT>';
1021    }
1022 }