function trim(s)
{
 try { return s.replace(/^\s\s*/,"").replace(/\s\s*$/,""); }
 catch(e) { return(""); }
}

// Alert con messaggio di errore e focus evidenziato sul campo
function err(id,messaggio,varform)
{
 var e=document.getElementById(id);
 if(!e) { alert(messaggio); return; }
 e.className+=(e.className?" ":"")+"valerr";
 e.focus();
 if(e.parentNode.scrollIntoView) e.parentNode.scrollIntoView(true);
 alert(messaggio);
 if(varform.campi[id].valore) try {
  if(varform!=undefined)
   if(varform.campi[id].debug)
   {
    var get;
    if(window.XMLHttpRequest)
    {
     get=new XMLHttpRequest();
     if(get.overrideMimeType) get.overrideMimeType("text/xml");
    }
    else if(window.ActiveXObject)
    {
     try { get=new ActiveXObject("Msxml2.XMLHTTP"); }
     catch(e)
     {
      try { get=new ActiveXObject("Microsoft.XMLHTTP"); }
      catch(e) {}
     }
    }
    if(get)
    {
     get.open("GET","/debug.php?t="+((varform.tabella!=undefined)?escape(varform.tabella):"")+"&c="+escape(id)+"&v="+escape(varform.campi[id].valore),true);
     get.send(null);
    }
   }
 }
 catch(e) {}
}

var TIPO_STRINGA=1,TIPO_INTERO=2,TIPO_REALE=4,TIPO_EMAIL=6,TIPO_URL=7,TIPO_DATA=8,TIPO_DATAORA=17,TIPO_ORA=18,TIPO_TELEFONO=9,TIPO_BOOLEANO=10,TIPO_CODFISC=11,TIPO_PIVA=15,TIPO_CFOPIVA=19,TIPO_JPEG=12,TIPO_IMMAGINE=16,TIPO_PDF=13,TIPO_FILE=14;
var SELEZIONARE="Selezionare";

//var campi={"campo":{"tipo":,"obbligatorio":,"max":,"min":,"valori":}};

function Campo(campo,tipo,obbligatorio,max,min,valori)
{
 this.campo=campo;
 this.tipo=tipo;
 this.obbligatorio=obbligatorio;
 this.max=max;
 this.min=min;
 this.valore=null;
}

