// Startup Functions
function init() {
	changeFontSize(getSelectedFontSizeFromCookie()); // set font size	
	checkReferral();
}
window.onload = init; 


/* ------------------------------------------------------------------------------  	*/
/* COMMON FUNCTIONS FOR BMO.COM														*/
/* ------------------------------------------------------------------------------  	*/

// Defines root path for referencing images within scipts (root relative paths)
function baseFileURL(){
	try{
		return BMO.staticPrefix + "/";
	}catch(e){
		var patt = /bmogc/;
		return patt.test(location.hostname) ? "/pccgprefix/" : "/";
	}
}


// Defines root path for referencing links within scipts (root relative paths)
function baseURL() {
	return BMO.sitePrefix + "/";
}

// Show-Hide Div
function showHide(divName) {
	var getObj = document.getElementById(divName);
	if(getObj == undefined)	{}
	else {
		if(getObj.style.display == "none"){
			getObj.style.display = 	"block";
		}
		else {
			getObj.style.display = "none";
		}
	}
}

//  Rates bar functionality
function ratesBar() {
	//captureLinkAlt(document.location.href,'','','action=ClickRatesButton');
	var handle = document.getElementById("rnav_ratestools_selector");
	var handle1 = document.getElementById("rates_box");
	var handle2 = document.getElementById("tools_box");
	//newImage = "url(../images/menu_bg.jpg)";
	//handle.style.backgroundImage = newImage;
	handle.className="rnav_ratestools_rates";
	handle1.style.display = "block";
	handle2.style.display = "none";
}

//  Tools bar functionality
function toolsBar() {
	//captureLinkAlt(document.location.href,'','','action=ClickToolsButton');
	var handle = document.getElementById("rnav_ratestools_selector");
	var handle1 = document.getElementById("rates_box");
	var handle2 = document.getElementById("tools_box");
	//newImage = "url(../images/menuTools_bg.jpg)";
	//handle.style.backgroundImage = newImage;
	handle.className="rnav_ratestools_tools";
	handle1.style.display = "none";
	handle2.style.display = "block";
}


// Set Language Preference (en, fr)
function setPreferredLang(lang) {
	setCookie('language',lang,365); // update cookie with preferred language
}

// Get Language Preference (en, fr)
function getPreferredLang() {	
	// Retrieve language preference from cookie
	var getLanguageFromCookie = getCookie('language'); 
	// If cookie doesn't exist, default language is English
	if (getLanguageFromCookie!=null && getLanguageFromCookie!="") {
		return getLanguageFromCookie;
	}
	else {
		return "en";
	}		
}


/* ------------------------------------------------------------------------------  	*/
/* UI Events																		*/
/* ------------------------------------------------------------------------------  	*/


// Opens Content Window 
function openContentWindow(id) {
	try {
		var buttonObj = document.getElementById('button_'+id);
		var contentWindowObj = document.getElementById('contentWindow_' + id);
		$(contentWindowObj).fadeIn("slow"); // Show Content Window			
		buttonObj.style.display = "none"; // Hide Read More Button
	} catch (err) {
		var contentWindowObj = document.getElementById('contentWindow_' + id);
		$(contentWindowObj).fadeIn("slow"); // Show Content Window			
	}
}

// Closes Content Window 
function closeContentWindow(id) {
	try {
		var buttonObj = document.getElementById('button_' + id);
		var contentWindowObj = document.getElementById('contentWindow_' + id);
		contentWindowObj.style.display = "none"; // Hide Content Window
		$(buttonObj).fadeIn("fast"); // Show Read More button
	} catch (err) {
		var contentWindowObj = document.getElementById('contentWindow_' + id);
		contentWindowObj.style.display = "none"; // Hide Content Window
	}
}

// Show Tooltip
function showToolTip(id) {
	ttObj = document.getElementById(id);
	/*$(ttObj).fadeIn("fast"); */
	ttObj.style.display = "block";
}

// Hide Tooltip
function hideToolTip(id) {
	ttObj = document.getElementById(id);
	ttObj.style.display = "none";	
	//$(ttObj).fadeOut("fast");
}				



/* ------------------------------------------------------------------------------  	*/
/* UTILITY FUNCTIONS																*/
/* ------------------------------------------------------------------------------  	*/

// Create Cookie
function setCookie(c_name,value,expiredays) {
	var exdate=new Date();
	var cookieDomain = document.domain.replace("www.","");
	exdate.setDate(exdate.getDate()+expiredays);
	//document.cookie=c_name+ "=" +escape(value)+ ((expiredays==null) ? "" : ";expires="+exdate.toGMTString()) + ";domain=bmo.com;path=/"; 
	document.cookie=c_name+ "=" +escape(value)+ ((expiredays==null) ? "" : ";expires="+exdate.toGMTString()) + ";domain="+cookieDomain+";path=/"; 
}

// Get Cookie Value
function getCookie(c_name) {
	if (document.cookie.length>0) {
		c_start=document.cookie.indexOf(c_name + "=");
		if (c_start!=-1) {
			c_start=c_start + c_name.length+1;
			c_end=document.cookie.indexOf(";",c_start);
			if (c_end==-1) c_end=document.cookie.length;
			return unescape(document.cookie.substring(c_start,c_end));
		}
	}
	return "";
}


