/* Helper functions */
DHTML = {
	htmlIDs: {
		browse: 'browse-by-sector',
		specialToggle: 'form-container-qs-postcode-toggle' /* This one causes the Go button to scoot across */
	}
};

// Set global browser boolean flags
document.isIE	= document.all;
document.isIE6	= document.isIE 	&& document.implementation;
document.isIE5	= document.isIE 	&& window.print 		&& !document.isIE6;
document.isIEDOM2 = document.isIE5 	|| document.isIE6;
document.isIE4	= document.isIE 	&& !document.isIEDOM2 		&& navigator.cookieEnabled;
document.isIE3	= document.isIE 	&& !document.isIE4 		&& !document.isIEDOM2;
document.isNS	= navigator.mimeTypes 	&& !document.isIE;
document.isNS3	= document.isNS 	&& !navigator.language;
document.isNS4	= document.layers;
document.isNS6	= document.getElementById && !document.isIE;
document.isNS7	= document.isNS6;
document.isNS71	= document.designMode;
document.isNSDOM2 = document.isNS6;
document.isDOM2	= document.isIEDOM2 	|| document.isNSDOM2;
document.isSafari = (navigator.userAgent.indexOf("Safari") != -1);

// Add arbitrary functions to an onsubmit
DHTML.AddOnsubmitToElem = function(elem, func, eventType) {
	if (typeof eventType == "undefined") eventType = "onsubmit";
	var arrName = eventType + "A";
	// Check if onsubmitArray exists
	if (typeof elem[arrName] == "undefined") {
		elem[arrName] = new Array();
		if (typeof elem.onsubmit != "undefined") {
			elem[arrName][0] = elem.onsubmit;
		}
	}
	elem[arrName].push(func);
	elem[eventType] = function() {
		var retVal = true;
		for (var i=0; i < elem[arrName].length; i++) {
			var f = elem[arrName][i];

			// Call f, as if it were a method of the element i.e. the element is the "this"
			if ((f != null) && (typeof f != "undefined")) {
				var retSingle = f.call(elem);
				if (typeof retSingle == "boolean") retVal = retVal && retSingle;
				if (!retVal) return false;
			}
		}
		return retVal;
	};

}

// Toggle the appearance or disappearance of an element
DHTML.toggleAnotherElement = function(pageLoading) {

	var thisID = "";
	if(typeof this.id == "undefined") {
		thisID = this.event.srcElement.id;
	} else {
		thisID = this.id;
	}


	var thisElem = $(thisID);
	var toggle = thisElem.checked;

	var thatElem = $(thisID.replace(/-toggle/,""));

	if (thatElem == null) { return false; }

	// Called with pageLoading, or with an event?
	if (typeof pageLoading != "boolean") pageLoading = false;

	// On page loading - don't hide if URL contains "&r_pc=1"
	if (typeof thisElem.urlForcesShow == "undefined") {
		thisElem.urlForcesShow = (window.location.search.indexOf("r_pc=1") != -1);
	} else {
		thisElem.urlForcesShow = false;
	}

	// Move either:
	// 	when a non-pageloading event
	//	OR
	//	when a pageloading event that's covering up the postcode box
	
		if (!pageLoading || (pageLoading && !toggle)) {
			if (thisElem.id == DHTML.htmlIDs.specialToggle) DHTML.specialToggle.moveGo(thisElem.form,toggle);
		}

		if (thisElem.tagName == "A" ) {
			DHTML.specialToggle.clickOnA(thatElem,pageLoading);
			// Prevent page from loading
			return false;
		} else {
			thatElem.style.visibility = (toggle ? "" : "hidden");
			// Don't prevent checkbox clicking
			return true;
		}
	return false;
}

DHTML.specialToggle = {};

DHTML.specialToggle.clickOnA = function(spanElem,pageLoading) {
	/* Special-case complication:
		If this is an anchor, it won't have the state record that
		a checkbox will have.
		So:
			on page loading, reveal if there's a URL.my_postcode
			after that, toggle */

	/* if (window.location.search.search(/[?|&]sort=[a|1]/i) != -1) {
		alert("Not sorting by postcode");
	} */
	if (pageLoading) {
		if (window.location.search.search(/my(_|%5f)postcode=[a-z]/i) != -1) {
			spanElem.style.visibility = "";
		} else {
			spanElem.style.visibility = "hidden";
		}
		// thatElem.style.display = "none";
	} else {
		if(spanElem.style.visibility == "hidden") {
			spanElem.style.visibility = "";
		}
		// Effect.BlindDown(thatElem);
	}
}

// Move the "Go" button when the header form is toggled
DHTML.specialToggle.moveGo = function(formElem, moveToRight) {
	var dist = ((moveToRight-0.5)*2) * 160;
	var inputs = formElem.getElementsByTagName("input");
	for (var i = 0; i < inputs.length; i++) {
		if (inputs[i].className == "gobutton") {
			new Effect.MoveBy(inputs[i], 0, dist, {duration: 0.05 });
		}
	}
}

