/**
 * Architect in the House 
 *
 * Form functions
 **/

// Load jQuery
google.load("jquery", "1.4.0");

/**  URL encode / decode - http://www.webtoolkit.info/ **/
var Url = {
	// public method for url encoding
	encode : function (string) {
		return escape(this._utf8_encode(string));
	},

	// public method for url decoding
	decode : function (string) {
		return this._utf8_decode(unescape(string));
	},

	// private method for UTF-8 encoding
	_utf8_encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";

		for (var n = 0; n < string.length; n++) {
			var c = string.charCodeAt(n);

			if (c < 128) {
				utftext += String.fromCharCode(c);
			} else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			} else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}
		}
		return utftext;
	},

	// private method for UTF-8 decoding
	_utf8_decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = 0;
		var c1 = 0;
		var c2 = 0;

		while ( i < utftext.length ) {
			c = utftext.charCodeAt(i);

			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			} else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			} else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}
		}
		return string;
	}
} // end Url object definition

function decode(inputValue) {
	return Url.decode(inputValue);
} // end decode


/** 
 * Look for address that match house number / name
 *
 * Usage: Add a bind to the lookup button 
 *		e.g. addressLookUp.lookUp(e, "#lookup_house_no_id", "#lookup_postcode_id");
 *
 * Override callback updating this parameter with the function name to call - addressLookUp.callback
 **/
var addressLookUp = {
	addressLines: null,
	addresses: null,
	objectToAppendTo: "#addressLookup", // place where messages are added;
	lookupValue: "",
	messageID: "addressLookUpMsg",
	callback: "this.finishedLookUp",
	noAddressMsg: "Sorry no addresses found, please try again or enter your address below",
	lookupURL: "aith_ajax_requests.php?action=addressLookup&postcode=",


	lookUp: function(e, inputHouseNoID, inputPostcodeID) {
		var inputHouseNo = jQuery.trim($(inputHouseNoID).val());
		var inputPostcode = jQuery.trim($(inputPostcodeID).val());

		this.lookupValue = Url.encode(inputHouseNo + "," + inputPostcode);

		if (inputHouseNo != "" && inputPostcode != "") {
			this.clearAddressErrors();
			$("#addressesHolder").remove();
			$(inputPostcodeID).addClass("ajaxLoading");
	
			var onSuccess = function(json) {
				$(inputPostcodeID).removeClass("ajaxLoading");
				addressLookUp.addresses = json.addresses;
				addressLookUp.displayList();
			};
			var onFail = function() {
				$(inputPostcodeID).removeClass("ajaxLoading");
				addressLookUp.displayMessage(this.noAddressMsg);
			};
			
			$.ajax({
				type: "GET",
				url: this.lookupURL + this.lookupValue,
				dataType: "json",
				timeout: 3000,
				success: onSuccess,
				error: onFail
			});
		} else {
			this.displayMessage("Please enter your house number and postcode to search.");
		}
	}, // end lookUp

	clearAddressErrors: function() {
		for (line in this.addressLines) {
			$("#" + this.addressLines[line]).parent().removeClass("requiredError");
			$("#" + this.addressLines[line] + "_reqMsg").hide();
		}
	}, // end clearAddressErrors

	displayMessage: function(message) {
		if ($("#" + this.messageID + " span").length > 0) {
			$("#" + this.messageID + " span").html(message);
		} else {
			message = "<p id=\"" + this.messageID + "\"><span>" + message + "</span></p>";
			$(this.objectToAppendTo).after(message);
		}
	}, // end displayMessage

	displayList: function() {
		if (this.addresses !== null && this.addresses.length) {
			if (this.addresses.length > 1) { // generate a list 
				var addressList = "";

				for (var i=0, l=this.addresses.length; i < l ; i++) {
					addressList += "<li>" + this.addresses[i] + "</li>\n";
				}
				addressListHTML = "<div id=\"addressesHolder\">\n";
				addressListHTML += "<div id=\"intro\">Please select an address</div>\n<div id=\"close\"><a href=\"#\">Close</a></div>\n";
				addressListHTML += "<ul id=\"addressLookUpList\">\n" + addressList + "</ul>\n";
				addressListHTML += "</div>\n";

				$("#" + this.messageID).remove();

				// display the item
				$(this.objectToAppendTo).append(addressListHTML);
				
				$("ul#addressLookUpList li").click(function(e) { // bind the click actions
					e.preventDefault();
					if (e.stopPropagation) { e.stopPropagation() };
					addressLookUp.insertAddress($(this).html());
					$("#addressesHolder").hide();
				});
				
				$("#close a").click(function() {
					$("#addressesHolder").hide();
					return false;
				});
			} else { // only 1 address so insert straight away
				var noMatchesRegExp = /W No matches/;

				if (!noMatchesRegExp.test(this.addresses[0])) {
					this.insertAddress(this.addresses[0]);
					this.displayMessage("Please check the address found");
					this.doCallback();
				} else {
					this.displayMessage(this.noAddressMsg);
					$("#addressLines").slideDown(500);
				}
			}
		} else { // no addresses found
			this.displayMessage(this.noAddressMsg);
			this.doCallback();
		}
	}, // end displayList

	insertAddress: function(value) {
		var parts = value.split(",");

		// populate address fields if address found
		addressParts = parts.length;
		if (addressParts > 0 && this.addressLines !== null) {
			// clear the current address
			for (var x in this.addressLines) {
				$("#" + this.addressLines[x]).val("");
			}

			// break up the final field
			pcCityParts = jQuery.trim(parts[addressParts -1]).split(" ");

			pc = pcCityParts[pcCityParts.length - 2] + " " + pcCityParts[pcCityParts.length - 1];
			city = pcCityParts[0];

			if (pcCityParts.length > 2) {
				for (i = 1; i < pcCityParts.length - 2; i++) {
					city += " " + pcCityParts[i];
				}
			}

			// populate according to the number of elements
			$("#" + this.addressLines[0]).val(jQuery.trim(parts[0])); // add 1
			if (parts[1] !== undefined && addressParts >= 3) {
				$("#" + this.addressLines[1]).val(jQuery.trim(parts[1])); // add 2
			}
			if (parts[2] !== undefined && addressParts >= 4) {
				$("#" + this.addressLines[2]).val(jQuery.trim(parts[2])); // add 3
			}
			if (parts[3] !== undefined && addressParts == 5) {
				$("#" + this.addressLines[3]).val(jQuery.trim(parts[3])); // city
				$("#" + this.addressLines[4]).val(city); // county
			} else if (addressParts > 1) {
				$("#" + this.addressLines[3]).val(city); // city
			}
			$("#" + this.addressLines[5]).val(pc); // postcode

			this.doCallback();
		}
	}, // end insertAddress
	
	doCallback: function() {
		this.clearAddressErrors();
		if (this.callback != null) {
			eval("" + this.callback + "()");
		}
	}, // end doCallback

	// callback - things to do when an address has been selected / when all actions have been performed
	finishedLookUp: function() {
		$("#addressLookup").slideUp(500);
		$("#addressLines").slideDown(500);
	}, // end finishedLookup

	// check that the firm name is not already in place
	duplicateNameCheck: function() {
		var firmName = jQuery.trim($("#firmname").val());

		if (firmName != "") {
			var regExLine = new RegExp(jQuery.trim($("#firmname").val()), "i");

			if (regExLine.test($("#address1").val())) {
				// repopulate the form fields
				$("#address1").val($("#address2").val());
				$("#address2").val($("#address3").val());
				$("#address3").val("");
			}
		}

		$("#addressLookup").slideUp(500);
		$("#addressLines").slideDown(500);
	}, // end duplicateNameCheck

	// callback2
	finishedLookUpContact: function() {
		$("#addressLookupContact").slideUp(500);
		$("#addressLinesContact").slideDown(500);
	} // end finishedLookUpContact

}; // end addressLookup object


