aggiunto overload di setTimeout
[brisk.git] / web / commons.js
1 /*
2  *  brisk - commons.js
3  *
4  *  Copyright (C) 2006 matteo.nastasi@milug.org
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful, but
12  * WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABLILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14  * General Public License for more details. You should have received a
15  * copy of the GNU General Public License along with this program; if
16  * not, write to the Free Software Foundation, Inc, 59 Temple Place -
17  * Suite 330, Boston, MA 02111-1307, USA.
18  *
19  * $Id$
20  *
21  */
22
23 var PLAYERS_N = 3;
24
25 function $(id) { return document.getElementById(id); }
26
27 /* replacement of setInterval on IE */
28 (function(){
29     /*if not IE, do nothing*/
30     if(!document.uniqueID){return;};
31
32     /*Copy the default setInterval behavior*/
33     var nativeSetInterval = window.setInterval;
34     window.setInterval = function(fn,ms) {              
35         var param = [];
36         if(arguments.length <= 2)       {
37             return nativeSetInterval(fn,ms);
38         }
39         else {
40             for(var i=2;i<arguments.length;i+=1) {
41                 param[i-2] =  arguments[i];
42             }   
43         }
44         
45         if(typeof(fn)=='function') {
46             
47             return (function (fn,ms,param) {
48                 var fo = function () {                                                          
49                     fn.apply(window,param);
50                 };                      
51                 return nativeSetInterval(fo,ms); 
52             })(fn,ms,param);
53         }
54         else if(typeof(fn)=='string')
55         {
56             return  nativeSetInterval(fn,ms);
57         }
58         else
59         {
60             throw Error('setInterval Error\nInvalid function type');
61         };
62     };
63
64     /*Copy the default setTimeout behavior*/
65     var nativeSetTimeout = window.setTimeout;
66     window.setTimeout = function(fn,ms) {               
67         var param = [];
68         if(arguments.length <= 2)       {
69             return nativeSetTimeout(fn,ms);
70         }
71         else {
72             for(var i=2;i<arguments.length;i+=1) {
73                 param[i-2] =  arguments[i];
74             }   
75         }
76         
77         if(typeof(fn)=='function') {
78             
79             return (function (fn,ms,param) {
80                 var fo = function () {                                                          
81                     fn.apply(window,param);
82                 };                      
83                 return nativeSetTimeout(fo,ms); 
84             })(fn,ms,param);
85         }
86         else if(typeof(fn)=='string')
87         {
88             return  nativeSetTimeout(fn,ms);
89         }
90         else
91         {
92             throw Error('setTimeout Error\nInvalid function type');
93         };
94     };
95
96 })()
97
98     // var card_pos = RANGE 0 <= x < cards_ea_n
99
100 function rnd_int(min, max) {
101   return Math.floor(Math.random() * (max - min + 1) + min);
102 }
103
104 function error_images()
105 {
106     alert("GHESEMU!");
107 }
108
109 function abort_images()
110 {
111     alert("ABORTAIMAGES");
112 }
113
114 function unload_images()
115 {
116     alert("ABORTAIMAGES");
117 }
118
119 function reset_images()
120 {
121     alert("ABORTAIMAGES");
122 }
123
124 function update_images()
125 {
126     $("imgct").innerHTML = "Immagini caricate "+g_preload_imgsz_arr[g_imgct]+"%.";
127     if (g_imgct < g_preload_img_arr.length)
128         setTimeout(preload_images, 100, g_preload_img_arr, g_imgct);
129     g_imgct++;
130     // $("imgct").innerHTML += "U";
131 }
132
133 function preload_images(arr,idx)
134 {
135     var im = new Image;
136     
137     // $("imgct").innerHTML = "Stiamo caricando "+arr[idx]+"%.<br>";
138     im.onload =   update_images;
139     im.onerror =  error_images;
140     im.onabort =  abort_images;
141     im.onunload = unload_images;
142     im.onreset =  reset_images;
143     im.src =      arr[idx];
144     // $("imgct").innerHTML += "P";
145 }
146
147 function safestatus(a)
148 {
149     try{
150         return (a.status);
151     } catch(b)
152         { return (-1); }
153 }
154
155 function createXMLHttpRequest() {
156     try { return new ActiveXObject("Msxml2.XMLHTTP");    } catch(e) {}
157     try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {}
158     try { return new XMLHttpRequest();                   } catch(e) {}
159     alert("XMLHttpRequest not supported");
160     return null;
161 }
162
163 function send_mesg(mesg)
164 {
165     var xhr_wr = createXMLHttpRequest();
166     // xhr_wr.open('GET', 'index_wr.php?sess='+sess+'&mesg='+encodeURIComponent(mesg), true);
167     xhr_wr.open('GET', 'index_wr.php?sess='+sess+'&mesg='+mesg, true);
168     xhr_wr.onreadystatechange = function() { return; };
169     xhr_wr.send(null);
170
171 }
172
173 /* Stat: CHAT and TABLE */
174
175 function chatt_checksend(obj,e)
176 {
177     var keynum;
178     var keychar;
179     var numcheck;
180
181     if(window.event) { // IE
182         keynum = e.keyCode;
183     }
184     else if(e.which) { // Netscape/Firefox/Opera
185         keynum = e.which;
186     }
187     // alert("OBJ: "+obj);
188     if (keynum == 13 && obj.value != "") { // Enter
189         act_chatt(obj.value);
190         obj.value = "";
191     }
192 }
193 function act_chatt(value)
194 {
195     send_mesg("chatt|"+encodeURIComponent(value));
196     /*
197     obj.disabled = true;
198     obj.value = "";
199     obj.disabled = false;
200     obj.focus();
201     */
202     return false;
203 }
204
205 /* Stat: ROOM */
206 function act_sitdown(table)
207 {
208     send_mesg("sitdown|"+table);
209 }
210
211 function act_wakeup()
212 {
213     send_mesg("wakeup");
214 }
215
216 /* Stat: TABLE  Subst: ASTA */
217 function act_asta(card,pnt)
218 {
219     send_mesg("asta|"+card+"|"+pnt);
220 }
221
222 function act_choose(card)
223 {
224     // alert("sitdown");
225     send_mesg("choose|"+card);
226 }
227
228 /* Stat: TABLE  Subst: GAME */
229 function act_play(card,x,y)
230 {
231     // alert("sitdown");
232     send_mesg("play|"+card+"|"+x+"|"+y);
233 }
234
235 function act_tableinfo()
236 {
237     send_mesg("tableinfo");
238 }
239
240 function act_help()
241 {
242     send_mesg("help");
243 }
244
245 function act_about()
246 {
247     send_mesg("about");
248 }
249
250 function safelogout()
251 {
252     var res;
253
254     res = window.confirm("Sei sicuro di volere abbandonare la partita?");
255     if (res)
256         act_logout();
257 }
258 function act_logout()
259 {
260     send_mesg("logout");
261 }
262
263 function act_reload()
264 {
265     window.onunload = null;
266     document.location.reload();
267 }
268
269 function act_shutdown()
270 {
271     var c = 0;
272
273     send_mesg("shutdown");
274     while (xhr_wr.readyState != 4)
275         c++;
276 }
277
278 function act_preout()
279 {
280     act_logout();
281 }
282
283 function postact_logout()
284 {
285     // alert("postact_logout");
286     try { 
287         xhr_rd.abort();
288     } catch (e) {}
289
290     // eraseCookie("sess");
291     document.location.assign("index.php");
292 }
293
294 /*
295   function slowimg(img,x1,y1,deltat,free,action,srcend)
296   img    - image to move
297   x1,y1  - destination coords
298   deltat - time for each frame (in msec)
299   free   - when the release the local block for other operations (range: 0 - 1)
300   action - function to run when the image is moved
301   srcend - image to switch when the image is moved
302 */
303
304 function sleep(st, delay)
305 {
306     // alert("LOC_NEW PRE: "+st.st_loc_new);
307
308     st.st_loc_new++;
309
310     setTimeout(function(obj){ if (obj.st_loc_new > obj.st_loc) { obj.st_loc++; }},
311                delay, st);
312 }
313
314 function slowimg(img,x1,y1,deltat,free,action,srcend) {
315     this.img = img;
316
317     this.x0  = parseInt(document.defaultView.getComputedStyle(this.img, "").getPropertyValue("left"));
318     // alert("img.x0 = "+this.x0);
319     this.y0  = parseInt(document.defaultView.getComputedStyle(this.img, "").getPropertyValue("top"));
320     this.x1  = x1;
321     this.y1  = y1;
322     this.deltat = deltat;
323     this.free = free;
324     this.action = action;
325     this.srcend = srcend;
326 }
327
328 slowimg.prototype = {
329     img: null, 
330     st: null,
331     x0: 0,
332     y0: 0,
333     x1: 0,
334     y1: 0,
335     dx: 0,
336     dy: 0,
337     free: 0,
338     step_n:    0,
339     step_cur:  0,
340     step_free: 0,
341     time:      0,
342     deltat:   40,
343     tout: 0,
344     action: null,
345     srcend: null,
346     
347     setstart: function(x0,y0)
348     {
349         this.x0 = x0;
350         this.y0 = y0;
351     },
352     
353     setaction: function(act)
354     {
355         this.action = act;
356     },
357     
358     settime: function(time) 
359     {
360         this.time = time;
361         this.step_n = parseInt(time / this.deltat);
362         this.dx = (this.x1 - this.x0) / this.step_n;
363         this.dy = (this.y1 - this.y0) / this.step_n;
364         if (this.step_n * this.deltat == time) {
365             this.step_n--;
366         }
367         this.step_free = parseInt(this.step_n * this.free);
368     },
369     
370     start: function(st)
371     {
372         // $("logz").innerHTML += "               xxxxxxxxxxxxxxxxxxxxxSTART<br>";
373         this.st = st;
374         this.st.st_loc_new++;
375         
376         this.img.style.visibility = "visible";
377         setTimeout(function(obj){ obj.animate(); }, this.deltat, this);
378     },
379     
380     animate: function()
381     {
382         // $("log").innerHTML = "Val " + this.step_cur + " N: " + this.step_n + "<br>";
383         if (this.step_cur == 0) {
384             var date = new Date();
385             // $("logz").innerHTML = "Timestart: " + date + "<br>";
386         }
387         if (this.step_cur <= this.step_n) {
388             this.img.style.left = this.x0 + this.dx * this.step_cur;
389             this.img.style.top  = this.y0 + this.dy * this.step_cur;
390             this.step_cur++;
391             setTimeout(function(obj){ obj.animate(); }, this.deltat, this);
392             if (this.step_cur == this.step_free && this.st != null) {
393                 if (this.st != null && this.st.st_loc < this.st.st_loc_new) {
394                     // alert("QUI1  " + this.step_cur + "  ZZ  "+  this.step_free);
395                     this.st.st_loc++;
396                     this.st = null;
397                 }
398             }
399         }
400         else {
401             this.img.style.left = this.x1;
402             this.img.style.top  = this.y1;
403             // $("logz").innerHTML += "xxxxxxxxxxxxxxxCLEAR<br>";
404             var date = new Date();
405             // $("logz").innerHTML += "Timestop: " + date + "<br>";
406             if (this.st != null && this.st.st_loc < this.st.st_loc_new) {
407                 // alert("QUI2");
408                 this.st.st_loc++;
409                 this.st = null;
410             }
411             if (this.action != null) {
412                 eval(this.action);
413             }
414             if (this.srcend != null) {
415                 this.img.src = this.srcend;
416             }
417         }
418     }
419 }
420
421 var asta_xarr = new Array(0,66,133);
422
423 /* TODO: impostare gli onclick */
424 function dispose_asta(idx, pnt)
425 {
426     var i, btn, pass;
427     
428     var btn;
429     for (i = 0 ; i < 10 ; i++) {
430         btn = $("asta"+i);
431         if (i < idx) {
432             btn.src = "img/astapasso"+(pnt >= 0 ? "" : "_ro")+".png";
433             pass = -1;
434         }
435         else {
436             btn.src = "img/asta"+i+(pnt >= 0 ? "" : "_ro")+".png";
437             pass = i;
438         }
439         if (i < 19)
440             btn.style.left = asta_xarr[i % 3];
441         else
442             btn.style.left = asta_xarr[(i+1) % 3];
443         
444         btn.style.top  = parseInt(i / 3) * 50+1;
445         // btn.style.visibility  = "visible";
446         
447         if (pnt >= 0)
448             eval("btn.onclick = function () { act_asta("+pass+",61); }");
449         else
450             btn.onclick = null;
451     }
452     
453     
454     btn = $("astaptdiv");
455     btn.style.left = asta_xarr[i % 3];
456     btn.style.top = parseInt(i / 3) * 50;
457     // btn.style.visibility  = "visible";
458     
459     btn = $("astapt");
460     var rpnt = (pnt < 0 ? -pnt : pnt);
461     btn.value = (rpnt < 61 ? 61 : (rpnt > 120 ? 120 : rpnt));
462     
463     btn = $("astaptsub");
464     btn.style.left = asta_xarr[i % 3];
465     btn.style.top = 25 + parseInt(i / 3) * 50;;
466     btn.src = "img/astaptsub"+(pnt >= 0 ? "" : "_ro")+".png";
467     // btn.style.visibility  = "visible";
468     if (pnt >= 0)
469         btn.onclick = function () { act_asta(9,$("astapt").value); };
470     else
471         btn.onclick = null;
472     
473     i+=1;
474     btn = $("astapasso2");
475     btn.style.left = asta_xarr[i % 3];
476     btn.style.top = parseInt(i / 3) * 50;;
477     btn.src = "img/astapasso"+(pnt >= 0 ? "" : "_ro")+".png";
478     // btn.style.visibility  = "visible";
479     if (pnt >= 0)
480         btn.onclick = function () { act_asta(-1,0); };
481     else
482         btn.onclick = null;
483     $("asta").style.visibility = "visible";
484 }
485
486 function hide_asta()
487 {
488     $("asta").style.visibility = "hidden"; 
489 }
490
491
492 function notify(st, text, tout, butt, w, h)
493 {
494     var clo, box;
495     var t = this;
496     
497     this.st = st;
498
499     this.ancestor = document.body;
500     
501     this.st.st_loc_new++;
502
503     clo = document.createElement("input");
504     clo.type = "submit";
505     clo.className = "button";
506     clo.style.bottom = "4px";
507     clo.value = butt;
508     clo.obj = this;
509     clo.onclick = this.input_hide;
510     
511     clodiv = document.createElement("div");
512     clodiv.className = "notify_clo";
513     clodiv.appendChild(clo);
514
515     box = document.createElement("div");
516     box.className = "notify";
517     box.innerHTML = text;
518     box.style.zIndex = 200;
519     box.style.width  = w+"px";
520     box.style.height = h+"px";
521     box.appendChild(clodiv);
522     box.style.visibility = "visible";
523
524     this.notitag = box;
525     
526     this.ancestor.appendChild(box);
527     
528     this.toutid = setTimeout(function(obj){ obj.unblock(); }, tout, this);
529 }
530
531 notify.prototype = {
532     ancestor: null,
533     st: null,
534     notitag: null,
535     toutid: null,
536     
537     unblock: function()
538     {
539         if (this.st.st_loc < this.st.st_loc_new) {
540             this.st.st_loc++;
541         }
542     },
543     
544     hide: function()
545     {
546         clearTimeout(this.toutid);
547         this.ancestor.removeChild(this.notitag);
548         this.unblock();
549     },
550
551     input_hide: function()
552     {
553         clearTimeout(this.obj.toutid);
554         this.obj.ancestor.removeChild(this.obj.notitag);
555         this.obj.unblock();
556     }
557 }
558         
559
560 function $(id) { 
561     return document.getElementById(id); 
562 }
563
564 function globst() {
565     this.st = -1;
566     this.st_loc = -1;
567     this.st_loc_new = -1;
568     this.comms  = new Array;
569 }
570
571
572
573 function remark_step()
574 {
575     var ct = $("remark").l_remct;
576     
577     if (ct != 0) {
578         ct++;
579         if (ct > 2)
580             ct = 1;
581         $("remark").className = "remark"+ct;
582         $("remark").l_remct = ct;
583         setTimeout(remark_step,500);
584     }
585     else
586         $("remark").className = "remark0";
587     
588     return;
589 }
590
591 function remark_on()
592 {
593     if ($("remark").l_remct == 0) {
594         $("remark").l_remct = 1;
595         setTimeout(remark_step,500);
596     }
597 }
598
599 function remark_off()
600 {
601     $("remark").l_remct = 0;
602     $("remark").className = "remark0";
603 }
604
605
606 function choose_seed(card)
607 {
608     var i;
609
610     $("chooseed").style.visibility = "visible";
611     for (i = 0 ; i < 4 ; i++) {
612         $("seed"+i).src = "img/"+i+""+card+".png";
613         seed=$("seed"+i);
614         eval("seed.onclick = function () { act_choose("+i+""+card+"); };");
615     }
616 }
617
618 function set_names(so,ea,ne,nw,we)
619 {
620 //    alert("EA: "+ea);
621     $("name").innerHTML = so; 
622     $("name").title = so; 
623     $("name_ea").innerHTML = ea;
624     $("name_ea").title = ea;
625     $("name_ne").innerHTML = ne;
626     $("name_ne").title = ne;
627     $("name_nw").innerHTML = nw;
628     $("name_nw").title = nw;
629     $("name_we").innerHTML = we;
630     $("name_we").title = we;
631
632     return;
633 }
634
635 var astat_suffix = new Array("","_ea","_ne","_nw","_we");
636
637 function show_astat(zer,uno,due,tre,qua)
638 {
639     var astat = new Array(zer,uno,due,tre,qua);
640
641     for (i = 0 ; i < PLAYERS_N ; i++) {
642         idx = (PLAYERS_N + i - table_pos) % PLAYERS_N;
643
644         if (astat[i] == -2) {
645             $("public"+astat_suffix[idx]).style.visibility = "hidden";
646         }
647         else if (astat[i] == -1) {
648             $("public"+astat_suffix[idx]).style.visibility = "visible";
649             $("pubacard"+astat_suffix[idx]).src = "img/astapasso.png";
650             $("pubapnt"+astat_suffix[idx]).innerHTML = "";
651             $("pubapnt"+astat_suffix[idx]).style.visibility = "hidden";
652         }
653         else if (astat[i] <= 10) {
654             $("public"+astat_suffix[idx]).style.visibility = "visible";
655             $("pubacard"+astat_suffix[idx]).src = "img/asta"+astat[i]+".png";
656             $("pubapnt"+astat_suffix[idx]).style.visibility = "hidden";
657         }
658         else if (astat[i] <= 120) {
659             $("public"+astat_suffix[idx]).style.visibility = "visible";
660             $("pubacard"+astat_suffix[idx]).src = "img/asta9.png";
661             $("pubapnt"+astat_suffix[idx]).style.visibility = "inherit"; // XXX VISIBLE
662             $("pubapnt"+astat_suffix[idx]).innerHTML = astat[i];
663         }
664     }
665 }
666
667 var fin = 0;
668
669 function table_init() {
670     var sux = new Array("", "_ea", "_ne", "_nw", "_we");
671
672     remark_off();
673
674     $("asta").style.visibility = "hidden";
675     $("caller").style.visibility = "hidden";
676     show_astat(-2,-2,-2,-2,-2);
677
678     for (i=0 ; i < 8 ; i++) {
679         Drag.init($("card" + i), card_mouseup_cb);
680         for (e = 0 ; e < PLAYERS_N ; e++)
681             $("card"+sux[e]+i).style.visibility = "hidden";
682     }
683     for (i=0 ; i < PLAYERS_N ; i++) {
684         $("takes"+sux[i]).style.visibility = "hidden";
685         }
686
687     for (i = 0 ; i < 8 ; i++) {
688         cards_pos[i] = i;
689         cards_ea_pos[i] = i;
690         cards_ne_pos[i] = i;
691         cards_nw_pos[i] = i;
692         cards_we_pos[i] = i;
693     }
694
695 }
696   
697
698
699 var chatt_lines = new Array();
700 var chatt_lines_n = 0;
701
702 var CHATT_MAXLINES = 40;
703
704 /* PRO CHATT */
705 function chatt_sub(name,str)
706 {
707   // alert("ARRIVA NAME: "+ name + "  STR:"+str);
708   if (chatt_lines_n == CHATT_MAXLINES) {
709     $("txt").innerHTML = "";
710     for (i = 0 ; i < (CHATT_MAXLINES - 1) ; i++) {
711       chatt_lines[i] = chatt_lines[i+1];
712       $("txt").innerHTML += chatt_lines[i];
713     }
714     chatt_lines[i] = "<b>"+name+"</b> "+str+ "<br>";
715     $("txt").innerHTML += chatt_lines[i];
716   }
717   else {
718     chatt_lines[chatt_lines_n] = "<b>"+name+"</b> "+str+ "<br>";
719     $("txt").innerHTML += chatt_lines[chatt_lines_n];
720     chatt_lines_n++;
721   }
722   $("txt").innerHTML;
723   $("txt").scrollTop = 10000000;
724 }
725
726 /*
727  *  GESTIONE DEI COOKIES
728  */
729 function createCookie(name,value,hours,path) {
730         if (hours) {
731                 var date = new Date();
732                 date.setTime(date.getTime()+(hours*60*60*1000));
733                 var expires = "; expires="+date.toGMTString();
734         }
735         else var expires = "";
736         document.cookie = name+"="+value+expires+"; path="+path;
737 }
738
739 function readCookie(name) {
740         var nameEQ = name + "=";
741         var ca = document.cookie.split(';');
742         for(var i=0;i < ca.length;i++) {
743                 var c = ca[i];
744                 while (c.charAt(0)==' ') c = c.substring(1,c.length);
745                 if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
746         }
747         return null;
748 }
749
750 function eraseCookie(name) {
751         createCookie(name,"",-1);
752 }
753
754 var onunload_times = 0;
755
756
757 function onunload_cb () {
758     var u = 0;
759     if (onunload_times == 0) {
760         var res = window.confirm("    Vuoi veramente abbandonare la briscola ?\n(clicca annulla o cancel se vuoi ricaricare la briscola)");
761         if (res == true) {
762             the_end = true; 
763             act_shutdown();
764             while (1) 
765                 u++;
766         }
767         else {
768             try {
769                 location = self.location;
770             } catch (e) {
771                 alert("Ripristino della briscola fallito, per non perdere la sessione ricaricare la pagina manualmente.");
772             }
773         }
774         onunload_times++;
775     }
776     
777     return(false);
778 }
779
780
781 function room_checkspace(emme,tables,inpe)
782 {
783     nome = "<b>";
784     for (i = 0 ; i < emme ; i++) 
785         nome += "m";
786     nome += "</b>";
787
788     alta = "";
789     for (i = 0 ; i < 5 ; i++) 
790         alta += nome+"<br>";
791
792     for (i = 0 ; i < tables ; i++) {
793         $("table"+i).innerHTML = alta;
794         $("table_act"+i).innerHTML = "<input type=\"button\" class=\"button\" name=\"xhenter"+i+"\"  value=\"Mi siedo.\" onclick=\"act_sitdown(1);\">";
795         }
796
797     stand = "<table class=\"table_standup\"><tbody><tr>";
798     for (i = 0 ; i < inpe ; i++) {
799         stand += "<td class=\"td_standup\">"+nome+"</td>";
800         if ((i+1) % 4 == 0) {
801             stand += "</tr><tr>";
802         }
803     }
804     stand += "</tr>";
805     $("standup").innerHTML = stand;
806
807     $("esco").innerHTML = "<input name=\"logout\" type=\"button\" value=\"Esco.\" onclick=\"window.onunload = null; act_logout();\" type=\"button\">";
808 }