﻿//------------------------------------------------------------------ 
//Organisation:		    Norwich and Peterborough Building Society
//Javascript file name:	main.js
//Date created:		    03/03/09 
//Dependency files:	    jquery.min.js
//--------------------------------------------------------------------


//#region Page ready functions
$(function () {

	//Fix IE 6, 7 & 8 Font Rendering issues
	$("h1, h2, h3, h4, h5, #nav a, div#footer a, #bannerText p").ieffembedfix();

	//Add class to last breadcrumb
	$('div#breadcrumb p span span:last').addClass('lastBreadcrumb');

	//Add class to first and last footer menu list item
	$('div#footer div ul li:first').addClass('firstMenuItem');
	$('div#footer div ul li:last').addClass('lastMenuItem');

	//Remove border-top from rates table's first td
	$('div.ratesTable tbody tr:first').find('td').css('border-top', 'none');

	//Remove border-bottom from standard table's last th
	$('table tbody tr th:last').css('border-bottom', 'none');

	//If there is no banner then remove margin, if banner has no content then hide
	$('#banner').each(function () {
		var bannerHtml = $('#banner').html();
		var additionalMargin;
		if ($('#content').hasClass('products')) additionalMargin = 1;
		if ($('#content').hasClass('category')) additionalMargin = 2;
		if ((bannerHtml != null) && (bannerHtml.trim() == "")) {
			$(this).css('width', 'auto');
			$('#content').css('margin-top', '0px');
			$('#sidebar').css('margin-top', '0px');
			switch (additionalMargin) {
				case 1:
					$('#sidebar').css('margin-top', '103px');
					break;
				case 2:
					$('#sidebar').css('margin-top', '185px');
					break;
			}
		};
		if ((bannerHtml != null) && (bannerHtml.trim() == "")) $('#banner').hide();
	});

	$('table#interestingDealsGrid tr').find('td:last').css('border-right', 'none');
	$('table#interestingDealsGrid tr').find('th:last').css('border-right', 'none');

	//Start underline function for content <div>
	$('#content').each(function () {
		$(this).underline();
	});

	//Add <p> to formattedTextArea and property pages in order to get black text
	$('div.formattedTextArea').find('li').wrapInner('<p>');
	$('div.lettingsPropertyDiv').find('li').wrapInner('<p>');

	//Remove border-bottom from lettingsPropertyDiv div
	$('div.lettingsPropertyDiv:last').css('border-bottom', 'none');

	//Add 'justify' class to next Div in teaser, remove justify for email form teaser, and fire justify()
	$('.justifyNext').find('div').addClass('justify');
	$('div.layout9').find('div').removeClass('justify');
	$('.justify').vjustify();

	//
	$('li.AspNet-TreeView-Parent ul li.AspNet-TreeView-Leaf a').css('padding-left', 0);
	$('li.AspNet-TreeView-Root > span').hide();

	//Banner loading image
	//$("div.csw").prepend("<p class='loading'>Loading...<br /><img src='/images/ajax-loader.gif' alt='loading...'/ ></p>");

	//Start banner
	$('div#slider1').each(function () {
		$(this).codaSlider();
	});

	//Add search activity spinner
	$('#related-nav p.searchButton a').click(function () {
		$(this).text('searching').css('color', 'black').css('outline', 'none').css('text-decoration', 'none').css('padding-left', '21px').css('background', 'url(../../images/spinner.gif) no-repeat 0 0');
	});

	//Fix for IE7 floated layout
	var newRowAt = 5;
	var inc = newRowAt - 1;
	$('li.AspNet-TreeView-Root').each(function (i) {
		if (newRowAt == i + 1) {
			$(this).before('<li class="clear-left">');
			//$(this).css('clear', 'left');
			newRowAt += inc;
		}
	});

	//Create 2 columns on product pages
	$('div.savingsProductDiv').each(function () {
		$(this).createProductColumns();
	});

	//Identify links to PDFs and add identifying text and force to open in a new window
	$("a[href*='pdf']" || "a[title*='pdf']").each(function () {
		var pdfLinkTitle = $(this).attr('title');
		pdfLinkTitle += " This link opens in a new window.";
		$(this).attr('title', pdfLinkTitle);
		$(this).append(' (PDF)');
		$(this).removeAttr('target');
		$(this).addClass('new-window');
	});

	//Add title to links requiring titles - this causes a tooltip to appear on FAQ tab and links that open a new window for accessibility
	$("a:contains('FAQs')").attr('title', 'Frequently asked questions');
	$("a[target='_blank']").each(function () {
		var linkTitle = ($(this).attr('title'));
		$(this).removeAttr('target').addClass('new-window');
		//If the new window link does not have a title attribute then add the tooltip text
		if (linkTitle == "") {
			$(this).attr('title', 'This link opens a new window')
		}
	});

	//Add underlines into footer of home page
	$('#content.home').each(function () {
		var footer = $('#footer');
		footer.prepend('<div class="underline"></div><div class="underline"></div><div class="underline lastUnderline"></div>');
		footer.css('margin-top', 0);
	});

	//Hide breadcrumb on error pages
	if (document.title == "Page not found" || document.title == "Access forbidden" || document.title == "Access denied") {
		$('div#breadcrumb').children().hide();
	};

	//Show declaration tab if linking from affinity
	$('#tabs').each(function () {
		var urlString = document.location.toString();
		if (urlString.match('#declare')) {
			$(this).find('#tabs-1').addClass('hidden');
			$(this).find("a[href='#tabs-1']").text('Declaration');
		} else {
			$('#TandCDeclaration').addClass('ui-tabs-hide');
		};
	});

	//Add <hr>s above <h3>s in formatted text areas
	$('div.formattedTextArea').find('h3:gt(0)').before('<hr />');
	$('.ratesTable').each(function () {
		var ratesToggles = $(this).find('a');
		if (ratesToggles.length > 0) {
			$(this).after('<hr />');
		}
	});

	//Start branch images rotation
	$('div.branchImages').each(function () {
		var imgNumber = $('div.branchImages IMG');
		if (imgNumber.length > 1) {
			setInterval("branchImagesRotate()", 5000);
		};
	});

	//Set default value into fields that require value
	jQuery(function ($) {
		$(".searchInput, .searchDiv input.textInput").defaultvalue(
			"Enter keyword(s)",
			"Enter town or postcode"
			);
	});
	jQuery(function ($) {
		$("div.teaser div.layout9 input.textInput").defaultvalue(
			"Your email address"
			);
	});
	jQuery(function ($) {
		$("input#metafaqHelp").defaultvalue(
			"Ask us a question..."
			);
	});

	//Email register popup start
	$("div.layout9").emailPopup()

	//    //Create sitemap structure
	//    $('li.AspNet-TreeView-Root').each(function() {
	//    });

	//create tab pages
	var $tabs = $("#tabs").tabs();
	var showFAQ = getParameterByName("showFAQ");
	if (showFAQ == "true") {
		$tabs.tabs('select', 'tabs-2');
	}
	var showTab = getParameterByName("showTab");
	if (showTab != null) {
		$tabs.tabs('select', 'tabs-' + showTab);
	}

	//Start toggle on anchors with class toggle
	$('a.toggle').toggle();

	//Remove double spaces from futureRatesNotice <p>
	//$('div.futureRatesNotice p').text().replace(/ /g, '');
	//    alert($('div.futureRatesNotice').text());
	////    $.trim($('div.futureRatesNotice').text())

	//Remove empty <li> on pager <ul>
	$('ul.pager li p:empty').parent('li').remove();

	//Add extra underline to search results page counter <ul>
	$('ul.pageCounter:last').addClass('underlineElement');

	//Start print page function for branch pages
	$('div.branchFinder, div.branchPage').each(function () {
		$(this).printPage();
	});

	//Customise dropdowns
	$('.jqtransform').each(function () {
		$(this).jqTransform();
	});

	//Start toogle on mortgage grid anchors
	$(this).showHideMortgageDetails();

	//Savings grid setup
	$("div.savingsTable table").savingsTableFormatting();
	$("div#filter a").click(function () {
		setTimeout(function () {
			$(this).savingsTableFormatting();
		}, 2500);
	});
	$("div.savingsTable table th a").live("click", function () {
		setTimeout(function () {
			$(this).savingsTableFormatting();
		}, 2500);
	});

	$(".review-comments input#showAll").click(function () {
		if ($(".review-comments input#showAll").attr("checked")) {
			$(".comment:empty").closest("li").slideUp("fast");
		} else {
			$(".comment:empty").closest("li").slideDown("fast");
		}
	});

	//Start insurance calculator
	$("div.insuranceCalc").insuranceCalc();

	// --- filter ---
	$(".category-filter-all input").click(function () {
		$(".category-filter input").attr("checked", false);
		setupAllCheckbox();
	});

	$(".category-filter input").click(function () {
		setupAllCheckbox();
	});

	function setupAllCheckbox() {
		$(".category-filter-all input").attr("checked", ($(".category-filter input:checked").length == 0));
	}



	//$("#filter a, th a").live("click", function() {
	// remove things added to the table
	//        $(".product-details").hide("fast", function() {
	//            $(".product-details").closest("tr").remove();
	//        });
	//});

	setupAllCheckbox();

	$("input.searchInput").keyup(function (event) {
		if (event.keyCode == 13) {
			$("p.searchButton a").click();
			return false;
		}
	});

	//New window onclick
	$('a.new-window').click(function () {
		window.open(this.href);
		return false;
	});

	//Metafaq help
	$('div#Metafaq').each(function () {
		var $this = $(this);
		$this.find('a').click(function () {
			var metafaqQuestion = $this.find('input').val();
			var windowSize = "width=1000,height=800,left=0,top=0,resizable=yes,scrollbars=yes,location=yes";
			if (metafaqQuestion) {
				window.open("http://ask.nandp.co.uk/templates/nandp/faqs/resultsPage?nlpq=" + metafaqQuestion, "MetaFaq", windowSize);
				return false;
			}
			window.open(this.href, "MetaFaq", windowSize);
			return false;
		});
	});

	//**Temporary fix**
	//Add news story link to highstreet branch images
	$('div.branchImages').each(function () {
		var branchName = { 'Ashby': 1, 'Bedford': 1, 'Chelmsford': 1, 'Clacton': 1, 'Colchester': 1, 'Halesworth': 1, 'Immingham': 1, 'Kettering': 1, 'Spilsby': 1, 'Unthank Road, Norwich': 1 };
		var branchArray = $('span.lastBreadcrumb').text();
		if (branchName[branchArray] == 1) {
			var path = window.location.pathname;
			$(this).find('img').wrap('<a>');
			var branchLink = $(this).find('a')
			branchLink.attr('href', 'http://www.nandp.co.uk' + path + 'branch-closure');
			branchLink.attr('title', 'The ' + branchArray + ' branch is closing. How will this effect you?');
		};
	});

}); 
//#endregion

