/****************************************************************************************************************
1 - Create a Web Form Label Object as following:
	
	<asp:label id="lblErrorMessage" runat="server" CssClass="noVisible"></asp:label>

2 - After the form declaration add the object and validations with this format		

		<script>
			AddValidator("ObjectName","ValidationType","Field Description","FormName");
		</script>
		
		Where:
			ObjectName:			Object ID that is going to be validate.
			ValidationType:		Point 6 contains the allowed values.
			Field Description:	This information will be used to show the message.
			FormName:			Use this field if you want to do different validations into the same form.	
	
		One for each object and validation.
		One object can have more than one validation.
		
3 - Call to the validateForm function on the necessary button:

		onclick="return validateForm('FormName');";
		
		The parameter is used just if a form has different buttons with differents validations and 
		it works in combination with the FormName in the AddValidator call.

4 - Include the following lines in the Styles file:

	.noVisible
	{
		display: none;
	}

	.errorLabels
	{
		font-weight: bold;
		font-size: 8pt;
		color: #ff3333;
	}

5 - Include this field into the html form that will be validated.

	<script language="javascript" src="validator.js" type="text/javascript"></script>


6 - Table of Validation Types

Validation Type						Definition
----------------------------------------------------------------------------------------------------------------
required or req						The field should not be empty.
maxlen=??? or maxlength=???			Checks the length entered data to the maximum. For example, if the maximum 
									size permitted is 25, give the validation descriptor as "maxlen=25".
minlen=??? OR minlength=???			Checks the length of the entered string to the required minimum. example 
									"minlen=5".
alphanumeric OR alnum				Check the data if it contains any other characters other than alphabetic 
									or numeric characters.
num OR numeric						Check numeric data.
alpha OR alphabetic					Check alphabetic data.
email								The field is an email field and verify the validity of the data. 
lt=??? OR lessthan=???				Verify the data to be less than the value passed. Valid only for numeric fields. 
									example: if the value should be less than 1000 give validation description as "lt=1000".
gt=??? OR greaterthan=???			Verify the data to be greater than the value passed. Valid only for numeric fields. 
									example: if the value should be greater than 10 give validation description as "gt=10".
regexp=???							Check with a regular expression the value should match the regular expression.
									example: "regexp=^[A-Za-z]{1,20}$" allow up to 20 alphabetic characters. 
dontselect=??						This validation descriptor is valid only for select input items (lists). 
									Normally, the select list boxes will have one item saying 'Select One' or some thing like that. 
									The user should select an option other than this option. If the index of this option is 0, 
									the validation description should be "dontselect=0"
date								Verify if the field contains a valid Date.										
phone								Verify Phone format number. Just allow numbers or "(" or ")" or "-" or space
time								Verify time
***********************************************************************************************************************************************************************************/
var ErrorString = '';

var validators = new Array;
var index=0;

function validateForm(formName)
{
	var lblErrorMessage = document.getElementById("lblErrorMessage")
	for (i=0;i<=index-1;i++)
	{
		if ( validators[i][3] == formName )
		{
			validate(validators[i][0],validators[i][1],validators[i][2]);
		}	
	}
	lblErrorMessage.innerHTML = ErrorString;
	lblErrorMessage.className = "errorLabels";
	ErrorString='';
	if ( lblErrorMessage.innerHTML == '' )
	{
		//alert('true');
		return true;
	}
	else
	{
		//alert('false');
		return false;					
	}	
}		

function AddValidator(objectId,validation,fieldDesc,formName)
{
	validators[index] = new Array(4);
	validators[index][0] = objectId;
	validators[index][1] = validation;
	validators[index][2] = fieldDesc;
	validators[index][3] = formName;
	index+=1;
}
			
function generateStrErrors(strError)
{
	if ( strError.length > 0 )
	{
		ErrorString += " * " + strError + "<br>";		
	}
}
			
