
// ie or other browsers?
var ie = !!document.all;
// Impostare:
// <body onload="imjs_HTMLOnLoad()">
// <img src="/immagineinsignificante.gif/jpg/png" onload="imjs_HTMLWhenLoaded(miafunzione, this, new Array(argomentivari)"></img>
var imjs_HTMLWhenLoadedQueue = new Array();

function imjs_HTMLWhenLoaded(fn, bag, args) {
   // Costruisco oggetto vuoto
   var WhenLoaded = {};
   // Aggiungo proprietà 'fn' (stringa = nome della funzione che desidero)
   WhenLoaded.fn = fn;
   // Oggetto che verrà passato alla 'fn'
   WhenLoaded.bag = bag;
   // Array di argomenti vari che verranno passati alla 'fn'
   WhenLoaded.args = args;
   // Aggiungo questa funzione alla coda delle funzioni onload
   imjs_HTMLWhenLoadedQueue.push(WhenLoaded);
}

// elabora la coda imjs_HTMLWhenLoadedQueue
function imjs_HTMLOnLoad() {
   while (0 < imjs_HTMLWhenLoadedQueue.length) {
      var WhenLoaded = imjs_HTMLWhenLoadedQueue.shift();
      // Costruisco la chiamata a funzione
      var cmdLoaded = new Array(
         WhenLoaded.fn
         , "("
         , "WhenLoaded.bag"
         , ","
         , "'"
         , WhenLoaded.args.join("','")
         , "'"
         , ")"
      ).join("");
      // Chiamo la funzione
      eval(cmdLoaded);
   }
}

function imjs_NewTag(tagname, innerhtml) {
   var t;
   if (0 < tagname.length) {
      t = document.createElement(tagname.toUpperCase());
      if (innerhtml != null && 0 < innerhtml.length) {
         t.innerHTML = innerhtml;
      }
   } else {
      t = document.createTextNode(innerhtml);
   }
   return t;
}

function imjs_NewInput(type, value, id, onclick) {
   var i = imjs_NewTag("input", "");
   i.setAttribute("type", type);
   i.setAttribute("value", value);
   i.setAttribute("id", id);
   i.setAttribute("name", id);
   i.setAttribute("onclick", onclick);
   return i;
}

function imjs_NewTable(align) {
   var t = imjs_NewTag("table");
   t.setAttribute("align",(align == null ? "center" : align));
   t.setAttribute("border","0");
   t.setAttribute("cellpadding","0");
   t.setAttribute("cellspacing","0");

   t
   .appendChild(imjs_NewTag("tbody"))
   .appendChild(imjs_NewTag("tr"))
   .appendChild(imjs_NewTag("td"))
   ;
   return t;
}

function imjs_NewTableShadow(align, shsize, shcolor) {
   var tbshadow = imjs_NewTable(align);
   var tbshadowimg;
   
   tbshadowimg = tbshadow.childNodes[0].childNodes[0].appendChild(imjs_NewTag("td")).appendChild(imjs_NewTag("img"));
   tbshadowimg.setAttribute("src", "http://www.imatica.it/javascript/DropShadow.php");
   tbshadowimg.setAttribute("alt", ".");
   tbshadowimg.setAttribute("onload", "".concat("imjs_HTMLDropShadow(this,", shsize, ",'", shcolor, "', 'e')"));
   
   var tbshadowtr = tbshadow.childNodes[0].appendChild(imjs_NewTag("tr"));
   tbshadowimg = tbshadowtr.appendChild(imjs_NewTag("td")).appendChild(imjs_NewTag("img"));
   tbshadowimg.setAttribute("src", "http://www.imatica.it/javascript/DropShadow.php");
   tbshadowimg.setAttribute("alt", ".");
   tbshadowimg.setAttribute("onload", "".concat("imjs_HTMLDropShadow(this,", shsize, ",'", shcolor, "', 's')"));

   tbshadowimg = tbshadowtr.appendChild(imjs_NewTag("td")).appendChild(imjs_NewTag("img"));
   tbshadowimg.setAttribute("src", "http://www.imatica.it/javascript/DropShadow.php");
   tbshadowimg.setAttribute("alt", ".");
   tbshadowimg.setAttribute("onload", "".concat("imjs_HTMLDropShadow(this,", shsize, ",'", shcolor, "', 'se')"));

   return tbshadow;
}


/*
 * Cerca un Tag corrispondente a determinati criteri
 * criteri di ricerca:
 * Se objname inizia con un '.' allora stiamo cercando una classe
 * Se objname inizia con un '#' allora stiamo cercando uno specifico id
 * In tutti gli altri casi cerchiamo il primo tag con il nome specificato
 */
function imjs_HTMLFindTag(starttag, objname, defaulttag) {
   var foundtag = starttag;
   switch (objname.charAt(0)) {
   case '#':
      foundtag = document.getElementById(objname.substr(1));
      break;
   case '.':
      objname = objname.substr(1);
      while (foundtag != null && foundtag.className != objname) {
        foundtag = (ie ? foundtag.parentElement : foundtag.parentNode);
      }
      break;
   default:
      objname = objname.toUpperCase();
      while (foundtag != null && foundtag.tagName != objname) {
        foundtag = (ie ? foundtag.parentElement : foundtag.parentNode);
      }
   }
   return (foundtag == null) ? defaulttag : foundtag;
}