// Replace decimal with comma (French formatting)
function makeFrDecimal(num) {
	return num.replace(/\./, ",");
}

// Go Back 
function goBack() {
	history.go(-1);
}

// Gets value from querystring parameter
function getQuerystring(key, default_) {
	if (default_==null) default_=""; 
	key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
	var qs = regex.exec(window.location.href);
	if(qs == null)
		return default_;
	else
		return qs[1];
} 


//  Open URL in parent window (if exists)													
function openPageInParent(url) {

	// Load URL into parent if still open
	if (window.opener && !window.opener.closed) {		
		window.opener.location.href = url;
		window.opener.focus();
	}
	// If parent is not open, open URL in new window
	else {
		var detailsWindow = window.open(url, 'details');
	}
	
}


// Ajax Request
function ajaxRequest(xml, callback) {
	var httpRequest = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
	httpRequest.onreadystatechange= function() { ajaxCallback(callback, httpRequest) };
	httpRequest.open("GET",xml,true);
	httpRequest.send(null);
}

// Ajax Callback function - calls requested function
function ajaxCallback(f, httpRequest) {
	f(httpRequest);
}


// Get node value for a given tag name
function getNodeValue(parentNode, instance, tagName) {
	var val = parentNode[instance].getElementsByTagName(tagName);
	try {
		return val[0].firstChild.nodeValue;
	}
	catch(ex) {
		return "";
	}	
}


// Get attribute value from tag
function getNodeAttribute(parentNode, instance, tagName, paramName) {
	var val = parentNode[instance].getElementsByTagName(tagName);
	return val[0].getAttribute(paramName);
}


// Dynamically load a script
function loadScript(url, id, oCallback) {
	var oHead = document.getElementsByTagName("head")[0];
	if (id) {
		// Check if element with id exists already
		var obj = document.getElementById(id);
		if (obj) { oHead.removeChild(obj); } // remove object
	}
	
	// Create new script tag		
	var oScript = document.createElement("script");
	oScript.type = "text/javascript";
	
	// Add callback if supplied
	if (oCallback) {		
		oScript.onload = oCallback; // All other browsers	
		oScript.onreadystatechange = function() { // IE 6 & 7
			if (this.readyState == 'complete' || this.readyState == 'loaded')  {  
				oCallback();
			}  
		}
	
	}
	if (id) { oScript.id = id; }
	oScript.src = encodeURI(url);
	oHead.appendChild(oScript);		
}


/* ------------------------------------------------------------------------------  	*/
/* FONT SIZE SELECTION FUNCTIONALITY												*/
/* ------------------------------------------------------------------------------  	*/

// Updates font size selection menu
function updateFontSizeMenu() {
	
	var currentFontSize = getSelectedFontSizeFromCookie(); // get current font size from cookie		
	var menu = "";	
		
	// Create Menu
	menu += '<a href="javascript:setDefaultFontSize(\'small\');" title="Small/Petit"><img id="small_textIcon" src="'+baseFileURL()+'images/smText_' + ((currentFontSize == "small") ? "on" : "off") + '.gif" class="textSizeIcon" alt="Small/Petit"></a>';
	menu += '<a href="javascript:setDefaultFontSize(\'medium\');" title="Medium/Moyen"><img id="medium_textIcon" src="'+baseFileURL()+'images/medText_' + ((currentFontSize == "medium") ? "on" : "off") + '.gif" class="textSizeIcon" alt="Medium/Moyen"></a>';
	menu += '<a href="javascript:setDefaultFontSize(\'large\');" title="Large/Grand"><img id="large_textIcon" src="'+baseFileURL()+'images/bgText_' + ((currentFontSize == "large") ? "on" : "off") + '.gif" class="textSizeIcon" alt="Large/Grand"></a>';	

	// Output Menu to Screen
	document.getElementById('fontSizeMenu').innerHTML = menu;

}

// Get currently selected font size
function getSelectedFontSizeFromCookie() {

	// Retrieve current font size from cookie
	var fontSizeFromCookie = getCookie('fontSize');
	
	// If cookie doesn't exist, current fonsize is Small (default)
	if (fontSizeFromCookie!=null && fontSizeFromCookie!="") {
		return fontSizeFromCookie;
	}
	else {
		return "small";
	}
	
}

// Sets font size for page
function setDefaultFontSize(size) {
	setCookie('fontSize',size,365); // update cookie with selected font size
	changeFontSize(size); // override CSS with select font size
	updateFontSizeMenu(); // update menu
}

// Override CSS with global font size selected by user
function changeFontSize(size) {
	var oldClasses = eval("/large|medium|small/ig"); //sets key words to be eliminated
	var currentClass = document.body.className; //gets the current class names
	document.body.className = currentClass.replace(oldClasses, "") + " " + size; //eliminates key words from string, then adds new size
}


