/*
	Format:
		Validate(Field,Type of validation,Alert Label, Mandatory, LengthCheck, LengthAlert)
		1. Field - The field that must be validated. e.g.: document.Form.FieldName
		2. Types - Refer below.
		3. Alert Label - The text that will throw up in the alert.
			Default label is available for type no.6, 7, 9
		4. Mandatory - Some value must be given if a field is mandatory(Refer Step 3).
		5. LengthCheck - Maximum and minumum length of field seperated by ,.
			e.g.: "5,15"
			a. If minimum is not necessary then "0,10"
			b. If maximum is not necessary then "10,0"
		6. LengthAlert - The alert that should pop up when the above condition fails.
		
	Types:
		1. empty.
		2. alphanumeric.
			Allows: a-z,A-Z,0-9
		3. alphabets.
			Allows: a-z,A-Z
		4. numbers.
			Allows: 0-9
		5. float.
			Allows: 0-9,.
		6. mobile/phone.
			Allows: 0-9,-,spaces
		7. email.
		8. locations.
			Allows: a-z,A-Z,0-9,-,_,.,spaces
		8. image.
			Allows: jpg,jpeg,gif
		10. html.
			Allows: html, htm formats.
		11. other format.
			Definition: other format - .FormatType (e.g: other format - csv)
			The above is for checking for other formats. Multiple formats must be seperated
			with a '|' (e.g: other format - csv|exe).
		12. Any other arguement:
			e.g: a-z,0-9,_,spaces,comma,-
				
	Steps in validation:
		1. Check validation type.
		2. Check whether field is mandatory.
		3. Mandatory will be undefined or "" if it is omitted while calling the function.
		4. Check if there is any value in the field.
		5. If there is value then validate.
		6. Check if there is any length validation.

	ASPCAE - Allow Special Characters at the end.
*/
function Validate(TheField,TheType,Label,Mandatory,LengthCheck,LengthAlert)
{
	TrimSpace(TheField)
	if(TheType=="url")
	{
		alert("Validate:\nThe type url has been removed.")
		return true
	}
	if(typeof(TheField)=="undefined")
	{
		alert("Validate:\nField name does not exist.")
		return true
	}
	if(typeof(TheField.value)=="undefined")
	{
		alert("Validate:\nThis field does not support 'value' method.")
		return true
	}
	TheValue=TheField.value
	TheValue=TheValue.replace(/\n/g,"")
	TheValue=TheValue.replace(/\r/g,"")
	TheType=TheType.toLowerCase()
	
	if(TheType=="empty")
	{
		if(!TheValue.match(/^.+$/ig))
		{
			if(typeof(Label)!="undefined")
				alert(Label)
			TheField.focus()
			if(TheField.type!="select-one")
			{
				TheField.select()
			}
			
			return true
		}
		TheExpression=new RegExp(".")
	}
	else if(TheType=="alphabets")
	{
		TheExpression=new RegExp("^[a-z][a-z\\-\\.]*[a-z]|^[a-z]$","gi")
	}
	else if(TheType=="locations")
	{
		TheExpression=new RegExp("^[a-z][a-z0-9\\s\\-\\._]*[a-z]$|^[a-z]$","gi")
	}
	else if(TheType=="alphanumeric")
	{
		TheExpression=new RegExp("^[a-z0-9]+$","gi")
	}
	else if(TheType=="numbers")
	{
		TheExpression=new RegExp("^[\\d]+$","gi")
	}
	else if(TheType=="float")
	{
		TheExpression=new RegExp("^[\\d]+(\\.[\\d]+)?$","gi")
	}
	else if(TheType=="phone" || TheType=="mobile")
	{
		TheExpression=new RegExp("^(\\(?[0-9]+\\)?[\\s\\-])*[0-9]+$","gi")
	}
	else if(TheType=="email")
	{
		if(Label=="")
		{
			Label="Please enter a valid email id."
		}
		TheExpression=new RegExp("^[a-z]([\\-_\\.]?[a-z0-9]+)*@([a-z0-9]+([\\-_][a-z0-9]+)*\\.)+[a-z]{2,}$","gi")
	}
	else if(TheType=="image")
	{
		if(Label=="")
		{
			Label="Please enter a valid image name."
		}
		TheExpression=new RegExp("^[^']+\\.(jpg|jpeg|gif)$","gi")
	}
	else if(TheType=="html")
	{
		TheExpression=new RegExp("^[^']+\\.(htm|html)$","gi")
	}
	else if(TheType.match(/^other format/))
	{
		Format=TheType.replace(/^other format - (.*)$/,"$1")
		TheExpression=new RegExp("\\.("+Format+")$","gi")
	}
	else if(TheType=="regex")
	{
		ThePattern=TheField.getAttribute("Pattern")
		if(ThePattern==null)
		{
			alert("Validation: The field '"+TheField.name+"' does not include the 'Pattern' keyword.")
			return false
		}
		TheExpression=new RegExp(ThePattern,"gi")
	}
	else
	{
		TheType1=TheType.replace(/spaces?/g,"")
		TheType1=TheType1.replace(/commas?/g,"")
		if((!TheType1.match(/[a-z]/)) && TheType1.indexOf("0-9")==-1)
		{
			alert("Validate:\nInvalid parameters.\n"+TheType)
			return true
		}
		TheRegExp=""
		StartString=""
		EndString=""
		
		TheSpValue=TheField.getAttribute("ASPCAE")
		if(TheSpValue==null)
			TheSpValue=""
		else
			TheSpValue=TheSpValue.toLowerCase()
		
			
		AllowedTypes=TheType.toLowerCase().split(",")
		for(j=0;j<AllowedTypes.length;j++)
		{
			if(AllowedTypes[j].match(/[a-z]-[a-z]/) || AllowedTypes[j].match(/[a-z]/))
			{
				if(AllowedTypes[j]=="spaces" || AllowedTypes[j]=="space")
				{
					TheRegExp+="\\\s"
					TheSpValue=TheSpValue.replace(/spaces/,"\\\s")
					TheSpValue=TheSpValue.replace(/space/,"\\\s")
				}
				else if(AllowedTypes[j]=="comma" || AllowedTypes[j]=="commas")
				{
					TheRegExp+=","
					TheSpValue=TheSpValue.replace(/comma/,",")
				}
				else if(AllowedTypes[j]=="dblqt")
				{
					TheRegExp+="\\\""
					TheSpValue=TheSpValue.replace(/dblqt/,"\\\"")
				}
				else if(AllowedTypes[j]=="snglqt")
				{
					TheRegExp+="'"
					TheSpValue=TheSpValue.replace(/snglqt/,"'")
				}
				else
				{
					TheRegExp+=AllowedTypes[j]
					StartString+=AllowedTypes[j]
				}
			}
			else if(AllowedTypes[j]=="0-9")
			{
				TheRegExp+="0-9"
				StartString+="0-9"
			}
			else if(AllowedTypes[j]==".")
			{
				TheRegExp+="\\\."
				TheSpValue=TheSpValue.replace(/\./,"\\\.")
			}
			else if(AllowedTypes[j]=="-")
			{
				TheRegExp+="\\\-"
				TheSpValue=TheSpValue.replace(/\-/,"\\\-")
			}
			else if(AllowedTypes[j]=="&")
			{
				TheRegExp+="\\\&"
				TheSpValue=TheSpValue.replace(/\&/,"\\\&")
			}
			else if(AllowedTypes[j]=="(")
			{
				TheRegExp+="\\\("
				TheSpValue=TheSpValue.replace(/\(/,"\\\(")
			}
			else if(AllowedTypes[j]==")")
			{
				TheRegExp+="\\\)"
				TheSpValue=TheSpValue.replace(/\)/,"\\\)")
			}
			else if(AllowedTypes[j]=="[")
			{
				TheRegExp+="\\\["
				TheSpValue=TheSpValue.replace(/\[/,"\\\[")
			}
			else if(AllowedTypes[j]=="]")
			{
				TheRegExp+="\\\]"
				TheSpValue=TheSpValue.replace(/\]/,"\\\]")
			}
			else if(AllowedTypes[j]=="?")
			{
				TheRegExp+="\\\?"
				TheSpValue=TheSpValue.replace(/\?/,"\\\?")
			}
			else if(AllowedTypes[j]!="")
			{
				TheRegExp+=AllowedTypes[j]
			}
		}
		
		if(TheSpValue!="")
		{
			TheSpValues=TheSpValue.split(",")
			for(j=0;j<TheSpValues.length;j++)
			{
				if(TheSpValues[j]!="")
				{
					EndString+=TheSpValues[j]
				}
			}
			EndString="["+EndString+"]?"
		}
		
		ThePattern="^["+StartString+"]["+TheRegExp+"]*["+StartString+"]"+EndString+"$|^["+StartString+"]"+EndString+"$"
			
		TheExpression=new RegExp(ThePattern,"gi")
	}


	//Finally the checking starts.
	if(typeof(Mandatory)=="undefined" || Mandatory=="")
	{
		if(!TheValue.match(/^$/ig))
		{
			if(!TheValue.match(TheExpression))
			{
				if(typeof(Label)!="undefined")
					alert(Label)
				TheField.focus()
				if(TheField.type!="select-one")
				{
					TheField.select()
				}

				return true
			}
			else
			{
				if(TheType=="url")
				{
					if(TheValue.match(TheExpression)[0].length!=TheValue.length)
					{
						if(typeof(Label)!="undefined")
							alert(Label)
						TheField.focus()
						if(TheField.type!="select-one")
						{
							TheField.select()
						}
						return true
					}
				}
				if(typeof(LengthCheck)!="undefined")
				{
					return CheckLength(TheField,TheValue,LengthCheck,LengthAlert)
				}
			}
		}
	}
	else
	{
		if(!TheValue.match(TheExpression))
		{
			if(typeof(Label)!="undefined")
				alert(Label)
			if(TheField.type!="select-one")
			{
				TheField.select()
			}
			return true

		}
		else
		{
			if(TheType=="url")
			{
				if(TheValue.match(TheExpression)[0].lengh!=TheValue.length)
				{
					if(typeof(Label)!="undefined")
						alert(Label)
					TheField.focus()
					if(TheField.type!="select-one")
					{
						TheField.select()
					}
					return true
				}
			}
			if(typeof(LengthCheck)!="undefined" || LengthCheck=="")
			{
				return CheckLength(TheField,TheValue,LengthCheck,LengthAlert)
			}
		}
	}
	return false
}

