// JavaScript Document for validating the contact form (#contactForm)

function addContactFormValidation()
{
	//adds validation to any form called #contactForm
	if (document.getElementById("contactForm"))
	{
		document.getElementById("contactForm").onsubmit=function(){return(validateContactForm());};
	}
}

function validateContactForm()
{
	//Must run removeErrorMessages() a couple times to get rid off all the messages for some reason...
	removeErrorMessages();
	removeErrorMessages();
	removeErrorMessages();
	removeErrorMessages();

	var form = document.getElementById("contactForm");
	var isError = false

	//A bit of clean up. Add any fields here to be cleaned up of weird punctuation or white space. Run through cleanOutJunk()
	form.message.value = cleanOutJunk(form.message.value); // without this the form can be submitted with a blank message (mainly if the user accidentally adds one space)

	//Check if all the required fields are filled in
	//****************************************************************************************************

	if (form.name.value === "")
	{
		addErrorMessage(form.name,"Please add your name.");
		isError = true;
	}
	
	
	if ((form.phone.value === "") && (form.email.value === ""))
	{
		addErrorMessage(form.phone,"Please enter a phone number (or email address).");
		addErrorMessage(form.email,"Please enter an email address (or phone number).");
		isError = true;
	}	
	else 
	{
		if (form.phone.value && (!checkInternationalPhone(form.phone.value)))
		{
			addErrorMessage(form.phone,"This phone number does not appear to be in an appropriate format.");
			isError = true;
		}
		if (form.email.value && ((form.email.value === "") || (!isEmail(form.email.value))))
		{
			addErrorMessage(form.email,"This email is not in the proper format (name@provider.com)");
			isError = true;
		}
	}
	
	if (form.message.value === "")
	{
		addErrorMessage(form.message,"Please let us know what we can do for you.");
		isError = true;
	}


	//End checking for filled in fields
	//****************************************************************************************************

	// if there are any errors, then don't send the info...
	if (isError === true) 
	{
		document.getElementById("errorMessageSection").innerHTML = '<p class="message-box error">There were some problems in with the info you provided. Please <a href="#contactForm">go back through the form</a> and fix all the fields with red text below them.</p>';
		return false;
	}
	
	// form is valid! Send info on to the PHP!
	form.validated.value = "true";
	return true;
}

addLoadEvent(addContactFormValidation); // run addValidation() onLoad 