
/**************************************************************
* Funzioni base (utilizzate in altre funzioni di validazione) *
**************************************************************/

// ritorna false se l'argomento ha lunghezza 0, true altrimenti
// Argomenti: str tipo stringa
function notNull(str) {
	if (str.length == 0 )
		return false
	else 
		return true
}

// ritorna false se l'argomento è costituito da soli spazi o
// ha lunghezza 0, true altrimenti
// Argomenti: str tipo stringa
function notBlank(str) {
	for (i = 0; i < str.length; i++) {
		if (str.charAt(i) != " ")
			return true
	}
	return false
}

// ritorna true se il primo argomento è una stringa di 
// lunghezza pari al valore del secondo argomento
// Argomenti: str tipo stringa, size intero
function isSize(str, size) {
	if (str.length == size) 
		return true
	else
		return false
}

// ritorna true se l'argomento è una stringa costituita
// unicamente da caratteri numerici, false altrimenti
// Argomenti: str stringa
function isDigits(str){ 
	var myExp=/^[0-9]*$/;
	
	return myExp.test(str)
}

// ritorna true se la stringa rappresenta un numero valido,
// con o senza decimali, false altrimenti. Il formato .nn 
// (Es: .123) è considerato valido
// Argomenti: str stringa
function isNumber(str){
	var myExp=/(^\d+$)|(^\d*\.\d+$)/
	
	return myExp.test(str)
}

// ritorna true se il primo argomento rappresenta un numero
// compreso tra il secondo (valore minimo) e il terzo 
// (valore massimo) argomento
// Argomenti: str stringa,  num1,num2 numerici
function isInRange(str, num1, num2) {
	var i = parseInt(str,10)
	
	return((i >= num1) && (i <= num2))
}

// ritorna true se l'argomento è una stringa composta unicamente
// da caratteri alfanumerici
// Argomenti: str stringa
function isAlfanumeric(str){
	var myExp=/^[a-z0-9]*$/i;
	
	return myExp.test(str)
}


/******************************
* Riformattazione di stringhe *
******************************/

// ritorna l'argomento al quale sono stati tolti i
// caratteri non numerici
// Argomenti: str stringa
function stripNonDigits(str) {
	return str.replace(/[^0-9]/g,"")
}

// ritorna l'argomento al quale sono stati tolti i
// caratteri contenuti nella stringa passata come
// secondo argomento
// Argomenti: str,chars stringhe
function stripChars(str, chars) {
	var i
	var newstring = ""
	for (i = 0;  i < str.length; i++) {
		mychar = str.charAt(i)
		if (chars.indexOf(mychar) == -1) // mychar non è contenuto in chars
			newstring += mychar
	}
	return newstring
}


/*******************************
* Validazione formati speciali *
*******************************/

// ritorna true se l'argomento è una password valida
// Argomenti: str stringa
function isPassword(str){
	var myExp=/^[A-Za-z0-9_]*$/i;
	
	if (!isInside(str,8,15)) return false;
	return myExp.test(str)
}

// ritorna true se l'argomento è un nickname valido
// Argomenti: str stringa
function isNickname(str){
	var myExp=/^[A-Za-z0-9_]*$/i;
	
	if (!isInside(str,5,10)) return false;
	return myExp.test(str)
}

// Ritorna true se l'argomento è un indirizzo di email valido.
// E' valida la sintassi usuale user@domain,
// ma sono consentiti anche i formati user@[ip]
// e "User with Spaces"@domain o [ip],
// (tutte sintassi legali secondo il W3C.)
// Sono controllati anche errori quali multipli @ o . limitrofi
// nell'indirizzo (Es: user@a@b.com ed user@a..b.co.uk).
// Argomenti: emailStr stringa.


function isEmail (emailStr) {
	// Formato user@domain e separazione di username e dominio
	var emailPat=/^(.+)@(.+)$/
	// Pattern per ritrovare i caratteri speciali (non consentiti)
	var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
	// Caratteri consentiti in username o domainname
	var validChars="\[^\\s" + specialChars + "\]"
	// Username contenente spazi
	var quotedUser="(\"[^\"]*\")"
	// domainName costituito da un indirizzo IP
	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
	// Unità 'atomo' ovvero una serie di caratteri non speciali
	var atom=validChars + '+'
	// Una 'word' dell'username. L'username può essere costituito da più 'word'
	// separate da .
	var word="(" + atom + "|" + quotedUser + ")"
	// Struttura dell'username
	var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
	// Dominio sombolico
	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")

	// Controllo della sintassi username@domain e separazione dell'username dal
	// domain
	var matchArray=emailStr.match(emailPat)
	if (matchArray==null) {
		//alert("Email address seems incorrect (check @ and .'s)")
		return false
	}
	var user=matchArray[1]
	var domain=matchArray[2]
	
	// User valido.
	if (user.match(userPat)==null) {
	    //alert("The username doesn't seem to be valid.")
	    return false
	}
	
	// Indirizzo IP valido (nel caso in cui il domain sia un IP.
	var IPArray=domain.match(ipDomainPat)
	if (IPArray!=null) {
		  for (var i=1;i<=4;i++) {
		    if (IPArray[i]>255) {
		        //alert("Destination IP address is invalid!")
			return false
		    }
	    }
	    return true
	}
	
	// Domain è un nome simbolico
	var domainArray=domain.match(domainPat)
	if (domainArray==null) {
		//alert("The domain name doesn't seem to be valid.")
	    return false
	}
	
	
	// controllo sulla parte terminale del domain.
	
	// Spezzo il domain in 'atomi'
	var atomPat=new RegExp(atom,"g")
	var domArr=domain.match(atomPat)
	var len=domArr.length
	if ((domArr[domArr.length-1].length<2) || 
	    (domArr[domArr.length-1].length>3)) {
	   // alert("The address must end in a three-letter domain, or two letter country.")
	   return false
	}
	
	// Parte terminale del dominio preceduta da un host name.
	if (len<2) {
	   //var errStr="This address is missing a hostname!"
	   //alert(errStr)
	   return false
	}
	
	return true;
}


