/**
 * Restituisce true se il campo ? un'email
 */
function Is_Email(sDato) {
 	if (sDato != "") {
	  var s = sDato;
	  var localPartfilter1 = /^[^<>()\[\]\x5C.,;:@" ]+(\.[^<>()\[\]\x5C.,;:@" ]+)*@$/;
	  var localPartfilter2 = /^"[^\r\n]+"@$/;
	  var domainfilter = /^([a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9]|[a-zA-Z0-9])(\.([a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9]|[a-zA-Z0-9]))(\.([a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9]|[a-zA-Z0-9]))*$/;
	  var sepPos = 0;
	  var localPart;
	  var domain;
	  var localPartOk = false;
	  var domainOk    = false;
	  sepPos = s.lastIndexOf("@");
	  localPart = s.substring(0,sepPos+1);
	  domain    = s.substring(sepPos+1,s.length);
	  if  (localPartfilter1.test(localPart))
	    localPartOk = true;
	  else if (localPartfilter2.test(localPart))
	    localPartOk = true;
	  else
	    localPartOk = false;
	  if (domainfilter.test(domain))
	    domainOk = true;
	  else
	    domainOk = false;

	  if (localPartOk != true || domainOk != true)
	    return false;
  }

  return true;
}

/**
 * Testa se la stringa passata ? un URL
 */
function Is_URL(theUrl){
  if(theUrl != "") {
	  var j = new RegExp();
	  j.compile("^[A-Za-z]+://[A-Za-z0-9-]+\.[A-Za-z0-9]+");
	  if (!j.test(theUrl))
	    return false;
	}

  return true;
}

/**
 * Restituisce true se il combo box ? selezionato.
 */
function Is_Select(theSel){
  if(theSel.options[theSel.selectedIndex].value == "")
	  return false
	return true;
}

// La funzione seleziona tutte le opzioni
// di una select multipla
// Da invocare prima del submit altrimenti
// non vengono passate le option contenute
function seleziona(theSel) {
  for (i=0; i<theSel.options.length; i++)
    theSel.options[i].selected=true;
}

/**
 * Converte una stringa passata nel formato dd/mm/yyyy
 * in una stringa nel formato yyyymmdd
 */
function toTimestamp_f(aDate){
  if(aDate.length < 10) return "";

  return aDate.substring(6,10)+aDate.substring(3,5)+aDate.substring(0,2);
}

/**
 * Versione lasca della precedente. Formati accettati:
 *  - ddmmyyyy
 *  - dd$mm$yyyy, dove $ ? un qualsiasi carattere.
 */
function toTimestamp(aDate){
  if((aDate.length != 8)&&(aDate.length != 10)) return "";

  if(aDate.length == 8)
    return aDate.substr(4,4)+aDate.substr(2,2)+aDate.substring(0,2);
  else
    return aDate.substring(6,10)+aDate.substring(3,5)+aDate.substring(0,2);
}

/**
 * Converte una stringa passata nel formato yyyymmdd
 * in una stringa nel formato dd/mm/yyyy
 */
function toDate(aTs){
  if(aTs.length < 8) return "";

  return aTs.substring(6,8)+"/"+aTs.substring(4,6)+"/"+aTs.substring(0,4);
}

function checkReal(elem){
  ok = true;
  elem.value = elem.value.replace(/\,/g,".");
  if((elem.value != "")&&(parseFloat(elem.value) != elem.value)) {
    ok = false;
  }
  elem.value = elem.value.replace(/\./g,",");
  return ok;
}

/**
 * Controlla che l'elemento sia della forma dd/mm/yyyy
 */
function Is_Date_f(theElement) {
  var DayArray =new Array(31,28,31,30,31,30,31,31,30,31,30,31);
  var MonthArray = new Array("01","02","03","04","05","06","07","08","09","10","11","12");
  var thisYear = null;
  var thisMon = null;
  var thisDay = null;
  var today = null;
  inpDate = theElement;
  if (inpDate.length == 0 )
    return true;
  thisDay = inpDate.substr(0,2);
  thisMonth = inpDate.substr(3,2);
  thisYear = inpDate.substr(6,4);
  var filter=/^[0-9]{2}\/[0-9]{2}\/[0-9]{4}$/;
  if (! filter.test(inpDate))
    return false;
  var filter=/01|02|03|04|05|06|07|08|09|10|11|12/ ;
  if (! filter.test(thisMonth))
    return false;
  N=Number(thisYear);
  if ( ( N%4==0 && N%100 !=0 ) || ( N%400==0 ) )
    DayArray[1]=29;
  for(var ctr=0; ctr<=11; ctr++){
    if (MonthArray[ctr]==thisMonth){
      if (thisDay<= DayArray[ctr] && thisDay >0 )
        return true;
      else
        return true;
    }
  }
  return true;
}

