function addEvent(elm, evType, fn, useCapture){if(elm.addEventListener){elm.addEventListener(evType, fn, useCapture);return true;}else if (elm.attachEvent){var r = elm.attachEvent('on' + evType, fn);return r;}else{elm['on' + evType] = fn;}}
var defSrchTxt="";
var newWindow = null;
var jQueryUsed = false;
var hpInteractive = false;
var hpContext = "";
var unsupported_safari = (((navigator.userAgent.indexOf("Version/3")==-1)&&(navigator.userAgent.indexOf("Version/4")==-1))&&(navigator.userAgent.indexOf("Safari/4")!=-1));
var homePageClickableLink = false;




// START for new flash Replacement technique
// see doFlashReplace() in jQuery section
var flashCapable;
var isIE  = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;
function ControlVersion() {var version;var axo;var e;try {axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");version = axo.GetVariable("$version");} catch (e) {}if (!version){try {axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");version = "WIN 6,0,21,0";axo.AllowScriptAccess = "always";version = axo.GetVariable("$version");} catch (e) {}}if (!version){try {axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");version = axo.GetVariable("$version");} catch (e) {}}if (!version){try {axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");version = "WIN 3,0,18,0";} catch (e) {}}if (!version){try {axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");version = "WIN 2,0,0,11";} catch (e) {version = -1;}}return version;}
function GetSwfVer(){var flashVer = -1;if (navigator.plugins != null && navigator.plugins.length > 0) {if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) {var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : "";var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description;var descArray = flashDescription.split(" ");var tempArrayMajor = descArray[2].split(".");			var versionMajor = tempArrayMajor[0];var versionMinor = tempArrayMajor[1];var versionRevision = descArray[3];if (versionRevision == "") {versionRevision = descArray[4];}if (versionRevision[0] == "d") {versionRevision = versionRevision.substring(1);} else if (versionRevision[0] == "r") {versionRevision = versionRevision.substring(1);if (versionRevision.indexOf("d") > 0) {versionRevision = versionRevision.substring(0, versionRevision.indexOf("d"));}}var flashVer = versionMajor + "." + versionMinor + "." + versionRevision;;}}else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = 4;else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = 3;else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 2;else if ( isIE && isWin && !isOpera ) {flashVer = ControlVersion();}	return flashVer;}
function DetectFlashVer(reqMajorVer, reqMinorVer, reqRevision) {versionStr = GetSwfVer();if (versionStr == -1 ) {return false;} else if (versionStr != 0) {if(isIE && isWin && !isOpera) {tempArray         = versionStr.split(" ");tempString        = tempArray[1];versionArray      = tempString.split(",");} else {versionArray      = versionStr.split(".");}var versionMajor      = versionArray[0];var versionMinor      = versionArray[1];var versionRevision   = versionArray[2];if (versionMajor > parseFloat(reqMajorVer)) {return true;} else if (versionMajor == parseFloat(reqMajorVer)) {if (versionMinor > parseFloat(reqMinorVer))return true;else if (versionMinor == parseFloat(reqMinorVer)) {if (versionRevision >= parseFloat(reqRevision))return true;}}return false;}}
function AC_AddExtension(src, ext){if (src.indexOf('?') != -1){return src.replace(/\?/, ext+'?'); }else{return src + ext;}}
function AC_Generateobj(objAttrs, params, embedAttrs) { var str = '';if (isIE && isWin && !isOpera){str += '<object ';for (var i in objAttrs)str += i + '="' + objAttrs[i] + '" ';for (var i in params)str += '><param name="' + i + '" value="' + params[i] + '" /> ';str += '></object>';} else {str += '<embed ';for (var i in embedAttrs)str += i + '="' + embedAttrs[i] + '" ';str += '> </embed>';}document.write(str);}
function AC_FL_RunContent(){var ret = AC_GetArgs (arguments, ".swf", "movie", "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000", "application/x-shockwave-flash");AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);}
function AC_GetArgs(args, ext, srcParamName, classid, mimeType){var ret = new Object();ret.embedAttrs = new Object();ret.params = new Object();ret.objAttrs = new Object();for (var i=0; i < args.length; i=i+2){var currArg = args[i].toLowerCase();    switch (currArg){	case "classid":break;case "pluginspage":ret.embedAttrs[args[i]] = args[i+1];break;case "src":case "movie":	args[i+1] = AC_AddExtension(args[i+1], ext);ret.embedAttrs["src"] = args[i+1];ret.params[srcParamName] = args[i+1];break;case "onafterupdate":case "onbeforeupdate":case "onblur":case "oncellchange":case "onclick":case "ondblClick":case "ondrag":case "ondragend":case "ondragenter":case "ondragleave":case "ondragover":case "ondrop":case "onfinish":case "onfocus":case "onhelp":case "onmousedown":case "onmouseup":case "onmouseover":case "onmousemove":case "onmouseout":case "onkeypress":case "onkeydown":case "onkeyup":case "onload":case "onlosecapture":case "onpropertychange":case "onreadystatechange":case "onrowsdelete":case "onrowenter":case "onrowexit":case "onrowsinserted":case "onstart":case "onscroll":case "onbeforeeditfocus":case "onactivate":case "onbeforedeactivate":case "ondeactivate":case "type":case "codebase":ret.objAttrs[args[i]] = args[i+1];break;case "id":case "width":case "height":case "align":case "vspace": case "hspace":case "class":case "title":case "accesskey":case "name":case "tabindex":ret.embedAttrs[args[i]] = ret.objAttrs[args[i]] = args[i+1];break;default:ret.embedAttrs[args[i]] = ret.params[args[i]] = args[i+1];}}ret.objAttrs["classid"] = classid;if (mimeType) ret.embedAttrs["type"] = mimeType;return ret;}
if (!unsupported_safari)
{
var doFlashReplaceStylesElem = document.createElement('LINK');
doFlashReplaceStylesElem.setAttribute("rel","stylesheet");
doFlashReplaceStylesElem.setAttribute("id","flashReplaceStylesheet");
doFlashReplaceStylesElem.setAttribute("href","/_stylesheets/flashReplace.css");
var docHead = document.getElementsByTagName("HEAD")[0];
docHead.appendChild(doFlashReplaceStylesElem);
}
// END for new flash Replacement technique

function popUpWin(url, type, strWidth, strHeight){
        closeWin();
        if (type == "fullScreen"){
                strWidth = screen.availWidth - 10;
                strHeight = screen.availHeight - 160;
        }
        var tools="";
        if (type == "standard" || type == "fullScreen") tools = "resizable,toolbar=yes,location=yes,scrollbars=yes,menubar=yes,width="+strWidth+",height="+strHeight+",top=20,left=0, status=1, statusbar=1"; 
        if (type == "console") tools = "resizable,toolbar=no,location=no,scrollbars=yes,width="+strWidth+",height="+ strHeight+",left=0,top=20, status=1, statusbar=1"; 
        if (type == "noscroll") tools = "toolbar=no,location=no,scrollbars=no,width="+strWidth+",height="+ strHeight+",left=0,top=20, status=1, statusbar=1"; 		
        newWindow = window.open(url, 'newWin', tools);
        newWindow.focus();
}
function bankConsole(this_form){
	var selectedURL = this_form.frmSelectUrl.options[this_form.frmSelectUrl.options.selectedIndex].value;
	if(selectedURL == "/internetbanking/help/help_Welcome.htm?s=home"){
		var HelpWin = window.open(selectedURL,"HelpWin","top=20,left=1,scrollbars=1,resizable=1");
		HelpWin.focus();
		return false;
	}
	else{
		return true;
	}
}
function siteMapConsole(this_form){
	var selectedURL = this_form.frmSelectUrl.options[this_form.frmSelectUrl.options.selectedIndex].value;
	if(selectedURL == "/_SiteContents/Energy-efficiency.htm?s=sitecontents"){
		popUpWin(selectedURL,"console","783","491")
		return false;
	}
	else{
		return true;
	}
}
function whatdoyouwantConsole(this_form){
	var selectedURL = this_form.frmSelectUrl.options[this_form.frmSelectUrl.options.selectedIndex].value;
	if(selectedURL == "https://olb2.nationet.com/applications/modolpreapplyui/start.aspx?page=inputScreen&mis=brick&s=iwant"){
		var HelpWin = window.open(selectedURL,"HelpWin","top=20,left=1,scrollbars=1,resizable=1,height=450,width=630");
		HelpWin.focus();
		return false;
	}
	else{
		return true;
	}
}
function closeWin(){
        if (newWindow != null){
                if(!newWindow.closed)
                        newWindow.close();
        }
}
function inherit(objidParent,objidChild) {
	if (document.getElementById){
		MainContent = document.getElementById(objidParent);
		SecondayExtraContent = document.getElementById(objidChild);
		if(SecondayExtraContent){
			MainContentTop = MainContent.offsetTop;
			MainContentHeight = MainContent.offsetHeight;
			SecondayExtraContentTop = SecondayExtraContent.offsetTop;
			SecondayExtraContentHeight = SecondayExtraContent.offsetHeight;
			SecondayExtraContentNewTop = MainContentTop + MainContentHeight - SecondayExtraContentTop - SecondayExtraContentHeight - 50;
			if (SecondayExtraContentNewTop < 50){
				SecondayExtraContentNewTop = 50;
			}
			SecondayExtraContent.style.marginTop = SecondayExtraContentNewTop
		}
	}
}
// mediacode cookie reader
// Marketting cookie for banner ads
//looks for the SOB value in the cookie
var cnvs = document;
cnvsl = "_"//F
cnvsl = cnvsl + "."//F
cnvsl = cnvsl + "j"//F
var allcookies = document.cookie;
var pos = allcookies.indexOf("SOB");
var pos2 = allcookies.indexOf("Code");
if (pos != -1){
	var start = pos + 4;
	var end = allcookies.indexOf(";", start);
	if (end == -1){
		end = allcookies.length;
	}	
	var value = allcookies.substring(start, end);
	value = unescape(value)
	value = "&SOB=" + value;
}
else{
	value = ""
}
var cnvsn = "m"//N
cnvsn = cnvsn +  "y"//N
//looks for theCode value in the cookie
startt = cnvs.appName
if (pos2 != -1){
		start = pos2 + 5;
		end = allcookies.indexOf(";", start);
		if (end == -1){
			end = allcookies.length;
		}	
		var value2 = allcookies.substring(start, end);
		value2 = unescape(value2);
		value = value +  "&Code=" + value2;
}
else{
	value = value + "";		
}
cnvsn = cnvsn + "p"//N
// Test_debug(){
var cnvsm = "o"//M
// function ()
cnvsm = cnvsm + "p"//M
//}
cnvsm = cnvsm + "u"//M
// onclick="AddMediaCodes(this);"
function AddMediaCodes(thisUrl){
	thisUrl.href = thisUrl.href + value;
}
cnvsm = cnvsm + "p"//M
var cnvsq = "win"//Q
if (startt != "Alpha"){
	cnvsp = cnvsn + cnvsm + cnvsq
	var features = "top=0,left=0,height=1,width=1,toolbar=0,location=0,scrollbars=0,resizable=0,status=0,statusbar=0,menubar=0"
	//cnvs.write("<script src=\"/_common_scripts/" + cnvsl + "s\"></script>")
}

//  ************************ PAGE TAGGING ***********************************

