
function IsElementVisible(myElement) {

	var e = myElement;
	var isVisible = 1;

	// initial check before moving through parent nodes
	if (e.id!='')
	{
		if (e.style.display=='none')
		{
			// hidden containing element found!
			isVisible = 0;
		}
	}
	

	while (e.tagName != 'BODY')
	{
		// get parent node
		e = e.parentNode

		//alert(e.className + ":" + e.id + ":" + e.tagName + "*");
		
		// only test elements with id's for display = 'none'
		if (e.id!='')
		{
			if (e.style.display=='none')
			{
				// hidden containing element found!
				isVisible = 0;
			}
		}
	}

	return isVisible


}


function TabToFront(myTab) {


	// loop through all "tabControl" elements
	if (document.getElementsByClassNamex) {

		///////////////////////////////////////////////////////
		// mozilla browsers method
		// loop through all fields with class = valEmail
		///////////////////////////////////////////////////////

		myFields = document.getElementsByClassName('tabActive');
		for (i = 0; i < myFields.length; i++) {
		
			// assign inactive class if not currently clicked id
			if (myFields[i].id != myTab.id) {
				
				// hide tab control
				myFields[i].className = 'tabControl tabInactive';
				
				// hide tab contents
				myContentID = myFields[i].id.toString() + "Content";
				myContent = document.getElementById(myContentID);
				myContent.style.display = "none";
				
			}
		}

	} 
	else {

		////////////////////////////////////////////////////
		// IE method
		// must loop through input tags and then select tags
		////////////////////////////////////////////////////

		// loop input tags
		i = 0;
		a = document.getElementsByTagName("h2");
		while (element = a[i++]) {
			if (element.className.search('tabActive') != -1) {
			
				// assign inactive class if not currently clicked id
				if (element.id != myTab.id) {
					element.className = 'tabControl tabInactive';
					
					// hide tab contents
					myContentID = element.id.toString() + "Content";
					myContent = document.getElementById(myContentID);
					myContent.style.display = "none";
					
					
				}
				
			}
			
		} // end while (input loop)

	} // end of IE method

	// bring active tab to front
	myTab.className='tabControl tabActive';
	
	// bring active content to front
	myContentID = myTab.id.toString() + "Content";
	myContent = document.getElementById(myContentID);
	myContent.style.display = "block";

}

function ConstructTextCounter(myTextArea) {

	/* dynamically create a div as follows:

	<div class='textareacounter' id='<myTextAreaName>Counter'></div>

	*/

	var targetID;
	var newDiv;

	// build target object name and id
	targetID = myTextArea.id.toString() + "Counter";

	// create new div object
	newDiv = document.createElement("div");
	newDiv.id = targetID;
	newDiv.className = 'textareacounter';

	// insert into DOM
	myTextArea.parentNode.appendChild(newDiv);

}


function TextCounter(myTextArea) {

	var targetID;
	var maxLimit;
	var targetObject;
	var charsRemaining;
	var origScrollTop;

	// initial values
	maxLimit = myTextArea.rows;
	targetID = myTextArea.id.toString() + "Counter";
	origScrollTop = myTextArea.scrollTop;

	// get target object
	targetObject = document.getElementById(targetID);
	if (!targetObject)
	{
		return;
	}

	// calculate field length and remaining
	if (myTextArea.value.length > maxLimit) {
		// field is too long, trim it to maximum permitted
		myTextArea.value = myTextArea.value.substring(0, maxLimit);
		
		// ensure scroll position is restored
		myTextArea.scrollTop = origScrollTop;
	}
	else {
		// update charsRemaining 
		charsRemaining = maxLimit - myTextArea.value.length;
		// display results
		targetObject.innerHTML = charsRemaining.toString() + " available characters";

		/*  // this breaks in IE for some stupid reason text content does not populate!
		if (targetObject.innerText) {
			targetObject.innerText = charsRemaining.toString() + " available characters";
		}
		else {
			targetObject.textContent = charsRemaining.toString() + " available characters";
		}
		*/
	}

}