/**
 * Questa ? una versione un po' pi? lasca della precedente
 * nel senso che permette di inserire date nei formati
 *  - ddmmyyyy
 *  - dd$mm$yyyy, dove $ ? un qualsiasi carattere.
 */
function Is_Date(theElement) {
  var DayArray =new Array(31,28,31,30,31,30,31,31,30,31,30,31);
  var thisYear = null;
  var thisMon = null;
  var thisDay = null;
  var today = null;
  inpDate = theElement;

  if(inpDate.length == 8) {
    thisDay = inpDate.substr(0,2);
    thisMonth = inpDate.substr(2,2);
    thisYear = inpDate.substr(4,4);
  } else if(inpDate.length == 10) {
    thisDay = inpDate.substr(0,2);
    thisMonth = inpDate.substr(3,2);
    thisYear = inpDate.substr(6,4);
  } else if (inpDate.length == 0 ) {
    return true;
  } else  {
    return false;
  }

  var filter=/01|02|03|04|05|06|07|08|09|10|11|12/ ;
  if (! filter.test(thisMonth))
    return false;
  N=Number(thisYear);
  if ( ( N%4==0 && N%100 !=0 ) || ( N%400==0 ) )
    DayArray[1]=29;

  M=Number(thisMonth);
  if (thisDay<=DayArray[(M-1)] && thisDay >0 )
    return true;
  else
    return false;
}

/*
 * Testa se il campo di tipo Orario
 * ? della forma h[h][:mm] (formato ISO 8601)
 */
function Is_Time(sTime) {
  return /^([01]?[0-9]|[2][0-3])(:[0-5][0-9])?$/.test(sTime);
}

/*
 * Data una stringa validata con Is_Time,
 * la ritorna paddata nella forma hh:mm
 */
function padTime(sTime){
	// controllo se esiste il separatore
 	if(sTime.indexOf(':')==-1){
 	  if(sTime.length<2)
 	    return "0"+sTime+":00";
 	  else
 	    return sTime+":00";
 	} else {
 	  ss=sTime.split(':');
 	  if(ss[0].length<2)
 	    return "0"+ss[0]+":"+ss[1];
 	  else
 	    return sTime;
 	}
}

function Is_CAP(theCap){
  if((parseInt(theCap.value) != theCap.value)&&(theCap.value.length!=5))
    return false;
  return true;
}

function Is_PIVA(sDato) {
	if(sDato.length !=11)
		return false;

	SOMMADISPARI=0;
	SOMMAPARI=0;

	for (i=0;i<9;i+=2)
	{
    SOMMADISPARI+=sDato.substr(i,1)-'0';
		DIVQ=parseInt((2*(sDato.substr(i+1,1))-'0')/10,10);
		DIVR=(2*(sDato.substr(i+1,1)-'0') % 10);
		SOMMAPARI+= (DIVQ + DIVR);
	}
	SOMMACTR=SOMMADISPARI+SOMMAPARI;
	DIVI= ((10-(SOMMACTR % 10)) % 10);
	if ((sDato.substr(10,1)-'0')==DIVI)
	  return true;
	else
	  return false;
}

function Is_FiscalCode(sDato) {

	if (sDato.length !=16)
		return false;
	sDato=sDato.toUpperCase();
	iChecksum=0;
	iPos=-1;
	iSum=0;
	bPari=true;
	sCaratteri = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
	sCodiciPari= "000102030405060708091011121314151617181920212223242500010203040506070809";
	sCodiciDispari="010005070913151719210204182011030608121416102225242301000507091315171921";
	for (iloop=0; iloop<16; iloop++)
	{
	  sCheck=sDato.substr(iloop,1);
	  iPos=((sCaratteri.indexOf(sCheck)+1)*2)-1;
 	  if ( (iloop%2) != 0)
 	  {
	  	iSum = parseInt(sCodiciPari.substr(iPos-1,2),10);
	 		//alert(iPos + ' ' + iSum);
	  }
	  else
	  {
			iSum = parseInt(sCodiciDispari.substr(iPos-1,2),10);
 			//alert(iPos + ' ' + iSum);
 	  }
	  if (iloop != 15)
			iChecksum = iChecksum +	iSum;
	}
	//alert(iSum + ' ' + (iChecksum % 26));
	if ((iChecksum % 26) !=	iSum)
		return false;
	else
		return true;
}

