var Form_ErrorCount = 0;
var keepErrors = false

function GetElementRight(elem)
{
	xPos = elem.offsetLeft;
	tempEl = elem.offsetParent;
  	while (tempEl != null) {
  		xPos += tempEl.offsetLeft;
	  	tempEl = tempEl.offsetParent;
  	}
	return xPos+elem.offsetWidth;
}

function GetElementLeft(elem)
{
	xPos = elem.offsetLeft;
	tempEl = elem.offsetParent;
  	while (tempEl != null) {
  		xPos += tempEl.offsetLeft;
	  	tempEl = tempEl.offsetParent;
  	}
	return xPos;
}

function GetElementTop(elem)
{
	yPos = elem.offsetTop;
	tempEl = elem.offsetParent;
	while (tempEl != null) {
  		yPos += tempEl.offsetTop;
	  	tempEl = tempEl.offsetParent;
  	}
	return yPos;
}

function NewErrorDiv(id,anchorPoint,type,errorHTML)
{

	CloseBox="<div onclick=\"RemoveError('"+id+"')\" >&nbsp;</div>"
	var ErrorDivs = document.getElementsByName("FormError").length;
	
	var x,y
	if (navigator.userAgent.indexOf("MSIE")>=0)
		y = document.createElement('a');  //terrible, ugly, awful solution... but it works
	else
		y = document.createElement('div');
		

	//build the error balloon based on type
	if(type == 1)
	{
		y.setAttribute("id",id);
		y.setAttribute("Name","FormError");
		y.setAttribute("class","LeftSmall");
		y.style.top= (GetElementTop(anchorPoint)-62)+'px';
		y.style.left= GetElementRight(anchorPoint) +'px';
		
		x = document.createElement('img');
		x.setAttribute("src","images/Left_balloon_short.png");
		y.appendChild(x);
	}
	else if(type == 2)
	{
		y.setAttribute("id",id);
		y.setAttribute("Name","FormError");
		y.setAttribute("class","LeftBalloon");
		y.style.top= (GetElementTop(anchorPoint)-85)+'px';
		y.style.left= GetElementRight(anchorPoint) +'px';
		
		x = document.createElement('img');
		x.setAttribute("src","images/Left_balloon.png");
		y.appendChild(x);

	}
	else if(type == 3)
	{
		y.setAttribute("id",id);
		y.setAttribute("Name","FormError");
		y.setAttribute("class","SmallBalloon");
		y.style.top= (GetElementTop(anchorPoint)-85)+'px';
		y.style.left= (GetElementLeft(anchorPoint)-158) +'px';

		
		x = document.createElement('img');
		x.setAttribute("src","images/Right_balloon_small.png");
		y.appendChild(x);
	}
	
	//add the error message as a span
	x = document.createElement('span');
	x.setAttribute("class","BalloonText");
	x.innerHTML=errorHTML;
	y.appendChild(x);
		
	//tack on the close box
	y.innerHTML = y.innerHTML + CloseBox
	
	
	//add the complete error balloon. (different depending on browser)
	if (navigator.userAgent.indexOf("MSIE")>=0)
	{
		var a = document.createElement('div');
		a.appendChild(y);
		document.getElementById("errorArea").innerHTML += a.innerHTML;
		
		correctPNG(); //This fixes the PNG in IE.
	}
	else
		document.getElementById("errorArea").appendChild(y);



	return;
}

function SetError(arr)
{
	var errorElement = document.getElementById(arr[0]+'err');
	if(errorElement)
	{
		errorElement.childNodes.item(2).innerHTML = arr[3];
	}
	else
	{
		var anchorPoint = document.getElementById(arr[1]);
		errorElement = NewErrorDiv(arr[0]+'err',anchorPoint,arr[2],arr[3]);
	}
	
	//set the remove error property
	var errorElement = document.getElementById(arr[0])
	if (errorElement.type == 'checkbox')
		errorElement.setAttribute("onclick", "RemoveError('"+arr[0]+'err'+"');this.setAttribute('onclick','');");
	if (errorElement.type == 'select-one')
		errorElement.setAttribute("onchange", "RemoveError('"+arr[0]+'err'+"');this.setAttribute('onchange','');");
	else
		errorElement.setAttribute("onKeyPress", "RemoveError('"+arr[0]+'err'+"');this.setAttribute('onKeyPress','');");
	
	//man is IE dumb. it won't reparse on setAttribute... look at the crap I have to do to get this part to work!	
	if (navigator.userAgent.indexOf("MSIE")>=0)
		document.getElementById(arr[0]).parentNode.innerHTML = document.getElementById(arr[0]).parentNode.innerHTML + " ";
	
	return;
}

function RemoveError(id)
{
	
	var errorElement = document.getElementById(id);
	
	if(errorElement)
	{
		if (navigator.userAgent.indexOf("MSIE")>=0)
		{
			document.getElementById("errorArea").removeChild(errorElement);
			document.getElementById("errorArea").innerHTML = document.getElementById("errorArea").innerHTML;
		}
		else
			document.getElementById("errorArea").removeChild(errorElement);
	}
		
	if(document.getElementsByName("FormError").length == 0)
		EnableSubbmission();		
}

