// returns true if the string is empty
function isEmpty(str){
	return (str == null) || (str.length == 0);
}

// returns true if the string's length equals "len"
function isLength(str, len){
	return str.length == len;
}

// returns true if the string's length is between "min" and "max"
function isLengthBetween(str, min, max){
	return (str.length >= min)&&(str.length <= max);
}

// returns true if the string is a US phone number formatted as 000-000-0000
function isPhoneNumber(str) {
	var re = /^\d{3}-\d{3}-\d{4}$/;
	return re.test(str);
}

// returns true if the string only contains characters A-Z, a-z or 0-9
function isAlphaNumeric(str){
	var re = /[^a-zA-Z0-9- ]/g;
	if (re.test(str)) return false;
	return true;
}

// returns true if the string only contains characters A-Z, a-z or 0-9
function isZipPostalCode(str){
	var re = /[^a-zA-Z0-9- \-]/g;
	if (re.test(str)) return false;
	return true;
}

// Returns true if the string only contains characters 0-9
function isNumeric(str) {
	var re = /[\D]/g;
	if (re.test(str)) return false;
	return true;
}

// Returns true if the string only contains characters A-Z or a-z
function isAlpha(str) {
	var re = /[^a-zA-Z]/g;
	if (re.test(str)) return false;
	return true;
}

// returns true if "str1" is the same as the "str2"
function isMatch(str1, str2){
	return str1 == str2;
}

// returns true if str is a valid uri
function isUri(str) {
	var re = new RegExp("^(http|https|ftp)\://[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(:[a-zA-Z0-9]*)?/?([a-zA-Z0-9\-\._\?\,\'/\\\+&%\$#\=~])*$");
	if (re.test(str)) return true;
	return false;
}

// returns true if emailStr is a valid email address
function isEmail (emailStr) {
	var checkTLD=1;
	var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;
	var emailPat=/^(.+)@(.+)$/;
	var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
	var validChars="\[^\\s" + specialChars + "\]";
	var quotedUser="(\"[^\"]*\")";
	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
	var atom=validChars + '+';
	var word="(" + atom + "|" + quotedUser + ")";
	var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");
	var matchArray=emailStr.match(emailPat);

	if (matchArray==null) {
		return false;
	}

	var user=matchArray[1];
	var domain=matchArray[2];
	for (i=0; i<user.length; i++) {
		if (user.charCodeAt(i)>127) {
			return false;
		}
	}

	for (i=0; i<domain.length; i++) {
		if (domain.charCodeAt(i)>127) {
			return false;
	   }
	}

	if (user.match(userPat)==null) {
		return false;
	}

	var IPArray=domain.match(ipDomainPat);
	if (IPArray!=null) {
		for (var i=1;i<=4;i++) {
			if (IPArray[i]>255) {
				return false;
			}
		}
		return true;
	}
	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 false;
	   }
	}
	if (checkTLD && domArr[domArr.length-1].length!=2 &&
		domArr[domArr.length-1].search(knownDomsPat)==-1) {
		return false;
	}

	if (len<2) {
		return false;
	}

	return true;
}

// returns true if theVal is in theArr
function inArray(theVal, theArr) {
	for(var index = 0; index < theArr.length; index++) {
		if(theVal == theArr[index])
			return true;
	}
	return false;
}

function setCountry(f) {
	if (f.elements["items[State]"].value != "") {
		f.elements["items[Country]"].value = "US";
	}
}

function setState(f) {
	if (f.elements["items[Country]"].value != "US") {
		f.elements["items[State]"].options[0].selected = true;
	}
}