// Functionality for menu rollovers
function MM_swapImgRestore() { //v3.0
	var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) 
	//alert(x.src);
	//alert(x.oSrc);
	x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
	var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
	var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
	if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
	var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
	d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
	if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
	for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
	if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
	var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
	if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

// Replaces decimal with comma for french rates formatting
function makeFrDecimal(num) {
	return num.replace(/\./, ",");
}

// Event handler for sign-in drop down menu
function goSignIn() {
	var si = document.getElementById("signin");
	var idx = si.selectedIndex;
	var url = si.options[idx].value;
	window.location.href = url;
}

// Opener for Popup Windows
function popup(url,width,height) {
	popupWidth = (width == null) ? 500 : width;
	popupHeight = (height == null) ? 600 : height;	
	var newPopupWindow = window.open(url, 'popup', 'scrollbars=1,resizable=1,width='+popupWidth+',height='+popupHeight);
}

// Opener for Popup Windows with disclaimer before proceeding
function redirectExt(url,lang) {
	var content="";
	content += "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"><html xmlns=\"http://www.w3.org/1999/xhtml\"><head>";
	content += (lang == "fr") ? "<title>BMO | BMO Groupe financier<\/title>" : "<title>BMO | BMO Financial Group<\/title>";
	content += "<link href=\"http://www.bmo.com/css/content.css\" rel=\"stylesheet\" type=\"text/css\" /><script src=\"http://www.bmo.com/scripts/bmo_common.js\" type=\"text/javascript\"><\/script><\/head>";
	content += (lang == "fr") ? "<body id=\"popup\" class=\"bmofg french\">" : "<body id=\"popup\" class=\"bmofg english\">";
	content += "<div class=\"popupHeader\"><div class=\"popupLogo\"><\/div><\/div><div class=\"popupContent\">";
	content += (lang == "fr") ? "Vous quittez le site Web de BMO Groupe financier, www.bmo.com, et passez au site d'un tiers. La Banque de Montr&eacute;al et ses filiales ne sont pas responsables du contenu de ce site, notamment les publicit&eacute;s, les offres, les promotions ou les noms. Nous vous remercions d'avoir visit&eacute; le site www.bmo.com.<br \/><br \/>" : "You are leaving www.bmo.com, the website of BMO Financial Group and entering an independent third party site. Bank of Montreal and its subsidiaries are not responsible for the content presented on the third party site including advertising claims, offers, endorsements, or names. Thank you for visiting www.bmo.com.<br \/><br \/>";
	content += (lang == "fr") ? "<div class=\"redButton\"><div><a href=\"javascript:opener.document.location='"+ url +"';self.close();\"  title=\"Continuer (ouvre dans une fen&ecirc;tre pr&eacute;c&eacute;dente)\">Continuer<\/a><\/div><\/div>" : "<div class=\"redButton\"><div><a href=\"javascript:opener.document.location='"+ url +"';self.close();\" title=\"Go (opens in previous window)\">Go<\/a><\/div><\/div>";
	content += (lang == "fr") ? "<div class=\"redButton\"><div><a href=\"javascript:self.close();\" title=\"Retour\">Retour<\/a><\/div><\/div>" : "<div class=\"redButton\"><div><a href=\"javascript:self.close();\" title=\"Cancel\">Cancel<\/a><\/div><\/div>";
	content += "<\/div><script type=\"text/javascript\" src=\"/scripts/webAnalytics.js\"><\/script><noscript><img src=\"http://csvtr.bmo.com/bmo/zag.gif?Log=1&\" height=\"1\"><\/noscript>";
	var popup = window.open('', 'BMO', 'scrollbars=1,resizable=1,width=400,height=300');
	popup.document.write(content);
	popup.document.close();
	popup.focus();
}

// Opener for Popup Windows with disclaimer before proceeding
function redirectExt1(url,lang) {
	var content="";
	content += "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"><html xmlns=\"http://www.w3.org/1999/xhtml\"><head>";
	content += (lang == "fr") ? "<title>BMO | BMO Groupe financier<\/title>" : "<title>BMO | BMO Financial Group<\/title>";
	content += "<link href=\"http://www.bmo.com/css/content.css\" rel=\"stylesheet\" type=\"text/css\" /><script src=\"http://www.bmo.com/scripts/bmo_common.js\" type=\"text/javascript\"><\/script><\/head>";
	content += (lang == "fr") ? "<body id=\"popup\" class=\"bmofg french\">" : "<body id=\"popup\" class=\"bmofg english\">";
	content += "<div class=\"popupHeader\"><div class=\"popupLogo\"><\/div><\/div><div class=\"popupContent\">";
	content += (lang == "fr") ? "Vous quittez le site Web de BMO Groupe financier, www.bmo.com, et passez au site d'un tiers. Nous vous remercions d'avoir visit&eacute; le site www.bmo.com.<br \/><br \/>" : "You are leaving www.bmo.com, the website of BMO Financial Group and entering an independent third party site. Thank you for visiting www.bmo.com.<br \/><br \/>";
	content += (lang == "fr") ? "<div class=\"redButton\"><div><a href=\"javascript:opener.document.location='"+ url +"';self.close();\"  title=\"Continuer (ouvre dans une fen&ecirc;tre pr&eacute;c&eacute;dente)\">Continuer<\/a><\/div><\/div>" : "<div class=\"redButton\"><div><a href=\"javascript:opener.document.location='"+ url +"';self.close();\" title=\"Go (opens in previous window)\">Go<\/a><\/div><\/div>";
	content += (lang == "fr") ? "<div class=\"redButton\"><div><a href=\"javascript:self.close();\" title=\"Retour\">Retour<\/a><\/div><\/div>" : "<div class=\"redButton\"><div><a href=\"javascript:self.close();\" title=\"Cancel\">Cancel<\/a><\/div><\/div>";
	content += "<\/div><script type=\"text/javascript\" src=\"/scripts/webAnalytics.js\"><\/script><noscript><img src=\"http://csvtr.bmo.com/bmo/zag.gif?Log=1&\" height=\"1\"><\/noscript>";
	var popup = window.open('', 'BMO', 'scrollbars=1,resizable=1,width=400,height=300');
	popup.document.write(content);
	popup.document.close();
	popup.focus();
}

