/*	Form Validation script (c) Jan 2008 by 3 Roads Media (www.3roadsmedia.com)
	This script validates the contact form by doing two things:
		1. Ensuring no required fields are left blank
		2. Ensuring fields are properly filled out; e.g., email address should
			be valid, name should not contain numbers.
*/

function checkForm(theForm) {
	// trim extra whitespace from form inputs so they can be properly checked with regex
	var fname = trim(theForm.name.value);
	var email = trim(theForm.email.value);
	var send2 = trim(theForm.send_to.value);
	var messg = theForm.message.value;
	
	// validate name and email inputs -- name: letters only, email: name@domain.ext format
	var validName = /^([a-zA-Z]+)$|([a-zA-z]+)\s([a-zA-Z]+)$/;
	var validEmail = /^[^@]+@[^@.]+\.[^@]*\w\w$/;
	
	// if name field is empty or if name fails validation, show error
	if (fname == "" || validName.test(fname) != true) {
		showErr("fnErr", "name");
		return false;
	// if email field is empty or if email fails validation, show error
	} else if (email == "" || validEmail.test(email) != true) {
		showErr("emErr", "email");
		return false;
	// if user hasn't chosen a recipient, show error
	} else if (send2 == "Choose One..." || send2 == 0) {
		hideErr();
		document.getElementById("sdErr").style.display = "block";
		return false;
	// if message field is left empty, show error
	} else if (messg =="") {
		showErr("msErr", "message");
		return false;
	}
	return true;
}

function checkForm_join(theForm) {
	var email = trim(theForm.email.value);
	var validEmail = /^[^@]+@[^@.]+\.[^@]*\w\w$/;

	if (email == "" || validEmail.test(email) != true) {
		document.getElementById("emErr").style.display = "block";
		return false;
	}
}

function trim(str) {
	// Special thanks to Breaking Par (www.breakingpar.com) for this function
	var temp = str;
	var obj = /^(\s*)([\W\w]*)(\b\s*$)/;
	if (obj.test(temp)) {
		temp = temp.replace(obj, '$2');
	}
	var obj = /  /g;
	while (temp.match(obj)) {
		temp = temp.replace(obj, " ");
	}
	return temp;
}

// hide all other errors that may be showing, then show the correct error message
function showErr(error, field) {
	hideErr();
	document.getElementById(error).style.display = "block";
	document.getElementById(field).select();
	document.getElementById(field).focus();
}

// hide any other error message that may be showing, so only one message displays at a time
function hideErr() {
	document.getElementById("fnErr").style.display = "none"
	document.getElementById("emErr").style.display = "none"
	document.getElementById("sdErr").style.display = "none"
	document.getElementById("msErr").style.display = "none"
}