function ClearErrors()
{
	var FormErrors = document.getElementsByName("FormError");
	for(var i=FormErrors.length-1;i>=0;i--)
		RemoveError(FormErrors[i].id);
	
	EnableSubbmission();
}


function RequiredFieldValidator(arr) {
	var fieldElement = document.getElementById(arr[0]);
	
	if(fieldElement.type=="checkbox")
	{
		if(!fieldElement.checked)
		{
			SetError(arr);
			Form_ErrorCount++;
			return;
		}
		else if(!keepErrors)
		{
			RemoveError(arr[0]+'err');
			return;
		}
	}
	else
	{
		if(fieldElement.value == null || fieldElement.value == "" || fieldElement.value == arr[4])
		{
			SetError(arr);
			Form_ErrorCount++;
			return;
		}
		else if(!keepErrors)
		{
			RemoveError(arr[0]+'err');
			return;
		}
	}
}

	
function RequiredIFValidator(arr) {

	var fieldElement = document.getElementById(arr[5]);
	
	if(fieldElement.type=="checkbox")
	{
		if(fieldElement.checked)
		{
			RequiredFieldValidator(arr);
			return;
		}
		else if(!keepErrors)
		{
			RemoveError(arr[0]+'err');
			return;
		}
	}
	else
	{
		if(!(fieldElement.value == null || fieldElement.value == "" || fieldElement.value == arr[6]))
		{
			RequiredFieldValidator(arr);
			return;
		}
		else if(!keepErrors)
		{
			RemoveError(arr[0]+'err');
			return;
		}
	}
}
	
function ValidateZipCode(arr){
	var fieldElement;

	fieldElement = document.getElementById(arr[0]);

	if (fieldElement.value.length > 0 && !fieldElement.disabled)
	{
		if (fieldElement.value.length != 5)
		{
			SetError(arr);
			Form_ErrorCount++;
			return;
		}
		else
			 NumValidator(arr);
	}
}

function NumValidator(arr) {
	var fieldElement;
	var div;
	var i;
	var searchstring;
	var x;
	var match;
	var GoodChar = new Array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9")
	
	fieldElement = document.getElementById(arr[0]);
	
	
	searchstring = fieldElement.value;
	fullLength = searchstring.length;

	if (fullLength > 0)
	{
		for (x=0;x<=fullLength;x++) {
			comp=searchstring.substring(x-1,fullLength);
	         
			match=false;
			for (i = 0; i < GoodChar.length; i++) {
	               
					comp=comp.substring(0,GoodChar[i].length);
					if (comp == GoodChar[i]) {
						match=true;
						break;
					}
			}
			if (match != true){
				SetError(arr);
				Form_ErrorCount++;
				return;
			}
		}
	}
}

function PhoneNumber(arr) {
	var fieldElement;
	var div;
	var i;
	var searchstring;
	var x;
	var match;
	var GoodChar = new Array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9" , " ", "-","(",")")
	var digitcount=0;
	
	fieldElement = document.getElementById(arr[0]);
	
	searchstring = fieldElement.value;
	fullLength = searchstring.length;

	if (fullLength > 0)
	{	
		for (x=1;x<=fullLength;x++) {
			comp=searchstring.substring(x-1,fullLength);
	         
			match=false;
			for (i = 0; i < GoodChar.length; i++) {
	               
				comp=comp.substring(0,GoodChar[i].length);
				if (comp == GoodChar[i]) {
					if(i<10) digitcount++;
						
					match=true;
					break;
				}
			}
			if (match != true){
				SetError(arr);
				Form_ErrorCount++;
				return;
			}
		}
		if (digitcount <10 || digitcount >11)
		{
			SetError(arr);
			Form_ErrorCount++;
			return;
		}
	}
	
	if(!keepErrors)
	{
		RemoveError(arr[0]+'err');
		return;
	}
}

function ValidateEmail(arr) {
	var fieldElement;
	var div;
	
	fieldElement = document.getElementById(arr[0]);

	//an empty field does not costitute an invalid email
	if ((fieldElement.value) == "")
	{
		if (!keepErrors)
		{
			document.getElementById(arr[1]).innerHTML = "";
		}
		return;
	}

	if (!emailCheck(fieldElement.value))
	{
		SetError(arr);
		Form_ErrorCount++;
		return;
	}
	else if(!keepErrors)
	{
		RemoveError(arr[0]+'err');
		return;
	}
	
}