function initRegistrationForm (formType) {
	// address lookup fields
	var addressLines = ["address1","address2", "address3", "towncity", "county", "projectPostcode"];
	var addressLinesContact = ["contact_address1","contact_address2", "contact_address3", "contact_towncity", "contact_county", "contact_postcode"];
	var addressLinesArchitect = ["address1", "address2", "address3", "towncity", "county", "postcode"];

	if (formType == "public") { // public reg form specific
		
		// show hide the contact address
		if($("input[name='same_address']:checked").val() == "n") {
			$('#contact_address').show();
		} else {
			$('#contact_address').hide();
		}

		// Show/hide extra address fields
		$("input[name='same_address']").change(function () {
			if($("input[name='same_address']:checked").val() == "n") {
				$('#contact_address').slideDown('medium');
			} else {
				$('#contact_address').slideUp('medium');
			}
		});

		// Where did you hear about Other field
		$("#other_refer").hide();

		$("#hearabout").change(function () {
			if (document.getElementById("hearabout").selectedIndex == 6) {
				$("#other_refer").slideDown('medium');
			} else {
				$("#other_refer").slideUp('medium');
			}
		});

		// postcode lookup bind Contact address
		$("#findAddressContact").bind("click", $("#addressLookupContact"), function (e) {
			addressLookUp.addressLines = addressLinesContact;
			addressLookUp.messageID = "addressLookupContactMsg";
			addressLookUp.objectToAppendTo = "#addressLookupContact";
			addressLookUp.callback = "this.finishedLookUpContact";
			addressLookUp.lookUp(e, "#lookupHouseNoContact", "#lookupPostcodeContact");
		});

	}

	// Address fields
	if ($("#addressLines").length > 0) {

		// hide the address lines
		$("#addressLinesContact[class='hide'], #addressLines[class='hide']").each(function() {
			$(this).hide();
		});

		// hide / switch labels
		$("input[id^='address'], input[id^='contact_address']").each(function() {
			if ($(this).attr("id").indexOf("address1") != -1) {
				$(this).parent().prev().children().last().html("Address");
			} else {
				$(this).parent().prev().children().html("&nbsp;");
			}
		});

		// manually enter address
		$("#enterAddressProject, #enterAddressContact").click(function() {
			$(this).hide();

			if ($(this).attr("id") == "enterAddressProject") {
				$("#addressLookup").slideUp(500);
				$("#addressLines").slideDown(500);
			} else {
				$("#addressLookupContact").slideUp(500);
				$("#addressLinesContact").slideDown(500);
			}

			if (addressLookUp.listmarkup !== null) {
				$(addressLookUp.listmarkup).hide();
			}
			return false;
		});

		// postcode lookup bind
		$("#findAddress").bind("click", $("#addressLookup"), function (e) {
			if ($("#postcode").length > 0) {
				addressLookUp.callback = "this.duplicateNameCheck";
				addressLookUp.addressLines = addressLinesArchitect;
			} else {
				addressLookUp.addressLines = addressLines;
			}
			addressLookUp.objectToAppendTo = "#addressLookup";
			addressLookUp.messageID = "addressLookUpMsg";
			addressLookUp.lookUp(e, "#lookupHouseNo", "#lookupPostcode");
		});

		// address Lines binds
		$("a.selectAddress").click(function(e) {
			this.clearAddressErrors();
			addressLookUp.addressLines = addressLines;
			addressLookUp.insertAddress($(this).html());
			return false;
		});
	}

	// form highlights
	$(".inputBox, .inputBoxReverse, .inputArea").focus(function () {
		$(this).css('background-color','#fff799');
	});

	$(".inputBox, .inputBoxReverse, .inputArea").blur(function () {
		$(this).css('background-color','#f6f6f0');
	});

	$("#archNotes").parent().hide();

	$("#moreNotes").click(function() {
		$("#insurance").slideDown();
		return false;
	});

} // initRegistrationForm