//#region Toggle display function http://bassistance.de/jquery-plugins/jquery-plugin-tooltip/
jQuery.fn.toggle = function() {

	//Hide all toggle items, as long as they're not referenced by the current location hash
	this.each(function() {
		if (($(this).attr("name") == '') || (location.hash == '') || ($(this).attr("name") != location.hash.replace("#", ""))) {
			$(this).next().hide();
		}
	});
	if (location.hash && location.hash[0]) { // make sure top of window is the selected item
		window.location.hash = window.location.hash;
	}

	this.click(function() {
		//There are two different implementations of toggle functionality - FAQs and products. 
		//First check if it is the product implementation.
		var currentLinkLocation = $(this).parent().attr('class');
		if ((currentLinkLocation == 'future-rates') || (currentLinkLocation == 'current-rates') || (currentLinkLocation == 'previous-rates')) {
			if ($(this).next().is(":visible")) {
				$(this).next().slideUp("slow");
				$(this).removeClass('active');
			} else {
				$(this).addClass('active');
				$(this).next().slideDown("slow");
				//Tweak style of tables when shown
				$('div.ratesTable tbody tr:first').find('td').css('border-top', 'none');
				$('table tbody tr th:last').css('border-bottom', 'none');
			}
		} else {
			//It is an FAQ implementation
			$('a.toggle').removeClass('active');
			if ($(this).next().is(":visible")) {
				$(this).next().slideUp("slow");
			} else {
				$(this).closest("div").find("a.toggle").next().slideUp("slow");
				$(this).addClass('active');
				$(this).next().slideDown("slow");
				//Tweak style of tables when shown
				$('div.ratesTable tbody tr:first').find('td').css('border-top', 'none');
				$('table tbody tr th:last').css('border-bottom', 'none');
			}
		}
		return false;
	});
};
//#endregion

