/*****************************************************************************
 							GENERIC VALIDATION FUNCTIONS
 *****************************************************************************/
 
 //////////////////////////////////////////////
 // Confirms if the string contains a valid  //
 // Email address							 //
 //////////////////////////////////////////////
function isEmail(string) 
{
	return (string.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) != -1);
}

 //////////////////////////////////////////////
 // Confirms if the string contains a valid  //
 // Phone Number							 //
 //////////////////////////////////////////////
function isPhoneNumber(string)
{
	var sValidCharacters = "+()0123456789 "
	var foundOK = false;

	for ( var i = 0; i < string.length; i++ ) 
	{
		
		var c = string.charAt(i);
		for ( j = 0; j < sValidCharacters.length; j++ )
		{
			var d = sValidCharacters.charAt(j);
			if ( d == c )
			{
				//return false;
				foundOK = true;
			}
		}
		if ( !foundOK )
		return false;
	}
	
	return true;
}

 //////////////////////////////////////////////
 // Confirms if the string contains only     //
 // Numeric values							 //
 //////////////////////////////////////////////
function isNumber(string)
{
	var sValidCharacters = "0123456789";
	var bAllOK = false;

	for ( var i = 0; i < string.length; i++ ) 
	{
		var c = string.charAt(i);
		bAllOK = false;
		for ( j = 0; j < sValidCharacters.length; j++ )
		{
			var d = sValidCharacters.charAt(j);
			if ( d == c )
			{
				bAllOK = true;
			}
		}
		
		if ( !bAllOK )
		{
			return false;
		}
	}
	
	return true;
}

 //////////////////////////////////////////////
 // Confirms if the string is more than or   //
 // equal to the minimum length				 //
 //////////////////////////////////////////////
function isMinLength ( string, minLength )
{
	return ( string.length >= minLength );
}

 //////////////////////////////////////////////
 // Confirms if the string is less than or   //
 // equal to the maximum length				 //
 //////////////////////////////////////////////
function isMaxLength ( string, maxLength )
{
	return ( string.length <= maxLength );
}

 //////////////////////////////////////////////
 // Confirms if the string contains only     //
 // spacial characters          			 //
 //////////////////////////////////////////////
function isBlank( mystring )
{
  for(var i=0; i<mystring.length; i++) {
    var c = mystring.charAt(i);
    if((c!=' ') && (c!='\n') && (c!='\t'))
      return false;
  }
  return true;
}



var myValidationList = new Array();
 /*****************************************************************************
 							GENERIC VALIDATION FUNCTIONS
 *****************************************************************************/
 
 /////////////////////////////////////////////////////////////////////////////
 // Creates a validation entry so that fields								//
 // can be validated            			 								//
 //											 								//
 // validateField ( field_name, field_label, validation_tasks )	//
 //											 								//
 // Possible Values:														//
 //											 								//
 // EMAIL : Runs email validation against the field							//
 // MAXLENGTH,n : Ensures the field does not exceed n Length				//
 // MINLENGTH,n : Ensures the field length is more than or equal to n		//
 // REQUIRED : Ensures a value has been put in the field					//
 // NUMBERS : Ensures the field contains only numeric characters			//
 // TELEPHONE : Ensures the field contains only a telephone number   		//
 // MUSTMATCH,nfield : Ensures the contents of the field match nfield		//
 // NOSPACES : Ensures the field contains no spacial characters				//
 /////////////////////////////////////////////////////////////////////////////
