var digits = "0123456789";
var lowercaseLetters = "abcdefghijklmnopqrstuvwxyz";
var uppercaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var whitespace = " \t\n\r";
var decimalPointDelimiter = ".";
var phoneNumberDelimiters = "()-+." + whitespace;
var validPhoneChars = digits + phoneNumberDelimiters;
var digitsInUSPhoneNumber = 10;
var ZIPCodeDelimeter = "-";
var validZIPCodeChars = digits+ZIPCodeDelimeter;
// Modified on 06/22/01 by Namita
// New system allows '_' in username
// var validUsername = digits + lowercaseLetters + uppercaseLetters + decimalPointDelimiter;
var underscoreDelimiters = "_";
var atsignDelimiters = "@";
var validUsername = digits + lowercaseLetters + uppercaseLetters + decimalPointDelimiter+underscoreDelimiters+atsignDelimiters;
var validCF_PIVA = digits + lowercaseLetters + uppercaseLetters;
var validWWWDomains = "/.com/.net/.org/.edu/.mil/.gov/.int/.biz/.aero";
var validCountryDomains  = "/.ac/.ad/.ae/.af/.ag/.ai/.al/.am/.an/.ao/.aq/.ar/.as/.at/.au/.aw/.az/.ba/.bb/.bd/.be/.bf/.bg/.bh/.bi/.bj/.bm/.bn/.bo/.br/.bs/.bt/.bv/.bw/.by/.bz/.ca/.cc/.cd/.cf/.cg/.ch/.ci/.ck/.cl/.cm/.cn/.co/.cr/.cu/.cv/.cx/.cy/.cz/.de/.dj/.dk/.dm/.do/.dz/.ec/.ee/.eg/.eh/.er/.es/.et/.fi/.fj/.fk/.fm/.fo/.fr/.ga/.gd/.ge/.gf/.gg/.gh/.gi/.gl/.gm/.gn/.gp/.gq/.gr/.gs/.gt/.gu/.gw/.gy/";
    validCountryDomains += "/.hk/.hm/.hn/.hr/.ht/.hu/.id/.ie/.il/.im/.in/.io/.iq/.ir/.is/.it/.je/.jm/.jo/.jp/.ke/.kg/.kh/.ki/.km/.kn/.kp/.kr/.kw/.ky/.kz/.la/.lb/.lc/.li/.lk/.lr/.ls/.lt/.lu/.lv/.ly/.ma/.mc/.md/.mg/.mh/.mk/.ml/.mm/.mn/.mo/.mp/.mq/.mr/.ms/.mt/.mu/.mv/.mw/.mx/.my/.mz/.na/.nc/.ne/.nf/.ng/.ni/.nl/.no/.np/.nr/.nu/.nz/.om/.pa/.pe/.pf/.pg/.ph/.pk/.pl/.pm/.pn/.pr/.ps/.pt/.pw/.py/";
    validCountryDomains += "/.qa/.re/.ro/.ru/.rw/.sa/.sb/.sc/.sd/.se/.sg/.sh/.si/.sj/.sk/.sl/.sm/.sn/.so/.sr/.st/.sv/.sy/.sz/.tc/.td/.tf/.tg/.th/.tj/.tk/.tm/.tn/.to/.tp/.tr/.tt/.tv/.tw/.tz/.ua/.ug/.uk/.um/.us/.uy/.uz/.va/.vc/.ve/.vg/.vi/.vn/.vu/.wf/.ws/.ye/.yt/.yu/.za/.zm/.zr/.zw/";
var validDomains = validWWWDomains + validCountryDomains;


function checkRagioneSociale(ragSoc){
    var ragioneSociale = trimAll(new String(ragSoc));
	if (ragioneSociale == "") {
		alert("Il campo \"ragione sociale\" non puņ essere lasciato vuoto");
		return false;
	}
	return true
}

function checkCF_PIVA(cf_piva){
    var cfPiva = trimAll(new String(cf_piva));
	var cfPivaLength = cfPiva.length;
	var type = "NA";
	switch (cfPivaLength) {
	    case 11: type = "PI"; break;
		case 16: type = "CF"; break;
	}
	if (type != "NA") {
		for (i=0; i<cfPivaLength; i++) {
     		if (validCF_PIVA.indexOf(cfPiva.charAt(i)) == -1) {
				if (type=="PI") {
				    alert ("Il carattere numero "+(i+1)+" della \"Partita I.V.A.\" non č consentito.");
				} else {
				    alert ("Il carattere numero "+(i+1)+" del \"Codice fiscale\" non č consentito.");
				}				
				return false
			}
		}
	} else {
	    alert ("Il dato immesso nel campo \"Codice Fiscale/Partita I.V.A.\" sembra essere scorretto!")
		return false
	}
	return true
}