//#region Branch Image Rotation
function branchImagesRotate() {

	var $active = $('div.branchImages IMG.active');
	
	if ($active.length == 0) $active = $('div.branchImages IMG:last');

	// use this to pull the images in the order they appear in the markup
	var $next = $active.next().length ? $active.next()
		: $('div.branchImages IMG:first');

	// uncomment the 3 lines below to pull the images in random order

	// var $sibs  = $active.siblings();
	// var rndNum = Math.floor(Math.random() * $sibs.length );
	// var $next  = $( $sibs[ rndNum ] );

	$active.addClass('last-active');

	$next.css({ opacity: 0.0 })
		.addClass('active')
		.animate({ opacity: 1.0 }, 1000, function() {
			$active.removeClass('active last-active');
		});
};
//#endregion

//#region Build two column of products
jQuery.fn.createProductColumns = function() {
	var firstColumn = this.find('p:even');
	var secondColumn = this.find('p:odd');
	firstColumn.wrapAll('<div>').parent().addClass('firstProductColumn');
	secondColumn.wrapAll('<div>');
};
//#endregion

//#region Build two column bullet list
jQuery.fn.buildTwoColumnBulletList = function() {
	var formattedTextAreaUls = $('div.formattedTextArea ul').siblings('ul');
	if (formattedTextAreaUls.length > 1) {
		formattedTextAreaUls.eq(1).addClass('float-left');
		formattedTextAreaUls.eq(0).addClass('secondColumn');
		$('div.formattedTextArea ul').wrapAll('<div style="overflow:auto">');
	};
};
//#endregion

