//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);
		}
	}
}
/**
 * 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(){};
 }


/**
 * 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();

	obj = document.getElementById("email");
	if(validateEmail(obj.value)) {
		sendEmail();
	} else {
		errorFields.push({fieldName:obj.id, message:'Required'});
		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 sendEmail ()
{
	//Initialize function scope variables
	var strPost 		= '';
	var page 			= "http://acte.org/includes/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 objImgProgress 	= document.getElementById('imgEmailProgress');
	var objH3title = document.getElementById('h3emailSignUp');
	var objEmail = document.getElementById("email");
	var objMessage 		= document.getElementById('emailMessage');
	objForm = document.getElementById('cForm');
	objMessage.style.display = "block";
	objMessage.innerHTML = "<strong style=\"color:#005B9C;\">Thanks for signing up, you will be contacted soon</strong>"
	//objImgProgress.style.display = 'block';
	objH3title.style.display = 'none';
	objEmail.style.display = 'none';
	objForm.style.display = 'none';
	objMessage.style.height = '100px';

	//sentTimer = setTimeout("hideContactTimer()",6000);
}

function hideContactTimer () {
//	var objImgProgress 	= document.getElementById('imgEmailProgress');
//	var objMessage 		= document.getElementById('emailMessage');
//	var objForm 		= document.getElementById('cForm');
//	// Hide the load bar alas! Done Loading
//	objImgProgress.style.display = "none";
//	objMessage.style.display = "block";
//	objMessage.innerHTML = '<strong style="color:#005B9C;">'+grabPosXML("confirmation")+'</strong>';
//
//	/* Added by CRC 070504 */
//	objForm = document.getElementById('cForm');
//	objForm.style.display = 'none';

}

function resetForm() {
	var objImgProgress 	= document.getElementById('imgEmailProgress');
	var objMessage 		= document.getElementById('emailMessage');
	var objH3title		= document.getElementById('h3emailSignUp');
	var objForm 		= document.getElementById('cForm');

	objImgProgress.style.display = 'none';
	objMessage = 'none';
	objForm.style.display = 'block';
	objH3title.style.display = 'block';
}

function ajaxContact() {
	var frmEl = document.getElementById('cForm');
	if(frmEl) {
		addEvent(frmEl, 'submit', validateFields, false);
		frmEl.onsubmit = function() { return false; }
	}
}

function loadXMLPosDoc(url,posData) {
    // branch for native XMLHttpRequest object
    if (window.XMLHttpRequest) {
        pos = new XMLHttpRequest();
        pos.onreadystatechange = processPosChange;
        pos.open("POST", url, true);
		pos.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        pos.send(posData);
    // branch for IE/Windows ActiveX version
    } else if (window.ActiveXObject) {
        pos = new ActiveXObject("Microsoft.XMLHTTP");
        if (pos) {
            pos.onreadystatechange = processPosChange;
            pos.open("POST", url, true);
			pos.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            pos.send(posData);
        }
    }
}

function grabPosXML (tagName) {
	return pos.responseXML.documentElement.getElementsByTagName(tagName)[0].childNodes[0].nodeValue;
}

function processPosChange() {
    // page loaded "complete"
    if (pos.readyState == 4) {

        if (pos.status == 200) {
			setTimeout("hideContactTimer()", 1000);
			if ( grabPosXML("posStatus") == 'NOTOK' ) {
				alert('There were problems Sending Email. Please check back in a couple minutes');
			}
		}
	}
}


var pos; // variable for posting information
addEvent(window, 'load', ajaxContact, false);

