/* ===========================
	SHELTER SITE WIDE SCRIPTS
	Version: 0.1

	1. Extensions
	----------------------------
	a. scrollTo
	b. titleCase
	c. URL encode/decode

	2. Shelter functions
	----------------------------
		eg shelter.changeLocation(para1,para2);
	a. changeLocation
	b. getQueryVariable
	c. AJAX search
	d. Social media icons
	e. Advice page country information
	f. Table of contents
	g. Form validation
	h. Address lookup
	i. Twitter parser
	l. Animated banner

	3. Init global

=========================== */


// 1a. scrollTo
jQuery.fn.extend({
	scrollTo : function(speed, easing) {
		return this.each(function() {
		var targetOffset = $(this).offset().top;
		$('html,body').animate({scrollTop: targetOffset}, speed, easing);
		});
	}
}); //scrollTo


// 1b. titleCase
// Extend String object to allow Title Case
String.prototype.titleCase = function () {
	var str = "";
	var wrds = this.split(" ");
	for(keyvar in wrds) {
		str += ' ' + wrds[keyvar].substr(0,1).toUpperCase() + wrds[keyvar].substr(1,wrds[keyvar].length).toLowerCase();
	}
	return jQuery.trim(str);
}; //titleCase


// 1c. URL encode/decode - http://www.webtoolkit.info/
var Url = {
	encode : function (string) { // url encoding
		return escape(this._utf8_encode(string));
	},

	decode : function (string) { // url decoding
		return this._utf8_decode(unescape(string));
	},

	_utf8_encode : function (string) { // UTF-8 encoding
		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;
	},

	_utf8_decode : function (utftext) { // UTF-8 decoding
		var string = "";
		var i = 0;
		var c = c1 = 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;
	}
}; //URL encode/decode

// 2.
var shelter = {};

// 2a. changeLocation
(function($) {
	if(typeof shelter.changeLocation == "undefined") shelter.changeLocation = {
		init:function() {
			$("#location a").click(function() {
				if ($(this).html() == "Scotland"){
					shelter.changeLocation.change('england','scotland');
				} else {
					shelter.changeLocation.change('scotland','england');
				}
			});
		},

		change:function(firstCookie, countryName){
			if(firstCookie=='england'){
				var cookieString="country" + "=" + "england"; // the begining of our cookie string
				cookieString +="; expires=01/01/1900 00:00:00";
				cookieString +="; path=/"
				document.cookie= cookieString; // final cookie string 
		
				var cookieString="country" + "=" + "scotland";
				cookieString +="; expires=01/01/2099 00:00:00";
				cookieString +="; path=/"
				document.cookie= cookieString;
			} else{
				var cookieString="country" + "=" + "scotland";
				cookieString +="; expires=01/01/1900 00:00:00";
				cookieString +="; path=/"
				document.cookie= cookieString;
		
				var cookieString="country" + "=" + "england";
				cookieString +="; expires=01/01/2099 00:00:00";
				cookieString +="; path=/"
				document.cookie= cookieString;
			}
		}
	}; // end changeLocation
})(jQuery);

// 2b. getQueryVariable
if(typeof shelter.getQueryVariable == "undefined") shelter.getQueryVariable = {
	init:function(variable, defaultValue) {
		var query = window.location.search.substring(1);
		var vars = query.split("&");
		for (var i=0; i<vars.length; i++) {
			var pair = vars[i].split("=");
			if (pair[0] == variable) {
				if (pair[1] != "") {
					return Url.decode(pair[1]);
				} else {
					return defaultValue;
				}
			}
		}
		return defaultValue;
	}
}; // end getQueryVariable