//#region Add print button to branch finder and branch page
jQuery.fn.printPage = function() {
	$('div#breadcrumb').append('<a class="printPage" href="#print">print page</a>');
	$('div#breadcrumb a.printPage').click(function() {
		window.print();
		return false;
	});
};
//#endregion

//#region Underline content <div>
jQuery.fn.underline = function() {
	var contentTeaser = this.children('div.teaser');
	//Check if content div contains teasers
	if (contentTeaser.html() != null || this.hasClass('noUnderline')) {
		var teaserHtml = contentTeaser.html();
		//Check if teasers have content
		if ((teaserHtml != null) && (teaserHtml.trim() == "")) {
			this.addClass('underlineElement');
		}
	}
	else {
		this.addClass('underlineElement');
	};
//    alert($('#content').html());
};
//#endregion

//#region Vertical justify function http://michael.futreal.com/jquery/vjustify
jQuery.fn.vjustify = function() {
	var maxHeight = 0;
	this.each(function() {
		if (this.offsetHeight > maxHeight) { maxHeight = this.offsetHeight; }
	});
	this.each(function() {
		$(this).height(maxHeight + "px");
		if (this.offsetHeight > maxHeight) {
			$(this).height((maxHeight - (this.offsetHeight - maxHeight)) + "px");
		}
	});
};
//#endregion

//#region jQuery Default Value Plugin v1.0 http://www.campbellsdigitalsoup.co.uk/about/default-value
(function($) {
	$.fn.defaultvalue = function() {
		// Scope
		var elements = this;
		var args = arguments;
		var c = 0;
		return (
			elements.each(function() {
				// Default values within scope
				var el = $(this);
				var def = args[c++];

				el.val(def).focus(function() {
					if (el.val() == def) {
						el.val("");
					}
					el.blur(function() {
						if (el.val() == "") {
							el.val(def);
						}
					});
				});
			})
		);
	}
})(jQuery)
//#endregion

//#region Product details gridview show hide
jQuery.fn.showHideMortgageDetails = function() {
	$("a.details").live("click", function() {
		var close = false;
		if ($(this).closest("tr").hasClass("selected")) {
			close = true;
		}

		// hide previously selected row
		var previousSelected = $("a.details.selected");
		if (previousSelected.length > 0) {
			var previousSelectedDiv = previousSelected.closest("tr").removeClass("selected").next().find(".product-details");
			previousSelectedDiv.slideUp();
			previousSelected.removeClass("selected");
			$("input.selectedUrl").val("");
		}

		if (!close) {
			var selectedRow = $(this).closest("tr");
			var selectedUrl = $(this).attr("href");            
			
			displayNextRow(selectedRow, selectedUrl, false);

			// update the reference to the currently selected url
			$("input.selectedUrl").val(selectedUrl);
		}
		return false;
	});
};
//#endregion

//#region Reselect Details
function reselectDetails() {
	var selectedUrl = $("input.selectedUrl").attr("value");
	var noReselectField = $("input.noReselect");
	if (selectedUrl != "" && noReselectField.attr("value") == "") {  
		$(".mortgageTable tr a.details").each(function() {
			if ($(this).attr("href") == selectedUrl) {
				displayNextRow($(this).closest("tr"), selectedUrl, true);
			}
		});
	}
	noReselectField.val("");
}
//#endregion