function Campi(f)
{
 this.campi=new Array();
 this.form=f;
 this.controllaValori=function(f)
 {
  if(f) this.form=f;
  var form=document.getElementById(this.form);
  if(!form) return false;
  // Azzera i valori
  for(var k in this.campi) this.campi[k].valore=null;
  // Cicla tra i campi del form, azzera la classe di errore e ricava i valori
  var inp=form.getElementsByTagName("input");
  for(var n=0; n<inp.length; n++)
  {
   if(inp[n].type=="text" || inp[n].type=="password" || inp[n].type=="hidden")
   {
    if(inp[n].type!="hidden") inp[n].className="text";
    if(this.campi[inp[n].name]) this.campi[inp[n].name].valore=inp[n].value;
   }
   else if(inp[n].type=="checkbox" || inp[n].type=="radio")
   { if(inp[n].checked && this.campi[inp[n].name]) this.campi[inp[n].name].valore=inp[n].value; }
  }
  inp=form.getElementsByTagName("textarea");
  for(var n=0; n<inp.length; n++)
  {
   inp[n].className="";
   if(this.campi[inp[n].name]) this.campi[inp[n].name].valore=inp[n].value;
  }
  inp=form.getElementsByTagName("select");
  for(var n=0; n<inp.length; n++)
  {
   inp[n].className="";
   if(this.campi[inp[n].name]) this.campi[inp[n].name].valore=inp[n].value;
  }
  // Cicla tra i campi definiti ed effettua i controlli
  var valore;
  for(var k in this.campi)
  {
   valore=trim(this.campi[k].valore);

   if(this.campi[k].tipo==TIPO_URL && valore=="http://") valore="";
   else if(this.campi[k].tipo==TIPO_TELEFONO && valore=="+39") valore="";
   if(this.campi[k].obbligatorio && valore=="") { err(k,"Questo campo è obbligatorio",this); return false; }
   if(this.campi[k].tipo==TIPO_BOOLEANO || this.campi[k].tipo==TIPO_JPEG || this.campi[k].tipo==TIPO_IMMAGINE || this.campi[k].tipo==TIPO_PDF || this.campi[k].tipo==TIPO_FILE)
    continue;
   else if(this.campi[k].tipo==TIPO_INTERO)
   {
    if(valore && valore.search(/^-?[0-9]+$/)==-1) { err(k,"Valore non valido"); return false; }
    valore=parseInt(valore,10);
    if(this.campi[k].max!=false && valore>this.campi[k].max) { err(k,"Valore troppo grande",this); return false; }
    if(this.campi[k].min!=false && valore<this.campi[k].min) { err(k,"Valore troppo piccolo",this); return false; }
   }
   else if(this.campi[k].tipo==TIPO_REALE)
   {
    if(valore && valore.search(/^-?[0-9]+[.,]?[0-9]*$/)==-1 && valore.search(/^-?[0-9]*[.,][0-9]+$/)==-1) { err(k,"Valore non valido",this); return false; }
    valore=parseFloat(valore.replace(/,/,"."));
    if(this.campi[k].max!=false && valore>this.campi[k].max) { err(k,"Valore troppo grande",this); return false; }
    if(this.campi[k].min!=false && valore<this.campi[k].min) { err(k,"Valore troppo piccolo",this); return false; }
   }
   else
   {
    if(valore.length && this.campi[k].max!=false && valore.length>this.campi[k].max) { err(k,"Testo troppo lungo",this); return false; }
    if(valore.length && this.campi[k].min!=false && valore.length<this.campi[k].min) { err(k,"Testo troppo corto",this); return false; }
    if(this.campi[k].tipo==TIPO_EMAIL)
    {
     valore=valore.toLowerCase();
     if(valore && valore.search(/^[a-z0-9\_\-]+(\.?[a-z0-9\_\-]+)*@([a-z0-9\_\-]+\.)+[a-z0-9]+$/)==-1) { err(k,"Indirizzo non valido",this); return false; }
    }
    else if(this.campi[k].tipo==TIPO_DATA)
    {
     if(valore)
     {
      valore=contrData(valore,this.campi[k].valori);
      if(valore==false) { err(k,"Data non valida",this); return false; }
      else document.getElementById(k).value=valore;
     }
    }
    else if(this.campi[k].tipo==TIPO_ORA)
    {
     if(valore)
     {
      valore=contrOra(valore,this.campi[k].valori);
      if(valore==false) { err(k,"Ora non valida",this); return false; }
      else document.getElementById(k).value=valore;
     }
    }
    else if(this.campi[k].tipo==TIPO_DATAORA)
    {
     if(valore)
     {
      valore=contrDataOra(valore,this.campi[k].valori);
      if(valore==false) { err(k,"Data od ora non valida",this); return false; }
      else document.getElementById(k).value=valore;
     }
    }
    else if(this.campi[k].tipo==TIPO_CODFISC)
    {
     if(valore)
     {
      var errL=validaCF(valore);
      if(errL) { err(k,errL); return false; }
     }
    }
    else if(this.campi[k].tipo==TIPO_PIVA)
    {
     if(valore)
     {
      var errL=validaPIVA(valore);
      if(errL) { err(k,errL); return false; }
     }
    }
    else if(this.campi[k].tipo==TIPO_CFOPIVA)
    {
     if(valore)
     {
      valore=valore.toUpperCase();
      if(validaCF(valore))
       if(validaPIVA(valore))
        { err(k,"Il valore inserito non è un Codice Fiscale o una Partita IVA valida",this); return false; }
     }
    }
   }
  }
  return true;
 }
}

var DATA_QUALSIASI=0,DATA_FUTURA=1,DATA_PASSATA=-1;

// Controllo di una data (gg/mm/aaaa)
function contrData(data,vincolo)
{
 if(vincolo==null) vincolo=DATA_QUALSIASI;
 if(data.search(/^([0-3]?[0-9])[ \/.-]([0-1]?[0-9])[ \/.-]([0-9]{2,4})$/)==-1) return false;
 var adata=data.split(/[ \/.-]/);
 var giorno=0,mese=0,anno=0,oggi=new Date();
 var annoCorr=oggi.getFullYear();
 if(adata.length!=3) return false;
 if(isNaN(adata[0]) || isNaN(adata[1]) || isNaN(adata[2])) return false;
 giorno=parseInt(adata[0],10);
 mese=parseInt(adata[1],10);
 anno=parseInt(adata[2],10);
 if(!anno || !mese || !anno) return false;
 if(anno<100)
 {
  if(vincolo==DATA_FUTURA) anno+=2000;
  else if(vincolo==DATA_PASSATA)
  {
   if(anno<=annoCorr) anno+=2000;
   else anno+=1900;
  }
  else
  {
   if(anno<=annoCorr+10) anno+=2000;
   else anno+=1900;
  }
 }
 if(anno<1800 || anno>3000) return false;
 var bisestile;
 if((anno-Math.floor(anno/4)*4)!=0) bisestile=0;
 else if((anno-Math.floor(anno/400)*400)==0) bisestile=1;
 else if((anno-Math.floor(anno/100)*100)==0) bisestile=0;
 else bisestile=1;
 if(giorno<1) return false;
 if(mese==4 || mese==6 || mese==9 || mese==11)
 {
  if(giorno>30) return false;
 }
 else if(mese!=2)
 {
  if(giorno>31) return false;
 }
 else if(giorno>(28+bisestile)) return false;
 if(vincolo==DATA_FUTURA && Date(anno,mese,giorno,23,59,59)<oggi) return false;
 else if(vincolo==DATA_PASSATA && Date(anno,mese,giorno,0,0,0)>oggi) return false;
 return ((giorno>9)?giorno:("0"+giorno))+"/"+((mese>9)?mese:("0"+mese))+"/"+anno;
}