/**
 * nella forma dd/mm/yyyy
 */
function getToday(){
  oggi = new Date();
  gg  = oggi.getDate();
  mm = oggi.getMonth() + 1;
  aa = oggi.getFullYear();

  if(gg<10)
    gg="0"+gg;
  if(mm<10)
    mm="0"+mm;

  return gg+"/"+mm+"/"+aa;
}

/**
 * nella forma hh:mm
 */
function getTime() {
	data_ora=new Date();
	hh=data_ora.getHours();
	min=data_ora.getMinutes();
	if (hh<10)
		hh="0"+hh;
	if (min<10)
		min="0"+min;

	return hh+":"+min;
}

/**
 * Traking
 */
function str_tra(ogg, theForm) {
	if (theForm.id.value != "") {
		str=theForm.track.value;
		if(str.search(ogg) < 0){
			theForm.track.value=theForm.track.value+ogg+" - ";
		}
	}
}

/**
 *
 *  str         --> stringa (This is a test of the JavaScript RegExp object)
 *  regex       --> espressione regolare (es \bt[a-z]+\b)
 *  replacement --> stringa da sostituire (es replaced)
 *
 *  risultato   --> This is a replaced of replaced JavaScript RegExp object
 */
function replace(str, regex, replacement){
  var re = new RegExp(regex);
  return str.replace(re, replacement);
}

/**
 * Testa se il valore passato ? un numero
 */
function IsNumeric(sText) {
  var ValidChars = "0123456789";
  var IsNumber=true;
  var Char;

  for (jj = 0; jj < sText.length && IsNumber == true; jj++) {
	  Char = sText.charAt(jj);
	  if (ValidChars.indexOf(Char) == -1) {
	  	IsNumber = false;
	  }
  }
  return IsNumber;
}

/**
 * Collassa sezione
 */
function nascondi_sez(id_sezione, path_base){
	obj=document.getElementById("sez_r"+id_sezione);
	if(obj){
		objIMG=document.getElementById("sez_img"+id_sezione);
		if (obj.style.display=="none"){
			objIMG.src=path_base+"/images/minus.jpg";
			obj.style.display="";
		}else{
			objIMG.src=path_base+"/images/add.jpg";
			obj.style.display="none";
		}
	}
}

function sezione(id_sezione){
	obj=document.getElementById(id_sezione);
	if(obj){
		if (obj.style.display=="none"){
			obj.style.display="";
		}else{
			obj.style.display="none";
		}
	}
}

function myO(who, hStr) {
	var mObj=document.getElementById(who);
	var fileName=mObj.src;
	var pos=fileName.lastIndexOf(".");
	var ext=fileName.substring(pos);
	var radix=fileName.substring(0, pos);

	if(radix.indexOf(hStr)==-1)
		mObj.src=radix+hStr+ext;
	else
		mObj.src=radix.substring(0, radix.length-hStr.length)+ext;
}

/**
 * calendario
 */
function initCal() {
  calendario = new CalendarPopup();
  calendario.showYearNavigation();
  calendario.setMonthNames("Gennaio","Febbraio","Marzo","Aprile","Maggio","Giugno","Luglio","Agosto","Settembre","Ottobre","Novembre","Dicembre");
  calendario.setWeekStartDay(1);
  calendario.setDayHeaders("D","L","M","M","G","V","S");
  calendario.setTodayText("Oggi");
  calendario.showYearNavigationInput();
}

/**
 * Dichiara la funzione da chiamare alla selezione della data
 * La funzione è onChangeCal()
 */
