window.onload = function () {
	PreventRedundantHomePageClickthroughs();
	PrependSubHeadingDashes();
	QuoteQTags();
	UnderlineH1s();
	FixIE7ZoomBug();
	FixGuillotineBug();
	ValidateQuoteAndEnquiryForms();
}

// Prevent redundant clickthroughs by converting home page anchors into spans.
// Prevents users clicking through to the home page while on the home page.
function PreventRedundantHomePageClickthroughs() {

	// Return if we're not on the home page
	if (location.pathname !== '/') return;

	// Remove href and title attributes, reset cursor, remove outline on focus and return false on click
	function disableAnchor(a) {
		a.removeAttribute('href');
		a.removeAttribute('title');
		a.style.cursor = 'default';
		a.onclick = function () { return false };
	}

	// Disable logo and home navigation item anchors
	disableAnchor(document.getElementById('logo'));
	disableAnchor(document.getElementById('navHome').getElementsByTagName('a')[0]);
}

/*  Prepends a dash to sub headings. This is achieved through JavaScript in order to hide the dashes
    from SEs, as less weight will be given to heading text were it to include a dash. */

function PrependSubHeadingDashes() {
	var featuresList = document.getElementById('featuresList'),
		featuresListH5,
		i;
	if (!featuresList)  return false;
	featuresListH5 = featuresList.getElementsByTagName('h5');	
	for (i = 0; i < featuresListH5.length; i++) {
		featuresListH5[i].innerHTML = '- ' + featuresListH5[i].innerHTML;
	}
}

function QuoteQTags() {
	var qs = document.getElementsByTagName('q');
	for (var i = 0; i < qs.length; i++) {
		qs[i].innerHTML = '<span class="quoteMark">&quot;</span>' + qs[i].innerHTML +
			'<span class="quoteMark quoteMarkR">&quot;</span>';
	}
}

/*  Underlines H1 tags on destination pages by wrapping a span around heading text. This is done through
    JavaScript for SEO and semantic reasons */

function UnderlineH1s() {
	var body = document.getElementsByTagName('body')[0],
		h1;
	if (body.className.match(/([a-z0-9-_]+)?destination([a-z0-9-_]+)?/i)) {
		h1 = document.getElementsByTagName('h1')[0];
		h1.className = 'spanned';
		h1.innerHTML = '<span>' + h1.innerHTML + '</span>';
	}
}

/* E7 has an annoying bug which causes the rendering engine to fail to zoom background images applied to
   the body. The only workaround is to	create a div element to surround everything and apply a background
   to this. This non-semantic div compromises the integrity of the markup and thus, I have opted to create
   the surrounding div dynamically with JavaScript and apply it only to users browsing in IE7.	*/

function FixIE7ZoomBug() {

	// is IE7?
	if (document.all && navigator.appVersion.indexOf('MSIE 7.') != -1) {

		// Get body, store innerHTML as variable and clear innerHTML and BG image
		var body = document.getElementsByTagName('body')[0],
			bodyInnerHTML  = body.innerHTML;
		body.innerHTML = '',
		body.style.backgroundImage = 'none';

		// Create surrounding div, give ID and append to the DOM
		surroundingDiv = document.createElement('div'),
		surroundingDiv.setAttribute('id','IE7SurroundingDiv');
		body.appendChild(surroundingDiv);

		// Grab viewport within document, style background image and apply HTML
		docSurroundingDiv = document.getElementById('IE7SurroundingDiv');
		docSurroundingDiv.style.background = 'url(../images/bg.jpg) repeat-x top';
		docSurroundingDiv.innerHTML = bodyInnerHTML;
	}

}

/* IE6 and 7 have an annoying bug which occurs when a floated element is defining the height of a
   container. If a link with :hover styling within said container is then hovered upon, the container's
   height drops and becomes defined by the non-floated element nearest the bottom of the container. This
   bug can only tackled with a non-empty element as the last of the container. This would require a
   non-semantic div, thus I have opted to create the clearing div dynamically with JavaScript.
		
   For more info on this bug, see: http://www.positioniseverything.net/explorer/guillotine.html */

function FixGuillotineBug() {
	var featuresList = document.getElementById('featuresList'),
		featuresListLi,
		featuresListDiv,
		i;
	// Continue if document.all is supported, an IE proprietry method, and #featuresList exists 
	if (!document.all || !featuresList) return false;
	featuresListLi = featuresList.getElementsByTagName('li');
	for (i = 0; i < featuresListLi.length; i++) {
		featuresListDiv = featuresListLi[i].getElementsByTagName('div')[0];
		featuresListDiv.innerHTML += '<div style="height:0"><!----></div>';
	}
}