// Old-version Safari's front-page sectors leave a lot to be desired
DHTML.fixSectorsForSafari = function() {
	if(document.isSafari) {
		var box = document.getElementById(DHTML.htmlIDs.browse);
		var sectors = box.getElementsByTagName("LI");
		for (var i = 0; i < sectors.length; i=i+3) {
			sectors[i].parentNode.insertBefore(document.createElement("BR"), sectors[i]);
		}
	}
}

DHTML.submitIfEnter = function(inputElem) {
	if(window.event && (window.event.keyCode == 13)) {
		if (inputElem.form.onsubmit()) {
			inputElem.form.submit();
		}
		return false;
	}
	return true;
}

/* Postcode functions */
Postcode = {
	pcText: 'Enter postcode',
	pcClass: 'postcode-to-register'
};

/* Validate functions */
Validate = {
	postcodeRe: /^\s*[A-Z]([A-Z]?[0-9]{1,2}|[0-9][A-Z]|[A-Z][0-9][A-Z])\s*[0-9][A-BD-HJLNP-UW-Z]{2}\s*$/,
	notEmptyRe: /\S+/
};

Postcode.registerAsPostcode = function(pcID) {

	if ($(pcID).value == "") {
		$(pcID).value = Postcode.pcText;
	}

	$(pcID).onfocus = function(elem) {
		Postcode.clearPostcodeIfDummy(this)
	};

	DHTML.AddOnsubmitToElem($(pcID).form,$(pcID).onfocus);
}


Validate.FormPostcode = function(formElem) {
	if (typeof formElem == "undefined") {
		formElem = this;
	}
	var postcodeArray = document.weedOutFormChildren(formElem,document.getElementsByClassName("postcode"));
	for (var i = 0; i < postcodeArray.length; i++) {
		var pc = postcodeArray[i].value.toUpperCase();
		if((pc.search(Validate.postcodeRe) == -1) && (pc.search(Validate.notEmptyRe) != -1)) {
			alert(pc + ' is not a valid postcode. Please try a different postcode.');
			return false;
		}
	}
	return true;
}

// A form loops over its inputs, and complains if they're registered
// as not-empty, yet have no content.
Validate.FormNotEmpty = function(formElem) {
	if (typeof formElem == "undefined") {
		formElem = this;
	}
	for (var i = 0; i < formElem.elements.length; i++) {
		var e = formElem.elements[i];
		// Registered?
		for (var j = 0; j < document.notEmpty.length; j++) {
			if (e.id == document.notEmpty[j]) {
				// If registered as not empty, does it have content?
				if (e.value.search(Validate.notEmptyRe) == -1) {
					alert('Please enter a search term.');
					return false;
				}
			}
		}
	}
	return true;
}


Postcode.clearPostcodeIfDummy = function(formOrInput) {

	// If we actually have a form, get the input
	if (typeof formOrInput.form == "undefined") {
		var allInputs = document.getElementsByClassName("postcode");
		allInputs = document.weedOutFormChildren(formOrInput,allInputs);
		for (var i = 0; i < allInputs.length; i++) {
			Postcode.clearPostcodeIfDummy(allInputs[i]);
		}
		return true;
	}

	// By now we must have an input
	if ( (formOrInput.value == Postcode.pcText) ) {
		formOrInput.value = "";
	}
	// Don't call this again
	formOrInput.onfocus = function() {return true;};
	return true;
}

document.weedOutFormChildren = function (f,a) {
	var toReturn = new Array();
	for (var i = 0; i < a.length; i++) {
		if (a[i].form === f) {
			toReturn.push(a[i]);
		}
	}
	return toReturn;
}

function RPGBodyOnload() {
	// Say we've loaded
	window.loaded = true;

	//// Body changes
	// Google map
	if (typeof RPGGoogle != "undefined") {
		RPGGoogle.bodyOnloadMap();
	}

	// Fix for Safari
	if (document.isSafari) {
		DHTML.fixSectorsForSafari();
	}

	// DHTML toggles - register the corresponding toggle event for each
	var toggleElems = document.getElementsByClassName("dhtml-toggle");
	for(var i = 0; i < toggleElems.length; i++) {
		toggleElems[i].onclick = DHTML.toggleAnotherElement;
		DHTML.toggleAnotherElement.call(toggleElems[i],true);
	}

	//// Validation
	// Search text fields
	document.notEmpty = [ 'form-quick-search-input', 'form-input-big-search-text' ];
	for (i = 0; i < document.notEmpty.length; i++) {
		var e = $(document.notEmpty[i]);
		if (e != null) {
			DHTML.AddOnsubmitToElem(e.form, Validate.FormNotEmpty);
		}
	}

	//// Element munging
	// Postcodes
	var pcElems = document.getElementsByClassName(Postcode.pcClass);
	for (i = 0; i < pcElems.length; i++) {
		Postcode.registerAsPostcode(pcElems[i].id);
	}

	//// Validation
	// Postcodes
	for (i = 0; i < pcElems.length; i++) {
		DHTML.AddOnsubmitToElem(pcElems[i].form, Validate.FormPostcode);
	}
	
	// Splash page
	if (typeof Splash != "undefined") {
		Splash.go();
	}
}
