window.onload = function () {
	ValidateQuoteForm();
};

function ValidateQuoteForm() {

	// Quotation form
	var quotationForm = document.getElementById('quotationForm');
	if (!quotationForm) return;

	// Quotation form fields
	var inputContactName = document.getElementById('inputContactName'),
		inputPhoneNumber   = document.getElementById('inputPhoneNumber'),
		inputEmail         = document.getElementById('inputEmail'),
		textareaDetails    = document.getElementById('textareaDetails');

	// Validate form fields on quotation form submission
	quotationForm.onsubmit = function () {
		if (!ValidateSubstance(inputContactName, 'Please enter a contact name')) return false;
		if (!ValidateSubstance(inputPhoneNumber, 'Please enter a telephone number')) return false;
		if (!ValidateTelNumber(inputPhoneNumber, 'Please enter a valid telephone number')) return false;
		if (!ValidateSubstance(inputEmail, 'Please enter an email address')) return false;
		if (!ValidateEmail(inputEmail, 'Please enter a valid email address. It should resemble \'name@company.com\'')) return false;
		if (!ValidateSubstance(textareaDetails, 'Please enter details of your transport requirements')) return false;
	
		return true;
	}
}

// Validate the existence of a value that isn't whitespace
function ValidateSubstance(el, msg) {
	return Validate(el, msg, (el.value !== ''));
}

// Validate the format of a telephone number, allowing numbers, pluses, dashes and whitespace, with an overall
// length between six and twenty characters
function ValidateTelNumber(el, msg) {
	var regex = /^[\+\(0-9\)\s\-]{6,20}$/;
	return Validate(el, msg, regex);
}

// Validate the format of an email address. Regex includes all TLDs as of Q1 2008
function ValidateEmail(el, msg) {
	var regex = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*\.(\w{2}|(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum))$/;
	return Validate(el, msg, regex);
}

// Encapsulates shared functionality by all validation functions; test either a boolean or a string against
// a RegEx, and if falsy, alert a message and focus on invalid field
function Validate(el, msg, test) {

	trim(el);

	if (typeof test == 'boolean') {
		var valid = test;
	}
	else {
		var valid = test.test(el.value);
	}

	if (!valid) {
		alert(msg);
		if (el) {
			el.focus();
		}
	}
	return valid;
}

// Removes leading and trailing whitespace from form fields
function trim(obj) {
	obj.value = obj.value.replace(/^\s+|\s+$/g, '');
}