//#region Display Next Row
function displayNextRow(selectedRow, selectedUrl, immediate) {
	// both the row and the link need to be marked as "selected"
	selectedRow.addClass("selected");
	selectedRow.find("a.details").addClass("selected");
	
	var nextRowDiv = selectedRow.next().find(".product-details");

	// if the details div hasn't been created yet, do it now
	if (nextRowDiv.length == 0) {
		var colSpan = selectedRow.children().length;
		var newRow = selectedRow.after("<tr><td colspan='" + colSpan + "' class='product-details-td'><div class='product-details' style='display:none' /></td></tr>").next();
		nextRowDiv = newRow.find(".product-details");
		nextRowDiv.css({ "background-color": $("body").css("background-color") });

		nextRowDiv.load(selectedUrl + " #productDetailsWrapper", "", function(responseText, textStatus, XMLHttpRequest) {
			//Check if two column bullet list present
			$(this).buildTwoColumnBulletList();

			//Show the panel
			if (!immediate) {
				$(this).slideDown("slow");
			} else {
				$(this).show();
			}

			$('div.formattedTextArea').find('li').wrapInner('<p>');
		});

	} else {
		nextRowDiv.slideDown("slow");
	}
}
//#endregion

//#region Banner function (based on jQuery Coda-Slider v1.1 - http://www.ndoherty.com/coda-slider)
var iTimer;
var previousColour;
var currentColour;
var cPanel = 1;
var moveTime = 200;
jQuery.fn.codaSlider = function() {
	return this.each(function() {
		var container = jQuery(this);

		// Remove the preloader gif...
		container.find("p.loading").remove();

		// Self-explanatory...
		container.removeClass("csw").addClass("stripViewer");

		// Get the width of a panel, set from CSS...
		var panelWidth = container.find("div.panel").width();

		// panelCount gives us a count of the panels in the container...
		var panelCount = container.find("div.panel").size();

		// Calculate the width of all the panels when lined up end-to-end...
		var stripViewerWidth = panelWidth * panelCount;

		// Use the above width to specify the CSS width for the panelContainer element...
		container.find("div.panelContainer").css("width", stripViewerWidth);

		//IE cleartype bug fix - this set background colour to avoid cleartype anti-alias bug on fadeOut / fadeIn.
		$("div.panelContainer").css({ "background-color": $("body").css("background-color") });

		//container.find('div.panelContainer').removeClass('hide');
		//$("div#banner").removeClass("hidden");

		// Create appropriate nav
		container.each(function(i) {

			// Create the Left and Right arrows
			jQuery(this).before("<div class='stripNavL' id='stripNavL'><a href='#'><span>Left</span></a><\/div>");
			jQuery(this).after("<div class='stripNavR' id='stripNavR'><a href='#'><span>Right</span></a><\/div>");

			//Add class current to first panel
			$("div.panel").eq(0).addClass("current");

			//Add colour class to bannerPanel div to colour border 
			currentColour = $("div.panel").eq(0).find("div#bannerText").attr("class");
			currentColour = currentColour + "Border";
			$("div#banner div.bannerPanel").addClass(currentColour);

			// Left nav
			jQuery("div#stripNavL a").click(function() {
				var prevPanel = cPanel;

				if (cPanel == 1) {
					var cnt = -(panelWidth * (panelCount - 1));
					cPanel = panelCount;
				} else {
					cPanel -= 1;
					var cnt = -(panelWidth * (cPanel - 1));
				};
				$("div.panelContainer").fadeOut(1000).animate({ left: cnt }, moveTime).fadeIn(1000);

				//Stop the banner rotate
				clearInterval(iTimer);

				//Change the colour class for the border
				previousColour = $("div.panel").eq(prevPanel - 1).find("div#bannerText").attr("class");
				$("div#banner div.bannerPanel").removeClass(previousColour);

				currentColour = $("div.panel").eq(cPanel - 1).find("div#bannerText").attr("class");
				$("div#banner div.bannerPanel").addClass(currentColour);

				//Change the panel class to current
				$("div.panel").eq(prevPanel - 1).removeClass("current");
				$("div.panel").eq(cPanel - 1).addClass("current");

				return false;
			});

			// Right nav
			jQuery("div#stripNavR a").click(function() {
				var prevPanel = cPanel;

				if (cPanel == panelCount) {
					var cnt = 0;
					cPanel = 1;
				} else {
					var cnt = -(panelWidth * cPanel);
					cPanel += 1;
				};
				$("div.panelContainer").fadeOut(1000).animate({ left: cnt }, moveTime).fadeIn(1000);

				//Stop the banner rotate
				clearInterval(iTimer);

				//Change the colour class for the border
				previousColour = $("div.panel").eq(prevPanel - 1).find("div#bannerText").attr("class");
				$("div#banner div.bannerPanel").removeClass(previousColour);

				currentColour = $("div.panel").eq(cPanel - 1).find("div#bannerText").attr("class");
				$("div#banner div.bannerPanel").addClass(currentColour);

				//Change the panel class to current
				$("div.panel").eq(prevPanel - 1).removeClass("current");
				$("div.panel").eq(cPanel - 1).addClass("current");

				return false;
			});

			function rotateBanner() {
				var prevPanel = cPanel;

				if (cPanel == panelCount) {
					var cnt = 0;
					cPanel = 1;
				} else {
					var cnt = -(panelWidth * cPanel);
					cPanel += 1;
				};
				$("div.panelContainer").fadeOut(1000).animate({ left: cnt }, moveTime).fadeIn(1000);

				//Change the colour class for the border
				previousColour = $("div.panel").eq(prevPanel - 1).find("div#bannerText").attr("class");
				previousColour = previousColour + "Border";
				$("div#banner div.bannerPanel").removeClass(previousColour);

				currentColour = $("div.panel").eq(cPanel - 1).find("div#bannerText").attr("class");
				currentColour = currentColour + "Border";
				$("div#banner div.bannerPanel").addClass(currentColour);

				//Change the panel class to current
				$("div.panel").eq(prevPanel - 1).removeClass("current");
				$("div.panel").eq(cPanel - 1).addClass("current");

			};

			//Rotate the banners if the left or right arrows have not been clicked, if there is only one banner then don't rotate
			if (panelCount == 1) {
				clearInterval(iTimer);
				$("div.stripNavL").hide();
				$("div.stripNavR").hide();
			}
			else {
				iTimer = setInterval(function() {
					rotateBanner();
				}, 17000);
			};
		});
	});
};
//#endregion