/*This script and many more are available free online at
The JavaScript Source!! http://javascript.internet.com

V1.1.3: Sandeep V. Tamhankar (stamhankar@hotmail.com) */
function emailCheck(emailStr) {

	/* The following is the list of known TLDs that an e-mail address must end with. */
	var checkTLD=1;
	var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;

	/* The following pattern is used to check if the entered e-mail address
	fits the user@domain format.  It also is used to separate the username
	from the domain. */
	var emailPat=/^(.+)@(.+)$/;

	/* The following string represents the pattern for matching all special
	characters.  We don't want to allow special characters in the address. 
	These characters include ( ) < > @ , ; : \ " . [ ] */
	var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";

	/* The following string represents the range of characters allowed in a 
	username or domainname.  It really states which chars aren't allowed.*/
	var validChars="\[^\\s" + specialChars + "\]";

	/* The following pattern applies if the "user" is a quoted string (in
	which case, there are no rules about which characters are allowed
	and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
	is a legal e-mail address. */
	var quotedUser="(\"[^\"]*\")";

	/* The following pattern applies for domains that are IP addresses,
	rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
	e-mail address. NOTE: The square brackets are required. */
	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;

	/* The following string represents an atom (basically a series of non-special characters.) */
	var atom=validChars + '+';

	/* The following string represents one word in the typical username.
	For example, in john.doe@somewhere.com, john and doe are words.
	Basically, a word is either an atom or quoted string. */
	var word="(" + atom + "|" + quotedUser + ")";

	// The following pattern describes the structure of the user
	var userPat=new RegExp("^" + word + "(\\." + word + ")*$");

	/* The following pattern describes the structure of a normal symbolic
	domain, as opposed to ipDomainPat, shown above. */
	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");

	/* Finally, let's start trying to figure out if the supplied address is valid. 
	Begin with the coarse pattern to simply break up user@domain into
	different pieces that are easy to analyze. */
	var matchArray=emailStr.match(emailPat);
	if (matchArray==null) 
		return false;
		
		
	var user=matchArray[1];
	var domain=matchArray[2];

	// Start by checking that only basic ASCII characters are in the strings (0-127).
	for (i=0; i<user.length; i++) 
		if (user.charCodeAt(i)>127) 
			return false;
	
	
	for (i=0; i<domain.length; i++) 
		if (domain.charCodeAt(i)>127) 
			return false;

	// See if "user" is valid 
	if (user.match(userPat)==null)
		return false;

	/* if the e-mail address is at an IP address (as opposed to a symbolic
	host name) make sure the IP address is valid. */
	var IPArray=domain.match(ipDomainPat);
	if (IPArray!=null) {

		// this is an IP address
		for (var i=1;i<=4;i++) 
			if (IPArray[i]>255) 
				return false;
	
		//and a valid one
		return true;
	}

	// Domain is symbolic name.  Check if it's valid.	 
	var atomPat=new RegExp("^" + atom + "$");
	var domArr=domain.split(".");
	var len=domArr.length;
	for (i=0;i<len;i++)
		if (domArr[i].search(atomPat)==-1)
			return false;

	/* domain name seems valid, but now make sure that it ends in a
	known top-level domain (like com, edu, gov) or a two-letter word,
	representing country (uk, nl), and that there's a hostname preceding 
	the domain or country. */
	if (checkTLD && domArr[domArr.length-1].length!=2 && domArr[domArr.length-1].search(knownDomsPat)==-1)
		return false;
	
	// Make sure there's a host name preceding the domain.
	if (len<2)
		return false;
	
	// If we've gotten this far, everything's valid!
	return true;
}
	
function Form_FullValidate(vForm) {
    Form_ErrorCount = 0;
    ClearErrors();
    
    //now go through every element and flag all errors
    keepErrors = true
    
    //Check Required Fields
    if (typeof Form_Required != "undefined")
		for ( var i = 0; i < Form_Required.length; i++)
			RequiredFieldValidator(Form_Required[i]);

	//check Dependand requirements
	if (typeof Form_RequiredIF != "undefined")
		for ( var i = 0; i < Form_RequiredIF.length; i++)
			RequiredIFValidator(Form_RequiredIF[i]);

	//check Page_ZipValidators
	if (typeof Page_ZipValidators != "undefined")
		for ( var i = 0; i < Page_ZipValidators.length; i++)
			ValidateZipCode(Page_ZipValidators[i]);
			
	//check for numbers
	if (typeof Page_NumValidators != "undefined")
		for ( var i = 0; i < Page_NumValidators.length; i++)
			NumValidator(Page_NumValidators[i]);
	
		
	//check email
	if (typeof Form_Email != "undefined")
		for ( var i = 0; i < Form_Email.length; i++)
			ValidateEmail(Form_Email[i]);
			
	//check for numbers
	if (typeof Page_PhoneValidators != "undefined")
		for ( var i = 0; i < Page_PhoneValidators.length; i++)
			PhoneNumber(Page_PhoneValidators[i]);
			
	

	//reset the keeperror flag so that corrections can be made
	keepErrors =  false

	//If Page is Valid, SUBMIT IT!!
	if (Form_ErrorCount < 1)
	{
		vForm.submit();
	}
	else
	{
		DisableSubbmission();
	}
}

