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
}

/**
 * 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);
}

 /**
  * Ritorna una stringa in formato dd/mm/yyyy hh:ii:ss
  *
  * @param aDate		oggetto Date
  * @return
 */
function stringDateExt(aDate){
 	var dd=aDate.getDate();
 	if(dd<10)
 		dd="0"+dd;
 	var mm=(aDate.getMonth()+1);
 	if(mm<10)
 		mm="0"+mm;

 	hh=aDate.getHours();
 	min=aDate.getMinutes();
 	sec=aDate.getSeconds()
 	if (hh<10)
 		hh="0"+hh;
 	if (min<10)
 		min="0"+min;
 	if (sec<10)
 		sec="0"+sec;

 	return dd+"/"+mm+"/"+aDate.getFullYear()+" "+hh+":"+min+":"+sec;
}

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 yyyy
 */
function getYear(){
  oggi = new Date();
  aa = oggi.getFullYear();
  return 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;
}

/**
 * nella forma dd-mm-yyyy hh:ii:ss
 */
function getFullDate(){
	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;

	hh=oggi.getHours();
	min=oggi.getMinutes();
	sec=oggi.getSeconds()
	if (hh<10)
		hh="0"+hh;
	if (min<10)
		min="0"+min;
	if (sec<10)
		sec="0"+sec;

	return gg+"/"+mm+"/"+aa+" "+hh+":"+min+":"+sec;
}

/**
 * nella forma yyyymmddhhiiss
 */
function getTimestamp() {
 	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;

 	hh=oggi.getHours();
 	min=oggi.getMinutes();
 	sec=oggi.getSeconds()
 	if (hh<10)
 		hh="0"+hh;
 	if (min<10)
 		min="0"+min;
 	if (sec<10)
 		sec="0"+sec;

 	return ""+aa+mm+gg+hh+min+sec
}

/**
 * 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_img){
	obj=document.getElementById(id_sezione);
	objIMG=document.getElementById(id_sezione+"_img");
	if(obj){
		if (obj.style.display=="none"){
			if (objIMG)
				objIMG.src=path_img+"minus.jpg";
			obj.style.display="";
		}else{
			if (objIMG)
				objIMG.src=path_img+"add.jpg";
			obj.style.display="none";
		}
	}
}

/**
 * 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;
}

//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 apriModifica(nome, titolo, lar, alt, feat){
	if(feat=='') feat = "toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=yes, copyhistory=no";
	apriPopupCentrata(nome, titolo, lar, alt, feat);
}

function isCheked(obj){
	if(obj){
		for(i=0; i<obj.length; i++){
			if(obj[i].checked) return true;
		}
	}
	return false;
}

function whatCheked(obj){
	if(obj){
		for(i=0; i<obj.length; i++){
			if(obj[i].checked) return obj[i].value;
		}
	}
	return '';
}

function isAnno(anno){
	if(anno!="" && anno.length==4 && IsNumeric(anno)) return true;
	else return false;
}

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();
}

/**
 * Ritorna un identificativo univoco
 */
function getUniqueID(){
	var d = new Date()
	return d.getDate()+""+d.getMonth()+1+""+d.getFullYear()+""+d.getHours()+""+d.getMinutes()+""+d.getSeconds();
}

/**
 * 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;
}


/**
* Trim
*/
function trim(srcStr){
	return srcStr.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}
function ltrim(srcStr) {
	return srcStr.replace(/^\s+/,"");
}
function rtrim(srcStr) {
	return srcStr.replace(/\s+$/,"");
}
//rimuove tutti gli spazi
function deleteWhitespace(srcStr) {
	return srcStr.replace(/\s+/g,'');
}

/**
 * Div popup
 */
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;
}

