addLoadEvent(function() {
	buttonHover();
});

function $(id) {
	return document.getElementById(id);
}

function addClass(el, className) {
	if (!hasClass(el, className)) el.className += ' ' + className;
}

function addLoadEvent(func) {
	var oldOnload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	}
	else {
		window.onload = function() {
			if (oldOnload) {
				oldOnload();
			}
			func();
		};
	}
}

function buttonHover() {
	var inputs = document.getElementsByTagName('input');

	for (var i = 0; i < inputs.length; i++) {
		if (hasClass(inputs[i], 'button')) {

			inputs[i].onmouseover = function () {
				addClass(this, 'buttonHover');
			};

			inputs[i].onmouseout = function () {
				removeClass(this, 'buttonHover');
			};
		}
	}
}

function hasClass(el, className) {
	var regex = new RegExp('(^|\\s)' + className + '(\\s|$)');
	return regex.test(el.className);
}

function removeClass(el, className) {
	var regex = new RegExp('(^|\\s)' + className + '(\\s|$)');
	el.className = el.className.replace(regex, ' ');
}


/*-------------------------------------------------------------------------------
	Functions used for validation of form fields
-------------------------------------------------------------------------------*/

// Removes leading and trailing whitespace from form fields
function trim(el) {
	el.value = el.value.replace(/^\s+|\s+$/g, '');
	return el;
}

// 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);
	var valid = (typeof test == 'boolean') ? test : test.test(el.value);
	if (!valid) {
		alert(msg);
		if (el) el.focus();
	}
	return valid;
}

// Validate the existence of a value that isn't whitespace
function ValidateSubstance(el, msg) {
	return Validate(el, msg, (el.value !== ''));
}

// Validate the selection of a select element
function ValidateSelection(el, msg) {
	return Validate(el, msg, (el.value !== '0' && el.value !== '00'));
}


// Validate the format of an email address. Regex includes all TLDs as of Q2 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))$/;
	if (!msg) var msg = 'The email address you have entered is invalid.\nIt should resemble \'name@company.com\'';
	return Validate(el, msg, regex);
}