function initHomepage() {

	// For feature rollovers
	$(".featureBox").hover(
		function() { // over
			$("#" + $(this).attr("id") + " .featureCaption").animate( {marginTop:"130px"}, 300);
		},
		function() { // out
			$("#" + $(this).attr("id") + " .featureCaption").animate( {marginTop:"190px"}, 300);
		}
	);

	// trigger for the whole image
	$(".featureBox").click(function(event) {
		switch ($(this).attr("id")) {
			case "feature1":
				location.href = "real_life_examples.php";
				break;
			case "feature2":
				location.href ="what_is_aith.php";
				break;
			case "feature3":
				location.href = "public_registration.php";
				break;
		}
	});

	// for quote transitions
	var noOfQuotes = $(".quoteFeature").length;
	var currentTimeoutID;

	function animateQuotes() {

		$(".quoteFeature:visible").each(function() {
			quoteNumber = new Number($(this).attr("id").substr("5", "6"));
			if (quoteNumber == noOfQuotes) {
				nextQuote = 1;
			} else {
				nextQuote = quoteNumber + 1;
			}

			$("#quote" + quoteNumber).fadeOut(400, function() {
				$("#quote" + nextQuote).fadeIn(400);
			});
			currentTimeoutID = setTimeout(animateQuotes, 6000);
		});
	} // end animtateQuotes

	if (noOfQuotes > 1) {
		$("[id^=quote]:gt(0)").hide(); // hide other elements
		currentTimeoutID = setTimeout(animateQuotes, 6000);
		
		// pause the animation when rollover
		$(".quoteFeature").mouseover(function() {
			clearTimeout(currentTimeoutID);
		}).mouseout(function() {
			currentTimeoutID = setTimeout(animateQuotes, 1000);
		});
	}

	jQuery.preLoadImages("images/george_clarke_bg.jpg", "images/before_you_build_cover_bg.jpg", "images/aith_regions_bg.jpg");

} // end initHomepage


// default onLoad actions
google.setOnLoadCallback(function () {
	if (typeof(jQuery) != "undefined") {
		// add gallery 
		$("a.fancybox").fancybox();
		
		// action for ext links
		$(".ext").attr("target", "_blank");

		(function($) {
			var cache = [];
			$.preLoadImages = function() {
				var args_len = arguments.length;
				for (var i = args_len; i--;) {
					var cacheImage = document.createElement('img');
					cacheImage.src = arguments[i];
					cache.push(cacheImage);
				}
			}
		})(jQuery);

	}
});/**
 * Architect in the House 
 *
 * Form functions
 **/

// Load jQuery
google.load("jquery", "1.4.0");

/**  URL encode / decode - http://www.webtoolkit.info/ **/
var Url = {
	// public method for url encoding
	encode : function (string) {
		return escape(this._utf8_encode(string));
	},

	// public method for url decoding
	decode : function (string) {
		return this._utf8_decode(unescape(string));
	},

	// private method for UTF-8 encoding
	_utf8_encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";

		for (var n = 0; n < string.length; n++) {
			var c = string.charCodeAt(n);

			if (c < 128) {
				utftext += String.fromCharCode(c);
			} else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			} else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}
		}
		return utftext;
	},

	// private method for UTF-8 decoding
	_utf8_decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = 0;
		var c1 = 0;
		var c2 = 0;

		while ( i < utftext.length ) {
			c = utftext.charCodeAt(i);

			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			} else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			} else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}
		}
		return string;
	}
} // end Url object definition

function decode(inputValue) {
	return Url.decode(inputValue);
} // end decode


/** 
 * Look for address that match house number / name
 *
 * Usage: Add a bind to the lookup button 
 *		e.g. addressLookUp.lookUp(e, "#lookup_house_no_id", "#lookup_postcode_id");
 *
 * Override callback updating this parameter with the function name to call - addressLookUp.callback
 **/
