/* <%--
//
//	File: 		validate/email.js
//	Purpose:	Provide email JavaScript validation operations
//  Usage:    This file contains functions for validating text fields
//            that contain email addresses using JavaScript.
//            See the file header.js for details on the validation process.

// ------ PUBLIC FUNCTION INDEX
// VAL_IsEmail( str )
// VAL_EmailCheckWithMessage ( fieldRef, desc )
// VAL_EmailListCheckWithMessage ( fieldRef, desc )
--%> */

// ------ GLOBAL PREFERENCES

// ------------------------------------------------------------------------ //
// Returns true if the string passed in is a valid email address.
// Address must be of form a@b.c -- in other words:
//   - there must be at least one character before the @
//   - there must be at least one character before and after any .
//   - the characters @ and . are both required
//   - no commas or semicolons are allowed after the @

function VAL_IsEmail(
	str  // string to check
)
{
	str = VAL_StripOuterWhitespace (str);
	
	// must not be blank and no blank characters anywhere
	if (VAL_IsBlank(str)) { return false; }
	if (str.indexOf( " " ) >= 0) { return false; }

	var check = false;

	// look for @
	checkPos = str.indexOf( "@" );
	// must be at least one character before it and no commas and semicolons or other @ after
	if (checkPos >= 1 &&
			str.indexOf( ",", checkPos ) < 0 &&
			str.indexOf( ";", checkPos ) < 0 &&
			str.indexOf( "@", checkPos + 1 ) < 0)
	{
		str = str.substring( checkPos + 1 );
		
    // look for .
		checkPos = str.indexOf( "." );
		while (checkPos >= 0) {
			if (checkPos >= 1) { // must be at least one character before it
				// at least one after it
				if (checkPos + 1 < str.length) { // must be at least one character after
					//2 periods must not be together
					if(str.charAt(checkPos + 1) == '.')
						check = false;
					else
						check = true;
	
					
				}	else {
					check = false;
					break;
				}
			} else {
			  check = false;
			  break;
			}
			if (!check) {
				break;
			} else {
				str = str.substring( checkPos + 1 );
				checkPos = str.indexOf( "." );
			}			
		}		
	}
	return check;
}


function VAL_EmailCheckWithMessage ( fieldRef, desc )
{
	if ( ! VAL_IsBlank ( fieldRef.value ) ) {
		if ( ! VAL_IsEmail ( fieldRef.value ) ) {
			VAL_AppendError( sprintf( VAL_invalidEmailMsg, desc ), fieldRef );
			return false;
		} else
			return true;
	} else
		return false;
}

function VAL_EmailListCheckWithMessage ( fieldRef, desc )
{
	arrayOfEmails = new Array();
	if (VAL_IsBlank( fieldRef.value )) {
		return true;
	}
	arrayOfEmails = fieldRef.value.split (";");
	for ( var i = 0; i < arrayOfEmails.length; i ++ ) {
		if (!VALLOC.VAL_IsEmail (arrayOfEmails[i])) {
			VAL_AppendError( sprintf( VAL_invalidEmailMsg, desc ), fieldRef );
			return false;
		}
	}
	return true;
}
