
function reformat(s) {   
	var arg;
  	var sPos = 0;
  	var resultString = "";

	for (var i = 1; i < reformat.arguments.length; i++) {
		arg = reformat.arguments[i];
		if (i % 2 == 1) {
			resultString += arg;
		}
		else {
			resultString += s.substring(sPos, sPos + arg);
			sPos += arg;
		}
	}
	return resultString;
}

function stripCharsInBag(s,bag) {   
	var i;
	var returnString = "";

	// Search through string's characters one by one.
	// If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++) {   
		// Check that current character isn't whitespace.
		var c = s.charAt(i);
		if (bag.indexOf(c) == -1) {
			returnString += c;
		}
	}
	return returnString;
}

function promptEnter(s) {   
	window.status =  "Please Enter " + s
	return true;
}

function promptSelect(s) {   
	window.status =  "Please Select " + s
	return true;
}

function isEmpty(s) {   
	if ((s == null) || (s.length == 0) || (/^\s+$/.test(s))) {
		return true;
	}
	else {
		return false;
	}
}

function isStateCode(s) {   
	var USStateCodes = "AL|AK|AS|AZ|AR|CA|CO|CT|DE|DC|FM|FL|GA|GU|HI|ID|IL|IN|IA|KS|KY|LA|ME|MH|MD|MA|MI|MN|MS|MO|MT|NE|NV|NH|NJ|NM|NY|NC|ND|MP|OH|OK|OR|PW|PA|PR|RI|SC|SD|TN|TX|UT|VT|VI|VA|WA|WV|WI|WY|AE|AA|AE|AE|AP";
	if (isEmpty(s)) {
		return true;
	}
	else {
		s = s.toUpperCase();
		return ((USStateCodes.indexOf(s) != -1));
	}
}

function checkEmail(s) {
	if (isEmpty(s)) {
		return true;
	}
	else {
		if (/^.+\@.+\..+$/.test(s)) {
			return true;
		}
	}
	alert("Invalid Email Address Format:  " + s + " !");
	return false;
}

function checkPhoneNumber(f) {
	if (isEmpty(f.value)) {
		return true;
	}
	else {
		var normalized = stripCharsInBag(f.value,"()- ");
		if (/^\d+$/.test(normalized) 
			&& normalized.length == 10) {
			f.value = reformat(normalized,"(",3,") ",3,"-", 4);
			return true;
		}
	}
	alert("Invalid Phone Number Format:  " + f.value + " Use:  222-222-2222");
	return false;
}

function checkZipCode(f) {
	if (isEmpty(f.value)) {
		return true;
	}
	else {
		var normalized = stripCharsInBag(f.value,"- ");
		if (/^\d+$/.test(normalized)) {
			if (normalized.length == 5) {
				return true;
			}
			else if (normalized.length == 9) {
				f.value = reformat(normalized,"",5,"-",4);
				return true;
			}
		}
	}
	alert("Invalid Zip Code Format:  " + f.value + " Use:  5 or 9 Digit Zip Code");
	return false;
}

function checkRequired(f) {   
	if (! isEmpty(f.value)) {
		return true;
	}
	alert("Field:  " + f.name + " (REQUIRED)");
	return false;
}

function checkStateCode(s) {   
	if (isStateCode(s)) {
		return true;
	}
	alert("Invalid State Code:  " + s.toUpperCase() + " ! ");
	return false;
}