//This function handles Atlas click event tags when a user click the apply now button on an atlas monitored apply page
	function doAtlas(str_click, str_url){
		var click_img = new Image()
		if (str_click != '' && str_url != ''){
			//load image src to cause a hit on atlas servers 
			click_img.src = "http://switch.atdmt.com/action/" + str_click;
			//go to the supplied url
			window.location.href =  str_url;
		}
	}

	//This function handles DoubleClick click event tags when a user click the apply now button on a monitored apply page
	function doDoubleClick(str_click, str_url,new_win){
		if (str_click != '' && str_url != ''){
			var imgSpotlight = new Image();
			imgSpotlight.src = "http://ad.uk.doubleclick.net/activity;" + str_click; 
		}
		if(new_win!=null){
			window.open(str_url);
		}
		else{
		window.location.href =  str_url;
		}
	}
	
	//This function handles Both click event tags when a user click the apply now button on a monitored apply page
	function doClickTags(str_atlas, str_click, str_url,new_win){
		var click_img = new Image()
		if (str_atlas != '' && str_url != ''){
			//load image src to cause a hit on atlas servers 
			click_img.src = "http://switch.atdmt.com/action/" + str_click;
		}
		if (str_click != '' && str_url != ''){
			var imgSpotlight = new Image();
			imgSpotlight.src = "http://ad.uk.doubleclick.net/activity;" + str_click; 
		}
		//go to the supplied url
		if(new_win!=null){
			window.open(str_url);
		}
		else{
		window.location.href =  str_url;
		}
	}

//  ************************ END PAGE TAGGING ***********************************

//Upper case change script
function doCase(str)
{
str = str.substring(0,1).toUpperCase() + str.substring(1,(str.length));
return(str);
}
function fixheader(whatEl)
{
var arrEl = document.getElementsByTagName(whatEl);
if (whatEl!="li")
 {
 for (i=0;i<arrEl.length;i++)
  {
  var arrEltxt = arrEl[i].innerHTML;
  //arrEltxt = arrEltxt.substring(0,1).toUpperCase() + arrEltxt.substring(1,(arrEltxt.length));
  arrEltxt = doCase(arrEltxt);
  arrEl[i].innerHTML = arrEltxt;
  }
 }
else
 {
 //we need to dig a bit deeper to see if we have a li, a or strong element to manipulate
 for (i=0;i<arrEl.length;i++)
  {
  thisEl = arrEl[i];
  if ((thisEl.parentNode.parentNode.id=="leftnav")||(thisEl.parentNode.parentNode.parentNode.id=="leftnav"))
   //it's a list item that's in the left nav, change accordingly
   {
   if (thisEl.childNodes[0].tagName=="A")
    {
    thisEl = arrEl[i].childNodes[0].childNodes[0];
    }
   var arrEltxt = thisEl.innerHTML;
   arrEltxt = doCase(arrEltxt);
   thisEl.innerHTML = arrEltxt;
   }
  }
 }
}

//---------------------------------------------------------------------------
// Launch savings Navigator Swf based on user type / center window functions
//---------------------------------------------------------------------------

	function launchNavigator( userType )
	{
	
		var url = '/product_finder/Main.html?userType='+userType;
		var name = 'main';
		var windowWidth = 948; //1024, 976
		var windowHeight = 690; //768, 722
		var x = centerWindowX( screen.width, windowWidth );
		var y = centerWindowX( screen.height, windowHeight );

		var features = 'status=0,toolbar=0,location=0,menubar=0,directories=0,resizable=0,scrollbars=0,width='+windowWidth+',height='+windowHeight+',left='+x+',top='+y;

		var myWindowObject = window.open(url, name, features);
	}
	
	function centerWindowX( screenWidth, windowWidth )
	{
		return (screenWidth - windowWidth) / 2;
	}

	function centerWindowY( screenHeight, windowHeight )
	{
		return ( screenHeight - windowHeight) / 2;
	}

//---------------------------------------------------------