var addressLookUp = {
	addressLines: null,
	addresses: null,
	objectToAppendTo: "#addressLookup", // place where messages are added;
	lookupValue: "",
	messageID: "addressLookUpMsg",
	callback: "this.finishedLookUp",
	noAddressMsg: "Sorry no addresses found, please try again or enter your address below",
	lookupURL: "aith_ajax_requests.php?action=addressLookup&postcode=",


	lookUp: function(e, inputHouseNoID, inputPostcodeID) {
		var inputHouseNo = jQuery.trim($(inputHouseNoID).val());
		var inputPostcode = jQuery.trim($(inputPostcodeID).val());

		this.lookupValue = Url.encode(inputHouseNo + "," + inputPostcode);

		if (inputHouseNo != "" && inputPostcode != "") {
			this.clearAddressErrors();
			$("#addressesHolder").remove();
			$(inputPostcodeID).addClass("ajaxLoading");
	
			var onSuccess = function(json) {
				$(inputPostcodeID).removeClass("ajaxLoading");
				addressLookUp.addresses = json.addresses;
				addressLookUp.displayList();
			};
			var onFail = function() {
				$(inputPostcodeID).removeClass("ajaxLoading");
				addressLookUp.displayMessage(this.noAddressMsg);
			};
			
			$.ajax({
				type: "GET",
				url: this.lookupURL + this.lookupValue,
				dataType: "json",
				timeout: 3000,
				success: onSuccess,
				error: onFail
			});
		} else {
			this.displayMessage("Please enter your house number and postcode to search.");
		}
	}, // end lookUp

	clearAddressErrors: function() {
		for (line in this.addressLines) {
			$("#" + this.addressLines[line]).parent().removeClass("requiredError");
			$("#" + this.addressLines[line] + "_reqMsg").hide();
		}
	}, // end clearAddressErrors

	displayMessage: function(message) {
		if ($("#" + this.messageID + " span").length > 0) {
			$("#" + this.messageID + " span").html(message);
		} else {
			message = "<p id=\"" + this.messageID + "\"><span>" + message + "</span></p>";
			$(this.objectToAppendTo).after(message);
		}
	}, // end displayMessage

	displayList: function() {
		if (this.addresses !== null && this.addresses.length) {
			if (this.addresses.length > 1) { // generate a list 
				var addressList = "";

				for (var i=0, l=this.addresses.length; i < l ; i++) {
					addressList += "<li>" + this.addresses[i] + "</li>\n";
				}
				addressListHTML = "<div id=\"addressesHolder\">\n";
				addressListHTML += "<div id=\"intro\">Please select an address</div>\n<div id=\"close\"><a href=\"#\">Close</a></div>\n";
				addressListHTML += "<ul id=\"addressLookUpList\">\n" + addressList + "</ul>\n";
				addressListHTML += "</div>\n";

				$("#" + this.messageID).remove();

				// display the item
				$(this.objectToAppendTo).append(addressListHTML);
				
				$("ul#addressLookUpList li").click(function(e) { // bind the click actions
					e.preventDefault();
					if (e.stopPropagation) { e.stopPropagation() };
					addressLookUp.insertAddress($(this).html());
					$("#addressesHolder").hide();
				});
				
				$("#close a").click(function() {
					$("#addressesHolder").hide();
					return false;
				});
			} else { // only 1 address so insert straight away
				var noMatchesRegExp = /W No matches/;

				if (!noMatchesRegExp.test(this.addresses[0])) {
					this.insertAddress(this.addresses[0]);
					this.displayMessage("Please check the address found");
					this.doCallback();
				} else {
					this.displayMessage(this.noAddressMsg);
					$("#addressLines").slideDown(500);
				}
			}
		} else { // no addresses found
			this.displayMessage(this.noAddressMsg);
			this.doCallback();
		}
	}, // end displayList

	insertAddress: function(value) {
		var parts = value.split(",");

		// populate address fields if address found
		addressParts = parts.length;
		if (addressParts > 0 && this.addressLines !== null) {
			// clear the current address
			for (var x in this.addressLines) {
				$("#" + this.addressLines[x]).val("");
			}

			// break up the final field
			pcCityParts = jQuery.trim(parts[addressParts -1]).split(" ");

			pc = pcCityParts[pcCityParts.length - 2] + " " + pcCityParts[pcCityParts.length - 1];
			city = pcCityParts[0];

			if (pcCityParts.length > 2) {
				for (i = 1; i < pcCityParts.length - 2; i++) {
					city += " " + pcCityParts[i];
				}
			}

			// populate according to the number of elements
			$("#" + this.addressLines[0]).val(jQuery.trim(parts[0])); // add 1
			if (parts[1] !== undefined && addressParts >= 3) {
				$("#" + this.addressLines[1]).val(jQuery.trim(parts[1])); // add 2
			}
			if (parts[2] !== undefined && addressParts >= 4) {
				$("#" + this.addressLines[2]).val(jQuery.trim(parts[2])); // add 3
			}
			if (parts[3] !== undefined && addressParts == 5) {
				$("#" + this.addressLines[3]).val(jQuery.trim(parts[3])); // city
				$("#" + this.addressLines[4]).val(city); // county
			} else if (addressParts > 1) {
				$("#" + this.addressLines[3]).val(city); // city
			}
			$("#" + this.addressLines[5]).val(pc); // postcode

			this.doCallback();
		}
	}, // end insertAddress
	
	doCallback: function() {
		this.clearAddressErrors();
		if (this.callback != null) {
			eval("" + this.callback + "()");
		}
	}, // end doCallback

	// callback - things to do when an address has been selected / when all actions have been performed
	finishedLookUp: function() {
		$("#addressLookup").slideUp(500);
		$("#addressLines").slideDown(500);
	}, // end finishedLookup

	// check that the firm name is not already in place
	duplicateNameCheck: function() {
		var firmName = jQuery.trim($("#firmname").val());

		if (firmName != "") {
			var regExLine = new RegExp(jQuery.trim($("#firmname").val()), "i");

			if (regExLine.test($("#address1").val())) {
				// repopulate the form fields
				$("#address1").val($("#address2").val());
				$("#address2").val($("#address3").val());
				$("#address3").val("");
			}
		}

		$("#addressLookup").slideUp(500);
		$("#addressLines").slideDown(500);
	}, // end duplicateNameCheck

	// callback2
	finishedLookUpContact: function() {
		$("#addressLookupContact").slideUp(500);
		$("#addressLinesContact").slideDown(500);
	} // end finishedLookUpContact

}; // end addressLookup object