function imjs_HTMLSavePos(tag) {
   var pos = {};
   tag.style.position = "relative";
   pos.x = tag.offsetLeft;
   pos.y = tag.offsetTop;

   tag.style.left = "0px";
   tag.style.top = "0px";

   pos.x -= tag.offsetLeft;
   pos.y -= tag.offsetTop;
   pos.tag = tag;
   pos.Restore = function () {
      this.tag.style.position = "relative";
      this.tag.style.left = "".concat(this.x, "px");
      this.tag.style.top = "".concat(this.y, "px");
   }

   tag.style.left = "".concat(pos.x, "px");
   tag.style.top = "".concat(pos.y, "px");
   return pos;
}

function imjs_HTMLRestorePos(tag, pos) {
}

// Restituisce un oggetto timer tramite il quale è possibile 
function imjs_HTMLMoveTag(tag, howto) {
   args = howto.split(",");
   var tm;
   switch (args.shift()) {
   case "circle":
      break;
   case "spiral":
      break;
   case "lineto":
      // 20 Fotogrammi al secondo
      var tmmillis = 1000 / 20;
      // Costruisco un oggetto Timer, con il quale muoverò il tag
      tm = new imjs_Timer(tmmillis, function(tm) {
         var nx = tm.fmX + tm.dX * tm.pulses;
         var ny = tm.fmY + tm.dY * tm.pulses;
         tm.tag.style.left = "".concat(nx, "px");
         tm.tag.style.top = "".concat(ny, "px");
         if (tm.steps <= tm.pulses) {
            if (tm.Moved != null) {
               tm.Moved(tm);
            }
            tm.Kill();
         }
      });

      // Per muovere il tag la position deve essere 'relative'
      tag.style.position = "relative";

      tm.pos = imjs_HTMLSavePos(tag);

      // Imposto le proprietà specifiche di questo movimento
      tm.fmX = tm.pos.x;
      tm.fmY = tm.pos.y;
      tm.toX = parseFloat(args.shift());
      tm.toY = parseFloat(args.shift());
      tm.steps = parseFloat(args.shift()) * (1000 / tmmillis);
      tm.dX = (tm.toX - tm.fmX) / tm.steps;
      tm.dY = (tm.toY - tm.fmY) / tm.steps;
      tm.tag = tag;
      break;
   }
   return tm;
}

// Crea un URL
function imjs_HTMLComposeGET() {
   var url = new Array();
   var sep = new Array( "", "?" );
   var narg = -1;
   while (++narg < arguments.length) {
      var arg = arguments[narg];
      if (arg != null) {
         url.push(sep.shift());
         url.push(arg);
         sep.push( "=", "&" );
      }
   }
   return url.join("");
}

// Aggiunge una Dropshadow ad una tabella appositamente creata
// Preraquisiti:
// - tabella 2x2
// Mettere nelle celle a E, SE, S 3 tag come questo:
// <img src="/javascript/DropShadow.php" alt="." onload="imjs_HTMLDropShadow(this, 4, 'FFFFFF', 'e')" />
// Variando l'ultimo parametro (che nell'esempio è la stringa 'e') a seconda della cella in cui risiede l'immagine.
// Questa funzione si occupa di aggiungere l'ombra ai tag IMG
function imjs_HTMLDropShadow(img, size, shcolor, type) {
   var td = imjs_HTMLFindTag(img, 'td', null);
   if (td != null) {
      var baseurl = img.src;

      var shurl = "".concat("url(", imjs_HTMLComposeGET(baseurl, "size", size, "shcolor", shcolor, "type", type), ") repeat-");
      td.style.textAlign = "left";
      td.style.verticalAlign = "top";

      switch (type) {
      case "s":
         td.style.background = shurl.concat("x");
         td.style.width = "";
         td.style.height = "";
         type = "sw";
         break;
      case "e":
         td.style.background = shurl.concat("y");
         td.style.width = "";
         td.style.height = "";
         type = "ne";
         break;
      }

      img.onload = "";
      img.src = imjs_HTMLComposeGET(baseurl, "size", size, "shcolor", shcolor, "type", type);
   }
}

function inspect(tag, showNaN) {
   var r = "";
   for (p in tag) {
      try {
         var v = parseFloat(tag[p]);
         if (!isNaN(v)) {
            r = r.concat(p, "=", v, "\n");
         } else if (showNAN) {
            r = r.concat(p, "\n");
            /*v = "".concat(tag[p].toString());
            //if (0 < v.length) {
               r = r.concat("=", v, "\n");
            //}*/
         }
      } catch (e) {
      }
   }
   return r;
}

function imjs_HTMLToMiddle(tag) {
   var pos = imjs_HTMLSavePos(tag);
   tag.style.position = "relative";
   tag.style.top = "0px";
   tag.style.left = "0px";
   var ph = tag.parentNode.clientHeight;
   var th = tag.scrollHeight;
   pos.Restore();
   if (th < ph) {
      pos.y = (ph - th) / 2;
   }
   return pos;
}