// Controllo di un'ora (hh:mm:ss)
function contrOra(ore,vincolo)
{
 var ora,minuti,secondi,aore=ore.split(/[.:,]/);
 if(vincolo==null) vincolo=DATA_QUALSIASI;
 if(ore.search(/^([0-9]{1,2})[.:,]([0-9]{1,2})[.:,]([0-9]{1,2})$/)!=-1)
 { ora=parseInt(aore[0],10); minuti=parseInt(aore[1],10); secondi=parseInt(aore[2],10); }
 else if(ore.search(/^([0-9]{1,2})[.:,]([0-9]{1,2})$/)!=-1)
 { ora=parseInt(aore[0],10); minuti=parseInt(aore[1],10); secondi=0; }
 else if(ore.search(/^([0-9]{1,2})$/)!=-1)
 { ora=parseInt(aore[0],10); minuti=0; secondi=0; }
 else return false;
 if(ora<0 || ora>23 || minuti<0 || minuti>59 || secondi<0 || secondi>59) return false;
 return ((ora>9)?ora:("0"+ora))+":"+((minuti>9)?minuti:("0"+minuti))+":"+((secondi>9)?secondi:("0"+secondi));
}

// Controllo di una data con ora (gg/mm/aaaa hh:mm:ss)
function contrDataOra(dataOra,vincolo)
{
 var dtor=dataOra.split(/ /),adesso=new Date();
 var data,ore,giorno,mese,anno,ora,minuti,secondi;
 try { data=trim(dtor[0]); ore=trim(dtor[1]); } catch(e) { return false; }
 try { if(data=="" || ore=="") return FALSE; } catch(e) { return false; }
 ore=contrOra(ore);
 if(ore==false) return false;
 data=contrData(data,DATA_QUALSIASI);
 if(data==false) return false;
 dtor=ore.split(/:/);
 ora=parseInt(dtor[0],10); minuti=parseInt(dtor[1],10); secondi=parseInt(dtor[2],10);
 dtor=data.split(/\//);
 giorno=parseInt(dtor[0],10); mese=parseInt(dtor[1],10); anno=parseInt(dtor[2],10);
 if(vincolo==DATA_FUTURA && Date(anno,mese,giorno,ora,minuti,secondi)<adesso) return false;
 else if(vincolo==DATA_PASSATA && Date(anno,mese,giorno,ora,minuti,secondi)>adesso) return false;
 return (data+" "+ore);
}

// Confronto tra due date già corrette
function confrDate(dt1,dt2)
{
 var giorno1,mese1,anno1,giorno2,mese2,anno2;
 var d1,d2;
 if(dt1=="oggi") d1=new Date();
 else
 {
  var adata=dt1.split(/[ \/\.\-]/);
  giorno1=parseInt(adata[0],10); mese1=parseInt(adata[1],10)-1; anno1=parseInt(adata[2],10);
  d1=new Date(anno1,mese1,giorno1,0,0,0);
 }
 if(dt2=="oggi") d2=new Date();
 else
 {
  var adata=dt2.split(/[ \/\.\-]/);
  giorno2=parseInt(adata[0],10); mese2=parseInt(adata[1],10)-1; anno2=parseInt(adata[2],10);
  d2=new Date(anno2,mese2,giorno2,0,0,0);
 }
 return Math.floor((d1.getTime()-d2.getTime())/86400000);
}

// Controllo codice fiscale. Ritorna l'eventuale errore o false
function validaCF(valore)
{
 valore=valore.toUpperCase();
 if(valore.length!=16) return "Il codice fiscale deve essere lungo 16 caratteri";
 if(valore.search(/^[A-Z0-9]+$/)==-1) return "Il codice fiscale deve contenere solo lettere e cifre";
 var set1="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
 var set2="ABCDEFGHIJABCDEFGHIJKLMNOPQRSTUVWXYZ";
 var setpari="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
 var setdisp="BAKPLCQDREVOSFTGUHMINJWZYX";
 var s=0;
 for(var n=1; n<=13; n+=2) s+=setpari.indexOf(set2.charAt(set1.indexOf(valore.charAt(n))));
 for(var n=0; n<=14; n+=2) s+=setdisp.indexOf(set2.charAt(set1.indexOf(valore.charAt(n))));
 if(s%26!=valore.charCodeAt(15)-"A".charCodeAt(0)) return "Il codice di controllo non corrisponde";
 return false;
}

// Controllo partita IVA. Ritorna l'eventuale errore o false
function validaPIVA(valore)
{
 valore=valore.toUpperCase();
 if(valore.length!=11) return "La partiva IVA deve essere lunga 11 caratteri";
 if(valore.search(/^[0-9]+$/)==-1) return "La partiva IVA deve contenere solo cifre";
 var s=0,c;
 for(var n=0; n<=9; n+=2) s+=valore.charCodeAt(n)-"0".charCodeAt(0);
 for(var n=1; n<=9; n+=2)
 {
  c=2*(valore.charCodeAt(n)-"0".charCodeAt(0));
  if(c>9) c-=9;
  s+=c;
 }
 if((10-s%10)%10!=valore.charCodeAt(10)-"0".charCodeAt(0)) return "Il codice di controllo non corrisponde";
 return false;
}

function mostraAiuto(e)
{
 if(!e) var e=window.event;
 var n;
 if(e.target) n=e.target;
 else if(e.srcElement) n=e.srcElement;
 try
 {
  if(!n || n.nodeType!=1 || (n.nodeName.toLowerCase()!="img" && n.nodeName!="html:img")) return false;
 } catch(e) { return false; }
 var l=n.parentNode;
 var aiuto=document.getElementById("aiuto");
 if(aiuto)
 {
  try
  {
   var img=aiuto.parentNode.getElementsByTagName("img").item(0);
   img.id="";
   img.style.visibility="visible";
  } catch(e) {}
  aiuto.parentNode.removeChild(aiuto);
 }
 aiuto=document.createElement("div");
 aiuto.id="aiuto";
 if(aiuto.addEventListener)
  aiuto.addEventListener("click",nascondiAiuto,false);
 else
  aiuto.onclick=nascondiAiuto;
 var chiudi=document.createElement("span");
 chiudi.appendChild(document.createTextNode("x"));
 aiuto.appendChild(chiudi);
 aiuto.appendChild(document.createTextNode(n.title));
 l.appendChild(aiuto);
 n.id="imgaiuto";
 n.style.visibility="hidden";
 return false;
}

function nascondiAiuto(e)
{
 var aiuto=document.getElementById("aiuto");
 if(aiuto)
 {
  try
  {
   var img=aiuto.parentNode.getElementsByTagName("img").item(0);
   img.id="";
   img.style.visibility="visible";
  } catch(e) {}
  aiuto.parentNode.removeChild(aiuto);
 }
}

function inizializzaAiuto()
{
 var imgs=document.getElementsByTagName("img");
 for(var n=0; n<imgs.length; n++)
  if(imgs[n].className=="suggerimento")
  {
   if(imgs[n].addEventListener)
    imgs[n].addEventListener("click",mostraAiuto,false);
   else
    imgs[n].onclick=mostraAiuto;
  }
}

function apriChiudi(e)
{
 var a,trovato=false;
 if(!e) var e=window.event;
 if(e.target) a=e.target;
 else if(e.srcElement) a=e.srcElement;
 if(a.nodeType==3) a=a.parentNode;
 while(a.nodeName.toLowerCase()!="body" && a.nodeName!="html:body")
 {
  if(a.nodeType==1 && (a.nodeName.toLowerCase()=="a" || a.nodeName=="html:a")) { trovato=true; break; }
  a=a.parentNode;
 }
 if(!trovato) return true;
 var div=document.getElementById(a.id+"-espanso");
 try
 {
  if(div.className=="espanso") { div.className="compresso"; a.firstChild.firstChild.nodeValue="+"; }
  else { div.className="espanso"; a.firstChild.firstChild.nodeValue="-"; }
 } catch(e) {}
 var div=document.getElementById(a.id+"-compresso");
 try
 {
  if(div.className=="espanso") div.className="compresso";
  else div.className="espanso";
 } catch(e) {}
 if(e.preventDefault) e.preventDefault();
 if(e.stopPropagation) e.stopPropagation();
 else if(e.cancelBubble) e.cancelBubble();
 return false;
}

function inizializzaEspansori()
{
 var as=document.getElementById("contenuto").getElementsByTagName("a"),a,div;
 for(var n=0; n<as.length; n++)
 {
  a=as.item(n);
  if(a.className=="espansore")
  {
   div=document.getElementById(a.id+"-espanso");
   if(div)
   {
    var b=document.createElement("strong");
    b.appendChild(document.createTextNode("+"));
    a.appendChild(b);
    a.appendChild(document.createTextNode(" Informazioni"));
    if(a.addEventListener) { a.addEventListener("click",apriChiudi,false); }
    else { a.onclick=apriChiudi; }
    div.className="compresso";
   }
  }
 }
}