function ValidateQuoteAndEnquiryForms() {
	var quotationForm = document.getElementById('quotationForm'),
		enquiryForm    = document.getElementById('enquiryForm');

	if (!quotationForm && !enquiryForm) return;

	// Quotation and enquiry form fields
	var iFullName = document.getElementById('iFullName'),
		iAddress1   = document.getElementById('iAddress1'),
		iCity       = document.getElementById('iCity'),
		iPostcode   = document.getElementById('iPostcode'),
		iTel        = document.getElementById('iTel'),
		iEmail      = document.getElementById('iEmail');

	// Exclusively quotation form fields
	var sEventType    = document.getElementById('sEventType'),
		sFirstLocation = document.getElementById('sFirstLocation'),
		tOtherLocation = document.getElementById('tOtherLocation'),
		iDateOfTravel  = document.getElementById('iDateOfTravel'),
		tRequirements  = document.getElementById('tRequirements');

	// Exclusively enquiry form fields
	var tEnquiry = document.getElementById('tEnquiry');

	// Contains validation used by both the quotation and enquiry forms
	function ValidateSharedFields() {
		if (!ValidateSubstance(iFullName, 'Please enter your full name')) return false;
		if (!ValidateSubstance(iAddress1, 'Please enter an address line 1 ')) return false;
		if (!ValidateSubstance(iCity, 'Please enter a town/city')) return false;
		if (!ValidateSubstance(iPostcode, 'Please enter a postcode')) return false;
		if (!ValidateSubstance(iTel, 'Please enter a telephone number')) return false;
		if (!ValidateSubstance(iEmail, 'Please enter an email address')) return false;
		if (!ValidateEmail(iEmail, "Please enter a valid email address. It should resemble 'name@company.com'")) return false;
		return true;
	}

	// When the quotation form is submitted, validate fields used by both quotation and enquiry forms by
	// using ValidateSharedFields function, then validate fields exculsively belonging to quotation form.
	if (quotationForm) {
		quotationForm.onsubmit = function () {
			if (!ValidateSharedFields()) return false;
			if (
				sEventType.value == '0' &&
				sFirstLocation.value == '0' &&
				trim(tOtherLocation.value) == '' &&
				trim(tRequirements.value) == ''
			) {
				var msg = 'Please either select an event type, select a first choice location, enter other locations or enter special requirements. This ' +
					'is to give us a better idea of the kind of event you are looking for.';
				return Validate(sEventType, msg, false);
			}
			if (trim(iDateOfTravel.value) != '' && !/^(0[1-9]|[1-2][0-9]|3(0|1))\/(0[1-9]|1[0-2])\/\d{4}$/.test(iDateOfTravel.value)) {
				var msg = "Please enter a valid date of travel in the format 'dd/mm/yyyy'";
				return Validate(iDateOfTravel, msg, false);
			}
			if (trim(iDateOfTravel.value) != '') {
				var today      = new Date(),
					travelDate  = new Date(),
					dateSegment = iDateOfTravel.value.split('/');
				travelDate.setFullYear(dateSegment[2], (dateSegment[1] - 1), dateSegment[0]);
				if (travelDate < today) {
					var msg = 'Please enter a date of travel that is in the future';
					return Validate(iDateOfTravel, msg, false);
				}
			}
			return true;
		}
	}

	// When the enquiry form is submitted, validate fields used by both enquiry and quotation forms by
	// using ValidateSharedFields function, then validate fields exculsively belonging to enquiry form.
	if (enquiryForm) {
		enquiryForm.onsubmit = function () {
			if (!ValidateSharedFields()) return false;
			if (!ValidateSubstance(tEnquiry, 'Please enter your enquiry')) return false;
			return true;
		}
	}
}

// Add functions to the onload event of the window object
function addLoadEvent(func) {
	oldOnload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	}
	else {
		window.onload = function() {
			oldOnload();
			func();
		};
	}
}

function ValidateSubstance(el, msg) {
	trim(el, true);
	return Validate(el, msg, (el.value !== ''));
}

function ValidatePostCode(el, msg) {
	var regex = /^[A-Za-z]{1,2}[\d]{1,2}([A-Za-z])?\s?[\d][A-Za-z]{2}$/;
	return Validate(el, msg, regex);
}

function ValidateNumber(el, msg) {
	var regex = /^[\+\(0-9\)\s\-]{6,20}$/;
	return Validate(el, msg, regex);
}

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);
}

function Validate(el, msg, test) {
	if (typeof test == 'boolean') {
		var valid = test;
	}
	else {
		trim(el, true);
		var valid = test.test(el.value);
	}
	if (!valid) {
		alert(msg);
		if (el) {
			el.focus();
		}
	}
	return valid;
}

function trim(obj, destroy) {
	var regex = /^\s+|\s+$/g;
	if (destroy) {
		obj.value = obj.value.replace(regex, '');
		return;
	}
	return obj.replace(regex, '');
}