//V6 Popup Windows call
function customPopup(url, features) {
	window.open(url, '', features);
}


/* ------------------------------------------------------------------------------   */
/* LOCATOR FUNCTIONS																*/
/* ------------------------------------------------------------------------------   */

var addressLabel_en = "Enter Street, City or Postal Code";
var addressLabel_fr = "Rue, ville ou code postal";
var provinceLabel_en = "Province";
var provinceLabel_fr = "Province ou territoire";
var transitLabel_en = "Transit Number";
var transitLabel_fr = "Num\u00e9ro de domiciliation";


// Show/Hide Transit Option in Locator Search Form
function toggleTransit(toggle, lang) {
	var toggleObj = document.getElementById('transitInput');	
	if (toggle == "off") { toggleObj.value = (lang == "fr") ? transitLabel_fr : transitLabel_en; }
	toggleObj.disabled = ((toggle == "on" ? false : true));
	//toggleObj.className = ((toggle == "on" ? "" : "disabled"));
	toggleObj.style.display = ((toggle == "on" ? "block" : "none"));	
}

// Handle focus/blur states for Address field in Locator Search form
function initAddressInput(lang) {
	var addressObj = document.getElementById('addressInput');
	if (addressObj.value == ((lang == "fr") ? addressLabel_fr : addressLabel_en )) {
		addressObj.value = "";
	}
	else if (addressObj.value == "") {
		addressObj.value = ((lang == "fr") ? addressLabel_fr : addressLabel_en );
	}
}

// Handle focus/blur states for Transit field in Locator Search form
function initTransitInput(lang) {
	var transitObj = document.getElementById('transitInput');
	if (transitObj.value == ((lang == "fr") ? transitLabel_fr : transitLabel_en )) {
		transitObj.value = "";
	}
	else if (transitObj.value == "") {		
		transitObj.value = ((lang == "fr") ? transitLabel_fr : transitLabel_en );
	}
}

// Submit Locator Search and open results in Popup Window
function submitLocatorSearch(lang) {

	var searchVal = "";
	for (var i=0; i < document.getElementsByName('search').length; i++) {
		if (document.getElementsByName('search').item(i).checked) {
			searchVal = document.getElementsByName('search').item(i).value;
		}
	}
	
	var addressVal = document.getElementById('addressInput').value;
	var provinceVal = document.getElementById('provinceSelect').value;
	var transitVal = document.getElementById('transitInput').value;
	var openWeekendsVal = document.getElementById('openWeekends').checked;
	var languageVal = document.getElementById('lang').value;		
	var LocatorWindow = window.open(' https://locator.bmo.com/Default.aspx?search=' + searchVal + ((addressVal != eval("addressLabel_"+lang)) ? '&address='+addressVal : '') + ((provinceVal != eval("provinceLabel_"+lang)) ? '&province='+provinceVal : '') + ((document.getElementById('transitInput').disabled == false && transitVal != eval("transitLabel_"+lang)) ? '&transit='+transitVal : '' ) + (openWeekendsVal ? "&weekend=true" : "") + '&lang='+languageVal+'&search_source=bmohp', 'locator', 'width=980,height=725,scrollbars=0,resizable=1,left=125,top=-25');
	
}

// Locator Popup (Handles all Locator Versions)
function openLocator(version, lang) {
	
	var locatorVer; // store query string variable needed to define locator version to display
	var langFlag; 	// store query string variable needed to define language	

	switch (version) {
		case 'branch': locatorVer = "bb"; break; 				// BMO Branch Locator
		case 'mortgage_specialist': locatorVer = "ms"; break; 	// Mortgage Specialist Locator
		case 'lending_specialist': locatorVer = "ils"; break; 	// Investment Lending Specialist Locator
		case 'financial_planner': locatorVer = "fp"; break; 	// Financial Planner Locator
		case 'investment_advisor': locatorVer = "ia"; break;	// Investment Advisor Locator
		case 'hpb': locatorVer = "hpb"; break;	// Investment Advisor Locator		
	}
	
	switch (lang) {
		case 'e': langFlag = "en"; break;	// English
		case 'f': langFlag = "fr"; break; 	// French
	}
	
	var LocatorWindow = window.open('https://locator.bmo.com/Default.aspx?t='+locatorVer+'&lang='+langFlag, 'locator', 'width=980,height=725,scrollbars=0,resizable=1,left=125,top=-25');
} 