function checkPhone(num){
    var phone = trimAll(new String(num));
    var phoneLength = phone.length;
    if (phoneLength == 0) {
	    alert("Il campo \"Cellulare\" non puņ essere lasciato vuoto!");
		return false;
	}
	for (i=0; i<phoneLength; i++) {
        if (validPhoneChars.indexOf(phone.charAt(i)) == -1) {
			alert(phone.charAt(i));
		    alert ("Il carattere numero "+(i+1)+" del \"Cellulare\" o del \"Telefono\" sembra scorretto.");
			return false
		}
	}
	return true
}


function checkEmail (address) {
var emailStr = new String(address);
//var emailStr = new String(document.form.email.value);

/* The following variable tells the rest of the function whether or not
to verify that the address ends in a two-letter country or well-known
TLD.  1 means check it, 0 means don't. */
var checkTLD=1;

/* The following is the list of known TLDs that an e-mail address must end with. */

var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum|[a-zA-Z][a-zA-Z]|COM|NET|ORG|EDU|INT|MIL|ARPA|BIZ|AERO|NAME|COOP|INFO|PRO|MUSEUM)$/;

/* The following pattern is used to check if the entered e-mail address
fits the user@domain format.  It also is used to separate the username
from the domain. */

var emailPat=/^(.+)@(.+)$/;

/* The following string represents the pattern for matching all special
characters.  We don't want to allow special characters in the address. 
These characters include ( ) < > @ , ; : ! # $ % & * = + / \ " . [ ] */

var specialChars="\\(\\)><@,;:!#$%&*=?+^|~\\/\\`\\'\\\\\\\"\\.\\[\\]";

/* The following string represents the range of characters allowed in a 
username or domainname.  It really states which chars aren't allowed.*/

var validChars="\[^\\s" + specialChars + "\]";

/* The following string represents an atom (basically a series of non-special characters.) */

var atom=validChars + '+';

/* The following string represents one word in the typical username.
For example, in john.doe@somewhere.com, john and doe are words.
Basically, a word is either an atom or quoted string. */

var word="(" + atom + ")";

// The following pattern describes the structure of the user

var userPat=new RegExp("^" + word + "(\\." + word + ")*$");


/* Finally, let's start trying to figure out if the supplied address is valid. */

/* Begin with the coarse pattern to simply break up user@domain into
different pieces that are easy to analyze. */

var matchArray=emailStr.match(emailPat);

if (matchArray==null) {

/* Too many/few @'s or something; basically, this address doesn't
even fit the general mould of a valid e-mail address. */

return alert("L'indirizzo e-mail sembra scorretto (controllare i caratteri speciali '@' and '.')");
}
var user=matchArray[1];
var domain=matchArray[2];

// Start by checking that only basic ASCII characters are in the strings (0-127).

for (i=0; i<user.length; i++) {
if (user.charCodeAt(i)>127) {
return alert("Il nome dell'utente contiene caratteri non validi.");

   }
}
for (i=0; i<domain.length; i++) {
if (domain.charCodeAt(i)>127) {
return alert("Il nome del dominio contiene caratteri non validi.");
   }
}

// See if "user" is valid 

if (user.match(userPat)==null) {

// user is not valid

return alert("Il nome dell'utente nell'indirizzo sembra essere scorretto.");
}


// Domain is symbolic name.  Check if it's valid.
 
var atomPat=new RegExp("^" + atom + "$");
var domArr=domain.split(".");
var len=domArr.length;
for (i=0;i<len;i++) {
if (domArr[i].search(atomPat)==-1) {
return alert("Il nome del dominio sembra essere scorretto.");
   }
}

/* domain name seems valid, but now make sure that it ends in a
known top-level domain (like com, edu, gov) or a two-letter word,
representing country (uk, nl), and that there's a hostname preceding 
the domain or country. */

/* Removed this logic to avoid the numbers in the TLDs */
/*if (checkTLD && domArr[domArr.length-1].length!=2 && 
domArr[domArr.length-1].search(knownDomsPat)==-1) {
return setError("The e-mail address must end in a well-known domain or two letter " + "country.");
}
*/
if (checkTLD && domArr[domArr.length-1].search(knownDomsPat)==-1) {
return alert("L'indirizzo e-mail deve terminare con un dominio noto o con la sigla a due caratteri di una " + "nazione.");
}

// Make sure there's a host name preceding the domain.
if (len<2) {
return alert("A questo indirizzo e-mail manca un hostname! (es.:xxx.yyy@hostname.domain)");
}

// If we've gotten this far, everything's valid!
return true;
}


function trimAll(sString) {
    while (sString.substring(0,1) == ' ') {
    	sString = sString.substring(1, sString.length);
    }
	while (sString.substring(sString.length-1, sString.length) == ' ') {
        sString = sString.substring(0,sString.length-1);
    }
    return sString;
}

