/*----------------------------------------------------------------------------
Apache JavaScript Functions

Author:   David Foster
Email:    david@apache.co.uk

Details:  Contains oft-required, project-nonspecific JavaScript functions.
          See I:\Apache\Code\JavaScript\Functions for full documentation.

ToC:      1 - jQuery Preperation
          2 - Apache Functions
----------------------------------------------------------------------------*/

/*----------------------------------------------------------------------------
  ~1 - jQuery Preperation
----------------------------------------------------------------------------*/

try {
	jQuery;
}
catch(error) {
	error = new Error();
	error.message = 'This website requires jQuery. In the \'head\' include file, please reference the latest jQuery script hosted on Google Code.';
	throw(error);
}

jQuery.noConflict();
var $j = jQuery;


/*----------------------------------------------------------------------------
  ~2 - Apache Functions
----------------------------------------------------------------------------*/

$ = 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 hasSubstance(obj) {
	obj = obj + '';
	return (trim(obj) !== '' && obj !== 'null' && obj !== 'undefined');
}

function isEmailAddress(str) {
	return /^[a-zA-Z0-9\._-]+@[a-zA-Z0-9\._-]+\.(\w{2}|(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum|mobi|tel))$/.test(trim(str));
}

function removeClass(el, className) {
	var regex = new RegExp('(^|\\s)' + className + '(\\s|$)');
	el.className = el.className.replace(regex, ' ');
}

function trim(obj) {
	if (typeof obj === 'object') {
		obj.value = obj.value.replace(/^\s{1,}/, '').replace(/\s{1,}$/, '');
		return obj;
	}
	return obj.replace(/^\s{1,}/, '').replace(/\s{1,}$/, '');
}

function validate(el, msg, valid) {
	trim(el);
	if (!valid) {
		alert(msg);
		el.focus();
	}
	return valid;
}