function initCalFun() {
  calendario = new CalendarPopup();
  calendario.showYearNavigation();
  calendario.setMonthNames("Gennaio","Febbraio","Marzo","Aprile","Maggio","Giugno","Luglio","Agosto","Settembre","Ottobre","Novembre","Dicembre");
  calendario.setWeekStartDay(1);
  calendario.setDayHeaders("D","L","M","M","G","V","S");
  calendario.setTodayText("Oggi");
  calendario.showYearNavigationInput();
  calendario.setReturnFunction('onChangeCal');
}

/**
 * id_dt --> id del campo data
 * anch --> anchor name del calendario associato
 */
function openCal(id_dt, anch){
  var oo = document.getElementById(id_dt);
  if(oo)
    calendario.select(oo,anch,'dd/MM/yyyy');
}

/**
 * analoga del php
 */
function isset(varname)  {
	if(typeof( window[ varname ] ) != "undefined") return true;
	else return false;
}

function gI(who) {
	return document.getElementById(who);
}

//funzione per controllare se viene cliccato più volte il pulsante
//deve essere presente nella pagina una funzione chiamata checkForm() che fa il controllo se serve
//e ritorna 1 se tutto va bene o 0 se c'è qualcosa che non va.
//come parametro vuole:
//form : oggetto form a cui fare la submit
//bypassCTRL: può essere non passato, se settato a 1 viene bypassata la funzione checkForm()
//
// Nota. Fa uso della fDelay definita nel top
function submitOnce(form, bypassCTRL){
	if (!isset("checkAttivo")){
		checkAttivo=1;
	}

	if (checkAttivo) {
		checkAttivo=0;
		var check=bypassCTRL || checkForm();
		if (check){
			fDelay(form);
		}else{
			checkAttivo=1;
		}
	}else{
		alert ("Attenzione!\nAvete già cliccato il comando. Attendere prego!");
	}
}

function fDelay(obj) {
	var tname=obj.tagName;
	if(tname=='FORM')
		obj.submit();
	else if(tname=='A')
		location.href=obj.href;
}

/**
 * Apre una popup centrata
 *
 * @param nome			url da caricare
 * @param titolo		titolo della finestra
 * @param lar 			larghezza
 * @param alt 			altezza
 * @param feat 			opzioni
 */
function apriPopupCentrata(nome, titolo, lar, alt, feat){
	var wdt = screen.width;
	var hgt = screen.height;
	var x = Math.round( (wdt / 2) - (lar / 2) );
	var y = Math.round( (hgt / 2) - (alt / 2) );
	window.open(nome, titolo, 'width=' + lar + ',height=' + alt + ',left=' + x + ',screenX=' + x + ',top=' + y + ',screenY=' + y + ',' + feat);
}




function apriInElement (id, url, options) {
	//id:id_div da modificare
	//url:url da richiamare
	if (!options) {
		options={};
	}
	options["method"]="get";
	options["update"]=$(id);
	options["evalScripts"]=true;

	new Ajax(url, options).request();
}



/**
 * Find Position
 */