function validateField ( )
{
	
	var args = validateField.arguments;
	
	if ( args.length < 3 )
	{
		alert("You have not specified enough arguments\nThe function call should be in the form of\ncreateValidationOject('FIELDNAME','FIELD LABEL','FIELDVALIDATIONPARAMETERS')");
		return;
	} else if ( args.length > 3 ) {
		alert("You have specified too many arguments\nThe function call should be in the form of\ncreateValidationOject('FIELDNAME','FIELD LABEL','FIELDVALIDATIONPARAMETERS')");
		return;
	} else {
		//First item must be the object name
		var x = args[0];
		var sType = document.getElementsByName(x)[0].type;
		var nCount = document.getElementsByName(x).length;
		
		
		if ( nCount > 1 && (sType == "text" || sType == "select-one" || sType == "select-multiple") )
		{
			alert("There are too many objects on the page with the name '" + args[0] + "'");
			return;
		}
		
		if ( nCount == 0 )
		{
			alert("There are no objects on the page with the name '" + args[0] + "'");
			return;
		}
		
		//Now find out what we need to validate on it
		var validationParams = args[2].split(" ");
		
		if ( isBlank(args[2]) )
		{
			alert("You have not specified any validation parameters for '" + args[0] + "'");
			return;
		}

		
		var myValidationObject = new Object();
		
		myValidationObject.fieldName = args[0];
		myValidationObject.Label = args[1];
		myValidationObject.isEmail = false;
		myValidationObject.maxLength = 0;
		myValidationObject.minLength = 0;
		myValidationObject.isRequired = false;
		myValidationObject.isNumeric = false;
		myValidationObject.isTelephone = false;
		myValidationObject.mustMatch = "";
		myValidationObject.hasErrors = false;
		myValidationObject.allowSpaces = true;
		myValidationObject.ErrorMessage = "";
		myValidationObject.nonErrorCSS = "";
		
		myValidationObject.isCheckBox = false;
		myValidationObject.isMultiSelect = false;
		myValidationObject.isRadio = false;
		myValidationObject.isCheckbox = false;
		myValidationObject.isSingleSelect = false;
		myValidationObject.isGroup = false;
		myValidationObject.requiredCount = 0;
		
		myValidationObject.nonErrorCSS = document.getElementsByName(x)[0].className;
		
		if ( sType == "select-one" )
		{	myValidationObject.isSingleSelect = true; }
		
		if ( sType == "select-multiple" )
		{	myValidationObject.isMultiSelect = true; }
		
		if ( sType == "radio" )
		{	myValidationObject.isRadio = true; }
		
		if ( sType == "checkbox" )
		{	myValidationObject.isCheckbox = true; }
		
		if ( nCount > 1 )
		{	myValidationObject.isGroup = true;}
		
		myValidationObject.validate =  function ( bStopAtFirstError )
		{
			
			//alert("Validating");
			this.ErrorMessage = "";
			
			if ( !this.isGroup )
			{
				if ( this.isEmail && !isEmail(document.getElementsByName(this.fieldName)[0].value) )
				{
					this.ErrorMessage += myValidationObject.Label + " does not contain a valid email address.\n";
					this.hasErrors = true;
				}
				
				if ( this.maxLength > 0 && !isMaxLength(document.getElementsByName(this.fieldName)[0].value, this.maxLength) )
				{
					this.ErrorMessage += myValidationObject.Label + " is too long. It is meant to have a maximum of " + this.maxLength;
					this.ErrorMessage += " characters\n but has " + document.getElementsByName(this.fieldName)[0].value.length;
					this.ErrorMessage += " characters.\n";
					this.hasErrors = true;
				}
				
				if ( this.minLength > 0 && !isMinLength(document.getElementsByName(this.fieldName)[0].value, this.minLength) )
				{
					this.ErrorMessage += myValidationObject.Label + " is too short. It is meant to have a minimum of " + this.minLength;
					this.ErrorMessage += " characters\n but has " + document.getElementsByName(this.fieldName)[0].value.length + " characters.\n";
					this.hasErrors = true;
				}
				
				if ( this.isCheckbox && this.isRequired )
				{
					if ( !document.getElementsByName(this.fieldName)[0].checked )
					{
						if ( myValidationObject.Label != "" && myValidationObject.Label != null)
						{
							this.ErrorMessage += myValidationObject.Label += " must be selected before you are able to continue.\n";
							this.hasErrors = true;
						}
					}
				}
				
				if ( this.isRequired && !this.isCheckBox && isBlank(document.getElementsByName(this.fieldName)[0].value) )
				{
					this.ErrorMessage += myValidationObject.Label + " is a required field.\n";
					this.hasErrors = true;
				}
				
						
				if ( this.isNumeric && !isNumber(document.getElementsByName(this.fieldName)[0].value) )
				{
					this.ErrorMessage += myValidationObject.Label + " must contain only numeric characters (no spaces).\n";
					this.hasErrors = true;
				}
				
				if ( this.isTelephone && !isPhoneNumber(document.getElementsByName(this.fieldName)[0].value) )
				{
					this.ErrorMessage += myValidationObject.Label + " must be a telephone number.\n";
					this.hasErrors = true;
				}
				
				if ( this.mustMatch.length > 0 )
				{
					if ( document.getElementsByName(this.fieldName)[0].value != document.getElementsByName(this.mustMatch)[0].value )
					{
						this.ErrorMessage += myValidationObject.Label + "s do not match.\n";
						this.hasErrors = true;
					}
				}
				
				if ( !this.allowSpaces && isBlank(document.getElementsByName(this.fieldName)[0].value) && document.getElementsByName(this.fieldName)[0].value != "" )
				{
					this.ErrorMessage += myValidationObject.Label + " does allow any spacial characters.\n";
					this.hasErrors = true;
				}
				
				if ( bStopAtFirstError )
				{
					document.getElementsByName(this.fieldName)[0].focus();
				}
				
			} else {
				//This is a group so will either be a checkbox or a radio list
				if ( this.isRequired )
				{
					//alert("Validating " + this.Label);
					var checkCount = 0;
					for ( n=0; n<document.getElementsByName(this.fieldName).length; n++ )
					{
						if ( document.getElementsByName(this.fieldName)[n].checked )
						{ checkCount ++; }
						
						//alert(document.getElementsByName(this.fieldName)[n].checked);
						
					}
					
					//alert(checkCount);
					//alert(this.Label);
					
					if ( checkCount < this.requiredCount )
					{
						this.ErrorMessage += "You must select atleast " + this.requiredCount + " items for " + myValidationObject.Label + ".\n";
						this.hasErrors = true;
					}
				}
				
				if ( bStopAtFirstError )
				{
					document.getElementsByName(this.fieldName)[0].focus();
				}

			}
			
			if ( isBlank(this.ErrorMessage) )
			{
				this.hasErrors = false;
			}
		
		}
		

	
		
		



		for ( i=0; i<validationParams.length; i++ )
		{
			switch ( validationParams[i] )
			{
				case "EMAIL": 
					myValidationObject.isEmail = true; 
					break;
				case "REQUIRED": 
					myValidationObject.isRequired = true; 
					break;
				case "NUMBERS": 
					myValidationObject.isNumeric = true; 
					break;
				case "TELEPHONE": 
					myValidationObject.isTelephone = true; 
					break;
				case "NOSPACES":
					myValidationObject.allowSpaces = false;
					break;
				default: 
					if ( validationParams[i].indexOf("MINLENGTH,") == -1 && validationParams[i].indexOf("MAXLENGTH,") == -1 && validationParams[i].indexOf("MUSTMATCH,") == -1 && validationParams[i].indexOf("REQUIRED,") == -1 )
					{
						alert("'" + validationParams[i] + "' is not a valid validation parameter");
					}
			}
			
			if ( validationParams[i].indexOf("MINLENGTH") != -1 )
			{
				var minLengthParams = validationParams[i].split(",");
				myValidationObject.minLength = minLengthParams[1];
			}
			
			if ( validationParams[i].indexOf("MAXLENGTH") != -1 )
			{
				var maxLengthParams = validationParams[i].split(",");
				myValidationObject.maxLength = maxLengthParams[1];
			}
			
			if ( validationParams[i].indexOf("MUSTMATCH") != -1 )
			{
				var mustMatchParams = validationParams[i].split(",");
				myValidationObject.mustMatch = mustMatchParams[1];
			}
			
			if ( validationParams[i].indexOf("REQUIRED") != -1 )
			{
				var reqParams = validationParams[i].split(",");
				myValidationObject.requiredCount = reqParams[1];
				myValidationObject.isRequired = true;
			}
		}
		
	}
	
		myValidationList.push(myValidationObject);
}