function getLabelForId(id) {  

	// get label text based on id reference in the for attribute

	var label;
	var labels = document.getElementsByTagName('label');  
	var labelText;

	// loop through all labels
	for (var i = 0; i < labels.length; i++) {
		
		// check for for=id match
		if (labels[i].htmlFor == id) {  

			// return innerText for IE or textcontent for Firefox/Safari
			// limit to first 30 characters
			if (labels[i].innerText) {
				labelText = labels[i].innerText;
				return labelText.slice(0,30);
			}
			else {
				labelText = labels[i].textContent;
				return labelText.slice(0,30);
			}  
		}  
	} 
	
	// nothing found
	return "";  
} 

function ChangeLabelColor(id) {  

	// get label object based on id reference and change to required color

	var labels = document.getElementsByTagName('label');  


	// loop through all labels
	for (var i = 0; i < labels.length; i++) {
		
		// check for for=id match
		if (labels[i].htmlFor == id) {  

			// assign new color style to label
			/*labels[i].style.background='#FDDCD5';*/
			labels[i].style.color='#349462';
			
		}  
	} 
	
	// nothing found
	return "";  
} 

function PureInteger(myValue) {
	
	// test for only digits 0-9
	var myRegEx=/^[0-9]+$/;
	var result=myRegEx.test(myValue);
	return result;

}

function Currency(input) {	

	// exit conditions 
	if (isNaN(input)) {
		return "0.00";
	}
	
	if (input=='') {
		return "0.00";
	}
	
	var temp; 
	temp = parseFloat(input);
	temp = temp.toFixed(2);
	return temp;
	
}

function OneDecimal(input) {	

	// exit conditions 
	if (isNaN(input)) {
		return "0.0";
	}
	
	if (input=='') {
		return "0.0";
	}
	
	var temp; 
	temp = parseFloat(input);
	temp = temp.toFixed(1);
	return temp;
	
}

function ValidateRequired(myForm) {

	// scan all valRequired fields for empty content

	var isGood = true;
	var m = '';
	var isEmpty;
	var myFieldType;
	var i;

	if (document.getElementsByClassName) {

		///////////////////////////////////////////////////////
		// mozilla browsers method
		// loop through all fields with class = valRequired
		///////////////////////////////////////////////////////

		myFields = myForm.getElementsByClassName('valRequired');
		for (i = 0; i < myFields.length; i++) {
		
			// only validate field if visible (mozilla works, but not IE 7 and under)
			//if (myFields[i].offsetLeft > 0) {

			// ensure element is visible (cross browser solution)
			if (IsElementVisible(myFields[i])) {

				// assume field is not empty
				isEmpty = false;
	
				// need to slide select since mozilla included type of select (single/multi)
				myFieldType = myFields[i].type;
				myFieldType = myFieldType.slice(0,6);
	
				// check for empty depending on tag type
				if (myFieldType=='select') {
					if (myFields[i].value=='-') {
						isEmpty = true;
					}
				} 
				else {
					if (myFields[i].value=='') {
						isEmpty = true;
					}
				}
	
				// check fields for empty
				if (isEmpty) {
	
					// empty field encountered, raise flag and obtain label text
					isGood = false;
					m = m + getLabelForId(myFields[i].id) + "\n";
	
				}
			
			} // end if visible
			
		}  // for loop
	} 
	else {

		////////////////////////////////////////////////////
		// IE method
		// must loop through input tags and then select tags
		////////////////////////////////////////////////////

		// loop input tags
		i = 0;
		a = myForm.getElementsByTagName("input");
		while (element = a[i++]) {
			if (element.className.search('valRequired') != -1) {
			
				// ensure element is visible
				if (IsElementVisible(element)) {

					// check fields for empty
					if (element.value=='') {
	
						// empty field encountered, raise flag and obtain label text
						isGood = false;
						m = m + getLabelForId(element.id) + "\n";
	
					}
				
				} // end if visible
			} 
		} // end while (input loop)

		// loop select tags
		i = 0;
		a = myForm.getElementsByTagName("select");
		while (element = a[i++]) {
			if (element.className.search('valRequired') != -1) {
			
				// ensure element is visible
				if (IsElementVisible(element)) {

					// check fields for empty
					if (element.value=='-') {
	
						// empty field encountered, raise flag and obtain label text
						isGood = false;
						m = m + getLabelForId(element.id) + "\n";
	
					}
				
				} // end if visible
			} 
		} // end while (input loop)
		
		// loop textarea tags
		i = 0;
		a = myForm.getElementsByTagName("textarea");

		while (element = a[i++]) {
			if (element.className.search('valRequired') != -1) {
				
				// ensure element is visible
				if (IsElementVisible(element)) {
					
					// check fields for empty
					if (element.value=='') {
	
						// empty field encountered, raise flag and obtain label text
						isGood = false;
						m = m + getLabelForId(element.id) + "\n";

					}

				} // end if visible
			} 
		} // end while (input loop)


	} // end of IE method


	if (!isGood) {
		alert("The following required fields are missing: \n\n" + m);
		return false;
	}

	return true;

}