// 2c. AJAX search
(function($) {
	if(typeof shelter.liveSearch == "undefined") shelter.liveSearch = {
		
		doingAjaxSearch: false, // global indicator of whether an search is going on
		currentSearchTerm: "", // current search term to prevent same AJAX search from happening
		searchTimeout:0, // ID of current search request
		alertTimerId: 0,

		init: function() {

			$("#header").append('<div id="ajax_search_container"></div>');
			$("#ajax_search_container").html("<div id=\"search_list\"><p id=\"searching_indicator\">Searching</p></div>");
			$("#search_list").hide();

			$("#queries_searchfield_query-new").bind('keyup', function() {
				var self = shelter.liveSearch;

				// clears the future search if a keypress is made within that time
				if(self.searchTimeout != undefined) {
					clearTimeout(self.searchTimeout);
				}

				// set doing the search in 500 milliseconds
				self.searchTimeout = setTimeout(function() {
					self.searchTimeout = undefined;
					shelter.liveSearch.ajaxSearch();
					}, 500 // increase time to reduce the server load
				);
			}).focus(function() {
				shelter.liveSearch.clearField(this.id);
			}).blur(function() {
				shelter.liveSearch.restoreField(this.id);
			});

			// when the return/enter key is pressed
			$(document).keyup(function(event){
				if (event.keyCode == 27) {
					shelter.liveSearch.closeSearchList();
				}
			});
		}, // end init

		ajaxSearch: function() {
			var search_term =  $("#queries_searchfield_query-new").val();
			var self = shelter.liveSearch;

			if (!self.doingAjaxSearch && (self.currentSearchTerm != self.search_term) && (self.search_term != "Search shelter...")) {
				if (search_term == "") {
					$("#search_list").fadeOut("medium");
				} else if (search_term.length >= 3) {
					shelter.liveSearch.doSearch();
				}
			}
		}, // end ajaxSearch

		doSearch: function() {
			$("#queries_searchfield_query-new").addClass("active_search");
			var self = shelter.liveSearch;

			self.doingAjaxSearch = true;

			$.ajax({
				type: "POST",
				url: "/ajax_search",
				data: "?mode=results&queries_search_query=" + $("#queries_searchfield_query-new").val(),
				dataType: "html",
				timeout: 30000, // 30 second timeout
				// ifModified: true, // don't do a search if the same as last request
				success: function(htmlData){
					self.doingAjaxSearch = false;
					self.currentSearchTerm = $("#queries_searchfield_query-new").val();

					$("#search_list").html(htmlData,function(){});
					
					$("#ajax_search_close").bind("click", function (event) {
						shelter.liveSearch.closeSearchList();
					});
					$("#more_search_results").attr("href","/search_results?mode=results&queries_search_query=" + $("#queries_searchfield_query-new").val());
					$("#search_list").fadeIn("fast");
					$("#queries_searchfield_query-new").removeClass("active_search");
				
					},
				error: function(request, errorType, errorThrown) {
					self.doingAjaxSearch = false;
					$("#queries_searchfield_query-new").removeClass("active_search");
					}
			});

		}, // end doSearch

		closeSearchList: function() {
			$("#search_list").fadeOut("medium");
			clearTimeout(shelter.liveSearch.searchTimeout);
			$("#queries_searchfield_query-new").removeClass("active_search");
			return false;
		}, // end closeSearchList

		clearField: function(x) {
			if (document.getElementById(x).value == document.getElementById(x).defaultValue) {
				document.getElementById(x).value = "";
			}
		}, 

		restoreField: function(x) {
			if (document.getElementById(x).value != document.getElementById(x).defaultValue) {
				document.getElementById(x).style.color="#000000";
			} else {
				document.getElementById(x).style.color="#BEBEBE";
			}

			if (document.getElementById(x).value == "") {
				document.getElementById(x).value = document.getElementById(x).defaultValue;
				document.getElementById(x).style.color="#BEBEBE";
			}
		}

	}; // end shelter.liveSearch
})(jQuery);

// 2d. Social Media Icons
(function($) { // prevent homepage $ conflicts
	if(typeof shelter.smIcons == "undefined") shelter.smIcons = {
		init: function() {
			$('.sm_icon').mouseover(function(e) { 
				shelter.smIcons.showLabel();
				$('#sm_label').text($(this).attr("title"));
				$('.sm_icon').css('background','');
				$(this).css('background',"url('http://england.shelter.org.uk/__data/assets/image/0009/178434/bubble_top.png') bottom center no-repeat");
			}); 
			$('#sm_icons_container').bind("mouseleave",function(){ shelter.smIcons.hideLabel(); });
		}, 

		showLabel: function() {
			if($('#sm_labels_container').css("opacity") == 0.4) {
				$('#sm_labels_container').fadeTo("fast",1);
			}
		},

		hideLabel: function() {
			$('#sm_labels_container').fadeTo("fast",0.4);
			$('#sm_label').html('Follow us');
			$('.sm_icon').css('background','');
		}

	}; // end shelter.smIcons
})(jQuery);


// 2e. Advice page country information
// Hide explanation paragraph and displays a link to call it
if (typeof shelter.countryInfo == "undefined") shelter.countryInfo = {

	init: function() {
		$("#countryinformation #explanation").css("height","0");
		$(".js-display-explanation strong").after("&nbsp;<a id='country_info_expose' href='#'>Why is this important?<\/a>");
		$("#explanation").css({ opacity: 1 });

		$('#country_info_expose').toggle(function() {
			$(this).addClass("info_exposed");
			$("#explanation").animate({
				height: "55px",
				opacity: 1
				}, 150);
		}, function(){
			$(this).removeClass("info_exposed");
			$("#explanation").animate({
				height: "0px",
				opacity: 0
			}, 150 );
		});
	}

}; // end shelter.countryInfo