/* ------------------------------------------------------------------------------   */
/* BMO.com Search																	*/
/* ------------------------------------------------------------------------------   */

var searchLabel_en = "Search BMO.com";
var searchLabel_fr = "Rechercher sur BMO.com";

// Handle focus/blur states for Search Input field 
function initSiteSearch(lang) {
	var siteSearchObj = document.getElementById('siteSearchInput');
	if (siteSearchObj.value == ((lang == "fr") ? searchLabel_fr : searchLabel_en )) {
		siteSearchObj.value = "";
	}
	else if (siteSearchObj.value == "") {		
		siteSearchObj.value = ((lang == "fr") ? searchLabel_fr : searchLabel_en );
	}
}


/* ------------------------------------------------------------------------------   */
/* Referrals																		*/
/* ------------------------------------------------------------------------------   */

// Check for referrer param, and store cookie
function checkReferral() {
	var referrerVal = getQuerystring('referrer');
	var referrerExpire = 30; // 30 days
	var re = /([a-zA-Z0-9_-]+)$/;
	// if valid referral, store to cookie
	if (re.test(referrerVal)) {
		var cookieVal = getCookie("referrer");
		if (cookieVal == "") { 
			setCookie("referrer",referrerVal,referrerExpire);			
		}
		else {
			if (cookieVal.indexOf(referrerVal) == -1)  { 
				setCookie("referrer",cookieVal+", "+referrerVal,referrerExpire);
			}		
		}
	}
}




/* ------------------------------------------------------------------------------   */
/* BMO Font Size Widget 															*/
/* To Do: Deprecate old functions 													*/
/* ------------------------------------------------------------------------------   */

// Font Size Widget
function bmoFontSizeWidget(lang) {
	this.container = document.getElementById("font-size-widget");
	this.language = lang;
	this.set = function(size) { 
		setCookie('fontSize',size,365);
		var oldClasses = eval("/large|medium|small/ig"); // replace previous size classes first
		document.body.className = document.body.className.replace(oldClasses,"") + " "+this.get(); // update class with new size
		this.setMenu(this.get());
	}
	this.get = function() { 
		return (getCookie('fontSize') != null && getCookie('fontSize') != "") ? getCookie('fontSize') : "small";
	}
	this.init = function() {
		var html = '<span class="text-size-col">';		
		html += (lang == "en") ? 'TEXT SIZE' : 'TEXTE';
		html += '	<a href="javascript:BMOFontSize.set(\'small\');" id="text-small-button" title="'+ ((lang == "en") ? 'Small' : 'Petit') +'" ></a>';
		html += '	<a href="javascript:BMOFontSize.set(\'medium\');" id="text-medium-button" title="'+ ((lang == "en") ? 'Medium' : 'Moyen') +'"></a>';
		html += '	<a href="javascript:BMOFontSize.set(\'large\');" id="text-large-button" title="'+ ((lang == "en") ? 'Large' : 'Grand') +'"></a>';
		html += '</span>';
		html += '<span class="print-col">';
		html += (lang == "en") ? 'PRINT' : 'IMPRIMER';
		html += '	<a href="javascript:window.print();" class="print-button"></a>';
		html += '</span>';
		html += '<div class="clear"></div>';
		this.container.innerHTML = html;
		this.setMenu(this.get());
	}
	this.setMenu = function(size) {
		// Update font size button
		document.getElementById("text-small-button").className = "";
		document.getElementById("text-medium-button").className = "";
		document.getElementById("text-large-button").className = "";
		document.getElementById("text-"+size+"-button").className = "active";		
	}
	this.init();
}



// **************************************************************************************************** //
// 	BMO UI (User Interface) 																			//
//	All future UI components should be wrapped in this object 											//
// **************************************************************************************************** //