function initRegistrationForm (formType) {
	// address lookup fields
	var addressLines = ["address1","address2", "address3", "towncity", "county", "projectPostcode"];
	var addressLinesContact = ["contact_address1","contact_address2", "contact_address3", "contact_towncity", "contact_county", "contact_postcode"];
	var addressLinesArchitect = ["address1", "address2", "address3", "towncity", "county", "postcode"];

	if (formType == "public") { // public reg form specific
		
		// show hide the contact address
		if($("input[name='same_address']:checked").val() == "n") {
			$('#contact_address').show();
		} else {
			$('#contact_address').hide();
		}

		// Show/hide extra address fields
		$("input[name='same_address']").change(function () {
			if($("input[name='same_address']:checked").val() == "n") {
				$('#contact_address').slideDown('medium');
			} else {
				$('#contact_address').slideUp('medium');
			}
		});

		// Where did you hear about Other field
		$("#other_refer").hide();

		$("#hearabout").change(function () {
			if (document.getElementById("hearabout").selectedIndex == 6) {
				$("#other_refer").slideDown('medium');
			} else {
				$("#other_refer").slideUp('medium');
			}
		});

		// postcode lookup bind Contact address
		$("#findAddressContact").bind("click", $("#addressLookupContact"), function (e) {
			addressLookUp.addressLines = addressLinesContact;
			addressLookUp.messageID = "addressLookupContactMsg";
			addressLookUp.objectToAppendTo = "#addressLookupContact";
			addressLookUp.callback = "this.finishedLookUpContact";
			addressLookUp.lookUp(e, "#lookupHouseNoContact", "#lookupPostcodeContact");
		});

	}

	// Address fields
	if ($("#addressLines").length > 0) {

		// hide the address lines
		$("#addressLinesContact[class='hide'], #addressLines[class='hide']").each(function() {
			$(this).hide();
		});

		// hide / switch labels
		$("input[id^='address'], input[id^='contact_address']").each(function() {
			if ($(this).attr("id").indexOf("address1") != -1) {
				$(this).parent().prev().children().last().html("Address");
			} else {
				$(this).parent().prev().children().html("&nbsp;");
			}
		});

		// manually enter address
		$("#enterAddressProject, #enterAddressContact").click(function() {
			$(this).hide();

			if ($(this).attr("id") == "enterAddressProject") {
				$("#addressLookup").slideUp(500);
				$("#addressLines").slideDown(500);
			} else {
				$("#addressLookupContact").slideUp(500);
				$("#addressLinesContact").slideDown(500);
			}

			if (addressLookUp.listmarkup !== null) {
				$(addressLookUp.listmarkup).hide();
			}
			return false;
		});

		// postcode lookup bind
		$("#findAddress").bind("click", $("#addressLookup"), function (e) {
			if ($("#postcode").length > 0) {
				addressLookUp.callback = "this.duplicateNameCheck";
				addressLookUp.addressLines = addressLinesArchitect;
			} else {
				addressLookUp.addressLines = addressLines;
			}
			addressLookUp.objectToAppendTo = "#addressLookup";
			addressLookUp.messageID = "addressLookUpMsg";
			addressLookUp.lookUp(e, "#lookupHouseNo", "#lookupPostcode");
		});

		// address Lines binds
		$("a.selectAddress").click(function(e) {
			this.clearAddressErrors();
			addressLookUp.addressLines = addressLines;
			addressLookUp.insertAddress($(this).html());
			return false;
		});
	}

	// form highlights
	$(".inputBox, .inputBoxReverse, .inputArea").focus(function () {
		$(this).css('background-color','#fff799');
	});

	$(".inputBox, .inputBoxReverse, .inputArea").blur(function () {
		$(this).css('background-color','#f6f6f0');
	});

	$("#archNotes").parent().hide();

	$("#moreNotes").click(function() {
		$("#insurance").slideDown();
		return false;
	});

} // initRegistrationForm