// 2f. Table of contents
if (typeof shelter.innerContentPageNav == "undefined") shelter.innerContentPageNav = {

	init: function () {
		var goBack = "<p class='btt'><a href='#content'>Back to top<\/a><\/p>";

		if (typeof(noParsing) == "undefined") {
			$("#bodycontent h2:first").before("<div id='page_index'><h3>Contents<\/h3><ul id='pagelist'><\/ul><\/div>");

			$("#bodycontent h2").each(function(index) {
				$(this).before("<a name='"+ index + "' id='" + index + "'><\/a>");
				$("#pagelist").append("<li><a href='#" + index + "' accesskey='"+index+"'>"+$(this).text()+"<\/a><\/li>");
			});

			$("#bodycontent h2:not(:first)").each(function(index) {
				$(this).prev().after(goBack);
			});
		}
	}
}; // end shelter.innerContentPageNav


// 2g. Form validation
/*
	// define field types
	var fieldsToCheck = {
		q39311_q1 : { type:"text", regExp:"textBox", msg:"Please fill in your first name", req:true },
	}

	shelter.inlineFormValidate.init({
		formID:"form_email_39309",
		fields: fieldsToCheck
	});
*/
if(typeof shelter.inlineFormValidate == "undefined")  shelter.inlineFormValidate = {
	// standard regexp
	regExp : { 
		"textBox":"^.{1,300}$",
		"textArea": "^.{1,3000}",
		"email": "^([\\da-zA-Z-_+][\\da-zA-Z-_+.\\w']*[\\da-zA-Z-_+]@[\\da-zA-Z]['-.\\w]*[\\da-zA-Z]\\.[a-zA-Z]{2,7})$",
		"postcode":"^([A-PR-UWYZ0-9][A-HK-Y0-9][AEHMNPRTVXY0-9]?[ABEHMNPRVWXY0-9]? {1,2}[0-9][ABD-HJLN-UW-Z]{2}|GIR 0AA)$",
		"phone":"^0[1237][\\d ]{5,18}$",
		"dateOfBirth":"^\\d{2,}\/[01]\\d\/19\\d{2,}$",
		"amount":"^\\d{1,10}\\.?\\d{0,2}$",
		"sortcode":"^\\d{6}$",
		"accNo":"^\\d{8}$"
		},

	// customisable fields
	formID: "",
	formFieldPrefix: "",
	fieldsToCheck:[],

	init: function(params) {
		if (typeof params.formID != "undefined") {
			this.formID = params.formID;
		}

		if (typeof params.fields != "undefined") {
			this.fieldsToCheck = params.fields;
		}

		// generic all form elements bind
		$("#" + this.formID + " :input").blur(function() {
			shelter.inlineFormValidate.doInlineCheck($(this).attr("id"));
		});

		// form submit - redo all checks
		$("#" + this.formID).submit(function() { 
			$("#addressFields").show();

			$("#" + shelter.inlineFormValidate.formID + " :input").each(function() {
				shelter.inlineFormValidate.doInlineCheck($(this).attr("id"));
			});

			// Check for uncorrected errors 
			if ($("#customForm div").hasClass("requiredError")) {
				$("#formErrors").html("<div style=\"color:#f00;\"><strong>Please correct the information in the fields below.</strong></div>");
				$("#customForm").scrollTo(500);
				return false;
			} else {
				$("#" + this.formID + "submit").val("Please wait...").attr("disabled", "disabled");
				return true;
			}
		});
	},

	doInlineCheck: function(fieldID) {
		if (typeof this.fieldsToCheck[fieldID] != "undefined") {
			var fieldProperties = this.fieldsToCheck[fieldID];

			switch (fieldProperties.type) {
				case "text":
					shelter.inlineFormValidate.checkField(fieldID, this.regExp[fieldProperties.regExp], fieldProperties.msg, fieldProperties.req);
					break;
				case "dropdown":
					shelter.inlineFormValidate.checkDropDown(fieldID, fieldProperties.emptyValue, fieldProperties.msg, fieldProperties.req);
					break;
				case "radio":
					shelter.inlineFormValidate.checkRadioSelect(fieldID, fieldProperties.msg);
					break;
				case "dob": // have a weird id that would require using eval - BAD
					shelter.inlineFormValidate.checkDOB(fieldProperties.day, fieldProperties.month, fieldProperties.year, fieldProperties.minAge, fieldProperties.req);
					break;
				case "title":
					shelter.inlineFormValidate.checkTitle(fieldID, fieldProperties.titleOther);
					break;
				case "checkbox":
					shelter.inlineFormValidate.checkCheckConfirm(fieldID, fieldProperties.msg);
					break;
				case "confirmEmail":
					shelter.inlineFormValidate.checkField(fieldID, this.regExp["email"], fieldProperties.msg, fieldProperties.req);
					shelter.inlineFormValidate.checkEmailConfirm(fieldProperties.emailID, fieldID);
					break;
			}
		}
	},  // end doInlineCheck

	displayMsg: function(field, fieldID, msg, show) {

		if (show) {
			$(fieldID).parent().removeClass("requiredOkay").addClass("requiredError");
			if ($("#" + field + "_reqMsg").length > 0) {
				$("#" + field + "_reqMsg").show();
			} else {
				$(fieldID).after("<div id=\"" +  field + "_reqMsg\" class=\"requiredMsg\">" + msg + "</div>")
			}
		} else {
			$(fieldID).parent().removeClass("requiredError requiredOkay");
			$("#" + field + "_reqMsg").hide();
		}

	}, // end displayMsg


	/**
	 * Checks for valid input based on reg expression
	 *
	 * field - The id of the field
	 * regExCheck - regular expression to check against
	 * message - message to display if it doesn't pass a check
	 * required - 1/0 Whether the field is required, ie if you can have a blank value in it
	 */
	checkField: function (field, regExCheck, message, required) {
		var regExLine = new RegExp(regExCheck, "i");
		var fieldID = "#" + field;
		var fieldVal = jQuery.trim($(fieldID).val());

		if (regExLine.test(fieldVal)) {
			if (fieldVal != "" || (fieldVal == "" && required == 1)) {
				$(fieldID).parent().removeClass("requiredError").addClass("requiredOkay");
			} else {
				$(fieldID).parent().removeClass("requiredError requiredOkay");
			}
			if ($(fieldID + "_reqMsg").length > 0) {
				$(fieldID + "_reqMsg").hide();
			}
		} else {
			if (fieldVal != "" || (fieldVal == "" && required == 1)) {
				shelter.inlineFormValidate.displayMsg(field, fieldID, message, true);
			} else {
				shelter.inlineFormValidate.displayMsg(field, fieldID, message, false);
			}
		}

		// replace value with whitespace trimmed version
		$(fieldID).val(fieldVal);
	}, // checkField

	/** 
	 * Check for a valid selection in a drop down
	 * field - dropdown box select id
	 * emptyValue - value to check against
	 * message - message to display if it doesn't pass a check
	 * required - 1/0 Whether the field is required, ie if you can have a blank value in it
	 */
	checkDropDown: function (field, emptyValue, message, required) {
		var fieldID = "#" + field;
		var fieldVal = $(fieldID + " option:selected").val();

		if (fieldVal != emptyValue) {
			if (fieldVal != "" || (fieldVal == "" && required == 1)) {
				$(fieldID).parent().removeClass("requiredError").addClass("requiredOkay");
			} else {
				$(fieldID).parent().removeClass("requiredError requiredOkay");
			}
			if ($(fieldID + "_reqMsg").length > 0) {
				$(fieldID + "_reqMsg").hide();
			}
		} else {
			if (fieldVal != "" || (fieldVal == "" && required == 1)) {
				shelter.inlineFormValidate.displayMsg(field, fieldID, message, true);
			}
		}
	}, // end checkDropDown

	checkExpiryDateField: function (monthField, yearField, regExCheckMonth, regExCheckYear, message, required) {
		var regExLineMonth = new RegExp(regExCheckMonth, "i");
		var regExLineYear = new RegExp(regExCheckYear, "i");

		var fieldID = "#" + yearField;
		var monthFieldVal = jQuery.trim($("#" + monthField).val());
		var yearFieldVal = jQuery.trim($("#" + yearField).val());

		if (regExLineMonth.test(monthFieldVal) && regExLineYear.test(yearFieldVal)) {
			if ((monthFieldVal != "" && yearFieldVal != "") || (monthFieldVal == "" && yearFieldVal == "" && required == 1)) {
				$(fieldID).parent().removeClass("requiredError").addClass("requiredOkay");
			} else {
				$(fieldID).parent().removeClass("requiredError requiredOkay");
			}
			if ($(fieldID + "_reqMsg").length > 0) {
				$(fieldID + "_reqMsg").hide();
			}
		} else {
			if ((monthFieldVal != "" || yearFieldVal != "") || (monthFieldVal == ""  && yearFieldVal == "" && required == 1)) {
				shelter.inlineFormValidate.displayMsg(yearField, fieldID, message, true);
			}
		}
	}, // checkExpiryDateField

	/**
	 * Basic credit card number check using Luhn algorithm 
	 * Strips out the white space and letters
	 * Does not do a check for proper issuers prefix
	 **/
	checkCardNumberField: function (field, message, required) {
		var fieldID = "#" + field;
		var fieldVal = jQuery.trim($(fieldID).val());

		// Strip any non-digits (useful for credit card numbers with spaces and hyphens)
		fieldVal = fieldVal.replace(/\D/g, '');

		if (fieldVal.length <= 19) {
			// Set the string length and parity
			var number_length = fieldVal.length;
			var parity = number_length % 2;

			// Loop through each digit and do the maths
			var total=0;
			for (i=0; i < number_length; i++) {
				var digit = fieldVal.charAt(i);
				// Multiply alternate digits by two
				if (i % 2 == parity) {
					digit=digit * 2;
					// If the sum is two digits, add them together (in effect)
					if (digit > 9) {
						digit=digit - 9;
					}
				}
				// Total up the digits
				total = total + parseInt(digit);
			}
		}

		// If the total mod 10 equals 0, the number is valid
		if (total % 10 == 0 && fieldVal.length >= 12 && fieldVal.length <= 19) {
			if (fieldVal != "" || (fieldVal == "" && required == 0)) {
				$(fieldID).parent().removeClass("requiredError").addClass("requiredOkay");

				shelter.inlineFormValidate.displayMsg(field, fieldID, "", false);
			} else {
				$(fieldID).parent().removeClass("requiredError requiredOkay");
			}
			if ($(fieldID + "_reqMsg").length > 0) {
				$(fieldID + "_reqMsg").hide();
			}
		} else {
			if (fieldVal != "" || (fieldVal == "" && required == 1)) {
				shelter.inlineFormValidate.displayMsg(field, fieldID, message, true);
			}
		}

		$(fieldID).val(fieldVal);
	}, // end checkCardNumberField

	/*
	 * Check for valid DOB when using 3 drop downs, optional over 18 check
	 * day, month, year - ids of the fields
	 * over18 - true/false
	 */
	checkDOB:function (day, month, year, minAge, required) {
		var selectedDay = $(day + " option:selected").text();
		var selectedMonth = $(month + " option:selected").text();
		var selectedYear = $(year + " option:selected").text();

		var today = new Date().getTime();
		var DOB = new Date(selectedYear, $(month + " option:selected").val() - 1, selectedDay).getTime();
		var yearsToDate = (today - DOB)/(1000*60*60*24*365);

		wrapperID = year;

		if ((selectedDay == "" || selectedMonth == "" || selectedYear == "")) {
			if ((selectedDay != "" || selectedMonth != "" || selectedYear != "")|| (selectedDay == "" && selectedMonth == "" && selectedYear == "" && required)) {
				
				$(wrapperID).parent().removeClass("requiredOkay").addClass("requiredError");
				if ($("#dob_reqMsg").length > 0) {
					$("#dob_reqMsg").show();
				} else {
					$(wrapperID).after("<div id=\"dob_reqMsg\" class=\"requiredMsg\">Please enter a valid date of birth</div>");
				}
				
				// shelter.inlineFormValidate.displayMsg(wrapperID, wrapperID, Please enter a valid date of birth, true);
			} else {
				if ($("#dob_reqMsg").length > 0) {
					$(wrapperID).parent().removeClass("requiredError");
					if (selectedDay != "" || selectedMonth != "" || selectedYear != "") {
						$(wrapperID).parent().addClass("requiredOkay");
					} else {
						$(wrapperID).parent().removeClass("requiredOkay");
					}
					$("#dob_reqMsg").hide();
				}
			}
		} else {
			if (typeof minAge == "number" && minAge != 0 && (yearsToDate < minAge)) {
				$(wrapperID).parent().removeClass("requiredOkay").addClass("requiredError");
				if ($("#dob_youngMsg").length > 0) {
					$("#dob_youngMsg").show();
				} else {
					$(wrapperID).after("<div id=\"dob_youngMsg\" class=\"requiredMsg\">You must be " + minAge +" or over</div>");
				}
				$("#dob_reqMsg").hide();
			} else {
				if (yearsToDate >= minAge) {
					$(wrapperID).parent().addClass("requiredOkay");
				} else {
					$(wrapperID).parent().removeClass("requiredOkay");
				}
				$(wrapperID).parent().removeClass("requiredError");
				$("#dob_youngMsg").hide();
				$("#dob_reqMsg").hide();
			}
		}
	}, // checkDOB

	/*
	 * Check that title has been selected, show/hide 'other' textbox as required
	 * title, titleOther - ids of the fields
	 * Other field value should be "Other"
	 * 'Please select' option field should be " "
	 */
	checkTitle: function(title, titleOther) {
		var titleField = $("#" + title);
		var titleOtherField = $("#" + titleOther);
		var titleErrorMsg = $("#" + title + "_reqMsg");
		var titleOtherErrorMsg = $("#" + titleOther + "_reqMsg");

		if (titleField.val() != " ") {
			titleField.parent().addClass("requiredOkay").removeClass("requiredError");
			titleErrorMsg.hide();

			if (titleField.val() == "Other") {
				titleOtherField.attr("disabled", "");
				if (titleOtherField.val() == "") {
					titleOtherField.focus();
				}
			} else {
				titleOtherField.parent().removeClass("requiredOkay requiredError");
				titleOtherField.val("");
				titleOtherField.attr("disabled", "disabled");
				titleOtherErrorMsg.hide();
			}
			$("#" + title + "_reqMsg").hide();
		} else {
			shelter.inlineFormValidate.displayMsg(title, "#" + title, "Please select a title", true);
		}
	}, // end checkTitle

	//-- Check emails match
	checkEmailConfirm: function(email1, email2) {
		var emailField = $("#" + email1);
		var emailConfirmField = $("#" + email2);
		var emailConfirmErrorMsg = $("#" + email2 + "_email_reqMsg");

		if (emailField.val() != emailConfirmField.val()) {
			shelter.inlineFormValidate.displayMsg(email2 + "_email", "#" + email2, "Your email addresses don't match", true);
		} else {
			emailConfirmErrorMsg.hide();
 		}
	}, // end checkEmailConfirm

	//-- Check a check box has been checked
	checkCheckConfirm: function (fieldID, message) {
		var checkBoxField =  $("#" + fieldID);
		var errorMsg = $("#" + fieldID + "_reqMsg");

		if (checkBoxField.attr("checked") == "" || checkBoxField.attr("checked") == undefined) {
			shelter.inlineFormValidate.displayMsg(fieldID, "#" + fieldID, message, true);
			return false;
		} else {
			shelter.inlineFormValidate.displayMsg(fieldID, "#" + fieldID, message, false);
			return true;
		}
	}, // end checkCheckConfirm

	//-- Check that at least one radio has been selected
	checkRadioSelect: function(fieldID, message) {
		var groupFieldID = fieldID.substr(0, fieldID.lastIndexOf("_"));
		var fieldName = groupFieldID.replace("_", ":");
		var field = $("#" + fieldID + "");

		var radioField = $("[name='" + fieldName + "']:checked");
		var errorMsg = $("#" + groupFieldID + "_reqMsg");

		if (radioField.length > 0) {
			$("input[name='" + fieldName + "']:last").parent().addClass("requiredError").removeClass("requiredOkay");
			if (errorMsg.length > 0) {
				errorMsg.show();
			} else {
				$("input[name='" + fieldName + "']:last").parent().append("<div id=\"" + fieldID + "_reqMsg\" class=\"requiredMsg\">" + message + "</div>");
			}
			// shelter.inlineFormValidate.displayMsg(fieldID, "#" + fieldID, message, false);
		} else {
			$("input[name='" + fieldName + "']:last").parent().removeClass("requiredError").addClass("requiredOkay");
			if (errorMsg.length > 0) {
				errorMsg.hide();
			}
			// shelter.inlineFormValidate.displayMsg(fieldID, "#" + fieldID, message, true);
		}
	}, // end checkRadioSelect

	//-- Superseeded by above function
	checkRadio: function(fieldID, message) {
		var radioField = $("input[name='" + fieldID + "']");
		var radioFieldLength = $("input[name='" + fieldID + "']:checked").length;
		var errorMsg = $("#" + fieldID.replace(":", "\\:") + "_reqMsg");

		if (radioFieldLength == 0) {
			radioField.eq(1).parent().addClass("requiredError").removeClass("requiredOkay");
			if (errorMsg.length > 0) {
				errorMsg.show();
			} else {
				radioField.eq(1).parent().append("<div id=\"" + fieldID + "_reqMsg\" class=\"requiredMsg\">" + message + "</div>");
			}
		} else {
			radioField.eq(1).parent().removeClass("requiredError").addClass("requiredOkay");
			if (errorMsg.length > 0) {
				errorMsg.hide();
			}
		}
	} // end checkRadio

}; // end inlineFomValidate object


