//Static array elements
var formNumbers 	= new Array('Zip', 'Phone', 'Fax');
var formEmail 		= new Array('txtEmail');
var formStates		= new Array('AK','AL','AR','AS','AZ','CA','CO','CT','DC','DE','FL','FM','GA','GU','HI','IA','ID','IL','IN','KS','KY','LA','MA','MD','ME','MH','MI','MN','MO','MP','MS','MT','NC','ND','NE','NH','NJ','NM','NV','NY','OH','OK','OR','PA','PR','PW','RI','SC','SD','TN','TX','UT','VA','VI','VT','WA','WI','WV','WY');


//Function to create an empty error message, for use in displayModalMessage
function errorMessage(errorFields) {
	for(var i in errorFields) {
		try {
			obj = document.getElementById(errorFields[i]['fieldName']);
			obj.value = errorFields[i]['message'];
			errorStyle(obj);
			obj.onfocus = function() {clearErrorStyle(this); this.value = ''};
		} catch (e) {
			alert(e);
		}
	}
	//Send the node to the function that displays everything
	//if(!document.all) {
		displayModalMessage(errorFields);
	//}
	//else {
	//	alert("Please enter all fields!");
	//}
}
/**
 * errorStyle - styles element for error
 * @param object obj element to style
 */
 function errorStyle(obj) {
	obj.style.background = '#ffc';
	obj.style.border = '1px solid #c00';
	obj.style.color = '#f00';
 }

/**
 * clearErrorStyle - clears any error styling
 * @param object obj the element to style
 */
 function clearErrorStyle(obj) {
	obj.style.background = '';
	obj.style.border = '';
	obj.style.color = '';
	obj.onfocus = function(){};
 }

/**
 * validatePhone - validates a phone number passed to it
 * @param string strValue
 * @return boolean true if successful, false if not
 */
function validatePhone(strValue) {
	var returnValue = true;
	strValue = strValue.replace(/\(/g, '');
	strValue = strValue.replace(/\)/g, '');
	strValue = strValue.replace(/-/g, '');
	strValue = strValue.replace(/\./g, '');
	strValue = strValue.replace(/^[\s]+$/, '');
	//First make sure the value isn't empty
	if(strValue == '') {
		returnValue = false;
	} else {
		//Parse out all off the non-number fields in the input value
		//All that SHOULD be left is a number. If the remaining value isn't numeric, return false.
		if(isNaN(strValue)) {
			returnValue = false;
		}
	}
	//Return the status of the field validation
	return returnValue;
}

/**
 * validateText - validates any text
 * @param string strValue
 * @return boolean true if successful, false if not
 */
function validateText(strValue) {
	var whiteSpace = /^[\s]+$/;
	var returnValue = true;
	if(strValue == 'This field is required') {
		return false;
	}
	strValue = strValue.replace(' ', '');
	//Just make sure it isn't empty
	if(strValue == '' || strValue == 'This field is required') {
		returnValue = false;
	}
	//Return the status of the field validation
	return returnValue;
}

/**
 * validateEmail -validates an email value passed to it
 * @param string strValue
 * @return boolean true if successful, false if not
 */
function validateEmail(strValue) {
	var returnValue = true;
	//First make sure the value isn't empty
	if(strValue == '') {
		returnValue = false;
	} else {
		validRegExp = /^[^@]+@[^@]+.[a-z]{2,}$/i;
	   	// search email text for regular exp matches
	    if (strValue.search(validRegExp) == -1) 	{
	      returnValue = false;
	    }
	}
	//Return the status of the field validation
	return returnValue;
}

/**
 * validateFields - gateway field validation function
 */
