String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.isEmail = function() {
	return /^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$/.test(this.toLowerCase());
}

var contactForm = {
	errors:[],
	init:function(formID) {
		if (!$(formID).length) {
			return false;
		}
		$(formID).submit(function() {
			contactForm.clearErrors();
			if (contactForm.validate()) {
				// allow page to post
				return true;
			} else {
				contactForm.displayErrors();
			}
			return false;
		});
	},
	validate:function() {
		// first name is required
		if (!$("[name='txtFName']").val().trim().length) {
			this.errors["txtFName"] = "Your first name is required.";
		}
		// last name is required
		if (!$("[name='txtLName']").val().trim().length) {
			this.errors["txtLName"] = "Your last name is required.";
		}
		// email is required
		if (!$("[name='txtEMail']").val().trim().length) {
			this.errors["txtEMail"] = "Your email address is required.";
		} else if (!$("[name='txtEMail']").val().trim().isEmail()) {
			// email must be valid
			this.errors["txtEMail"] = "A valid email address is required.";
		}

		// if any errors
		for (i in this.errors) {
			return false;
		}

		return true;
	},
	displayErrors:function() {
		for (el in this.errors) {
			$("[name='"+el+"']").after("<div class=\"error\">"+this.errors[el]+"</div>\n");
		}
	},
	clearErrors:function() {
		this.errors = [];
		$(".error").remove();
	}
};

// Contact and Technical Support
// Sales Contact
contactForm.init("#frmContact");

// Live Software Demonstrations
contactForm.init("#frmQuickContact");

// Free Email Updates
if ($("[name='email']").length) {
var frmEmailUpdates = contactForm;		// this appears to be copying by reference. Not desired. Can't validate both forms on the same page
	frmEmailUpdates.validate = function() {
		// email is required
		if (!$("[name='email']").val().trim().length) {
			this.errors["email"] = "Your email address is required.";
		} else if (!$("[name='email']").val().trim().isEmail()) {
			// email must be valid
			this.errors["email"] = "A valid email address is required.";
		}
	
		// if any errors
		for (i in this.errors) {
			return false;
		}
	
		return true;
	}
	frmEmailUpdates.init("#frmEmailUpdates");
}