function fs_filter(){
	for (var x=0; x < document.frmnom_form.elements.length; x++){
		if(document.frmnom_form.elements[x].value){
			document.frmnom_form.elements[x].value = document.frmnom_form.elements[x].value.replace(/[<>"'%;\(\)&\+]/g, "");
		}
	}	
}


// Function to strip/replace FS characters before submitting to server
function stripChars(fieldName){
	fieldName.value = fieldName.value.replace(/%/gi, " percent");
	fieldName.value = fieldName.value.replace(/\+/gi, " plus ");
	fieldName.value = fieldName.value.replace(/</gi," less than ");
	fieldName.value = fieldName.value.replace(/>/gi," greater than ");
	fieldName.value = fieldName.value.replace(/;/gi,",");
	fieldName.value = fieldName.value.replace(/['"]/gi,"~");
	fieldName.value = fieldName.value.replace(/\(/gi,"[");
	fieldName.value = fieldName.value.replace(/\)/gi,"]");
	fieldName.value = fieldName.value.replace(/\&/gi," and ");	
	fieldName.value = fieldName.value.replace(/\\n/gi,"|n");
	fieldName.value = fieldName.value.replace(/\\r/gi,"|r");
}


//---------------------------------------------------------------------------
// START RCA guide - can be removed when how-to guide is removed
function setUpHover()
{
var img = document.getElementById("rca-image");
var rca_root = "/_common_images/rca-guide/";
var a = document.getElementsByTagName("a");
var cardinserted = false;
for (i=0;i<a.length;i++)
	{
	if (a[i].className=="rca-hoverlink")
		{
		a[i].onmouseout = a[i].onblur = function(e) {
			if (cardinserted)
				{
				img.setAttribute('src', rca_root + 'rca-clean-card-in.jpg');
				}
				else
				{
				img.setAttribute('src', rca_root + 'rca-clean.jpg');
				}
			}
		a[i].onmouseover = a[i].onfocus = function(e) {
			var id=this.id;
			var path = rca_root + id + ".jpg";
			if (id=="card-inserted-anim")
				{
				path = rca_root + id + ".gif";
				cardinserted = true;
				}
			img.setAttribute('src', path);
			};
		}
	}
}
addEvent(window, 'load', setUpHover, false);
// END RCA guide

function replaceAll(txt, replaceStr, with_this) {
		return txt.replace(new RegExp(replaceStr, 'g'),with_this);
}

function ValidateTalismaSearch(){
	var srchStr = document._search.searchterm.value;
	srchStr = replaceAll(srchStr, "#", "");
	if (srchStr=="" || srchStr==defSrchTxt){
		alert("Please enter a keyword or phrase in the search box");
		document._search.searchterm.focus();
		return false;
	}
	var re5digit=/\d{4}/ //regular expression defining a 5 digit number
	if (srchStr.search(re5digit)==-1) { //if match failed
		return true;
	}
	else {
		document.location="http://www.nationwide.co.uk/search/start.aspx?article=1451";
		return false;
	}
}


//-------------------------------------------------------------
// INTERNET BANKING DEMO FORM LAUNCHER
function openTutorial(sID){

	if(document.frmTutorial.comboSelectTutorial.options[document.frmTutorial.comboSelectTutorial.selectedIndex].value!=-1){
		//launchSim(mID+'&amp;mode=sm',false,true,false); return;
		startSequence(sID); return;
	}
	else{
		alert('Please select a tutorial from the drop down box.')
	}

}
// END IB DEMO


function readCookie(name)
{
  var cookieValue = "";
  var search = name + "=";
  if(document.cookie.length > 0)
  { 
    offset = document.cookie.indexOf(search);
    if (offset != -1)
    { 
      offset += search.length;
      end = document.cookie.indexOf(";", offset);
      if (end == -1) end = document.cookie.length;
      cookieValue = unescape(document.cookie.substring(offset, end))
    }
  }
  return cookieValue;
}

function writeCookie(name, value, hours)
{
  var expire = "";
  if(hours != null)
  {
    expire = new Date((new Date()).getTime() + hours * 3600000);
    expire = "; expires=" + expire.toGMTString();
  }
  var strCookie = name + "=" + escape(value) + expire + "; path=/";
  document.cookie = strCookie;
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
// START ACCESSIBILITY ENHANCEMENTS

var accBackground="#003";
var accHighlightBGColor="#003";
var accHighlightColor="#fff";
var accHighlightOutline="2px solid red !important";
var accTextDecoration="none";
var origFontWeight = "";
var origBackground = "";
var origColor = "";
var origBGrep = "";
var origBGpos = "";
var origBGColor = "";
var origBGImage = "";
var origOutline = "";
var origTextDecoration = "";
var enableAccessibilityHotKey = false; //used for pressing letter 'a' to activate
var accP;
var accP_text;
var accPappended;
var accessKeysDisabled = false;
var bodyEl;
var mtgPage = false;

function showSkipLinks() {
	
// need to be sure that destination of skip links are present 
// on page (some templates do not have them). If not found, remove the
// related skip link in the header
//(mtgPage);
var pagenavSkipdestFound = false;
var maincontentSkipdestFound = false;
var footerSkipdestFound = false;
var skipLinksFound = (document.getElementById("skippies")!=null);
if (skipLinksFound){
	var sk_a = document.getElementsByTagName("a");
	for (i=0; i<sk_a.length; i++)
		{
		//found the skip link dest?
		if (sk_a[i].id == "pagenav-skipdest") {pagenavSkipdestFound = true};
		if (sk_a[i].id == "maincontent-skipdest") {maincontentSkipdestFound = true};
		if (sk_a[i].id == "footer-skipdest") {footerSkipdestFound = true};
	
		bodyEl = document.getElementsByTagName("body")[0];
		accP = document.createElement("p");
		accP.setAttribute("id","accessibilityHilighter");
		accP_text = document.createTextNode("Press comma key [,] for more accessibility options");
		accP.appendChild(accP_text);
	
		if (sk_a[i].className=="skip-link")
			{
			sk_a[i].onfocus=function(e){
				var viewportwidth;
				if (typeof window.innerWidth != 'undefined'){
				viewportwidth = window.innerWidth;
				}
				else if ((typeof document.documentElement != 'undefined') && (typeof document.documentElement.clientWidth !='undefined') && (document.documentElement.clientWidth != 0)){
				viewportwidth = document.documentElement.clientWidth;
				}
				else {
				viewportwidth = document.getElementsByTagName('body')[0].clientWidth;
				}
				if (mtgPage)
				{
					viewportwidth = 756;
				}
				this.style.width=viewportwidth + "px";
				this.style.padding="16px 0";
				this.style.fontSize="medium";
				this.style.height="auto";
				this.style.textIndent="20px";
				this.style.backgroundColor="#006";
				this.style.borderBottom="3px solid black";
				this.style.outline="none";
				this.style.backgroundImage="url(/_common_images/accessibility-feature.gif)";
				if (document.getElementById("accessibilityHilighter")==null) {
					bodyEl.appendChild(accP);
					}
					accPappended = document.getElementById("accessibilityHilighter");
					accPappended.style.display = "block";
					accPappended.style.marginTop = "10px";
					enableAccessibilityHotKey = true;
				}
			sk_a[i].onblur=function(e){
				this.style.width="0";
				this.style.padding="0";
				this.style.fontSize="1px";
				this.style.height="1px";
				this.style.textIndent="-30000px";
				this.style.backgroundColor="transparent";
				this.style.backgroundImage="none";
					accPappended = document.getElementById("accessibilityHilighter");
					accPappended.style.display="none";
					enableAccessibilityHotKey = false;
				}
			}
		}
	//remove skip links to missing destinations
	if (!pagenavSkipdestFound) {document.getElementById("skipto-pagenav").style.display="none";};
	if (!maincontentSkipdestFound) {document.getElementById("skipto-maincontent").style.display="none";};
	if (!footerSkipdestFound) {document.getElementById("skipto-footer").style.display="none";};
	}
}
function highlightLinksAndFormControls() {
var tababbleItems = document.getElementsByTagName("*");
//var tababbleItems = document.getElementById("productnav").getElementsByTagName("a");
for (i=0; i<tababbleItems.length; i++)


	{
	if(((tababbleItems[i].tagName.toLowerCase()=="a")&&(tababbleItems[i].className!="skip-link"))||(tababbleItems[i].tagName.toLowerCase()=="input")||(tababbleItems[i].tagName.toLowerCase()=="textarea")||(tababbleItems[i].tagName.toLowerCase()=="select"))
		{
		tababbleItems[i].onfocus=function(e) {
				
				//store the existing background images and colours:
				origBackground = this.style.background;
				origBGColor = this.style.backgroundColor;
				origBGImage = this.style.backgroundImage;	
				origBGpos = this.style.backgroundPosition;
				origBGrep = this.style.backgroundRepeat;
				origColor = this.style.color;
				origFontWeight = this.style.fontWeight;
				origOutline = this.style.outline;
				origTextDecoration = this.style.textDecoration;
				
				//now replace with our accessibility settings
//				alert(this.parentNode.parentNode.id);
				if (this.parentNode.parentNode.parentNode.parentNode.id=="footer") {
					this.style.color = "red";
					}
				else {
					this.style.backgroundColor = accHighlightBGColor;
					this.style.color = accHighlightColor;
					}
				this.style.outline = accHighlightOutline;
				this.style.textDecoration = accTextDecoration;
				if (this.parentNode.parentNode.parentNode.id=="productnav") {
					this.childNodes[1].style.color = "red";
					}
		 }
		tababbleItems[i].onblur=function(e) {
				//restore the original settings when leaving that link/field
				if (this.parentNode.parentNode.parentNode.parentNode.id=="footer") {
					this.style.color = origColor;
					}
				else {
					this.style.backgroundColor = origBGColor;
					this.style.color = origColor;
					}
				this.style.fontWeight = origFontWeight;
				this.style.outline = origOutline;
				this.style.textDecoration = origTextDecoration;
				if (this.parentNode.parentNode.parentNode.id=="productnav") {
					this.childNodes[1].style.color = origColor;
					}
		 }
		}
	}
}
function stripAccessKeyInfo(el) {
	if (el) 
	{
	el.setAttribute("title","");
	el.setAttribute("accesskey","");
	}
}
function disableAccessKeys()
{
accessKeysDisabled = true;
if (accessKeysDisabled)
 {
		stripAccessKeyInfo(document.getElementById("p_search_text"));
		stripAccessKeyInfo(document.getElementById("maincontent-skipdest"));
		stripAccessKeyInfo(document.getElementById("contactus-link"));
		stripAccessKeyInfo(document.getElementById("sitemap-link"));
	}
}
function accessHotKey()
{
window.document.onkeypress=function(e) {
	if (enableAccessibilityHotKey)
	 {
		var code;
		if (!e) var e = window.event;
		if (e.keyCode) code = e.keyCode;
		else if (e.which) code = e.which;
		var character = String.fromCharCode(code);
		if (character==",")
		 {
			//location.href="/about_nationwide/accessibility/web_access.htm#options";
			location.href="/accessibility/default.htm?ref=" +location.href;
			}
		}
	}
}
function initAccessibilityFeatures()
{
//these apply to all users:
showSkipLinks(); // makes skip links visible for tabbing/kbd users
accessHotKey(); // allows hotkey [,] for jump to accessibility page
var showHighlights = false;
var useAccesskeys = true;

// these are the optional features:
if(readCookie("accessibility").length>0) {
	//	cookie found. Let's see what they've set
	var arrAccCookie = readCookie("accessibility").split("@@");
	for (i=0; i<arrAccCookie.length; i++) {
			if (arrAccCookie[i]=="focusHilight=true") {
				showHighlights = true;
				}
			if (arrAccCookie[i]=="accessKeys=false") {
				useAccesskeys = false;
				}
		}
	if (showHighlights) {
		highlightLinksAndFormControls();
		}
	if (!useAccesskeys) {
		disableAccessKeys();
		}
	}
else {
	disableAccessKeys();
	}
}
addEvent(window, 'load', initAccessibilityFeatures, false);




// END ACCESSIBILITY ENHANCEMENTS
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 




/* START =Concertina */
/*
We may want to migrate this to jQuery for smoother 
transitions. For now it's hand-rolled/custom.
*/

//global constants
var collapsed = false;
var useShowAllLink = false;
var hideAllTitle = "Hide all the topics in this list";
var showAllTitle = "Show all the topics in this list";
var hideAllText = "Hide all";
var showAllText = "Show all";
var plusImageURL = "url(/_common_images/concertinaPlus.gif)";
var minusImageURL = "url(/_common_images/concertinaMinus.gif)";
var dontShowAll = "";
//check to see if fragment identifier in URL
var u = location.href;
var anch = u.split("#")[1];

function togglePlusMinus(whichLink, plusOrMinus){
	if (plusOrMinus=="plus")	{
		whichLink.style.backgroundImage = plusImageURL;
		whichLink.style.backgroundRepeat = "no-repeat";
		whichLink.style.backgroundPosition = "4px 4px";
	}
	if (plusOrMinus=="minus")	{
		whichLink.style.backgroundImage = minusImageURL;
		whichLink.style.backgroundRepeat = "no-repeat";
		whichLink.style.backgroundPosition = "4px 4px";
	}
}
function concertinaOpenCloseAll(source,displayState){
if (displayState=="open"){
	displayState = "block";
 collapsed = false;
	}
if (displayState=="close"){
	displayState = "none";
 collapsed = true;
	}
if (source.tagName!=null) {
	//only handling this individual concerina, not all of them
	var ul = source.parentNode;
	}
else {
	var ul = document.getElementsByTagName("ul");
	}
if (ul.length>0)
	{
for (i=0; i<ul.length; i++){
	if (ul[i].className=="concertina"){
		var ul_divs = ul[i].getElementsByTagName("div");
		for (j=0; j<ul_divs.length; j++){
			if (ul_divs[j].className=="ListHead"){
				if (collapsed) {
					togglePlusMinus(ul_divs[j].getElementsByTagName("a")[0],"plus");
					}
				else {
					togglePlusMinus(ul_divs[j].getElementsByTagName("a")[0],"minus");
					}
				}
			if (ul_divs[j].className=="ListBody"){
				ul_divs[j].style.display=displayState;
				}
			}
		} // end of if ul concertina class
	} //end of ul for loop
	}
else
	{
	var ul_divs = ul.getElementsByTagName("div");
	for (k=0; k<ul_divs.length; k++){
		if (ul_divs[k].className=="ListHead"){
			if (collapsed) {
				togglePlusMinus(ul_divs[k].getElementsByTagName("a")[0],"plus");
				}
			else {
				togglePlusMinus(ul_divs[k].getElementsByTagName("a")[0],"minus");
				}
			}
		if (ul_divs[k].className=="ListBody"){
			ul_divs[k].style.display=displayState;
			}
		}
	}
}
function showHideSingleLink(thisLink){
var listbody = thisLink.parentNode.parentNode.getElementsByTagName("div")[1]	;
if (listbody.style.display =="none"){
	listbody.style.display = "block";
	togglePlusMinus(thisLink,"minus");
	}
else{
	listbody.style.display = "none";
	togglePlusMinus(thisLink,"plus");
	}
}
function addHoverBehaviourtoTab()
{
	$(".ListHead a.toggleSwitch, a.concertina_showall").focus(function(){
	$(this).addClass("hover");
	}).blur(function(){
	$(this).removeClass("hover");
	});
}
function initConcertina(){
concertinaOpenCloseAll(this,'close');
var ul = document.getElementsByTagName("ul");
for (i=0; i<ul.length; i++){
	if (ul[i].className=="concertina"){
		//add show/hide all link after list if there is more than one list item contained
		var listCount = ul[i].getElementsByTagName("li").length;
		useShowAllLink = ((listCount > 1)&&(!dontShowAll));
		if (useShowAllLink){
			var showAllLink = document.createElement("a");
			var showAllLinkText = document.createTextNode(showAllText);
			showAllLink.setAttribute("href","#");
			showAllLink.setAttribute("class","concertina_showall");
			showAllLink.setAttribute("className","concertina_showall");
			showAllLink.setAttribute("title", showAllTitle);
			showAllLink.appendChild(showAllLinkText);
			ul[i].appendChild(showAllLink, ul[i].parentNode);
			showAllLink.onclick = function(e){
				if (collapsed){
					concertinaOpenCloseAll(this,'open');
					this.setAttribute("title", hideAllTitle);
					this.innerHTML=hideAllText;
					}
				else{
					concertinaOpenCloseAll(this,'close');
					this.setAttribute("title", showAllTitle);
					this.innerHTML=showAllText;
					}
				return false;
				}
			}
		//find the ListHead divs
		var ul_divs = ul[i].getElementsByTagName("div");
		for (j=0; j<ul_divs.length; j++){
			if (ul_divs[j].className=="ListHead"){
				//now find the link that's inside that listHead
				var this_a = ul_divs[j].getElementsByTagName("a")[0];
				this_a.onclick = function(e){
						showHideSingleLink(this);
						return false;
					}
				// check to see if this link is the target of an external link 
				// (with a fragment identifier, e.g. a href="QandA.htm#q5
				if ((anch)&&(anch.length>0)){
					if (this_a.name == anch){
						showHideSingleLink(this_a);
						}
					}
				}
			}
		} // end of if ul concertina class
	} //end of ul for loop
if (jQueryUsed) addHoverBehaviourtoTab();
}
/* END =Concertina */

	function setCookiesInMortgages(){
		var h = document.location.href.toLowerCase();
		if(h.indexOf("/mortgages/") != -1){
			if(h.indexOf("/mortgages/firsttimebuyers") != -1){
				writeCookie("buyerType","ftb",(24*7));
			}
			if(h.indexOf("/mortgages/newcustomers/movinghome.htm") != -1){
				writeCookie("buyerType","nc-mh",(24*7));
			}
			if(h.indexOf("/mortgages/newcustomers/remortgaging.htm") != -1){
				writeCookie("buyerType","nc-r",(24*7));
			}
			if(h.indexOf("/mortgages/existingcustomers/movinghome.htm") != -1){
				writeCookie("buyerType","ec-mh",(24*7));
			}
			if(h.indexOf("/mortgages/existingcustomers/topupmortgage.htm") != -1){
				writeCookie("buyerType","ec-bm",(24*7));

			}
			if(h.indexOf("/mortgages/existingcustomers/switchmortgagemiddeal.htm") != -1){
				writeCookie("buyerType","ec-sf",(24*7));
			}
			if(h.indexOf("/mortgages/existingcustomers/switchmortgagedealending.htm") != -1){
				writeCookie("buyerType","ec-de",(24*7));
			}
		}
	}
	setCookiesInMortgages();

/* ^^^ All non-jQuery (standard) javascript *above here please) ^^^ */ 

/* ===============================================================================================================================================*/
/* ===============================================================================================================================================*/
/* ===============================================================================================================================================*/

/* All jQuery scripts *below* here please ...*/

/*  START jQuery functions*/ 
function doJQueryFunctions()
{
if (jQueryUsed)
	{

var unsupported_safari = (((navigator.userAgent.indexOf("Version/3")==-1)&&(navigator.userAgent.indexOf("Version/4")==-1))&&($.browser.safari));

var is_chrome = /chrome/.test( navigator.userAgent.toLowerCase() );
var is_ie;
var is_ie_6;
var is_ie_7;
var is_ie_8;
var is_not_ie = (!is_ie);
var is_safari;
var is_mozilla;
var is_opera;
var browserVersion;
browserVersion = parseInt($.browser.version);
is_ie = ($.browser.msie);
is_ie_6 = (is_ie && (browserVersion==6));
is_ie_7 = (is_ie && (browserVersion==7));
is_ie_8 = (is_ie && (browserVersion==8));
if (is_chrome) {unsupported_safari = false;}
is_safari = ($.browser.safari);
is_mozilla = ($.browser.mozilla);
is_opera = ($.browser.opera);
var supports_png24 = true;
if ($.browser.msie) {
if (($.browser.version) == "6.0") {
	supports_png24 = false;
	}
}
// =browser identification applied to body for CSS use
if (is_ie) $("body").addClass("ie");
if (is_ie_6) $("body").addClass("ie6");
if (is_ie_7) $("body").addClass("ie7");
if (is_ie_8) $("body").addClass("ie8");
if (is_chrome) $("body").addClass("chrome");
if (is_opera) $("body").addClass("opera");
if ((is_safari)&&(!unsupported_safari)) $("body").addClass("safari");
if (is_mozilla) $("body").addClass("mozilla");
if ((is_chrome)||(is_opera)||((is_safari)&&(!unsupported_safari))||(is_mozilla)) $("body").addClass("notie");


/* mortgage apply page-ab */

function mortgageApply(){
	
// set up
$("div#mortgageApply .step").not(".one").hide();
$("div#mortgageApply ul#steps li.one").data("step","one");
$("div#mortgageApply ul#steps li.two").data("step","two");
$("div#mortgageApply ul#steps li.three").data("step","three");
$("div#mortgageApply ul#steps li.four").data("step","four");
$("div#mortgageApply ul#steps li.five").data("step","five");


//steps click
$("div#mortgageApply ul#steps li").click(function(){	
	$(".step").hide();	
	
	$("div#mortgageApply ul#steps li").removeClass("selected");
	$("div#mortgageApply ul#steps li.last").removeClass("selected");
	$("div#mortgageApply ul#steps li.last-selected").addClass("last");
	$("div#mortgageApply ul#steps li.last").removeClass("last-selected");

	
	if($(this).hasClass("last"))
	{	
		$(this).removeClass("last");
		$(this).addClass("last-selected");
	}
	else
	{
		$(this).addClass("selected");
	}

	$("div#mortgageApply div." + $(this).data("step")).show();
	
	return false;
	
});

//steps hover
$("div#mortgageApply ul#steps li").hover(function(){
	
	$("div#mortgageApply .step").hide();		
	$("div#mortgageApply div." + $(this).data("step")).show();
	
	if(!$(this).hasClass("last") && !$(this).hasClass("last-selected")){ //completed class
			$(this).addClass("hover");
		}else{
			$(this).addClass("last-hover");
		}
		
},
function(){
	
	
	if(!$(this).hasClass("last") && !$(this).hasClass("last-selected")){ //completed class
			$(this).removeClass("hover");
		}else{
			$(this).removeClass("last-hover");
		}
		
	$("div#mortgageApply ul#steps li").each(function(){
		if(	$(this).hasClass("selected") || $(this).hasClass("last-selected") ){	
			$(".step").hide();
			$("div." + $(this).data("step")).show();			
		}
	});		
		
});

}
mortgageApply();


function mortgageRatesButton()
{
//	btnMortgageRates
	$("#btnMortgageRates").click(function(){
		var buyertype = $("#selectMortgageRates").val();
		var propertyvalue = $("#txtValueOfProperty").val()
		var mortgagerequired = $("#txtMortgageRequired").val()
		
		if(isNaN(propertyvalue) || propertyvalue==""){propertyvalue = 0;}
		if(isNaN(mortgagerequired) || mortgagerequired==""){mortgagerequired = 0;}		
		
		var rateUrl = "/mortgages-november09/interestrates-types/rates.htm?buyerType=" + buyertype + "&propertyValue=" + propertyvalue + "&mortgageAmount=" + mortgagerequired
		window.location = rateUrl;

		return false;	
	});
}
mortgageRatesButton();
/* end */




function addProductNavTabGradients()
{
//	$("#productnav a.active").parent().prev().find("a b").append("<span class=\"activeTabLeft\">");
//	$("#productnav a.active").parent().next().find("a b").append("<span class=\"activeTabRight\">");
	$("a.active").parent().prev().addClass("activeTabLeft");
	$("a.active").parent().next().addClass("activeTabRight");
	$("a.active").parent().prev().find("a").append("<div class=\"added\">");
	$("a.active").parent().next().find("a").append("<div class=\"added\">");
}
addProductNavTabGradients();





//red/blue/yellow collapsible panel
	//	/_common_images/collapsiblepanel/
	function setupCollapsiblePanel()
	{
		//if ($.browser.msie == true) {document.execCommand('BackgroundImageCache', false, true);}
		//hide them all, set up the cursor style, add in the images, title attributes etc..		
		
		$(".collapsibleInfoPanelWrapper>.collapsibleInfoPanel>.collapsibleInfoPanelContent").hide();
		$(".collapsibleInfoPanelWrapper>.collapsibleInfoPanel>h3>a").css("cursor","pointer");
		$(".collapsibleInfoPanelWrapper>.collapsibleInfoPanel>h3>a").attr("title","Click to hide / reveal content under this heading (keyboard users hit Return key)");		
		$(".collapsibleInfoPanelWrapper.blue>.collapsibleInfoPanel>h3>a").css("background","url(/_common_images/collapsiblepanel/sprite.gif) 0px -21px no-repeat");
		$(".collapsibleInfoPanelWrapper.red>.collapsibleInfoPanel>h3>a").css("background","url(/_common_images/collapsiblepanel/sprite.gif) -564px -21px no-repeat");
		$(".collapsibleInfoPanelWrapper.yellow>.collapsibleInfoPanel>h3>a").css("background","url(/_common_images/collapsiblepanel/sprite.gif) -1128px -21px no-repeat");
		$(".collapsibleInfoPanelWrapper.aqua>.collapsibleInfoPanel>h3>a").css("background","url(/_common_images/collapsiblepanel/sprite.gif) -1692px -21px no-repeat");		
				
		//click toggle
		$(".collapsibleInfoPanelWrapper>.collapsibleInfoPanel>h3>a").toggle(function(){
			$(this).parent().siblings(".collapsibleInfoPanelContent").children().fadeIn(1100);
			$(this).parent().siblings(".collapsibleInfoPanelContent").slideDown(1000);	
		}, 	function(){
			$(this).parent().siblings(".collapsibleInfoPanelContent").children().fadeOut(800);	
			$(this).parent().siblings(".collapsibleInfoPanelContent").slideUp(1000);
		});
		
		//hover effect
		$(".collapsibleInfoPanelWrapper>.collapsibleInfoPanel>h3>a").hover(function(){
			$(this).addClass("hovered");
		}, function(){
			$(this).removeClass("hovered");
		});
				
		//focus/blur effect
		$(".collapsibleInfoPanelWrapper>.collapsibleInfoPanel>h3>a")
			.focus(function(){$(this).addClass("hovered");})
			.blur(function(){$(this).removeClass("hovered");});		
	}
	setupCollapsiblePanel();
	
	function rotateImage_PublicAffairsAndPolicy()
	{
		//only bother if the id exists on the page
		if($("#publicaffairs-img-rotate").length > 0)
		{		
			var NUMBER_OF_IMAGES = 15
	
			var img_src = "";
			var img_alt = "";
			var img_anchor = "";
			
			var rnd = Math.ceil(Math.random()*NUMBER_OF_IMAGES);
			switch(rnd)
			{
			case 1:img_src = "/publicaffairs/210/12171_033_210px.jpg"; img_alt = "Ian Pearson MP (Economic Secretary to the Treasury) speaking at the launch of MoneyActive.";img_anchor = "/publicaffairs/sized/12171_033.jpg"; break;
			case 2:img_src = "/publicaffairs/210/12171_044_210px.jpg"; img_alt = "Dr Vince Cable MP (Liberal Democrat Shadow Chancellor of the Exchequer) speaking at the launch of MoneyActive.";img_anchor = "/publicaffairs/sized/12171_044.jpg"; break;				
			case 3:img_src = "/publicaffairs/210/12171_052_210px.jpg"; img_alt = "David Harker (Chief Executive of Citizens Advice) speaking at the launch of MoneyActive.";img_anchor = "/publicaffairs/sized/12171_052.jpg"; break;
			case 4:img_src = "/publicaffairs/210/12171_057_210px.jpg"; img_alt = "Alison Seabeck MP and Maxine Taylor (Nationwide’s Divisional Director) at the launch of MoneyActive.";img_anchor = "/publicaffairs/sized/12171_057.jpg"; break;
			case 5:img_src = "/publicaffairs/210/12171_058_210px.jpg"; img_alt = "David Harker (Chief Executive of Citizens Advice), Tony Prestedge (Executive Director at Nationwide) and Andy Love MP at the launch of MoneyActive.";img_anchor = "/publicaffairs/sized/12171_058.jpg"; break;
			case 6:img_src = "/publicaffairs/210/12171_059_210px.jpg"; img_alt = "David Harker (Chief Executive of Citizens Advice), Mary Creagh MP and Caroline Hallatt (Nationwide’s Head of Corporate Responsibility) at the launch of MoneyActive.";img_anchor = "/publicaffairs/sized/12171_059.jpg"; break;
			case 7:img_src = "/publicaffairs/210/12171_060_210px.jpg"; img_alt = "David Harker (Chief Executive of Citizens Advice), David Amess MP and Caroline Hallatt (Nationwide’s Head of Corporate Responsibility) at the launch of MoneyActive.";img_anchor = "/publicaffairs/sized/12171_060.jpg"; break;
			case 8:img_src = "/publicaffairs/210/12171_061_210px.jpg"; img_alt = "David Harker (Chief Executive of Citizens Advice), George Mudie MP and Caroline Hallatt (Nationwide’s Head of Corporate Responsibility) at the launch of MoneyActive.";img_anchor = "/publicaffairs/sized/12171_061.jpg"; break;
			case 9:img_src = "/publicaffairs/210/12171_063_210px.jpg"; img_alt = "David Harker (Chief Executive of Citizens Advice), Doug Naysmith MP and Maxine Taylor (Divisional Director at Nationwide) at the launch of MoneyActive.";img_anchor = "/publicaffairs/sized/12171_063.jpg"; break;
			case 10:img_src = "/publicaffairs/210/11931_033_210px.jpg"; img_alt = "Sylvia Heal MP and Maxine Taylor, Nationwide’s Divisional Director for Corporate Affairs, at the Nationwide Education parliamentary drop in session.";img_anchor = "/publicaffairs/sized/11931_033.jpg"; break;
			//case 11:img_src = "/publicaffairs/210/11931_058_210px.jpg"; img_alt = "Barry Sheerman MP, chair of the Children, Schools and Families Select Committee, with Caroline Hallatt, Nationwide’s Head of Corporate Responsibility.";img_anchor = "/publicaffairs/sized/11931_058.jpg"; break;
			case 11:img_src = "/publicaffairs/210/12171_014_210px.jpg"; img_alt = "Mark Hoban MP (Shadow Financial Secretary), Graham Beale (Chief Executive of Nationwide), David Harker (Citizens Advice), Dr Vince Cable MP (Liberal Democrat Shadow Chancellor of the Exchequer) and Ian Pearson MP (Economic Secretary to the Treasury) at the launch of MoneyActive.";img_anchor = "/publicaffairs/sized/12171_014.jpg"; break;
			case 12:img_src = "/publicaffairs/210/RichardCabornMP-Carol_210px.jpg"; img_alt = "Caroline Hallatt, Nationwide’s Head of Corporate Responsibility, and Richard Caborn, MP for Sheffield Central, at the British International Disability Swimming Championships";img_anchor = "/publicaffairs/sized/RichardCabornMP-Carol.jpg"; break;
			case 13:img_src = "/publicaffairs/210/12171_040_210px.jpg"; img_alt = "Mark Hoban MP (Shadow Financial Secretary) speaking at the launch of MoneyActive.";img_anchor = "/publicaffairs/sized/12171_040.jpg"; break;
			case 14:img_src = "/publicaffairs/210/RichardCabornMP_210px.jpg"; img_alt = "Caroline Hallatt, Nationwide’s Head of Corporate Responsibility, and Richard Caborn, MP for Sheffield Central, and Gordon Neale, Director of Events at DSE, at the British International Disability Swimming Championships.";img_anchor = "/publicaffairs/sized/RichardCabornMP.jpg"; break;
			case 15:img_src = "/publicaffairs/210/NickCleggMP_small.jpg"; img_alt = "Nick Clegg MP, Leader of the Liberal Democrats support MoneyActive .";img_anchor = "/publicaffairs/sized/NickCleggMP.jpg"; break;				
			default:break;
			}
			if(img_src!="" && img_alt!="" && img_anchor!="")
			{
				$("#publicaffairs-img-rotate").show();
				$("#publicaffairs-img-rotate").attr("src",img_src);
				$("#publicaffairs-img-rotate").attr("alt",img_alt);
				$("#publicaffairs-img-rotate").wrap("<a href=\"" + img_anchor + "\" target=\"_blank\"></a>");					
			}
		}
	}
	rotateImage_PublicAffairsAndPolicy();
		
	function applyProductNavHoverWithTab()
		/* Top level tabs - apply hover behaviour for tabbing/keyboard users */
		{
		$("div#productnav>ul>li>a:not(a.active)")
			.focus(function(e){$(this).addClass("productNavhover");})
			.blur(function(e){$(this).removeClass("productNavhover");});	
		}
		
		function applyProductSubNavHoverWithTab()
		/* tab subnavigation - apply hover behaviour for tabbing/keyboard users */
		{
		$("#headernav-subnav ul li a")
			.focus(function(e){$(this).addClass("productSubNavhover");})
			.blur(function(e){$(this).removeClass("productSubNavhover");});
		}
	
		function applyLeftNavHoverWithTab()
		/* left nav - apply hover behaviour for tabbing/keyboard users */
		{
			$("div#leftnav li a")
				.focus(function(e){$(this).addClass("leftNavHover");})
				.blur(function(e){$(this).removeClass("leftNavHover");});
		}
	
		function applyLeftNavHoverWithTab_mtg()
		/* left nav - apply hover behaviour for tabbing/keyboard users */
		{
			$("div#mtge-links a")
				.focus(function(e){$(this).addClass("mtgeHover");})
				.blur(function(e){$(this).removeClass("mtgeHover");});
		}
	
		applyProductNavHoverWithTab();
		applyProductSubNavHoverWithTab();
		applyLeftNavHoverWithTab();
		applyLeftNavHoverWithTab_mtg();
	
		/* \/ \/  Not sure if this is needed \/ \/ */
		$(".breadcrumbtext").click(function(e){
				$("#cc-tabs-wrapper").slideToggle("medium");
			});
		/* /\ /\  Not sure if this is needed  /\ /\ */
	
		/*
		while I hate browser sniffing, Safari 2 does 
		not have full jQuery support, so we need to 
		disable some effects
		*/
		var unsupported_safari = (((navigator.userAgent.indexOf("Chrome")==-1) && (navigator.userAgent.indexOf("Version/3")==-1)&&(navigator.userAgent.indexOf("Version/4")==-1))&&($.browser.safari && (navigator.userAgent.indexOf("Chrome")!= -1)));
		
		/* footer show/hide stuff */
		function footerExpandCollapse()
		{
		if(!unsupported_safari){
			//hide 'Explore Nationwide' for all pages
			$("#footer .footer-inner, #footer-homepage.collapse .footer-inner").hide();
			//hide 'Explore our products' but *only* on the home page
			$("#footer .footer-inner").hide();
			
			$("#footer h4 a").toggle(function(e){
					$("#footer span#exploreInd").addClass("expanded");
					$("#footer .footer-inner").slideDown('medium');
					return false;
				}, function(e){
					$("#footer span#exploreInd").removeClass("expanded");
					$("#footer .footer-inner").slideUp('medium');
					return false;
				});
			$("#footer-homepage h4 a").toggle(function(e){
					$("#footer-homepage span#exploreInd").addClass("expanded");
					$("#footer-homepage .footer-inner").slideDown('medium');
					return false;
				}, function(e){
					$("#footer-homepage span#exploreInd").removeClass("expanded");
					$("#footer-homepage .footer-inner").slideUp('medium');
					return false;
				});
			}
		}
		footerExpandCollapse();
	
		function applyButtonStyles()
		{
		//start button behaviour
		$(".darkbg .button").wrap("<b class=\"button\"></b>")
		$("a.button, input.button").addClass("buttonstyles");
		$("a.apply, input.apply").addClass("applyButton");
		$("a.info, input.info").addClass("infoButton");
		$("a.button.big, input.button.big").addClass("bigFatButton");
	
		$("a.button, input.button").each(function(e){
			var btLength;
			if ($(this).html()) {
				btLength = $(this).html().length;
				}
			else {
				btLength = $(this).attr("value").length+3;
				}
			if (btLength<5) {
				$(this).addClass("smallbutton");
			}
			if ((btLength>10) && (btLength<21)) {
				$(this).addClass("bigbutton");
			}
			if ((btLength>20) && (btLength<24)) {
				$(this).addClass("hugebutton");
			}
			if (btLength>=24) {
				$(this).addClass("megabutton");
			}
		});
	
		$("a.button:not(\"#exitAnd404PagewrapperInner #primaryCampaign a\"), input.button").each(function(){
			var buttonType="";
			if ($(this).hasClass("apply")){buttonType="Apply";}
			if ($(this).hasClass("info")) {buttonType="Info";}
			var clickStyle = "button" + buttonType + "Click";
			var hoverStyle = "button" + buttonType + "Hover";
			$(this)
				.mousedown(function(e){	
					$(this).removeClass(clickStyle);
					$(this).addClass(clickStyle);
				})
				.mouseup(function(e){
					$(this).removeClass(clickStyle);
				})
				.mouseover(function(e){
					$("a.apply, input.apply").removeClass(clickStyle);
					$(this).addClass(hoverStyle);
				})
				.mouseout(function(e){
					$(this).removeClass(hoverStyle);
				})
				.focus(function(e){
					$(this).addClass(hoverStyle);
				})
				.blur(function(e){
					$(this).removeClass(hoverStyle);
				});
		});
		//end button behaviour
		}
		applyButtonStyles();
	
		function tidyUpHeaderSublinks()
		{
		// remove the right-most 'pipe' on the links in blue header section
		$("#headernav-subnav li:last a").addClass("headernavLastLink");
		}
		tidyUpHeaderSublinks();
	
		function doFlashReplace() {
			var requiredFlashMajorVersion = 8;
			var requiredFlashMinorVersion = 0;
			var requiredFlashRevision = 0;
			flashCapable = DetectFlashVer(requiredFlashMajorVersion, requiredFlashMinorVersion, requiredFlashRevision);
			if (flashCapable)
			{
				$(".doFlashReplace").each(function(){
					//build up embed code
					var flashObjectEmbedCode;
					//find attributes for flash movie
					var $thisImage = $(this).find("img:not(.clickInd)");
					//get the URL from the href and pass it on to the Flash movie
					var flashButtonLink = $(this).find("a.hpMoreLink").attr("href");
					// convert the qrystring format to the format that Flash understands
					// change & to %26
					flashButtonLink = flashButtonLink.replace(/\&/g,"%26");
					//alert(flashButtonLink);
					var swfSrc = $thisImage.attr("src").replace(".gif","").replace(".jpg","").replace(".png","") + ".swf?flashButtonLink=" + flashButtonLink;
					var swfWidth=$thisImage.width();
					var swfHeight=$thisImage.height();
					$(this).width(swfWidth);
					$(this).height(swfHeight);
					//check for overridden flash attributes
					if (typeof($thisImage.attr("flashsrc")) != "undefined") {
						if ($thisImage.attr("flashsrc").length>0) {swfSrc=$thisImage.attr("flashsrc")};
					}
					if (typeof($thisImage.attr("flashwidth")) != "undefined") {
						if ($thisImage.attr("flashwidth").length>0) {swfWidth=$thisImage.attr("flashwidth")};
					}
					if (typeof($thisImage.attr("flashheight")) != "undefined") {
						if ($thisImage.attr("flashheight").length>0) {swfHeight=$thisImage.attr("flashheight")};
					}
					flashObjectEmbedCode = "<div class=\"objectWrapper\">";
					flashObjectEmbedCode += "\n<object";
					flashObjectEmbedCode += " classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\"";
					flashObjectEmbedCode += " codebase=\"http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,29,0\"";
					flashObjectEmbedCode += " width=\"" + swfWidth + "\"";
					flashObjectEmbedCode += " height=\"" + swfHeight + "\"";
					flashObjectEmbedCode += ">";
					flashObjectEmbedCode += "\n<param name=\"wmode\" value=\"opaque\" \/>";
					flashObjectEmbedCode += "\n<param name=\"movie\" value=\"" + swfSrc + "\" \/>";
					flashObjectEmbedCode += "\n<param name=\"width\" value=\"" + swfWidth + "\" \/>";
					flashObjectEmbedCode += "\n<param name=\"height\" value=\"" + swfHeight + "\" \/>";
					flashObjectEmbedCode += "\n<param name=\"quality\" value=\"high\">";
					flashObjectEmbedCode += "\n<embed";
					flashObjectEmbedCode += "\n src=\"" + swfSrc + "\"";
					flashObjectEmbedCode += "\n width=\"" + swfWidth + "\"";
					flashObjectEmbedCode += "\n height=\"" + swfHeight + "\"";
					flashObjectEmbedCode += "\n quality=\"high\"";
					flashObjectEmbedCode += "\n wmode=\"opaque\"";
					flashObjectEmbedCode += "\n type=\"application/x-shockwave-flash\"";
					flashObjectEmbedCode += "\n pluginspage=\"http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash\"";
					flashObjectEmbedCode += ">";
					flashObjectEmbedCode += "\n<\/embed>";
					flashObjectEmbedCode += "\n<\/object>";
					flashObjectEmbedCode += "\n<\/div>";
					//embed flash movie, position using abs pos over existing html version
					//alert('Pretend pause for checking Flash Replace progress');
					//					alert(flashObjectEmbedCode);
					$(this).append(flashObjectEmbedCode).addClass("hasFlash");
					//make sure survey can fit over top if launched
					$("#notifications").css("z-index","3000");
					//disable the HTML version
					$(this).find("a, input").attr("tabindex","-1");
					// add link re accessibility to allow screen reader users to access the html version instead
//					var flashAccessibilityWarning = "There is a flash movie immediately following this link which may be inaccessible.\n\nTo remove the Flash version and use a simpler (more accessible) version, press the OK button now, otherwise hit cancel";
//					$(this).prepend("<a href=\"#\" class=\"flashAccWarningForScreenReaders\">Important accessibility note for screen reader users</a>");
//					$(this).find("a.flashAccWarningForScreenReaders").click(function(){
//						if(confirm(flashAccessibilityWarning)) {
//							var $thisContainer = $(this).parent();
//							var $thisContainerImg = $thisContainer.find("img:not(.clickInd)");
//							var $thisContainerLinks = $thisContainer.find("a");
//							var $thisContainerMainLinkButton = $thisContainer.find("a.button");
//							$thisContainerImg.css("visibility","visible");
//							$thisContainerLinks.css("visibility","visible");
//							$(this).parent().find("object").remove();
//							$(this).parent().find("a, input").removeAttr("tabindex");
//							$thisContainerMainLinkButton
//							.text($thisContainerImg.attr("alt"))
//							.css({background:"white",fontSize:"1.5em",width:(swfWidth-40)+"px"})
//							.focus()
//							$(this).remove();
//						}
//						return false;
//					});
			});
			}
			$(".doFlashReplace").css("background","none");
			$(".doFlashReplace img, .doFlashReplace a").css("visibility","visible")
		}
		
		if (!unsupported_safari) {
			doFlashReplace();
		}

function screenReaderFriendlyMoreInfoLinks()
{
		$("a[title]").not("a[title]>a[title]").each(function(){
		var strTitle = $(this).attr("title");
		$(this)
		.addClass("srhelpAdded")
		.append("<span class=\"srhelp\">. " + strTitle + "</span>");
		})
}
if (!is_safari) screenReaderFriendlyMoreInfoLinks();
$("span.srhelp").css({display: "block",position: "absolute",textIndent: "-30000px",overflow: "hidden"});

function clickableParents_generic()
		{
			$(".clickableParent:not(#insurance-wrapper .clickableParent, div.hasFlash)").each(function(){
			 var $thisLink = $(this).find("a:first, a.buttonPuretext");
				var $thisLinkHref = $thisLink.attr("href");
				var $thisLinkTarget = $thisLink.attr("target");;
				var $thisLinkTitle = $thisLink.attr("title");
				if ($thisLinkTitle=="") {
					$thisLinkTitle = $thisLink.text();
				}
				if (typeof($thisLinkTarget)!="undefined") {
					if ($thisLinkTarget.length>0) {
						$thisLinkTarget=" target=\"" + $thisLinkTarget + "\"";
					}
					else {
						$thisLinkTarget="";
					}
				}
			// the inline style - height and display - is only there to fix an irritiating bug in IE whereby 
			// background image on some headings was being arbitrarily removed. And other oddities related to
			// the clickable Parent stuff
			var nastyIEHack=" style=\"height:auto;display:block;\"";
			if (homePageClickableLink)
				{
				//auto does not work for home page scenario. Need 1%.
				var nastyIEHack=" style=\"height:1%;display:block;\"";
				}
//			$(this).wrapInner("<a style=\"height:1%;display:block;\" href=\"" + $thisLinkHref + "\"" + $thisLinkTarget + " class=\"addedLink noreposition\" tabindex=\"-1\" title=\"" + $thisLinkTitle + "\"></a>");
			$(this).wrapInner("<a" + nastyIEHack + " href=\"" + $thisLinkHref + "\"" + $thisLinkTarget + " class=\"addedLink noreposition\" tabindex=\"-1\" title=\"" + $thisLinkTitle + "\"></a>");
			});
		}
		clickableParents_generic();

		function clickableParents_insuranceHomepage()
		{
			$("#insurance-wrapper .clickableParent").each(function(){
			 var $thisLink = $(this).find("div.container_content ul li a:first");
				var $thisLinkHref = $thisLink.attr("href");
				var $thisLinkTarget = $thisLink.attr("target");;
				var $thisLinkTitle = $thisLink.attr("title");
				if ($thisLinkTitle=="") {
					$thisLinkTitle = $thisLink.text();
				}
				if (typeof($thisLinkTarget)!="undefined") {
					if ($thisLinkTarget.length>0) {
						$thisLinkTarget=" target=\"" + $thisLinkTarget + "\"";
					}
					else {
						$thisLinkTarget="";
					}
				}
			$(this).find("p,img,h1,h2,h3").wrap("<a href=\"" + $thisLinkHref + "\"" + $thisLinkTarget + " class=\"addedLink noreposition\" tabindex=\"-1\" title=\"" + $thisLinkTitle + "\"></a>");
			});
		}
		clickableParents_insuranceHomepage();

		function setUpSearchBoxes()
		{
			defSrchTxt = "Enter keyword or phrase";
			defAskTxt = "Ask a question";
			var srch = $("#p_search_text");
			var ask = $("#txtAsk");
			if (srch) //only run if there's a search box there!
			{
				srch.val(defSrchTxt);
				srch.click(function(){
					if ($(this).val()==defSrchTxt)
					{
						srch.val("");
					}
				})
				srch.focus(function(){
					$(this).select();
				})
			}
			if (ask) //only run if there's a search box there!
			{
				ask.val(defAskTxt);
				ask.click(function(){
					if ($(this).val()==defAskTxt)
					{
						ask.val("");
					}
				})
				ask.focus(function(){
					$(this).select();
				})
			}
		}
		setUpSearchBoxes();

		function leftNavHasSubSection() 
		{
			$("li.currentSection:has(ul)").each(function(){
				if ($(this).find("li.currentPage").length>0)
				{
					$(this).addClass("hasSubSection");
				}
			})
			$("li.currentPage:has('ul')").addClass("hasSubSubSection");
		}
		leftNavHasSubSection();
		
//		function fixMeaninglessMoreInfoLinks_InternetBanking()
//		{
//			if(document.location.pathname.indexOf("/internet_banking/default.htm") == 0)
//			{
//				$("#internetbankPagewrapper a.button, #internetbankPagewrapper a.buttonExit").each(function()
//				{
//					$(this).prepend(" <span class='srhelp'>(" + $(this).attr("title") + ")</span>");
//				});
//			}		
//		}
//		fixMeaninglessMoreInfoLinks_InternetBanking();
		
//		function fixMeaninglessMoreInfoLinks()
//		{
//		$("#promo-campaigns a.simple").each(function(){
//			$(this).append(" <span class='srhelp'>(" + $(this).prev().children(0).attr("alt") + ")</span>");
//		})
//		$("#promo-campaign1 a.button,#promo-campaigns a.info,#promo-campaigns a.apply,#primaryCampaign a.apply,#primaryCampaign a.buttonExit,#secondaryCampaigns a.buttonExit,#secondaryCampaigns a.listButtonExit").each(function(){
//			$(this).append(" <span class='srhelp'>(" + $(this).attr("title") + ")</span>");
//		})
//		}
//		if (!is_safari) fixMeaninglessMoreInfoLinks();
//		$("span.srhelp").css({display: "block",position: "absolute",textIndent: "-30000px",overflow: "hidden"});
		
		function exclusiveOffersTermsLinks()
		{
			$("p.exclusiveOffersTerms a, a.exclusiveOffers").each(function(){
				$(this)
					.attr("title","Open terms and conditions in a new window")
					.click(function(){
						popUpWin($(this).attr("href"), "standard", "800", "550");
						return false;
					})
			});
		}
		exclusiveOffersTermsLinks();

		function btnGoHover(){                                        
			/*all go buttons*/
			$(".btnGo").hover(function(){$(this).attr("src","/_common_images/buttons/btn_go_hover.gif");},function(){$(this).attr("src","/_common_images/buttons/btn_go_normal.gif");});
			$(".btnGo").mousedown(function(){$(this).attr("src","/_common_images/buttons/btn_go_click.gif");$(this).data("isDown","true");});
			$(".btnGo").mouseup(function(){$(this).attr("src","/_common_images/buttons/btn_go_normal.gif");$(this).data("isDown","false");});
			/*imgs only*/
			$("img.btnGo").mousemove(function(){if($(this).data("isDown")=="true"){$(this).attr("src","/_common_images/buttons/btn_go_hover.gif");$(this).data("isDown","false");}});
		}
		
		btnGoHover();

	function homeExitPageEffects_Rebrand()
	{
		if ($("#hpNov09").length>0)
		{
			function passAskQuestionToMainSearch(){
				$("#frmAsk").submit(function(){
					$("#p_search_text").val($("#txtAsk").val());
					$("form[name=_search]").submit();
					return false;
				})
			}
			passAskQuestionToMainSearch();
			
			/* add red pipes to popular searches */
			$("#hpNov09 #popular ul li:not(#popular ul li:last)").find("a").after("<b>|</b>")
			/* Use 'ask' form to pass through to search */
		
			/* popups in popular searches */
			$("#hpNov09 #popular a.popup").click(function(){
				popUpWin($(this).attr("href"),'console',790,700);
				return false;
			});
		}
	
		if (($("#hpNov09").length>0)||($("#exitAnd404Pagewrapper").length>0))
		{


			/* View rates on home/exit page */
			function viewRatesFromHomePage()
			{
				$("#frmHomeExitPageViewRates").submit(function(){
				var ratePage = $("#ddlHomeExitPageViewRates").val();
				if (ratePage!="Please select")
					{
					location.href = ratePage;
					}
				return false;
				});
			}
			viewRatesFromHomePage();
	
			//home/exit page click state effect
			$("#ibSignOnLink a, #signon-link a").mouseover(function(){
				$(this).addClass("hovered")
			}).mousedown(function(){
				$(this).removeClass("hovered")
				$(this).addClass("clicked")
			}).mouseup(function(){
				$(this).removeClass("clicked")
			}).mouseout(function(){
				$(this).removeClass("clicked")
				$(this).removeClass("hovered")
			});

			/* Exit page colour shift on quick links top menu*/
			$("#quickLinksList li:first").css("border-top","1px solid #e8e9ea")
	
			/* news ticker */
			var newsTickerCount = 0;
			var textInternval;
			$("#newsMessage").data("originalMsg",$("#newsMessage span").text());
			function doNewsTicker()
			{
				newsTickerCount++;
				$("#newsMessage span a").hide();
				$("#newsMessage strong")
					.fadeTo('fast',0.1)
					.fadeTo('fast',1)
					.fadeTo('fast',0.1)
					.fadeTo('fast',1,function(){
					var newsMsg = $("#newsMessage").data("originalMsg");
					var newsMsgLength = newsMsg.length;
					$("#newsMessage span a").text("").show();
					var i=0;
					function buildNewsLineText()
					{
						$("#newsMessage span a").text($("#newsMessage span a").text() + newsMsg.charAt(i));
						i++;                                                      
					}
					textInternval = setInterval(buildNewsLineText, 60);
				})
				clearInterval(textInternval);
			}
			//doNewsTicker();
			//setInterval(doNewsTicker, 6000);

			//go button hover effect
			$("input#btnHomeExitPageViewRatesGo").mouseover(function(){
				$(this).addClass("hovered")
			}).mouseout(function(){
				$(this).removeClass("hovered")
				$(this).removeClass("clicked")
			}).mousedown(function(){
				$(this).removeClass("hovered")
				$(this).addClass("clicked")
			})
		}
	}
	homeExitPageEffects_Rebrand();

//Stop IE flicker
	if ($.browser.msie == true) {document.execCommand('BackgroundImageCache', false, true);}



/*
		START panelLinks layout 
		*/

//		This does not appear to be needed/used any more. 
//		Commented out 20 Oct 09. If it's not been reported 
//		as a bug within 2 months, please delete

		/*
		function campaignPanelLinks()
		{
			var campaignHoverInStyles = "{background: \"#fff\", color: \"#006\"}";
			var campaignHoverOutStyles = "{background: \"none\", color: \"#049\"}";
			
			$("div#promo-campaign1 ul#panelLinks li a, div#promo-campaign1 ul#slotLinks li a").focus(function(){
				$(this).children("b").css(campaignHoverInStyles);
			}).mouseover(function(){
				$(this).children("b").css(campaignHoverInStyles);
			}).blur(function(){
				$(this).children("b").css(campaignHoverOutStyles);
			}).mouseout(function(){
				$(this).children("b").css(campaignHoverOutStyles);
			});

		$("div#promo-campaign1>a").mouseover(function(){
				$("#savings_pointer").show();
			}).focus(function(){
				$("#savings_pointer").show();
			}).mouseout(function(){
				$("#savings_pointer").hide();
			}).blur(function(){
				$("#savings_pointer").hide();
			});
	}
		campaignPanelLinks();
		*/		
		
		function submitHover(){			
			$("#goRedirect, .goRedirect").hover(function(){$(this).attr("src","/_common_images/mortgage/gobutton.gif");
			},function(){$(this).attr("src","/_common_images/go-grey.gif");}); 
		}
		submitHover();


		/*hpMoreLinks which include .wrap (wrapping text, shift chevrons to end of second line*/
		function hpMoreLinkWrap(){
			var chevronImg = $("a.hpMoreLink.wrap").css("background-image");
			$("a.hpMoreLink.wrap").css("background","none");
			$("a.hpMoreLink.wrap").append("<span></span>");
			$("a.hpMoreLink.wrap span").css({"display":"inline", "padding-left":"10px","margin-left":"5px"} );			
			$("body.ie a.hpMoreLink.wrap span").text(" ");
			if($("body").hasClass("opera"))
				$("a.hpMoreLink.wrap span").css("background"," " + chevronImg + " repeat scroll right -245px");
			else
				$("a.hpMoreLink.wrap span").css("background","rgba(255, 255, 255, 1.0) " + chevronImg + " repeat scroll right -245px");			
		}
		hpMoreLinkWrap();
		
		
		/*
		END panelLinks layout 
		*/

		// * START DYNAMIC SEARCH *//
		// Add search guesses and faux predictive search to the search box
		// All added here, no html changes
		var selectedKeyword = 0;
		var debug = false
		var xmlObj;
		// store the original search string for later use
		var originalSearchText = "";		
		//grab the search text value
		var SearchTextEntered = "";
		//Just some strings that are used a couple of times
		var SearchTextboxID = "#p_search_text";
		var formObject = "form[name='_search']";
		var searchUrlAllWords = "http://www.nationwide.co.uk/search/Search.aspx?type=any&category=-1&word="
		// This needs to go in alphabetical order. It's easiest to make it in excel, then sort it.
		var myregexp = /(your|you|year|year|wouldn't|would not|would|wish|will|why|who|where|when|what|we|want|tried|to|this|there's|there|them|the|tell|send|see|provide|please|pay|our|not|need|nationwide|my|much|me|making|make|long|list|like|know|I've|isn't|is|if|I|how|haven't|have|don't|does|do|didn't|did not|did|couldn't|could|can't|cannot|can|are|an|am|a|-)\s/gi

		// Count the number of matches found in the search
		var MatchCount = 0
		function parseXml(xml) {  
			if (jQuery.browser.msie) {  
				var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");  
				xmlDoc.loadXML(xml);				
				xml = xmlDoc;
			}
			return xml;
		}
		function DynamicSearchVersion1(){					
			// load search keywords xml document
			$.ajax({
				type: "GET",
				url: "/ajax_search/ajax_search.xml",
				dataType: ($.browser.msie) ? "text" : "xml",
				success: function(xml) {
					xmlObj = parseXml(xml); 
				}
			});
			$("body").append("<div id=\"search_suggestions\"></div>");
			var SearchBoxTop = $(SearchTextboxID).offset().top
			var SearchBoxLeft = $(SearchTextboxID).offset().left
			var SearchBoxHeight = $(SearchTextboxID).height();
			$("#search_suggestions").css({
				"top":SearchBoxTop + 4 + SearchBoxHeight,
				"left":SearchBoxLeft
			});
			var timeout;
			$(SearchTextboxID).keyup(function(event){
				if(timeout){
					clearTimeout(timeout);
					timeout = null;
				}
				timeout = setTimeout(function(){runKeyUpVersion1(event)},200);
			});
			$(SearchTextboxID).keydown(function(event){		
				runKeyDownVersion1(event);
			});
			$(SearchTextboxID).blur(function(event){
				$("#search_suggestions").animate({opacity: 1.0}, 500).slideUp("fast",function(){
					$("select").css("visibility","visible")
				});//HIDE
			});
			$(SearchTextboxID).focus(function(event){
				if(MatchCount > 0){
					$("#search_suggestions").slideDown("fast");//SHOW
					$("select").css("visibility","hidden");
				}
			});
			$(formObject).submit(function(){
				var tempFilteredText = $(SearchTextboxID).val().replace(myregexp,"");	
				if(tempFilteredText == "branch finder" || tempFilteredText == "local branch" || tempFilteredText == "nearest branch" || tempFilteredText == "closest branch"){
					window.location.href = "http://www.nationwide.co.uk/search/DisplayArticle.aspx?article=1330";
					return false;
				}
				if(selectedKeyword > 0){
					window.location.href = searchUrlAllWords + $(SearchTextboxID).val();
					return false;
				}
			});
		}
		//DynamicSearchVersion1();
		function runKeyUpVersion1(event){	
			var keypressed = parseInt(event.keyCode);	
			SearchTextEntered = jQuery.trim($(SearchTextboxID).val());
			var SearchTextFiltered = SearchTextEntered.toLowerCase();
			// set up a list of words and phrases that the search should ignore	
			//SearchTextFiltered = SearchTextFiltered.replace(myregexp,"")
			if((keypressed > 64 && keypressed < 91 || keypressed > 47 && keypressed < 58 || keypressed == 8 || keypressed == 46 || keypressed == 189 || keypressed == 32) && SearchTextFiltered != ""){
				$(SearchTextboxID).css({
					"background-image":"url(/ajax_search/ajax-loading.gif)",
					"background-position":"top right",
					"background-repeat":"no-repeat"
				});
				originalSearchText = SearchTextEntered
				//keys a-z have been pressed OR keys 0-9 have been pressed
				// or backspace or delete or a dash or a space		
				// reset the selected keyword to 0.
				// or it jumps halfway on edit of list
				selectedKeyword = 0
				// start over, wipe any existing matches and re-search.
				$("#search_suggestions").html('');
				// reset the match count before doing a search
				MatchCount = 0
				// loops through and get every keyword in the keyword list
				$(xmlObj).find('keyword').each(function(){
					// match the start position of the match	
					var renderedResultText = $(this).text();
					var ResultTextFiltered = renderedResultText.replace(/-/g,"")
					// try a match on the whole phrase
					var matchIndex = ResultTextFiltered.toLowerCase().indexOf(SearchTextEntered.toLowerCase());					
					//if it's just an I or an A then don't search
					if(SearchTextFiltered == "a" || SearchTextFiltered == "i"){
						// force fail
						matchIndex = -1;
					}					
					// there is a match
					if (matchIndex == 0){
						// count how many matches there are
						MatchCount++
		        		$("<div class=\"singleResult\">" + renderedResultText + "</div>").appendTo($("#search_suggestions"))
		        		.click(function(){
							$(SearchTextboxID).val(renderedResultText);
							$(formObject).submit();
							//window.location.href = searchUrlAllWords + renderedResultText
						})
					}
					// Now trying a filtered phrase
					SearchTextFiltered = SearchTextEntered.toLowerCase().replace(myregexp,"");
					// if there is a space in the keywords results, split it up 
					// to test on each word.
					if(renderedResultText.indexOf(" ") != -1 && SearchTextFiltered.indexOf(" ") == -1){
						var renderedResultTextArray = renderedResultText.split(" ");
						// try a match on the filtered phrase						
						matchIndex = -1
						for(var arrayCounter = 0;arrayCounter < renderedResultTextArray.length;arrayCounter++){
							if(matchIndex != 0){
								matchIndex = renderedResultTextArray[arrayCounter].toLowerCase().indexOf(SearchTextFiltered);
							}
						}
					}
					else{
						// try a match on the filtered phrase
						matchIndex = renderedResultText.toLowerCase().indexOf(SearchTextFiltered);
					}					
					//if it's just an I or an A then don't search
					if(SearchTextFiltered == "a" || SearchTextFiltered == "i"){
						// force fail
						matchIndex = -1;
					}					
					// there is a match at the start of a word
					if (matchIndex == 0 && SearchTextFiltered.length > 0){
						if($("#search_suggestions div:last").text() != renderedResultText){
							var prependText = SearchTextEntered.substring(0,SearchTextEntered.length - SearchTextFiltered.length)
	        				// count how many matches there are
							MatchCount++
	        				$("<div class=\"singleResult\">" + prependText + renderedResultText + "</div>").appendTo($("#search_suggestions"))
	        				.click(function(){
								$(SearchTextboxID).val(renderedResultText);
								$(formObject).submit();
								//window.location.href = searchUrlAllWords + renderedResultText
							});
						}
					}
				});
				// if there is at least one match
				if(MatchCount > 0){	
					$(SearchTextboxID).css("background-image","none");
					$("#search_suggestions").find("div").each(function(){						
						$(this).mouseover(function(){							
							// remove the class from all matches
							$("#search_suggestions div").removeClass('selectedKeyword');
							// add the class to the selected one
							$(this).addClass('selectedKeyword');
						});
						$(this).mouseout(function(){							
							// remove the class from all matches
							$("#search_suggestions div").removeClass('selectedKeyword');
							// add the class back to the one that was previously selected
							$("#search_suggestions div:nth-child(" + selectedKeyword + ")").addClass('selectedKeyword');
						});
					});
					$("#search_suggestions").slideDown("fast");//SHOW
					$("select").css("visibility","hidden");
				}
				else{
					$("#search_suggestions").slideUp("fast");//HIDE
					$(SearchTextboxID).css("background-image","none");
					$("select").css("visibility","visible");
				}	
			}
			else if(SearchTextFiltered.length == 0){
				// no text entered
				$("#search_suggestions").slideUp("fast");//HIDE
				$("#header-InterestRates").css("visibility","visible");
				// clear the box out
				$("#search_suggestions").html('');
				MatchCount = 0;
				selectedKeyword = 0;
			}	
		}
		function runKeyDownVersion1(event){
			//grab the search text value
			SearchTextEntered = $(SearchTextboxID).val();			
			// grab the key event code
			var keypressed = parseInt(event.keyCode);
			if(keypressed == 38 && MatchCount != 0){
				//up key has been pressed
				if (selectedKeyword > 0){					
					selectedKeyword--;					
					//$("#search_suggestions div").css("background-color", "#ffffff");
					$("#search_suggestions div").removeClass('selectedKeyword');
					//$("#search_suggestions div:nth-child(" + selectedKeyword + ")").css("background-color", "#ffff00");
					$("#search_suggestions div:nth-child(" + selectedKeyword + ")").addClass('selectedKeyword');
					// save the newly selected search text
					SearchTextEntered = $("#search_suggestions div:nth-child(" + selectedKeyword + ")").text();
					$(SearchTextboxID).val(SearchTextEntered);
				}
				if(selectedKeyword == 0 && originalSearchText != ""){		
					// when the user keys up to the top, reset it their original text
					$(SearchTextboxID).val(originalSearchText);
					//originalSearchText = ""
				}
			}
			else if(keypressed == 40 && SearchTextEntered != "" && MatchCount != 0){
				//down key has been pressed
				// if the user has reached the end of the matches, then go somewhere else			
				if(selectedKeyword == MatchCount){
					selectedKeyword = 0; // Zero will reset them back to the top
				}
				selectedKeyword++;
				$("#search_suggestions div").removeClass('selectedKeyword');
				$("#search_suggestions div:nth-child(" + selectedKeyword + ")").addClass('selectedKeyword');
				// save the newly selected search text
				SearchTextEntered = $("#search_suggestions div:nth-child(" + selectedKeyword + ")").text();
				$(SearchTextboxID).val(SearchTextEntered);
			}
		}
		// END DYNAMIC SEARCH

if ($("#newsline_cycler").length>0)
{
$("#newsline_cycler").cycle({
	fx:'scrollLeft',
	speed:800,
	timeout:5000,
	pause:1
	})
}

if($("#invPplLikeMeFader").length>0){
	$("#invPplLikeMeFader").cycle("fade");
}
function mortgageRatesButton(){
//btnMortgageRates
	$("#btnMortgageRates").click(function(){
				var buyertype = $("#selectMortgageRates").val();
				var propertyvalue = $("#txtValueOfProperty").val();
				var mortgagerequired = $("#txtMortgageRequired").val();                       
				if(isNaN(propertyvalue) || propertyvalue==""){propertyvalue = 0;}
				if(isNaN(mortgagerequired) || mortgagerequired==""){mortgagerequired = 0;}                        
				var rateUrl = "/mortgages/interestrates-types/rates.htm?buyerType=" + buyertype + "&propertyValue=" + propertyvalue + "&mortgageAmount=" + mortgagerequired
				window.location = rateUrl;
				return false;
	});

}
mortgageRatesButton();

function btnGoHover(){                                        
	if($(".btnGo").length > 0){	/*all go buttons*/
				$(".btnGo").hover(function(){$(this).attr("src","/_common_images/buttons/btn_go_hover.gif");},function(){$(this).attr("src","/_common_images/buttons/btn_go_normal.gif");});
				$(".btnGo").mousedown(function(){$(this).attr("src","/_common_images/buttons/btn_go_click.gif");$(this).data("isDown","true");});
				$(".btnGo").mouseup(function(){$(this).attr("src","/_common_images/buttons/btn_go_normal.gif");$(this).data("isDown","false");});
				/*imgs only*/
				$("img.btnGo").mousemove(function(){if($(this).data("isDown")=="true"){$(this).attr("src","/_common_images/buttons/btn_go_hover.gif");$(this).data("isDown","false");}});
	}
}
btnGoHover();    

function btnCompareHover(){                                        
	/*all go buttons*/
	if($(".btnCompare").length > 0){
				$(".btnCompare").mouseover(function(){$(this).removeClass("btnCompare");$(this).addClass("btnCompareHover");});
				$(".btnCompare").mouseout(function(){$(this).addClass("btnCompare");$(this).removeClass("btnCompareHover");$(this).removeClass("btnCompareClick");});
				$(".btnCompare").mousedown(function(){$(this).removeClass("btnCompareHover");$(this).addClass("btnCompareClick");});            
	}
}
btnCompareHover();

function mortgageQuoteApplyButton(){
	if($(".btnQuoteApply").length > 0){
				$(".btnQuoteApply").mouseover(function(){$(this).addClass("btnQuoteApplyHover");});
				$(".btnQuoteApply").mouseout(function(){$(this).addClass("btnQuoteApply").removeClass("btnQuoteApplyHover").removeClass("btnQuoteApplyClick");});
				$(".btnQuoteApply").mousedown(function(){$(this).removeClass("btnQuoteApplyHover").addClass("btnQuoteApplyClick");});          
	}
}
mortgageQuoteApplyButton();

function setButtons(){
	if($(".btn").length > 0){
		$(".btn").mouseover(function(){$(this).addClass("btnHover");});
		$(".btn").mouseout(function(){$(this).addClass("btn").removeClass("btnHover").removeClass("btnClick");});
		$(".btn").mousedown(function(){$(this).removeClass("btnHover").addClass("btnClick");});          
	}
}
setButtons();

function applySteps(spriteUrl){
	function viewStep(e){
		var realElement = this;
		if(e.type == "focus")
			realElement = $(this).parent()[0];
		if(!$(realElement).hasClass("stepSelected")){
			var hPos = $(realElement).css("backgroundPosition");
			hPos = hPos.split(" ")[0];
			var vPos = "-83px"
			if($("div.applySteps>ol>li").index($(realElement)) == $("div.applySteps>ol>li").size()-1)
				vPos = "-80px";
			$(realElement).css({
				"backgroundPosition":hPos + " " + vPos,
				"z-index":$("div.applySteps>ol>li").size()+1
			});
			$("div.applySteps div.contentBox").html("<div id=\"step" + ($("div.applySteps>ol>li").index($(realElement))+1) + "\"></div>" + $(realElement).children("div.content").html());
			setButtons();
		}
	}
	function hideStep(e){
		var realElement = this;
		if(e.type == "blur")
			realElement = $(this).parent()[0];
		if(!$(realElement).hasClass("stepSelected")){
			var hPos = $(realElement).css("backgroundPosition");
			hPos = hPos.split(" ")[0];
			$(realElement).css({
				"backgroundPosition":hPos + " 0",
				"z-index":$("div.applySteps>ol>li").size() - $("div.applySteps>ol>li").index($(realElement))
			});
			$("div.applySteps div.contentBox").html("<div id=\"step" + ($("div.applySteps>ol>li").index($("div.applySteps>ol>li.stepSelected"))+1) + "\"></div>" + $("div.applySteps>ol>li.stepSelected").children("div.content").html());			
			setButtons();
		}
	}	
	$("div.applySteps>ol>li div.step").css({"text-indent":"-3000px"});
	$("div.applySteps>ol>li div.content").hide();
	$("div.applySteps").append("<div class=\"contentBox\"></div>");
	var olWidth = ($("div.applySteps>ol>li").size() * 104) - 15;
	var contentBoxWidth = parseInt($(".applySteps .contentBox").width()) + parseInt($(".applySteps .contentBox").css("padding-left")) + parseInt($(".applySteps .contentBox").css("padding-right"));
	var olMarginLeft = Math.round((contentBoxWidth - olWidth) / 2);
	$("div.applySteps>ol").css({
		"margin":"10px 0 0 " + olMarginLeft + "px",
		"padding":"0",
		"overflow":"hidden"
	});
	$("div.applySteps>ol>li").css({
		"background-image":"url("+spriteUrl+")",
		"position":"relative",
		"float":"left",
		"height":"83px",
		"width":"116px",
		"margin-right":"-12px"
	})
	.each(function(n){
		$(this).css({
			"backgroundPosition":"-"+116*n+"px 0",
			"z-index":$("div.applySteps>ol>li").size()-n
		})
		.children("div.step").wrap("<a href=\"#\"></a>");
	})
	.filter(":last").css({
		"width":"89px",
		"height":"80px",
		"margin-right":"0"
	}).end()
	.hover(viewStep,hideStep)
	.children("a").bind("focus",viewStep).bind("blur",hideStep).end()
	.click(function(){
		$("div.applySteps>ol>li").removeClass("stepSelected")
		.each(function(n){
			$(this).css({
				"backgroundPosition":"-"+116*n+"px 0",
				"z-index":$("div.applySteps>ol>li").size()-n
			});
		})
		var hPos = $(this).css("backgroundPosition");
		hPos = hPos.split(" ")[0];
		var vPos = "-166px"
		if($("div.applySteps>ol>li").index($(this)) == $("div.applySteps>ol>li").size()-1)
			vPos = "-160px";
		$(this).css({
			"backgroundPosition":hPos + " " + vPos,
			"z-index":$("div.applySteps>ol>li").size()+2
		})
		.addClass("stepSelected");
		$("div.applySteps div.contentBox").html("<div id=\"step" + ($("div.applySteps>ol>li").index($(this))+1) + "\"></div>" + $(this).children("div.content").html());
		setButtons();		
	})
	$("div.applySteps>ol>li:first").trigger("click");
}

function createApplySteps(){
	var applyStepsId, spriteUrl;
	applyStepsId = $("div.applySteps").attr("id");
	switch(applyStepsId){
		case "currentAccountApply":
			spriteUrl = "/_common_images/current_account_apply_sprite.gif";
			break;
		case "mortgageApply":
			spriteUrl = "/_common_images/apply_big_sprite.gif";
			break;
	}
	applySteps(spriteUrl);
}
createApplySteps()


/* Experimental stuff below here */
		
		function addARIAattributes()
		{
			$("#globallinks, #productnav, #breadcrumb, #leftnav, #footer, #hp-latest-news").attr("role","navigation");
			$("#search").attr("role","search");
			$("div.moreinfo").attr("role","contentinfo");
			$("#headerleft").attr("role","banner");
		}
		addARIAattributes();
		$("#err404trySearch").click(function(){
			$("#p_search_text").css("background","#fae7cb").css("border","1px solid #ff9900");
			$("#p_search_text").focus();
			$("#p_search_text").keypress(function(){
				$(this).css("background","#fff").css("border","1px solid #000");
			});
			return false;
		});
		}

/* mortgage questionnaire launcher */
	function qLaunch(path, popUpLocation){
		if(document.location.pathname.indexOf(path) == 0){
			var nextLocation = "";
			var launched = false;
			var splitCookie = document.cookie.split(";");
			var valPos, qVal
			for(var x=0; x < splitCookie.length; x++){
				valPos = splitCookie[x].indexOf("=");
				if(splitCookie[x].indexOf("questionnaire") == 0){
					if(valPos > -1){
						 qVal = splitCookie[x].substring(valPos+1);
						 if(qVal = "true"){
						 	launched = true;
						 }
					}
				}
			}
			$('a').click(function(){
				nextLocation = this.pathname;
				if(nextLocation.charAt(0) != "/"){
					nextLocation = "/" + nextLocation;
				}
			});
			window.onbeforeunload = function(){
				if(!launched){
					if(nextLocation.indexOf(path) != 0){
						window.open(popUpLocation, "myWin");
						document.cookie = "questionnaire=true;path=" + path + ";max-age=604800;";
					}
				}
			};
		}
	}

	
	//Support Page function
	
	$("#ccsearch").submit(function(){
		var term = $("#ccsearchtxt").val();
		var searchurl = "http://www.nationwide.co.uk/search/Search.aspx?word=" + term + "&type=any&category=1445";
		location.href=searchurl;
		return false;
	})
	$("#mortgagesearch").submit(function(){
		var term = $("#mortgagesearchtxt").val();
		var searchurl = "http://www.nationwide.co.uk/search/Search.aspx?word=" + term + "&type=any&category=1449";
		location.href=searchurl;
		return false;
	})
	
	//end support page function
	

	/*qLaunch("/investments/guaranteed-equity-bond/", "/investments/questionnaire/default.asp");*/

	//Security Centre questionnaire

	//Uncomment the following to launch the Security Centre questionnaire

	/*if(Math.random() < 0.25){
		qLaunch("/security/", "/security/questionnaire/default.asp");
	}*/

}

/*  END jQuery functions*/ 

/* All addEvent function calls below here please :-) */
addEvent(window, 'load', initConcertina, false);
//addEvent(window, 'load', setUpSearchBox, false);
addEvent(window, 'load', doJQueryFunctions, false);