function ValidateEmail(myForm) {

	// scan all valEmail fields for incorrect content

	var isGood = true;
	var isFieldGood;
	var m = '';
	var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
	var i;


	//var isEmpty;
	//var myFieldType;

	if (document.getElementsByClassName) {

		///////////////////////////////////////////////////////
		// mozilla browsers method
		// loop through all fields with class = valEmail
		///////////////////////////////////////////////////////

		myFields = myForm.getElementsByClassName('valEmail');
		for (i = 0; i < myFields.length; i++) {
		
			// ensure email field is not empty
			if (myFields[i].value != '') {

				// test email field
				isFieldGood = (reg.test(myFields[i].value));
	
				// check fields for empty
				if (!isFieldGood) {
	
					// invalid email field encountered, raise flag and obtain label text
					isGood = false;
					m = m + getLabelForId(myFields[i].id) + "\n";
	
				}
			
			}
		}
	} 
	else {

		////////////////////////////////////////////////////
		// IE method
		// must loop through input tags and then select tags
		////////////////////////////////////////////////////

		// loop input tags
		i = 0;
		a = myForm.getElementsByTagName("input");
		while (element = a[i++]) {
			if (element.className.search('valEmail') != -1) {
			
				// ensure email field is not empty
				if (element.value != '') {

					// test email field
					isFieldGood = (reg.test(element.value));
	
					// check fields for empty
					if (!isFieldGood) {
	
						// invalid email field encountered, raise flag and obtain label text
						isGood = false;
						m = m + getLabelForId(element.id) + "\n";
	
					}
				
				}
			} 
		} // end while (input loop)

	} // end of IE method


	if (!isGood) {
		alert("The following email fields are invalid: \n\n" + m);
		return false;
	}

	return true;

}


function ValidateIntNoNeg(myForm) {

	// scan all valRequired fields for empty content

	var isGood = true;
	var m = '';
	var isFieldGood;
	var myFieldType;
	var i;

	if (document.getElementsByClassName) {

		///////////////////////////////////////////////////////
		// mozilla browsers method
		// loop through all fields with class = valRequired
		///////////////////////////////////////////////////////

		myFields = myForm.getElementsByClassName('valIntNoNeg');
		for (i = 0; i < myFields.length; i++) {

			// test field for valide form
			isFieldGood = PureInteger(myFields[i].value);

			if (!isFieldGood) {

				// invalid field encountered, raise flag and obtain label text
				isGood = false;
				m = m + getLabelForId(myFields[i].id) + "\n";

			}
		}
	} 
	else {

		////////////////////////////////////////////////////
		// IE method
		// must loop through input tags and then select tags
		////////////////////////////////////////////////////

		// loop input tags
		i = 0;
		a = myForm.getElementsByTagName("input");
		while (element = a[i++]) {
			if (element.className.search('valIntNoNeg') != -1) {


				// test field for valide form
				isFieldGood = PureInteger(element.value);

				if (!isFieldGood) {

					// invalid field encountered, raise flag and obtain label text
					isGood = false;
					m = m + getLabelForId(element.id) + "\n";

				}

			} 
		} // end while (input loop)


	} // end of IE method


	if (!isGood) {
		alert("The following fields must be non-negative whole numbers: \n\n" + m);
		return false;
	}

	return true;

}