function validate(objID, strValidateStr, strFieldDesc)
{				
	var objValue = document.getElementById(objID);	
	var epos = strValidateStr.search("=");
	var  command  = "";
	var  cmdvalue = "";
	var  strError = "";
	
	if(epos >= 0)
	{
		command  = strValidateStr.substring(0,epos);
		cmdvalue = strValidateStr.substr(epos+1);
	}
	else
	{
	command = strValidateStr;
	}
	switch(command)
	{
		case "req":
		case "required":
		{
			if(eval(objValue.value.length) == 0)
			{
				strError = strFieldDesc + " : Required Field";
				generateStrErrors(strError)
				return;
				
			}//if
			break;
		}//case required
		case "maxlength":
		case "maxlen":
		{
			if(eval(objValue.value.length) >  eval(cmdvalue))
			{
				strError = strFieldDesc + " : "+cmdvalue+" characters maximum ";
				generateStrErrors(strError + "\n[Current length = " + objValue.value.length + " ]")
				return;
			}//if
			break;
		}//case maxlen
		case "minlength":
		case "minlen":
		{
			if(eval(objValue.value.length) <  eval(cmdvalue))
			{
				strError = strFieldDesc + " : " + cmdvalue + " characters minimum  ";
				generateStrErrors(strError + "\n[Current length = " + objValue.value.length + " ]");
				return;
			}//if
			break;
		}//case minlen
		case "alnum":
		case "alphanumeric":
		{
			var charpos = objValue.value.search("[^A-Za-z0-9]");
			if(objValue.value.length > 0 &&  charpos >= 0)
			{
				strError = strFieldDesc +": Only alpha-numeric characters allowed ";
				generateStrErrors(strError + "\n [Error character position " + eval(charpos+1)+"]");
				return;
			}//if
			break;
		}//case alphanumeric
		case "num":
		case "numeric":
		{
			//var charpos = objValue.value.search("[^0-9]");
			//if(objValue.value.length > 0 &&  charpos >= 0)
			if ( isNaN(objValue.value))
			{
				strError = strFieldDesc + ": Only digits allowed ";
				generateStrErrors(strError)
				return;
			}//if
			break;
		}//numeric
		case "alphabetic":
		case "alpha":
		{
			var charpos = objValue.value.search("[^A-Za-z]");
			if(objValue.value.length > 0 &&  charpos >= 0)
			{
				strError = strFieldDesc +": Only alphabetic characters allowed ";
				generateStrErrors(strError + "\n [Error character position " + eval(charpos+1)+"]")
				return;
			}//if
			break;
		}//alpha
		case "alnumhyphen":
		{
			var charpos = objValue.value.search("[^A-Za-z0-9\-_]");
			if(objValue.value.length > 0 &&  charpos >= 0)
			{
				strError = strFieldDesc +": characters allowed are A-Z,a-z,0-9,- and _";
				generateStrErrors(strError + "\n [Error character position " + eval(charpos+1)+"]")
				return;
			}//if
			break;
		}
		case "email":
		{
			if(!emailvalidation(objValue.value))
			{
				strError = strFieldDesc +": Enter a valid Email address ";
				generateStrErrors(strError);
				return;
			}//if
			break;
		}//case email
		case "phone":
		{
		 	if(objValue.value.length > 0)
			{
				var reqExp = "^[0-9\() -]+$";				
				if(!objValue.value.match(reqExp))
				{
					strError = strFieldDesc +": Invalid characters found ";
					generateStrErrors(strError);
					return;
				}//if
			}
			break;
		}//case phone
		case "time":
		{
		 	if(objValue.value.length > 0)
			{
				var reqExp = "^[0-9\:]+$";				
				if(!objValue.value.match(reqExp))
				{
					strError = strFieldDesc +": Invalid characters found ";
					generateStrErrors(strError);
					return;
				}//if
			}
			break;
		}//case time
		case "lt":
		case "lessthan":
		{
			if(isNaN(objValue.value))
			{
				generateStrErrors( strFieldDesc + ": Should be a number ");
				return;
			}//if
			if(eval(objValue.value) >=  eval(cmdvalue))
			{
				strError = strFieldDesc + " : value should be less than "+ cmdvalue;
			}//if
			generateStrErrors(strError);
			return;
			break;
		}//case lessthan
		case "gt":
		case "greaterthan":
		{
			if(isNaN(objValue.value))
			{
				generateStrErrors(objValue.name+": Should be a number ");
				return;
			}//if
			if(eval(objValue.value) <=  eval(cmdvalue))
			{
				strError = strFieldDesc + " : value should be greater than "+ cmdvalue;
				generateStrErrors(strError);
				return;
			}//if
			break;
		}//case greaterthan
		case "regexp":
		{
			//alert('Entro por aqui');
		 	if(objValue.value.length > 0)
			{
				//alert(objValue.value.match(cmdvalue));				
				if(!objValue.value.match(cmdvalue))
				{
					strError = strFieldDesc +": Invalid characters found ";
					generateStrErrors(strError);
					return;
				}//if
			}
			break;
		}//case regexp
		case "dontselect":
		{
			if(objValue.selectedIndex == null)
			{
				alert("BUG: dontselect command for non-select Item");
				return false;
			}
			if(objValue.selectedIndex == eval(cmdvalue))
			{
				strError = strFieldDesc +": Please Select one option ";
				generateStrErrors(strError);
				return;
			}
			break;
		}//case dontselect
		case "date":
		{
			var DateFormatMask ="MM/DD/YYYY";
			var DateOrder ="MDY";
			var DateSeparator = "/";
			arguments.IsValid=true;
			
			strError = strFieldDesc;

			var dtValue = objValue.value;

			if (dtValue=='') {
					// Null dates are allowed
					//generateStrErrors("Invalid date: " + strError +  ". Please enter a date with the format MM/DD/YYYY")
					return;				
			} else {
				var firstSeparator = dtValue.indexOf(DateSeparator);
				var secondSeparator	= firstSeparator + dtValue.substring(firstSeparator + 1).indexOf(DateSeparator) + 1 ;
			// if no separators are present, format is incorrect
				if (firstSeparator < 0 || secondSeparator < 0)
				{
					generateStrErrors("Invalid date: " + strError +  ". Please enter a date with the format MM/DD/YYYY");
					return;
				}
				var dtData = new Array(3);
				dtData[0] = dtValue.substring(0,firstSeparator);
				dtData[1] = dtValue.substring(firstSeparator+1,secondSeparator);
				dtData[2] = dtValue.substring(secondSeparator+1);
				

				for(var i=0; i<=2; i++){
					switch(DateOrder.substring(i,i+1).toUpperCase()){
						case "M":
							mm = dtData[i];
							break;
						case "D":
							dd = dtData[i];
							break;
						case "Y":
							yyyy = dtData[i];
							break;
					}
				}
				
				if(yyyy.length!=4)
				{
					if ( yyyy.length!=2 )
					{
						//alert(1);
						generateStrErrors("Invalid date: " + strError +  ". Please enter a date with the format MM/DD/YYYY")
						return;										
					}
					else
					{
						if ( yyyy > 80 )
						{
							yyyy = eval(yyyy) + eval(1900);
						}
						else
						{
							yyyy = eval(yyyy) + eval(2000);
						}
					}
				} 
				var dtTemp = new Date(yyyy,mm - 1,dd);
				

				if(isNaN(dtTemp)){
					//alert(2);
					generateStrErrors("Invalid date: " + strError +  ". Please enter a date with the format MM/DD/YYYY")
					return;
				}
				
				if((parseInt(mm,10)!=dtTemp.getMonth()+1 ) ||
				(parseInt(dd,10)!=dtTemp.getDate()) ||
				(parseInt(yyyy,10)!=dtTemp.getFullYear())){
					//alert(3);	
					generateStrErrors("Invalid date: " + strError +  ". Please enter a date with the format MM/DD/YYYY")
					return;
				}
				if(dtTemp.getFullYear()<1900){
					//alert(4);
					generateStrErrors("Invalid date: " + strError +  ". Please enter a date with the format MM/DD/YYYY")
					return;
				}				
			}
			objValue.value = mm + DateSeparator + dd + DateSeparator + yyyy;
			break;
		}//case date
	}//switch
	return;
}				

function emailvalidation(str) {

		var at="@"
		var dot="."
		var lat=str.indexOf(at)
		var lstr=str.length
		var ldot=str.indexOf(dot)
		if (str.indexOf(at)==-1){
		   return false
		}

		if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		   return false
		}

		if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		    return false
		}

		 if (str.indexOf(at,(lat+1))!=-1){
		    return false
		 }

		 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		    return false
		 }

		 if (str.indexOf(dot,(lat+2))==-1){
		    return false
		 }
		
		 if (str.indexOf(" ")!=-1){
		    return false
		 }

 		 return true					
	}