//#region Get Parameter By Name
function getParameterByName(name) {  
	name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");  
	var regexS = "[\\?&]"+name+"=([^&#]*)";  
	var regex = new RegExp( regexS );  
	var results = regex.exec( window.location.href );  
	return (results == null) ? "" : results[1];
}
//#endregion

//Popup functions for email registration
jQuery.fn.emailPopup = function() {
	var teaserDiv = $(this);
	var emailTextInput = teaserDiv.find(".textInput");
	teaserDiv.find(".button").click(function() {
		//Remove any error messages that may already be added.
		teaserDiv.find("span.ErrorMessage").remove();
		var email = emailTextInput.val();
		var formSrc = teaserDiv.find(".popupIFrame").attr("src");
		if (email != 0 && email != "Your email address") {
			if (isValidEmailAddress(email)) {
				teaserDiv.find(".popupIFrame").attr("src", formSrc + "&email=" + email);
				centerPopup();
			} else {
				teaserDiv.find("p.errorHolder").append("<span class='ErrorMessage'>There appears to be a problem with this email address. Please re-enter your email address.</span>");
				emailTextInput.addClass("errorStyle");
			}
		} else {
			teaserDiv.find("p.errorHolder").append("<span class='ErrorMessage'>Please enter your email address</span>");
			emailTextInput.val("Your email address").addClass("errorStyle");
		}
		return false;
	});
	//Remove any error messages that may already be added.
	emailTextInput.focus(function() {
		$(this).removeClass("errorStyle").val("");
		teaserDiv.find("span.ErrorMessage").remove();
	});
	$("a.popupClose").click(function() {
		disablePopup();
		emailTextInput.val("Your email address");
	});
	$("a.closeButton").click(function() {
		disablePopup();
		emailTextInput.val("Your email address");
	});
	$("#mask").click(function() {
		disablePopup();
		emailTextInput.val("Your email address");
	});
}

function centerPopup() {
	var windowHeight = document.documentElement.clientHeight;
	var vspaceHeight = windowHeight / 2 - 300
	var scrollPosition = $(window).scrollTop();
	var popupForm = $("#popupForm");
	popupForm.css({
		"top": scrollPosition + vspaceHeight
	});
	$("#mask").css({
		"height": $(document).height(),
		"opacity": "0.7"
	});
	$("#mask").fadeIn("slow");
	popupForm.css("display", "block");
	popupForm.css({
		"left": 180
	});
}

function disablePopup(){  
	//disables popup only if it is enabled  
	$("#mask").fadeOut("slow");
	$("#popupForm").fadeOut("slow");
}

