/****************************************************************************************************************
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.		
match                               Validates values are equal, useful in case you need to validate password entries match.							
                                    AddValidator("ObjectName","match=<field to compare>","Field Description","FormName");

***********************************************************************************************************************************************************************************/
//debugger
var ErrorString = '';

var validators = new Array;
var index=0;
var regExpMail = "^([0-9a-zA-Z]+[-._+&])*[0-9a-zA-Z]+@([-0-9a-zA-Z]+[.])+[a-zA-Z]{2,6}$";
var regExpZip = "^(\d{5}$)|^(\d{5}-\d{4}$)";
function validateForm(formName, AdditionalText)
{
    var lblErrorMessage;
	if (AdditionalText.length>0)
	    lblErrorMessage = document.getElementById(AdditionalText + "lblErrorMessage")
	else
	    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 == '' )
	{   
		return true;		
	}
	else 
	{
		return false;					
	}	
}		
function ValidateQA( fld_drpDownQu, fld_txtQ, fld_txtAnswer)
{
    var  strError = "";
    drpQues = document.getElementById(fld_drpDownQu);
    txtQues = document.getElementById(fld_txtQ);
    txtAns = document.getElementById(fld_txtAnswer);
    
    if(drpQues.options[drpQues.selectedIndex].value == '')
    {
        if(eval(txtQues.value.length) == 0)
        {
            strError = "Please provide a question.";
			generateStrErrors(strError)
			return;
        }
        
        
    }
    if(eval(txtAns.value.length) == 0)
    {
        strError = "Please provide an asnwer to the question.";
		generateStrErrors(strError)
		return;
    }
    
}
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 = "Please provide a valid " + strFieldDesc + ".";
				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 "zip": 
		{ 
		    // USA Regular    -     ^(\d{5}-\d{4}|\d{5}$)
		    // Canada Regular -     ^(\D{1}\d{1}\D{1}\s{1}\d{1}\D{1}\d{1}$)
		    		    
		    var numWithNoDash = objValue.value.replace(/-/, "")
		    
		    if(objValue.value.length < 5 || objValue.value.length >10 ) //CANADA
			{
			    strError =  "Please provide a valid 5-10 character " + strFieldDesc + ".";
			    generateStrErrors(strError);
			    return;
			}
		    //USA - xxxxx-xxx
		    if(objValue.value.length >= 5 && !isNaN(numWithNoDash))
			{ 
			    if( !objValue.value.match(/^(\d{5}-\d{4}|\d{5}$)/i))
			    {
				    strError =  "Please provide a valid 5-10 character " + strFieldDesc + ".";
				    generateStrErrors(strError );
				    return;
				}
				else
				{
				    break;
				}
			}
			//CAN - LNL NLN
			else if(objValue.value.length >= 5 && isNaN(numWithNoDash) )	
			{	
			    if( !objValue.value.match( /^(\D{1}\d{1}\D{1}[\s{0}|\-]\d{1}\D{1}\d{1}$)|(\D{1}\d{1}\D{1}\d{1}\D{1}\d{1}$)/i)  )
			    {
			        strError =  "Please provide a valid 5-10 character " + strFieldDesc + ".";
				    generateStrErrors(strError );
				    return;
				}
				else
				    break;
			}
			
    	   
			break;
		}
		case "questionOpt":
		{
		    var drpDwnQuest = document.getElementById('drpDownQuestion');
	        if(drpDwnQuest.options[drpDwnQuest.selectedIndex].value == 'Other...')
	        {
	           if(eval(objValue.value.length) == 0)
		       {
			       strError = "Please provide a valid " + strFieldDesc + ".";
			       generateStrErrors(strError)
			       return;
    				
		        }    		   	
			}	  
			break; 
		}
		case "ActivationCode":
		{
				if(eval(objValue.value.length) !=  eval(cmdvalue))
			{
				strError =  "Your ActivationCode must be at least 6 characters long.";
				generateStrErrors(strError );
				return;
			}
			break;
		}
		//Case Phone Number 
		case "phone": 
		{
    	    //strip out acceptable non-numeric characters
    	    //Here we put any acceptable character
    	    var strippedPhone = objValue.value.replace(/[\(\)\.\-\_\\\/\ ]/g, '');
    	    //StrippedPhone must be a number.
		    if (isNaN(strippedPhone) || strippedPhone.length != 10) 
			{
			    strError =  "Please provide a valid " + strFieldDesc + ".";
			    generateStrErrors(strError );
			    return;
			}
			break;
		}
		
		//case maxlen
		
		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 ( objValue.value.length == 0 || isNaN(objValue.value))
			{
				strError = "Please provide a valid " + strFieldDesc + ".";
				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 "alnumhyphenperiod": 
		{
			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 "zipcode":
		{
			if(!objValue.value.match(regExpZip))
			{
				strError = "Please provide a valid " + strFieldDesc;
				generateStrErrors(strError);
				return;
			}//if
			break;
		}//case zipcode
		case "email":
		{
			if(!objValue.value.match(regExpMail))
			{
				strError = "Please provide a valid " + strFieldDesc;
				generateStrErrors(strError);
				return;
			}//if
			break;
		}//case email
		
		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( objValue.value.length == 0 || isNaN(objValue.value))
			{
				generateStrErrors("Please provide a valid " + strFieldDesc + ".");
				return;
			}//if
			if(eval(objValue.value) <=  eval(cmdvalue))
			{
				strError = "Please provide a " + strFieldDesc + " greater than "+ cmdvalue;
				generateStrErrors(strError);
				return;
			}//if
			break;
		}//case greaterthan
		case "get":
		case "grOrEqThan":
		{
			if( objValue.value.length == 0 || isNaN(objValue.value))
			{
				generateStrErrors("Please provide a valid " + strFieldDesc + ".");
				return;
			}//if
			if(eval(objValue.value) < eval(cmdvalue))
			{
				strError = "Please provide a " + strFieldDesc + " greater or equal than "+ cmdvalue;
				generateStrErrors(strError);
				return;
			}//if
			break;
		}//case greaterthan
		case "regexp": 
		{
		 	if(objValue.value.length > 0)
			{
				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 = "Please select one option from "  + strFieldDesc + ". ";
				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 
		case "match":
		{

		    var matchValue = document.getElementById(cmdvalue)
		    if (objValue.value != matchValue.value)
		    {
		            strError = "Please enter a valid confirmation e-mail address.";
		            generateStrErrors(strError);
					return;		        
		    }

		    break;
		} // case match
		case "password":
		{

		    var matchValue = document.getElementById(cmdvalue)
		    if (objValue.value != matchValue.value)
		    {
		            strError = "The password and the confirmation password do not match. Please try again.";
		            generateStrErrors(strError);
					return;		        
		    }

		    break;
		} // case password
		case "fromTo":
		{

		    if(objValue.selectedIndex == null)
			{
				alert("BUG: dontselect command for non-select Item");
				return false;
			}
			var matchValue = document.getElementById(cmdvalue)
			if (objValue.selectedIndex > 0 && matchValue.selectedIndex > 0)
			{
			    if(objValue.selectedIndex > matchValue.selectedIndex)
			    {
				    strError = "Please "  + strFieldDesc + ". ";
				    generateStrErrors(strError);
				    return;
			    }
            }
            if (matchValue.selectedIndex > 0 && objValue.selectedIndex < 1)
            {
                strError = "Please "  + strFieldDesc + ". ";
                generateStrErrors(strError);
                return;
            }
			break;
		}//case dontselect
	}//switch
	return;
}				