// ritorna true se nella stringa passata per argomento
// sono contenuti 5 o 9 caratteri numerici 
// Argomenti: str stringa
function isZip(str) {
	if (notNull(str)) {
		newstring = stripNonDigits(str)
		if (isSize(newstring,5) || isSize(newstring, 9)) 
			return true
	}
	return false
}

// ritorna true se nella stringa passata per argomento
// sono contenuti 5 caratteri numerici 
// Argomenti: str stringa
function isCAP(str) {
	if (notNull(str)) {
		newstring = stripNonDigits(str)
		if (isSize(newstring,5)) 
			return true
	}
	return false
}

//
function isURL(str) {  
	var myExp=/./;
	
	return myExp.test(str)
}

// ritorna true se la data rappresentata dal giorno pari al
// primo argomento, dal mese pari al secondo e dall'anno pari 
// al terzo è valida, false altrimenti
// Argomenti gg,mm,aaaa stringhe rappresentanti interi
// (aaaa anno in formato esteso a 4 cifre)
function isDate(gg,mm,aaaa){ 
	// gg, mm, aaaa sono stringhe tutte di caratteri numerici
	if (!isDigits(gg)) return false;
	if (!isDigits(mm)) return false;
	if (!isDigits(aaaa)) return false;
	
	giorno = parseInt(gg,10);
	mese = parseInt(mm,10);
	anno = parseInt(aaaa,10);
	
	if (!isInRange(giorno,1,31)) return false;
	if (!isInRange(mese,1,12)) return false;
	
	testDate = new Date(anno,mese-1,giorno);
	
	return ( testDate.getMonth()==(mese-1) && 
			 testDate.getDate()==(giorno)    )
}

// ritorna true se la stringa è contiene solo caratteri
// numerici e  +-/ o spazio, false altrimenti
// Argomenti: str stringa
function isPhone(str){	
	
	newstring = stripChars(str, "+ -/");
	if (isDigits(newstring)) return true;
	return false
}


/*******************************
* Validazione formati standard *
*******************************/

// ritorna true se l'argomento è una stringa non 
// vuota e non costituita da soli spazi
// Argomenti: str stringa
function isValidString(str) {
	if (notNull(str)&& notBlank(str)) 
		return true;
	return false;
}

// ritorna true se il primo argomento è una stringa
// di lunghezza superiore al valore del secondo argomento,
// false altrimenti
// Argomenti: str stringa, maxLength numerico
function isLonger(str,maxLength) {
	if (str.length>maxLength)
		return true;
	return false
}

// ritorna true se il primo argomento è una stringa
// di lunghezza inferiore al valore del secondo argomento,
// false altrimenti
// Argomenti: str stringa, minLength numerico
function isShorter(str,minLength) {
	if (str.length<minLength)
		return true;
	return false
}

// ritorna true se la lunghezza della stringa passata come 
// primo argomento è compresa tra i valori rappresentati
// dal secondo (minimo) e il terzo (massimo) argomento,
// false altrimenti
// Argomenti: str stringa, minLength,maxLength numerici
function isInside(str,minLength,maxLength) {
	if (!isShorter(str,minLength) && !isLonger(str,maxLength))
		return true;
	return false
}


/********
* Varie *
********/

// ritorna true se l'oggetto radio passato per argomento 
// ha una selezione effettuata, false altrimenti
// Argomenti: radio INPUT di tipo radio
function isRadioSelected(radio) {
	for (i=0 ; i< radio.length ; i++){
		if (radio[i].checked) return true;
	}
	return false
}

// ritorna l'indice dell'oggetto radio passato per argomento 
// che ha una selezione effettuata, -1 altrimenti
// Argomenti: radio INPUT di tipo radio
function RadioSelected(radio) {
	for (i=0 ; i< radio.length ; i++){
		if (radio[i].checked) return i;
	}
	return -1;
}