//Insurance calculator
jQuery.fn.insuranceCalc = function() {

	//Setup global variables
	var pageNo = 1;
	var subTotal = 0;
	var runningSubTotal = 0;

	//DOM object selection operations
	var nextButton = $("a.next");
	var previousButton = $("a.previous");
	var roomImage = $("div.calculatorHolder img");

	//Reset any cached values in all fields and tables
	$("fieldset input").val('');
	$("div.calculatorHolder input:hidden").val(0);

	$("a#CalculatorStart").click(function() {
		//Alter layout elements
		$("p.calculatorDesc").addClass("hide");
		$("tfoot tr:eq(0)").css("display", "none");
		$("tfoot").find("tr.hide").removeClass();
		$("div.questionHolder").removeClass("hide");
		//$("div.calculatorHolder").css("border-bottom", "1px solid #7D1B7F");
		$(".insuranceCalc li div").css("display", "none");
		//Modify the default call to action styling
		modifyCallToAction();
		//Calculate the total
		calculateTotal(pageNo, subTotal);
		//Move to the next page
		changePage(pageNo, subTotal);
		return false;
	});

	nextButton.click(function() {
		//Check if it is the summary page
		if (pageNo < 8) {
			//Get subtotal for current room from hidden field 
			subTotal = parseFloat($("fieldset#Questions" + pageNo + " input.subTotal").val());
			subTotal = isNaN(subTotal) ? 0 : subTotal;
			//Alter layout elements
			$("fieldset#Questions" + pageNo).addClass("hide");
			$("div#tipsArea" + pageNo).addClass("hide");
			//Update table row with room subtotal
			updateCalculatorRow(pageNo, subTotal);
			//Move to next page
			pageNo++
			changePage(pageNo, subTotal);
			subTotal = 0;
		} else {
			//Show the summary page
			//Get subtotal for current room from hidden field 
			subTotal = parseFloat($("fieldset#Questions" + pageNo + " input.subTotal").val());
			subTotal = isNaN(subTotal) ? 0 : subTotal;
			//Select the table row
			selectCalculatorRow(pageNo);
			//Alter layout elements
			$("fieldset#Questions" + pageNo).addClass("hide");
			$("div#tipsArea" + pageNo).addClass("hide");
			roomImage.attr({
				"src": "../../images/insurance/insuranceHouseRoom0.jpg",
				"width": "255"
			});
			//Update table row with room subtotal
			updateCalculatorRow(pageNo, subTotal);
			//Move to next page
			pageNo++
			//Alter layout elements
			$(this).after("<a class='button restart'>Calculate again</a>").css("display", "none");
			$("a.restart").click(function() { location.reload(true); });
			previousButton.css("display", "none");
			$("div#Summary").removeClass("hide");
			//Calculate total
			calculateTotal(pageNo, subTotal);
		}
		return false;
	});

	previousButton.click(function() {
		subTotal = parseFloat($("fieldset#Questions" + pageNo + " input.subTotal").val());
		subTotal = isNaN(subTotal) ? 0 : subTotal;
		nextButton.text("Next room");
		$("fieldset#Questions" + pageNo).addClass("hide");
		$("div#tipsArea" + pageNo).addClass("hide");
		updateCalculatorRow(pageNo, subTotal);
		pageNo--
		subTotal = 0;
		changePage(pageNo, subTotal);
		return false;
	});

	function changePage(pageNo, subTotal) {
		//Change the room image
		roomImage.attr("src", "../../images/insurance/insuranceHouseRoom" + pageNo + ".jpg");
		$("fieldset#Questions" + pageNo).removeClass("hide");
		$("div#tipsArea" + pageNo).removeClass("hide");
		if (pageNo > 1 && pageNo < 9) {
			previousButton.css("display", "block");
		} else {
			previousButton.css("display", "none");
		}
		if (pageNo >= 8) {
			nextButton.text("Summary");
		}
		selectCalculatorRow(pageNo, subTotal);
		calculateTotal(pageNo, subTotal);
	}

	function selectCalculatorRow(pageNo) {
		if (pageNo < 9) {
			var selectedRoomInputValue = $("div.calculatorHolder input#roomInput" + pageNo).val();
			var selectedRoom = $("tr#room" + pageNo);
			var selectedRoomName = selectedRoom.find("th").text();
			selectedRoom.empty();
			selectedRoom.append('<th class="selected">' + selectedRoomName + '</th>');
			selectedRoom.append('<td class="selected">£' + selectedRoomInputValue + '</td>');
		}
	}

	function updateCalculatorRow(pageNo, subTotal) {
		var selectedRoom = $("tr#room" + pageNo);
		var selectedRoomName = selectedRoom.find("th").text();
		selectedRoom.empty();
		selectedRoom.append('<th class="highlight8">' + selectedRoomName + '</th>');
		selectedRoom.append('<td class="highlight8 completed">£' + subTotal + '</td>');
		$("div.calculatorHolder input#roomInput" + pageNo).val(subTotal);
	}

	function calculateTotal(pageNo, subTotal) {
		var runningTotal = 0;
		$("div.calculatorHolder input:hidden").each(function() {
			var fieldValue = $(this).val();
			if (fieldValue) {
				runningTotal = (parseFloat(runningTotal) + parseFloat(fieldValue)).toFixed(2);
			}
		});
		var selectedTotal = $("tr#total");
		selectedTotal.find("td").remove();
		selectedTotal.append('<td class="highlight8">£' + runningTotal + '</td>');
		if (pageNo == 9) {
			$("div#Summary p.highlight8").append(runningTotal);
		}
		runningTotal = 0;
	}

	for (currentPageNo = 1; currentPageNo < 9; ++currentPageNo) {
		var subTotalFields = $("fieldset#Questions" + currentPageNo + " input.textInput");

		subTotalFields.keypress(function(e) {
			// Only allow numeric input. Allow only backspace, delete, fullstop and Firefox tab
			if (e.which == 46 || e.which == 8 || e.which == 190 || e.keyCode == 9) {
				// let it happen, don't do anything
			} else {
				// Ensure that it is a number and stop the keypress
				if (e.which < 48 || e.which > 57) { e.preventDefault(); }
			}
		});
		subTotalFields.focus(function() {
			$(".insuranceCalc li div:visible").fadeOut("slow");
			$(this).next("div").fadeIn("slow");
		});
		subTotalFields.blur(function() {
			var parsedValue = $(this).val();
			//check the field value is a number again
			parsedValue.replace(/(^-?\d+$)|(^-?\d+\.\d+$)/);
			//If the field has been completed then format and add to the running total
			if (parsedValue) {
				//format to two decimal places
				parsedValue = parseFloat(parsedValue).toFixed(2);
				$(this).val(parsedValue);
				//Add the value of the fields to the subtotal
				$(this).closest("ul").find("input.textInput").each(function() {
					var fieldValue = $(this).val();
					if (fieldValue) {
						runningSubTotal = (parseFloat(runningSubTotal) + parseFloat(fieldValue)).toFixed(2);
					}
				});
				$(this).closest("ul").find("input.subTotal").val(runningSubTotal);
				runningSubTotal = 0;
			}
		});
	}

	function modifyCallToAction() {
		$("div.calcCallToAction").each(function() {
			var H3Text = $(this).find("h3").text();
			var PText = $(this).find("p").text();
			$(this).find("p").replaceWith("<p class='highlight7'>" + PText + "</p>");
			$(this).find("h3").replaceWith("<p class='highlight8'>" + H3Text + "</p>");
			$(this).find("img").attr("src", "../../images/insurance/phone_red.jpg");
			$(this).removeClass("hide");
		});
	}

}

