var MSIE = false;

var aweberReq;

function GetXMLRequest()
{
	// Centralized XMLHttpRequest generation code - cross platform compatible
	var xmlrequest = false;
	// Pseudo-standard
	if (window.XMLHttpRequest) {
		try {
			xmlrequest = new XMLHttpRequest();
		} catch(e) {
			xmlrequest = false;
		}
	// MSIE XMLHttpRequest call
	} else if (window.ActiveXObject) {
		try {
        	xmlrequest = new ActiveXObject("Msxml2.XMLHTTP");
      	} catch(e) {
        	try {
          		xmlrequest = new ActiveXObject("Microsoft.XMLHTTP");
        	} catch(e) {
          		xmlrequest = false;
        	}
		}
		if(xmlrequest)
		{
			MSIE = true;
		}
	}
	return xmlrequest;
}

function ShowErrorMessage()
{
	alert("An error occurred when trying to submit the form.");
}

function ValidateFields()
{
	message = false;
	element = false;
	
	visitorNameRegex = /^[a-zA-Z ]+$/; //space intentional, do not remove
	visitorEmailRegex = /^[\w\d]+\@[\w\d\.]+\.[\w\d\.]+$/;
	visitorPhoneRegex = /^.{0,1}\d{3}.{0,2}\d{3}.{0,1}\d{4}$/;
	zipcodeRegex = /^\d{5}$/;
	notesRegex = /http/;
	
	vdform = document.mainform;
	
	if(visitorNameRegex.exec(vdform.visitor.value) == null)
	{
		message = "Please enter your name.";
		element = vdform.visitor;
	}
	else if(visitorEmailRegex.exec(vdform.visitormail.value) == null)
	{
		message = "Please enter a valid e-mail address.";
		element = vdform.visitor;
	}
	else if(visitorPhoneRegex.exec(vdform.phone.value) == null)
	{
		message = "Please enter a valid phone number.";
		element = vdform.phone;
	}
	else if(zipcodeRegex.exec(vdform.zipcode.value) == null)
	{
		message = "Please enter a valid zipcode.";
		element = vdform.zipcode;
	}
	else if(notesRegex.exec(vdform.notes.value) != null) // if it does match - we DON'T want http links in the notes section
	{
		message = "Please do not include URLs in the notes section.";
		element = vdform.notes;
	}
	else if(vdform.notes.value.length <= 0)
	{
		message = "Please provide a brief description of the work you would like done.";
		element = vdform.notes;
	}
	
	if(message || element)
	{
		alert(message);
		element.focus();
		return false;
	}
	else
	{
		return true;
	}
}

function OnSubmit()
{
	if(ValidateFields())
	{
		aweberReq = GetXMLRequest();
		
		function aweberCallback()
		{
			if(aweberReq.readyState == 4)
			{
				document.mainform.submit();
			}
		}
		
		if(aweberReq) {
		
			aweberReq.onreadystatechange = aweberCallback;
			
			// open connections
			aweberReq.open("GET", "aoc-west-aweber.php?name=" + document.mainform.visitor.value + "&from=" + document.mainform.visitormail.value, true);
				
			// send the requests
			if(MSIE) {
				aweberReq.send();
			} else {
				aweberReq.send(null);
			}
		} else {
			ShowErrorMessage();
		}
	}
}