function ValidateMain(myForm) {

	// exit if no DOM support
	if ((!document.getElementById) ||(!document.getElementsByTagName)) {
		alert("Unsupported Browser");
		return false;
	}


	// validate required
	if (!ValidateRequired(myForm)) {
		return false;
	}
	

	// validate valIntNoNeg
	if (!ValidateIntNoNeg(myForm))
	{
		return false;
	}

	// validate valEmail
	if (!ValidateEmail(myForm)) {
		return false;
	}

	// validate nonnegative

	// validate local page
	if (ValidateLocal) {
	
		if (!ValidateLocal()) {
			return false;
		}
	}

	// must be okay
	return true;

	// faking false (blocked from above return)
	alert('Validation passed, simulating failure.');
	return false;
}


function prepValidation() {

	var myForms;
	var i;
	var tempID;

	// ensure DOM exists
	if ((document.getElementById) && (document.getElementsByTagName)) {

		// loop through all form elements 
		myForms = document.getElementsByTagName( 'form' );
		for( i=0; i < myForms.length; i++ ){

			// add submit event only to those with "validate" class name
			if (myForms[i].className.search('validate') != -1) {

				myForms[i].onsubmit = function() {	
					return ValidateMain(this);
				}
			}
		}

		// relabel required elements (input)
		myForms = document.getElementsByTagName('input' );
		for( i=0; i < myForms.length; i++ ){

			// add submit event only to those with "validate" class name
			if (myForms[i].className.search('valRequired') != -1) {

				tempID = myForms[i].id;
				ChangeLabelColor(tempID);

			}
		}

		// relabel required elements (select)
		myForms = document.getElementsByTagName('select' );
		for( i=0; i < myForms.length; i++ ){

			// add submit event only to those with "validate" class name
			if (myForms[i].className.search('valRequired') != -1) {

				tempID = myForms[i].id;
				ChangeLabelColor(tempID);

			}
		}

		// loop through all input elements and search for class = 'valIntNoNeg'
		myForms = document.getElementsByTagName( 'input' );
		for( i=0; i < myForms.length; i++ ){

			// add submit event only to those with "validate" contained within class name
			if (myForms[i].className.search('valIntNoNeg') != -1) {
				myForms[i].onblur = function() {
					
					// replace any non pure integers with zero
					if (!PureInteger(this.value)) {
						this.value=0;
					}
				}
				
				// default empty values to zero
				if (myForms[i].value=='') {
					myForms[i].value="0";
				}
			}
		}
		
		// loop through all input elements and search for class = 'valAutoSubmit'
		myForms = document.getElementsByTagName( 'input' );
		for( i=0; i < myForms.length; i++ ){

			// add submit event only to those with "validate" contained within class name
			if (myForms[i].className.search('valAutoSubmit') != -1) {

				// get type (checkbox)
				myType = myForms[i].type;
				if (myType=='checkbox') {
					myForms[i].onclick = function() {
						// automatically submit when clicked
						this.form.submit();
					}
				}
			}
		}
		
		// loop through all select elements and search for class = 'valAutoSubmit'
		myForms = document.getElementsByTagName( 'select' );
		for( i=0; i < myForms.length; i++ ){

			// add submit event only to those with "validate" contained within class name
			if (myForms[i].className.search('valAutoSubmit') != -1) {

				// get type (checkbox)
				myForms[i].onchange = function() {
					// automatically submit when clicked
					alert('hes');
					this.form.submit();
				}

			}
		}
		
				
		// loop through all input elements and search for class = 'valUppercase'
		myForms = document.getElementsByTagName( 'input' );
		for( i=0; i < myForms.length; i++ ){

			// add submit event only to those with "validate" contained within class name
			if (myForms[i].className.search('valUppercase') != -1) {
				myForms[i].onblur = function() {
					
					// replace contents with uppercase
					this.value=this.value.toUpperCase();
				}
			}
		}

		// loop through all input elements and search for class = 'valTrimNumeric'
		myForms = document.getElementsByTagName( 'input' );
		for( i=0; i < myForms.length; i++ ){

			// add submit event only to those with "validate" contained within class name
			if (myForms[i].className.search('valTrimNumeric') != -1) {
				myForms[i].onblur = function() {
					
					// replace contents with uppercase
					var s = this.value
					while (s.substr(0,1) == '0' && s.length>1) { 
						s = s.substr(1,9999); 
					}
					this.value = s;
				}
			}
		}


		// loop through all input elements and search for class = 'valCurrency'
		myForms = document.getElementsByTagName( 'input' );
		for( i=0; i < myForms.length; i++ ){

			// add submit event only to those with "validate" contained within class name
			if (myForms[i].className.search('valCurrency') != -1) {
				myForms[i].onblur = function() {
					
					// replace contents with uppercase
					this.value=Currency(this.value);
				}
				
				// default empty values to 0.00
				if ((myForms[i].value=='') || (myForms[i].value=='0')) {
					myForms[i].value="0.00";
				}
				
			}
		}


		// loop through all input elements and search for class = 'valOneDecimal'
		myForms = document.getElementsByTagName( 'input' );
		for( i=0; i < myForms.length; i++ ){

			// add submit event only to those with "validate" contained within class name
			if (myForms[i].className.search('valOneDecimal') != -1) {
				myForms[i].onblur = function() {
					
					// replace contents with uppercase
					this.value=OneDecimal(this.value);
				}
				
				// default empty values to 0.00
				if ((myForms[i].value=='') || (myForms[i].value=='0')) {
					myForms[i].value="0.0";
				}
				
			}
		}

		// loop through all input elements and search for class = 'valFocus'
		myForms = document.getElementsByTagName( 'input' );
		for( i=0; i < myForms.length; i++ ){

			// add submit event only to those with "validate" contained within class name
			if (myForms[i].className.search('valFocus') != -1) {
				
				// set focus during load
				myForms[i].focus();
			}
		}

		// loop through all input elements and search for class = 'valCounter'
		myForms = document.getElementsByTagName( 'textarea' );
		for( i=0; i < myForms.length; i++ ){

			// add submit event only to those with "validate" contained within class name
			if (myForms[i].className.search('valCounter') != -1) {

				// Construct counter div immediately below text area
				ConstructTextCounter(myForms[i]);

				// fire function immediately after load to catch pre-populated text
				TextCounter(myForms[i]);
				
				// create event function for onkeydown
				myForms[i].onkeydown = function() {
					TextCounter(this);
				}

				// create event function for onkeydown
				myForms[i].onkeyup = function() {
					TextCounter(this);
				}

			}
		}
		

		// loop through all input elements and search for class = 'tabControl'
		myForms = document.getElementsByTagName( 'h2' );
		for( i=0; i < myForms.length; i++ ){

			// add submit event only to those with "validate" contained within class name
			if (myForms[i].className.search('tabControl') != -1) {
				myForms[i].onclick = function() {
					
					// bring tab to front
					TabToFront(this);
					
				}
			}
		}





	}  // end check DOM
} // end prep Validation



addLoadEvent(prepValidation);

