//Creates an ajax object and runs the request
function createRequest(url, func)
{
	try
	{
		request = new XMLHttpRequest();
	}
	catch (trymicrosoft)
	{
		try
		{
			request = new ActiveXObject("Msxm12.XMLHTTP");
		}
		catch (othermicrosoft)
		{
			try
			{
				request = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (failed)
			{
				request = null;
			}
		}
	}

	if (request == null) {
		alert("Error creating request object.");
	} else {
		workRequest(url, func);
	}
}

//Send a new ajax request
function workRequest(url, func)
{
	request.open("GET", url, true);
	request.onreadystatechange = func;
	request.send(null);
}

/* AJAX handlers for the country/state/county fields */

//xml request wrapper
function grabCountiesByStateID(stateID)
{
	url = "/ajax.php?mode=countiesSelect&statecode=" + stateID;
	createRequest(url, updateCounties);
}
//Updates the county list with the results from the AJAX query.
function updateCounties()
{
	if (request.readyState != 4) { return; } // We only care about state 4
	
	var e = document.getElementById("countycode");
	
	for(var index = e.options.length-1; index >= 0; index--)
	{
		e.remove(index);
	}

	useClass(e, requiredClassName, true);
	var parentNode = getParentNode(request.responseText,"counties");
	if (parentNode)
	{
		var blankOption = new Option('',0);
		try { e.add(blankOption, null); } //FF
		catch(ex) { e.add(blankOption); } //IE
		
		for(var i = 0; i < parentNode.childNodes.length; i++)
		{
			var county = parentNode.childNodes.item(i);
			var countyID = county.attributes.getNamedItem('id').value;
			var countyName = county.attributes.getNamedItem('name').value;	
			var newOption = new Option(countyName, countyID);
			
			try { e.add(newOption, null); } //FF
			catch(ex) { e.add(newOption); } //IE
		}
	} else {
		var msg = '';
		var stateSel = document.getElementById('statecode');
		if (stateSel)
		{
			if (stateSel.selectedIndex <= 0) 
				msg = 'Select a state';
			else {
				useClass(e, requiredClassName, false);	//No counties, don't require the field
				msg = 'None';
			} 
		}
		
		var newopt = new Option(msg,0);
		try { e.add(newopt, null); } //FF
		catch(ex) { e.add(newopt); } //IE
	}
	//Force revalidation of the county field
	e.blur();
	checkSubmitButton();
}
//xml request wrapper
function stateValidate(countryID)
{
	url = "/ajax.php?mode=selectstates&countrycode=" + countryID;
	createRequest(url,updateState);
}
//Retrieves a node from the xml tree based on name
function getParentNode(data, nodeName)
{
	if (data.length > 0) {
		var xmlObj = getXMLObj(data);
		var parentNode = xmlObj.getElementsByTagName(nodeName).item(0);
		if (parentNode && parentNode.childNodes.length > 0) {
			return parentNode;
		}
	}
	return null;
}
//Creates a new xml object
function getXMLObj(data)
{
	var xmlObj = null;
	try // Internet Explorer
	{
		xmlObj = new ActiveXObject("Microsoft.XMLDOM");
		xmlObj.async = "false";
		xmlObj.loadXML(data);
	} catch (e) {
		try //Firefox, Mozilla, Opera, etc
		{
			var parser = new DOMParser();
			xmlObj = parser.parseFromString(data, "text/xml");
		} catch(e) {
			alert(e.message);
			xmlObj = null;
		}
	}
	return xmlObj;
}

/* Field validation helpers. */

/* The specific validation functions (e.g. email, phone, etc) are located inside of the homstudy php script. 
 * They are located there to make it easier to update the regular expressions (one spot vs multiple).
 */
var errorClassName = 'inputValidationError';	//Class to apply when there is an error
var goodClassName = 'inputValidationOkay';	//Class to apply when things are okay
var requiredClassName = 'req';			//Class to apply to mark a field as required, update in php if changed here
var validatingAll = false;
//Generic validation function. Expects an element and a regular expression.
function validateGeneric(e,rex)
{
	//Exepects a form element and a regular expression
	var ret = false;
	if (e)
	{
		var waserror = false;

		if (e.value.match(rex)==null) { waserror = true; }

		showErrorClass(e,waserror);	//Toggle the error class
		ret = !waserror;
	} else { /*Invalid element*/ }
	checkSubmitButton();	//Update the submit button
	return ret;
}
//A wrapper that allows a field to be validated only if there is something entered.
//Expects a form element, the secondary function to validate with, and an optional element to make visible on failed validation
function validateOptional(src, func, err)
{
	var ret = true;
	showErrorClass(src,false);
	if (src.value.length > 0) {	ret = func(src); }
	
	if (err) err.style.display = ret ? 'none' : 'block';
	
	return ret;
}
//A wrapper requires a field to have some data and validates it against the passed in function
//Expects a form element, the secondary function to validate with, and an optional element to make visible on failed validation
function validateRequired(src, func, err)
{
	var ret = true;
	showErrorClass(src,false);
	if (src.value.length > 0) { ret = func(src); }
	else {
		//We call this instead of returning false to make sure
		//any extras that validateGeneric does are also called
		ret = validateGeneric(src, /./)
	}
	
	if (err) err.style.display = ret ? 'none' : 'block';
	
	return ret;
}
//onchange event handler for the state list
function stateSelectOnChange(e){
	if (e) {
		grabCountiesByStateID(e.value); //Updates the county list
		return e.blur(); //Causes state field validation
	}
	return false;
}
//Allows toggling of a pass/fail style
function showErrorClass(e, addClass)
{
	if (e)
	{
		useClass(e, errorClassName, addClass);	//Toggles the error class
		useClass(e, goodClassName, !addClass);	//Toggles the good class
	} else { /* Invalid element */ }
}
//Allows addition and removal of a class to an element
function useClass(e, className, add)
{
	if (e)
	{
		if (add)
		{
			//Add the class if it doesn't already exist
			if (!e.className.match(className)) {
				e.className += ' ' + className;
			}
		} else {
			//Remove the class
			e.className = e.className.replace(className,'');
		}
	} else { /* Invalid element */ }
}
//Swaps the enabled/disabled status of the submit button based on current validation states
function checkSubmitButton()
{
	var btn = document.getElementById('inquireSubmit');
	if (btn)
	{
		btn.disabled = !isGoodToSubmit(document.getElementById('inquireform'));
	} else { /* No submit found */ }
}
//Checks all fields to see if they validate okay
function isGoodToSubmit(form)
{
	if (form)
	{
		var isGood = true;
		for (var i = 0; i < form.length; i++) {
			//If there is an onblur event then this needs to be counted as needing validation
			if (form.elements[i].onblur) {
				/*
	 			* If the error class has been applied then we aren't ready to submit
	 			* If the good class has NOT been applied, but the required class is set then we aren't ready to submit
	 			*/
				isGood &= ((form.elements[i].className.indexOf(errorClassName) != -1) ||
					((form.elements[i].className.indexOf(goodClassName) == -1) &&
					(form.elements[i].className.indexOf(requiredClassName) != -1))) ? false : true;
				if (!isGood) break;
			}
		}
		return isGood;
	} else { /* Invalid form */ }
	
	return false;
}
//Runs the validation function (assumed to be called by onblur) for each form element
function checkAll(form)
{
	if (form)
		for(var i = 0; i < form.length; i++)
			if (form.elements[i].onblur) form.elements[i].onblur();
}

setTimeout('checkSubmitButton()', 1000);	//Slight delay so that the element is on the page when the function runs
