//# TODO: remove comments and "fluff characters" before release
//#
//#----------------------------------------------------------------------------
//#	validate_email_address
//#
//#	  Parameters:
//#		  email_address: the email address to validate;
//#
//#	  Purpose:
//#	  	validates an email address (format only, doesn't check for "liveness")
//#
//#  	Return:
//#  		0   if valid
//#     10  if invalid: not present
//# 		20  if invalid: invalid format
//#     30  if invalid: invalid chars present
//#     
//#----------------------------------------------------------------------------
//FUNCTION CHECKS FOR WHITE SPACE
//TRIMS WHITE SPACE
function trimWhiteSpace(wrd)
{

	word = new String(wrd);	
	len = word.length;
	//dbug ="|"+wrd+"|";
	if(len == 0){ return; }
	var hold = '';
	var c;
	cnt = 0;
	while(cnt < len)
	{
		c = word.charAt(cnt);
		if(! c.match(/\s/))
		{
			if(hold == ''){ hold = c; }
			else{ hold += c; }
		}	
		cnt++;
	}
	//alert("trimWhiteSpace \nbefor "+dbug+"\nafter |"+hold+"|");
	if(hold != '') return hold;
	return word;
}
function validate_email_address( address )
{
	//# trim email value
	address = trimWhiteSpace(address);

	//# not present or ""?
	if (!address || (address.length == 0) )
	{
		return( 10 );
	}

	//# contain any wacky chars?
	for( var ii = 0; ii < address.length; ii++ )
	{
		if( address.charCodeAt(ii) > 127 )
		{
  		return( 30 );  //# invalid characters
		}
	}

	//# must have an '@', but it can't be the first or last char
	var pos = address.indexOf('@');  //# returns -1 if not found
	if( (pos <= 0) || (pos >= address.length-1) )
	{
		return( 20 );  //# invalid format
	}

	//# no whitespace, no consecutive dots
	if( address.match(/\s|\.\./) )
	{
		return( 20 );  //# invalid format
	}

	var user_host = address.split('@');
	var user_part = user_host[0];
	var host_part = user_host[1];

	//# the user part can only contain alphanumeric, dot, dash, amp, underbar
	if( user_part.match(/[^a-zA-Z0-9\.\-\_\&]/) )
	{
		return( 30 );  //# invalid characters
	}

	//# the host part can only contain alphanumeric, dot, dash, underbar
	if( host_part.match(/[^a-zA-Z0-9\.\_\-]/)   )
	{
		return( 30 );  //# invalid characters
	}

	//# must be at least 2 characters long
	if( host_part.length < 2 )
	{
		return( 20 );  //# invalid format
	}

	//# the host part must have at least one dot, but it can't be the first or last char
	pos = host_part.indexOf ('.');
	if( (pos <= 0) || (pos >= host_part.length-1) )
	{
		return( 20 );  //# invalid format
	}

	//# TODO: fix this code: it doesn't catch strings which end with a dot or dash!!
	//# Neither the host or user part can start or end with a dot or dash
	if( user_part.match(/^[\.\-]|[\.\-]$/) || host_part.match(/^[\.\-]|[\.\-]$/) )
	{
	  return( 20 );  //# invalid format
	}
	
	return( 0 ); //# appears to be valid
}