/*
* Crea una immagine sfumata, da utilizzare come ombra o come riempimento.
* Si usa creando un tag IMG. Esempio:
* <img src="/javascript/Gradient.php" alt="." onload="imjs_HTMLGradient(this, '.bordoinrilievo', 'v', 'CBD0E4', '342F1B')" />
*/
function imjs_HTMLGradient(tag, findparent, type, fmcolor, tocolor) {
   if (tag.tagName == "IMG") {
      tag.style.display = "none";
      var t = imjs_HTMLFindTag(tag, findparent, null);
      if (t != null) {
         // Mi faccio richiamare quando il body è pronto
         imjs_HTMLWhenLoaded("imjs_HTMLGradient", t, new Array( tag.src, type, fmcolor, tocolor ));
      }
   } else {
      var atype = type.split(",");
      type = atype.shift().replace("v","s").replace("h","e");
      var bgpos = " ";
      var size = (
         0 < atype.length
         ? atype.shift()
         : (type == "s" || type == "n")
         ? tag.clientHeight
         : (type == "w" || type == "e")
         ? tag.clientWidth
         : "".concat(tag.clientWidth, ":", tag.clientHeight)
      );

      if (0 < atype.length) {
         bgpos = bgpos.concat(atype.shift());
      }
      var url = imjs_HTMLComposeGET(findparent, "type", type, "size", size, "fmcolor", fmcolor, "tocolor", tocolor);
      tag.style.background = "".concat("url(", url, ") repeat-", (type == "s" || type == "n" ? "x" : "y"), bgpos);
   }
}

function imjs_HTMLLocationReplace(newlocation, qstring) {
   if (newlocation.length == 0) {
      newlocation = location.href.indexOf("?");
      newlocation = location.href.substr(0, 0 < newlocation ? newlocation : location.href.length);
   }
   location.replace(0 < qstring.length ? newlocation.concat("?", qstring) : newlocation);
}

function imjs_HTTPQuery(vn, vv) {
   return vn.concat("=", vv
      .replace(/%/g,"%25")
      .replace(/&/g,"%26")
      .replace(/=/g,"%3D")
      .replace(/\r/g,"%0D")
      .replace(/\n/g,"%0A")
      .replace(/\t/g,"%09")
   );
}

/*
* Invia un POST verso una pagina web.
* Richiede un elenco di id di tags (solitamente <input/>)
* da cui recuperare i relativi valori al fine di comporre coppie nome=valore
* Restituisce un oggetto xmlhttp sincrono.
*/
function imjs_AjaxPOST(ajaxserverpage, atags) {
   if (window.XMLHttpRequest) {
      // code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp = new XMLHttpRequest();
   } else {
      // code for IE6, IE5
      xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
   }
   xmlhttp.open("POST", ajaxserverpage, false);
   xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
   // Spedisco sempre una variabile apposita
   // che informa che questa è un'operazione AJAX,
   // invece di un normale caricamento HTMl.
   var txtsend = "ajaxpost=1";
   // Preparo uno a uno tutti i valori da inviare.
   while (0 < atags.length) {
      // Prendo il prossimo valre
      var tagname = atags.shift();
      // Se il 'tagname' contiene un simbolo di '='
      // allora va copiato così com'è nella stringa del POST
      // altrimenti cerco un tag con id==tagname e ne recupero il value.
      if (tagname.indexOf("=") < 0) {
         tagname = imjs_HTMLFindTag(null, "#".concat(tagname), null);
         if (tagname != null) {
            tagname = imjs_HTTPQuery(tagname.id, tagname.value);
         }
      }
      txtsend = txtsend.concat("&", tagname);
   }
   xmlhttp.send(txtsend);
   return xmlhttp;
}

// Contiene tutti i Timer definiti dall'utente
document.imjs_Timers = new Array();
document.imjs_TimerTick = function(nTimer) {
   var Timer = document.imjs_Timers[nTimer];
   if (!Timer.paused && !Timer.ended) {
      Timer.pulses++;
      Timer.fn(Timer);
   }
}

/*
 * Classe TimerListener
 * Contiene informazioni su un singolo oggetto Listener
 */
function imjs_Timer(millis, fn) {
   this.Stop = function() {
      this.paused = true;
   };

   this.Start = function() {
      this.paused = false;
   };

   this.Kill = function() {
      this.Stop();
      this.ended = true;
      clearInterval(this.id);
      //document.imjs_Timers[this.nTimer] = null;
   };
   this.End = this.Kill;

   this.Trigger = function() {
      this.paused = !this.paused;
   };

   this.millis = millis;
   this.fn = fn;
   this.pulses = 0;
   // Tutti i TimerListener vengono creati in stato 'paused'
   this.paused = true;
   this.ended = false;

   this.nTimer = document.imjs_Timers.length;
   document.imjs_Timers.push(this);
   this.id = setInterval("".concat("document.imjs_TimerTick(", this.nTimer, ")"), millis);
}