function initHomepage() {

	// For feature rollovers
	$(".featureBox").hover(
		function() { // over
			$("#" + $(this).attr("id") + " .featureCaption").animate( {marginTop:"130px"}, 300);
		},
		function() { // out
			$("#" + $(this).attr("id") + " .featureCaption").animate( {marginTop:"190px"}, 300);
		}
	);

	// trigger for the whole image
	$(".featureBox").click(function(event) {
		switch ($(this).attr("id")) {
			case "feature1":
				location.href = "real_life_examples.php";
				break;
			case "feature2":
				location.href ="what_is_aith.php";
				break;
			case "feature3":
				location.href = "public_registration.php";
				break;
		}
	});

	// for quote transitions
	var noOfQuotes = $(".quoteFeature").length;
	var currentTimeoutID;

	function animateQuotes() {

		$(".quoteFeature:visible").each(function() {
			quoteNumber = new Number($(this).attr("id").substr("5", "6"));
			if (quoteNumber == noOfQuotes) {
				nextQuote = 1;
			} else {
				nextQuote = quoteNumber + 1;
			}

			$("#quote" + quoteNumber).fadeOut(400, function() {
				$("#quote" + nextQuote).fadeIn(400);
			});
			currentTimeoutID = setTimeout(animateQuotes, 6000);
		});
	} // end animtateQuotes

	if (noOfQuotes > 1) {
		$("[id^=quote]:gt(0)").hide(); // hide other elements
		currentTimeoutID = setTimeout(animateQuotes, 6000);
		
		// pause the animation when rollover
		$(".quoteFeature").mouseover(function() {
			clearTimeout(currentTimeoutID);
		}).mouseout(function() {
			currentTimeoutID = setTimeout(animateQuotes, 1000);
		});
	}

	jQuery.preLoadImages("images/george_clarke_bg.jpg", "images/before_you_build_cover_bg.jpg", "images/aith_regions_bg.jpg");

} // end initHomepage


// default onLoad actions
google.setOnLoadCallback(function () {
	if (typeof(jQuery) != "undefined") {
		// add gallery 
		$("a.fancybox").fancybox();
		
		// action for ext links
		$(".ext").attr("target", "_blank");

		(function($) {
			var cache = [];
			$.preLoadImages = function() {
				var args_len = arguments.length;
				for (var i = args_len; i--;) {
					var cacheImage = document.createElement('img');
					cacheImage.src = arguments[i];
					cache.push(cacheImage);
				}
			}
		})(jQuery);

	}
});/**
 * Architect in the House 
 *
 * Form functions
 **/

// Load jQuery
google.load("jquery", "1.4.0");

/**  URL encode / decode - http://www.webtoolkit.info/ **/
var Url = {
	// public method for url encoding
	encode : function (string) {
		return escape(this._utf8_encode(string));
	},

	// public method for url decoding
	decode : function (string) {
		return this._utf8_decode(unescape(string));
	},

	// private method for UTF-8 encoding
	_utf8_encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";

		for (var n = 0; n < string.length; n++) {
			var c = string.charCodeAt(n);

			if (c < 128) {
				utftext += String.fromCharCode(c);
			} else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			} else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}
		}
		return utftext;
	},

	// private method for UTF-8 decoding
	_utf8_decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = 0;
		var c1 = 0;
		var c2 = 0;

		while ( i < utftext.length ) {
			c = utftext.charCodeAt(i);

			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			} else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			} else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}
		}
		return string;
	}
} // end Url object definition

function decode(inputValue) {
	return Url.decode(inputValue);
} // end decode


/** 
 * Look for address that match house number / name
 *
 * Usage: Add a bind to the lookup button 
 *		e.g. addressLookUp.lookUp(e, "#lookup_house_no_id", "#lookup_postcode_id");
 *
 * Override callback updating this parameter with the function name to call - addressLookUp.callback
 **/
