//TODO: namespace s1 stuff from alessio
var Barclays = {};

function logIt(msg){
	addText(msg,create("p","error",document.getElementById("header")))
}

Barclays.Common = {

	// stop background images flickering in IE6
	stopBackgroundImageFlicker: function(){
	
	    try {
            document.execCommand("BackgroundImageCache", false, true);
        } 
        
        catch(err) {}
    },
	
	getIEMajorVersion : function(){
		if(navigator.appName === "Microsoft Internet Explorer"){
			var regExp = /MSIE\s(\d+)\./gi;
			var testUA = regExp.exec(navigator.userAgent);
			return testUA[1];
		}
		else{
			return false;
		}
	},
	
	islteIE6 : function(){
		var IEVersion = Barclays.Common.getIEMajorVersion();
		if(IEVersion && IEVersion < 7){
			return true;
		}
		return false;
	},
	
	/*	Original code developed by Robert Nyman, http://www.robertnyman.com	Code/licensing: http://code.google.com/p/getelementsbyclassname/ */
	getElementsByClassName: function (oElm, strTag, strClassName){
		if (document.getElementsByClassName) {
			getElementsByClassName = function (oElm, strTag, strClassName) {
				oElm = oElm || document;
				var elements = oElm.getElementsByClassName(strClassName),
				nodeName = (strTag && (strTag !== "*"))? new RegExp("\\b" + strTag + "\\b", "i") : null,
				returnElements = [],
				current;
				for(var i=0, il=elements.length; i<il; i+=1){
					current = elements[i];
					if(!nodeName || nodeName.test(current.nodeName)) {
						returnElements.push(current);
					}
				}
				return returnElements;
			};
		}
		else if (document.evaluate) {
			getElementsByClassName = function (oElm, strTag, strClassName) {
				strTag = strTag || "*";
				oElm = oElm || document;
				var classesToCheck = "",
				xhtmlNamespace = "http://www.w3.org/1999/xhtml",
				namespaceResolver = (document.documentElement.namespaceURI === xhtmlNamespace)? xhtmlNamespace : null,
				returnElements = [],
				elements,
				node;           
				classesToCheck += "[contains(concat(' ', @class, ' '), ' " + strClassName + " ')]";
		 
				try     {
					elements = document.evaluate(".//" + strTag + classesToCheck, oElm, namespaceResolver, 0, null);
				}
				catch (e) {
					elements = document.evaluate(".//" + strTag + classesToCheck, oElm, null, 0, null);
				}
				while ((node = elements.iterateNext())) {
					returnElements.push(node);
				}
				return returnElements;
			};
		}
		else {
			getElementsByClassName = function (oElm, strTag, strClassName) {
				strTag = strTag || "*";
				oElm = oElm || document;
				var classes = strClassName.split(" "),
				classesToCheck = [],
				elements = (strTag === "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTag),
				current,
				returnElements = [],
				match;
				for(var k=0, kl=classes.length; k<kl; k+=1){
					classesToCheck.push(new RegExp("(^|\\s)" + classes[k] + "(\\s|$)"));
				}
				for(var l=0, ll=elements.length; l<ll; l+=1){
					current = elements[l];
					match = false;
					for(var m=0, ml=classesToCheck.length; m<ml; m+=1){
						match = classesToCheck[m].test(current.className);
						if (!match) {
							break;
						}
					}
					if (match) {
						returnElements.push(current);
					}
				}
				return returnElements;
		 	};
		}
	return getElementsByClassName(oElm, strTag, strClassName);
	},
	getParentByTagName : function(el,tagName){
		var parent=el.parentNode;
		while(tagName.toLowerCase()!=parent.nodeName.toLowerCase()){
			parent=parent.parentNode;
			if(!parent || parent.nodeName=="#document"){return false;}
		}
		return parent;
	},
	//returns the first parent node of oElm that has strClassName in its class attribute
	//classname is 'fuzzy'
	getParentByClassName : function(oElm,strClassName){
		var parent=oElm.parentNode;
		while(parent.className.indexOf(strClassName)==-1){
			parent=parent.parentNode;		
			if(!parent || parent.nodeName=="#document"){return false;}
		}
		return parent;
	},
	//finds the elements in oElm's block that has a specified attribute with a specified value
	//CAVEAT: IE6 and below has patchy support for class attribute, don't use for that
	getByAttribute : function(oElm,strTagName,attribName,attribValue){
		var sEls=oElm.getElementsByTagName(strTagName);
		var aElms=new Array();
		for(var s=0;s<sEls.length;s++){
			if(sEls[s].getAttribute(attribName)==attribValue){
				aElms.push(sEls[s]);
			}
		}
		return aElms;
	},
	changeClass: function(element,value) {
		if (value === "") {
			element.className = "";
		}
		else {
			if (!element.className) {
				element.className = value;
			} 
			else {
	//			element.className+= " ";
				element.className= value;
			}
		}
	},
	//as getelementbyclassname, but looks for a partial match rather than exact
	fuzzyClassName : function(tag,fClass)	{
		var el = (tag == "*" && document.all) ? document.all : document.getElementsByTagName(tag);
		var o=[];
		for (var i=0;i<el.length;i++)	{
			if (el[i].className.indexOf(fClass)!=-1)	{
				o.push(el[i]);
			}
		}
		return o;
	},
	//as fuzzyClassName, but restriced to self and children of a specific DOM object
	fuzzyClassNameBlock : function(block,tag,fClass)	{
		var el = (tag == "*" && block.all) ? block.all : block.getElementsByTagName(tag);
	
		var o=[];
		for (var i=0;i<el.length;i++)	{
			if (el[i].className.indexOf(fClass)!=-1)	{
				o.push(el[i]);
			}
		}
		if(block.className.indexOf(fClass)!=-1){
			o.push(block);
		}
		return o;
	},
	//get the contents between ( and ) marks attached to a classname that starts with a given marker
	getPEClassInfo : function(el,marker){
		var fullClass = el.className;
		var info = fullClass.substring(fullClass.indexOf(marker+"(")+marker.length+1);
		info = info.substring(0,info.indexOf(")"));
		return info;
	},
	//handle cross-browser reading of CSS-set styles
	getStyle : function (el,stylename){
		if(el.style[stylename]){
			return el.style[stylename];
		}
		else if(el.currentStyle){
			//handle IE's style-name to styleName convention
			if(stylename.indexOf("-") != -1 && !el.currentStyle[stylename]){
				//get 1st char after -, uppercase, rem -
				var preHyphen = stylename.substr(0,stylename.indexOf("-"));
				var postHyphenFirstLetter = stylename.substr(stylename.indexOf("-")+1,1).toUpperCase();
				var postHyphenRemainder = stylename.substr(stylename.indexOf("-")+2);
				stylename = preHyphen + postHyphenFirstLetter + postHyphenRemainder;
			}
			return el.currentStyle[stylename];
		}
		else if(document.defaultView && document.defaultView.getComputedStyle){
			return document.defaultView.getComputedStyle(el,null).getPropertyValue(stylename);
		}
		else{return false;}
	},
	//handle cross-browser viewport height
	getViewPortHeight : function(){
		if(window.innerHeight){
			return window.innerHeight;
		}
		else if(document.documentElement && document.documentElement.clientHeight){
			return document.documentElement.clientHeight;
		}
		else if(document.body){
			return document.body.clientHeight;
		}
		else{return false;}
	},
	//handle cross-browser viewport width
	//nb getWindowSize was duplicate, removed that due to stack overflows in IE6
	getViewPortWidth : function(){
		if(window.innerWidth){
			return window.innerWidth;
		}
		else if(document.documentElement && document.documentElement.clientWidth){
			return document.documentElement.clientWidth;
		}
		else if(document.body){
			return document.body.clientWidth;
		}
		else{return false;}
	},
	//find and compare viewport and body heights and widths. return the largest of each dimension in array
	getFullPageDimensions : function(){
		var newHeight = Barclays.Common.getViewPortHeight();
		var newWidth  = Barclays.Common.getViewPortWidth();
		/*compare with body */
		if(newWidth < document.body.clientWidth){
			newWidth = document.body.clientWidth;
			newWidth += parseInt(Barclays.Common.getStyle(document.body,"margin-left"),10) + parseInt(Barclays.Common.getStyle(document.body,"margin-right"),10);
		}
		if(newHeight < document.documentElement.scrollHeight){
			newHeight = document.documentElement.scrollHeight;
			newHeight += parseInt(Barclays.Common.getStyle(document.body,"margin-top"),10) + parseInt(Barclays.Common.getStyle(document.body,"margin-bottom"),10);
			if(window.innerWidth && window.innerWidth > document.body.scrollWidth){newWidth -= 17;}//handle Firefox bug where it counts the scrollbar too for scrolling pages
		}
		
	
		return [newWidth,newHeight];
	},
	//handle cross-browser retrieval of how far user has scrolled down
	getScrollTop : function(){
		if(window.pageYOffset){
			return window.pageYOffset;
		}
		else if(document.documentElement && document.documentElement.scrollTop){
			return document.documentElement.scrollTop;
		}
		else if(document.body){
			return document.body.scrollTop;
		}
		else{return false;}
	},
	//handle cross-browser adding events
	addEvent : function (obj,evt,fn){
		if(document.addEventListener){
			Barclays.Common.addEvent = function(obj,evt,fn){
				obj.addEventListener(evt,fn,false);
			}
		}
		else if(document.attachEvent){
			Barclays.Common.addEvent = function(obj,evt,fn){
				obj["e"+evt+fn] = fn;
				obj[evt+fn] = function() { obj["e"+evt+fn]( window.event ); }
				obj.attachEvent( "on"+evt, obj[evt+fn] );
			}
		}
		else{
			return false;
		}
		Barclays.Common.addEvent(obj,evt,fn);
	},
	loadCSSFile : function(filename){
		var fileLink = document.createElement("link");
		fileLink.rel = "stylesheet";
		fileLink.type = "text/css";
		fileLink.media = "screen";
		fileLink.href = filename;
		document.getElementsByTagName("head")[0].appendChild(fileLink);
	},
	/*Generic AJAX functions*/
	/* XML DATA REQUEST AND MANIPULATION FUNCTIONS */
	AJAX : {
	// returns a cross-browser XMLHTTPRequest object
		createXMLHttpRequest : function() {
			try { return new XMLHttpRequest(); } catch(e) {}
			try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {}
			try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {}
			alert("XMLHttpRequest not supported");
			return null;
		},
		processingIndicator : function(){
			var processingImg = document.getElementById("ajax_wait");
			if(!processingImg){
				processingImg = document.createElement("img");
				processingImg.src="/assets/img/icons/ajax-loader.gif";
				processingImg.alt="Please wait, processing your request.";
				processingImg.id="ajax_wait";
			}
			return processingImg;
		},
	//accessibility hack: updates the value of a hidden field to trigger a buffer refresh. called in the functions that are run when an AJAX call has returned data or error
		updateBuffer : function(){
			var bufferReset = document.getElementById("bufferReset");
			if(!bufferReset){
				bufferReset = document.createElement("input");
				bufferReset.type="hidden";
				bufferReset.name="bufferReset";
				bufferReset.value=1;
					bufferReset.id="bufferReset";
				document.body.appendChild(bufferReset);
			}
			bufferReset.value++;
		}
	},
	pngFix : function(){
	var root=false;
	var applyPositioning=false;
	var shim='/assets/img/placeholder/blank.gif';
	var shim_pattern=/\/assets\/img\/placeholder\/blank\.gif$/i;
	
		var fnLoadPngs=function(){
			if(root){
				root=document.getElementById(root);
			}else{
				root=document;
			}
		for(var i=root.all.length-1,obj=null;(obj=root.all[i]);i--){if(obj.currentStyle.backgroundImage.indexOf(".png") != -1){bg_fnFixPng(obj);}
		//used to avoid the use of the fix with png8 inages
		if(obj.tagName=='IMG'&&obj.className.indexOf("noPngFix")>-1) return false;
		
		if(obj.tagName=='IMG'&&obj.src.match(/\.png$/i)!==null){el_fnFixPng(obj);}
		if(obj.tagName=='IMG'&&obj.className.indexOf("png")>-1){
			el_fnFixPng(obj);
		}

if(applyPositioning&&(obj.tagName=='A'||obj.tagName=='INPUT')&&obj.style.position===''){obj.style.position='relative';}}};var bg_fnFixPng=function(obj){var mode='scale';var bg=obj.currentStyle.backgroundImage;var src=bg.substring(5,bg.length-2);if(obj.currentStyle.backgroundRepeat=='no-repeat'){mode='crop';}
obj.style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+src+"', sizingMethod='"+mode+"')";obj.style.backgroundImage='url('+shim+')';};var el_fnFixPng=function(img){var src=img.src;img.style.width=img.width+"px";img.style.height=img.height+"px";img.style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+src+"', sizingMethod='scale')";img.src=shim;};

	fnLoadPngs();
	},
	//onload event
	addLoadEvent : function(func) {
		if(typeof func != 'function'){
			return false;
		}
	  var oldonload = window.onload;
	  if (typeof window.onload != 'function') {
	    window.onload = func;
	  } else {
	    window.onload = function() {
	      oldonload();
	      func();
	    }
	  }
	},
	
	setUpDOMReady : function(){
		if (!/Opera/i.test(navigator.userAgent)){
			
			if (document.addEventListener) {
				document.addEventListener("DOMContentLoaded", Barclays.Custom.domReadyInit, null);
			}
		}else{
			G_wk = setInterval(function(){
											if (document.getElementsByTagName("body")[0]) {
												clearInterval(G_wk);
												delete G_wk;
												Barclays.Custom.domReadyInit();
											}
										},1000);
		}
		if (/WebKit/i.test(navigator.userAgent)){
			G_wk = setInterval(function(){
										if (/loaded|complete/.test(document.readyState)) {
											clearInterval(G_wk);
											delete G_wk;
											Barclays.Custom.domReadyInit();
											return;
										}
											},50);
			}
		/* DO NOT REMOVE THIS SECTION - IE CONDITIONAL COMPILATION */
		/*@cc_on @*/
		/*@if (@_win32)
		document.write("<script id=el_ie defer src=/assets/script/blank.js><\/script>");
		var script = document.getElementById("el_ie");
		script.onreadystatechange = function() {
			if (this.readyState == "complete") {
				Barclays.Custom.domReadyInit();
				return;
			}
		}
		/*@end @*/
		/* IE CONDITIONAL COMPILATION ENDS */
		//failsafe
		//Barclays.Common.addLoadEvent(Barclays.Custom.domReadyInit);
		
		Barclays.Common.addLoadEvent(function() {
				//logIt("LoadEvent")				
				if(Barclays.Common.islteIE6()){
					Barclays.Common.pngFix();		
				}				
			});
		
		/* - */
	}	

}; 



Barclays.Custom = {
	domReadyInit : function(){
			
		if (window.initialised){return;}
		window.initialised=true;
		
		
		
		//Barclays.Common.loadCSSFile('/assets/style/has_js.css');
		addClass(document.body,"hasJs");
		
		/*@cc_on @*/
		/*@if (@_win32)
			Barclays.Common.loadCSSFile('/assets/style/ie/ie_has_js.css');
		/*@end @*/
		//logIt("domReadyInit start")
		
		Barclays.Common.stopBackgroundImageFlicker();
		Barclays.Custom.positionElements();
		Barclays.Custom.toggleVisibility();
		Barclays.Custom.resetImgs();
		Barclays.Custom.glow();
		Barclays.Custom.contextualHelp();
		Barclays.Custom.layerList();
		Barclays.Custom.filterSearch();
		Barclays.Custom.externalLinks();
		Barclays.Custom.Scroller.init();
		Barclays.Custom.printPage();
		Barclays.Custom.popup();
		Barclays.Custom.popupOpener();
		Barclays.Custom.floatingListHeights();
		Barclays.Custom.sifr();
		Barclays.Custom.imgSwap();
		Barclays.Custom.bgImgSwap();
		Barclays.Lightbox.init();
		Barclays.Custom.splitEmails();
		Barclays.Custom.initCarousel();
		Barclays.Custom.Poll.init();
		Barclays.Custom.highlighting();
		Barclays.Custom.emboldenLabels();
		Barclays.Custom.secondaryNavigation.init();
		Barclays.Custom.radioButtonsReplaceForm.init();
		Barclays.Custom.AJAXLightbox.init();
		Barclays.Custom.HRhandler();
		
		//logIt("domReadyInit end")
		
	
			
		
	},
	//onload
	init: function(){
		Barclays.Maps.init();
		Barclays.Custom.clearFields();
		Barclays.Custom.setupExpandableAreas();//after map setup
	},
	/*
	PRINT PAGE
		buttons to trigger the print dialog for the user to print the page.  these are hidden with CSS and re-displayed with javascript so that non-js users don't see a button they cannot use.
	REQUIRED:
		<a> with class 'PE_print' on it
	*/
	printPage : function(){
		var printLinks = Barclays.Common.getElementsByClassName(document,"a","PE_print");
		for(var i=0,j=printLinks.length;i<j;i++){
			if(window.print){printLinks[i].style.visibility = "visible";}
			printLinks[i].onclick = function(){window.print();return false;}
		}
	},
	/*
	POPUP WINDOWS
		adds window.open functionality to a link.  it makes use of the link's href attribute to determine what url to open in the new window.
		resizable and scrollbars options must be left on for accessibility.
	REQUIRED:
		<a> with class PE_popup(300,200) where 300 is desired with and 200 is desired height
	*/
	popup : function(){
		function openWin(){
			window.open (this.href,'barclayspopup','width='+this.winWidth+',height='+this.winHeight+",resizable=yes,scrollbars=yes");
			return false;
		}
		var popupLinks = Barclays.Common.fuzzyClassName("a","PE_popup");
		for(var i=0,j=popupLinks.length;i<j;i++){
			var dimensions = Barclays.Common.getPEClassInfo(popupLinks[i],"PE_popup");
			var aDim = dimensions.split(",");
			popupLinks[i].winWidth = aDim[0];
			popupLinks[i].winHeight = aDim[1];
			popupLinks[i].onclick = openWin;
		}
	},
	popupOpener : function(){
		
		function openerWin(){
			//window.opener.location.href = this.href;
			setTimeout(window.close,100)
			//return true;
		};
		var popupLinks = Barclays.Common.fuzzyClassName("a","PE_opener");
		for(var i=0,j=popupLinks.length;i<j;i++){
			popupLinks[i].onclick = openerWin;
			popupLinks[i].target="_blank";
		}
	},
	/*
	HIGHLIGHTING 
		rolling over a link highlights all items belonging to that group
		e.g. countries containing certain business areas
		
	REQUIRED:
		<a> width class PE_category(id)
		element with class PE_hasCategories(id1,id2)
	*/
	highlighting : function(){
		var categories = Barclays.Common.fuzzyClassName("a","PE_category");
		var filtersCount = 0;
		for(var i=0,j=categories.length;i<j;i++){
			var catID = Barclays.Common.getPEClassInfo(categories[i],"PE_category");
			var categoriesItems = Barclays.Common.fuzzyClassName("*","PE_hasCategories");
			
			var toggleParent = Barclays.Common.getParentByClassName(categories[i],"PE_toggle");

			if(toggleParent.length < 1){continue;}
			var countriesList = Barclays.Common.getElementsByClassName(toggleParent,"div","countriesList");
			
			//disable all the categories anchors
			for(var x=0;x<categoriesItems.length;x++){
				var a=categoriesItems[x].getElementsByTagName("a")[0];
				
				a.isValid=function(){
					
					var div=this.parentNode.parentNode.parentNode;
					var li=this.parentNode;
					
					var isFiltered=div.className.indexOf("filtered")>-1;
					var isHighlighted=li.className.indexOf("highlight")>-1;
					
					if(isFiltered){
						return isHighlighted;
					}
					
					return true

				}
			}								
						
			if(countriesList.length < 1){continue;}
			categories[i].countriesList = countriesList[0];
			categories[i].catItems = [];
			for(var k=0,m=categoriesItems.length;k<m;k++){
				if( Barclays.Common.getPEClassInfo(categoriesItems[k],"PE_hasCategories").indexOf(catID) != -1){
					categories[i].catItems.push(categoriesItems[k]);
				}
			}
			categories[i].onclick = function(){				
				
				if(this.parentNode.className.indexOf("filterOn") == -1){//filter is not on
					this.parentNode.className += " filterOn";
					filtersCount++;
					for(var n=0,p=this.catItems.length;n<p;n++){
						this.catItems[n].className += " highlight";//use multiple instances of this as a tally
					}
				}else{
					this.parentNode.className = this.parentNode.className.replace("filterOn","");
					filtersCount--;
					for(var n=0,p=this.catItems.length;n<p;n++){
						this.catItems[n].className = this.catItems[n].className.replace("highlight","");
					}
				}
				
				if(filtersCount > 0){
					if(this.countriesList.className.indexOf("filtered") == -1){
						this.countriesList.className += " filtered";
					}
				}else{
					this.countriesList.className = this.countriesList.className.replace("filtered","");
				}
				
				return false;
			};
		}
	},
	//Embolden the labels of selected checkboxes
	emboldenLabels : function(){
		function emboldenLabel(e){
			var findTarget = function(){
				var yourTarget;
				if(e.target){
					yourTarget = e.target;
				}
				else if (e.srcElement){
					yourTarget = e.srcElement;
				}
				if (yourTarget.nodeType == 3){ // defeat Safari bug
					yourTarget = yourTarget.parentNode;
				}
				findTarget = function(){
					return(yourTarget);
				};
				return findTarget();
			};
			var targ = findTarget();
			var theTarget;
			var targParent;
			if (targ.tagName === "INPUT"){
				theTarget = targ;
			}
			else if(targ.tagName === "LABEL"){
				targetFor = targ.getAttribute('for') || targ.getAttribute('htmlFor');
				theTarget = document.getElementById("targetFor");
			}
			if(theTarget){
				targParent = theTarget.parentNode;
				if (theTarget.checked){
					targParent.className+= " embolden";
				}
				else{
					targParent.className = targParent.className.replace("embolden","");	
				}
			}
		}
		var inputsList = Barclays.Common.getElementsByClassName(document,"*","PE_emboldenLabels");		
		for(var i=0;inputsList[i];i++){
			Barclays.Common.addEvent(inputsList[i],'click',emboldenLabel);
		}
	},
	
	/* replace the <hr /> element with a div */	
	HRhandler:function(){		
			var HRs=document.getElementsByTagName("hr");
			for(var x=0;x<HRs.length;x++){								
				var div=create("div","hr");
				HRs[x].parentNode.insertBefore(div,HRs[x]);
				div.appendChild(HRs[x]);
			}
		},	
	
	// fix spacing on the secondary navigation
	secondaryNavigation : {
		
		init : function(){
			
			var linkText, theWords, numberOfWords, longestWord, theWord, theWordWidths, combineNumber, stringLength, position, tempWidth, tempMaxWidth, previousMaxWidth, linkHeight;
			var theLinkLength = 0;
			var listLength = 0;
			var longestWordWidth = 0;
			var theIndex = 0;
			var excess = 0;
			var toTrim = 0;
			var numberOfSqueezableItems = 0;
			var numberOfSqueezableItemsTest = 0;
			var desiredWidth = 0;
			var widestWordWidth = 0;
			var maxHeight = 0;
			var squeezable = [];
			var theWordWidths = [];
			var wordWidths = [];
			
			// get the navigation
			var theNavigation = Barclays.Common.getElementsByClassName(document,"ul","secondaryNav")[0];
			
			if(!theNavigation){
				
				return false;
				
			}
			
			// get each link in the navigation
			var theNavigationLinks = theNavigation.getElementsByTagName('a');
			var numberOfLinks = theNavigationLinks.length;
			
			for(var i=0;i<numberOfLinks;i++){
				
				// split the link string into an array of its words
				linkText = theNavigationLinks[i].innerHTML;
				theWords = linkText.split(' ');
				numberOfWords = theWords.length;
				
				// if only one word in the link, set this as the width
				if(numberOfWords === 1){
					
					// find the width of the word
					longestWordWidth = Barclays.Custom.secondaryNavigation.stringLength(linkText);
					
					// set the width of the link
					theNavigationLinks[i].style.width = longestWordWidth + 'px';
					
				}
				else{
					
					// store the widths of these words
					for(var j=0;j<numberOfWords;j++){
						
						theWordWidths[j] = Barclays.Custom.secondaryNavigation.stringLength(theWords[j]);
																									 
					}
					
					// if there are two words in the link, the width of the link is the width of the longest word
					if(numberOfWords === 2){
						
						longestWordWidth = Barclays.Custom.secondaryNavigation.setLinkWidthToWidest(theNavigationLinks[i], theWordWidths[0], theWordWidths[1]);
					
					}
					else{
					
						// function to split the link into two strings at the first space after the middle of the link
						function findBestSplit(theIndexParam){
							
							var betterIndex = linkText.indexOf(' ', theIndexParam);
							
							if((betterIndex === -1) || (betterIndex === theLinkLength)){
								
								theIndex = theIndexParam;
								
							}
							else{
								
								betterIndex = (betterIndex + 1);
								
								if(betterIndex < (theLinkLength/2)){
								
									findBestSplit(betterIndex);
								
								}
								else{
									
									theIndex = betterIndex - 1;
									
								}
								
							}
						
						}
						
						theLinkLength = linkText.length;
						theIndex = 0;
					
						// split the string at the first space after the middle
						findBestSplit(theIndex);
						firstString = linkText.substr(0, theIndex + 1);
						secondString = linkText.substr(theIndex, theLinkLength);
						firstStringWidth = Barclays.Custom.secondaryNavigation.stringLength(firstString);
						secondStringWidth = Barclays.Custom.secondaryNavigation.stringLength(secondString);
						
						// set the width of the link and store this
						longestWordWidth = Barclays.Custom.secondaryNavigation.setLinkWidthToWidest(theNavigationLinks[i], firstStringWidth, secondStringWidth);
						
						// store this link as i can reduce its width if necessary
						squeezable.push(i);
						
					}
					
				}
				
				listLength = longestWordWidth + listLength + parseInt(Barclays.Common.getStyle(theNavigationLinks[i],"padding-left"),10) + parseInt(Barclays.Common.getStyle(theNavigationLinks[i],"padding-right"),10);
				
			}
			
			// if the list is now too wide, squash items that have more than 2 words
			if(listLength > 730){
					
				numberOfSqueezableItems = squeezable.length;
				excess = listLength - 730;
				toTrim = Math.ceil(excess / numberOfSqueezableItems);
				numberOfSqueezableItemsTest = numberOfSqueezableItems;
					
				for(var i=0;i<numberOfSqueezableItems;i++){
						
					// what's the new max width for this element?
					desiredWidth = parseInt(Barclays.Common.getStyle(theNavigationLinks[squeezable[i]],"width"),10) - toTrim;
						
					// find the width of every word in the link
					linkText = theNavigationLinks[squeezable[i]].innerHTML;
					theWords = linkText.split(' ');
					numberOfWords = theWords.length;
						
					for(var j=0;j<numberOfWords;j++){
							
						wordWidths[j] = Barclays.Custom.secondaryNavigation.stringLength(theWords[j]);
							
					}
						
					// find the widest word in the link
					widestWordWidth = 0;
					
					for(var j=0;j<numberOfWords;j++){
							
						if(wordWidths[j] > widestWordWidth){
								
							widestWordWidth = wordWidths[j];
							
						}
						
					}
					
					// if the widest word in this link is larger than the desired width, set as the width of this link and reduce the desired width of the other squeezable links
					if(widestWordWidth > desiredWidth){
							
						// set width
						theNavigationLinks[squeezable[i]].style.width = widestWordWidth + 'px';
							
						// update trim amount
						excess = excess + (widestWordWidth - desiredWidth);
						numberOfSqueezableItemsTest = numberOfSqueezableItems - 1;
						toTrim = Math.ceil(excess / numberOfSqueezableItemsTest);
							
					}
					else{
							
						// combine the words into strings and find the widest string beneath the desired width, this will be the new width
						combineNumber = 2;
						stringLength = position = tempWidth = tempMaxWidth = 0;
						previousMaxWidth = widestWordWidth;
							
						while(combineNumber < numberOfWords){
								
							while(position < numberOfWords -1){
							
								tempWidth = 0;
								
								for (var j=0;j<combineNumber;j++){
									
									tempWidth = tempWidth + wordWidths[j + position];
									
								}
								
								position = position + combineNumber;
								
								if ((tempWidth > tempMaxWidth)){
									
									tempMaxWidth = tempWidth;
									
								}
								
							}
							
							if(tempMaxWidth > desiredWidth){
									
								// set the width at the max width for the previous combo of words
								theNavigationLinks[squeezable[i]].style.width = previousMaxWidth + 'px';
								
								// update trim amount
								excess = excess + (widestWordWidth - desiredWidth);
								numberOfSqueezableItemsTest = numberOfSqueezableItems - 1;
								toTrim = Math.ceil(excess / numberOfSqueezableItemsTest);
								
								break;
								
							}
							else{
								
								previousMaxWidth = tempMaxWidth;
								
								// up the combo number and rerun
								combineNumber = combineNumber + 1;
								position = 0;
									
							}
								
						}
						
					}
					
				}
				
			}
			
			// ensure all link items are now the same height
			maxHeight = 0;
            
			//find tallest link item
            for(var i=0;i<numberOfLinks;i++){
				
				linkHeight = theNavigationLinks[i].clientHeight;
                linkHeight = linkHeight - parseInt(Barclays.Common.getStyle(theNavigationLinks[i],"padding-top"),10) - parseInt(Barclays.Common.getStyle(theNavigationLinks[i],"padding-bottom"),10);
				
				if(maxHeight < linkHeight){
                    	
					maxHeight = Math.ceil(linkHeight);
                	
				}
            	
			}
            
			//set all in row to tallest
            for(var i=0;i<numberOfLinks;i++){
                	
            	if(typeof document.body.style.maxHeight != "undefined"){
                
					theNavigationLinks[i].style.minHeight = maxHeight+1+"px";
                	
				}
                else{
                
					theNavigationLinks[i].style.height = maxHeight+1+"px";
                	
				}
            	
			}
			
		},
		
		// find the pixel width of a string
		stringLength : function(theString){
			
			var stringWidth;
			
			var spanElement = document.createElement('span');
			
			spanElement.className = 'calculateStringLengthContainer';
			spanElement.style.whiteSpace = 'nowrap';
			spanElement.innerHTML = theString;
			document.body.appendChild(spanElement);
			stringWidth = spanElement.offsetWidth;
			document.body.removeChild(spanElement);
			
			return stringWidth;
			
		},
		
		setLinkWidthToWidest : function(theLink, widthOne, widthTwo){
							
			var widest;
							
			if(widthOne < widthTwo){
																																			  				widest = widthTwo;
						
			}
			else{
					
				widest = widthOne;
																							 
			}
			
			theLink.style.width = widest + 'px';
							
			return widest;
							
		}
		
	},
	
	/*
TOGGLEAREA makes 1+ areas shown or hidden when a link is clicked, depending on whether the div is currently visible or not
REQUIRED:
	<a> with class PE_toggleArea(id)
	<div> with class PE_toggle(id)

TOGGLEVIEW allows specified content to be displayed and hidden depending on one of a group of links being clicked or an input being checked.
the visible content area's link has its link removed so it is just a span, when it is no longer the visible area a link is written around it dynamically
REQUIRED:
	toggling content grouped inside a container element with class PE_toggleView
	FOR LINKS
		toggling text in span element with class PE_toggler(uid)
	FOR INPUTS
		input given class PE_toggler(uid)
	FOR HIDING ALL TOGGLE AREAS
		input or span with class PE_toggler()
	block element wrapping the content to be toggled with class PE_toggle(uid)
	the toggler for the starting toggle view has no link around it, all the other togglers do
*/
	toggleVisibility : function(){
		toggleArea();
		toggleViews();
		function toggleArea(){
			var toggleLinks = Barclays.Common.fuzzyClassName("a","PE_toggleArea");
			for(var i=0,j=toggleLinks.length;i<j;i++){
				var toggleAreaID = Barclays.Common.getPEClassInfo(toggleLinks[i],"PE_toggleArea");
				toggleLinks[i].toggleAreas = Barclays.Common.fuzzyClassName("div","PE_toggle("+toggleAreaID+")");
				toggleLinks[i].allToggleLinks = Barclays.Common.fuzzyClassName("a","PE_toggleArea("+toggleAreaID+")");
				for(var k=0,m=toggleLinks[i].toggleAreas.length;k<m;k++){
					if(toggleLinks[i].toggleAreas[k].className.indexOf("defaultToOpen") != -1){continue;}
					hide(toggleLinks[i].toggleAreas[k]);
				}
				toggleLinks[i].onclick = toggleOnOff;
			}
			return false;
		}
		function toggleViews(){
			var toggleViewContainer = Barclays.Common.getElementsByClassName(document,"*","PE_toggleView");
			for(var i=0,j=toggleViewContainer.length;i<j;i++){
				toggleViewContainer[i].style.display = "block";
				toggleViewContainer[i].style.visibility = "visible";
				var toggles = Barclays.Common.fuzzyClassNameBlock(toggleViewContainer[i],"span","PE_toggler");
				var toggleInputs = Barclays.Common.fuzzyClassNameBlock(toggleViewContainer[i],"input","PE_toggler");
				for(var t=0,u=toggleInputs.length;t<u;t++){
					toggles.push(toggleInputs[t]);
				}
				for(var k=0,m=toggles.length;k<m;k++){
					toggles[k].allToggles = toggles;
					var toggleViewMarker = Barclays.Common.getPEClassInfo(toggles[k],"PE_toggler");
					var toggleViews = Barclays.Common.fuzzyClassName("*","PE_toggle("+toggleViewMarker+")");
					if(toggleViewMarker == ""){
						toggleViews = null;
					}
					else if(toggleViews.length == 0){
						continue;
					}
					else{
						toggles[k].toggleView = toggleViews[0];
					}
					toggles[k].parentNode.toggle = toggles[k];
					//for spans
					if(toggles[k].parentNode.tagName.toLowerCase() == "a"){
						toggles[k].parentNode.onclick = toggleBetweenViews;
						if(toggles[k].className.indexOf("PE_togglerInit") != -1){
							toggleBetweenViews.call(toggles[k].parentNode);
							continue; //no need to hide things twice
						}
						else{
							hide(toggles[k].toggleView);
						}
					}
					//for inputs
					else if(toggles[k].tagName.toLowerCase() == "input"){
						toggles[k].toggle = toggles[k]
						if(toggles[k].checked == false){
							hide(toggles[k].toggleView);
						}
						toggles[k].onclick = toggleBetweenViews;
					}
				}
			}
			return;
		}
		function toggleOnOff(){
			for(var i=0,j=this.toggleAreas.length;i<j;i++){
				if(this.toggleAreas[i].className.indexOf("hide") != -1){
					show(this.toggleAreas[i]);
					for(var k=0,m=this.allToggleLinks.length;k<m;k++){
						this.allToggleLinks[k].className += " toggleShow";
					}
					this.innerHTML = this.innerHTML.replace(/\bOpen\b/gi,"Close");
				}
				else{
					hide(this.toggleAreas[i]);
					for(var k=0,m=this.allToggleLinks.length;k<m;k++){
						this.allToggleLinks[k].className = this.allToggleLinks[k].className.replace("toggleShow","");
					}
					this.innerHTML = this.innerHTML.replace(/\bClose\b/gi,"Open");
				}
			}
			return false;
		}
		function toggleBetweenViews(){
			if(this.tagName.toLowerCase() == "input"){
				if(this.checked){
					show(this.toggle.toggleView);
				}
				else{
					hide(this.toggle.toggleView);
				}
			}
			else{
				show(this.toggle.toggleView);
				for(var n=0,p=this.toggle.allToggles.length;n<p;n++){
					if(this.toggle.allToggles[n] == this.toggle){
						this.parentNode.className += " activeToggle";
						if(this.tagName.toLowerCase() == "a"){
							this.parentNode.insertBefore(this.toggle,this);
							this.parentNode.removeChild(this);
						}
						continue;
					}
					else{
						this.toggle.allToggles[n].parentNode.className = this.toggle.allToggles[n].parentNode.className.replace("activeToggle","");
						hide(this.toggle.allToggles[n].toggleView);
						if(this.toggle.allToggles[n].parentNode.tagName.toLowerCase() != "a" && this.tagName.toLowerCase() != "input" ){
							var toggleLink = document.createElement("a");
							toggleLink.href="#";
										this.toggle.allToggles[n].parentNode.insertBefore(toggleLink,this.toggle.allToggles[n]);
							toggleLink.appendChild(this.toggle.allToggles[n]);
							toggleLink.toggle = this.toggle.allToggles[n];
							toggleLink.onclick = toggleBetweenViews;
						}
					}
				}
				if(this.tagName.toLowerCase() == "a"){return false;}
			}
		}
		function hide(el){
			if(!el){return false;}
			if(el.className.indexOf("hide") == -1){
				el.className += " hide";
			}
			return true;
		}
		function show(el){
			if(!el){return false;}
			 el.className = el.className.replace("hide","");
			 return true;
		}
	},

	/*

	SCROLLER
		sets up a carousel-type scrolling list
		Scroll object is an object of arguments for one particular scroller, you can have 1+ on a page
		Scroll.list is the ul of items to scroll through
		Scroll.currentPage is the page that you are 'on', starts from 0
		Scroll.pageOffsets is the left offset of each page start
		Scroll.pagination is the pagination ul
		Scroll.pageCount is the total number of pages, like length, so will be maximum currentPage+1
	REQUIRED:
		div with class PE_scroller which contains an unordered list of items to be scrolled through
		
	*/
	Scroller : {
		//animation for moving
		scrollMove : function(){
			function scrollIterate(){
				try{
					if(currentMargin != finalMargin){
						if((increment < 0 && currentMargin - increment > finalMargin) || (increment > 0 && currentMargin - increment < finalMargin)){
							trigger.Scroll.list.style.marginLeft = finalMargin + "px";
						}
						else{
							trigger.Scroll.list.style.marginLeft = currentMargin - increment + "px";
						}
					}
					else{
						clearInterval(scrollInterval);
					}
					currentMargin = parseInt(Barclays.Common.getStyle(trigger.Scroll.list,"margin-left"),10);
				}catch(e){
					
				}
			}
			var trigger = this;
			var finalMargin = trigger.Scroll.pageOffsets[trigger.pageNumber] * -1;
			var increment = 25;
			var currentMargin = parseInt(Barclays.Common.getStyle(trigger.Scroll.list,"margin-left"),10);
			if(currentMargin != finalMargin){
				if(currentMargin < finalMargin){
					increment = 0 - increment;
				}
				scrollIterate();
				var scrollInterval = setInterval(scrollIterate,10);
				this.Scroll.currentPage = this.pageNumber;
				Barclays.Custom.Scroller.updateFeatures(this);
			}
		},
		//goes straight to a page, no anim
		jumpToPage : function(){
			var trigger = this;
			var finalMargin = trigger.Scroll.pageOffsets[trigger.pageNumber] * -1;
			trigger.Scroll.list.style.marginLeft = finalMargin + "px";
			this.Scroll.currentPage = this.pageNumber;
			Barclays.Custom.Scroller.updateFeatures(this);
		},
		//updates features like pagination or page information if they exist
		updateFeatures : function(scroller){
			if(scroller.Scroll.pagination){
				Barclays.Custom.Scroller.updatePaginationList.call(scroller);
			}
			if(scroller.Scroll.pageIndicator){
				scroller.Scroll.pageIndicator.innerHTML = "";
				scroller.Scroll.pageIndicator.appendChild(Barclays.Custom.Scroller.updatePageMessage.call(scroller));
			}
		},
		//updates indication on list of pages
		updatePaginationList : function(){
			var paginationUL = this.Scroll.pagination;
			var pageLinks = paginationUL.getElementsByTagName("a");
			for(var i=0,j=this.Scroll.pageCount;i<j;i++){
				var img = pageLinks[i].getElementsByTagName("img")[0];		
				if(this.Scroll.currentPage === i){
					if(img.src.indexOf("_current") == -1){
						img.src = img.src.replace(/scroller_page_(off|over)/,"scroller_page_current");
					}
				}
				else{
					img.src = img.src.replace("_current","_off");
				}
			}
		},
		updatePageMessage : function(){
			return document.createTextNode("Page " + (this.Scroll.currentPage+1) + " of " + this.Scroll.pageCount);
		},
		//for safari, won't calculate offsets properly until load
		stylings : function(){
			var scrollerHeight = this.Scroll.list.getElementsByTagName("li")[0].offsetHeight;
			this.Scroll.prevLink.style.marginTop = Math.floor(scrollerHeight / 2 - this.Scroll.prevLink.offsetHeight / 2) + "px";
			this.Scroll.nextLink.style.marginTop = Math.floor(scrollerHeight / 2 - this.Scroll.nextLink.offsetHeight / 2) + "px";

			var scrollerLinks = Barclays.Common.fuzzyClassNameBlock(this.Scroll.list,"a","PE_lightboxOpen");
			for(var p=0,q=scrollerLinks.length;p<q;p++){
				var linkImg = scrollerLinks[p].getElementsByTagName("img");
				if(linkImg.length < 1){continue;}
				var linkImg = linkImg[0];
				scrollerLinks[p].span.style.top = linkImg.offsetTop + "px";
				scrollerLinks[p].span.style.left = linkImg.offsetLeft + "px";
			}
		},
		init : function(){
			function createPagination(){
				var that = {};
				that.Scroll = Scroll;
				//pagination links
				var pagination = document.createElement("ul");
					pagination.className = "scrollerPagination";
				for(var k=0;k<pageCount;k++){
					var pageNavImg = document.createElement("img");
						pageNavImg.src = "/assets/img/buttons/scroller_page_off.gif";
						pageNavImg.alt = "Page " + (k+1);
						pageNavImg.className = "PE_swap";
					var pageNavLink = document.createElement("a");
						pageNavLink.href="#";
						pageNavLink.Scroll = Scroll;
						pageNavLink.scroller = scroller[i];
						pageNavLink.pageNumber = k;
						pageNavLink.onblur = pageNavLink.onmouseout = function(){
							if(this.Scroll.currentPage === this.pageNumber){
								Barclays.Custom.Scroller.updatePaginationList.call(this);
							}
						};
						pageNavLink.onclick = function(){
							Barclays.Custom.Scroller.scrollMove.call(this);
							Barclays.Custom.Scroller.updatePaginationList.call(this);
							//reset the interval
							clearInterval(this.scroller.autoLoop);
							return false;
						};
						pageNavLink.appendChild(pageNavImg);
					var pageNavItem = document.createElement("li");
						pageNavItem.appendChild(pageNavLink);
					pagination.appendChild(pageNavItem);
				}
				scroller[i].parentNode.appendChild(pagination);//?
				Scroll.pagination = pagination;
				//next/prev links
				var prevLink = document.createElement("a");
					prevLink.className = "scrollernav";
					prevLink.href="#";
				var prevImg = document.createElement("img");
					prevImg.src = "/assets/img/buttons/scroller_previous_off.gif";
					prevImg.alt = "Previous page";
					prevImg.className = "PE_swap";
					prevLink.appendChild(prevImg);
					prevLink.Scroll = Scroll;
					prevLink.scroller = scroller[i];
					prevLink.onclick = function(){
						if(this.Scroll.currentPage === 0){return false;}
						this.pageNumber = this.Scroll.currentPage - 1;
						Barclays.Custom.Scroller.scrollMove.call(this);
						Barclays.Custom.Scroller.updatePaginationList.call(this);
						//reset the interval
						clearInterval(this.scroller.autoLoop);
						return false;
					};
				var nextLink = document.createElement("a");
					nextLink.href="#";
					nextLink.className = "scrollernav";	
				var nextImg = document.createElement("img");
					nextImg.src = "/assets/img/buttons/scroller_next_off.gif";
					nextImg.alt = "Next page";
					nextImg.className = "PE_swap";
				nextLink.appendChild(nextImg);
				nextLink.Scroll = Scroll;
				nextLink.scroller = scroller[i];
				nextLink.onclick = function(){
					if(this.Scroll.currentPage+1 === this.Scroll.pageCount){return false;}
					this.pageNumber = this.Scroll.currentPage + 1;
					Barclays.Custom.Scroller.scrollMove.call(this);
					Barclays.Custom.Scroller.updatePaginationList.call(this);
					//reset the interval
					clearInterval(this.scroller.autoLoop);
					return false;
				};
				var scrollerHeight = scroller[i].offsetHeight;
					scroller[i].parentNode.insertBefore(prevLink,scroller[i]);
				scroller[i].parentNode.insertBefore(nextLink,pagination);
				//now that they are in the page, vertically centre them
				prevLink.style.marginTop = Math.floor(scrollerHeight / 2 - prevLink.offsetHeight / 2) + "px";
				nextLink.style.marginTop = Math.floor(scrollerHeight / 2 - nextLink.offsetHeight / 2) + "px";
				
				

				Barclays.Custom.Scroller.updatePaginationList.call(that);//init
				//end pagination links
				that.Scroll.prevLink = prevLink;
				that.Scroll.nextLink = nextLink;
				Barclays.Common.addLoadEvent(function(){Barclays.Custom.Scroller.stylings.call(that)});
				//hide pagination if only 1 page
				if(pageCount === 1){
					prevLink.style.visibility = nextLink.style.visibility = pagination.style.visibility = "hidden";
				}
			}
			/*end create pagination*/
			/*autoscroll function - NB only one on the page*/
			function autoScroll(scroller){
				var scroller = scroller;
				scroller.autoLoop = setInterval(function(){
					if(scroller.Scroll.pageCount === scroller.pageNumber+1){
						scroller.pageNumber = 0;
						Barclays.Custom.Scroller.jumpToPage.call(scroller);
					}
					else{
						scroller.pageNumber = scroller.Scroll.currentPage + 1;
						Barclays.Custom.Scroller.scrollMove.call(scroller);
						scroller.Scroll.currentPage = scroller.pageNumber;
					}
				},10000);
				
				var stopLink = document.createElement("a");
						stopLink.href="#";
						stopLink.scroller = scroller;
						stopLink.className = "scrollerstop";
						stopLink.appendChild(document.createTextNode("Stop"));
						stopLink.onclick = function(){
							clearInterval(this.scroller.autoLoop);
							return false;
						};
					/*var nextLink = document.createElement("a");
						nextLink.href = "#";
						nextLink.scroller = scroller;
						nextLink.appendChild(document.createTextNode("Next"));
						nextLink.onclick = function(){
							clearInterval(this.scroller.autoLoop);
							if(this.scroller.Scroll.pageCount === this.scroller.pageNumber+1){
								this.scroller.pageNumber = 0;
							}
							else{
								this.scroller.pageNumber = this.scroller.pageNumber + 1;
							}
							Barclays.Custom.Scroller.jumpToPage.call(this.scroller);
							return false;
						};*/
					scroller.appendChild(stopLink);
					//scroller.appendChild(nextLink);
			}
			function setupLightboxLinks(scrollerLinks){
				//set up overlay on lightbox links
				for(var p=0,q=scrollerLinks.length;p<q;p++){
					var linkImg = scrollerLinks[p].getElementsByTagName("img");
					if(linkImg.length < 1){continue;}
					var linkImg = linkImg[0];
					var spanCTA = document.createElement("span");
					scrollerLinks[p].appendChild(spanCTA);
						spanCTA.style.width = linkImg.offsetWidth +"px";
						spanCTA.style.height = linkImg.offsetHeight +"px";
						spanCTA.style.top = linkImg.offsetTop + "px";
						spanCTA.style.left = linkImg.offsetLeft + "px";
						spanCTA.style.visibility = "hidden";
					scrollerLinks[p].span = spanCTA;
					scrollerLinks[p].onfocus = scrollerLinks[p].onmouseover = function(){
						this.span.style.visibility = "visible";
						return false;
					};
					scrollerLinks[p].onmousedown = function(){
						return false;//prevents onblur triggering which stops lightbox opening
					};
					scrollerLinks[p].onblur = scrollerLinks[p].onmouseout = function(){
						this.span.style.visibility = "hidden";
						return false;
					};
				}
			}
			/*scroller set-up*/
			var scroller = Barclays.Common.fuzzyClassName("div","PE_scroller");	
			for(var i=0,j=scroller.length;i<j;i++){
				var Scroll = {};
				scroller[i].Scroll = Scroll;
				var scrollingList = scroller[i].getElementsByTagName("ul");
				if(scrollingList.length < 1){return;}
				scrollingList = scrollingList[0];
				Scroll.list = scrollingList;
				var scrollingListItems = scrollingList.childNodes;
				if(scrollingListItems.length < 1){return;}
	
				var scrollerFrame = document.createElement("div");
					scrollerFrame.className = "scrollerFrame";
				scrollerFrame.appendChild(scrollingList);
				scroller[i].appendChild(scrollerFrame);
								
				var frameWidth = 0;
				var ascrollingListItems = [];
				for(var m=0,n=scrollingListItems.length;m<n;m++){
					if(scrollingListItems[m].nodeType === 3){
						continue;
					}
					ascrollingListItems.push(scrollingListItems[m]);
					frameWidth += scrollingListItems[m].offsetWidth;
				}

				scrollerFrame.style.width = frameWidth+"px";
				var scrollWidth = scroller[i].offsetWidth;
				var itemWidth = Math.ceil(frameWidth / ascrollingListItems.length);
				var itemsPerRow = Math.floor(scrollWidth / itemWidth);
				if(itemsPerRow < 1){itemsPerRow = 1;}
				var pageCount = Math.ceil(ascrollingListItems.length / itemsPerRow);
				var pageOffsets = [];
				Scroll.currentPage = 0;
				Scroll.pageOffsets = pageOffsets;
				Scroll.pageCount = pageCount;
				for(var k=0;k<pageCount;k++){
					var gotoItem = k * itemsPerRow;
					pageOffsets[k] = ascrollingListItems[gotoItem].offsetLeft;
				}

				//set up special features
				setupLightboxLinks(Barclays.Common.fuzzyClassNameBlock(scrollingList,"a","PE_lightboxOpen"));
				var inpagePagination = Barclays.Common.getElementsByClassName(scroller[i],"ul","scrollerPagination");
				var scrollerType = Barclays.Common.getPEClassInfo(scroller[i],"PE_scroller");
				//auto-scroller
				if(scrollerType.indexOf("auto") != -1){
					autoScroll(scroller[i]);
				}
				//end auto-scroller
				//page x of y
				if(scrollerType.indexOf("pageIndicator") != -1){
					var pageIndicator = document.createElement("p");
					pageIndicator.appendChild(Barclays.Custom.Scroller.updatePageMessage.call(scroller[i]));
					scroller[i].appendChild(pageIndicator);
					scroller[i].Scroll.pageIndicator = pageIndicator;
				}
				//pagination
				if(scrollerType.indexOf("paged") != -1){
					createPagination();
				}
			}
		}
	},
	
	filterSearch: function(){
		var showFilter = Barclays.Common.getElementsByClassName(document, "*", "showFilter");
		var filterContainer = Barclays.Common.getElementsByClassName(document, "*", "searchFilter");
		var theInnerHTML;
		filter = showFilter[0];
		list = filterContainer[0];
		if(filterContainer.length > 0){
			theInnerHTML = showFilter[0].innerHTML;
			
			var oLink = document.createElement('a');
			oLink.id =  'showFilterLink';
			oLink.href = '#'; // Make the link focusable for keyboard users
			oLink.appendChild(document.createTextNode(theInnerHTML));
			oLink.onclick = function() {
				if(list.className.indexOf('hide') != -1){
					list.className = "searchFilter show";
					document.getElementById('showFilterLink').innerHTML = 'Close filter';
					filter.className = "showFilter showFilterShown";	
					return false;
				}
				else{
					list.className = "searchFilter hide";					
					document.getElementById('showFilterLink').innerHTML = theInnerHTML;
					filter.className = "showFilter";	
					return false;
				}
			}
			showFilter[0].innerHTML = "";
			showFilter[0].appendChild(oLink);
			if(list.className.indexOf("defaultToOpen") != -1){
				list.className += "searchFilter show";
				oLink.innerHTML = 'Close filter';
				filter.className = "showFilter showFilterShown";
			}
			else{
				list.className += "searchFilter hide";
			}
		}
		return;
	},
	//update DB: changed handling for text areas
	clearFields: function(){
		var inp = [];
		var inps = document.getElementsByTagName('input');
		var textAreas = Barclays.Common.getElementsByClassName(document, "textarea", "textAreaWithOverlayLabel");
		for (var x=0; inps[x]; x++){
			inp.push(inps[x]);
		}	
		
		var labels = document.getElementsByTagName('label');
		var overlayLabel = function(theInput) {
				theInput.theLabel.className = "overlayLabel";
				var theParent = theInput.parentNode;
				theParent.style.position = "relative";
				theInput.theLabel.style.position = "absolute"; 
				var topPosition = theInput.offsetTop + 6;
				var leftPosition = theInput.offsetLeft + 4;
				theInput.theLabel.style.left = leftPosition + "px"; 
				theInput.theLabel.style.top = topPosition + "px"; 
			}
		for(var i=0,j=textAreas.length;i<j;i++){
			var startValue = textAreas[i].value;
			textAreas[i].onfocus = function(){
				if(this.value === startValue){
					this.value = "";
				}
			};
			textAreas[i].onblur = function(){
				if(this.value === ""){
					this.value = startValue;
				}
			};
		}
		for(var i = 0; i < inp.length; i++) {
			if(inp[i].type == 'text') {
				var temp = inp[i].className;
				if(!temp){continue;}
				inp[i].value = inp[i].className.split('//')[1];
				inp[i].onfocus = function() {
					if(this.value == this.className.split('//')[1]) {
						this.value = '';
					}
					else {
						return false;
					}
				};
				inp[i].onblur = function() {
					if(this.value == '') {
						this.value = this.className.split('//')[1];
					} else {
						return false;
					}
				};
			}
			else if((inp[i].type == 'password') || (inp[i].className.indexOf("textAreaWithOverlayLabel")!==-1)) {
				var labels = Barclays.Common.getByAttribute(document,"label","for",inp[i].id);
				if(labels == ""){
					labels = Barclays.Common.getByAttribute(document,"label","htmlFor",inp[i].id);
				}
				//Create a property for each input that refers to its label - I have settled on doing it this way because getByAttribute struddles with htmlFor
				inp[i].theLabel = function(that){
					for (var i = 0; labels[i]; i++) {
						if (labels[i].className === "hideJS") {
							return labels[i];
						}
					}
				}(inp[i]);				
				//We only want to overlay the label if it is a hidden label
				if(inp[i].theLabel){
					if (inp[i].theLabel.className === "hideJS"){
						//Initially move labels over the inputs				
						overlayLabel(inp[i]);
						//Remove the labels when the field is focussed				
						inp[i].onfocus = function(){
							this.theLabel.className = "hideJS";
							this.theLabel.style.left = "-9999px";
						}
						//Return the labels when the field is blurred
						inp[i].onblur = function(){
							//Only return the label if nothing has been entered in the field
							if ((this.value.length === 0) || (this.value.length === null)) {
								var sensPar = this;
								overlayLabel(sensPar);
								return false;
							}
						}
					}
				}
			}
		}
		return;
	},
	
	initCarousel:function(){		
	
		Barclays.Common.addEvent(window,"load",function(){						
																Barclays.Common.carousels=new Array()
																var imagesSet=Barclays.Common.getElementsByClassName(document,"div","PE_carousel");
																for (var x=0;x<imagesSet.length;x++){
																	Barclays.Common.carousels[x]=new carousel();
																	Barclays.Common.carousels[x].initCarousel(imagesSet[x]);
																}																																										
														})	
	

		
	},

	//puts a zero-width breaking space after each letter to allow email addresses to wrap.
	//the character does not work in IE6 or below because you need IE7+ for zero-width breaking spaces, so IE6 is prevented from doing this.  however, IE6's broken box model means that it will however expand the width of the containing box to accommodate the long text.
	splitEmails : function(){
	
		if(Barclays.Common.islteIE6()){
			return;
		}
		var emails = Barclays.Common.getElementsByClassName(document,"a","PE_emails");
		for(var i=0,j=emails.length;i<j;i++){
			var emailAdr = emails[i].innerHTML;
			var emailUser = emailAdr.split("@");
			emails[i].innerHTML = emailUser[0].replace(/(\w)/gi,"$1\u200B") + "@"+ emailUser[1];
		}
	},
	
	 positionElements: function() {
		if (!document.getElementsByTagName) {return false;}
		if (!document.getElementById) {return false;}
		var screenwidth = 0;
		if (document.getElementById("relatedContent")) {
			var thediv = document.getElementById("relatedContent");
			this.switchClass(thediv);
			Barclays.Custom.switchClass(thediv);
		};
		var maindiv = document.getElementById("pageWrapper");
		this.setWidth(maindiv);
		var screenWidth = Barclays.Common.getViewPortWidth();
		window.onresize = function() {
			if(screenWidth != Barclays.Common.getViewPortWidth()){
				Barclays.Custom.setWidth(maindiv);
			}
			screenWidth = Barclays.Common.getViewPortWidth();
		};
	},
	
	setWidth: function(element){
		if(!element){return false;}
		screenwidth = Barclays.Common.getViewPortWidth();
		if (screenwidth > 994) {
			if (element.className !== "fullWidth"){
				Barclays.Common.changeClass(element,"fullWidth");
				Barclays.Custom.floatingListHeights();
			}
		}
		else {
			if (element.className !== "reducedWidth"){
				Barclays.Common.changeClass(element,"reducedWidth");
				Barclays.Custom.floatingListHeights();
			}
		}
	},
	
	switchClass: function(element) {
		screenwidth = Barclays.Common.getViewPortWidth();
		if (screenwidth > 994) {
			Barclays.Common.changeClass(element,"hasWidth");
		}
		else {
			Barclays.Common.changeClass(element,"hasNoWidth");
		}
	},
	
		externalLinks: function (){
		var anchorTags = document.getElementsByTagName('a');
		var len = anchorTags.length;
		
		for(var i=0; i<len; i++){
			if("external" == anchorTags[i].getAttribute('rel')){
				anchorTags[i].setAttribute('target','_blank');
			}
		}
	},
	//Accordion Functions
		//Accordion Functions
	setupExpandableAreas: function() {
		//find all expandable areas on page
		var closure='<div class="closureButton"><a href="#" class="closureSwitch">Close</a></div>';
		expandableAreas=Barclays.Common.getElementsByClassName(document, "div","expandableContent");
		for (var i=0;i<expandableAreas.length;i++) {
			expandableAreas[i].id = "expandableArea_"+i;
			var oEl=document.getElementById(expandableAreas[i].id);
			//collapse all expandable areas - unless wrapper has class defaultToOpen
			if (oEl.className.indexOf("defaultToOpen")==-1)	{
				if (oEl.className.indexOf("expandableContentCollapsed")==-1) {
					oEl.className+= " expandableContentCollapsed";
				}
			}
			//if shortdesc has radio/checkbox form elements and answer also has form elements then open on 
			//if shortdesc has radio form element, close the other related radio groups' answer
			if(Barclays.Common.getElementsByClassName(expandableAreas[i],"div","question").length>0){
				var thisquestion=Barclays.Common.getElementsByClassName(expandableAreas[i],"div","question")[0];
				// add closure if class withClosure is given
				if (thisquestion.className.indexOf("withClosure")!=-1){
					if(expandableAreas[i].className.indexOf("defaultToOpen")===-1){
						closure='<div class="closureButton"><a href="#" class="closureSwitch">Open</a></div>';
					}
					else{
						closure='<div class="closureButton"><a href="#" class="closureSwitch">Close</a></div>';
					}
							
					thisquestion.innerHTML=closure+thisquestion.innerHTML;
				}
				var questionInputs=thisquestion.getElementsByTagName("input");
				var answerInputs=Barclays.Common.getElementsByClassName(expandableAreas[i],"div","answer")[0].getElementsByTagName("input");
				for(var j=0;j<questionInputs.length;j++){
					if(answerInputs.length===0){
						continue;
					}
					if(questionInputs[j].type=="radio" || questionInputs[j].type=="checkbox"){
						questionInputs[j].iteration=i;
						function collapseUnselected(e){
							if(!e){var e=window.event;
						}
						var elem=(e.currentTarget)?e.currentTarget:e.srcElement;
						if(elem.nodeType==3){
							elem=elem.parentNode;
						}
						var expandableArea=document.getElementById("expandableArea_"+elem.iteration);
						if(expandableArea.className.indexOf("expandableContentCollapsed")!=-1){
							expandableArea.className=expandableArea.className.replace("expandableContentCollapsed","");
						}
						elem.checked=true;
						if(elem.type=="radio"){
							var radiogroup=elem.name;
							//go through all expandable areas, get their question input, if it matches radiogroup then add the collapse			
							for(var k=0;k<expandableAreas.length;k++){
								var sdInput=Barclays.Common.getElementsByClassName(expandableAreas[k],"div","question")[0].getElementsByTagName("input")[0];
								if(sdInput.name==radiogroup){
									if (sdInput.checked){
										if(expandableAreas[k].className.indexOf("expandableContentCollapsed")==-1){
											expandableAreas[k].className+=" expandableContentCollapsed";
										}
									}
								}
							}
						}
					}
					questionInputs[j].addEventListener ? questionInputs[j].addEventListener("click",collapseUnselected,false) : questionInputs[j].attachEvent("onclick",collapseUnselected);
				}
			}
		}
		//remove link from anchor, assisgn id
		if (Barclays.Common.getElementsByClassName(expandableAreas[i], 'div', 'question')[0]) {
			if (expandableAreaAnchor = Barclays.Common.getElementsByClassName(expandableAreas[i], 'div', 'question')[0].getElementsByTagName("a")[0])	{
				expandableAreaAnchor.id = "expandableAreaAnchor_"+i;
				expandableAreaAnchor.href="#";
				expandableAreaAnchor.onclick = function () {
					elementId = this.id.split("_").reverse()[0]; //puts the element id number at the front of array
					Barclays.Custom.openOrCloseExpandableContent("expandableArea_" + elementId );
					return false;
				}
			}
		}
		if (Barclays.Common.getElementsByClassName(expandableAreas[i], 'div', 'question')[0]) {
			if (exp2Parent=Barclays.Common.getElementsByClassName(expandableAreas[i], 'div', 'closureButton')[0]){
				if (expandableAreaAnchor2 = Barclays.Common.getElementsByClassName(expandableAreas[i], 'div', 'question')[0].getElementsByTagName("a")[1]){
					expandableAreaAnchor2 = Barclays.Common.getElementsByClassName(expandableAreas[i], 'div', 'question')[0].getElementsByTagName("a")[1];
					expandableAreaAnchor2.id = "expandableAreaAnchor2_"+i;
					expandableAreaAnchor2.href="#";
					expandableAreaAnchor2.onclick = function () {
						elementId = this.id.split("_").reverse()[0]; //puts the element id number at the front of array
						Barclays.Custom.openOrCloseExpandableContent("expandableArea_" + elementId );
							return false;
						}
					}
				}
			}
		}
	},
	//simpler expandable areas, not accordion as above
	openOrCloseExpandableContent: function(id) {
		var oEl=document.getElementById(id);
		var toSwitch = Barclays.Common.getElementsByClassName(oEl, "a", "closureSwitch")[0];
		if (oEl.className.indexOf("expandableContent")!=-1)	{
			oEl.className=oEl.className.replace(" defaultToOpen","");
			if (oEl.className.indexOf("expandableContentCollapsed")==-1) 	{
				oEl.className += " expandableContentCollapsed";
				if (toSwitch){
					toSwitch.innerHTML = "Open";
				}
			}
			else {
				oEl.className=oEl.className.replace(" expandableContentCollapsed","");
				if (toSwitch){
					toSwitch.innerHTML = "Close";
				}
			}
		}
	},
	glow: function(){
		function showGlow(){
				var parentWrap = Barclays.Common.getParentByClassName(this,"wrap");
				if(parentWrap.className.indexOf("active") == -1){parentWrap.className += " active";}
			}
		function hideGlow(){
			var parentWrap = Barclays.Common.getParentByClassName(this,"wrap");
			parentWrap.className = parentWrap.className.replace("active","");
		}
		var glowDivs = Barclays.Common.getElementsByClassName(document,"div","glowInput");
		for(var i=0,j=glowDivs.length;i<j;i++){
			var inputs = glowDivs[i].getElementsByTagName("input");
			var selects = glowDivs[i].getElementsByTagName("select");
			for(var k=0,m=inputs.length;k<m;k++){
				Barclays.Common.addEvent(inputs[k],'focus',showGlow);
				Barclays.Common.addEvent(inputs[k],"blur",hideGlow);
			}
			for(var k=0,m=selects.length;k<m;k++){
				Barclays.Common.addEvent(selects[k],'focus',showGlow);
				Barclays.Common.addEvent(selects[k],"blur",hideGlow);
			}
		}
	},
	/*contextualHelp finds all paragraphs with the class name toolTip, gets their specified shared parent wrapper element to find out which field to attach them to, and shows them onfocus and hides them onblur by putting a class on the wrapping element
	REQUIRED:
	<p> with class 'toolTip' nested inside a div with the class 'wrap', which also contains the relevant input or select
*/
	contextualHelp : function(){
		var helpPs = Barclays.Common.getElementsByClassName(document,"p","toolTip");
		for(var i=0;i<helpPs.length;i++){
			//get parent div before progressively enhancing with more divs
			var parentWrap = Barclays.Common.getParentByClassName(helpPs[i],"wrap");
			if(!parentWrap){return false;}
			//get all contained fields
			var inputs = parentWrap.getElementsByTagName("input");
			var selects = parentWrap.getElementsByTagName("select");
			var textareas = parentWrap.getElementsByTagName("textarea");
			function showHelp(){
				var parentWrap = Barclays.Common.getParentByClassName(this,"wrap");
				if(parentWrap.className.indexOf("active") == -1){parentWrap.className += " active";}
			}
			function hideHelp(){
				var parentWrap = Barclays.Common.getParentByClassName(this,"wrap");
				parentWrap.className = parentWrap.className.replace("active","");
			}
			function hideAllHelp(){
				var helpPs = Barclays.Common.getElementsByClassName(document,"p","toolTip");
				for(var a=0;a<helpPs.length;a++){
					hideHelp.call(helpPs[a]);
				}
				showHelp.call(this.helpP);
			}
			//add event handlers for fields
			for(var n=0;n<inputs.length;n++){
				inputs[n].helpP = helpPs[i];

				if(/WebKit/i.test(navigator.userAgent)){  //safari doesn't focus/blur radio or checkboxes
						if(inputs[n].type == "radio" || inputs[n].type == "checkbox"){
						Barclays.Common.addEvent(inputs[n],'click',hideAllHelp);
					}
					else{
						Barclays.Common.addEvent(inputs[n],'focus',hideAllHelp);
					}
				}
				else{
					Barclays.Common.addEvent(inputs[n],'focus',showHelp);
				}
				Barclays.Common.addEvent(inputs[n],'blur',hideHelp);
			}
			for(var s=0;s<selects.length;s++){
				selects[s].helpP = helpPs[i];
				if(/WebKit/i.test(navigator.userAgent)){  //safari doesn't focus/blur radio or checkboxes
					Barclays.Common.addEvent(selects[s],'focus',hideAllHelp);
				}
				else{
					Barclays.Common.addEvent(selects[s],'focus',showHelp);
				}
				Barclays.Common.addEvent(selects[s],'blur',hideHelp);
			}
			for(var t=0;t<textareas.length;t++){
				textareas[t].helpP = helpPs[i];
				if(/WebKit/i.test(navigator.userAgent)){  //safari doesn't focus/blur radio or checkboxes
					Barclays.Common.addEvent(textareas[t],'focus',hideAllHelp);
				}
				else{
					Barclays.Common.addEvent(textareas[t],'focus',showHelp);
				}
				Barclays.Common.addEvent(textareas[t],'blur',hideHelp);
			}
		}
	},
	//turns a reset input into an image with a link that 
	resetImgs : function(){
		var resetButtons = Barclays.Common.fuzzyClassName("input","PE_resetImg");
		for(var i=0,j=resetButtons.length;i<j;i++){
			var imgSrc = Barclays.Common.getPEClassInfo(resetButtons[i],"PE_resetImg");
			if(!imgSrc){continue;}
			var parentForm = Barclays.Common.getParentByTagName(resetButtons[i],"form");
			if(!parentForm){continue;}
			var resetLink = document.createElement("a");
				resetLink.href = "#";
				resetLink.form = parentForm;
			var resetImg = document.createElement("img");
				resetImg.src = imgSrc;
				resetImg.alt = resetButtons[i].value;
			resetLink.appendChild(resetImg);
			resetButtons[i].parentNode.insertBefore(resetLink,resetButtons[i]);
			resetButtons[i].parentNode.removeChild(resetButtons[i]);
				resetLink.onclick = function(){
					for(k=0,m=this.form.elements.length;k<m;k++){
						if(this.form.elements[k].type=="hidden") continue;
						if(this.form.elements[k].type === "checkbox" || this.form.elements[k].type === "radio"){
							this.form.elements[k].checked = false;
						}
						if(this.form.elements[k].type === "select-one" || this.form.elements[k].type === "select-multiple"){
							this.form.elements[k].selectedIndex = 0;
						}
						else{
							this.form.elements[k].value = "";
						}
					}
					return false;
				}
		}
	},
	
	/*
	Takes a group of radio buttons and turns them into a list of 'links'.  They aren't actually links, they are labels adapted to look and behave like links that are attached to radio buttons.

	The list is hidden unless you click on the selected visible option
	
	
	REQUIRED:
		fieldset with class PE_radioAsLayerList
		fieldset contains radio buttons, their text is extracted from their labels.
		
		
	*/
	layerList : function(){
		var fieldsets = Barclays.Common.getElementsByClassName(document,"fieldset","PE_radioAsLayerList");
		if(fieldsets.length < 1){return;}
		for(var i=0,j=fieldsets.length;i<j;i++){
			function getRadioText(radios){
				for(var k=0,m=radios.length;k<m;k++){
					if(radios[k].checked === true){
						var label = Barclays.Common.getByAttribute(document,"label","for",radios[k].id);
						if(label == ""){
							label = Barclays.Common.getByAttribute(document,"label","htmlFor",radios[k].id);
						}
						return label[0].innerHTML;
					}
				}
				return "Select";
			}
			var radios = fieldsets[i].getElementsByTagName("input");
			if(radios.length < 1){return;}
			var radioList = fieldsets[i].getElementsByTagName("ul");
			if(radioList.length < 1){return;}
			radioList[0].className += " hide";
			var layerLink = document.createElement("a");
				layerLink.href="#";
				layerLink.innerHTML = getRadioText(radios);//update to get selected radio button text
				layerLink.radioList = radioList[0];
				layerLink.onclick = function(){
					if(this.radioList.className.indexOf("hide") != -1){
						this.radioList.className = this.radioList.className.replace("hide","");
					}
					else{
						this.radioList.className += " hide";
					}
					return false;
				}
			fieldsets[i].insertBefore(layerLink,fieldsets[i].firstChild);
			for(var k=0,m=radios.length;k<m;k++){
				radios[k].radioList = radioList[0];
				radios[k].layerLink = layerLink;
				radios[k].onclick = function(){
					var radioGroup = Barclays.Common.getByAttribute(document,"input","name",this.name);
					this.layerLink.innerHTML = getRadioText(radioGroup);
					this.radioList.className += " hide";
				}
			}
		}
	},
	/*
	POLLING
		a form where users can pick an option and submit their vote.  the results are pulled back via 	AJAX.
	REQUIRED
		main container div with class 'PE_vote'
		submitting input with class 'PE_vote'
		radio inputs
		hidden input with id 'PollAjaxUrl' that has the url to make the AJAX call to as its value
		results table with 'pollTable' as its class
	*/
	Poll : {
		init : function(){
			//set up any existing poll tables
			Barclays.Custom.Poll.barChart();
			//set up vote submit buttons
			var voteModules = Barclays.Common.getElementsByClassName(document,"div","PE_vote");
			
			for(var i=0,j=voteModules.length;i<j;i++){
				var voteBtn = Barclays.Common.getElementsByClassName(voteModules[i],"input","PE_vote");
				if(voteBtn.length < 1){return;}
				var voteInputs = voteModules[i].getElementsByTagName("input");
				voteBtn[0].options = [];
				for(var k=0,m=voteInputs.length;k<m;k++){
					if(voteInputs[k].type === "radio"){
						voteBtn[0].options.push(voteInputs[k]);							
					}
				}
				voteBtn[0].parentDiv = voteModules[i];
				voteBtn[0].onclick = Barclays.Custom.Poll.vote;
			}
		},
		vote : function(){
			function showError(){
				var errorText = "Sorry, there was a problem adding your vote.  Please try again.";
				var errorP = Barclays.Common.getElementsByClassName(parentDiv,"p","error");
				if(errorP.length < 1){
					var error = document.createElement("p");
					error.className = "error";
					error.appendChild(document.createTextNode(errorText));
					parentDiv.insertBefore(error,voteform);
				}
				voteform.style.display = "block";
			}
			var chosenOption;
			for(var i=0,j=this.options.length;i<j;i++){
				if(this.options[i].checked === true){
					chosenOption = this.options[i].value;
				}
			}
			var parentDiv = this.parentDiv;
			var voteform = parentDiv.getElementsByTagName("form")[0];
			var urlField = document.getElementById("PollAjaxUrl");
			if(!chosenOption){return false;}
			var avoidCache = Math.floor(Math.random()*1000);
			var xhr = Barclays.Common.AJAX.createXMLHttpRequest();
			var url = urlField.value + "&poll=" + chosenOption + "&nocache=" + avoidCache;
			xhr.open("GET",url,true);
			xhr.onreadystatechange = function(){
				var processingImg = Barclays.Common.AJAX.processingIndicator();
					voteform.style.display = "none";
					parentDiv.appendChild(processingImg);
				if (xhr.readyState != 4)  { return false; }
					processingImg.parentNode.removeChild(processingImg);
				if (xhr.status != 200)  { 
					showError();
					return false;
				}
				var xhrResponse = xhr.responseText;
				parentDiv.innerHTML = xhrResponse;
				Barclays.Custom.Poll.barChart();
			};
			xhr.send(null);
			return false;
			
			
		},
		// display results and calculate bar chart widths //TODO
		barChart : function(){
			var pollResultsTable = Barclays.Common.getElementsByClassName(document,"table","pollTable");
			if(pollResultsTable.length < 1){return;}
			var pollResults = [];
			var pollValue;
			var purePollValue;
			var howFarLeft;
			var marginRight;
			
			//Get each poll
			for (var i=0; pollResultsTable[i]; i++){
				pollResults = pollResultsTable[i].getElementsByTagName("td");
				for (var j=0; pollResults[j]; j++){
					//Get a string containing the value of the result
					var barSpace = pollResults[j].offsetWidth;
					pollValue = pollResults[j].innerHTML;
					//Get rid of the percent
					purePollValue = pollValue.replace(/[^0-9]/g, '');
					howFarLeft = parseInt(purePollValue*(((barSpace - 46)/100)));
					//I don't want a gap to the left of the text if there is no image
					if (howFarLeft < 1){
						marginRight = 0;
					}
					else{
						marginRight = "5px";
					}
							
					//Insert an image into the td
					pollResults[j].innerHTML = "<span style='width:" + howFarLeft + "px;margin-right:" + marginRight + "'><img src='/assets/img/backgrounds/poll-bar.gif' alt=''></span>" + pollValue; 
				}
			}
			//Get each poll result
			//Find the largest one and assign it the orange bar
			//Assign the others blue bar
			//Position the bars
		}
	},
	//Generic function takes a list of floated items, determines the highest list item in each row and then sets the other list items in that row to be the same height. Assumes that each list item has the same width
 	//- as used on Site Map
	floatingListHeights : function(){
		var setHeightsInRow = function(elems, itemsPerRow){
        	var rows = Math.ceil(elems.length / itemsPerRow);
        	for(var i=0;i<=rows;i++){
            	var firstInRowIndex = i*itemsPerRow;
            	var maxHeight = 0;
            	//find tallest in row
            	for(var j=firstInRowIndex;j<firstInRowIndex+itemsPerRow;j++){
                	if(j>=elems.length){break;}
                	var elemHeight = elems[j].clientHeight;
                	elemHeight = elemHeight - parseInt(Barclays.Common.getStyle(elems[j],"padding-top"),10) - parseInt(Barclays.Common.getStyle(elems[j],"padding-bottom"),10);
                	if(maxHeight < elemHeight){
                    	maxHeight = Math.ceil(elemHeight);
                	}
            	}
            	//set all in row to tallest
            	for(var j=firstInRowIndex;j<firstInRowIndex+itemsPerRow;j++){
                	if(j>=elems.length){break;}
                	if(typeof document.body.style.maxHeight != "undefined"){
                    	elems[j].style.minHeight = maxHeight+1+"px";
                	}
                	else{
                    	elems[j].style.height = maxHeight+1+"px";
                	}
            	}
        	}
		}
        var viewList = Barclays.Common.getElementsByClassName(document,"ul","floatingList");
       	if(viewList.length < 1){
            return false;
        }
        for(var listsCount = 0; listsCount < viewList.length; listsCount++){
            var viewListChildren = viewList[listsCount].childNodes;
            var viewListItems = [];
            for(var i=0,j=viewListChildren.length;i<j;i++){
                if(viewListChildren[i].nodeName.toLowerCase() == "li"){
                    viewListItems.push(viewListChildren[i]);
                }
            }
            if(viewListItems.length < 1){return false;}
            //get widths and items per row
            var listWidth = viewList[listsCount].clientWidth;
			if(listWidth === 0){return;}
            var listItemWidth = viewListItems[0].clientWidth;
			if(listItemWidth === 0){return;}			
            var itemsPerRow = Math.floor(listWidth / listItemWidth);
            setHeightsInRow(viewListItems,itemsPerRow);  
        }

	},
	


	sifr : function(){
		if(typeof sIFR !== "function"){return;}
		//sifr is inaccessible in IE7 and Gecko 1.9+
		//there's no way to detect zoom mode, so we are left with checking the useragent, generally not preferred practice
		var browser = navigator.userAgent;
		var geckoReg = /rv:(\d+[\.\d]+)\) Gecko/;
		var geckoVersion = geckoReg.exec(browser);
		if(geckoVersion){
			if(parseFloat(geckoVersion[1],10) >= 1.9){
				//remove class added in to html element by sifr regardless of whether it is called or not
				var html = document.getElementsByTagName("html")[0];
				html.className = html.className.replace("sIFR-hasFlash","");
				return false;
			}
		}
		if(Barclays.Common.getIEMajorVersion() >= 7){
			var html = document.getElementsByTagName("html")[0];
			html.className = html.className.replace("sIFR-hasFlash","");
			return false;
		}
		sIFR();
		
		//media centre hub
		sIFR.replaceElement("#mediacentre #hubIntro h2.brandfont", "/assets/flash/expertsans_bold.swf", named({sColor:'#ffffff',sHoverColor:'#ffffff',sWmode:'transparent',nPaddingTop:0, nPaddingBottom:0, sFlashVars:"underline=true", bdoGhost:true}));
		//list of resource types
		sIFR.replaceElement("#content .resourceLibrary h2.brandfont", "/assets/flash/expertsans_bold.swf", named({sColor:'#003366',sHoverColor:'#003366',sWmode:'transparent', nPaddingTop:7, nPaddingBottom:0, sFlashVars:"underline=true", bdoGhost:true}));
		//crosspromotion
		/*sIFR.replaceElement("#content .crossPromotion h2.brandfont", "/assets/flash/expertsans_bold.swf", named({sColor:'#00A4E8',sHoverColor:'#00A4E8',sWmode:'transparent', nPaddingTop:0, nPaddingBottom:0, sFlashVars:"underline=true", bdoGhost:true}));*/
		//grey headings
		sIFR.replaceElement("#content .heroArea h1.brandfont", "/assets/flash/expertsans.swf", named({sColor:'#666666',sHoverColor:'#666666',sWmode:'transparent', nPaddingTop:4, nPaddingBottom:0, sFlashVars:"underline=true", bdoGhost:true}));
		
	},
	
	
	//imgSwap swaps out images on rollover
	imgSwap : function(){
		var swapImgs=getElementsByClassName(document,"*","PE_swap");
        for(var i=0;i<swapImgs.length;i++){
        	swapImgs[i].onmouseover=function(){
				if(Barclays.Common.islteIE6()){ //handle png filters in IE6
					if(this.style.filter && this.style.filter.indexOf(".png") != -1){
						this.oldFilter = this.style.filter;
						this.style.filter = this.style.filter.replace(/(_off|_current|\-active)?\.png/,"_over.png");
						return;
					}
				}
				this.oldSrc = this.src;
            	var newImg=this.src.replace(/(_off|_current|\-active)?\.(gif|jpg|png)/,"_over.$2");
                this.src=newImg;
            };
	        swapImgs[i].onmouseout=function(){
				if(this.oldFilter){
					this.style.filter= this.oldFilter;
					return;
				}
                this.src=this.oldSrc;
			};
           	swapImgs[i].onfocus=swapImgs[i].onmouseover;
            swapImgs[i].onblur=swapImgs[i].onmouseout;
        }
	},
	//bgImgSwap swaps out images on rollover
	bgImgSwap : function(){
		var swapImgs=getElementsByClassName(document,"*","PE_swapBG");
        for(var i=0;i<swapImgs.length;i++){
			swapImg[i].oldSrc = Barclays.Common.getStyle(swapImg[i],"background-image");
        	swapImgs[i].onmouseover=function(){
            	var newImg=this.style.backgroundImage.replace(/(_off)?\./,"_over.");
                this.style.backgroundImage=newImg;
            };
	        swapImgs[i].onmouseout=function(){
            	var newImg=this.oldSrc;
                this.style.backgroundImage=newImg;
			};
           	swapImgs[i].onfocus=swapImgs[i].onmouseover;
            swapImgs[i].onblur=swapImgs[i].onmouseout;
        }
	},
	
	// replace radio buttons in a form with panels
	radioButtonsReplaceForm : {
		
		init : function(){
			
			var theFieldsets, numberOfFieldsets;
			
			// get the forms
			var theForms = Barclays.Common.getElementsByClassName(document,"form","PE_RadioBtnReplace");
			var numberOfForms = theForms.length;
			
			for(var i=0;i<numberOfForms;i++){
				
				// get the fieldsets
				theFieldsets = theForms[i].getElementsByTagName('fieldset');
				numberOfFieldsets = theFieldsets.length;
				
				for(var j=0;j<numberOfFieldsets;j++){
					
					Barclays.Custom.radioButtonsReplaceForm.thinOrWide(theFieldsets[j]);
					Barclays.Custom.radioButtonsReplaceForm.userFeedback(theFieldsets[j]);
					
				}
				
				Barclays.Custom.radioButtonsReplaceForm.resetForm(theForms[i]);
				
			}
			
		},
		
		// if there are four more items in the fieldset, I want them in two columns with each item the same height
		thinOrWide : function(theFieldset){
			
			var elemHeight, theLabel, theLabels, numberOfLabels, theList;
			
			var theListItems = theFieldset.getElementsByTagName('li');
			var numberOfListItems = theListItems.length;
			var maxHeight = 0;
			var noMinHeight = false;
        
			if (typeof document.body.style.maxHeight == "undefined") {
            
				noMinHeight = true;
        
			}
			
			if(numberOfListItems > 3){
				
				// put a class on the ul to make the list items thin
				theList = theListItems[0].parentNode;
				theList.className = "thinListItems";
				
				// get the max height of the labels
				theLabels = theFieldset.getElementsByTagName('label');
				
				for(var i=0;i<numberOfListItems;i++){
					
					elemHeight = theLabels[i].clientHeight;
                	elemHeight = elemHeight - parseInt(Barclays.Common.getStyle(theLabels[i],"padding-top"),10) - parseInt(Barclays.Common.getStyle(theLabels[i],"padding-bottom"),10);
                
					if(maxHeight < elemHeight){
                    
						maxHeight = Math.ceil(elemHeight);
                
					}
					
				}
				
				setMinOrMaxHeight = function(element){
					
					if (typeof document.body.style.maxHeight == "undefined") {
						
						element.style.height = maxHeight+1+"px";
						
						setMinOrMaxHeight = function(element){
							
							element.style.height = maxHeight+1+"px";
							
						}
						
					}
					else{
						
						element.style.minHeight = maxHeight+1+"px";
						
						setMinOrMaxHeight = function(element){
						
							element.style.minHeight = maxHeight+1+"px";
							
						}
						
					}
					
				}
				
				for(var i=0;i<numberOfListItems;i++){
					
					setMinOrMaxHeight(theLabels[i]);
					
					// put a clear on every second item to handle text size change
					if(i % 2 == 0){
						
						theLabels[i].parentNode.style.clear = 'left';
						
					}
					
				}
				
			}
			
		},
		
		// highlight the panels on hover and on checked
		userFeedback : function(theFieldset){
			
			var theLabels = theFieldset.getElementsByTagName('label');
			var numberOfLabels = theLabels.length;
			var theInputs = theFieldset.getElementsByTagName('input'); 
			
			// function to handle on keyup on input
			inputKeyUp = function(j){
				
				return function(){
					
					this.style.right = '20px';
					
					// if we are selecting a new input by using the arrows, we have to clear the others
					if(this.checked){
						
						// remove highlight from all other labels
						for (var i=0;i<numberOfLabels;i++){
															
							theLabels[i].className = '';
						
						}
						
						theLabels[j].className = 'labelSelected';
					
					}
				
					if (theLabels[j].className == ''){
						
						theLabels[j].className = 'labelHovered';
						
					}
					
					// handle keyboard users
					theInputs[j].onblur = function(){
						
						this.style.right = '9999px';
					
						// remove highlight from all other labels
						for (var i=0;i<numberOfLabels;i++){
						
							if (theInputs[i].checked == false){
															
								theLabels[i].className = '';
								
							}
						
						}
						
					}
										
					theInputs[j].onclick = function(){		
					
						// remove selected from all other labels
						for (var i=0;i<numberOfLabels;i++){
						
							if (theLabels[i].className == 'labelSelected'){
															
								theLabels[i].className = '';
								
							}
						
						}
																	
						theLabels[j].className = 'labelSelected';
					
					}
				
				}
				
			}
			
			for (var i=0;i<numberOfLabels;i++){
				
				theLabels[i].onmouseover = function(){
					
					if (this.className == ''){
						
						this.className = 'labelHovered';
						
					}
			
				}
				
				theLabels[i].onmouseout = function(){
					
					removeClass(this, 'labelHovered');
			
				}
				
				theLabels[i].onclick = function(){
					
					// remove any backgrounds from other elements
					for (var j=0;j<numberOfLabels;j++){
						
						theLabels[j].className = '';
						
					}
					
					// add the blue background as the element is now selected
					this.className = 'labelSelected';
			
				}				
				
				theInputs[i].onkeyup = inputKeyUp(i);
				
			}
			
		},
		
		// remove all styling from labels when form is cleared
		resetForm : function(theForm){
			
			var cancelButton = theForm.getElementsByTagName('a')[0];
			
			cancelButton.onclick = function(){
				
				var theLabels = theForm.getElementsByTagName('label');
				var theInputs = theForm.getElementsByTagName('input');
				var numberOfLabels = theLabels.length;
				
				for (var i=0;i<numberOfLabels;i++){
					
					theLabels[i].className = '';
					
					if(theInputs[i]){
					
						if(theInputs[i].type === "radio"){
					
							theInputs[i].checked = false;
							
						}
						
					}
					
				}
				
				return false;
				
			}			
			
		}
		
	},
	
	// post the results of a form and return info AJAX-stylee in a lightbox
	AJAXLightbox : {
		
		lightboxContent : null,
		
		init : function(){
			
			var theSubmits, numberOfSubmits;
			
			// get the forms
			var theForms = Barclays.Common.getElementsByClassName(document,"form","PE_RadioBtnReplace");
			var numberOfForms = theForms.length;
			
			// function for onsubmit of the input
			formSubmit = function(j){
				
				return function(){
					
					// delete existing AJAX lightbox as I need to replace it with a new one with new content
					var existingAJAXLightbox = document.getElementById('AJAXLightbox');
					
					if(existingAJAXLightbox){
						
						existingAJAXLightbox.parentNode.removeChild(existingAJAXLightbox);

					}
				
					// create the lightbox content
					Barclays.Custom.AJAXLightbox.createContent(theForms[j]);
					
					return false;
					
				}
				
			}
			
			for(var h=0;h<numberOfForms;h++){
			
				// get the special submit buttons
				theSubmits = Barclays.Common.getElementsByClassName(theForms[h],"input","PE_AJAXLightbox");
				numberOfSubmits = theSubmits.length;
		
				for (var i=0;i<numberOfSubmits;i++){
			
					theSubmits[i].onclick = formSubmit(i);
				
				}
			
			}
			
		},
		
		createContent : function(theForm){
			
			var lightboxContainer = document.getElementsByTagName('body')[0];
			
			// get the hidden input that contains the URL we want
			var urlField = Barclays.Common.getElementsByClassName(theForm,"input","hiddenAJAXURL")[0];	
			var url = urlField.value;
			
			var values = [];
			var allSelected = true; 
			var avoidCache = Math.floor(Math.random()*1000);
			
			// get the fieldsets
			var theFieldsets = theForm.getElementsByTagName('fieldset');
			var numberOfFieldsets = theFieldsets.length;

			// put in a loading image
			var processingImg = document.createElement('img');
			
			var viewPortCenter = Math.round(Barclays.Common.getViewPortHeight() / 2);
			var scrolledTop = Barclays.Common.getScrollTop();
			var userViewCenter = parseInt(viewPortCenter) + parseInt(scrolledTop);
			var lightboxCenter = processingImg.offsetHeight / 2;
			
			processingImg.src="/assets/img/icons/ajax-loader-dark.gif";
			processingImg.alt="Please wait, processing your request.";
			processingImg.id="ajax_wait";
			Barclays.Lightbox.tintBg();
			lightboxContainer.insertBefore(processingImg, lightboxContainer.firstChild);
			processingImg.className = 'AJAXProcessingImg';
			processingImg.style.top = userViewCenter - lightboxCenter + "px";
				
			for(var i=0;i<numberOfFieldsets;i++){
				
				// find which option is checked
				var theRadioButtons = theFieldsets[i].getElementsByTagName('input');
				var numberOfRadioButtons = theRadioButtons.length;
				
				for(var j=0;j<numberOfRadioButtons;j++){
					
					if(theRadioButtons[j].checked){
						
						values.push(i + '=' + theRadioButtons[j].value);
						
					}
					
				}
				
				// if none of the radio buttons are checked don't bother checking the next fieldset
				if(values.length === 0){
					
					i = numberOfFieldsets;
					
				}
				
			}
			
			// create the div to go in the lightbox and populate it with content
			var theLightboxContent = document.createElement('div');
			
			theLightboxContent.className = 'PE_lightBox lightBox'
			theLightboxContent.id = 'AJAXLightbox';
			
			// if the user has checked an option for every field, return their content through AJAX
			if (values.length === numberOfFieldsets){	
				
				var xhr = Barclays.Common.AJAX.createXMLHttpRequest();
				
				// create a query string with the values of the checked items
				values.push('nocache=' + avoidCache);
				url = url += (url.indexOf("?") > -1 ? '&' : '?') + values.join('&');
			
				xhr.open("GET",url,true);
			
				xhr.onreadystatechange = function(){
				
					if (xhr.readyState != 4)  { 
				
						return false; 
					
					}
				
					if (xhr.status != 200)  { 
				
						theLightboxContent.innerHTML = '<div class="heading"><h2>Sorry!</h2></div><div class="content"><p class="feature">We have been unable to process your request, please try again.</p></div>';
							
						// put the content into the page
						Barclays.Custom.AJAXLightbox.insertContent(lightboxContainer, theLightboxContent, processingImg);
				
					}
				
					if(xhr.readyState == 4){
				
						theLightboxContent.innerHTML = xhr.responseText;
							
						// put the content into the page
						Barclays.Custom.AJAXLightbox.insertContent(lightboxContainer, theLightboxContent, processingImg);	
				
					}
										
				};
				
				xhr.send(null);
				
			}
			// if the user hasn't answered every question, display a generic error in the lightbox
			else{
				
				//theLightboxContent.innerHTML = '<div class="heading"><h2>Oooops!</h2></div><div class="content"><p class="feature">Please select an option from every section.</p></div>';
				var elError = document.getElementById('error');
				theLightboxContent.innerHTML = elError.innerHTML;
							
				// put the content into the page
				Barclays.Custom.AJAXLightbox.insertContent(lightboxContainer, theLightboxContent, processingImg);
				
			}
			
			return false;
			
		},
		
		// put lightbox content into the page
		insertContent : function(theContainer, theContent, theSpinner){
		
			theContainer.insertBefore(theContent,theContainer.firstChild);
			
			// equalize list heights
			Barclays.Custom.floatingListHeights();
			
			Barclays.Custom.AJAXLightbox.showBox(theContent);
			
			// remove loading image
			theSpinner.parentNode.removeChild(theSpinner);
			
		},
			
		
		showBox : function(lightbox){	
		
			Barclays.Lightbox.addBoxStyles(lightbox);
			Barclays.Lightbox.addBoxClose(lightbox);
			Barclays.Lightbox.showLightbox(lightbox);
			
		}
		
	}		
	
}; 

			


	
/*LIGHTBOX
	a lightbox is a box of content that sits above the main area, which is usually faded out
	setting up the tint bg element at init phase works around a obscure IE bug
	if a lightbox contains form elements, the form must be self-contained and within the lightbox content area
	a lightbox can be opened on page load by giving the url the lightbox's ID as a bookmark, e.g.
	url.html#lightbox_mylightbox.  The ID of this lightbox MUST start with 'lightbox_'
	REQUIRED:
		class 'PE_lightBox'  (NB case-sensitive) on the div to become a lightbox, this area must also have an id
		class 'PE_lightboxOpen(id_of_lightbox)' on the anchor that triggers the lightbox if triggered by a link
		class 'PE_lightboxIfInvalid(id_of_lightbox)' on the div with the PE_validate() class if the lightbox is triggered by an invalid field (see validate section comments for further details)
	REQUIRED SUPPORTING EXTERNAL FUNCTIONS:
		fuzzyClassName
		fuzzyClassNameBlock
		getParentByTagName
		getPEClassInfo
		getElementsByClassName
		getViewPortHeight
		getScrollTop
		getFullPageDimensions
		getStyle
*/
Barclays.Lightbox = {
	active : 0,
	height: 0,
	init : function(){
		if(Barclays.Lightbox.hasCSS() == false){return;}
		var lightboxes = Barclays.Common.fuzzyClassName("div","PE_lightBox");
		var lightboxLinks = Barclays.Common.fuzzyClassName("a","PE_lightboxOpen");
		for(var i=0,j=lightboxes.length;i<j;i++){
			var lightboxContainer = document.getElementsByTagName('body')[0];
			lightboxes[i].style.visibility = "visible";  //remove styles from IE foc prevention
			//take out of position in HTML and insert at end of page, necessary for placing above the tinted background in IE

			var lightbox = lightboxes[i].parentNode.removeChild(lightboxes[i]);
			lightboxContainer.appendChild(lightbox);
			Barclays.Lightbox.hideLightbox(lightbox);
			Barclays.Lightbox.addBoxStyles(lightbox);
			Barclays.Lightbox.addBoxClose(lightbox);
		}
		Barclays.Lightbox.active = 0;
		Barclays.Lightbox.setUpTintBg();
		for(var h=0,m=lightboxLinks.length;h<m;h++){
			lightboxLinks[h].className = lightboxLinks[h].className.replace("hide","");
			lightboxLinks[h].title = "This link opens a box in the middle of the screen.";
			lightboxLinks[h].onclick=function(){
				
				if (this.isValid){
					if(!this.isValid()) return false;
				}
				
				var thisLightbox = document.getElementById(Barclays.Common.getPEClassInfo(this,"PE_lightboxOpen"));
				if(typeof thisLightbox == "undefined"){alert("DEV ERROR: no element with ID specified in link's class");return;}

				Barclays.Lightbox.showLightbox(thisLightbox);
				Barclays.Lightbox.tintBg();
				return false;
			};
		}
		//lightbox on page load - this should be the last part of init()
		if(location.hash.indexOf("lightbox_") != -1){
			var thisLightbox = document.getElementById(location.hash.replace("#",""));
			if(!thisLightbox){return;}
			Barclays.Lightbox.showLightbox(thisLightbox);
			Barclays.Lightbox.tintBg();
		}
	},
	/*dynamically creates a lightbox.
	takes either a string or node object for headNode and contentNode and a string for id*/
	create: function(headNode,contentNode,id){
		var lightbox = document.createElement("div");
			lightbox.className = "lightBox PE_lightBox";
			var i=0;
			while(document.getElementById(id)){
				i++;
				var lastUScore = id.lastIndexOf("_");
				var ind = id.substring(lastUScore+1);
				if(parseInt(ind),10){
					id = id.substring(0,lastUScore+1) + i;
				}
				else{
					id = id + "_" + i;
				}
			}
			lightbox.id = id;
		var lightboxHead = document.createElement("div");
			lightboxHead.className = "heading";
			if(typeof(headNode) == "string"){
				headNode = document.createTextNode(headNode);
			}
			lightboxHead.appendChild(headNode);
		lightbox.appendChild(lightboxHead);
		var lightboxContent = document.createElement("div");
			lightboxContent.className = "content";
			if(typeof(contentNode) == "string"){
				contentNode = document.createTextNode(contentNode);
			}
			lightboxContent.appendChild(contentNode);
		lightbox.appendChild(lightboxContent);
		document.body.className += " hasJS";
		Barclays.Lightbox.hideLightbox(lightbox);
		Barclays.Lightbox.addBoxStyles(lightbox);
		Barclays.Lightbox.addBoxClose(lightbox);
		var pageDiv = document.getElementsByTagName("body")[0];
		pageDiv.appendChild(lightbox);
		lightbox.style.visibility = "visible";  //remove styles from IE foc prevention
		return lightbox;
	},
	addBoxStyles : function(elem_lightbox){
		//middle - take all children of lightbox and put them into the boxRight div
		var boxRight = document.createElement("div");
			boxRight.className = "lightbox-right";
		while(elem_lightbox.childNodes.length > 0){
			boxRight.appendChild(elem_lightbox.firstChild);
		}
		var boxMain = document.createElement("div");
			boxMain.className = "lightbox-main";
			boxMain.appendChild(boxRight);
			elem_lightbox.appendChild(boxMain);
		//gif layout
		//top
		var boxTop = document.createElement("div");
			boxTop.className = "lightbox-top";
		var boxTopLeft = document.createElement("div");
			boxTopLeft.className = "lightbox-top-left";
		var boxTopRight = document.createElement("div");
			boxTopRight.className = "lightbox-top-right";
			boxTopLeft.appendChild(boxTopRight);
			boxTopRight.appendChild(boxTop);
			elem_lightbox.insertBefore(boxTopLeft,elem_lightbox.firstChild);
		//base
		var boxBase = document.createElement("div");
			boxBase.className = "lightbox-base";
		var boxBaseLeft = document.createElement("div");
			boxBaseLeft.className = "lightbox-base-left";
		var boxBaseRight = document.createElement("div");
			boxBaseRight.className = "lightbox-base-right";
			boxBaseLeft.appendChild(boxBaseRight);
			boxBaseRight.appendChild(boxBase);
			elem_lightbox.appendChild(boxBaseLeft);
	},
	closeLightbox : function(elem_lightbox){
		Barclays.Lightbox.rehideLightbox(elem_lightbox);
		Barclays.Lightbox.removeTintBg();
		//accessibility aid: refocus on the link or validated field that triggered the lightbox
		var lightboxTrigger = Barclays.Common.fuzzyClassName("a","PE_lightboxOpen(" + elem_lightbox.id + ")")[0];
		if(!lightboxTrigger){
			var lightboxDiv = Barclays.Common.fuzzyClassName("div","PE_lightboxIfInvalid(" + elem_lightbox.id + ")")[0];
			if(lightboxDiv){lightboxTrigger = lightboxDiv.getElementsByTagName("input")[0];}
		}
		if(lightboxTrigger){lightboxTrigger.focus();}
		return false;
	},
	addBoxClose : function(elem_lightbox){
		
		var closeLinkTxt = document.createTextNode("Close");
		
		closeLink = document.createElement("a");
		closeLink.href = "#";
		closeLink.id = "close_" + elem_lightbox.id;
		closeLink.className = "closeBtn clearfix";
		
		closeLink.onclick = function(){
		
			Barclays.Lightbox.closeLightbox(elem_lightbox);
			
			return false;
			
		};
		
		var closeSpan = document.createElement("span");
		
		closeSpan.appendChild(closeLinkTxt);
		closeLink.appendChild(closeSpan);
		
		var lightboxHeading = Barclays.Common.getElementsByClassName(elem_lightbox,"*","heading")[0];
		
		lightboxHeading.insertBefore(closeLink,lightboxHeading.firstChild);
		lightboxHeading.className += " clearfix";
		//accessibility aid: add hidden close at bottom of lightbox
		var closeLinkHidden = document.createElement("a");
			closeLinkHidden.innerHTML = 'End of in page popup. Close using this link to return to main content.';
			closeLinkHidden.href = "#";
			closeLinkHidden.className = "hide";
			closeLinkHidden.onclick = closeLink.onclick;
			closeLinkHidden.onblur = function(){
				
				Barclays.Lightbox.closeLightbox(elem_lightbox);
				
				return false;
			
			}
		elem_lightbox.appendChild(closeLinkHidden);
		elem_lightbox.closeButtons = [closeLink,closeLinkHidden];
		//detect cancel buttons in HTML and use those too
		var cancelLinks = Barclays.Common.fuzzyClassNameBlock(elem_lightbox,"a","PE_closeLightbox");
		for(var i=0;i<cancelLinks.length;i++){
			cancelLinks[i].onclick = closeLink.onclick;
			elem_lightbox.closeButtons.push(cancelLinks[i]);
		}
	},
	setUpTintBg : function(){
		/*@cc_on @*/
		/*@if (@_jscript_version < 5.6)
			return; // impossible in IE5
		/*@end @*/
		var pageDiv = document.getElementsByTagName("body")[0];
		var tint = document.createElement("div");
		tint.className = "tintedBg";
		pageDiv.insertBefore(tint,pageDiv.firstChild);
	},
	tintBg : function(){
		if(Barclays.Lightbox.hasCSS() == false){return;}//in case it is switched off after load
		var tint = Barclays.Common.getElementsByClassName(document,"div","tintedBg")[0];
		if(!tint){return;}
		tint.style.height = "0px";
		var pageDimensions = Barclays.Common.getFullPageDimensions();
		var newWidth = pageDimensions[0];
		var newHeight = pageDimensions[1];
		if(Barclays.Lightbox.height > newHeight){
			tint.style.height = Barclays.Lightbox.height +"px";
		}
		else{
			tint.style.height = newHeight +"px";
		}
		tint.style.width = newWidth +"px";
	},
	removeTintBg : function(){
		if(Barclays.Lightbox.active > 0){return;}
		var tint = Barclays.Common.getElementsByClassName(document,"div","tintedBg")[0];
		if(!tint){return;}
		tint.style.width = "0px";
		tint.style.height = "0px";
	},
	showLightbox : function(elem_lightbox){
		
		if(Barclays.Common.islteIE6()){
			Barclays.Lightbox.hideSelects(elem_lightbox); //hide select boxes due to buggy IE6 handling of them
		}
		elem_lightbox.className = elem_lightbox.className.replace(/ hideLightbox/g,"");
		//set the lightbox in the vertical center of the page, account for relatively-positioned parents
		// if the lightbox is bigger than the viewport, set its top to the top of the viewable screen
		var viewPortCenter = Math.round(Barclays.Common.getViewPortHeight() / 2);
		var scrolledTop = Barclays.Common.getScrollTop();
		var userViewCenter = parseInt(viewPortCenter) + parseInt(scrolledTop);
		var lightboxCenter = elem_lightbox.offsetHeight / 2;
		var lightboxRelativeTop = 0;
		var parent = elem_lightbox.parentNode;
		while(parent){
			if(parent.nodeName=="#document"){break;}
			if(Barclays.Common.getStyle(parent,"position") == "relative"){
				lightboxRelativeTop += parent.offsetTop;
			}
			parent = parent.parentNode;
		}
		if(Barclays.Common.getViewPortHeight() < elem_lightbox.offsetHeight){
			elem_lightbox.style.top = scrolledTop - lightboxRelativeTop + "px";
		}
		else{
			elem_lightbox.style.top = userViewCenter - lightboxCenter - lightboxRelativeTop + "px";
		}
		Barclays.Lightbox.active++;
		Barclays.Lightbox.height = parseInt(elem_lightbox.offsetHeight) + parseInt(elem_lightbox.offsetTop);
		//accessibility aid: send cursor to close button on the lightbox
		var closebtn = document.getElementById("close_" + elem_lightbox.id);
		var hiddenFocusLink = document.getElementById("hiddenFocus_" + elem_lightbox.id);
		if(!hiddenFocusLink){
			var hiddenFocusLink = document.createElement("a");
				hiddenFocusLink.href = "#";
				hiddenFocusLink.onclick = function(){return false;}
				hiddenFocusLink.id = "hiddenFocus_" + elem_lightbox.id;
				hiddenFocusLink.innerHTML = 'In page pop-up layer. Use close links to return to main content.';
				elem_lightbox.insertBefore(hiddenFocusLink,elem_lightbox.firstChild);
		}
		hiddenFocusLink.focus();
		hiddenFocusLink.className = "hide";

		if(scrolledTop != Barclays.Common.getScrollTop()){
			window.scrollTo(0,scrolledTop);
		}
	},
	hideLightbox : function(elem_lightbox){
		if(Barclays.Common.islteIE6()){
			Barclays.Lightbox.showSelects();
		}
		elem_lightbox.className += " hideLightbox";
		var hiddenFocusLink = document.getElementById("hiddenFocus_" + elem_lightbox.id);
		if(hiddenFocusLink){hiddenFocusLink.className = hiddenFocusLink.className.replace("hide","");}
	},
	rehideLightbox : function(elem_lightbox){
		Barclays.Lightbox.hideLightbox(elem_lightbox);
		Barclays.Lightbox.active--;
	},
	//one for set up, one for show/hide
	//hide select boxes due to buggy IE<7 handling of them
	hideSelects : function(){
		var selects = document.getElementsByTagName("select");
		for(var i=0;i<selects.length;i++){
			selects[i].style.visibility = "hidden";
		}
	},
	showSelects : function(){
		var selects = document.getElementsByTagName("select");
		for(var i=0;i<selects.length;i++){
			selects[i].style.visibility = "visible";
		}
	},
	hasCSS : function(){
		var testDiv = document.createElement("div");
		testDiv.className = "hide";
		document.body.appendChild(testDiv);
		if(Barclays.Common.getStyle(testDiv,"position") != "absolute"){
			return false;
		}
		return true;
	}
};
/*
MAPS

get telephone no. as well
*/
Barclays.Maps = {
	init : function(){
		//set up map
		var mapDiv = document.getElementById("gmap");
		if(!mapDiv){return false;}
		if(Barclays.Maps.hasCSS() === false){return;}
		if(!GBrowserIsCompatible()) {return false;}
		Barclays.Maps.gmap = new GMap2(mapDiv);
		
		//get in-page map points
		Barclays.Maps.setIcons();
		Barclays.Maps.setupPointsFromHTML();
		Barclays.Maps.setupPointsFromJSON();
		GEvent.addListener(Barclays.Maps.gmap, 'zoomend', function() { Barclays.Maps.gmap.closeInfoWindow(); });
    	//set up cluster handling

		var clusterOptions = {
			markers : Barclays.Maps.markers,
			clusterMarkerIcon : Barclays.Maps.clusterIcon,
			clusterMarkerTitle : '%count items',
			clusterMarkerClick : function(args){
				zoomLinkAction = function(){
					Barclays.Maps.gmap.setCenter(args.clusterMarker.getLatLng(),
					Barclays.Maps.gmap.getBoundsZoomLevel(args.clusterMarker.clusterGroupBounds));
					delete zoomLinkAction;
					return false;
				};
				var aInfoHTML = [];
				aInfoHTML.push('<div class="gmapInfo clusterInfo">'); 
				aInfoHTML.push('<p class="pseudohead">There are ' + args.clusteredMarkers.length + ' stories at this location, <a href="javascript:void(0)" onclick="zoomLinkAction()">zoom in</a> to see all of them</p>');
				aInfoHTML.push('<ul>');
				var developmentsListItems = (args.clusteredMarkers.length > 20) ? 20 : args.clusteredMarkers.length;
				for(var i=0,j=developmentsListItems;i<j;i++){
					aInfoHTML.push('<li>');
					aInfoHTML.push('<a href="javascript:Barclays.Maps.cluster.triggerClick('+args.clusteredMarkers[i].index+')">'+args.clusteredMarkers[i].heading+'</a>');
					aInfoHTML.push('</li>');
					if(i===19){
						aInfoHTML.push('<li>');
						aInfoHTML.push('...');
						aInfoHTML.push('</li>');
					}
				}
				aInfoHTML.push('</ul>');
				aInfoHTML.push('</div>');
				var infoHTML = aInfoHTML.join('');
				Barclays.Maps.gmap.openInfoWindow(args.clusterMarker.getLatLng(), infoHTML);
				return false;
			}
		};
		Barclays.Maps.cluster = new ClusterMarker(Barclays.Maps.gmap, clusterOptions );
		
		
		//display options for maps, by default controls are on
		var options = Barclays.Common.getPEClassInfo(mapDiv,"PE_gmapOptions");
		
		if(options.indexOf('maxzoom') != -1){
			var zoomReg = /maxZoom=(\d+)/gi;
			var maxZoomLevel = zoomReg.exec(options)[1];
			Barclays.Maps.cluster.fitMapMaxZoom=parseInt(maxZoomLevel,10);
		}

		Barclays.Maps.cluster.fitMapToMarkers();


		if(options.indexOf('maptype=') != -1){
			var maptypeIndex=options.indexOf('maptype=');
			var maptypeEnd= options.indexOf(",",maptypeIndex);
			if(maptypeEnd < maptypeIndex){maptypeEnd = options.length;}
			var maptype = options.substring(maptypeIndex+8,maptypeEnd);
			var maptypeConst;
			switch (maptype) {
				case "G_PHYSICAL_MAP" : 
					maptypeConst = G_PHYSICAL_MAP;
					break;
				case "G_SATELLITE_MAP" :
					maptypeConst = G_SATELLITE_MAP;
					break;
				case "G_HYBRID_MAP" : 
					maptypeConst = G_HYBRID_MAP;
					break;
				default : 
					maptypeConst = G_NORMAL_MAP;
			}
			Barclays.Maps.gmap.setMapType(maptypeConst);
		}
		if(options.indexOf('changemaptype=off') == -1){
			Barclays.Maps.gmap.addControl(new GMapTypeControl());
		}
		if(options.indexOf('mapcontrol=off') == -1){
			Barclays.Maps.gmap.addControl(new GLargeMapControl());
		}
		if(options.indexOf('scale=off') == -1){
			Barclays.Maps.gmap.addControl(new GScaleControl());
		}
		if(options.indexOf('overview=off') == -1){
			Barclays.Maps.gmap.addControl(new GOverviewMapControl());
		}
		Barclays.Maps.Sustainability.init();//do near end
		Barclays.Maps.Regions.setupRegions();//do last
	},
	hasCSS : function(){
		var testDiv = document.createElement("div");
		testDiv.className = "hide";
		document.body.appendChild(testDiv);
		if(Barclays.Common.getStyle(testDiv,"position") != "absolute"){
			return false;
		}
		return true;
	},
	setupPointsFromHTML : function(){
		var mapPoints = Barclays.Common.fuzzyClassName("*","PE_gmapPlace");
		for(var i=0,j=mapPoints.length;i<j;i++){
			var lat = Barclays.Common.getElementsByClassName(mapPoints[i],"span","latitude");
			var lng = Barclays.Common.getElementsByClassName(mapPoints[i],"span","longitude");
			var geoLocation = {'latitude' : lat[0].innerHTML,  'longitude' : lng[0].innerHTML};		
			var fn = Barclays.Common.getElementsByClassName(mapPoints[i],"*","fn");
			//if can't find, go up to vcard and get fn
			if(fn.length < 1){
				var vcard = Barclays.Common.getParentByClassName(mapPoints[i],"vcard");
				fn = Barclays.Common.getElementsByClassName(vcard,"*","fn");
			}
			var street = Barclays.Common.getElementsByClassName(mapPoints[i],"span","street-address");
			var locality = Barclays.Common.getElementsByClassName(mapPoints[i],"span","locality");
			var region = Barclays.Common.getElementsByClassName(mapPoints[i],"span","region");
			var postcode = Barclays.Common.getElementsByClassName(mapPoints[i],"span","postal-code");
			var orgUnit = Barclays.Common.getElementsByClassName(mapPoints[i],"*","organization-unit");
			var tel = Barclays.Common.getElementsByClassName(mapPoints[i],"*","tel");
			if(tel.length > 0){
				if(tel[0].getElementsByTagName("span").length > 0){
					tel = tel[0].getElementsByTagName("span");
				}
			}
			var info = {
				fn : (fn.length > 0) ? fn[0].innerHTML : null,
				street : (street.length > 0) ? street[0].innerHTML : null,
				locality : (locality.length > 0) ? locality[0].innerHTML : null,
				region : (region.length > 0) ? region[0].innerHTML : null,
				postcode : (postcode.length > 0) ? postcode[0].innerHTML : null,
				orgUnit : (orgUnit.length > 0) ? orgUnit[0].innerHTML : null,
				tel : (tel.length > 0) ? tel[0].innerHTML : null				
			}
			var infoHTML = Barclays.Maps.createInfoHTML(info);
			var iconType = "";
			var markerType = Barclays.Common.getElementsByClassName(mapPoints[i],"span","type");
			if(markerType.length > 0){
				iconType = markerType[0].innerHTML;
			}
			info.type = iconType;
			if(geoLocation.latitude == 0 && geoLocation.longitude == 0){
				Barclays.Maps.replaceNullLongLat(info.postcode,infoHTML,iconType);
				return false;
			}
			Barclays.Maps.setMarker(geoLocation,infoHTML,iconType);
		}
	},
	setupPointsFromJSON : function(){
		var locations = Barclays.Locations;
		if(!locations){return;}
		for(var i=0,j=locations.length;i<j;i++){
			createPoint(locations[i]);
		}
		//abstracted in case loop needs further logic applied before making a marker
		function createPoint(location){
			var geoLocation = {'latitude' : location.vcard.geo.latitude, 'longitude' : location.vcard.geo.longitude};
			var info = {
				fn : location.vcard.fn,
				street : location.vcard.adr["street-address"],
				locality : location.vcard.adr.locality,
				region : location.vcard.adr.region,
				postcode : location.vcard.adr["postal-code"],
				country : location.vcard.adr["country-name"],
				url : location.vcard.url,
				imgSrc : location.vcard.photo,
				note : location.vcard.note,
				orgName : location.vcard.org["organization-name"],
				orgNameURL : location.vcard.org["organization-name-url"],
				orgUnit : location.vcard.org["organization-unit"],
				orgUnitURL : location.vcard.org["organization-unit-url"],
				type : location.vcard.adr.type,
				category : location.vcard.category
			};
			var infoHTML = Barclays.Maps.createInfoHTML(info);
			var iconType = location.vcard.adr.type;
			
			if(geoLocation.latitude == 0 && geoLocation.longitude == 0){
				Barclays.Maps.replaceNullLongLat(info.postcode,infoHTML,iconType);
				return false;
			}
			var newMarker = Barclays.Maps.setMarker(geoLocation,infoHTML,iconType);
			if(info.category){
				newMarker.category = info.category;
			}
		}
	},
	//takes an object with values set in as properties
	//returns a DOM object
	createInfoHTML : function(info){
		var infoHTML = document.createElement("div")
		infoHTML.className = "gmapInfo";
		
		if(info.fn){
			var infoHead = document.createElement("p");
			infoHead.className = "pseudohead";
			infoHead.appendChild(document.createTextNode(info.fn));
			infoHTML.appendChild(infoHead);
		}
		var infoAddr = document.createElement("p");
			infoAddr.className = "address";
		if(info.imgSrc){
			var img = document.createElement("img");
			img.src = info.imgSrc;
			img.className = "gmapImg";
			if(img.height != 0){
				if(info.url){
					var imgLink = document.createElement("a");
						imgLink.href = info.url;
					img.alt = info.fn;
					imgLink.appendChild(img);
					infoHTML.appendChild(imgLink);
				}
				else{
					info.alt = "";
					infoHTML.appendChild(img);
				}
			}
		}
		
		if(info.tel){
			var telP = document.createElement("p");
				telP.appendChild(document.createTextNode(info.tel));
				telP.className = "tel";
			infoHTML.appendChild(telP);
		}
		
		if(info.street){infoAddr.appendChild(document.createTextNode(info.street + ", "));}
		if(info.locality){infoAddr.appendChild(document.createTextNode(info.locality + ", "));}
		if(info.region){infoAddr.appendChild(document.createTextNode(info.region + ", "));}
		if(info.postcode){infoAddr.appendChild(document.createTextNode(info.postcode));}
		if(info.country){infoAddr.appendChild(document.createTextNode(info.country));}
		
		infoHTML.appendChild(infoAddr);
		
		if(info.orgName || info.orgUnit){
			var subhead = document.createElement("p");
				subhead.className = "pseudosubhead";
			if(info.orgName){
				if(info.orgNameURL){
					var orgLink = document.createElement("a");
						orgLink.href = info.orgNameURL;
					orgLink.appendChild(document.createTextNode(info.orgName));
					subhead.appendChild(orgLink);
				}
				else{
					subhead.appendChild(document.createTextNode(info.orgName));
				}
			}	
			if(info.orgName && info.orgUnit){
				subhead.appendChild(document.createTextNode(" : "));
			}
			if(info.orgUnit){
				if(info.orgUnitURL){
				var orgUnitLink = document.createElement("a");
					orgUnitLink.href = info.orgUnitURL;
					orgUnitLink.appendChild(document.createTextNode(info.orgUnit));
					subhead.appendChild(orgUnitLink);
				}
				else{
					subhead.appendChild(document.createTextNode(info.orgUnit));
				}
			}
			infoHTML.appendChild(subhead);
		}

		
		
		if(info.note){
			var infoNote = document.createElement("p");
			infoNote.appendChild(document.createTextNode(info.note));
			infoHTML.appendChild(infoNote);
		}
		if(info.url){
			var infoURL = document.createElement("p");
			var infoLink = document.createElement("a");
				infoLink.className = "calltoaction";
			infoLink.href=info.url;
			infoLink.appendChild(document.createTextNode("View the project details"));
			infoURL.appendChild(infoLink);
			infoHTML.appendChild(infoURL);
		}
		
		return infoHTML;
	},
	//	MARKERS
	markers : [],
	//geolocation expects an object with latitude and longitude
	//infohtml is the html for the popup information window
	//iconType is the type of icon to show
	setMarker : function(geoLocation,infoHTML,iconType){
		var geo = new GLatLng(geoLocation.latitude,geoLocation.longitude);
		var head = Barclays.Common.getElementsByClassName(infoHTML,"p","pseudohead");
		var headText = "";
		if(head.length > 0){
			headText = head[0].innerHTML;
		}
		var markertitle = headText;
		
		var marker = new GMarker(geo,{ icon:Barclays.Maps.getIcon(iconType),title:markertitle });
		GEvent.addListener(marker, "click", function() {
			var zoomPara = Barclays.Common.getElementsByClassName(infoHTML,"p","zoom");
			if(zoomPara.length < 1){
				zoomPara = document.createElement("p");
				zoomPara.className = "zoom";
				var zoomLink = document.createElement("a");
				zoomLink.href = "#";	
				zoomLink.marker = this;
			}
			else{
				zoomPara = zoomPara[0];
				zoomLink = zoomPara.getElementsByTagName("a")[0];
			}
			zoomLink.zoomLevel = Barclays.Maps.gmap.getZoom();
			zoomLink.innerHTML = "Zoom ";
			if(zoomLink.zoomLevel < 10){
				zoomLink.innerHTML += "in";
			}
			else{
				zoomLink.innerHTML += "out	";
			}
			zoomLink.onclick = function(){
				var newZoom = 9;
				if(this.zoomLevel < 10){
					newZoom = this.zoomLevel + 1;
				}
				else{
					newZoom = this.zoomLevel - 1;
				}
				Barclays.Maps.gmap.setCenter(this.marker.getPoint(),newZoom);
				GEvent.trigger(this.marker, "click");
				return false;
			}
			zoomPara.appendChild(zoomLink);
			//infoHTML.appendChild(zoomPara);
			
	    	this.openInfoWindow(infoHTML);       
		});
		marker.heading = headText;
		Barclays.Maps.markers.push(marker);
		
		return marker;
	},
	getIcon : function(iconType){
		switch (iconType.toLowerCase()){
			case "work" :
				return Barclays.Maps.officeIcon;
			default :
				return Barclays.Maps.icon;
		}
	},
	setIcons : function(){
		var baseIcon = new GIcon();
			baseIcon.iconSize = new GSize(22,32);
			baseIcon.iconAnchor = new GPoint(10,30);
			baseIcon.infoWindowAnchor = new GPoint(10,30);
			baseIcon.shadow = '';
			baseIcon.printShadow = '';
			baseIcon.image = '/assets/img/icons/ico_map.png';
			baseIcon.printImage = '/assets/img/icons/ico_map_print.gif';
			baseIcon.mozPrintImage = baseIcon.printImage;
		Barclays.Maps.icon = new GIcon(baseIcon);		
		Barclays.Maps.officeIcon = new GIcon(baseIcon);
			Barclays.Maps.officeIcon.image = '/assets/img/icons/ico_map_office.png';
			Barclays.Maps.officeIcon.printImage = '/assets/img/icons/ico_map_office_print.gif';
			Barclays.Maps.officeIcon.mozPrintImage = Barclays.Maps.officeIcon.printImage;
		Barclays.Maps.clusterIcon = new GIcon(baseIcon);
			Barclays.Maps.clusterIcon.image = '/assets/img/icons/ico_map_cluster_20plus.png';
			Barclays.Maps.clusterIcon.iconSize = new GSize(38,38);
			Barclays.Maps.clusterIcon.iconAnchor = new GPoint(19,34);
			Barclays.Maps.clusterIcon.infoWindowAnchor = new GPoint(30,30);
			Barclays.Maps.clusterIcon.printImage = '/assets/img/icons/ico_map_cluster_print.gif';
			Barclays.Maps.clusterIcon.mozPrintImage = Barclays.Maps.clusterIcon.printImage;
	},
	Regions : {
		moveToRegion : function(){
			var latLng = this.options[this.selectedIndex].value.split(",");
			var north = parseFloat(latLng[0]);
			var east = parseFloat(latLng[1]);
			var south = parseFloat(latLng[2]);
			var west = parseFloat(latLng[3]);
			var bounds = new GLatLngBounds(new GLatLng(south,west),new GLatLng(north,east));
			var centre = bounds.getCenter();
			var zoom = Barclays.Maps.gmap.getBoundsZoomLevel(bounds);
			Barclays.Maps.gmap.setCenter(centre,zoom);
			//stop looping if it currently is looping
			if(Barclays.Maps.Sustainability.isLooping === true){
				Barclays.Maps.Sustainability.stopLoop();
			}
		},
		//outlines a region, useful for testing the bounds rectangle
		outlineRegion : function(north,east,south,west){
			var points = [ new GLatLng(north,east), new GLatLng(south,east),new GLatLng(south,west),new GLatLng(north,west), new GLatLng(north,east)];
			Barclays.Maps.gmap.addOverlay(new GPolyline(points));
		},
		setupRegions : function(){
			var selectRegion = Barclays.Common.getElementsByClassName(document,"select","PE_mapregions");
			for(var i=0,j=selectRegion.length;i<j;i++){
				selectRegion[i].onchange = Barclays.Maps.Regions.moveToRegion;
			}
		}
	},
	Sustainability : {
		loopIndex : 0,
		isLooping : false,
		looper : null,
		loopControl : null,
		//run through marker array, ensures goes back to 0 or doesn't run if no markers
		markerIteration : function(){
			if(Barclays.Maps.cluster._mapMarkers.length === 0){
				Barclays.Maps.Sustainability.stopLoop();
				return;
			}
			if(Barclays.Maps.Sustainability.loopIndex >= Barclays.Maps.cluster._mapMarkers.length){
				Barclays.Maps.Sustainability.loopIndex = 0;
			}
			if(Barclays.Maps.gmap.getZoom() > 0){
				Barclays.Maps.gmap.setZoom(1);
			}
			try{
				GEvent.trigger(Barclays.Maps.cluster._mapMarkers[Barclays.Maps.Sustainability.loopIndex], "click");
			}
			//FIX: occasionally failing when iteration tries to go to a cluster. This avoids failure, but zooms in on the marker.  at the next iteration, the map zoom is reset to 0.
			catch(e){
				Barclays.Maps.cluster.triggerClick(Barclays.Maps.Sustainability.loopIndex);
			}
			Barclays.Maps.Sustainability.loopIndex++;
		},
		//trigger the next marker display, and set up interval call
		startLoop : function(){
			Barclays.Maps.Sustainability.looper = setInterval(Barclays.Maps.Sustainability.markerIteration,5000);
			Barclays.Maps.Sustainability.isLooping = true;
			if(Barclays.Maps.Sustainability.loopControl){
				Barclays.Maps.Sustainability.loopControl.src = 			Barclays.Maps.Sustainability.loopControl.src.replace("play","pause");
				Barclays.Maps.Sustainability.loopControl.alt = "Pause";
			}
		},
		//stop interval call
		stopLoop : function(){
			clearInterval(Barclays.Maps.Sustainability.looper);
			Barclays.Maps.Sustainability.isLooping = false;
			if(Barclays.Maps.Sustainability.loopControl){
				Barclays.Maps.Sustainability.loopControl.src = 			Barclays.Maps.Sustainability.loopControl.src.replace("pause","play");
				Barclays.Maps.Sustainability.loopControl.alt = "Play";
			}
		},
		setUpLoop : function(){
			function waitForData(){
				if(!map.childNodes[0]){
					setTimeout(waitForData,1000);
					return false;
				}
				Barclays.Maps.Sustainability.startLoop();
			}
			var control = Barclays.Common.getElementsByClassName(document,"a","PE_loopControl");
			if(control.length < 1){return false;}//do not allow unpausable loops to run, AA accessibility
			var map = Barclays.Maps.gmap.getContainer();
			Barclays.Maps.gmap.setZoom(0);
			waitForData();
			//
			var linkImg = control[0].getElementsByTagName("img");
			if(linkImg.length > 0){
				Barclays.Maps.Sustainability.loopControl = linkImg[0];
			}
			map.appendChild(control[0]);
				control[0].onclick = function(){
				if(Barclays.Maps.Sustainability.isLooping){
					Barclays.Maps.Sustainability.stopLoop();
					wasLooping = Barclays.Maps.Sustainability.isLooping;
				}
				else{
					Barclays.Maps.Sustainability.loopIndex++;
					Barclays.Maps.Sustainability.startLoop();
				}
				return false;
			};
			//stops the looping behaviour when the user drags the map, otherwise it could be very difficult to interact with it.  

			var wasLooping;
			GEvent.addDomListener(Barclays.Maps.gmap,"drag",function(){
				wasLooping = Barclays.Maps.Sustainability.isLooping;
				Barclays.Maps.Sustainability.stopLoop();
			});
		},
		// we have to remove all markers and reasses the array fresh because of the way clustermarker handles removing markers
		refreshAllMarkers : function(){
			var wasLooping = Barclays.Maps.Sustainability.isLooping;
			Barclays.Maps.Sustainability.stopLoop();
			var visibleMarkers = [];
			Barclays.Maps.cluster.removeMarkers();
			//if no checkboxes are checked, show all
			var checkCount = 0;
			for(var n=0,p=this.allCheckboxes.length;n<p;n++){
				if(this.allCheckboxes[n].checked === true){
					checkCount++;
					var addMarkers = Barclays.Maps.Sustainability[this.allCheckboxes[n].id];
					for(var q=0,r=addMarkers.length;q<r;q++){
						if(visibleMarkers.indexOf(addMarkers[q]) == -1){
							visibleMarkers.push(addMarkers[q]);
						}
					}
				}
			}
			if(checkCount === 0){
				for(var n=0,p=this.allCheckboxes.length;n<p;n++){
					var addMarkers = Barclays.Maps.Sustainability[this.allCheckboxes[n].id];
					for(var q=0,r=addMarkers.length;q<r;q++){
						if(visibleMarkers.indexOf(addMarkers[q]) == -1){
							visibleMarkers.push(addMarkers[q]);
						}
					}
				}
			}
			if(visibleMarkers.length > 0){//IE throws a problem if there are no markers to add, test first
				Barclays.Maps.cluster.addMarkers(visibleMarkers);
				Barclays.Maps.cluster.refresh();
			}
			if(wasLooping){
				Barclays.Maps.Sustainability.startLoop();
			}
		},
		setUpFilters : function(){
			var checkboxList = Barclays.Common.getElementsByClassName(document,"ul","PE_sustainabilityAreas");
			if(checkboxList.length < 1){return;}
			var checkboxes = checkboxList[0].getElementsByTagName("input");
			var triggerBtn = Barclays.Common.getElementsByClassName(document,"a","PE_filterSubmit");
			for(var i=0,j=checkboxes.length;i<j;i++){
				//make arrays for each checkbox for their projects
				Barclays.Maps.Sustainability[checkboxes[i].id] = [];
				var catRegExp = new RegExp("\\b"+checkboxes[i].id+"\\b","gi");
				for(var k=0,m=Barclays.Maps.markers.length;k<m;k++){
					if(catRegExp.test(Barclays.Maps.markers[k].category) === true){
						Barclays.Maps.Sustainability[checkboxes[i].id].push(Barclays.Maps.markers[k]);
						catRegExp.lastIndex = 0;//reset regexp
					}
				}
			}
			if(triggerBtn.length > 0){
				triggerBtn[0].allCheckboxes = checkboxes;
				Barclays.Common.addEvent(triggerBtn[0],'click',Barclays.Maps.Sustainability.refreshAllMarkers);
			}
		},
		init : function(){
			Barclays.Maps.Sustainability.setUpFilters();
			Barclays.Maps.Sustainability.setUpLoop();
		}	
	}	
};