var BMO_UI = {
	
	// ------------------------------------------------ //
	// Sign In Menu										//
	// ------------------------------------------------ //
	SignInMenu : {	
		// Open list of menu options
		Toggle: function(){
			var menuOptions = document.getElementById("options");
			var toggle = menuOptions.style.display == "block" ? false : true;
			BMO_UI.SignInMenu.Open(toggle);
		},
		Open: function(toggle) {
			var menuOptions = document.getElementById("options");
			menuOptions.style.display = (toggle) ? "block" : "none";
			if (toggle) {
				menuOptions.focus();
			}
		},
		// Selects menu option
		Select: function(obj) {
			var selected = document.getElementById("selected-sign-in");
			var signInButton = document.getElementById("sign-in-button");	
			selected.href = obj.href;
			selected.innerHTML = ((obj.innerHTML.length > 30) ? obj.innerHTML.substr(0,27) + "..." : obj.innerHTML) + '<span href="javascript:showOptions()" class="handle"></span>';
			BMO_UI.SignInMenu.ShadeSelection(obj);
			BMO_UI.SignInMenu.Open(false);
			signInButton.focus();		
		},
		// Shade currently selected menu option	
		ShadeSelection : function(obj) {
			var menuOptions = document.getElementById("options");
			var menuItems = menuOptions.getElementsByTagName("li");
			for (x=0; x<menuItems.length; x++) {
				menuItems[x].className = "";
			}
			obj.parentNode.className = "selected";					
		},	
		// Launch selected website
		Go: function() {
			var url = document.getElementById('selected-sign-in').href;
			window.location.href = url;
		},
		// Init menu
		Init : function() {		
			document.body.onclick = function() { BMO_UI.SignInMenu.Open(false) }; // close menu on body click
			//document.getElementById("selected-sign-in").onfocus = function() { BMO_UI.SignInMenu.Open(true); }; // open menu on focus
			// On blur of last menu item, close menu
			var menuOptions = document.getElementById("options"); 
			var menuLinks = menuOptions.getElementsByTagName("a");			
			menuLinks[menuLinks.length-1].onblur = function() { BMO_UI.SignInMenu.Open(false); };						
			document.getElementById("sign-in-list").onclick = function(event) { 
				var e = (window.event) ? window.event : event;
				try {
					e.stopPropagation();	
				}
				catch (ex) {
					e.cancelBubble = true; // ie
				}
			}		
		}
	},
	
	
	
	// ------------------------------------------------ //
	// Search Widget									//
	// ------------------------------------------------ //
	
	Search : {
						
		// Search Widget Object		
		Widget : function(topSearchesSource) {		
			this.element = document.getElementById("searchOverlay");
			//this.apiURL =  location.protocol + "//198.96.179.20/search?proxystylesheet=bmo_json", // New GSA
			this.apiURL =  location.protocol + "//findit.bmo.com/search?proxystylesheet=bmo_json",
			this.frontEndURL = BMO.sitePrefix + ((lang == "en") ? "/home/search/results/" : "/accueil/rechercher/resultant/"); 			
			this.minCharacterLength = 3; // minimum number of character user has to enter to perform search
			this.delaySearchRequest = 1000; // number of milliseconds to delay before perform ajax call
			this.timeoutSearchRequest = null; // global property to hold timeout obj for search delay
			this.delayTrackingRequest = 3000; // number of milliseconds to delay before tracking query
			this.timeoutTrackingRequest = null; // global property to hold timeout obj for tracking delay
			this.numResults = 5; // number of results to retreive from GSA
			this.searchSite = $("#search_site").val(); 
			this.searchClient = $("#search_client").val();
			this.topSearchesSource = BMO.staticPrefix + "/scripts/top-searches/" + topSearchesSource + "_" + lang + ".js"; // json file of top search results			
			this.init = function() {
				BMO_UI.Search.BuildWidgetStructure(this.element);	 // build elements for widget
				// Register event handlers
				$('body').click(function() { BMO_UI.Search.ShowWidget(false); }); //  closes search overlay when clicked outside element
				$('#searchWrapper').click(function(event){ event.stopPropagation(); }); // prevents search overlay from closing when clicked on
				$('#searchInput').keyup(function() { BMO_UI.Search.DoSearch(); });
				$('#searchInput').focus(function() { if (this.value == this.title) { this.value = ""; } BMO_UI.Search.DoSearch(true); });
				$('#searchInput').blur(function() { if (this.value == "") { this.value = this.title; } });
				$('#searchInput').click(function(event){ event.stopPropagation(); });
				$('#searchForm').submit(function() { if ($('#searchInput').val() != $('#searchInput').attr('title') && $('#searchInput').val() != "") { BMO_UI.Search.DoSearch(true); return false; } else { $('#searchInput').focus(); $('#searchInput').select(); return false; } } );		
			},
			this.init();
		},
			
		// Labels for widget (init first, then pass to search obj)
		Dictionary : function() {
			this.popularSearchText = (lang == "en") ? "Popular searches on BMO.com:" : "Recherches courantes sur le site BMO.com :";
			this.contactUsText = (lang == "en") ? "Can't find what you're looking for? <br/> Call us at 1-877 CALL BMO." : "Vous ne trouvez pas ce que vous cherchez? <br /> Composez le 1-877-225-5266.";
			this.resultsIntroText = (lang == "en") ? "Displaying top results for " : "Afficher les principaux r&eacute;sultats pour ";
			this.showMeText = (lang == "en") ? "Show me " : "Afficher ";
			this.allResultsText = (lang == "en") ? "all results" : "tous les r&eacute;sultats";
			this.allResultsBarText = (lang == "en") ? "View all results" : "Afficher tous les r&eacute;sultats";
			this.closeText = (lang == "en") ? "close [ x ]" : "fermer [ x ]";
			this.noResultsText = (lang == "en") ? "Sorry, your search returned no results." : "D&eacute;sol&eacute;, votre recherche n&rsquo;a donn&eacute; aucun r&eacute;sultat.";
			this.suggestedSpellingText = (lang == "en") ? "Were you searching for" : "Vouliez-vous dire";
			this.alternateQueriesText = (lang == "en") ? "You can also try searching for" : "Utiliser plut&ocirc;t"; 
		},	
		
		// Perform search
		DoSearch : function(noDelay) {
			var query = $("#searchInput").val();
			// Display default search content if search not performed (show top searches)
			if (query.length < BMOSearch.minCharacterLength ) {
				BMO_UI.Search.WriteDefaultSearchContent();
			}
			// Request search results through AJAX request
			else {
				clearTimeout(BMOSearch.timeoutSearchRequest);
				clearTimeout(BMOSearch.timeoutTrackingRequest);
				searchDelay = (noDelay) ? 0 : BMOSearch.delaySearchRequest; // check event type (if user's type, wait a bit before searching)
				BMOSearch.timeoutSearchRequest = setTimeout(function() { BMO_UI.Search.WriteLoading(); loadScript(BMOSearch.apiURL +"&site="+BMOSearch.searchSite+"&client="+BMOSearch.searchClient+"&output=xml&num="+BMOSearch.numResults+"&q="+query+"&oe=utf8","SearchResults", BMO_UI.Search.WriteResults) },searchDelay);	
				BMOSearch.timeoutTrackingRequest = setTimeout( function() { captureVirtualURI("bmo.com/search/EN/DT6499/?search="+escape(query))},BMOSearch.delayTrackingRequest ); // track queries after x time
			}
		},
			
		// Build Overlay
		BuildWidgetStructure : function(widgetObj) {			
			var topDiv = document.createElement("div");
			topDiv.className = "searchTopCap";	
			var middleDiv = document.createElement("div");
			middleDiv.className = "searchMiddle";
			var contentDiv = document.createElement("div");
			contentDiv.id = "searchContent";
			middleDiv.appendChild(contentDiv);	
			var footerDiv = document.createElement("div");
			footerDiv.className = "searchFooterLinks";
			footerDiv.innerHTML = "<a href='javascript:BMO_UI.Search.ShowWidget(false);' class='searchCloseButton'>"+BMOSearchLabels.closeText+"</a><div class='clear'></div>";
			middleDiv.appendChild(footerDiv);	
			var bottomDiv = document.createElement("div");
			bottomDiv.className = "searchBottomCap";
			var searchLabel = document.createElement("label");
			searchLabel.className = "searchLabel";
			searchLabel.setAttribute("for","searchInput");
			widgetObj.appendChild(topDiv);
			widgetObj.appendChild(middleDiv);	
			widgetObj.appendChild(bottomDiv);	
			widgetObj.appendChild(searchLabel);		
		},
		
		// Get and Write Top Searches
		GetTopSearches : function() {						
			if (typeof TopSearches != "undefined") { // TopSearches object exists
				BMO_UI.Search.WriteTopSearches();				
			} 
			else { // Doesn't exist, get JSON
				loadScript(BMOSearch.topSearchesSource,"TopSearches", BMO_UI.Search.WriteTopSearches);
			}
		},			
		
		// Get and Write Top Searches
		WriteTopSearches : function() {			
			var html = "";
			for (x=0; x<TopSearches.Terms.length; x++) {
				html += "<li><a href='javascript:BMO_UI.Search.ReviseQuery(\""+TopSearches.Terms[x]+"\")'>"+TopSearches.Terms[x]+"</a></li>";								
			}			
			html += "<li class='clear'></li>";
			$(".popular-searches").html(html);		
		},		
		
		// Return default search content (Popular Searches)
		WriteDefaultSearchContent : function() {
			var html = "<div class=\"padded\"><strong>"+BMOSearchLabels.popularSearchText+"</strong>";
			html += "<ul class=\"popular-searches\"><li class='searchLoading'></li></ul>";
			html += "<p>"+BMOSearchLabels.contactUsText+"</p></div>";	
			$("#searchContent").html(html);
			BMO_UI.Search.ShowWidget(true);			
			BMO_UI.Search.GetTopSearches();	
		},	
		
		// Write loading message
		WriteLoading : function() {
			$("#searchContent").html("<div class='searchLoading'></div>"); // show loading image
		},

		// Get Featured Results HTML
		WriteFeaturedResults : function() {
			var html = "";
			if (GSA_Response.Featured.length > 0) {
				html += "<ul class='recommendedResults'>";
				for (var key in GSA_Response.Featured) {
					html += "<li><a href='"+GSA_Response.Featured[key]['url']+"' onclick='captureEvent(\"DT6499_SFRen\")'><span class='linkTitle'>"+GSA_Response.Featured[key]['label']+"</span></a></li>";
				}	
				html += "</ul>";
			}
			return html;
		},
				
		// Get Organic Results HTML
		WriteOrganicResults : function() {			
			var html = "";
			if (GSA_Response.Results.length > 0) {				
				html += "<ul class='organicResults'>";
				for (var key in GSA_Response.Results) {
					if (GSA_Response.Results[key]["T"] != "") {
						html += "<li><a href='"+GSA_Response.Results[key]["U"]+"' onclick='captureEvent(\"DT6499_SORen\")'><span class='linkTitle'>"+GSA_Response.Results[key]["T"]+"</span><span class='linkDescription'>"+GSA_Response.Results[key]["S"]+"</span></a></li>";
					}
				}
				if (GSA_Response.TotalResults > BMOSearch.numResults) { html += "<li class='bottomLI'><a href='"+BMOSearch.frontEndURL+"?site="+escape(BMOSearch.searchSite)+"&q="+escape(GSA_Response.Query)+"' onclick='captureEvent(\"DT6499_SMRen\"); BMO_UI.Search.ShowWidget(false);'>"+BMOSearchLabels.allResultsBarText+"</a></li>"; }
				html += "</ul>";
			}
			return html;
		},		
		
		// Get Related Queries HTML
		WriteRelatedQueries : function() {
			var html = "";
			if (GSA_Response.Synonyms.length > 0) {
				html += "<div class='relatedQueries searchText'>You may also be interested in:<br />";
				for (x=0; x < GSA_Response.Synonyms.length; x++) {
					html +=  "<a href='javascript:BMO_UI.Search.ReviseQuery(\""+GSA_Response.Synonyms[x]+"\");' onclick='captureEvent(\"DT6499_SCSen\");'>" + GSA_Response.Synonyms[x] + "</a>";												
					html += (x != GSA_Response.Synonyms.length-1) ? ", " : "";
				}			
				html += "</div>";
			}
			return html;
		},
		
		// Write Results to Page
		WriteResults : function() {	
			var html = "";
			if (GSA_Response.Results.length > 0) {
				html += "<div class='searchText'>"+BMOSearchLabels.resultsIntroText+" \"<nobr>"+ GSA_Response.Query +"</nobr>\". <br />"+BMOSearchLabels.showMeText+" <a href='"+BMOSearch.frontEndURL+"?site="+escape(BMOSearch.searchSite)+"&q="+escape(GSA_Response.Query)+"' onclick='captureEvent(\"DT6499_SMRen\"); BMO_UI.Search.ShowWidget(false);'>"+BMOSearchLabels.allResultsText+"</a>.";			
				html += "<ul class='searchResultList'>";
				html += BMO_UI.Search.WriteFeaturedResults();
				html += BMO_UI.Search.WriteOrganicResults();
				html += "</ul>";
				html += BMO_UI.Search.WriteRelatedQueries();				
			}
			else {
				html += "<div class='padded'>" + BMOSearchLabels.noResultsText + ((GSA_Response.Spelling.length > 0) ? " <br />"+BMOSearchLabels.suggestedSpellingText+" <a href='javascript:BMO_UI.Search.ReviseQuery(\""+GSA_Response.Spelling[0]+"\");'>"+GSA_Response.Spelling[0]+"</a>?" : "") +"<p>"+BMOSearchLabels.contactUsText+"</p></div>";
			}
			$("#searchContent").html(html); // output html to browser
			BMO_UI.Search.ShowWidget(true);
			return;
		},
		
		// Handles showing and hiding of widget		
		ShowWidget : function(on) {	
			if (on && !$(BMOSearch.element).is(":visible")) {
				$("#locatorSearchForm").addClass('visibility-hidden'); // hide drop down for ie6 issue
				$("#provinceSelect").hide(); // hide old locator drop down
				($.browser.msie) ? $(BMOSearch.element).show() : $(BMOSearch.element).fadeIn();
				captureVirtualURI("bmo.com/search/EN/DT6499/"); 		
			}
			else if (!on && $(BMOSearch.element).is(":visible")) {
				($.browser.msie) ? $(BMOSearch.element).hide() : $(BMOSearch.element).fadeOut('fast');			
				$("#locatorSearchForm").removeClass('visibility-hidden'); // unhide drop down for ie6 issue
				$("#provinceSelect").show(); // unhide old locator drop down
				captureEvent("DT6499_SCLen");
			}
		},
		
		// Revise Query
		ReviseQuery : function(query) {
			$('#searchInput').val(query);
			BMO_UI.Search.DoSearch(true);
		}		
			

	} // End Search 
	

} // End BMO_UI 

/* -------------------------------------------------------- */
/*  Add this to zig.js										*/
/* -------------------------------------------------------- */

function captureVirtualURI(virtualURI) {
	var cd = "http://csvtr.bmo.com"; 
	if (document.location.href.indexOf('https') == 0) { cd = "https://csvtr.bmo.com"; }
	
	var lc=new Image();
	lc.src = cd + "/bmo/zag.gif?Log=1&virtual_uri="+escape(virtualURI)+"&cb="+new Date().getTime();
}

function captureEvent(actionValue) {
	var cd = "http://csvtr.bmo.com"; 
	if (document.location.href.indexOf('https') == 0) { cd = "https://csvtr.bmo.com"; }
		
	var lc=new Image();	
	lc.src = cd + "/bmo/zag2.gif?Log=1&action="+actionValue+"&cb="+new Date().getTime();
}