//No wrap account balance column width on Savings grid (a pause is required with results returned when filtering)
jQuery.fn.savingsTableFormatting = function() {
	$("table.savingsNestedHead").parent("th").css("padding", "0");
	var savingsNestedTable = $("table.savingsNestedTable");
	savingsNestedTable.parent("td").css("padding", "0");
	savingsNestedTable.find("tr:last td").each(function() {
		$(this).css("border-bottom", "none");
	});
	var savingsTable = $("div.savingsTable table").eq(0);
	var savingsNestedTable = savingsTable.find("table.savingsNestedTable");
	var savingsNestedHead = savingsTable.find("table.savingsNestedHead");
	//Add classes to head to achieve desired widths
	savingsNestedHead.find("th:nth-child(1)").addClass("accountBalanceCol");
	//Add classes to columns to achieve desired widths
	savingsTable.find("tr>td:nth-child(1)").addClass("accountCol").end().find("tr>td:nth-child(2)").addClass("accountTypeCol");
	savingsNestedTable.find("tr>td:nth-child(1)").addClass("accountBalanceCol");
}

//---- Validation ----
//Email
function isValidEmailAddress(emailAddress) {
	var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
	return pattern.test(emailAddress);
}
//Number
function isValidNumber(obj) {
	val = obj.value;
	cur = /^-?\d{1,3}(,\d{3})*(\.\d{1,2})?$/;
	anum = /(^-?\d+$)|(^-?\d+\.\d+$)/;
	ret = false;
	if (val.indexOf(",") > -1)
		ret = cur.test(val);
	else
		ret = anum.test(val);
	if (!ret) {
		alert("Invalid number format");
		return false;
	}
	else
		return true;
}