/*
 * SETUP DOM READY AND LOAD EVENTS HERE
*/
/*ON DOM READY FUNCTIONS*/
Barclays.Common.setUpDOMReady();
/*ON LOAD FUNCTIONS*/
Barclays.Common.addLoadEvent(Barclays.Custom.init);
/*UNLOAD FUNCTIONS*/
if(typeof GUnload == "function"){window.onunload = GUnload;}//unload googlemaps

/*
METAPROGRAMMING

Array indexOf for browsers which don't support it
REF: https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference:Objects:Array:indexOf
*/
if(typeof Array.prototype.indexOf=="undefined"){
	Array.prototype.indexOf=function(searchElement,fromIndex){
		var startIndex = parseInt(fromIndex,10) || 0;
		for(var i=startIndex;i<this.length;i++){
			if(this[i] === searchElement){
				return i;
			}
		}
		return -1;
	};
}

// carousel object //
function carousel(){			
	var currentPanel=null;
	var slideshowTimer=null;
	
	var bgWidth=0;
	var bgHeight=0;	
	var scrollDiv=null;	
	var buttonsArray=new Array();		// buttons used to iterate the carousel images
	var btnIndex=0;						// used by the slideshow function, Holds the button currently pressed
	
	var fxInProgress=false;
	
	var transition="scrollToPanel";		// the transition is customisable HTML side!
	
	var mouseOver=false;		var thisObj=this;
	this.initCarousel=function(obj){	
		var ul=obj.getElementsByTagName("ul")[0];
		if (ul.className.length>0){
			transition=ul.className;
		}
		
		//creating a container for the UL.
		//this container allows the buttons horizontal scroll
		scrollDiv=create("div","scrollDiv",obj);
		//moving the UL inside the scrollDiv
		scrollDiv.appendChild(ul);
		var li=obj.getElementsByTagName("li");
		
		//defining the module height
		bgImage=Barclays.Common.getElementsByClassName(li[0],"img","bgImage")[0];
		bgWidth=bgImage.offsetWidth;
		bgHeight=bgImage.offsetHeight;					

		obj.style.width=bgWidth+"px";			
		
		ul.onmouseout=function(){mouseOver=false};			
		
		// attaching the mousemove event		
		ul.onmousemove=function(evt){			
			evt=evt?evt:window.event;			
			var x=evt.layerX?evt.layerX:evt.offsetX;									
			var el=evt.srcElement?evt.srcElement:evt.target;						
			if (el.tagName=="SPAN") el=el.parentNode;	//IE			
			x-=scrollDiv.scrollLeft-el.offsetParent.offsetLeft;											
			if(el.tagName!="BUTTON"){								
				mouseOver=false;				
				return false;						
			}									
			mouseOver=true;									
			scrollDiv.scrollLeft=-50+(ul.offsetWidth-(bgWidth-50))/(bgWidth-50)*x;		
		}		
		
		var totalWidth=0;
		for(var x=0;x<li.length;x++){
			var divs=li[x].getElementsByTagName("div");
			var divContainer=divs[0];
			var	divFooter=divs[1];
			
			divContainer.style.width=bgWidth+"px";
			divFooter.style.width=bgWidth+"px";
						
			var title=Barclays.Common.getElementsByClassName(divFooter,"*","title")[0]

			li[x].style.paddingTop=bgHeight+"px";	
			li[x].style.backgroundPosition="right " + bgHeight+"px";	
													
			
			//adding an extra container						
			var extraDiv=create("div","slidingDiv",li[x]);
			extraDiv.style.display="none";
			extraDiv.index=x;
			extraDiv.appendChild(divContainer);
			
			var btn=create("button","activateBtn");
			li[x].insertBefore(btn,li[x].firstChild);
			
			buttonsArray.push(btn);
			var btnTxt=create("span","",btn);
			addText(title.firstChild.nodeValue,btnTxt);

			Barclays.Common.addEvent(btn,"click",function(evt){
										clearInterval(slideshowTimer);
										var btn=evt.srcElement?evt.srcElement:evt.target;
										if(btn.tagName=="SPAN") btn=btn.parentNode;
										thisObj.activateSection(btn)}													
										);
			
			// get the li width
			totalWidth+=btnTxt.offsetWidth+30;
			li[x].style.width=btnTxt.offsetWidth+30+"px"
			
			//try to see if it fits with the bgImage width....->
			
		}
		
		//...-> if not than add the scrolling function
		if (totalWidth>bgWidth){
			ul.style.width=totalWidth + "px";		
		}else{
			for(var x=0;x<li.length;x++){
				li[x].style.width=(100/li.length)-0.1 + "%";
			}									
			li[li.length-1].style.width= bgWidth-(li[li.length-1].offsetWidth*(li.length-1))+0.4+"px"	//0.4 is to fix a FF rounding up bug
		}

		for(var x=0;x<li.length;x++){
			buttonsArray[x].style.width="100%"
		}	
		
		//display the current panel
		currentPanel=bgImage.parentNode.parentNode;
		currentPanel.style.display="block";	
		addClass(currentPanel.parentNode,"selected");
		
		slideshowTimer=setInterval(this.showNext,4000);					//<-- customise this to change the pictures display speed
		
	}
	
	this.showNext=function(){
		btnIndex++;
		
		if(btnIndex==buttonsArray.length) btnIndex=0;
		
		var btn=buttonsArray[btnIndex]		
		var li=btn.parentNode;
		
		var finalScroll=null
		
		
		if(!mouseOver){	//if I am not hovering the component...
			//ensure that the current button is visible
			if((li.offsetLeft+li.offsetWidth)>bgWidth){
				
				finalScroll=scrollDiv.scrollLeft-((li.offsetLeft+li.offsetWidth)-bgWidth);
			}
			
			if(scrollDiv.scrollLeft>li.offsetLeft){
				finalScroll=scrollDiv.scrollLeft-li.offsetLeft;
			}
			if (finalScroll){
				var scrollFx=new smoothFx(600);
				scrollDiv.oldScroll=scrollDiv.scrollLeft;
				scrollFx.onProgress=function(prog,obj){
					obj.scrollLeft=obj.oldScroll-finalScroll*prog;
				}
				scrollFx.onStart=function(){
					thisObj.activateSection(btn);
				}
				scrollFx.start(scrollDiv);
			}else{
				thisObj.activateSection(btn);					
			}
		}else{
			thisObj.activateSection(btn);					
		}
		
	}
	
	this.activateSection=function(btn){										
	
		var li=btn.parentNode;
		var div=li.getElementsByTagName("div")[0];
		
		
		if(!fxInProgress && currentPanel!=div) {
			
			removeClass(currentPanel.parentNode,"selected")									
			addClass(li,"selected")
			
			li.style.height=btn.offsetHeight+"px";
			
			
			//performs the transition defined in the UL class name
			eval("this." + transition+"(div)")
		}
	}


// transition effects: //
	this.loopToPanel=function(newPanel){
		var fxOut=new smoothFx(1000);
		fxInProgress=true;
		
		var toRight=(currentPanel.index>newPanel.index);
		
		fxOut.onStart=function(){																
			
			newPanel.style.zIndex=1;
			currentPanel.style.zIndex=2;
			
			if (toRight){
				currentPanel.style.left="0px";
				currentPanel.style.right="auto";
				
				newPanel.style.left="0px";
				newPanel.style.right="auto";							
			}else{
				currentPanel.style.right="auto";
				currentPanel.style.left="0px";
				
				newPanel.style.left="0px";
				newPanel.style.right="auto";							
			}
			
			newPanel.style.width=bgWidth+"px";
			newPanel.style.display="block";
			
		}
		
		fxOut.onProgress=function(prog){
			if(toRight){
				currentPanel.style.left=bgWidth*prog + "px";												
				newPanel.style.left=-(bgWidth-prog*bgWidth) + "px";
			}else{
				currentPanel.style.left=-currentPanel.offsetWidth*prog + "px";
				newPanel.style.left=bgWidth-prog*bgWidth + "px";																		
			}						
		}
		
		fxOut.onComplete=function(obj){
			currentPanel.style.display="none";						
			currentPanel=newPanel;											
			fxInProgress=false;
		}
		
		fxOut.start();					
	}

	this.scrollToPanel=function(newPanel){
		var fxOut=new smoothFx(1000);
		fxInProgress=true;
		
		fxOut.onStart=function(){		
			currentPanel.style.display="none"		
			newPanel.style.display="none";
			
			newPanel.style.zIndex=1;
			newPanel.style.left="0px";
			currentPanel.style.zIndex=2;

			
			newPanel.style.bottom=-currentPanel.offsetHeight+"px";															
			
			newPanel.style.height="0px";
			newPanel.style.display="block";
			currentPanel.style.display="block";			
		}
		
		fxOut.onProgress=function(prog){
			currentPanel.style.height=bgHeight-(bgHeight*prog)+ "px";
			newPanel.style.height=prog*bgHeight + "px";						
		}
		
		fxOut.onComplete=function(obj){
			currentPanel.style.display="none";						
			currentPanel=newPanel;											
			fxInProgress=false;
		}
		
		fxOut.start();					
	}
	
	this.slideToPanel=function(newPanel){
		var fxOut=new smoothFx(800);
		fxInProgress=true;
		
		fxOut.onStart=function(){		
			newPanel.style.zIndex=1;
			currentPanel.style.zIndex=2;
			newPanel.style.width="0px";
			newPanel.style.display="block";
		}
		
		fxOut.onProgress=function(prog){
			currentPanel.style.width=(1-prog)*100 + "%";
			newPanel.style.width=prog*100 + "%";						
		}
		
		fxOut.onComplete=function(obj){
			currentPanel.style.display="none";						
			currentPanel=newPanel;											
			fxInProgress=false;
		}
		
		fxOut.start();					
	}
					
	this.fadeToPanel=function(newPanel){		// fxIn/out transition
		var div=newPanel;
		var fxOut=new smoothFx(500);
		fxInProgress=true;
		
		fxOut.onProgress=function(prog,obj){
			setOpacity(obj,1-prog);
		}
		
		fxOut.onComplete=function(obj){
			obj.style.display="none";	
			currentPanel=div;					
			
			var fxIn=new smoothFx(500);
			fxIn.onStart=function(){
				setOpacity(div,0);
				div.style.display="block";
			}
			
			fxIn.onProgress=function(prog){
				setOpacity(div,prog);
				div.style.filter="";
			}
			fxIn.onComplete=function(){
				fxInProgress=false;
			}
			
			fxIn.start(div);
		}
		
		fxOut.start(currentPanel);									
	}
	
}



