//# TODO: remove comments and "fluff characters" before release
//#
//#----------------------------------------------------------------------------
//#	validate_postal_code
//#
//#	  Parameters:
//#		  postalCode: the postal code (zip) to validate;
//#		  countryCode: the A2 country code whose rules apply;
//#
//#	  Purpose:
//#	  	Validates the format of a postal code. If no country_code,
//#     then uses US and Canada rules. Doesn't check
//#     to see if it's a real postal code, just checks to see that it looks
//#     ok.
//#
//#  	Return:
//#  		0   if valid
//#     -10 if invalid: not present
//#     -20 if invalid: invalid chars present
//#     -30 if invalid: invalid format
//#     
//#----------------------------------------------------------------------------
function validate_postal_code( postalCode, countryCode )
{
    if ( !countryCode ) 
	{
		//# Determine if it is US or Canada
		if ( postalCode.length > 5 ) 
		    countryCode = "CA";
		else 
			countryCode = "US";
	}

	//# not present or ""?
	if ((!postalCode || (postalCode.length == 0)) && (countryCode != "IE"))
	{
		return( -10 );
	}

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

	// postal code format
	var format = new Object();
	// permitted characters
	var chars = new Object();

	// ####################################################################
	// For each country, be sure to assign both format and chars patterns.
	// ####################################################################
	// Use this 9-digit code when everything else can handle it
	format["US"] = "^[0-9]{5}(-[0-9]{4})?$";
	chars["US"] = "^[-0-9]+$";
	// old version:  use the 5 digit code
	// format["US"] = "^[0-9]{5}$";
	// chars["US"] = "^[0-9]+$";
	format["GB"] = "^([a-zA-Z]{1,2}[0-9][0-9A-Za-z]? ?[0-9][A-Za-z]{2})|(BFPO ?\d+)$";
	chars["GB"] = "^[-a-zA-Z0-9 ]+$";
	// Ireland currently uses UK postal codes; may change later.
	// format["IE"] = "^[Dd][0-9]{1,2}[Ww]?$";
	// chars["IE"] = "^[DdWw0-9]+$";
	format["CA"] = "^[a-zA-Z][0-9][a-zA-Z] *[0-9][a-zA-Z][0-9]$";
	chars["CA"] = "^[a-zA-Z0-9 ]+$";

	// If either test is missing, return ok
	if ( ! format[countryCode] || ! chars[countryCode] )
	{
	    return 0 ;
	}
	else
	{
	    if (! postalCode.match(chars[countryCode]))
	    {
		return( -20 );  //# invalid characters
	    }
	    else if (! postalCode.match(format[countryCode]))
	    {
	        return( -30 ); //# invalid format
	    }
		else
		{
			return( 0 ); //# appears to be valid
		}
	}
}