if (typeof shelter.bankwizard == "undefined") shelter.bankwizard = {
	// for bank wizard
	branchdetails: {},
	bankvalid: true,
	
	// Checks the bank details are valid, function checkForm must exist for finishing the checking.
	check: function(accNo, sortCode, functionToCall) {
		var bankwizardreached = function(json) {
			if (!json.validated) {
				// errorMessage = "<li>Bank details are invalid, please check account number and sort code</li>";
				shelter.bankwizard.bankvalid = false;
			}
			if (json.branchdetails) {
				shelter.bankwizard.bankvalid = true;
				errorMessage = "";
				shelter.bankwizard.branchdetails = json.branchdetails;

				$("#step3 span#bankName_answer").html(shelter.bankwizard.branchdetails.bankname);
			}
			if (typeof functionToCall == "function") {
				functionToCall(); // rest of checking
			}
		};

		// unable to connect with the bank wizard system
		var bankwizardfailed = function() {
			if (typeof functionToCall == "function") {
				functionToCall(); // rest of checking
			}
		};

		$.ajax({
			url: "/bankwizard/check.php?sc=" + sortCode + "&an=" + accNo,
			dataType: "json",
			success: bankwizardreached,
			error: bankwizardfailed
		});
	} // end checkBankDetails
};


// 2h. Address lookup
/** 
 * Look for address that match house number / name
 *
 * Usage:
	shelter.addressLookUp.init({
		addressLines:["line1","line2", "line3", "town", "county", "postcode"]
	});
 * Override callback updating this parameter with the function name to call - addressLookUp.callback
 **/
