$(function(){
	invjs.init();
});

$(window).resize(function(){
	if((invjs.resizing == 0) && (invjs.transferring == 0)){
		invjs.resizing = 1;
		clearTimeout(loc);
		var loc = setTimeout("invjs.locateElements()", 750); // this delay is necessary for browsers that trigger resize events while still resizing
	}
});

invjs = {
	//site root variable for files accessed via JS
	jspath: "", // it's setup in html_end.jsp

	// properties used by various methods after page load
	elegance: true,
	externalLinksInNewWindow: false,
	anchorSeparatorChar: "+",
	minSiteWidth: 1000,
	minSiteHeight: 550,
	windowWidth: null,
	windowHeight: null,
	isie: $.browser.msie,
	browserVer: $.browser.version,
	menuSpeed: 300,
	quickSpeed: 10,
	animating: 0,
	mainOpen: 0,
	libOpen: 0,
	mainLocked: 0,
	libLocked: 0,
	sharesOpen: 0,
	fontAdjust: 0,
	searchBoxText: null,
	searchAgainBoxText: null,
	numTabs: null,
	selectedTab: null,
	tabScrollPos: 0,
	resizing: 0,
	transferring: 0,
	recentHash: null,
	lastAjaxCall: "",
	lastReferrer: "",
	countryOpened: false,
	servicesOpened: false,
	userClicked: false,	
	footerPopup: false,
	footerPopupWaitTime: 2000,
	footerPopupShowTime: 2000,
	eleganceLoaded: false,
	geoCountry: "",
	geoCity: "",
	popupShown: false,

	init: function(){

	 	$.ajaxSetup({  
	  		beforeSend:function(xhr) {
	   			xhr.setRequestHeader("Investec-Elegance-Call", "true");
	   		}  

	  	});

		// various routines here cater for updating just the central content pane of the page using AJAX.
		// bookmarkability is to be catered for using # and window.location.hash
		// see http://ajaxpatterns.org/Unique_URLs for more on this concept/technique

		/* INVESTECAFTERCARE-105 */
			$("#outerContainer").show();

		$("#nonJS, #whiteout").hide();

		var targPage;

		// avoid any ajax'ey behaviour on intro page 
		if (!isChooseUserType) {

			if(invjs.isie && invjs.elegance){
				invjs.setupIframe();
			} 

			if (clickmapMode) {
				invjs.elegance = false;
			}

			if(invjs.elegance){
				// check URL for existence of #
				if(window.location.href.indexOf("#") != -1) {
					// URL contains #. now check where the # occurs in the URL

					var checkFilename = invjs.getFileName(window.location.href);
					
					// if there is a filename before the #, get rid of it and redirect, we only want the one after
					var hashLoc = checkFilename.indexOf("#");
					if(hashLoc != 0) {
						document.location.href = invjs.jspath + (checkFilename.substr(hashLoc));
						return false;
					} else {
						// the # is at the beginning of the page name, so set target page for loading later
						targPage = invjs.jspath + checkFilename.substr(hashLoc+1);
					}
				} else {
					// white sheet, let's not peek where
					if(!isChooseUserType) {
						$("body").append('<div id="cover"></div>');
					}

				    var ref = readCookie("investec_referrer");
			
					if (invjs.isie) {						
						var ieRef = document.referrer;
						if (ref && ref!="") {
							ieRef = ref;
							eraseCookie("investec_referrer");
						}
						createCookie("investec_referrer_iefix", ieRef, 1);
					}
					else {
						if (!ref || ref== "" || typeof(ref) == "undefined") {					
							createCookie("investec_referrer", document.referrer, 1);
						}
					}
					

					// there's no #, so put one in and redirect to root. makes the rest of URL behaviour more predictable and useful.
					
					var checkFilename = invjs.getFileName(window.location.href);

					// avoid doing the clever redirect for the intro page, as that does not use the same framework
					if(!isChooseUserType) {
						if (checkFilename == "") {
							// this is very weird case, it looks like document.location.href here basically goes
							// from index.html# to index.html#home.html
							// not resulting in proper redirect, but weird elegance loading.
							// we need to fix few things here (potentially unstable, though)

							$("div#cover").remove();

							var url = document.location.protocol + "//" + document.location.host + invjs.jspath + "#" + "home.html";
							// document.location.href = invjs.jspath + "#" + "home.html";
							document.location.replace(url);

							setPageBackground();
							// return false; // why oh why it crashes when I put return false; here???
						}
						else {
							var url = document.location.protocol + "//" + document.location.host + invjs.jspath + "#" + checkFilename;
							// document.location.href = invjs.jspath + "#" + checkFilename;
							document.location.replace(url);

							return false;
						}
					}
				}
			}

			invjs.eleganceLoaded = true;


			// set up screen size and main page elements
			invjs.setScreen(targPage);
			
			invjs.setTriggers();
			invjs.setupMenus();
			invjs.setupUtils();

			invjs.setupSharesbar();
			 
			if(invjs.elegance) {
				invjs.enableBackButton();
			}
			
			// fix anchors on author
			if (!invjs.elegance) {		
				invjs.ajaxifyAuthor();
			}

		}
		else {
			$("div#introSelector ul li").mouseover(function(){
				$(this).addClass("opened");
			}).mouseout(function(){
				$(this).removeClass("opened");
			});

			// fix for choose user type, need to overwrite default 550 px of choose user type
			var windowHeight = $(window).height();
			$("#outerContainer").height(windowHeight);
		}
	},
	setScreen: function(targPage){
		// set up location and dimensions of screen elements such as pullout menus and shares info bar
		invjs.windowWidth = $(window).width();
		invjs.windowHeight = $(window).height();

		var wWidth = invjs.getWidth();
		var wHeight = invjs.getHeight();
		  
		invjs.setContentArea(wHeight);
		 
		invjs.setOuterElements(wWidth, wHeight);
		  
		// attach behaviour to menu locks
		$("#mainMenuLock span").unbind("click").click(function(){
			this.blur();
			invjs.clickLock("main");
			/* INVESTECAFTERCARE-239 */
			isNavMenuLocked = invjs["mainLocked"];
			createCookie("is_navmenu_locked", isNavMenuLocked, cookieExpirationTime)
			return false;
		});
		$("#libMenuLock span").unbind("click").click(function(){
			this.blur();
			invjs.clickLock("lib");
			/* INVESTECAFTERCARE-239 */
			isLibMenuLocked = invjs["libLocked"];
			createCookie("is_libmenu_locked", isLibMenuLocked, cookieExpirationTime)
			return false;
		});
		  
		// locate country and services (login) dropdown boxes
		invjs.setupDropdowns();


		// load central pane of target page
		// NO LONGER REQUIRED now that location polling is happening
		/*if(targPage && invjs.elegance){
			invjs.urlHash(targPage);
		}*/


	},
	getWidth: function(){
		var invWid = invjs.windowWidth;
		if(invWid < invjs.minSiteWidth) {
			invWid = invjs.minSiteWidth;
		}
		return invWid;
	},
	getHeight: function(){
		var invHei = invjs.windowHeight;

		if($.browser.opera) {
			var ver = $.browser.version;
			var rx = /\./g;
			ver = ver.replace(rx,"");
			if (parseInt(ver) >= 950) {
				invHei = document.getElementsByTagName('html')[0].clientHeight;
			}
		}

		if(invHei < invjs.minSiteHeight) {
			invHei = invjs.minSiteHeight;
		}

		return invHei;
	},
	setContentArea: function(wHeight, wAnchor) {
		invjs.setContentPane(wHeight);
		invjs.setupTools();
		invjs.setupTabs();
		invjs.setupTooltips();
		 
		if(invjs.elegance){
			invjs.ajaxify();
		} 

		invjs.externaliseLinks();

		invjs.amendContentOnLoad(wAnchor);
	},
	setContentPane: function(wHeight){

		/* INVESTECAFTERCARE-116 */
		/*
		if(invjs.isie){
			if(invjs.browserVer <= 6){
				wHeight+=1;
			} else {
				wHeight+=4;
			}
		}
		*/

		$("#logo").css("width","45%");

		var header_height = $("#header").height();

		$("#mainContentArea").height(wHeight-120);

		var delta = 31; // tabbar height

		$("div#basicPage").height(wHeight-198+ delta);

	//	alert("wHeight: "+wHeight+" delta: " +delta+" header_height: "+header_height);		
				
		var adjustSize; // header margin

		if (isCQEditMode()) {
			adjustSize = 0;			
		}
		else {
			adjustSize = 55;
		}
		
		var isChallenge = $(".pageContent.challenge").length > 0 ? true : false;
		
		// adjust content pane for challenge
		if ( typeof(isChallenge) != 'undefined' && isChallenge == true) {
			adjustSize += 22;
		}

		// popup footer for challenge
		if (invjs.footerPopup) {
			if ( typeof(isChallenge) != 'undefined' && isChallenge == true) {
				setTimeout(function() { invjs.clickExpandLink(); }, invjs.footerPopupWaitTime);
				setTimeout(function() { invjs.clickExpandLink(); invjs.footerPopup = false; }, invjs.footerPopupWaitTime + invjs.footerPopupShowTime);
			}
		}

		$("div#basicPage div.pageContent, div#basicPage div#pageTools").height(wHeight-275+delta - header_height + adjustSize);

	},
	setOuterElements: function(wWidth, wHeight){
		if (!isChooseUserType) {
			$("#outerContainer").width(wWidth).height(wHeight);
		} else {
			var zebraTop = $("#introZebra").offset().top;
			var zebraHeight = $("#introZebra").height();
			var totalHeight = zebraTop + zebraHeight - 15;	
			$("#header").css("width",$("#introOuter").width());
			$("#logo").css("left","345px");
			$("#outerContainer").width(wWidth).height(totalHeight);
		}
		$("#mainMenu").height(wHeight).css("left","-250px");
		$("#libMenu").height(wHeight).css("right",null).css("left", wWidth+"px");
		$("#mainMenuTrigger").show().css("left", "0px");
		var rightTriggerWidth = $("#libMenuTrigger").width();
		$("#libMenuTrigger").show().css("right", null).css("left", (wWidth-rightTriggerWidth)+"px");
		$("div#sharesMenuTrigger").remove();

		var disclaimerHeight = $("#disclaimer").length > 0 ? 14 : 0;
		
		var omnitureString = "onClick=\""
		+ "s_objectID='JS_ACTION_FOOTER_CLICKED';"
		+ "var s=s_gi(s_account);"
		+ "s.linkTrackVars='events,eVar4,prop16';"
		+ "s.linkTrackEvents=(invjs.sharesOpen==0)?'event16':'event17';"
		+ "s.events=(invjs.sharesOpen==0)?'event16':'event17';"
		+ "s.eVar4=s.prop16;"
		+ "s.tl(true, 'o', (invjs.sharesOpen==0)?'FOOTER_EXPAND':'FOOTER_COLLAPSE');\"";

		$("div#sharesMenu").width(wWidth).css("bottom",null).css("top",(wHeight-50-disclaimerHeight)+"px").after('<div id="sharesMenuTrigger" '+omnitureString+'></div>');

		$("div#sharesMenuTrigger").width(wWidth).css("bottom",null).css("top",(wHeight-50-disclaimerHeight)+"px").unbind("click").click(function(){
			$(this).blur();
			invjs.clickExpandLink();
			return false;
		});
	},

	locateElements: function(){
		/* INVESTECAFTERCARE-112 */
			$("#outerContainer").width(invjs.minSiteWidth).height(invjs.minSiteHeight);

		invjs.windowWidth = $(window).width();
		invjs.windowHeight = $(window).height();

		var wWidth = invjs.getWidth();
		var wHeight = invjs.getHeight();

		invjs.setContentPane(wHeight);
		invjs.setOuterElements(wWidth, wHeight);

		if((invjs.mainOpen == 1) && (invjs.libOpen == 1)){
			invjs.showMainMenu(1, invjs.quickSpeed); // use flag to chain showing of both menus
		} else {
			if(invjs.mainOpen == 1){
				invjs.showMainMenu();
			}
			if(invjs.libOpen == 1){
				invjs.showLibMenu();
			}
		}


		invjs.setupDropdowns();

		invjs.setupSharesbar(invjs.sharesOpen);

		invjs.locateFooterLinks();

		invjs.resizing=0;
	},
	locateFooterLinks: function(){
		$("#footerLinks").css("margin-top", "20px");
		var isChallenge = $(".pageContent.challenge").length > 0 ? true : false;
		if (isChallenge) {return;}
		
		
		if( document.getElementById("footerLinks") ) {
			var fTop = $("#footerLinks").offset().top;
			var sTop = $("#sharesMenu").offset().top;

			//alert("fTop = "+fTop+", sTop = "+sTop);

			if(sTop > fTop){
				var addMargin = sTop-(fTop + $("#footerLinks").height() + 5 );
				$("#footerLinks").css("margin-top", addMargin+"px");
			}
		}
		
	},
	clickLock: function(wLock){
		if(invjs[wLock+"Locked"] == 1){
			$("#"+wLock+"MenuLock span").empty().text("lock").removeClass("locked");
			invjs[wLock+"Locked"] = 0;
		} else {
			$("#"+wLock+"MenuLock span").empty().text("unlock").addClass("locked");
			invjs[wLock+"Locked"] = 1;
		}

		invjs.checkMenus();
	},
	setTriggers: function(){
		$("div#mainMenuTrigger").mouseover(function(){
			invjs.showMainMenu();
		});
		$("div#libMenuTrigger").mouseover(function(){
			invjs.showLibMenu();
		});

		$("div#mainMenu a.close").click(function(){
			this.blur();
			invjs.hideMainMenu();
			return false;
		});
		$("div#libMenu a.close").click(function(){
			this.blur();
			invjs.hideLibMenu();
			return false;
		});
	},
	hideMainMenu: function(both){
		if(both && (invjs.mainLocked ==1)){
			invjs.hideLibMenu();
		}
		if((invjs.animating == 0) && (invjs.mainLocked == 0)){

			$("#mainMenuLock").hide();
			invjs.animating = 1;

			$("#mainMenu").animate({
				left: "-250px"
			}, invjs.menuSpeed);

			$("#mainMenuTrigger").animate({
				left: "0px"
			}, invjs.menuSpeed	, "swing", function(){
				invjs.animating = 0;
				invjs.mainOpen = 0;
				if (both) {
					invjs.hideLibMenu();
				}
			});
		}
	},
	hideLibMenu: function(){
		if((invjs.animating == 0) && (invjs.libLocked == 0)){

			$("#libMenuLock").hide();
			invjs.animating = 1;

			$("#libMenu").animate({
				left: (invjs.windowWidth)+"px"
			}, invjs.menuSpeed);

			var rightTriggerWidth = $("#libMenuTrigger").width();
			$("#libMenuTrigger").animate({
				left: (invjs.windowWidth-rightTriggerWidth)+"px"
			}, invjs.menuSpeed	, "swing", function(){
				invjs.animating = 0;
				invjs.libOpen = 0;
			});
		}
	},
	showMainMenu: function(both, spd){
		var wSpeed = (spd) ? spd : invjs.menuSpeed;
		if(invjs.animating == 0){
			invjs.animating = 1;

			$("#mainMenu").animate({
				left: "0px"
			}, wSpeed);

			$("#mainMenuTrigger").animate({
				left: "-90px"
			}, wSpeed	, "swing", function(){
				$("#mainMenuLock").show();
				invjs.animating = 0;
				invjs.mainOpen = 1;
				if(both){
					invjs.showLibMenu(spd);
				} else {
					invjs.buildCloseTrigger();
				}
			});
		}
	},
	showLibMenu: function(spd){
		var wSpeed = (spd) ? spd : invjs.menuSpeed;
		if(invjs.animating == 0){
			invjs.animating = 1;

			var rightMenuWidth = $("#libMenu").width();
			$("#libMenu").animate({
				left: (invjs.windowWidth-rightMenuWidth)+"px"
			}, wSpeed);

			$("#libMenuTrigger").animate({
				left: invjs.windowWidth+"px"
			}, wSpeed	, "swing", function(){
				$("#libMenuLock").show();
				invjs.animating = 0;
				invjs.libOpen = 1;
				invjs.buildCloseTrigger();
			});
		}
	},
	buildCloseTrigger: function(){
		var trigX = 0;
		var trigY = 0;
		var trigW = invjs.getWidth();
		var trigH = invjs.getHeight();

		if(invjs.mainOpen == 1){
			trigX += $("#mainMenu").width();
			trigW -= $("#mainMenu").width();
		}
		if(invjs.libOpen == 1){
			trigW -= $("#libMenu").width();
		}

		$("#menuCloseTrigger").remove();
		$("body").append('<div id="menuCloseTrigger"></div>');
		$("#menuCloseTrigger").css({
			left: 			trigX+"px",
			top: 			trigY+"px",
			width: 			trigW+"px",
			height: 		trigH+"px"
		}).mouseover(function(){
			invjs.activateCloseTrigger();
		});
	},
	destroyCloseTrigger: function(){
		$("#menuCloseTrigger").remove();
	},
	activateCloseTrigger: function(){
		invjs.destroyCloseTrigger();

		if(invjs.mainOpen && invjs.libOpen){
			invjs.hideMainMenu(1);
		} else if(invjs.mainOpen){
			invjs.hideMainMenu();
		} else if(invjs.libOpen){
			invjs.hideLibMenu();
		}

		invjs.checkMenus();
	},
	checkMenus: function(){
		if((invjs.mainLocked == 1 || invjs.mainOpen == 0) && (invjs.libLocked == 1 || invjs.libOpen == 0)){
			return;
		} else if (invjs.animating == 0){
			invjs.buildCloseTrigger();
		}
	},
	setupMenus: function(){
		$("div.level2navwrapper, div.level3navwrapper").hide();
		$("li.level1.selected > div.level2navwrapper, li.level2.selected > div.level3navwrapper").show();

		$("li.level1 > span.nav1arrow").click(function(){
			var index = $("li.level1 > span.nav1arrow").index(this);
			invjs.selectMenu(index);
		});

		$("li.level2:has(span.nav2arrow) > span").click(function(){
			var index = $("li.level2:has(span.nav2arrow) > span").index(this);
			invjs.selectMenuL2(index);
		});


		$("ul.level1nav li a").click(function(){
			this.blur();
		});
		
		/* INVESTECAFTERCARE-239 */
		isNavMenuLocked = readCookie("is_navmenu_locked");
		isLibMenuLocked = readCookie("is_libmenu_locked");
		if(isNavMenuLocked && isLibMenuLocked && 
				isNavMenuLocked==1 && isLibMenuLocked==1){
			//invjs.clickLock("lib");
			//invjs.clickLock("main");
			$("#libMenuLock span").empty().text("unlock").addClass("locked");
			invjs["libLocked"] = 1;
			$("#mainMenuLock span").empty().text("unlock").addClass("locked");
			invjs["mainLocked"] = 1;
			invjs.showMainMenu(1, invjs.quickSpeed); // use flag to chain showing of both menus
		} else {
			if(isLibMenuLocked && isLibMenuLocked==1){
				invjs.clickLock("lib");
				invjs.showLibMenu();
			}
			if(isNavMenuLocked && isNavMenuLocked==1){
				invjs.clickLock("main");
				invjs.showMainMenu();
			}
		}
		/* CHANGE END */

	},
	selectMenu: function(wMenu){
		var l1menus = $("li.level1");
		if(l1menus[wMenu].className.indexOf("selected") != -1){
			$(l1menus[wMenu]).removeClass("selected");
			$(l1menus[wMenu]).children("div.level2navwrapper").slideUp();
			$("span.navpicscroll").animate({
				top: "0px"
			}, invjs.menuSpeed);
		} else {
			for(var x=0; x<l1menus.length; x++){
				if(x==wMenu){
					$(l1menus[x]).addClass("selected");
					$(l1menus[x]).children("div.level2navwrapper").slideDown();
					$("span.navpicscroll").animate({
						top: (-(x+1) * 71)+"px"
					}, invjs.menuSpeed);
				} else {
					$(l1menus[x]).removeClass("selected");
					$(l1menus[x]).children("div.level2navwrapper").slideUp();
				}
			}
		}
		invjs.closeAllL2Menus();
	},
	selectMenuL2: function(wMenu){
		var l2menus = $("li.level2:has(span.nav2arrow)");
		if(l2menus[wMenu].className.indexOf("selected") != -1){
			$(l2menus[wMenu]).removeClass("selected");
			$(l2menus[wMenu]).children("div.level3navwrapper").slideUp();
		} else {
			for(var x=0; x<l2menus.length; x++){
				if(x==wMenu){
					$(l2menus[x]).addClass("selected");
					$(l2menus[x]).children("div.level3navwrapper").slideDown();
				} else {
					$(l2menus[x]).removeClass("selected");
					$(l2menus[x]).children("div.level3navwrapper").slideUp();
				}
			}
		}
	},
	closeAllL2Menus: function(){
		var l2menus = $("li.level2:has(span.nav2arrow)");
		for(var x=0; x<l2menus.length; x++){
			if(l2menus[x].className.indexOf("selected") != -1){
				$(l2menus[x]).removeClass("selected");
				$(l2menus[x]).children("div.level3navwrapper").slideUp();
			}
		}
	},
	traceNavigationMenu: function(checkFilename) {
			// close all level 1 menus
			$("li.level1").each(function(){
				if (this.className.indexOf("selected") != -1) {
					$(this).removeClass("selected");
					/*					
					$(this).children("div.level2navwrapper").slideUp();
					$("span.navpicscroll").animate({
						top: "0px"
					}, invjs.menuSpeed);
					*/
				}
			})
			
			// close all level 2 menus
			invjs.closeAllL2Menus();

			// let's see how many slashes we have in link
			var split = checkFilename.split('/');
			var slashCount = split.length - 1;

			// we will build now seperate names for level 2 and 3,
			// to match them against links in menu <li> items
			// note : home is counted as level 1 here

			var secondLevelFileName = checkFilename;
			var thirdLevelFileName = checkFilename;

			if (slashCount >= 2) {
				secondLevelFileName =  split[0] + "/" + split[1] + ".html";

				if (slashCount >= 3) {
					thirdLevelFileName = split[0] + "/" + split[1] + "/" + split[2] + ".html";
				}

			}

			// now we have those two links extracted from original url, so we can try and match them

			// if any second level link in menu matches the one currently requested (stripped ver)
			// then open this menu
			$("li.level1 > a").each(function(){
				if (this.href.indexOf(secondLevelFileName) != -1) {
						var index = $("li.level1 > a.navheading").index(this);
						invjs.selectMenu(index);
				}

			});

			// if any third level link in menu matches the one currently requested (stripped ver)
			// then open this menu
			$("li.level2.hasSub > a").each(function(){
				if (this.href.indexOf(thirdLevelFileName) != -1) {
						var index = $("li.level2.hasSub > a").index(this);
						invjs.selectMenuL2(index);
				}

			});

	},
	setupUtils: function(){
		// search

		invjs.searchBoxText = $("div#utilities input#searchInput").val();
		$("div#utilities input#searchInput").unbind("focus").focus(function(){
			if($(this).val() == invjs.searchBoxText){
				$(this).val("");
			}
		})
		/*.unbind("blur").blur(function(){
			if($(this).val() == "") {
				$(this).val(invjs.searchBoxText);
			}
		});
		*/	

		$("#searchBoxForm #submitButton").unbind("click").click(function(){
			var searchText = $("div#utilities input#searchInput").val();
			if (searchText == "" || searchText == "Search") {
				invjs.popupMessage("Please type the word(s) you wish to search.");
				return false;
			}
			else {
				return true;
			}
		});

		// note : behaviour for other forms (search again/press) is moved to amendContentOnLoad

			
		// search again. (this should likely have been incorporated into the previous function, but this would have required changes to already supplied HTML, or more time than I have)
		/*
		invjs.searchAgainBoxText = $("input#searchAgainInput").val();
		$("input#searchAgainInput").unbind("focus").focus(function(){
			if($(this).val() == invjs.searchAgainBoxText){
				$(this).val("");
			}
		}).unbind("blur").blur(function(){
			if($(this).val() == ""){
				$(this).val(invjs.searchAgainBoxText);
			}
		});
		*/

		// country
		$("div#countryBox").unbind("click").click(function(){
	       if(invjs.countryOpened) {
			invjs.hideCountry();
			return false;
           }
		   else	 {
			invjs.openCountry();
			return false;
           }
		});

		//services
		$("div#services").unbind("click").click(function(){
	       if(invjs.servicesOpened) {
			invjs.hideServices();
			return false;
           }
		   else	 {
			invjs.openServices();
			return false;
           }
		});
	},
	setupDropdowns: function(){
		var countryLeft = $("#countryBoxInner").offset().left;
		var countryTop = $("#countryBoxInner").offset().top +20;
		$("div#countryBoxOpened").remove().appendTo("body").css({left: countryLeft+"px", top: countryTop+"px"});

		var servicesLeft = $("#servicesInner").offset().left;
		var servicesTop = $("#servicesInner").offset().top +20;
		$("div#servicesOpened").remove().appendTo("body").css({left: servicesLeft+"px", top: servicesTop+"px"});

		// and attach behaviours
		$(".countryClose, #countryBoxOpenedInner .countryTrigger").unbind("click").click(function(){
			invjs.hideCountry();
			return false;
		});
		$(".servicesClose, #servicesOpenedInner .servicesTrigger").unbind("click").click(function(){
			invjs.hideServices();
			return false;
		});

		$("#countryBoxOpened .current img").remove().addClass("show").appendTo("#countryList ul li:last");

		/* this is turned off, we cannot use it
		$("#countryList ul li a").click(function(){
			// this function purely here to manipulate the body class and demonstrate changing the bg image
			var wCountry = $(this).text();
			wCountry = wCountry.toLowerCase().replace(" ","");

			// this line may need changing if other classes are ever needed on the body tag, as the first thing this does is to clear it
			$("body").attr("class","").addClass(wCountry);

			$("#countryList ul li").removeClass("current");
			$(this).parents("li").addClass("current");

			//return false;
		});
		*/
		//piochoo start
		//$("#countryList ul li a").unbind("click").click(function(){
		//	
		//	createCookie("user_selected_country_page",
		//			escape( this.href), cookieExpirationTime);
		//	return true;
		//	
		//});
		//piochoo end
	},
	openCountry: function(){
		invjs.hideServices();
		$("div#countryBoxOpened").show();
		invjs.countryOpened = true;
	},
	hideCountry: function(){
		$("div#countryBoxOpened").hide();
		invjs.countryOpened = false;
	},
	openServices: function(){
		invjs.hideCountry();
		$("div#servicesOpened").show();
		invjs.servicesOpened = true;
	},
	hideServices: function(){
		$("div#servicesOpened").hide();
		invjs.servicesOpened = false;
	},
	leadingZero: function(i){
		if (i<10) {
			i="0" + i;
		}
		return i;
	},
	setupSharesbar: function(open){
		$("div#sharesMenu").show();
		invjs.setTime();
		var t=setInterval('invjs.setTime()',60000);

		invjs.writeExpandLink();
		// moved into component body -- start
		//$("#sharesMenuInner #currency table tr:odd, #sharesMenuInner #indices table tr:odd, #sharesMenuInner #prices table tr:even:not(:first)").css("background","#fdfdfd");
		// moved into component -- end
		var disclaimerHeight = $("#disclaimer").length > 0 ? 14 : 0;
		invjs.sharesOpen = 0;
		$("div#sharesMenu, div#sharesMenuInner, div#sharesMenuInner div.tableWrapper").height(50+disclaimerHeight).css("overflow","hidden");
		
		//$("div#sharesMenuInner div table").css("overflow", "hidden");
		//$("div#sharesMenuInner div#greeting table, div#sharesMenuInner div#currency table>tr:gt(1), div#sharesMenuInner div#indices table>tr:gt(1), div#sharesMenuInner div#prices table>tr:gt(0)").css("display", "none");

		if(open == 1){
			invjs.clickExpandLink();
		}
	},
	setTime: function(){
		if (!isChooseUserType) {
			worldClock();
		}
	},
	writeExpandLink: function(){
		$("div#sharesMenuInner div h5 span").unbind("click").click(function(){
			$(this).blur();
			invjs.clickExpandLink();
			return false;
		});
	},
	clickExpandLink: function(){
		$("div#sharesMenuInner div h5 span").toggleClass("opened");
		$("div#sharesMenuInner table").toggleClass("opened");
		var wTop = parseInt($("div#sharesMenu").css("top"));

		if(invjs.sharesOpen == 0){

			invjs.sharesOpen = 1;
			var disclaimerHeight = $("#disclaimer").length > 0 ? 14 : 0;
			$("div#sharesMenu, div#sharesMenuInner, div#sharesMenuInner div, div#sharesMenuTrigger").height(160+disclaimerHeight);
			$("div#sharesMenu, div#sharesMenuTrigger").css("top",(wTop-110)+"px");


			//$("div#sharesMenuInner div.tableWrapper").height(136).css("overflow-y", "auto");
			$("div#sharesMenuInner div.tableWrapper").height(136).css("overflow-y", "hidden");

			//$("div#sharesMenuInner div#greeting table, div#sharesMenuInner div#currency table tr, div#sharesMenuInner div#indices table tr, div#sharesMenuInner div#prices table tr").css("display", "table-row");
			$("div#sharesMenuInner div#greeting table").css('display','block');

			$("#prices .tableWrapper div").css("height","auto");
			$("#prices .tableWrapper div").css("clear","both");

		} else {
			invjs.sharesOpen = 0;
			var disclaimerHeight = $("#disclaimer").length > 0 ? 14 : 0;
			$("div#sharesMenu, div#sharesMenuInner, div#sharesMenuInner div, div#sharesMenuTrigger").height(50+disclaimerHeight);
			$("div#sharesMenu, div#sharesMenuTrigger").css("top",(wTop+110)+"px");

			$("div#sharesMenuInner div.tableWrapper").css("overflow-y", "hidden");
			//$("div#sharesMenuInner div#greeting table, div#sharesMenuInner div#currency table>tr:gt(1), div#sharesMenuInner div#indices table>tr:gt(1), div#sharesMenuInner div#prices table>tr:gt(0)").css("display", "none");
			$("div#sharesMenuInner div#currency table>tr:gt(1), div#sharesMenuInner div#indices table>tr:gt(1), div#sharesMenuInner div#prices table>tr:gt(0)").css("display", "none");
			$("div#sharesMenuInner div#greeting table").css("display","none");
		}

	},
	alterEditFieldsBehaviour: function(){
		$("input[type='text']").unbind("click");
		$("input[type='text']").click( function() {
			$(this).select();
		});
		$("textarea").unbind("click");
		$("textarea").click( function() {
			$(this).select();
		});

		$("div.formPageWrapper input[type='text']").unbind("click");
		$("div.formPageWrapper textarea").unbind("click");
	},
	amendContentOnLoad: function(wAnchor){

		$("input.rollImg").unbind("mouseover").unbind("mouseout").mouseover(function(){
			$(this).attr("src", $(this).attr("src").replace(".gif", "_Roll.gif") );
		}).mouseout(function(){
			$(this).attr("src", $(this).attr("src").replace("_Roll.gif", ".gif") );
		});

		$("input.rollReset").unbind("mouseover").unbind("mouseout").mouseover(function(){
			$(this).attr("style", $(this).attr("style").replace(".gif", "_Roll.gif") );
		}).mouseout(function(){
			$(this).attr("style", $(this).attr("style").replace("_Roll.gif", ".gif") );
		});

		$("a.rollImg").unbind("mouseover").unbind("mouseout").mouseover(function(){
			$(this).find("img").attr("src", $(this).find("img").attr("src").replace(".gif", "_Roll.gif") );
		}).mouseout(function(){
			$(this).find("img").attr("src", $(this).find("img").attr("src").replace("_Roll.gif", ".gif") );
		});

		$(".rollCss").unbind("mouseover").unbind("mouseout").mouseover(function(){
			$(this).css("background-image", $(this).css("background-image").replace(".gif", "_Roll.gif") );
		}).mouseout(function(){
			$(this).css("background-image", $(this).css("background-image").replace("_Roll.gif", ".gif") );
		});

		// moved to quoteBox component
		//$("div.quoteBox").prepend('<div class="openQuote">&ldquo;</div>').append('<div class="closeQuote">&rdquo;</div>');

		$("div.blogPost:last").addClass("lastPost");

		$("div.libraryItemRow:nth-child(even)").addClass("shaded");

		$("div.sharePriceItemRow:nth-child(even)").addClass("shaded");

		$("div.sharePerformanceContentBlock table tr:nth-child(even)").addClass("shaded");
		$("table#sharePriceTable tbody tr:even").addClass("stripe");
		$("table.collapsible tbody").each(function(){
			$(this).children("tr:not(:has(td.subhead)):odd").addClass("stripe");
		});

		$("table.collapsible tr.collapseHeader th").unbind("click").click(function(){
			$(this).parents("table").find("tbody").toggle();
			$(this).parents("table").find("tr.collapseHeader").each(function(){
				$(this).children("th:gt(0)").toggle();
				$(this).children("th:first").toggleClass("arrowDown").toggleClass("arrowUp");
			});
		});

		$("table.collapsible tr.collapseHeader th:nth-child(1)").addClass('arrowDown');

		invjs.alterEditFieldsBehaviour();

		// trim empty P from richtexts
		$("div.pageCopy p").each(function() {
			var inside = $.trim($(this).html());
			if ( inside.length < 1 || (inside.length == 1 && inside == " ") || (inside.length == 6 && inside == "&nbsp;") ) { 
				$(this).remove();
			}
		});   

		$("#searchAgainBox #searchAgainButton").unbind("click").click(function(){
			var searchText = $("#searchAgainBox #searchAgainInput").val();
			if (searchText == "" || searchText == "Search") {
				invjs.popupMessage("Please type the word(s) you wish to search.");
				return false;
			}
			else {
				return true;
			}
		});

		$("#searchPressReleasesBox #searchButton").unbind("click").click(function(){
			var searchText = $("#searchPressReleasesBox #searchAgainInput").val();
			if (searchText == "" || searchText == "Search") {
				invjs.popupMessage("Please type the word(s) you wish to search.");
				return false;
			}
			else {
				return true;
			}
		});

		// grab all forms with class of AJAXForm and make them submit via AJAX
		$("form.AJAXForm").submit(function(){
			$("div#progressIcon").css("display","block");
			var action = $(this).attr("action").replace(".html",".ajax.html");

			$.ajax({
				type: 		$(this).attr("method"),
				url: 		action,
				data: 		$(this).serialize(),
				success: 	function(msg){
					invjs.contentSquirtFromSource(msg);
				},
				error: 		function(msg){
					invjs.popupMessage(getFormSubmitError());
				}
			});
			return false;
		});

		$("form.AJAXFormSearchContact").submit(function(){
			$("div#progressIcon").css("display","block");

			var action = $(this).attr("action").replace(".html",".ajax.html");

			queryString = $(this).serialize();				
							
			var hash = getSearchContactsProviderUrl();
			var hashIndex = hash.indexOf(invjs.jspath) + invjs.jspath.length;
			hash = hash.substring(hashIndex);		
		
			window.location.hash = hash + "?" + queryString + "&searchId=" + Math.round(Math.random() * 10000000);;

			return false;
		});

		$("form.AJAXFormSearch").submit(function(){	

			// this block, up to unbind section will be bound twice to this form submit
			// it's not easy to unbind this properly assuming the page won't reload	
			// so i'm allowing it to run twice, but popup is shown only first time
			// second time it detects that it's already shown and do not open it again

			var searchText = "";

			var id = this.id;
			if (id == "searchBoxForm") {
				searchText = $("div#utilities input#searchInput").val();
			}	
			else {
				searchText = $("#searchAgainBox #searchAgainInput").val();
			}

			if (searchText == "" || searchText == "Search") {
				if (!invjs.popupShown) {
					invjs.popupMessage("Please type the word(s) you wish to search.");
				}
				return false;
			}

			// parent function (amendContentOnLoad is called everytime a page loads (from setContentArea),
			// therefore, forms being outside of mainContent (in Ajax Shell) would get this binding twice	
            // (note : shouldn't this be moved to success section? submit not always guarantee calling amendContentonLoad)
			
			$("form.AJAXFormSearch").unbind("submit");
			
			$("div#progressIcon").css("display","block");

			var hash = getSearchProviderUrl();
			var hashIndex = hash.indexOf(invjs.jspath) + invjs.jspath.length;
			hash = hash.substring(hashIndex);

			// lets strip ".default" from original handler, because in paging it is sent without this selector 
			// it's passed via querystring.

			var generalHash = hash;
			var selectorIndex = generalHash.indexOf(".default");

			if (selectorIndex != -1) {
				generalHash = generalHash.substring(0, selectorIndex) + ".html";
			}

			window.location.hash = generalHash + "?query=" + searchText + "&searchId=" + Math.round(Math.random() * 10000000);

			return false;
		});

		$("form.AJAXFormSearchPress").submit(function(){

			var searchText = "";

			if ( $("#searchAgainBox").size() > 0 ) {
				searchText = $("#searchAgainBox #searchAgainInput").val();
			}	
			else if ( $("#searchPressReleasesBox").size() > 0 ) {
				searchText = $("#searchPressReleasesBox #searchAgainInput").val();
			}

			if (searchText == "" || searchText == "Search") {
				invjs.popupMessage("Please type the word(s) you wish to search.");
				return false;
			}
			
			$("div#progressIcon").css("display","block");

			var hash = getSearchPressProviderUrl();
			var hashIndex = hash.indexOf(invjs.jspath) + invjs.jspath.length;
			hash = hash.substring(hashIndex);

			window.location.hash = hash + "?query=" + searchText + "&searchId=" + Math.round(Math.random() * 10000000);;;

			return false;
		});

		invjs.setupPopupForms();

		invjs.setupRelatedArticles();

		// this is called from breadcrumb component now;
		// invjs.setupBreadcrumbPopup();

		invjs.locateFooterLinks();

		// since the page content will be loaded via ajax, scripts can no longer run in the head of each page
		// therefore page specific JS must be applied at this stage, and is stored in pageScripts.js
		// and run here after checking the class of the ajaxContainer div for additional classes which then
		// indicate extra scripts to run.

		var wClass = $("div.ajaxContainer").attr("class");
		if(wClass){
			// using untidy if statements purely for speed
		if(wClass.indexOf("basicContentVideo") != -1){
			basicContentVideo.init();
		}
		if(wClass.indexOf("mapPage") != -1){
			officeLoc.init();
		}
		if(wClass.indexOf("pressReleases") != -1){
			pressReleases.init();
		}
		if(wClass.indexOf("singleVideo") != -1){
			singleVideo.init();
		}
		if(wClass.indexOf("sitemap") != -1){
			sitemap.init();
		}
		if(wClass.indexOf("tombstone") != -1){
			tombstone.init();
		}
			if(wClass.indexOf("galleryPage") != -1){
				gallery.init();
			}
		}
		if(wAnchor){
			if(wAnchor != "undefined"){
				setTimeout("invjs.scrollToAnchor('"+wAnchor+"')", 500);
			}
		}
	},
	scrollToAnchor: function(wAnchor) {
		//var aO = $("#"+wAnchor).offset().top;
		
		var aO;
		if (invjs.isie) {			
			$(".pageContent a").each(function(){
				if (this.name == wAnchor) {
					aO = $(this).offset().top;				
				}
			});
		}
		else {
			aO = $("a[name="+wAnchor+"]").offset().top;
		}

		var cO = $("div.pageContent").offset().top;
		var cS = $("div.pageContent:first").scrollTop();
		var scrollTarg = aO+cS-cO;
		if(wAnchor == "top"){
			scrollTarg = 0;
		}
		$("div.pageContent").animate({
			scrollTop: 		scrollTarg
		}, 250);
	},
	setupPopupForms: function(){
		$(".officeDetails a.emailMeLink, ul.contactLinks a.emailMeLink, div.person div.details a.email").unbind("click").click(function(){
			$("div#dialog").remove();
			$("body").append('<div id="dialog"></div>');

			$("#dialog").dialog({
				title: 			getEmailMeHeader(), 
				modal: 			true,
				draggable: 		false,
				resizable: 		false,
				width: 			279,
				height: 		220,
				overlay: 		{
					opacity: 		0.7,
					background: 	"white"
				},
				open: 			function(){
					$(".ui-dialog-overlay").unbind("click").unbind("dblclick").click(function(){
						$("#dialog").dialog("close");
						return false;
					});
				},
				close: 			function(){
					$(this).dialog("destroy");
					$("#dialog").remove();
				}
			});
			$("#dialog").resizable("destroy");

			// need to additionally grab the person this applies to, i.e. the person the email will go to
			var toName = $(this).attr("data");
			var toEmail = $(this).attr("emaildata");
			//toName = toName.substring(toName.indexOf(":")+1);

			$("div#dialog").load(getPopupPage('email') + ' #popupContainer', {}, function(){
				invjs.alterEditFieldsBehaviour();
				invjs.setupEmailForm(toName, toEmail);
			});

			return false;
		});
		$(".officeDetails a.requestCallbackLink, ul.contactLinks a.requestCallbackLink, div.person div.details a.tel").unbind("click").click(function(){
			$("div#dialog").remove();
			$("body").append('<div id="dialog"></div>');

			$("#dialog").dialog({
				title: 			getCallbackHeader(), 
				modal: 			true,
				draggable: 		false,
				resizable: 		false,
				width: 			279,
				height: 		160,
				overlay: 		{
					opacity: 		0.7,
					background: 	"white"
				},
				open: 			function(){
					$(".ui-dialog-overlay").unbind("click").unbind("dblclick").click(function(){
						$("#dialog").dialog("close");
						return false;
					});
				},
				close: 			function(){
					$(this).dialog("destroy");
					$("#dialog").remove();
				}
			});
			$("#dialog").resizable("destroy");

			// need to additionally grab the person this applies to, i.e. the person the email will go to
			var toName = $(this).attr("data");
			var toEmail = $(this).attr("emaildata");
			//toName = toName.substring(toName.indexOf(":")+1);

			$("div#dialog").load(getPopupPage('callback') + ' #popupContainer', {}, function(){
				invjs.alterEditFieldsBehaviour();
				invjs.setupCallbackForm(toName, toEmail);
			});

			return false;
		});
	},
	setupRelatedArticles: function(){
		var numArts = $("div.relatedWrapper div.relatedInner").length;
		if(numArts % 2 != 0){
			$("div.relatedWrapper").append('<div class="relatedInner"></div>');
			numArts++;
		}
		//alert(numArts);

		var scrollSize = 114;

		$("a#moreArticles").click(function(){
			invjs.scrollArticles(scrollSize, (numArts-2)*scrollSize/2);
			return false;
		});
	},
	scrollArticles: function(scrollSize, maxScroll){
		var theWrapper = $("div.relatedWrapper:first");
		var currScroll = theWrapper.scrollTop();

		var scrollTarg = (currScroll >= maxScroll) ? 0 : scrollSize+currScroll;

		$("div.relatedWrapper").animate({
			scrollTop: 	scrollTarg
		}, 250);
	},
	setupBreadcrumbPopup: function(){
		var startLinks = getBreadrcumbHead(); 	// does not include home link
		var endLinks = getBreadrcumbTail(); 		// does not include the non-linked current page

		var totalLinks = $("div#breadcrumb a").length;

		if(totalLinks > (startLinks + endLinks + 1)){
			$("div#breadcrumbPopup").css("display","none");

			var bPos = $("div#breadcrumb").offset();
			var bOffset = 5;
			$("div#breadcrumbPopup").html( $("div#breadcrumb").html() ).css("left",(bPos.left+bOffset)+"px").css("top",(bPos.top+bOffset)+"px").mouseout(function(e){
				// need to check mouse position against coords of breadcrumbPopup to check if it has left
				var x = e.pageX - this.offsetLeft;
				var y = e.pageY - this.offsetTop;
				var w = $("div#breadcrumbPopup").width() + parseInt( $("div#breadcrumbPopup").css("padding-left") ) + parseInt( $("div#breadcrumbPopup").css("padding-right") );
				var h = $("div#breadcrumbPopup").height() + parseInt( $("div#breadcrumbPopup").css("padding-top") ) + parseInt( $("div#breadcrumbPopup").css("padding-bottom") );

				if(x<0 || x>w || y<0 || y>h){
					$(this).hide();
				}
			});



			$("div#breadcrumb a:lt("+(totalLinks-endLinks)+"):gt("+(startLinks+1)+")").remove();
			$("div#breadcrumb span:lt("+(totalLinks-endLinks)+"):gt("+(startLinks+1)+")").remove();
			$("div#breadcrumb a:eq("+(startLinks+1)+")").text("...").attr("href",null).attr("rel",null).mouseover(function(){
				// reveal breadcrumb popup
				$("div#breadcrumbPopup").show();
				$("div#breadcrumbPopup").css("z-index","100");
				$("div#breadcrumbPopup").css("display","block");
			});
		}
		
		if (!isCQEditMode() && !isCQEditCollapsedMode()) {
			$("#breadcrumb *:not(:first)").hide();  /* <INVESTECAFTERCARE-108 /> */
		}
	},
	setupTools: function(){
 		// $("div#pageTools li").show(); /* <INVESTECAFTERCARE-108 /> */
		$("#textLarger").click(function(){
			if(invjs.fontAdjust < 3) {
				invjs.fontAdjust++;
				$("div.pageContent").css("font-size", ((invjs.fontAdjust*10)+100)+"%");
				$("div.pageContent table *").css("font-size","10px");
				invjs.locateFooterLinks();
			}
			return false;
		});
		$("#textNormal").click(function(){
			if(invjs.fontAdjust > 0) {
				invjs.fontAdjust--;
				$("div.pageContent").css("font-size", ((invjs.fontAdjust*10)+100)+"%");
				$("div.pageContent table *").css("font-size","10px");
 			  invjs.locateFooterLinks();
			}
			return false;
		});

		$("#pageTools #libraryLink").unbind("click").click(function(){
			invjs.transferring = 1;
			var transTarg = (invjs.libOpen == 0) ? "#libMenuTrigger" : "#savedDocsChunk h3";

			// store user library links in cookies
			// key=LIBLINK_escaped page url, value=page title
			var url = invjs.getPageUrlWithQuery();
			url = url.substring(url.indexOf(getPageExternalizedHandle()), url.length);

			var title = shortenTitle(getPageTitle()); // was : $("#pageHeader h1").text();

			// add link to library only if this link is not already added
			var cookie = readCookie(linkCookiePrefix+escape(url));

			if (cookie == null) {
				$(".ajaxContainer").effect("transfer", { to: transTarg }, 1000, function(){
					var li_count = 0;
					$("#savedDocsChunk #savedDocsContent ul li").each(function(){
						++li_count;
					});
					var ul = $("#savedDocsChunk #savedDocsContent ul");
					if (ul[0] == null) {
						$("#savedDocsChunk #savedDocsContent").removeAttr("style");
						$("#savedDocsChunk #savedDocsContent").append("<ul></ul>");
					}
					if (li_count > 3) {
						$("#savedDocsChunk #savedDocsContent ul li:last").remove();
					}
					$("#savedDocsChunk #savedDocsContent ul").prepend('<li><a rel="a" href="'+url+'" onclick="var s_objectID=\'LIBRARY|'+ url +'\';">'+title+'</a></li>');
					$("#savedDocsChunk #savedDocsContent ul li:first").effect("highlight", {}, 3000);
					invjs.transferring = 0;
				});

				// library items are stored in cookies
				if (title.length == 0) {
					var lastDotIdx = url.lastIndexOf(".");

					title = url.substring(url.substring(0,lastDotIdx).lastIndexOf("/")+1,lastDotIdx);
				}

				// create cookie with expiration time read from configuration page (passed by global var)
				createCookie(linkCookiePrefix+escape(url), escape(title), cookieExpirationTime);
			} else {
				invjs.popupMessage(getLibraryAlreadyAddedMessage());
			}

			/*
			$.ajax({
				type: 		"POST",
				url: 		"inc/addToLibraryHandler.php", // demo file included purely to trigger success method
				data: 		"url="+url+"&title="+title,
				success: 	function(msg){
					//alert( "Data Sent: " + msg ); // uncomment this line for debug
				},
				error: 		function(msg){
					//alert( "Error: " + msg ); // uncomment this line for debug
				}
			});
			*/

			return false;
		});

		$("#pageTools #emailLink").unbind("click").click(function(){
			$("div#dialog").remove();
			$("body").append('<div id="dialog"></div>');

			$("#dialog").dialog({
				title: 			getSendToFriendHeader(), 
				modal: 			true,
				draggable: 		false,
				resizable: 		false,
				width: 			279,
				height: 		270,
				overlay: 		{
					opacity: 		0.7,
					background: 	"white"
				},
				open: 			function(){
					$(".ui-dialog-overlay").unbind("click").unbind("dblclick").click(function(){
						$("#dialog").dialog("close");
						return false;
					});
				},
				close: 			function(){
					$(this).dialog("destroy");
					$("#dialog").remove();
				}
			});
			$("#dialog").resizable("destroy");

			//var page = getPageHandle(); //this function is placed in contentToolbar.jsp
			$("div#dialog").load(getPopupPage('sendtofriend') + ' #popupContainer', {}, function(){
				invjs.alterEditFieldsBehaviour();
				invjs.setupSendForm();
			});

			return false;
		});

		$("#pageTools #shareLink").unbind("click").click(function(){
			$("div#dialog").remove();
			$("body").append('<div id="dialog"></div>');

			$("#dialog").dialog({
				title: 			"Social bookmarks", 
				modal: 			true,
				draggable: 		false,
				resizable: 		false,
				width: 			279,
				height: 		220,
				overlay: 		{
					opacity: 		0.7,
					background: 	"white"
				},
				open: 			function(){
					$(".ui-dialog-overlay").unbind("click").unbind("dblclick").click(function(){
						$("#dialog").dialog("close");
						return false;
					});
				},
				close: 			function(){
					$(this).dialog("destroy");
					$("#dialog").remove();
				}
			});
			$("#dialog").resizable("destroy");

			$("div#dialog").load(getPopupPage('social') + ' #popupContainer', {}, function(){
				invjs.setupSocialBookmarks();
			});

			return false;
		});

		$("#pageTools #printLink").unbind("click").click(function(){
			window.open(invjs.getPrintPageUrlWithQuery(),"",'menubar=no, toolbar=no, location=no, scrollbars=yes, status=no, width=860, height=600');
			return false;
		});
		/*
		$("#pageTools #downloadLink").unbind("click").click(function(){
			window.open(getPdfPage(),"",'menubar=no, toolbar=no, location=no, scrollbars=yes, status=no, width=800, height=600');
			return false;
		});
		*/
	},
	setupSendForm: function(){
		$("form#popupFriendForm").submit(function(){
			return false;
		});
		$("form#popupFriendForm input#submit").unbind("click").click(function(){

			var name = $("#popupFriendForm #name").val();
			var email = $("#popupFriendForm #email").val();
			var friendName = $("#popupFriendForm #friendname").val();
			var friendEmail = $("#popupFriendForm #friendemail").val();
			var message = $("#popupFriendForm #message").val();
			var type = $("#popupFriendForm #type").val();
			var pageUrl = invjs.getPageUrlWithQuery();
			var pageName = getPageTitle();
			
			// message length validation
			var msgLimit = 140;
			if (message.length > msgLimit) {
				alert("Message must be shorter than "+msgLimit+" characters.");
				return false;
			}

			$.ajax({
				type: 		"POST",
				url: 		getFormPage(),
				data: 		"pageUrl="+(encodeURIComponent(pageUrl))+"&pageName="+(encodeURIComponent(pageName))+"&name="+encodeURIComponent(name)+"&email="+encodeURIComponent(email)+"&friendname="+encodeURIComponent(friendName)+"&friendemail="+encodeURIComponent(friendEmail)+"&message="+encodeURIComponent(message)+"&type="+type,
				success: 	function(msg){
					// alert( "Data Sent: " + msg ); // uncomment this line for debug
					$("#dialog").dialog("close");
					invjs.popupMessage(getSendToFriendSuccess());
				},
				error: 		function(msg){
					// alert( "Error: " + msg ); // uncomment this line for debug
					$("#dialog").dialog("close");
					invjs.popupMessage(getSendToFriendError());
				}
			});
		});
	},
	setupEmailForm: function(toName, toEmail){
		$("form#popupEmailForm").submit(function(){
			return false;
		});

		$("form#popupEmailForm input#submit")

		var varScript="<script>var popupEmailAddress='"+toEmail+"'";
        varScript+="<";
        varScript+="/script>";

		$("div#popupContainer").prepend(varScript);

		$("form#popupEmailForm input#submit").unbind("click").click(function(){

			var name = $("#popupEmailForm #name").val();
			var email = $("#popupEmailForm #email").val();
			var message = $("#popupEmailForm #message").val();
			var type = $("#popupEmailForm #type").val();
			var pageUrl = getPageUrl();
			var pageName = getPageTitle();

			$.ajax({
				type: 		"POST",
				url: 		getFormPage(), 
				data: 		"pageUrl="+encodeURIComponent(pageUrl)+"&pageName="+encodeURIComponent(pageName)+"&toName="+encodeURIComponent(toName)+"&name="+encodeURIComponent(name)+"&email="+encodeURIComponent(email)+"&message="+encodeURIComponent(message)+"&type="+type,
				success: 	function(msg){
					//alert( "Data Sent: " + msg ); // uncomment this line for debug
					$("#dialog").dialog("close");
					invjs.popupMessage(getEmailMeSuccess());
				},
				error: 		function(msg){
					//alert( "Error: " + msg ); // uncomment this line for debug
					$("#dialog").dialog("close");
					invjs.popupMessage(getEmailMeError());
				}
			});
		});
	},
	setupCallbackForm: function(toName, toEmail){
		$("form#popupCallbackForm").submit(function(){
			return false;
		});

		var varScript="<script>var popupEmailAddress='"+toEmail+"'";
        varScript+="<";
        varScript+="/script>";
		$("div#popupContainer").prepend(varScript);

		$("form#popupCallbackForm input#submit").unbind("click").click(function(){
			// clear errors:
			$("div#calltimeBorder").removeClass("errorField");
			$("input").removeClass("errorField");
			$("label#errorMessage").text("").hide();

			var name = $("#popupCallbackForm #name").val();
			var phone = $("#popupCallbackForm #phone").val();
			var calltime = $("#popupCallbackForm #calltime").val();
			var type = $("#popupCallbackForm #type").val();
			var pageUrl = getPageUrl();
			var pageName = getPageTitle();
			
			var clearPhone = phone.replace(/[\s()-]/g,'');
			if(!invjs.isInternationalPhoneNumber(clearPhone)){
				$("input#phone").addClass("errorField");
				if(invjs.isNonInternationPhoneNumber(clearPhone)){
					$("label#errorMessage").text(getCallbackNoCountryCodeInPhone()).fadeIn("slow");	
				}else{
					$("label#errorMessage").text(getCallbackNoPhone()).fadeIn("slow");
				}
				return false;
			}

			if(calltime == "none") {
				$("label#errorMessage").text(getCallbackNoTime()).fadeIn("slow");
				$("div#calltimeBorder").addClass("errorField");
				return false;
			}
			
			$.ajax({
				type: 		"POST",
				url: 		getFormPage(), 
				data: 		"pageUrl="+encodeURIComponent(pageUrl)+"&pageName="+encodeURIComponent(pageName)+"&toName="+encodeURIComponent(toName)+"&name="+encodeURIComponent(name)+"&phone="+encodeURIComponent(phone)+"&calltime="+encodeURIComponent(calltime)+"&type="+type,
				success: 	function(msg){
					//alert( "Data Sent: " + msg ); // uncomment this line for debug
					$("#dialog").dialog("close");
					invjs.popupMessage(getCallbackSuccess());
				},
				error: 		function(msg){
					//alert( "Error: " + msg ); // uncomment this line for debug
					$("#dialog").dialog("close");
					invjs.popupMessage(getCallbackError());
				}
			});
		});
	},
	isNonInternationPhoneNumber: function(phone){
		return (3 <= phone.length) && (phone.length <= 19) && (phone.match(/^[1-9]{1}(\d){2,18}$/));		
	},
	isInternationalPhoneNumber: function(phone){
		return (4 <= phone.length) && (phone.length <= 21) && (phone.match(/^((\+{1})|(0{2}[1-9]{1}))(\d){3,19}$/));
	},
	setupSocialBookmarks: function(){
		$("ul#socialBookmarks li a").each(function(){
			var url = $(this).attr("href");
			var thisPageUrl = invjs.getPageUrlWithQuery();

			// attempt to add hash in proper place. Succeded but you cant send # in GET, most
            // social sites don't accept it
//			var hashIndex = thisPage.indexOf(invjs.jspath) + invjs.jspath.length;
//			thisPage = thisPage.substring(0, hashIndex) + "&#35;" + thisPage.substring(hashIndex);

			var thisPageTitle = getPageTitle(); // was : $("#pageHeader h1").text();
			thisPageUrl = thisPageUrl.replace(/&/g,"AMPERSAND");
			url = encodeURI(url.replace(/INSURL/, thisPageUrl).replace(/INSTITLE/, thisPageTitle));
			url = url.replace(/AMPERSAND/g, "%26");
			$(this).attr("href", url).attr("target", "_blank").unbind("click").click(function(){
				$("#dialog").dialog("close");
			});
		});
	},
	popupMessage: function(wText){
		$("div#dialog").remove();
		$("body").append('<div id="dialog"><div id="popupMessage">'+wText+'</div></div>');

		$("#dialog").dialog({
			title: 			getPopupMessageHeader(), 
			modal: 			true,
			draggable: 		false,
			resizable: 		false,
			width: 			279,
			height: 		90,
			overlay: 		{
				opacity: 		0.7,
				background: 	"white"
			},
			open: 			function(){
				invjs.popupShown = true;
				$(".ui-dialog-overlay").unbind("click").unbind("dblclick").click(function(){
					$("#dialog").dialog("close");
					return false;
				});
			},
			close: 			function(){
				invjs.popupShown = false;
				$(this).dialog("destroy");
				$("#dialog").remove();
			}
		});
		$("#dialog").resizable("destroy");

		return false;
	},
	setupTabs: function(){
		var tabs = $("div.pageTab");
		invjs.numTabs = tabs.length;
		if(invjs.numTabs > 5) {
	
			var omnitureString="onClick=\""
			+ "s_objectID='JS_ACTION_TAB_MANIPULATION';"
			+ "var s=s_gi(s_account);"
			+ "s.linkTrackVars='events,eVar4,prop16';"
			+ "s.linkTrackEvents='event7';"
			+ "s.events='event7';"
			+ "s.eVar4=s.prop16;"
			+ "s.tl(true, 'o', 'TAB_LEFT_RIGHT_MANIPULATION');\"";

			$("div#pageTabs").append('<div class="tabControl"><span id="previousTab" '+omnitureString+'></span></div><div class="tabControl"><span id="nextTab" '+omnitureString+'></span></div>');
			$("div.pageTab:gt(4)").hide();
			//invjs.selectedTab = $("div.pageTab").index( $(".current")[0] );
			invjs.selectedTab = $("div#pageTabs > div").index( $("div.current") );

			$("#previousTab").unbind("click").click(function(){
				invjs.scrollTabs(-1); // -1 for left
				$(this).blur();
			});
			$("#nextTab").unbind("click").click(function(){
				invjs.scrollTabs(1); // 1 for right
				$(this).blur();
			});

			$("span#previousTab").addClass("disabled");	

			// tabScrollPos is not remebmered when opening new tab
			invjs.tabScrollPos = 0;
			if(invjs.selectedTab >= 5){
				var wDiff = invjs.selectedTab-4;
				invjs.scrollTabs(wDiff);
			}		
			
			// tabScrollPos remembered and changed only when needed
			//var wDiff = 0;
			//if (invjs.prevNumTabs != invjs.numTabs) {				
			//	invjs.tabScrollPos = 0;	
			//}
			//if(invjs.selectedTab > 4 + invjs.tabScrollPos) {
			//	invjs.tabScrollPos = 0;
			//	wDiff = invjs.selectedTab-4;
			//}
			//if(invjs.selectedTab < invjs.tabScrollPos) {
			//	invjs.tabScrollPos = 0;
			//	wDiff = invjs.selectedTab;
			//}
			//invjs.scrollTabs(wDiff);
			//invjs.prevNumTabs = invjs.numTabs;
		}
	},
	scrollTabs: function(adj){
		if((invjs.tabScrollPos+adj >= 0) && (invjs.tabScrollPos+adj+5 <= invjs.numTabs)) {
			invjs.tabScrollPos += adj;
			var tabs = $("div.pageTab");
			for(var x=0; x<invjs.numTabs; x++){
				if((x<invjs.tabScrollPos) || (x>invjs.tabScrollPos+4)) {
					$(tabs[x]).hide();
				} else {
					$(tabs[x]).show();
				}
			}
		}
		if(invjs.tabScrollPos == 0){
			$("span#previousTab").addClass("disabled");
		} else {
			$("span#previousTab").removeClass("disabled");
		}
		if(invjs.tabScrollPos == invjs.numTabs-5){
			$("span#nextTab").addClass("disabled");
		} else {
			$("span#nextTab").removeClass("disabled");
		}
	},

	setupTooltips: function(){
		//var ttTrack = ((invjs.isie) && (parseInt(invjs.browserVer) < 7)) ? false : true; // was being used to switch tracking off for IE6 only

		$("ul.dataTypes a, div#pageTools span").tooltip({
			delay: 			1, /* <INVESTECAFTERCARE-118 /> */
			showURL: 		false,
			top: 			-48,
			left: 			-30,
			track: 			false
		});

		/* <INVESTECAFTERCARE-118> */
		$("#outerContainer, #contentOuter").mouseover(function(){
			$("#tooltip").hide();
		});
	},	/* </INVESTECAFTERCARE-118> */

	externaliseLinks: function(){
		if(invjs.externalLinksInNewWindow){
			$("a[href^='http://']").click(function(){
				$(this).attr("target","_blank");
			});
		}
	},
	ajaxifyAuthor: function() {
		var url = window.location.href;
		var indexOfHash = url.indexOf("#");

		if(indexOfHash != -1) {
			var uAnchor = url.substring(indexOfHash + 1, url.length);
			setTimeout("invjs.scrollToAnchor('"+uAnchor+"')", 2000);
		}

		$("a[href*='#']").each(function(){
			var wHref = $(this).attr("href");

			if( wHref.indexOf(invjs.jspath) != -1 ){
				wHref = wHref.substr( (wHref.indexOf(invjs.jspath) + invjs.jspath.length) );
			}

			if(wHref.length > 1){
				if( wHref.charAt(0) == "#"){ // it's on this page
					var uAnchor = wHref.substr(1);
					$(this).unbind("click").click(function(event){
							  event.preventDefault();
							  invjs.scrollToAnchor(uAnchor);
					});							
				} else { // it's on another page
					
				}
			}
		});
	},
	ajaxify: function(){

		$("a[href*='#']").each(function(){
			var wHref = $(this).attr("href");

			if( wHref.indexOf(invjs.jspath) != -1 ){
				wHref = wHref.substr( (wHref.indexOf(invjs.jspath) + invjs.jspath.length) );
			}

			if(wHref.length > 1){
				if( wHref.charAt(0) == "#"){ // it's on this page
					var uAnchor = wHref.substr(1);
					var currPage = window.location.hash.substr(1).split(invjs.anchorSeparatorChar)[0];
					$(this).attr("href", currPage + invjs.anchorSeparatorChar + uAnchor );
				} else { // it's on another page
					$(this).attr("href", wHref.replace("#", invjs.anchorSeparatorChar) );
				}
			}
		});

		// this function hangs the main ajax-powered page load mechanism onto all links with a rel attribute of "a"
		// but not ones that start with http://

		/* (FF ONLY) */
		$("a[rel='a']:not([href^=http://])").unbind("click").click(function(){
			if ((this.href.indexOf('/etc/medialib') == -1 ) && (this.href.indexOf('mailto:') == -1)) {
				invjs.urlHash(this.href);
				// INVEST-519
				invjs.userClicked = true;
				this.blur();
				return true;
			}
		});

		/* fix for 1st level navigation (FF ONLY) */
		$("a[rel='a'][class='navheading']").unbind("click").click(function(){
			var index = $("li.level1 > a.navheading").index(this);
			invjs.selectMenu(index);
			invjs.urlHash(this.href);
			this.blur();
			return true;
		});

		// INVEST-483
		/* fix for 2nd level navigation (FF ONLY) */
		$("li.level2.hasSub > a").unbind("click").click(function(){
			var index = $("li.level2.hasSub > a").index(this);
			invjs.selectMenuL2(index);
			invjs.urlHash(this.href);
			this.blur();
			return true;
		});


		// now those three again in IE (because those selectors won't pick up in IE)
		if (invjs.isie)	{
			var domain = getBrowserHostname();

			$("a[rel='a']").unbind("click").click(function(){
				var url = this.href;

				// we want to ajaxify links only from our domain and if not,
				// then those containing "+", as those most probably are anchors

				var beginsWithDomain = (url.indexOf("http://" + domain) != -1);
				var hasAnchor = (url.indexOf(invjs.anchorSeparatorChar) != -1);

				if (beginsWithDomain || (!beginsWithDomain && hasAnchor) ) {
					if (hasAnchor) {
						// this is special case for ie, which do not externalize anchor links
						var hashIndex = window.location.href.indexOf("#");
						if (hashIndex != -1) {
							var strippedUrl = $(this).attr("href");
							url = window.location.href.substring(0,hashIndex) + "#" + strippedUrl;
						}						
					}

					var clazzName = this.className;
					if (clazzName == "navheading") {
						var index = $("li.level1 > a.navheading").index(this);
						invjs.selectMenu(index);
					}

					if ((url.indexOf('/etc/medialib') == -1) && (url.indexOf('mailto:') == -1)) {
						invjs.userClicked = true;
						invjs.urlHash(url);
						this.blur();
						if (!hasAnchor) {
							return true;
						}
						else {
							return false;
						}
					}
				}
			});

			// we've unbound everything in previous iteration
	        // so we need this to rebind again

			$("li.level2.hasSub > a").unbind("click").click(function(){
				var index = $("li.level2.hasSub > a").index(this);
				invjs.selectMenuL2(index);
				invjs.urlHash(this.href);
				this.blur();
				return true;
			});

		}

		$("a[rel='a']").click(function(event) {
			   var wHref = this.href;
			   var domain = getBrowserHostname();
			   if (wHref.indexOf("http://" + domain) != -1) {
					if (wHref.indexOf('/etc/medialib') == -1 ) {					
			   			event.preventDefault();
					}
			   }
		});

	},
	urlHash: function(wPage){
		// setup URL location bar for bookmarkability
		var pathSplit, checkFilename;

		if(wPage.indexOf(invjs.jspath) == -1){
			// it's different shell, we need to reload whole page anyway
			checkFilename = wPage;
			document.location.href = checkFilename;

		} else {
			// we can use this shell and load by elegance

			invjs.lastReferrer = getPageUrl();

			var checkFilename = invjs.getFileName(wPage);

			checkFilename = invjs.removeHashPrefix(checkFilename);

			if(invjs.isie) {
				var hashName = checkFilename;

				// avoid having two "?" in query string for iframe
				var index = checkFilename.lastIndexOf("?");
				if (index != -1 ) {
					checkFilename = checkFilename.substring(0,index) + "&" + checkFilename.substring(index + 1 , checkFilename.length);
				}
				// it's very important for these two lines to be next to each other,
				// this count as two clicks for IE (frame clicking issue) and in order to avoid that
				// they have to execute one after another so IE has no time to issue two click sounds				
				$("#ieUrlFrame").attr("src", getUrlHandler() + "?hash="+checkFilename);
				window.location.hash = hashName;
				
			}
			else {
				// and here's just rest of the world, without incident, without resistance
				window.location.hash = checkFilename;
			}
		}

	},
	getQueryString: function(){
		var query = "";
		var href = window.location.href;
		var index = href.indexOf("?");
		if (index != -1) {
			query = href.substr(index);
		}
		return query;

	},
	clearQueryString: function(newUrl){
		var index = newUrl.indexOf("?");
		if (index != -1) {
			newUrl = newUrl.substr(0,index);
		}
		return newUrl;

	},
	contentSquirt: function(wPage, wAnchor) {

		$("div#progressIcon").css("display","block");

		var queryString = invjs.getQueryString();

		var pathSplit, checkFilename;
		if(wPage.indexOf(invjs.jspath) == -1){
			checkFilename = wPage;
		} else {
			pathSplit = wPage.indexOf(invjs.jspath)+invjs.jspath.length;
			checkFilename = wPage.substr(pathSplit+1);
		}

		// clear whole query string in browser location bar and replace with new one
		checkFilename = invjs.clearQueryString(checkFilename);
		
		var checkFilenameAjax;

		// check if the url called ENDS on .html
		if ( (checkFilename.lastIndexOf(".html") + (".html").length) == checkFilename.length) {
			checkFilenameAjax = checkFilename.replace(".html",".ajax.html");
		}
		// if not (probably a page not found anyway, so we need to failsafe)
		else {
			checkFilename = checkFilename.substr(0,checkFilename.lastIndexOf("/")+1);
			checkFilenameAjax = checkFilename + "invalid_link.ajax.html";
		}
		
		checkFilename += queryString;
		checkFilenameAjax += queryString;
		
		// save query to ie frame
		if(queryString != "" && invjs.isie) {
			$("#ieUrlFrame").attr("src", getUrlHandler() + "?hash="+ checkFilename);
		}
	

		// (in ie) let's check if we ask for the same ajax call, if yes, then don't call it
		if (invjs.isie) {
			if (checkFilenameAjax == invjs.lastAjaxCall){
				return;
			}
			invjs.lastAjaxCall = checkFilenameAjax;
		}

		$.ajaxSetup({cache:true});
		$.ajax({
			type: 		"GET",
			url: 		checkFilenameAjax,
			dataType: 	"html",
			success: 	function(src){			

				// redirect in elegant mode, hacky
				if (src.indexOf("/* <redirectURL> */") != -1) {
					var redirectURL = src.substring(src.indexOf("/* <redirectURL> */\"") + "/* <redirectURL> */\"".length, src.indexOf("\"/* </redirectURL> */"));
					invjs.urlHash(redirectURL);
					return false;
				}

				$("#mainContentArea").empty();

				// strip this div. It's needed for cms, but not here
				src = src.slice(src.indexOf("<div id=\"mainContentArea\">") + "<div id=\"mainContentArea\">".length, src.lastIndexOf("</div>"));

				$("#mainContentArea").append( src );

				$("div#progressIcon").css("display","none");

				setTimeout("$(\"#breadcrumb *, #breadcrumbPopup *\").show()", 500); /* <INVESTECAFTERCARE-108 /> */

				setTimeout("invjs.addDartDownloadTracking()", 500);

				var wHeight = invjs.getHeight();

				setTimeout("invjs.setContentArea("+wHeight+", '"+wAnchor+"')", 250);

				invjs.traceNavigationMenu(checkFilename);

				},
			error: 	function(XMLHttpRequest, textStatus, errorThrown){
				if (typeof(s) == "undefined") {
			        $.getScript(getOmnitureCodeUrl(), function() {
        				s.pageURL = document.location;
						s.pageName = document.location;
						s.pageType = "errorPage";
						s.t();
			        });
				}
				else {
					s.pageURL = document.location;
					s.pageName = document.location;
					s.pageType = "errorPage";
					s.t();
				}
	
				//need to make this request in other way
				if (invjs.isie) {
					$("#ieUrlFrame").attr("src", getUrlHandler() + "?hash="+'commons/page_not_found.html');
				}
				invjs.contentSquirtNoPageNotFound('commons/page_not_found.html');
				}

			});
	},
	contentSquirtNoPageNotFound: function(wPage, wAnchor) {

		$("div#progressIcon").css("display","block");

		var pathSplit, checkFilename;
		if(wPage.indexOf(invjs.jspath) == -1){
			checkFilename = wPage;
		} else {			
			pathSplit = wPage.indexOf(invjs.jspath)+invjs.jspath.length;
			checkFilename = wPage.substr(pathSplit+1);
		}

		var checkFilenameAjax = checkFilename.replace(".html",".ajax.html");

		$.ajax({
			type: 		"GET",
			url: 		checkFilenameAjax,
			dataType: 	"html",
			success: 	function(src){
				$("#mainContentArea").empty();

				// strip this div. It's needed for cms, but not here
				src = src.slice(src.indexOf("<div id=\"mainContentArea\">") + "<div id=\"mainContentArea\">".length, src.lastIndexOf("</div>"));

				$("#mainContentArea").append( src );

				$("div#progressIcon").css("display","none")

				setTimeout("$(\"#breadcrumb *, #breadcrumbPopup *\").show()", 500); /* <INVESTECAFTERCARE-108 /> */

				var wHeight = invjs.getHeight();
				setTimeout("invjs.setContentArea("+wHeight+", '"+wAnchor+"')", 250);

			}
		});
	},
	contentSquirtFromSource: function(src){
		$("#mainContentArea").empty();

		src = src.slice(src.indexOf("<div id=\"mainContentArea\">") + "<div id=\"mainContentArea\">".length, src.lastIndexOf("</div>"));

		$("#mainContentArea").append( src );

		$("div#progressIcon").css("display","none")

		setTimeout("$(\"#breadcrumb *, #breadcrumbPopup *\").show()", 500); /* <INVESTECAFTERCARE-108 /> */

		setTimeout("invjs.addDartDownloadTracking()", 500);

		var wHeight = invjs.getHeight();
		setTimeout("invjs.setContentArea("+wHeight+")", 250);

	},
	enableBackButton: function(){
		var pollInterval = 500; // could be adjusted if performance is affected or if polling is too eager
		if(invjs.isie){
			var h = setInterval('invjs.pollIframe()', pollInterval);
		} else {
			var h = setInterval('invjs.pollURL()', pollInterval);
		}
	},
	pollURL: function(){
		if(!window.location.hash){
			return;
		}
		if(window.location.hash != invjs.recentHash || invjs.userClicked){ // url bar has changed
			if(window.location.hash.indexOf(invjs.anchorSeparatorChar) != -1 
				&& window.location.hash.indexOf("?query=") == -1) { // there's an anchor (and it is not search, because it can contain + in query)

				// anchor handling
				var tAnchor, currFile, recentFile;
				tAnchor = window.location.hash.substr(window.location.hash.indexOf(invjs.anchorSeparatorChar)+1);
				currFile = window.location.hash.split(invjs.anchorSeparatorChar)[0];
				if(invjs.recentHash){
					recentFile = invjs.recentHash.split(invjs.anchorSeparatorChar)[0];
				}

				if(currFile != recentFile){ // the filename has changed as well as there being a hash, therefore the anchor is on another page
					invjs.contentSquirt(invjs.jspath + currFile, tAnchor);
				} else { // the anchor is on this page
					invjs.scrollToAnchor(tAnchor); 
				}
			} else { // no anchor, so the change must be in the filename
				invjs.contentSquirt(invjs.jspath + window.location.hash);
			}
			invjs.recentHash = window.location.hash;
			// consume user click
			invjs.userClicked = false;
		}
	},
	pollIframe: function(){
		if(!window.location.hash){
			return;
		}

		var frameUrl = $("#ieUrlFrame").contents().find("p#urlText").text(); // getting the src of the iframe on pressing back button doesn't work like it should. it seems not to update even though the content changes. writing it to text and polling that instead appears clumsy, but it works.

		var frameUrlArr = frameUrl.split("hash=");

		// back there we've changed one ? into & to pass it correctly through iframe (it already has ?hash= ...)
        // now we need to transform this first & into ? back again

		if (frameUrlArr[1]) {
			var firstAmpIndex = frameUrlArr[1].indexOf("&");
			var firstQstMrkIndex = frameUrlArr[1].indexOf("?");

			if ( firstAmpIndex != -1 && firstQstMrkIndex == -1 ) {
				frameUrlArr[1] = frameUrlArr[1].substring(0, firstAmpIndex) + "?" + frameUrlArr[1].substring(firstAmpIndex + 1, frameUrlArr[1].length);
			}
		}

		// this is fix for ie6 not seeing query in recent hash, so we need to take it from address bar
		// and use from now on instead of window.location.hash
		// note : it shouldn't change anything on ie7, ie7 hash is ok and will have ? as well as location bar

		var loc = document.location + "";
		var realHash = window.location.hash;
		if (realHash.indexOf("?") == -1 && loc.indexOf("?") != -1) {
			realHash = realHash + loc.substring(loc.indexOf("?"), loc.length);
		}

		if((invjs.recentHash == null)){ // page freshly loaded, a urlhash is present. probably a pasted link or browser refresh.
			invjs.recentHash = realHash;

			if(realHash.indexOf(invjs.anchorSeparatorChar) != -1 && realHash.indexOf("?query=") == -1) {
				invjs.contentSquirt(invjs.jspath + realHash.split(invjs.anchorSeparatorChar)[0], realHash.split(invjs.anchorSeparatorChar)[1]);
			} else {
				invjs.contentSquirt(invjs.jspath + realHash);
			}
		} else {
			if(realHash != invjs.recentHash || invjs.userClicked){ // urlhash has changed, user has clicked an ajaxed link OR an anchor on the same page
				// anchor handling
				var tAnchor, currFile, recentFile;

				var anchorIndex = realHash.indexOf(invjs.anchorSeparatorChar);
				if (anchorIndex != -1 && realHash.indexOf("?query=") == -1) {
					tAnchor = realHash.substr(anchorIndex + 1);
				}

				//checkFilename = realHash.substr(0, realHash.indexOf(invjs.anchorSeparatorChar));

				if (realHash.indexOf("?query=") == -1) {
					currFile = realHash.split(invjs.anchorSeparatorChar)[0];
				}
				else {
					currFile = realHash;
				}


				if(invjs.recentHash) {
					if (invjs.recentHash.indexOf("?query=") == -1) {
						recentFile = invjs.recentHash.split(invjs.anchorSeparatorChar)[0];
					}
					else {
						recentFile = invjs.recentHash;
					}
				}

				if(currFile != recentFile){ // the filename has changed as well as there being a hash, therefore the anchor is on another page
					invjs.contentSquirt(invjs.jspath + currFile, tAnchor);
				} else { // the anchor is on this page
					invjs.scrollToAnchor(tAnchor); 
				}

				invjs.recentHash = realHash;
				// consume user click
				invjs.userClicked = false;

			} else if(invjs.recentHash.substr(1) != frameUrlArr[1]){ // iframeurl has changed, user has clicked back or forward.
				window.location.hash = frameUrlArr[1];
				invjs.recentHash = window.location.hash;
				if(window.location.hash.indexOf(invjs.anchorSeparatorChar) != -1 && window.location.hash.indexOf("?query=") == -1) {
					invjs.contentSquirt(invjs.jspath + window.location.hash.split(invjs.anchorSeparatorChar)[0], window.location.hash.split(invjs.anchorSeparatorChar)[1]);
				} else {
					invjs.contentSquirt(invjs.jspath + window.location.hash);
				}
			}
		}
	},
	setupIframe: function() {
			$("#outerContainer").append('<div id="urlFrame"></div>');

			var hashStr = window.location.hash ? "?hash="+window.location.hash.substr(1) : "";

			var checkFilename = invjs.getFileName(window.location.href);

			if (checkFilename == "") {
				hashStr = "?hash=home.html";
			}

			$("#urlFrame").html('<iframe style="display:none" id="ieUrlFrame" src="' + getUrlHandler() + hashStr+'"></iframe>');
	},
	getPageUrlWithQuery: function() {
			var thisPageUrl = "";
			var browserHref = document.location.href;
			if (browserHref.indexOf("?") != -1) {
				thisPageUrl = browserHref.replace("#","");
				if (thisPageUrl.indexOf(".press") != -1) {
					thisPageUrl = thisPageUrl.replace(".press","");
					thisPageUrl = thisPageUrl + "&selector=press";
				}
				if (thisPageUrl.indexOf(".default") != -1) {
					thisPageUrl = thisPageUrl.replace(".default","");
					thisPageUrl = thisPageUrl + "&selector=default";
				}
			}
			else {
				thisPageUrl = getPageUrl();
			}	
			return thisPageUrl;
	},
	getPrintPageUrlWithQuery: function() {
			var thisPageUrl = "";
			var browserHref = document.location.href;
			if (browserHref.indexOf("?") != -1) {
				thisPageUrl = browserHref.replace("#","");
				thisPageUrl = thisPageUrl.replace(".html?",".print.html?");
			}			
			else {
				thisPageUrl = getPrintPage();
			}	
			return thisPageUrl;
	},	
	getFileName: function(href){
		var prefix = document.location.protocol + "//" + document.location.host;
		
		var prefixLength = 0;
		if(href.indexOf(prefix) === 0) {
			prefixLength = prefix.length;
		} 
		
		if(href.indexOf(invjs.jspath) != -1) {
			var pathSplit = href.indexOf(invjs.jspath, prefixLength) + invjs.jspath.length;
			return href.substr(pathSplit);
		} else {
			return href;
		}
	},
	removeHashPrefix : function(name){
		if(name.indexOf("#") === 0){
			name = name.substr(1);
		}
		return name;		
	},
	addDartDownloadTracking : function(){
		$("a[name^='dart-']").each(function(){
			var name = this.name;
			var params = name.split("-");
			var dartSrc = params[1];
			var dartType = params[2];
			var dartCat = params[3];

			var omnitureFunction = "";
			if (this.onclick) {
				omnitureFunction = this.onclick.toString().match(/\{([\s\S]*)\}/m)[1];
			}

			this.setAttribute("onclick", "trackDartDownload(this,'" + dartSrc + "','" + dartType + "','" + dartCat + "');" + omnitureFunction);
		});
		
	}
};