function findX(obj){
	var curleft = 0;
	if (obj.offsetParent) {
		while (obj.offsetParent) {
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	} else if (obj.x) {
		curleft += obj.x;
	}
	return curleft;
}

function findY(obj) {
	var curtop = 0;
	if (obj.offsetParent) {
		while (obj.offsetParent) {
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	} else if (obj.y) {
		curtop += obj.y;
	}
	return curtop;
}


// funzioni Utils::customInput
function selectChoice(options){
	if (options.obj){
		var obj=$(options.obj);
		var imgChoice=obj.getFirst();
	}
	var inputChoice=eval("document."+options.form_name+"."+options.hidden);

	if (imgChoice){
		if (imgChoice.get("valueImg")==inputChoice.value){
			inputChoice.value="";
		}else{
			inputChoice.value=imgChoice.get("valueImg");
		}
	}else if (options.value){
		inputChoice.value=options.value;
	}

	if (options.group && options.group!=""){
		var elems=$$("."+options.group);

		var i=0;
		while (i<elems.length){
			if (elems[i].get("valueImg")!=inputChoice.value){
				elems[i].set("src", elems[i].get("srcStandard"));
			}else {
				if (elems[i].get("srcSelected") && elems[i].get("srcSelected")!="") {
					elems[i].set("src", elems[i].get("srcSelected"));
				}else{
					elems[i].set("src", elems[i].get("srcActive"));
				}
			}
			i++;
		}
	}
	if (options.onchange){
		eval(options.onchange);
	}
	return false;
}


function overChoice(options){
	if (options.obj){
		var obj=$(options.obj);
		var imgChoice=obj.getFirst();
		imgChoice.set("src", imgChoice.get("srcActive"));
	}
	return false;
}
function outChoice(options){
	if (options.obj){
		var obj=$(options.obj);
		var imgChoice=obj.getFirst();
		var inputChoice=eval("document."+options.form_name+"."+options.hidden);


		if (inputChoice.value!=imgChoice.get("valueImg")){
			imgChoice.set("src", imgChoice.get("srcStandard"));
		}else{
			if (imgChoice.get("srcSelected") && imgChoice.get("srcSelected")!="") {
				imgChoice.set("src", imgChoice.get("srcSelected"));
			}else{
				imgChoice.set("src", imgChoice.get("srcActive"));
			}
		}
	}
	return false;
}

function correctPNG(){
	if((navigator.userAgent.indexOf("MSIE") > 0) && (navigator.userAgent.indexOf("MSIE 7.0") == -1)) {
   	for(var i=0; i<document.images.length; i++){
      var img = document.images[i]
      var imgName = img.src.toUpperCase()
      if (imgName.substring(imgName.length-3, imgName.length) == "PNG"){
         var imgID = (img.id) ? "id='" + img.id + "' " : ""
         var imgClass = (img.className) ? "class='" + img.className + "' " : ""
         var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
         var imgStyle = "display:inline-block;" + img.style.cssText
         if (img.align == "left") imgStyle = "float:left;" + imgStyle
         if (img.align == "right") imgStyle = "float:right;" + imgStyle
         // if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle
         var strNewHTML = "<span " + imgID + imgClass + imgTitle
         + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
         + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
         + "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>"
         img.outerHTML = strNewHTML
         i = i-1
        }
     }
   }
 }

/**
 * Form-specific
 */
function checkEnter(e) {
	var charCode = (navigator.appName == "Netscape") ? e.which : e.keyCode
	// status = charCode // see ASCII character value!
	if (charCode != 13) return false
	else return true
}



function scrolPosition(){
	var ScrollTop = document.body.scrollTop;

	if (ScrollTop == 0) {
		if (window.pageYOffset)
			ScrollTop = window.pageYOffset;
		else
			ScrollTop = (document.body.parentElement) ? document.body.parentElement.scrollTop : 0;
	}
	return ScrollTop;
}

/**************************************************************************************
** 
**	FINE Funzioni per pulsanti custom 
** 
*/
function apriScheda(url){
	
	var elemOscuro=new Element("div", {
	    'id': "opacizza",
	    events: {'click': chiudiTesto }
	});
	elemOscuro.inject("corpo", 'top');
	
	var elemContenitore=new Element("div", {
    "id": "contenitore_opacizzato"
	});
	elemContenitore.style.height="0px";
	elemContenitore.style.top="0px";
	elemContenitore.style.top=(scrolPosition())+"px";
	elemContenitore.inject("corpo", "top");
	elemContenitore.addClass("loading");
	
	
	elemX=new Element("div", {
    "id": "contenitore_opacizzato_chiusura",
    events: {'click': chiudiTesto }
	});
	elemX.set("html", "X");
	
	var options={};
	options["method"]="get";
	options["update"]=elemContenitore;
	options["onComplete"]=function(){elemContenitore.removeClass("loading");elemX.inject($("contenitore_opacizzato"), "bottom"); (function(){$("contenitore_opacizzato").tween('height', $$("#contenitore_opacizzato")[0].getFirst().getSize().y )}).delay(0); } ;
	options["evalScripts"]=true;
	options["url"]=url;

	new Request.HTML(options).send();
	
	return false;
}


function chiudiTesto(){
	if( $("opacizza") )$("opacizza").destroy();
	if( $("contenitore_opacizzato") )$("contenitore_opacizzato").destroy();
}






function apri(url, div){
	var options={};
	options["method"]="get";
	options["update"]=div;
	options["evalScripts"]=true;
	options["url"]=url;

	new Request.HTML(options).send();

}

Number.prototype.toFixedR= function(n){
	  var N= this;
	  N= Math.round(N*Math.pow(10,n));
	  N/=Math.pow(10,n);
	  return(N.toFixed(n));
	 }