var addressLookUp = {
	addressLines: null,
	addresses: null,
	objectToAppendTo: "#addressLookup", // place where messages are added;
	lookupValue: "",
	messageID: "addressLookUpMsg",
	callback: "this.finishedLookUp",
	noAddressMsg: "Sorry no addresses found, please try again or enter your address below",
	lookupURL: "aith_ajax_requests.php?action=addressLookup&postcode=",


	lookUp: function(e, inputHouseNoID, inputPostcodeID) {
		var inputHouseNo = jQuery.trim($(inputHouseNoID).val());
		var inputPostcode = jQuery.trim($(inputPostcodeID).val());

		this.lookupValue = Url.encode(inputHouseNo + "," + inputPostcode);

		if (inputHouseNo != "" && inputPostcode != "") {
			this.clearAddressErrors();
			$("#addressesHolder").remove();
			$(inputPostcodeID).addClass("ajaxLoading");
	
			var onSuccess = function(json) {
				$(inputPostcodeID).removeClass("ajaxLoading");
				addressLookUp.addresses = json.addresses;
				addressLookUp.displayList();
			};
			var onFail = function() {
				$(inputPostcodeID).removeClass("ajaxLoading");
				addressLookUp.displayMessage(this.noAddressMsg);
			};
			
			$.ajax({
				type: "GET",
				url: this.lookupURL + this.lookupValue,
				dataType: "json",
				timeout: 3000,
				success: onSuccess,
				error: onFail
			});
		} else {
			this.displayMessage("Please enter your house number and postcode to search.");
		}
	}, // end lookUp

	clearAddressErrors: function() {
		for (line in this.addressLines) {
			$("#" + this.addressLines[line]).parent().removeClass("requiredError");
			$("#" + this.addressLines[line] + "_reqMsg").hide();
		}
	}, // end clearAddressErrors

	displayMessage: function(message) {
		if ($("#" + this.messageID + " span").length > 0) {
			$("#" + this.messageID + " span").html(message);
		} else {
			message = "<p id=\"" + this.messageID + "\"><span>" + message + "</span></p>";
			$(this.objectToAppendTo).after(message);
		}
	}, // end displayMessage

	displayList: function() {
		if (this.addresses !== null && this.addresses.length) {
			if (this.addresses.length > 1) { // generate a list 
				var addressList = "";

				for (var i=0, l=this.addresses.length; i < l ; i++) {
					addressList += "<li>" + this.addresses[i] + "</li>\n";
				}
				addressListHTML = "<div id=\"addressesHolder\">\n";
				addressListHTML += "<div id=\"intro\">Please select an address</div>\n<div id=\"close\"><a href=\"#\">Close</a></div>\n";
				addressListHTML += "<ul id=\"addressLookUpList\">\n" + addressList + "</ul>\n";
				addressListHTML += "</div>\n";

				$("#" + this.messageID).remove();

				// display the item
				$(this.objectToAppendTo).append(addressListHTML);
				
				$("ul#addressLookUpList li").click(function(e) { // bind the click actions
					e.preventDefault();
					if (e.stopPropagation) { e.stopPropagation() };
					addressLookUp.insertAddress($(this).html());
					$("#addressesHolder").hide();
				});
				
				$("#close a").click(function() {
					$("#addressesHolder").hide();
					return false;
				});
			} else { // only 1 address so insert straight away
				var noMatchesRegExp = /W No matches/;

				if (!noMatchesRegExp.test(this.addresses[0])) {
					this.insertAddress(this.addresses[0]);
					this.displayMessage("Please check the address found");
					this.doCallback();
				} else {
					this.displayMessage(this.noAddressMsg);
					$("#addressLines").slideDown(500);
				}
			}
		} else { // no addresses found
			this.displayMessage(this.noAddressMsg);
			this.doCallback();
		}
	}, // end displayList

	insertAddress: function(value) {
		var parts = value.split(",");

		// populate address fields if address found
		addressParts = parts.length;
		if (addressParts > 0 && this.addressLines !== null) {
			// clear the current address
			for (var x in this.addressLines) {
				$("#" + this.addressLines[x]).val("");
			}

			// break up the final field
			pcCityParts = jQuery.trim(parts[addressParts -1]).split(" ");

			pc = pcCityParts[pcCityParts.length - 2] + " " + pcCityParts[pcCityParts.length - 1];
			city = pcCityParts[0];

			if (pcCityParts.length > 2) {
				for (i = 1; i < pcCityParts.length - 2; i++) {
					city += " " + pcCityParts[i];
				}
			}

			// populate according to the number of elements
			$("#" + this.addressLines[0]).val(jQuery.trim(parts[0])); // add 1
			if (parts[1] !== undefined && addressParts >= 3) {
				$("#" + this.addressLines[1]).val(jQuery.trim(parts[1])); // add 2
			}
			if (parts[2] !== undefined && addressParts >= 4) {
				$("#" + this.addressLines[2]).val(jQuery.trim(parts[2])); // add 3
			}
			if (parts[3] !== undefined && addressParts == 5) {
				$("#" + this.addressLines[3]).val(jQuery.trim(parts[3])); // city
				$("#" + this.addressLines[4]).val(city); // county
			} else if (addressParts > 1) {
				$("#" + this.addressLines[3]).val(city); // city
			}
			$("#" + this.addressLines[5]).val(pc); // postcode

			this.doCallback();
		}
	}, // end insertAddress
	
	doCallback: function() {
		this.clearAddressErrors();
		if (this.callback != null) {
			eval("" + this.callback + "()");
		}
	}, // end doCallback

	// callback - things to do when an address has been selected / when all actions have been performed
	finishedLookUp: function() {
		$("#addressLookup").slideUp(500);
		$("#addressLines").slideDown(500);
	}, // end finishedLookup

	// check that the firm name is not already in place
	duplicateNameCheck: function() {
		var firmName = jQuery.trim($("#firmname").val());

		if (firmName != "") {
			var regExLine = new RegExp(jQuery.trim($("#firmname").val()), "i");

			if (regExLine.test($("#address1").val())) {
				// repopulate the form fields
				$("#address1").val($("#address2").val());
				$("#address2").val($("#address3").val());
				$("#address3").val("");
			}
		}

		$("#addressLookup").slideUp(500);
		$("#addressLines").slideDown(500);
	}, // end duplicateNameCheck

	// callback2
	finishedLookUpContact: function() {
		$("#addressLookupContact").slideUp(500);
		$("#addressLinesContact").slideDown(500);
	} // end finishedLookUpContact

}; // end addressLookup object


