// requires mam.core.js
if(mam.hub == undefined)
{
mam.hub = new function() {
	var that = this;
	// Public Methods
	jQuery.extend(this,  {
		version: "1.0",
		config: mam.config,
		indexHandler: function() {
			if(!mam.util.env.isDefaultHost()) {
				forwardToHomePage();
			} else {
				if(loadCookie()) {
					mam.config.initialize(function() {
						forwardToHomePage({host: getSiteHost()});
					}, {
						controlXml: true,
						siteSelectorXml: false
					});
				} else {
					forwardToHub();
				}
			}
		},
		hubHandler: function() {
			if(!mam.util.env.isDefaultHost()) {
				forwardToHub();
			} else {
				mam.page.loadPage({
					title: "Hub",
					leftColumnImg: {
						src: "/core/library/images/left_column/hand_clap.jpg",
						alt: "Hand Clap"
					}
				});
				mam.config.initialize(function() {
					$(document).ready(function() {
						buildSiteSelector();
					});
				}, {controlXml: true,siteConfigXml: true});
			}
		},
		pageHandler: function() {
			// get location and investor type from query string if present and store in a cookie
			// alert(window.location.search);
			var query = window.location.search.substring(1);
			// alert("query: "+query);
			var pArray = query.split("&");
			var queryParms = {};
			// alert("parameters length:"+ parameters.length);
			$.each(pArray, function(i,n){
				var pos = n.indexOf('=');
				if (pos > 0) {
					var key = n.substring(0,pos);
					var val = n.substring(pos+1);
					queryParms[key] = val;
				}
			});
			if(queryParms.location != undefined) {
				location = queryParms.location;
				clientType = queryParms.investorType;
				remember = queryParms.remember; // makes it work in TeamSite
				storeCookie();
				forwardToHomePage({host: getSiteHost(), query: ""}); // we have stored the location and investor type info now so forward to home page without the query string.
			}
			
			var excludedPage = false;
			var includedPage = false;
			var path = mam.util.url.getPath();
			var excludedPagesRegex = [
				".*"
			];
			var includedPagesRegex = [
				"/notcore/home/home.html"
			];
			$.each(excludedPagesRegex, function(i,n){
				var re = new RegExp(n);
				if(re.test(path)) excludedPage = true;
			});
			$.each(includedPagesRegex, function(i,n){
				var re = new RegExp(n);
				if(re.test(path)) includedPage = true;
			});
			// alert("excludedPage:"+excludedPage+", includedPage:"+includedPage);
			// alert(importantInfoConfirmed());
			if(!excludedPage || includedPage) { // allow navigation to excluded pages without visiting the hub. Inclusions override exclusions
				if(!importantInfoConfirmed()) {
					// alert("forward to important info");
					forwardToImportantInfo();
				}
			}
			
			// Call core page handler
			var callCorePageHandler = false;
			var regex = [
				"/core/mellons_boutiques/.*",
				"/core/specialist_asset_managers/.*"
			];
			$.each(regex, function(i,n){
				var re = new RegExp(n);
				if(re.test(path)) callCorePageHandler = true;
			});
			if(callCorePageHandler) mam.hub.corePageHandler();

		},
		importantInfoHandler: function() {
				// alert("importantInfoHandler...");
				$(document).ready(function() {
						// load investor type specific text
						if(loadCookie()) {
							var investorTypeText = {
								individual: "am an individual investor",
								institutional: "am an institutional investor",
								wholesale: "am a private bank, advisor or distributor"
							};
							if(investorTypeText[clientType] != undefined && investorTypeText[clientType] != "") $("#investor-type-specfic").html(investorTypeText[clientType]);
						} else {
							// Do nothing
						}

						if(loadImportantInfoCookie()) {
							$("#importantInformationCheckbox").get(0).checked = importantInformation.confirmed;
						}
						$("#go-button").click(function(){
								$(".formError").remove(); // clear errors
								// alert("go");
								if($("#importantInformationCheckbox").get(0).checked) {
									importantInformation.confirmed = true;
									storeImportantInfoCookie();
									// alert("forward to home");
									forwardToHomePage();
								} else {
									clearImportantInfoCookie();
									$("fieldset.importantInformation").append('<p class="formError">You must agree to the terms and conditions.</p>')
								}
								return false;
						});
				});
			// load site specifc Important Infomation
				mam.config.initialize(function() {
					$(document).ready(function() {
						// alert(mam.util.path.getSiteImportantInfoPath());
						$("#site-specific-important-info").load(mam.util.path.getSiteImportantInfoPath());
					});
				}, {controlXml: true});
		},
		corePageHandler: function() {
			// alert("1");
			if(!loadCookie() && mam.util.env.isDefaultHost()) { // Show site selector if visitor has not already chosen a site.
				mam.config.initialize(function() {
					$(document).ready(function() {
						buildSiteSelector();
					});
				}, {
					controlXml: true,
					siteConfigXml: true,
					siteSelectorXml: false
				});
			}
		}
	});
	var siteSelectorPath = "/core/hub/hub.html";
	var homePagePath = "/core/home/home.html";
	var investorTypes = {
			individual: {
				name: "Individual Investors",
				value: "individual",
				description: "Individual Investors - Information on funds suitable for direct investment by private individuals, including individual savings accounts (ISAs).",
				locations: {
					empty: {name: "Please choose your location", value: ""},
					austria: {name: "Austria", value: "austria", site: "mellon-international-retail"},
					brazil: {name: "Brazil", value: "brazil", site: "mellon-international-retail"},
					chile: {name: "Chile", value: "chile", site: "mellon-international-retail"},
					china: {name: "China", value: "china", site: "mellon-international-retail"},
					dubai: {name: "Dubai", value: "dubai", site: "mellon-international-retail"},
					france: {name: "France", value: "france", site: "mellon-international-retail"},
					germany: {name: "Germany", value: "germany", site: "west-lb"},
					hongKong: {name: "Hong Kong", value: "hongKong", site: "mellon-international-retail"},
					ireland: {name: "Ireland", value: "ireland", site: "mellon-uk-retail"},
					italy: {name: "Italy", value: "italy", site: "mellon-international-retail-italian"},
					japan: {name: "Japan", value: "japan", site: "mellon-japan"},
					portugal: {name: "Portugal", value: "portugal", site: "mellon-international-retail"},
					spain: {name: "Spain", value: "spain", site: "mellon-international-retail-spain"},
					switzerland: {name: "Switzerland", value: "switzerland", site: "mellon-international-retail"},
					netherlands: {name: "Netherlands", value: "netherlands", site: "mellon-international-retail"},
					oman: {name: "Oman", value: "oman", site: "mellon-international-retail"},
					otherContinentalEurope: {name: "Other Continental Europe", value: "otherContinentalEurope", site: "mellon-international-retail"},
					otherFarEast: {name: "Other Far East", value: "otherFarEast", site: "mellon-international-retail"},
					otherLatinAmerica: {name: "Other Latin America", value: "otherLatinAmerica", site: "mellon-international-retail"},
					otherMiddleEast: {name: "Other Middle East", value: "otherMiddleEast", site: "mellon-international-retail"},
					qatar: {name: "Qatar", value: "qatar", site: "mellon-international-retail"},
					saudiArabia: {name: "Saudi Arabia", value: "saudiArabia", site: "mellon-international-retail"},
					uae: {name: "UAE", value: "uae", site: "mellon-international-retail"},
					uk: {name: "United Kingdom", value: "uk", site: "newton"}
				}
			},
			institutional: {
				name: "Institutional Services",
				value: "institutional",
				description: "Institutional Services - This site provides information on investment strategies suitable for institutional investors, such as pension funds, global corporations, investment & pension consultants, insurance companies and endowment plans.",
				locations: {
					empty: {name: "Please choose your location", value: ""},
					australia: {name: "Australia", value: "australia", site:"mellon-australia"},
					canada: {name: "Canada", value: "canada", site:"mam"},
					germany: {name: "Germany", value: "germany", site:"west-lb"},
					japan: {name: "Japan", value: "japan", site:"mellon-japan"},
					other: {name: "Other", value: "other", site:"mellon-institutional"},
					uk: {name: "United Kingdom", value: "uk", site:"mellon-institutional"},
					us: {name: "United States", value: "us", site:"mam"}
				}
			},
			wholesale: {
				name: "Private Banks, Advisors & Distributors",
				value: "wholesale",
				description: "Private Banks, Advisors & Distributors - This site provides information on offshore funds registered for distribution throughout the world for private banks, family offices, advisors and distributors.",
				locations: {
					empty: {name: "Please choose your location", value: ""},
					austria: {name: "Austria", value: "austria", site: "mellon-international-wholesale"},
					brazil: {name: "Brazil", value: "brazil", site: "mellon-international-wholesale"},
					chile: {name: "Chile", value: "chile", site: "mellon-international-wholesale"},
					china: {name: "China", value: "china", site: "mellon-international-wholesale"},
					dubai: {name: "Dubai", value: "dubai", site: "mellon-international-wholesale"},
					france: {name: "France", value: "france", site: "mellon-international-wholesale"},
					germany: {name: "Germany", value: "germany", site: "west-lb"},
					hongKong: {name: "Hong Kong", value: "hongKong", site: "mellon-international-wholesale"},
					ireland: {name: "Ireland", value: "ireland", site: "mellon-uk-wholesale"},
					italy: {name: "Italy", value: "italy", site: "mellon-international-wholesale-italian"},
					japan: {name: "Japan", value: "japan", site: "mellon-international-wholesale"},
					portugal: {name: "Portugal", value: "portugal", site: "mellon-international-wholesale"},
					spain: {name: "Spain", value: "spain", site: "mellon-international-wholesale-spain"},
					switzerland: {name: "Switzerland", value: "switzerland", site: "mellon-international-wholesale"},
					netherlands: {name: "Netherlands", value: "netherlands", site: "mellon-international-wholesale"},
					oman: {name: "Oman", value: "oman", site: "mellon-international-wholesale"},
					otherContinentalEurope: {name: "Other Continental Europe", value: "otherContinentalEurope", site: "mellon-international-wholesale"},
					otherFarEast: {name: "Other Far East", value: "otherFarEast", site: "mellon-international-wholesale"},
					otherLatinAmerica: {name: "Other Latin America", value: "otherLatinAmerica", site: "mellon-international-wholesale"},
					otherMiddleEast: {name: "Other Middle East", value: "otherMiddleEast", site: "mellon-international-wholesale"},
					qatar: {name: "Qatar", value: "qatar", site: "mellon-international-wholesale"},
					saudiArabia: {name: "Saudi Arabia", value: "saudiArabia", site: "mellon-international-wholesale"},
					uae: {name: "UAE", value: "uae", site: "mellon-international-wholesale"},
					uk: {name: "United Kingdom", value: "uk", site: "mellon-uk-wholesale"}
				}
			}
		};

	var location = "";
	var clientType = "";
	var remember = "";
	var cookieExists = {};
	var importantInformation = {};
	importantInformation.confirmed = false;
	var importantInfoConfirmed = function() {
		// alert("cookie: "+loadImportantInfoCookie()+", confirmed: "+importantInformation.confirmed);
		return (loadImportantInfoCookie() && importantInformation.confirmed);
	};
	
	// Private Methods
	var getSite = function() {
		var site = investorTypes[clientType].locations[location].site;
		// alert("getSite: "+site);
		if(site != undefined && site != "") {
			return site;
		} else { // no match return default
			return "default";
		}
	};
	var clearCookie = function() {
		var cookie = new Cookie(document, "hub", 0 , "/", null, false);
		cookie.remove();
	};
	var forwardToHub = function(p) {
		var parms = {
				host: mam.util.env.getDefaultHost(),
				preserveHistory: false,
				test: false,
				pathname: siteSelectorPath
		}; // defaults 
		jQuery.extend(parms, p);
		forwardToPage(parms);
	};
	var forwardToImportantInfo = function(p) {
		var parms = {
				host: "",
				preserveHistory: false,
				test: false,
				pathname: "/core/important_information/important_information.html"
		}; // defaults 
		jQuery.extend(parms, p);
		forwardToPage(parms);
	};
	var forwardToHomePage = function(p) {
		var parms = {
				host: "",
				preserveHistory: false,
				test: false,
				pathname: homePagePath
		}; // defaults 
		jQuery.extend(parms, p);
		forwardToPage(parms);
	};
	var forwardToPage = function(p) {
		var url;
		var parms = {
				host: "",
				preserveHistory: false,
				test: false,
				pathname: "default.html"
		}; // defaults 
		jQuery.extend(parms, p);
		// alert("forwardToHomePage: host: "+parms.host+"\npreserveHistory: "+parms.preserveHistory+"\ntest: "+parms.test);
		url = mam.util.url.constructURL({
			host: parms.host,
			pathname: parms.pathname,
			query: parms.query
		});
		// url += this.homePagePath;
		mam.util.url.forward({
			url: url,
			preserveHistory: parms.preserveHistory,
			test: parms.test
		});
	};
	var getSiteHost = function(site) {
		var host, siteElements, hostElements;
		if(mam.config.getControlXml() != undefined) {
			if(site == undefined) site = getSite();
			// alert("method: getSiteHost\n\nsite: "+site+"\n\nenv: "+mam.util.getEnvName()+"\n\nlocation: "+this.location+"\n\nclientType: "+this.clientType);
			siteElements = mam.util.dom.getElementsByAttribute($("site", mam.config.getControlXml()), "id", site);
			if(siteElements.size() == 0) {site = "default";} // if site not found, try default
			siteElements = mam.util.dom.getElementsByAttribute($("site", mam.config.getControlXml()), "id", site);
			hostElements = mam.util.dom.getElementsByAttribute($("host", siteElements), "env", mam.util.env.getEnv());
			var host = hostElements.get(0).getAttribute("name");
		} else {
			host = "";
		}
		// alert("getSiteHost: "+host);
		return host;
	};
	var loadCookie = function() {
		var cookie = new Cookie(document, "hub", 8760 , "/", null, false);
		if(cookie.load()) {
			cookieExists.hub = true;
			location = cookie.location;
			clientType = cookie.clientType;
			remember = cookie.remember;
		} else {
			cookieExists.hub = false;
		}
		// alert("loadCookie: "+cookieExists.hub);
		return cookieExists.hub;
	};
	var storeCookie = function() {
		var cookie = new Cookie(document, "hub", 8760 , "/", null, false);
		cookie.location = location;
		cookie.clientType = clientType;
		cookie.remember = remember;
		cookie.store();
	};
	var loadImportantInfoCookie = function() {
		var cookie = new Cookie(document, "importantInfo", 8760 , "/", null, false);
		if(cookie.load()) {
			cookieExists.importantInfo = true;
			importantInformation.confirmed = cookie.confirmed;
			// alert(importantInformation.confirmed);
		} else {
			cookieExists.importantInfo = false;
		}
		return cookieExists.importantInfo;
	};
	var storeImportantInfoCookie = function() {
		var cookie = new Cookie(document, "importantInfo", 8760 , "/", null, false);
		cookie.confirmed = importantInformation.confirmed;
		cookie.store();
	};
	var clearImportantInfoCookie = function() {
		var cookie = new Cookie(document, "importantInfo", 0 , "/", null, false);
		cookie.remove();
	};
	var setLocation = function(p_location) {
		location = p_location;
	};
	var setClientType = function(p_clientType) {
		clientType = p_clientType;
	};
	var setRemember = function(p_remember) {
		remember = p_remember;
	};
	var go = function() {
		setLocation($("#location").val());
		setClientType($("input[@name=investorType][@checked]").val());
		setRemember($("#remember").get(0).checked);
		// alert(clientType+":"+location);
		// alert(investorTypes[clientType].locations[location].site);
		if(remember) storeCookie(); else clearCookie();
		forwardToHomePage({host: getSiteHost(), preserveHistory: true, query: "location="+location+"&investorType="+clientType+"&remember="+remember});
		return true;
	};
	var buildSiteSelector = function() {
		//alert("Building site selector...");
		if($("div.siteSelector").size() == 0) $("#main-content").append("<div class=\"siteSelector\"></div>");
		$("div.siteSelector").each(function(){
				$(this).append("<p><strong>To help us direct you to the most appropriate information, please select your investor type and your country or region from the following options:</strong></p>");
				$(this).append('<fieldset class="siteSelectorForm"></fieldset>');
				$.each(investorTypes, function(i, n) {
						$(".siteSelectorForm").append('<div><label for="'+n.value+'" id="'+n.value+'Label" title="'+n.description+'"">'+n.name+'</label><input name="investorType" id="'+n.value+'" type="radio" value="'+n.value+'" title="'+n.description+'"/></div>');
					$("#"+n.value).validate({type:"blur", validation:"notnull", store: true});
					$("#"+n.value).click(function() {selectInvetorType(n);});
					
				});
				$(this).append('<input id="go-button" type="image" src="/core/library/images/go.gif" value="Go" />');
				$(this).append('<p class="preferences"><input id="remember" type="checkbox"/>&nbsp;<strong>Remember my preferences</strong><br/>(only available if your browser has cookies enabled)</p>');
				$("input:radio").addClass("radio");

				$('#go-button').validate({type:'click', checkAll: true, fail: function() {alert("fail")}, success: function() {go();} });
				initValues(investorTypes);
				$(".siteSelectorForm input, .siteSelectorForm label").Tooltip({delay: 0, fixPNG: true, track: true, showBody: " - "});
				$("#tooltip").bgiframe();
		});
		$("div.siteSelector").show();
	};
	var selectInvetorType = function(investorType) {
		setLocation($("#location").val());
		setClientType($("input[@name=investorType][@checked]").val());
		buildLocations(investorType);
	};
	var initValues = function(investorTypes) {
		loadCookie();
		// alert(loadCookie());
		if(clientType != "") buildLocations(investorTypes[clientType]);
		$("#"+clientType).each(function(){this.checked = true;});
		$("#location").each(function(){this.value = location;});
		$("#remember").each(function(){this.checked = remember;});
	};
	var initLocationValue = function() {
		$("#investorType").each(function(){this.value = clientType;});
	};
	var buildLocations = function(investorType) {
		$("#location").each(function(){this.options.length = 0});
		if($("#location").size() == 0) $(".siteSelectorForm").append('<select id="location"></select>');
		var i = 0;
		$.each(investorType.locations, function(key, o) {
			var selected = false;
			if(o.value == location) selected = true;
			$("#location").get(0).options[i] = new Option(o.name, o.value, false, selected);
			i++;
		});
		mam.validator.clear();
		$('#location').validate({type:'blur', validation:'notnull', store: true});
	};
};
}
