/*
Error Codes:
Invalid Canada Zip	InvalidZipCA
Invalid US ZIP		InvalidZipUS
Invalid email		InvalidEmail
InvalidPhoneNumber  InvalidPhone
*/

/**
 * errorHandler Should contain a method handleError(errorCode)
 * @param errorHandler the error handler object 
 * @param country the current country
 */
var Validator = function(errorHandler,country)
{
	this.errorHandler = errorHandler;
	this.canadaZipCode = /^\D{1}\d{1}\D{1}\-?\d{1}\D{1}\d{1}$/;
	this.usZipCode = /^\d{5}$/;
	this.email = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9])+$/;
	this.country = country;
	
	this.checkZip = function(value)
	{
		// If the country is canada check for it
		if(this.country && this.country == "ca")
		{
			if(this.canadaZipCode.test(value))
			{
				return true;
			}
			this.errorHandler.handleError('InvalidZipCA');
			return false;
		}
		
		// Else check for US
		if(this.usZipCode.test(value))
		{
			return true;
		}
		this.errorHandler.handleError('InvalidZipUS');
		return false;
	}
	
	this.checkEmail = function(value)
	{
		if(!this.email.test(value))
		{
			this.errorHandler.handleError('InvalidEmail');
			return false;
		}
		return true;
	}
	
	this.checkFirstName = function(value)
	{
		if (value.length < 2 || !goodString(value, alphas + ".- "))
		{
			this.errorHandler.handleError('InvalidFirstName');	
			return false
		}
		return true;
	}
	
	this.checkLastName = function(value)
	{
		if (value.length < 2 || !goodString(value, alphas + ".- "))
		{
			this.errorHandler.handleError('InvalidLastName');	
			return false
		}
		return true;
	}
	
	this.checkAddress = function(value)
	{
		var charsSupported = nums + alphas + ".-,&:# ";
		if(this.country && this.country == "ca") {
			charsSupported = charsSupported + frenchChars;
		}		
		if (value.length < 2 || !goodString(value, charsSupported))
		{			
			this.errorHandler.handleError('InvalidAddress');	
			return false
		}
		return true;
	}
	
	this.checkPhone = function(value)
	{
		if(digitCount(value) != 10 || !goodString(value, nums + "/\-() "))
		{
			this.errorHandler.handleError('InvalidPhone');
			return false;
		}
		return true;
	}
	
	
}


/**
 * The error handler
 * @param errorArray contains a list of error messages for different error codes
 *                   and a default error message if the error codes is not found
 * @param errorDisplay Should be a method to display a message passed as a param
 */
var ErrorHandler = function(errorArray,errorDisplay)
{
	this.errorArray = errorArray;
	this.errorDisplay = errorDisplay;
	
	this.handleError = function(errorCode)
	{
		var errorMsg = this.errorArray[errorCode];
		if(!errorMsg || errorMsg == null)
		{
			errorMsg = errorArray['default'];
			if(!errorMsg || errorMsg == null)
			{
				errorMsg = 'Please check the form before submission';
			}
		}
		this.errorDisplay(errorMsg);
		
	}
}