function initRegistrationForm (formType) {
	// address lookup fields
	var addressLines = ["address1","address2", "address3", "towncity", "county", "projectPostcode"];
	var addressLinesContact = ["contact_address1","contact_address2", "contact_address3", "contact_towncity", "contact_county", "contact_postcode"];
	var addressLinesArchitect = ["address1", "address2", "address3", "towncity", "county", "postcode"];

	if (formType == "public") { // public reg form specific
		
		// show hide the contact address
		if($("input[name='same_address']:checked").val() == "n") {
			$('#contact_address').show();
		} else {
			$('#contact_address').hide();
		}

		// Show/hide extra address fields
		$("input[name='same_address']").change(function () {
			if($("input[name='same_address']:checked").val() == "n") {
				$('#contact_address').slideDown('medium');
			} else {
				$('#contact_address').slideUp('medium');
			}
		});

		// Where did you hear about Other field
		$("#other_refer").hide();

		$("#hearabout").change(function () {
			if (document.getElementById("hearabout").selectedIndex == 6) {
				$("#other_refer").slideDown('medium');
			} else {
				$("#other_refer").slideUp('medium');
			}
		});

		// postcode lookup bind Contact address
		$("#findAddressContact").bind("click", $("#addressLookupContact"), function (e) {
			addressLookUp.addressLines = addressLinesContact;
			addressLookUp.messageID = "addressLookupContactMsg";
			addressLookUp.objectToAppendTo = "#addressLookupContact";
			addressLookUp.callback = "this.finishedLookUpContact";
			addressLookUp.lookUp(e, "#lookupHouseNoContact", "#lookupPostcodeContact");
		});

	}

	// Address fields
	if ($("#addressLines").length > 0) {

		// hide the address lines
		$("#addressLinesContact[class='hide'], #addressLines[class='hide']").each(function() {
			$(this).hide();
		});

		// hide / switch labels
		$("input[id^='address'], input[id^='contact_address']").each(function() {
			if ($(this).attr("id").indexOf("address1") != -1) {
				$(this).parent().prev().children().last().html("Address");
			} else {
				$(this).parent().prev().children().html("&nbsp;");
			}
		});

		// manually enter address
		$("#enterAddressProject, #enterAddressContact").click(function() {
			$(this).hide();

			if ($(this).attr("id") == "enterAddressProject") {
				$("#addressLookup").slideUp(500);
				$("#addressLines").slideDown(500);
			} else {
				$("#addressLookupContact").slideUp(500);
				$("#addressLinesContact").slideDown(500);
			}

			if (addressLookUp.listmarkup !== null) {
				$(addressLookUp.listmarkup).hide();
			}
			return false;
		});

		// postcode lookup bind
		$("#findAddress").bind("click", $("#addressLookup"), function (e) {
			if ($("#postcode").length > 0) {
				addressLookUp.callback = "this.duplicateNameCheck";
				addressLookUp.addressLines = addressLinesArchitect;
			} else {
				addressLookUp.addressLines = addressLines;
			}
			addressLookUp.objectToAppendTo = "#addressLookup";
			addressLookUp.messageID = "addressLookUpMsg";
			addressLookUp.lookUp(e, "#lookupHouseNo", "#lookupPostcode");
		});

		// address Lines binds
		$("a.selectAddress").click(function(e) {
			this.clearAddressErrors();
			addressLookUp.addressLines = addressLines;
			addressLookUp.insertAddress($(this).html());
			return false;
		});
	}

	// form highlights
	$(".inputBox, .inputBoxReverse, .inputArea").focus(function () {
		$(this).css('background-color','#fff799');
	});

	$(".inputBox, .inputBoxReverse, .inputArea").blur(function () {
		$(this).css('background-color','#f6f6f0');
	});

	$("#archNotes").parent().hide();

	$("#moreNotes").click(function() {
		$("#insurance").slideDown();
		return false;
	});

} // initRegistrationForm


function initHomepage() {

	// For feature rollovers
	$(".featureBox").hover(
		function() { // over
			$("#" + $(this).attr("id") + " .featureCaption").animate( {marginTop:"130px"}, 300);
		},
		function() { // out
			$("#" + $(this).attr("id") + " .featureCaption").animate( {marginTop:"190px"}, 300);
		}
	);

	// trigger for the whole image
	$(".featureBox").click(function(event) {
		switch ($(this).attr("id")) {
			case "feature1":
				location.href = "real_life_examples.php";
				break;
			case "feature2":
				location.href ="what_is_aith.php";
				break;
			case "feature3":
				location.href = "public_registration.php";
				break;
		}
	});

	// for quote transitions
	var noOfQuotes = $(".quoteFeature").length;
	var currentTimeoutID;

	function animateQuotes() {

		$(".quoteFeature:visible").each(function() {
			quoteNumber = new Number($(this).attr("id").substr("5", "6"));
			if (quoteNumber == noOfQuotes) {
				nextQuote = 1;
			} else {
				nextQuote = quoteNumber + 1;
			}

			$("#quote" + quoteNumber).fadeOut(400, function() {
				$("#quote" + nextQuote).fadeIn(400);
			});
			currentTimeoutID = setTimeout(animateQuotes, 6000);
		});
	} // end animtateQuotes

	if (noOfQuotes > 1) {
		$("[id^=quote]:gt(0)").hide(); // hide other elements
		currentTimeoutID = setTimeout(animateQuotes, 6000);
		
		// pause the animation when rollover
		$(".quoteFeature").mouseover(function() {
			clearTimeout(currentTimeoutID);
		}).mouseout(function() {
			currentTimeoutID = setTimeout(animateQuotes, 1000);
		});
	}

	jQuery.preLoadImages("images/george_clarke_bg.jpg", "images/before_you_build_cover_bg.jpg", "images/aith_regions_bg.jpg");

} // end initHomepage


// default onLoad actions
google.setOnLoadCallback(function () {
	if (typeof(jQuery) != "undefined") {
		// add gallery 
		$("a.fancybox").fancybox();
		
		// action for ext links
		$(".ext").attr("target", "_blank");

		(function($) {
			var cache = [];
			$.preLoadImages = function() {
				var args_len = arguments.length;
				for (var i = args_len; i--;) {
					var cacheImage = document.createElement('img');
					cacheImage.src = arguments[i];
					cache.push(cacheImage);
				}
			}
		})(jQuery);

	}
});