//bStopAtFirstError, ExecuteOnCompletion, newErrorClass, oldErrorClass
function doValidation()
{
	
	var bStopAtFirstError = false;
	var bExecuteOnComplete = false;
	var bApplyErrorClass = false;
	var sExecuteString = "";
	var newErrorClass = "";
	
	if ( doValidation.arguments.length > 0 )
	{
		if ( doValidation.arguments[0] == true )
		{
			bStopAtFirstError = true;
		}
		
		if ( doValidation.arguments.length > 1 && !isBlank(doValidation.arguments[1]) )
		{
			bExecuteOnCompletion = true;
			sExecuteString = doValidation.arguments[1];
		}
		
		if ( doValidation.arguments.length > 2 && !isBlank(doValidation.arguments[2]) )
		{
			bApplyErrorClass = true;
			newErrorClass = doValidation.arguments[2];
		}

	}
	
	var sErrorList = "";
	
	for ( i = 0; i < myValidationList.length; i++ )
	{
		
		myValidationList[i].validate(bStopAtFirstError);
		
		if ( myValidationList[i].hasErrors )
		{
			sErrorList += " - " + myValidationList[i].ErrorMessage;
			
			if ( bApplyErrorClass )
			{
				document.getElementsByName(myValidationList[i].fieldName)[0].className = newErrorClass;
			}
			
			if ( bStopAtFirstError )
			{
				break;
			}
		} else {
		
			if ( bApplyErrorClass )
			{
				document.getElementsByName(myValidationList[i].fieldName)[0].className = myValidationList[i].nonErrorCSS;
			}
		
		}
	}
	
	if ( sErrorList.length > 0 )
	{
		alert("The following field(s) require your attention:-\n\n" + sErrorList);
		return false;
	} else {
  	return true;
	}

}
