/*----------------------------------------------------------------------------
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
----------------------------------------------------------------------------*/

var $ = 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 embedFlashObject(url, width, height, flashVars) {
	var html = 
		'<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0" width="' + width + '" height="' + height + '">' +
			'<param name="allowScriptAccess" value="sameDomain" />' +
			'<param name="movie" value="' + url + '" />' +
			'<param name="quality" value="high" />' +
			'<param name="bgcolor" value="#FFF" />' +
			'<param name="wmode" value="transparent" />' +
			((flashVars) ? ('<param name="FlashVars" value="' + flashVars + '" />') : '') +
			'<embed src="' + url + '"' + ((flashVars) ? (' flashvars="' + flashVars + '"') : '') + ' quality="high" wmode="transparent" bgcolor="#FFF" width="' + width + '" height="' + height + '" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />' +
		'</object>';
	document.write(html);
}

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 isPostcode(str) {
	return /^(?:GIR 0AA|[A-PR-UWYZ](?:[0-9]{1,2}|(?:[A-HK-Y][0-9]|[A-HK-Y][0-9](?:[0-9]|[ABEHMNPRV-Y]))|[0-9][A-HJKS-UW]) [0-9][ABD-HJLNP-UW-Z]{2})$/.test(trim(str.toUpperCase()));
}

function removeClass(el, className) {
	var regex = new RegExp('(^|\\s)' + className + '(\\s|$)');
	el.className = el.className.replace(regex, ' ');
}

function replaceClass(el, className1, className2) {
	if (hasClass(className1)) {
		removeClass(el, className1);
		addClass(el, className2);
	}
}


function toDashCase(str) {
	return str.toLowerCase().replace(/[^a-zA-Z0-9 ]/g, '').replace(/[ ]+/g, '-');
};


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, clearValueIfInvalid) {
	if (!valid) {
		alert(msg);
		if (clearValueIfInvalid) {
			el.value = '';
		}
		el.focus();
	}
	return valid;
}

// validate is a radio input has been selected
function validateRadio(el, elName, msg) {
	var valid = true;
	var radios = $j('input:radio[name='+elName+']');
	if (!radios.is(':checked')) {
		alert(msg);
		el.focus();
		valid = false;
	}
	return valid;
}


// Validate a date in the format dd/mm/yyyy
function ValidateDdMmYyyyDate(el, fieldName, message) {
	var valid = true, msg;
	if (/^(0[1-9]|1[0-9]|2[0-9]|3[01])\/(0[1-9]|1[012])\/([0-9][0-9][0-9][0-9])$/.test(el.value)) {
		var dd		= el.value.substring(0,2);
		var mm		= el.value.substring(3,5);
		var yyyy	= el.value.substring(6);

		// 31st of a month with 30 days
		if (dd == 31 && (mm == 4 || mm == 6 || mm == 9 || mm == 11)) {
			var month;
			switch (mm) {
				case 4:		month = 'April';			break;
				case 6:		month = 'June';				break;
				case 9:		month = 'September';	break;
				case 11:	month = 'November';		break;
			}
      valid	= false;
			msg		= 'You have entered a day of the 31st. ' + month + ' has only 30 days; please enter a ' +
							'valid date';
    }
		// February 30th or 31st
		else if (dd >= 30 && mm == 2) { 
			day		= (dd == 30) ? dd + 'th' : dd + 'st';
      valid = false;
			msg		= 'You have entered a day of the ' + day + '. February has only 28 days, or 29 days on ' +
							'a leap year; please enter a valid date';
    }
		// February 29th outside a leap year
		else if (mm == 2 && dd == 29 && !(yyyy % 4 == 0 && (yyyy % 100 != 0 || yyyy % 400 == 0))) {
      valid = false;
			msg		=	'You have entered a day of the 29th and a month of February. ' + yyyy + ' is not a ' +
							'leap year, so February has only 28 days; please enter a valid date';
    }
	}
	else {
		valid = false;
		msg		= 'Please enter a valid ' + fieldName;
	}
	return validate(el, msg, valid);
}