//author: 	Sam Curry
//date:		Sunday, 29th April 2001
//example:
/*
<SCRIPT LANGUAGE="JavaScript" SRC="includes/fnValidEmail.js"></SCRIPT>
<SCRIPT LANGUAGE="JavaScript">
function validateForm() {
		if ((obj["Email"].value.trim() != "") && (! obj["Email"].value.validEmail("E-mail Address"))) {
			obj["Email"].focus()
			return false
		}
}
</SCRIPT>
*/

String.prototype.validEmail = function(strNameToDisplay) {
	
	if (strNameToDisplay == null) {
		alert("error - function missing paramter: strNameToDisplay")
		return false
	}
	
	var strAlertSentence = createAlertSentence(strNameToDisplay)
	
	var strEmail = new String(this)
	
	if (strEmail.length == 0) {
		alert(strAlertSentence)
		return false
	}

	if (strEmail.indexOf("@") != strEmail.lastIndexOf("@")) {
		alert(strAlertSentence + " with no more than 1 '@'")
		return false
	}
	else if ((strEmail.indexOf("@") < 1) || (strEmail.lastIndexOf("@") == (strEmail.length - 1))) {
		alert(strAlertSentence + " with an '@' between the first and last character")
		return false
	}
	else if ((strEmail.indexOf(".") < 1) || (strEmail.lastIndexOf(".") == (strEmail.length - 1))) {
		alert(strAlertSentence + " with a '.' between the first and last character")
		return false
	}
	else if (strEmail.lastIndexOf("@") > strEmail.lastIndexOf(".")) {
		alert(strAlertSentence + " with '.' appearing after '@'")
		return false
	}
	else if ((strEmail.nextIndexOf(strEmail.indexOf("@"), ".") - strEmail.indexOf("@")) < 2) {
		alert(strAlertSentence + " with '@' and '.' separated by at least 1 character")
		return false
	}
	
	var arrBadChars = new Array(" ", "`", "~", "!", "#", "$", "%", "^", "&", "*", "(", ")", "=", "+", "[", "]", "{", "}", "\\", "/", ";", ":", "'", "\"", "<", ">", ",", "?")
	
	var strReturnChars = new String("")
	
	for (var i = 0; i < arrBadChars.length; i++) {
		strReturnChars = strReturnChars + (strEmail.indexOf(arrBadChars[i]) == -1 ? "" : arrBadChars[i])
	}
	
	if (strReturnChars != "") {
		alert(strAlertSentence + " without the following characters:\n" + strReturnChars)
		return false
	}
	else
		return true
		
	function createAlertSentence(strNameToDisplay) {
	
		var arrVowels = new Array("a", "e", "i", "o", "u")
	
		return "Please enter" + getWordSeparater() + strNameToDisplay
	
		function getWordSeparater() {
			for (var i = 0; i < arrVowels.length; i++) {
				var strFirstLetter = strNameToDisplay.charAt(0).toLowerCase()
				if (strFirstLetter == arrVowels[i])
					return " an "
			}
			return " a "
		}
	}
}


String.prototype.nextIndexOf = function(intStartIndex, strFind) {

	var strEmail = new String(this)

	var intFindLength = strFind.length

	for (var i = intStartIndex + 1; i < strEmail.length; i++) {
		if ((i + intFindLength) > strEmail.length)
			return -1
		else if (strEmail.slice(i, i + intFindLength) == strFind)
			return i
	}
	
	return -1
}