function validateFields() {
	var sendMail = true;
	var errorFields = new Array();

	objForm = document.getElementById("cForm");
	//Loop through all of the submitted form elements
	for(var i = 0; i < objForm.elements.length; i++)
	{
		//Make sure that the element being passed isnt an empty string, null, or "undefined"
		if(objForm.elements[i].name != ""
			&& objForm.elements[i].name != null
			&& objForm.elements[i].name != "undefined")
		{
			//Create a new variable referencing the form element being inspected
			var objElement = objForm.elements[i];
			//Create a variable holding the fieldValidator attribute of the element being inspected
			var fieldType = objElement.getAttribute("fv");

			//Check the for the type of FieldValidation to run
			switch(fieldType) {

				case "email":
					//If email validation fails, push the name of the element and it's error type on the error array
					if(!validateEmail(objElement.value)) {
						errorFields.push({fieldName:objElement.id, message:'Please enter a valid email address'});
						sendMail = false;
					} else {
						objElement.onfocus = function(){};
						clearErrorStyle(objElement);
					}
				break;

				case "phone":
					//If email validation fails, push the name of the element and it's error type on the error array
					if(!validatePhone(objElement.value)) {
						errorFields.push({fieldName:objElement.id, message:'Please enter a valid phone number'});
						sendMail = false;
					} else {
						objElement.onfocus = function(){};
						clearErrorStyle(objElement);
					}
				break;

				case "text":
					//If email validation fails, push the name of the element and it's error type on the error array
					if(!validateText(objElement.value)) {
						errorFields.push({fieldName:objElement.id, message:'This field is required'});
						sendMail = false;
					} else {
						objElement.onfocus = function(){};
						clearErrorStyle(objElement);
					}

				break;
			}
		}
	}
	//If nothing has tripped up in the looping through submitted values, then send the e-mail
	if(sendMail) {
		sendPosEmail();
	} else {
		errorMessage(errorFields);
	}
}

//Standard function for cleaning input values
function cleanInput(str) {
	//str = str.replace(/&/g, "**am**");
	//str = str.replace(/=/g, "**eq**");
	//str = str.replace(/\+/g, "**pl**");
	str = str.replace(/txt/, '');
	str = str.replace(/opt/, '');
	str = str.replace(/pos/, '');
	return str;
}

function sendPosEmail ()
{
	//Initialize function scope variables
	var strPost 		= '';
	var page 			= "/scripts/xmlHttpRequest.php?contact=true&xml=true";

	//Display the progress bar
	showContactTimer ();

	objForm = document.getElementById("cForm");
	//Loop through the form elements
	for(var i = 0; i < objForm.elements.length; i++) {
		//Make sure that the element being passed isnt an empty string, null, or "undefined"
		if(objForm.elements[i].name != ""
			&& objForm.elements[i].name != null
			&& objForm.elements[i].name != "undefined")
		{
			//Assign each form element to a variable, named objElement
			var objElement = objForm.elements[i];
			//Call the cleanInput function for each value posted to the function
			strVar = cleanInput(objElement.value);
			//Append the string to send to the AJAX function
			strPost = strPost + '&' + objElement.name + '=' + strVar;
		}
	}
	//Call the AJAX request function
	loadXMLPosDoc(page, strPost);

	return false;
}
function showContactTimer () {
	var loader = document.getElementById('loadBar');
	loader.style.display = 'block';
	//sentTimer = setTimeout("hideContactTimer()",6000);
}

function hideContactTimer () {
	var loader = document.getElementById('loadBar');
	var success = document.getElementById('emailSuccess');
	var fieldArea = document.getElementById('cForm');
	var inputs = fieldArea.getElementsByTagName('input');
	var inputsLen = inputs.length;
	var tAreas = fieldArea.getElementsByTagName('textarea');
	var tAreasLen = tAreas.length;
	// Hide the load bar alas! Done Loading
	loader.style.display = "none";
	success.style.display = "block";
	success.innerHTML = '<strong>'+grabPosXML("confirmation")+'</strong>';
	// Now Hijack the form elements
	for ( i=0;i<inputsLen;i++ ) {
		if ( inputs[i].getAttribute('type') == 'text' ) {
			inputs[i].value = '';
		}
	}
	for ( j=0;j<tAreasLen;j++ ) {
		tAreas[j].value = '';
	}




	/* Added by CRC 070504 */
	objForm = document.getElementById('cForm');
	//sobjForm.style.display = 'none';

}

function ajaxContact() {
	var frmEl = document.getElementById('cForm');
	if(frmEl) {
		addEvent(frmEl, 'submit', validateFields, false);
		frmEl.onsubmit = function() { return false; }
	}
}

addEvent(window, 'load', ajaxContact, false);