// there maybe a conflict with using '$' operator with another library for this page
jQuery.noConflict();

/**
 * When page is loaded
 * - hook validation method
 */
jQuery(document).ready(function() {
	jQuery('#form1').submit(validateContactForm);
});

/**
 * Client side validation
 * - hopefully reduce the number of server side validations needed.
 */
function validateContactForm() {
	shouldSendForm = true;

	jQuery('input.validate_required').each(function() {
		if(!validateRequired(jQuery(this).val())) {
			jQuery(this).addClass('form-validation-error');
			shouldSendForm = false;			// set the error, don't send this form
		}
		else jQuery(this).removeClass('form-validation-error');
	});

	jQuery('input.validate_email').each(function() {
		if(!validateEmail(jQuery(this).val())) {
			jQuery(this).addClass('form-validation-error');
			shouldSendForm = false;			// set the error, don't send this form
		}
		else jQuery(this).removeClass('form-validation-error');
	});

	jQuery('input.validate_phone').each(function() {
		if(!validatePhone(jQuery(this).val())) {
			jQuery(this).addClass('form-validation-error');
			shouldSendForm = false;			// set the error, don't send this form
		}
		else jQuery(this).removeClass('form-validation-error');
	});

	return shouldSendForm;
}

/**
 * validate that this field is an e-mail
 */
function validateEmail(email) {
	var expr = /^[\w\.\-]+@(\w+(-\w+)*\.)+[A-Za-z]+$/;
	return expr.test(email);
}

/**
 * Validate that this field is a phone number
 */
function validatePhone(phone) {
	var expr = /^(\(?\d{3}\)?\s*-?\s*\d{3}[\-\s]*\d{4})$/;
	return expr.test(phone);
}

function validateStateAbbr(state) {
	var expr = /^[A-Z]{2}$/;
	return expr.test(state);
}

/**
 * Zip codes can be formatted to be
 * -in the form of XXXXX-XXXX or XXXXX
 */
function validateZipCode(zip) {
	var expr = /^\d{5}(-?\d{4})?$/;
	return expr.test(zip);
}

/**
 * Make sure the passed field is not blank.
 */
function validateRequired(field) {
	return (field != null && field.length > 0);
}