function CheckLength(TheField,TheString,TheLength,TheAlert)
{
	TheLength=TheLength.split(",")
	Min=parseInt(TheLength[0])
	Max=parseInt(TheLength[1])
	if(TheString.length<Min)
	{
		alert(TheAlert)
		TheField.focus()
		if(TheField.type!="select-one")
		{
			TheField.select()
		}
		return true
	}
	if(Max!=0 && TheString.length>Max)
	{
		alert(TheAlert)
		TheField.focus()
		if(TheField.type!="select-one")
		{
			TheField.select()
		}
		return true
	}
	return false
}
function validate(FunctionToCall,TheForm)
{
	if(typeof(TheForm)=="undefined")
		TheFormElements=document.forms[0].elements
	else
		TheFormElements=TheForm
		
	for(i=0;i<TheFormElements.length;i++)
	{
		if(TheFormElements[i].getAttribute("ValidationType")!=null)
		{
			ValidationType=TheFormElements[i].getAttribute("ValidationType")
			LengthCheck=TheFormElements[i].getAttribute("LengthCheck")	
			if(LengthCheck==null)
				LengthCheck=""
			LengthAlert=TheFormElements[i].getAttribute("LengthAlert")
			if(LengthAlert==null)
				LengthAlert=""
			if(TheFormElements[i].getAttribute("EmptyLabel")!=null)
			{
				if(TheFormElements[i].getAttribute("InvalidLabel")==null)
				{
					if(Validate(TheFormElements[i],"empty",TheFormElements[i].getAttribute("EmptyLabel"),"",LengthCheck,LengthAlert))
					{
						return false
						break
					}
				}
				else
				{
					if(Validate(TheFormElements[i],"empty",TheFormElements[i].getAttribute("EmptyLabel")))
					{
						return false
						break
					}
				}
			}
			if(TheFormElements[i].getAttribute("InvalidLabel")!=null)
			{
				if(Validate(TheFormElements[i],ValidationType,TheFormElements[i].getAttribute("InvalidLabel"),"",LengthCheck,LengthAlert))
				{
					return false
					break
				}
			}
			
			if(TheFormElements[i].getAttribute("CallNext")!=null)
			{
				TheFn=TheFormElements[i].getAttribute("CallNext")
				TheFn=TheFn.replace(/this\.value/,"'"+TheFormElements[i].value.replace(/'/g,'VALIDATE_SINGLE_QOUTES')+"'")
				if(!eval(TheFn))
				{
					return false
					break
				}
			}
		}
	}
	if(typeof(FunctionToCall)=="undefined" || FunctionToCall=="")
		return true
	else
		return eval(FunctionToCall)
}

//Credit Card Validation
function CheckCreditCard(str,TheAlert)
{
	
	str=str.replace(/VALIDATE_SINGLE_QOUTES/g,"'")
	SecondNumber=false
	NewNumber=""
	CheckSum=0
	for(j=str.length;j>-1;j--)
	{
		TheNumber=parseInt(str.substring(j,j+1))
		if(!isNaN(TheNumber))
		{
			if(SecondNumber)
			{
				NewNumber+=(TheNumber*2)
			}
			else
			{
				NewNumber+=TheNumber
			}
			SecondNumber=(!SecondNumber)
		}
	}
	for(j=NewNumber.length;j>-1;j--)
	{
		TheNumber=parseInt(NewNumber.substring(j,j+1))
		if(!isNaN(TheNumber))
		{
			CheckSum+=TheNumber
		}
	}
	if(CheckSum % 10 !=0)
	{
		if(typeof(TheAlert)=="undefined" || TheAlert=="")
			TheAlert="Invalid card number."
		alert(TheAlert)
		return false
	}
	return true
}


//Mark mandatory fields.
var MarkMandatoryFields=false
var MandatoryMark='<font color="#ff0000">*</font>'
function MarkMandatoryFieldsFn(TheForm)
{
	if(typeof(TheForm.elements)=="undefined")
		TheFormElements=document.forms[0].elements
	else
		TheFormElements=TheForm
	
	for(i=0;i<TheFormElements.length;i++)
	{
		if(TheFormElements[i].getAttribute("EmptyLabel")!=null && MarkMandatoryFields)
		{
			TheParentNode=TheFormElements[i].parentNode
			var MandatoryElem=document.createElement("span")
			MandatoryElem.innerHTML=MandatoryMark
			TheParentNode.appendChild(MandatoryElem)
		}
	}
}


//Give focus to first field.
var GiveFocusToFirstField=true
function GiveFocusToFirstFieldFn(TheForm)
{
	if(typeof(TheForm.elements)=="undefined")
		TheFormElements=document.forms[0].elements
	else
		TheFormElements=TheForm
	
	//alert(TheFormElements.length)

	if(GiveFocusToFirstField)
	{
		for(i=0;i<TheFormElements.length;i++)
		{
			if(TheFormElements[i].name && TheFormElements[i].type!="hidden")
			{
				//alert(TheFormElements[i].name);
				TheFormElements[i].focus()
				break
			}		
		}
	}
}

if(navigator.appName.indexOf("Microsoft")!=-1)
{
	window.attachEvent("onload",MarkMandatoryFieldsFn)
	window.attachEvent("onload",GiveFocusToFirstFieldFn)
}
else
{
	window.addEventListener('load',MarkMandatoryFieldsFn,false)
	window.addEventListener('load',GiveFocusToFirstFieldFn,false)
}

function TrimSpace(vInput)
{
		if (vInput.type=="text")
		{	
			vInput.value=vInput.value.replace(/\s+$/,"")
			vInput.value=vInput.value.replace(/^[\s]+/,"")
		}	
}