function apriTesto(url, height){
	var padre = 'container';

	var elemOscuro=new Element("div", {
    'id': "opacizza",
    events: {'click': chiudiTesto }
	});
	elemOscuro.inject(padre, 'top');

	var elemContenitore=new Element("div", {
    "id": "contenitore_opacizzato"
	});
	window.scrollTo(0,0);
	elemContenitore.style.height="0px";
	elemContenitore.style.top=(scrolPosition())+"142px";
	elemContenitore.inject(padre, "top");
	elemContenitore.addClass("loading");


	elemX=new Element("div", {
    "id": "contenitore_opacizzato_chiusura",
    events: {'click': chiudiTesto }
	});
	elemX.set("html", "");

	var options={};
	options["method"]="get";
	options["update"]=elemContenitore;
	options["onComplete"]=function(){
			elemContenitore.removeClass("loading");
			elemX.inject($("contenitore_opacizzato"), "bottom");

			if (height) {
				//window.addEvent('domready', function(){ tweenHeight($("contenitore_opacizzato"), height) });
				(function(){ tweenHeight($("contenitore_opacizzato"), height); }).delay(500);
			}else{
				//window.addEvent('domready', function(){ tweenHeight($("contenitore_opacizzato"), $("contenitore_opacizzato").getFirst().getSize().y+40) });
				(function(){ tweenHeight($("contenitore_opacizzato"), $("contenitore_opacizzato").getFirst().getSize().y+40);}).delay(500);
			}
	} ;
	options["evalScripts"]=true;
	options["url"]=url;

	new Request.HTML(options).send();

	//return false;
}

function tweenHeight(obj, height){
	obj.tween ('height', height);
}
function tweenBackGround(obj, color){
	var color=obj.getStyle("background-color");
	obj.tween('background-color', '#52a6ef');
	(function(){obj.tween('background-color', color);}).delay(700);
}

function chiudiTesto(){
	if( $("opacizza") )$("opacizza").destroy();
	if( $("contenitore_opacizzato") )$("contenitore_opacizzato").destroy();
}

/**
* level è per uso interno, quindi la signature DEVE essere
* 		inspect(obj, maxLevels)
*/
function inspect(obj, maxLevels, level){
	var str = '', type, msg;

	// Start Input Validations
	// Don't touch, we start iterating at level zero
	if(level == null)
		level = 0;

	// At least you want to show the first level
	if(maxLevels == null)
		maxLevels = 1;
	if(maxLevels < 1)
		return '<font color="red">Error: Levels number must be > 0</font>';

	// We start with a non null object
	if(obj == null)
		return '<font color="red">Error: Object <b>NULL</b></font>';
	// End Input Validations

	// Each Iteration must be indented
	str += '<ul>';
	// Start iterations for all objects in obj
	for(property in obj) {
		try {
			// Show "property" and "type property"
			type =  typeof(obj[property]);
			str += '<li>(' + type + ') ' + property + ( (obj[property]==null)?(': <b>null</b>'):('')) + '</li>';
			// We keep iterating if this property is an Object, non null
			// and we are inside the required number of levels
			if((type == 'object') && (obj[property] != null) && (level+1 < maxLevels))
				str += inspect(obj[property], maxLevels, level+1);
		} catch(err) {
			// Is there some properties in obj we can't access? Print it red.
			if(typeof(err) == 'string')
				msg = err;
			else if(err.message)
				msg = err.message;
			else if(err.description)
				msg = err.description;
			else
				msg = 'Unknown';

			str += '<li><font color="red">(Error) ' + property + ': ' + msg +'</font></li>';
		}
	}
	// Close indent
	str += '</ul>';
	return str;
}

function sec_to_time(secs){
	var hr = Math.floor(secs / 3600);
	var min = Math.floor((secs - (hr * 3600))/60);
	secs -= ((hr * 3600) + (min * 60));
	secs += ''; min += '';
	while (min.length < 2) {min = '0' + min;}
	while (secs.length < 2) {secs = '0' + secs;}
	hr = (hr)?':'+hr:'';
	return hr + min + ':' + secs;

}