(function($) {
	if (typeof shelter.addressLookUp == "undefined") shelter.addressLookUp = {
		updateLabels:true,
		addressLines: [],
		addresses: null,
		lookupValue: "",
		messageID: "addressLookUpMsg",
		callback: "shelter.addressLookUp.finishedLookUp",
		noAddressMsg: "Sorry no addresses found, please try again or enter your address below",
		submitButtonID: "lookupsubmit",
		inputPostcodeID:"#lookup_postcode",
		inputHouseNoID:"#lookup_house_no",
		objectToAppendTo: "#lookup_postcode",
		addressFieldsWrapper:"#addressFields",

		init:function (parameters) {
			if (typeof parameters.updateLabels != "undefined") {
				this.updateLabels = parameters.updateLabels;
			}
			
			if (typeof parameters.addressLines != "undefined") {
				this.addressLines = parameters.addressLines;
			}

			if (typeof parameters.objectToAppendTo != "undefined") {
				this.objectToAppendTo = parameters.objectToAppendTo;
			}

			// initial hide sections
			$(this.addressFieldsWrapper).hide();
			$("#addressLookup").show();
			this.updateAddressLabels();

			// Add check functions for postcode lookup 
			$("#" + this.submitButtonID).bind("click", $("#lookup_postcode"), function (e) {
				shelter.addressLookUp.clearAddressErrors();
				shelter.addressLookUp.lookUp(e);
			});

			// manually enter address
			$("#enterAddress").click(function() {
				$("#enterAddressLink").hide();
				$("#addressLookup").slideUp(500);
				$(shelter.addressLookUp.addressFieldsWrapper).slideDown(500);
				if ($("#addressesHolder").length > 0) {
					$("#addressesHolder").hide();
				}
				return false;
			});

		}, // end init

		// update the address labels
		updateAddressLabels: function() {
			$("label[for='" + this.addressLines[0] + "']").html("Address");
			$("label[for='" + this.addressLines[1] + "'], label[for='"+ this.addressLines[2] + "']").hide();
		},

		displayMessage: function(message) {
			if ($("#" + this.messageID + " span").length > 0) {
				$("#" + this.messageID + " span").html(message);
			} else {
				message = "<div id=\"" + this.messageID + "\"><span>" + message + "</span></div>";
				$(this.objectToAppendTo).parent().append(message);
			}
		}, // end displayMessage

		clearAddressErrors: function() {
			for (line in this.addressLines) {
				$("#" + this.addressLines[line]).parent().removeClass("requiredError");
				$("#" + this.addressLines[line] + "_reqMsg").hide();
			}

			this.displayMessage("");
		}, // end clearAddressErrors

		lookUp: function(e) {
			var inputHouseNo = jQuery.trim($(this.inputHouseNoID).val());
			var inputPostcode = jQuery.trim($(this.inputPostcodeID).val());

			this.lookupValue = Url.encode(inputHouseNo + "," + inputPostcode);

			if (inputHouseNo != "" && inputPostcode != "") {
				$("#addressesHolder").remove();
				$(this.inputPostcodeID).addClass("ac_loading");
		
				var onSuccess = function(json) {
					$(shelter.addressLookUp.inputPostcodeID).removeClass("ac_loading");
					if (json != null) {
						shelter.addressLookUp.addresses = json.addresses;
						shelter.addressLookUp.displayList();
					} else {
						onFail();
					}
				};
				var onFail = function() {
					$(shelter.addressLookUp.inputPostcodeID).removeClass("ac_loading");
					shelter.addressLookUp.displayMessage(this.noAddressMsg);
				};
				
				$.ajax({
					type: "GET",
					url: "/postcode/check.php?address=" + this.lookupValue,
					dataType: "json",
					success: onSuccess,
					error: onFail
				});
			} else {
				this.displayMessage("Please enter your house number and postcode to search.");
			}
		}, // end lookUp

		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><div id=\"close\"><a href=\"#\">Close</a></div>";
					addressListHTML += "<ul id=\"addressLookUpList\">\n" + addressList + "</ul>\n";
					addressListHTML += "</div>\n";

					$("#" + this.messageID).remove();

					// display the item
					$(this.objectToAppendTo).parent().after(addressListHTML);
					
					$("ul#addressLookUpList li").click(function(e) { // bind the click actions
						e.preventDefault();
						if (e.stopPropagation) e.stopPropagation();
						shelter.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");
					} else {
						this.displayMessage(shelter.addressLookUp.noAddressMsg);
					}
					this.doCallback();
				}
			} else { // no addresses found
				this.displayMessage(shelter.addressLookUp.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 (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].titleCase();

				if (pcCityParts.length > 2) {
					for (i = 1; i < pcCityParts.length - 2; i++) {
						city += " " + pcCityParts[i].titleCase();
					}
				}

				// 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].titleCase())); // add 3
				}
				if (parts[3] != undefined && addressParts == 5) {
					$("#" + this.addressLines[3]).val(jQuery.trim(parts[3].titleCase())); // 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() {
			if (this.callback != null) {
				eval("" + this.callback + "()");
			}
		}, // end doCallback

		// callback - when all actions have been performed
		finishedLookUp: function() {
			$("#enterAddressLink").hide();
			$(this.addressFieldsWrapper).slideDown(500);
		} // end finishedLookup

	}; // end addressLookup object
})(jQuery);

