/*
function IsValidEmailAddress(src) {
     var emailReg = "^[\\w-_\.]*[\\w-_\.]\@[\\w]\.+[\\w]+[\\w]$";
     var regex = new RegExp(emailReg);
     return regex.test(src);
}
*/

// Deletes 'intNoChars' characters from 'strOrig' starting from 'intPos' and replaces them with 'strReplace'. 
// The function works even if 'strReplace.length' <> intNoChars. 
function replaceChars(strOrig, intPos, intNoChars, strReplace) {
	strOrig = strOrig.replace(/\s/g,"");
	if (intPos < 0) intPos = 0;
	if (intPos >= strOrig.length) intPos = strOrig.length - 1;
	if (intNoChars < 0) intNoChars = 0;
	if (intNoChars > strOrig.length) intNoChars = strOrig.length;
	return (strOrig.substring(0, intPos) + strReplace + strOrig.substring(intPos + intNoChars));
}

// Replaces every instance of substring 'strFind' in 'strOrig' with 'strReplace'.
function replaceAll(strOrig, strFind, strReplace) {
	strOrig = strOrig.replace(/\s/g,"");
    var intCount = strOrig.indexOf(strFind);
	while (intCount != -1)	{
		strOrig = replaceChars(strOrig, intCount, strFind.length, strReplace);
		intCount = strOrig.indexOf(strFind);
	}
	return strOrig;
}

//this function checks if there are any characters in 'strCheck', that are not in 'strValid'
function fIsValidChars(strCheck, strValid) {
	var strChar = "";
	
	for (var intCount = 0; intCount < strCheck.length; intCount++) {
		strChar = strCheck.charAt(intCount);
		if (strValid.indexOf(strChar) == -1) 
			return false;
	}

	return true;
}
	
// Check to see if a form text field contains a valid email address
function IsValidEmailAddress(strEmailAddress) {
	strEmailAddress = strEmailAddress.replace(/\s/g,""); //trim
	var intCount = "";
	var strCheck = "";
	
	//split part 1 and 2 into separate variables
	var arrEmail = strEmailAddress.split('@');
	
	//check that there are at least 2 parts to the email
	if (arrEmail.length < 2)
		return false;
	
	var strPart2 = arrEmail[arrEmail.length-1];
	var strPart1 = replaceAll(strEmailAddress,'@' + strPart2,'');
	
	//split the periods from each part into arrays
	var arrPart2 = strPart2.split('.');
	
	if (arrPart2.length < 2)
		return false;
	
	// Check for Valid Characters
	if (!fIsValidChars(strPart1,'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789@._-'))
		return false;
	
	//check for validity in part 2 array
	for (intCount = 0; intCount < arrPart2.length; intCount++) {
		strCheck = arrPart2[intCount];

		//check for empty string
		if (strCheck.length <= 0) 
			return false;
		
		// Check for Valid Characters
		if (!fIsValidChars(strCheck,'abcdefghijklmnopqrstuvwxyz0123456789._-'))
			return false;
	}	
	
	// If all was ok, return true
	return true;
}