function formValidate(f) {
	// the countries that require a zip/postal code
	var countries = new Array("AR",	"AU", "AT",	"BE", "BR",	"CA", "CN",	"DK", "FI",	"FR", "DE",	"GR", "IN",	"IL", "IT",	"JP", "MY",	"MX", "NL",	"NZ", "NO", "PH", "PL",	"PT", "PR",	"RU", "SG",	"KR", "ES",	"SE", "CH",	"TW", "TH",	"TR", "GB",	"US");

	errorstr = new String();
	errorstr += "ERROR: Please correct the following fields:\n";
	errorstrLen = errorstr.length;

	for (i=0; i < f.length; i++) {
		e = f.elements[i];
		val = e.value;

		if (e.name == "items[FirstName]") {

			if (isEmpty(val))
				errorstr += "  * First name missing\n";
			else if (!isAlphaNumeric(val))
				errorstr += "  * First name must be alphanumeric\n";

		} else if (e.name == "items[MiddleName]") {

			//if (!isEmpty(val) && !isAlphaNumeric(val))
			//	errorstr += "  * Middle Name must be alphanumeric\n";

		} else if (e.name == "items[LastName]") {

			if (isEmpty(val))
				errorstr += "  * Last name missing\n";
			else if (!isAlphaNumeric(val))
				errorstr += "  * Last name must be alphanumeric\n";

		} else if (e.name == "items[Suffix]") {

			//if (!isEmpty(val) && !isAlpha(val))
			//	errorstr += "  * Suffix must be alphabetical\n";

		} else if (e.name == "items[Credentials]") {

			if (isEmpty(val))
				errorstr += "  * Credentials missing\n";

		} else if (e.name == "items[Title]") {

			//if (!isEmpty(val) && !isAlphaNumeric(val))
			//	errorstr += "  * Title must be alphanumeric\n";

		} else if (e.name == "items[Hospital]") {

			if (isEmpty(val))
				errorstr += "  * Hospital name missing\n";

		} else if (e.name == "items[Address]") {

			if (isEmpty(val))
				errorstr += "  * Address missing\n";

		} else if (e.name == "items[City]") {

			if (isEmpty(val))
				errorstr += "  * City missing\n";

		} else if (e.name == "items[Country]") {

			if (val == "US") 
				f.elements["items[StateOther]"].value = '';
			else 
				f.elements["items[State]"].value = '';

		} else if (e.name == "items[State]") {

			if (f.elements["items[Country]"].value == "US" && isEmpty(val))
				errorstr += "  * State/Territory missing\n";
			else if (f.elements["items[Country]"].value == "CA" && isEmpty(f.elements["items[StateOther]"].value))
				errorstr += "  * State/Territory missing\n";
			
		} else if (e.name == "items[Zip]") {

			if(f.elements("items[Country]").value == "US") {
				
				if (isEmpty(val))
					errorstr += "  * Zip code missing\n";
				else if (!isLength(val,5))
					errorstr += "  * Zip Code must be five (5) numbers\n";
				else if (!isNumeric(val))
					errorstr += "  * Zip code must be a number\n";
			}

			else if (inArray(f.elements("items[Country]").value, countries)) {
				if(isEmpty(val))
					errorstr += "  * Zip/Postal code missing\n";
			}

			if(!isEmpty(val) && !isZipPostalCode(val))
					errorstr += "  * Zip/Postal code can only contain letters, numbers, spaces, and \"-\"\n";

		} else if (e.name == "items[ZipPlus4]") {
			
			if (!isEmpty(val) && !isNumeric(val))
				errorstr += "  * Zip plus 4 must be a number\n";
			else if (!isEmpty(val) && !isLength(val,4))
				errorstr += "  * Zip plus 4 must be four (4) numbers\n";

		} else if (e.name == "items[WorkPhone]") {

			if (isEmpty(val))
				errorstr += "  * Phone number missing\n";
			else if (f.elements["items[Country]"].value == "US" && !isPhoneNumber(val))
				errorstr += "  * Phone number improperly formatted\n";

		} else if (e.name == "items[WorkPhoneExt]") {

			if (!isEmpty(val) && !isNumeric(val))
				errorstr += "  * Phone extension must be a number\n";

		} else if (e.name == "items[WorkFax]") {

			if (f.elements["items[Country]"].value == "US" && !isEmpty(val) && !isPhoneNumber(val))
				errorstr += "  * Fax number improperly formatted\n";

		} else if (e.name == "items[Email]") {

			if (isEmpty(val))
				errorstr += "  * E-mail address missing\n";
			else if (!isEmail(val))
				errorstr += "  * E-mail address improperly formatted\n";

		} else if (e.name == "EmailConfirm") {

			if (isEmpty(val))
				errorstr += "  * E-mail confirmation missing\n";
			else if (!isEmail(val))
				errorstr +=	"  * E-mail confirmation improperly formatted\n";
			else if (!isMatch(val, f.elements["items[Email]"].value))
				errorstr += "  * E-mail addresses do not match\n";

		} else if (e.name == "items[Website]") {

			if (!isEmpty(val) && !isUri(val))
				errorstr += "  * Web site address must be formatted like http://www.myhospital.com/\n";

		}
	}

	if ( errorstr.length > errorstrLen) {
		alert(errorstr);
		return false;
	}

	return true;
}