// 2i. Twitter
if (typeof shelter.twitterParser == "undefined") shelter.twitterParser = {
	init:function() {
		var URLRegExp = /(https?:\/\/([-\w\.]+)+(:\d+)?(\/([\w/_\.]*(\?\S+)?)?)?)/gi;
		var twitTagsRegExp = /((^|\s)[#|@](\w+))/g;
		
		// process the tweets for links
		$(".tweet").each(function() {
			var tweetLine = $(this).html();
			// remove the 'Shelter:' prefix
			tweetLine = tweetLine.replace(/Shelter: /i, "");
			// add links to the URLs
			tweetLine = tweetLine.replace(URLRegExp, "<a href=\"$1\">$1</a>");
			// bold the twitter tags
			tweetLine = tweetLine.replace(twitTagsRegExp, "<strong>$1</strong>");
			$(this).html(tweetLine);
		});
	}
};

// 2j. In content JS execution
function doContentJS() {
	if (typeof contentInit == "function") {
		contentInit();
	}
};

// 2k. Bind onload events
function addWindowBind(functionName) {
	if (typeof functionName == "function") {
		if (window.addEventListener){ // compliant
			window.addEventListener("load", functionName, false);
		} else if (window.attachEvent){ // IE support
			window.attachEvent("onload", functionName);
		}
	}
};

// 2l. Create animated banner. Pass in the target div, an array of urls to load other panels from, and a delay
(function($) {
if (typeof shelter.animated_banner == "undefined") shelter.animated_banner = {
	
	containerDiv: "",
	extraScreens: [],
	panelTime: 3000,
	current_panel:0,
	next_panel:1,
	c:0,
	bannerTimer:null,
	
	init:function(parameters) {
		
		if (typeof parameters.containerDiv != "undefined") {
			this.containerDiv = parameters.containerDiv;
		}
				
		if (typeof parameters.extraScreens != "undefined") {
			this.extraScreens = parameters.extraScreens;
		}
		if (typeof parameters.panelTime != "undefined") {
			this.panelTime = parameters.panelTime;
		}
				
		$("#" + this.containerDiv + " .banner_panel").attr("rel","panel_0");
		shelter.animated_banner.get_data();
	},
	
	get_data:function() {	
		
		var count = this.c;
		var container = this.containerDiv;
		var urlToLoad = this.extraScreens[count];
		var arrayLength = this.extraScreens.length-1;
		var newpanel = "";
				
		$.ajax({
				url: urlToLoad,
				success: function(data){
					$("#" + container).append(data);
					$("#" + container + " div:last-child").attr("rel","panel_" + (count+1)).hide();
					Cufon.replace("#" + container + " div[rel$='panel_" + (count+1) + "'] .cufon_text");
					
					if (count == arrayLength)
					{
						$("#" + container + " .banner_panel").each(function(){
							$(this).css({"position":"absolute","top":"0","left":"0"});
						});
						shelter.animated_banner.start_animation();
						shelter.animated_banner.stopStartRotate();
					} else {
						
						shelter.animated_banner.incrementCount();	
						shelter.animated_banner.get_data();	
					}
				}
			});
	},
	
	stopStartRotate:function()
	{			
		$("#" +  this.containerDiv).mouseenter(function(){
			shelter.animated_banner.stop_animation();
		});
		
		$("#" +  this.containerDiv).mouseleave(function(){
			shelter.animated_banner.restart_animation();
		});
	},
	
	stop_animation:function()
	{
		clearTimeout(this.bannerTimer);
	},
	
	incrementCount:function()
	{	
		this.c++;
	},
	
	start_animation:function()
	{	
		if (this.current_panel == this.extraScreens.length)
		{
			this.next_panel = 0;
		} else {
			this.next_panel = this.current_panel + 1;
		}
		this.bannerTimer = setTimeout(function(){shelter.animated_banner.show_next_panel(this.current_panel,this.next_panel);}, this.panelTime);
	},
	
	restart_animation:function()
	{	
		clearTimeout(this.bannerTimer);
		this.bannerTimer = setTimeout(function(){shelter.animated_banner.show_next_panel(this.current_panel,this.next_panel);}, this.panelTime);
	},
	
	
	show_next_panel:function()
	{				
		clearTimeout(this.bannerTimer);
		$("#" + this.containerDiv + " div[rel$='panel_" + this.next_panel + "']").fadeIn();
		$("#" + this.containerDiv + " div[rel$='panel_" + this.current_panel + "']").fadeOut();
		
		this.current_panel = this.next_panel;
		
		shelter.animated_banner.start_animation();
	}
	
};
})(jQuery);


// 3. Init global
(function($) {
	jQuery(document).ready(function($) {
		// add page binds here or on in page content
		shelter.liveSearch.init();
		shelter.smIcons.init();
		shelter.changeLocation.init();

		// autorun content JS 
		addWindowBind(doContentJS);
	});
})(jQuery);