// utilities //

	function create(objType,className, parent){
		var obj=document.createElement(objType);
		
		if(className) obj.className=className;
		if(parent) parent.appendChild(obj);
		return obj;		
	}
	
	function addText(str, parent){
		var obj=document.createTextNode(str);
		parent.appendChild(obj);
		return obj;		
	}
	
	function setOpacity(obj,value){
		obj.style.filter="alpha(opacity=" + value*100 +")";
		obj.style.opacity=value;
		return obj;
	}
	
	function addClass(obj, className){
		if (obj.className.indexOf(className)==-1) obj.className+=" " + className;	
		return obj;
	}
	
	function removeClass(obj, className){
		obj.className=obj.className.replace(" " + className,"");
		obj.className=obj.className.replace(className,"");				
		return obj;
	}
	
// smoothFx - transitions maker tool
function smoothFx(duration,fps,power){ this.duration=1000; this.fps=40; this.maxVal=3; this.power=3; this.style="easeIn"; this.htmlObj=null; if(duration) this.duration=duration; if(fps) this.fps=fps; if(power) this.power=power; this.onProgress=function(x){}; this.onStart=function(){}; this.onComplete=function(){}; this.timerHnd=null; this.startTime=null; var obj=this; this.loops=0; this.progress=function(){ var tmpDate=new Date(); var now=tmpDate.getTime(); var deltaT=now-obj.startTime; var tProgr=deltaT/obj.duration; var valProg=null; obj.loops++; switch (this.style){ case "easeIn":
valProg=Math.pow(tProgr*obj.maxVal,obj.power)/Math.pow(obj.maxVal,obj.power); break; case "easeOut":
valProg=1-Math.abs(Math.pow(tProgr*obj.maxVal-obj.maxVal,obj.power))/Math.pow(obj.maxVal,obj.power); break; default:
valProg=1-Math.abs(Math.pow(tProgr*obj.maxVal-obj.maxVal,obj.power))/Math.pow(obj.maxVal,obj.power);}
if(now>obj.startTime+obj.duration){ obj.onProgress(1,obj.htmlObj); obj.onComplete(obj.htmlObj);} else { obj.onProgress(valProg,obj.htmlObj); obj.timerHnd=setTimeout(strProgr,1000/obj.fps);}
}
var strProgr=this.progress; this.start=function(htmlObj,style){ this.stop(); if(htmlObj){ this.htmlObj=htmlObj;}
if(style) obj.style=style; var tmpDate=new Date(); this.startTime= tmpDate.getTime(); this.timerHnd=setTimeout(this.progress,1000/this.fps); this.onStart(htmlObj);}
this.stop=function(){ clearTimeout(this.timerHnd); obj.htmlObj=null;}
}
