﻿var IE = (navigator.userAgent.indexOf("Win") != -1) && (navigator.appVersion.indexOf("MSIE")!=-1);
var IEVersion = IE ? parseFloat((new RegExp("MSIE ([0-9]{1,}[.0-9]{0,})")).exec(navigator.userAgent)[1]):-1;
var IE6 = IEVersion == 6 ? true : false;

var page_Name_analytics ='';

//*********************************************************************************
// Title: 				getCookieValue
// Desc: 				Get cookie values for a given cookie
// Created : 			July 31, 2002
// Last Modified: 		Sept 23, 2002
// Accepts:				cookieName - Name of the cookie.
// Returns:				The cookie value(s).
//*********************************************************************************
function getCookieValue(cookieName){
	var cookieValue = document.cookie;
	var cookieStartsAt = cookieValue.indexOf(" " + cookieName + "=");
	
	// check if cookie exists.  If cookie does not exist, do a second check at the beginning of the string
	if (cookieStartsAt == -1){
		cookieStartsAt = cookieValue.indexOf(cookieName + "=");
	}
	
	if (cookieStartsAt == -1){
		// coookie really does not exist
		cookieValue = null;
	}else{
		cookieStartsAt = cookieValue.indexOf("=", cookieStartsAt) + 1;
		var cookieEndsAt = cookieValue.indexOf(";", cookieStartsAt);
		if (cookieEndsAt == -1){
			// cookie is the last one in the string
			cookieEndsAt = cookieValue.length;
		}
		cookieValue = unescape(cookieValue.substring(cookieStartsAt, cookieEndsAt));
	}
	return cookieValue;
}

//*********************************************************************************
// Title: 				setSessionCookie
// Desc: 				Get cookie values for a given cookie
// Created : 			August 12, 2005
// Last Modified: 		August 31, 2005
// Accepts:				cookieName - Name of the cookie.
// 						cookieValue - Cookie value(s).
// 						cookiePath - Path cookie is valid for.
// 						cookieDomain - Expriy date/time of the cookie.
// Returns:				
//*********************************************************************************
function setSessionCookie(cookieName, cookieValue, cookiePath, cookieDomain){
	cookieValue = escape(cookieValue);
	
	if (cookiePath == "" || cookiePath == null){
		cookiePath = "; path=/";
	}else{
		cookiePath = "; path=" + cookiePath;
	}
	
	if (cookieDomain == "" || cookieDomain == null){
		cookieDomain = "";
	}else{
		cookieDomain = "; domain=" + cookieDomain;
	}
	//alert(cookieName + "=" + cookieValue + "; expires=" + cookieExpires + cookiePath + cookieDomain);
	document.cookie = cookieName + "=" + cookieValue + ";" + cookiePath + cookieDomain;
}

//*********************************************************************************
// Title: 				setCookie
// Desc: 				Get cookie values for a given cookie
// Created : 			July 31, 2002
// Last Modified: 		March 1, 2005
// Accepts:				cookieName - Name of the cookie.
// 						cookieValue - Cookie value(s).
// 						cookiePath - Path cookie is valid for.
// 						cookieExpires - Expriy date/time of the cookie.
// Returns:				
//*********************************************************************************
function setCookie(cookieName, cookieValue, cookieExpires, cookiePath, cookieDomain){
	cookieValue = escape(cookieValue);
	
	if (cookieExpires == "" || cookieExpires == null){
		var nowDate = new Date();
		nowDate.setMonth(nowDate.getMonth() + 1);
		cookieExpires = nowDate.toGMTString();
	}
	
	if (cookiePath == "" || cookiePath == null){
		cookiePath = "; path=/";
	}else{
		cookiePath = "; path=" + cookiePath;
	}

	if (cookieDomain == "" || cookieDomain == null || cookieDomain == undefined){
		cookieDomain = "; domain=" + document.domain.replace(/www\./,"");
	}else{
		cookieDomain = "; domain=" + cookieDomain;
	}
	//alert(cookieName + "=" + cookieValue + "; expires=" + cookieExpires + cookiePath + cookieDomain);
	document.cookie = cookieName + "=" + cookieValue + "; expires=" + cookieExpires + cookiePath + cookieDomain;
}


//*********************************************************************************
// Desc: 				Cookie tracking code for all pages on cibc.com
// Created : 			April 27, 2004
// Last Modified: 		June 29, 2004
//*********************************************************************************
var trackTest = getCookieValue("trackCookie");
var locTest = getCookieValue("locCookie");
var domain = ".cibc.com";
var trackingVal = "";
var theDate = new Date();
theDate.setYear(theDate.getFullYear() + 1);
dateExpires = theDate.toGMTString();
if(!trackTest){
	trackingVal = Math.random() * 99999999999999999;
	setCookie('trackCookie', trackingVal, dateExpires, '/', domain);
}
if(!locTest){
	trackingVal = "m";
	setCookie('locCookie', trackingVal, dateExpires, '/', domain);
}

//*********************************************************************************
// Title: 				todaysDate
// Desc: 				writes the date to the document object in a standard format
//						in English or French.
// Created : 			Unknown
// Last Modified: 		Unknown
// Accepts:				
// Returns:				N/A
//*********************************************************************************

// Get today's current date.
var now = new Date();
function todaysDate()	{
	//first determine language by checking path
	var x=""+document.location;
	if (x.indexOf('-fr.html') > 0) { lang="fr"; }
	else{ lang="en"; }
	
	// Array list of months.
	if (lang=="fr"){
		var months = new	Array('janvier','f&eacute;vrier','mars','avril','mai','juin','juillet','ao&ucirc;t','septembre','octobre','novembre','d&eacute;cembre');
	}
	else{
		var months = new	Array('January','February','March','April','May','June','July','August','September','October','November','December');
	}
	// Calculate the number of the current day in the week.
	var date = now.getDate();
	// Calculate four digit year.

	// Join it all together
	if (lang=="fr"){
		date = ((now.getDate()<10) ? "0" : "")+ date;
		today = "le " +  date + " " + months[now.getMonth()] + " " + (fourdigits(now.getYear()));
	}else{
		today =  months[now.getMonth()] + " " + date + ", " + (fourdigits(now.getYear()));
	}
	
	// Print out the data.
	document.write("" +today+ "");
}
//Usage: <script>todaysDate()</script>

//This is to cope with two digit years.
function fourdigits(number)	{
	return (number < 1000) ? number + 1900 : number;
}

//*********************************************************************************
// Title: 				formatDate
// Desc: 				writes a UTC date to the document object in a standard format
//						in English or French.
// Created : 			Feb 23, 2004
// Last Modified: 		August 30, 2004
// Accepts:				inDate, a date string
// Returns:				N/A
//*********************************************************************************
function formatDate(inDate)	{
	outDate=new Date(inDate);
	
	//first determine language by checking path
	var x=""+document.location;
	if (x.indexOf('-fr.html') > 0) { lang="fr"; }
	else{ lang="en"; }
	
	// Array list of months.
	if (lang=="fr"){
		var months = new	Array('janvier','f&eacute;vrier','mars','avril','mai','juin','juillet','ao&ucirc;t','septembre','octobre','novembre','d&eacute;cembre');
	}else{
		var months = new	Array('January','February','March','April','May','June','July','August','September','October','November','December');
	}
	// Calculate the number of the current day in the week.
	var date = outDate.getUTCDate();
	// Calculate four digit year.

	// Join it all together
	if (lang=="fr"){
		date = ((outDate.getUTCDate()<10) ? "0" : "")+ date;
		today = date + " " + months[outDate.getUTCMonth()] + " " + (fourdigits(outDate.getUTCFullYear()));
	}else{
		today =  months[outDate.getUTCMonth()] + " " + date + ", " + (fourdigits(outDate.getUTCFullYear()));
	}

	// Print out the data.
	document.write("" +today+ "");
}

//*********************************************************************************
// Title: 				importSearchTerms
// Desc: 				imports search terms from /ca/js/search-terms.js,
//						searchTerms array is used in the search functions
// Created : 			Unknown
// Last Modified: 		July 24, 2006
// Accepts:				
// Returns:				N/A
//*********************************************************************************

function importSearchTerms() {
	if (document.getElementsByTagName) {
		var head = document.getElementsByTagName("head").item(0);
		var scriptElement;
		scriptElement = document.createElement("script");
		scriptElement.type = "text/javascript";
		scriptElement.src = "/ca/js/search-terms.js";
		scriptElement.charset = "ISO-8859-1";
		head.appendChild(scriptElement);
	}
}
// Don't import when viewing pages in TMS or infonow locators
//if (!(/view-Pages.asp/.test(location.href)) && !(/infonow.net/.test(location.href)) && !(/tools/.test(location.href))) {
if (!(/view-Pages.asp/.test(location.href)) && !(/infonow.net/.test(location.href)) && !(/tools/.test(location.href)) && !(/query.html/.test(location.href))) {
	importSearchTerms();
}

//*********************************************************************************
// Title: 				submitSearch
// Desc: 				confirms that a search term has been entered
// Created : 			Unknown
// Last Modified: 		April 22, 2004
// Accepts:				
// Returns:				Boolean indicating whether search field is blank or not
//						and error message if blank
//*********************************************************************************

function submitSearch(){
	testQt = document.basicSearch.qt.value.toLowerCase();
	// trim leading/trailing whitespace
	testQt = testQt.replace(/^\s*|\s*$/g,"");
	/* Targeted search landing pages:
	loop through all search terms, if we match, goto the corresponding landing page*/
	if (typeof(searchTerms) != "undefined") {
		for (var i = 0; i < searchTerms.length; i++) {
			if (testQt == searchTerms[i].en) {
				document.location='/ca/search/' + searchTerms[i].page + '.html?qt='+ escape(testQt);
				return false;
			}
		}
	}

	// Default search
	if(document.basicSearch.qt.value == "" || document.basicSearch.qt.value == "Search"){
		if (document.basicSearch.qt.value == "Search"){
			document.basicSearch.qt.value = "";
		}
		alert('The search word is missing. Enter the word or phrase to search.');
		return false;
	}else{
		document.basicSearch.qt.value = document.basicSearch.qt.value.replace(/\+ /g, "+");
		document.basicSearch.qt.value = document.basicSearch.qt.value.replace(/- /g, "-");
		document.characterSet="UTF-8";
		document.charset="UTF-8";
		document.defaultCharset="UTF-8";
		return true;
	}
}

//*********************************************************************************
// Title: 				submitSearchFR
// Desc: 				confirms that a search term has been entered
// Created : 			Jan 14, 2004
// Last Modified: 		April 22, 2004
// Accepts:				
// Returns:				Boolean indicating whether search field is blank or not
//						and error message if blank
//*********************************************************************************
function submitSearchFR(){
	testQt = document.basicSearch.qt.value.toLowerCase();
	// trim leading/trailing whitespace
	testQt = testQt.replace(/^\s*|\s*$/g,"");
	/* Targeted search landing pages:
	loop through all search terms, if we match, goto the corresponding landing page*/
	if (typeof(searchTerms) != "undefined") {
		for (var i = 0; i < searchTerms.length; i++) {
			if (testQt == searchTerms[i].fr) {
				document.location='/ca/search/' + searchTerms[i].page + '-fr.html?qt='+ escape(testQt);
				return false;
			}
		}
	}
	
	// Default search
	if(document.basicSearch.qt.value == "" || document.basicSearch.qt.value == "Recherche"){
		if (document.basicSearch.qt.value == "Recherche"){
			document.basicSearch.qt.value = "";
		}
		alert('Le terme d\'interrogation n\'est pas inscrit. Inscrivez un mot ou une phrase � rechercher.');
		return false;
	}else{
		document.basicSearch.qt.value = document.basicSearch.qt.value.replace(/\+ /g, "+");
		document.basicSearch.qt.value = document.basicSearch.qt.value.replace(/- /g, "-");
		document.characterSet="UTF-8";
		document.charset="UTF-8";
		document.defaultCharset="UTF-8";
		return true;
	}
}

//*********************************************************************************
// Title: 				roundIt
// Desc: 				rounds a number to x decimal places.
// Created : 			July 15, 2003
// Last Modified: 		Unknown
// Accepts:				number - the float to be changed to "count" decimal places.
//						count - the minimum number of decimal places
// Returns:				a number to "count" decimal places
//*********************************************************************************
function roundIt(number,count){
	//Convert value to string and split on the
	//decimal point. tempAmount[0] represents
	//dollars and tempAmount[1] represents cents.
	var outpt = "";
	var num = number+"";
	var index = num.indexOf('.');
	if(index==-1){
		return num;
	}else{
		var tempAmount = num.split(".");
		outpt = "1." + tempAmount[1];
		outpt = Math.round(parseFloat(outpt) * Math.pow(10, count));
		outpt = "" + outpt;
		if (parseInt(outpt.charAt(0)) > 1){
			tempAmount[0] = Math.round(parseFloat(tempAmount[0]) + 0.5);
			return parseFloat(tempAmount[0] + "." + outpt.slice(1, outpt.length));
		}else{
			return parseFloat(tempAmount[0] + "." + outpt.slice(1, outpt.length));
		}
	}
}


//*********************************************************************************
// Title: 				toTwoDecimal
// Desc: 				Changes an integer input into a 2 decimal number.
// Created : 			Unknown
// Last Modified: 		Unknown
// Accepts:				number - the integer to be changed to 2 decimal places.
// Returns:				a number to two decimal places
//*********************************************************************************
function toTwoDecimal(number){
	//Convert value to string and split on the
	//decimal point. tempAmount[0] represents
	//dollars and tempAmount[1] represents cents.
	var count = 2;
	var outpt = "";
	var num = number+"";
	var index = num.indexOf('.');
	if(index==-1){
		return num + ".00";
	}else{
		var tempAmount = num.split(".");
		outpt = "1." + tempAmount[1];
		outpt = Math.round(parseFloat(outpt) * Math.pow(10, count));
		outpt = "" + outpt;
		if (parseInt(outpt.charAt(0)) > 1){
			tempAmount[0] = Math.round(parseFloat(tempAmount[0]) + 0.5);
		}
		if (parseFloat(outpt) != 0){
			return tempAmount[0] + "." + outpt.slice(1, outpt.length);
		}else{
			return tempAmount[0] + ".00";
		}
	}
}
//*********************************************************************************
// Title: 				toTwoDecimalFr
// Desc: 				Changes an integer input into a 2 decimal number in french.
// Created : 			Unknown
// Last Modified: 		July 12, 2005
// Accepts:				number - the integer to be changed to 2 decimal places.
// Returns:				a number to two decimal places
//*********************************************************************************
function toTwoDecimalFr(number){
	//Convert value to string and split on the
	//decimal point. tempAmount[0] represents
	//dollars and tempAmount[1] represents cents.

	var count = 2;
	var outpt = "";
	var num = number+"";
	var index = num.indexOf(',');

	if(index==-1){
		return num + ",00";
	}else{
		var tempAmount = num.split(",");
		outpt = "1," + tempAmount[1];
		outpt = Math.round(parseFloat(outpt) * Math.pow(10, count));
		outpt = "" + outpt;
		
		if (parseInt(outpt.charAt(0)) > 1){
			tempAmount[0] = Math.round(parseFloat(tempAmount[0]) + 0.5);
		}
		if (parseFloat(outpt) != 0){
			return tempAmount[0] + "," + outpt.slice(1, outpt.length);
		}else{
			return tempAmount[0] + ",00";
		}
	}
}

//*********************************************************************************
// Title: 				dollarOutput
// Desc: 				Function dollarOutput(value) returns value
//						coverted to currency format. Commas are
//						inserted as needed. If value has more than
//						two digits after the decimal point, the
//						digits that follow the first two are truncated.
//						If value has no digits after the decimal point
//						or has one digit after the decimal point one or
//						two trailing zeroes are appended respectively as
//						done by the toTwoDecimal(value) function.
//						Precond: value is a number. 
// Created : 			Unknown
// Last Modified: 		June 19, 2003
// Accepts:				value - the number to be changed to dollar format.
// Returns:				a number to two decimal places
//*********************************************************************************
function dollarOutput(value){	
	toTwoDecimal(value);
	//Convert value to string and split on the
	//decimal point. tempAmount[0] represents
	//dollars and tempAmount[1] represents cents.
	var tempAmount = (value + "").split(".");
	
	var offset = 1;
	var amount = "";

	//Go through each character in the dollar part
	//of value.
	for(var i = tempAmount[0].length - 1; i >= 0; i--){	
		
		//If current offset is a multiple of 3 add a comma.
		if((offset++ % 3) == 0){
			amount = "," + tempAmount[0].substr(i,1) + amount
		}
		else{	
			amount = tempAmount[0].substr(i,1) + amount
		}	
  }
	
	//If value had digits after the decimal point
	//append those back.
	if(tempAmount.length == 2){
		amount += "." + tempAmount[1];
	}
		
	//Get rid of the leading comma if it exists.	
	if(amount.charAt(0) == "," || (amount.charAt(0) == "-" && amount.charAt(1) == ",")){
		amount = amount.replace(/,/,"");		
	}
	
	//Convert the final amount to
	//two decimal point format and return.
	return amount;
}

//*********************************************************************************
// Title: 				dollarOutputFr
// Desc: 				Function dollarOutput(value) returns value
//						coverted to currency format. Commas are
//						inserted as needed. If value has more than
//						two digits after the decimal point, the
//						digits that follow the first two are truncated.
//						If value has no digits after the decimal point
//						or has one digit after the decimal point one or
//						two trailing zeroes are appended respectively as
//						done by the toTwoDecimal(value) function.
//						Precond: value is a number. 
// Created : 			June 18, 2003 (modified dollarOutput)
// Last Modified: 		July 12, 2005
// Accepts:				value - the number to be changed to dollar format.
// Returns:				a number to two decimal places
//*********************************************************************************
function dollarOutputFr(value){	
	toTwoDecimal(value);
	//Convert value to string and split on the
	//decimal point. tempAmount[0] represents
	//dollars and tempAmount[1] represents cents.
	var tempAmount = (value + "").split(".");
	
	var offset = 1;
	var amount = "";

	//Go through each character in the dollar part
	//of value.
	for(var i = tempAmount[0].length - 1; i >= 0; i--){	
		
		//If current offset is a multiple of 3 add a comma.
		if((offset++ % 3) == 0){
			amount = " " + tempAmount[0].substr(i,1) + amount
		}
		else{	
			amount = tempAmount[0].substr(i,1) + amount
		}	
  }
	
	//If value had digits after the decimal point
	//append those back.
	if(tempAmount.length == 2){
		amount += "," + tempAmount[1];
	}
		
	//Get rid of the leading comma if it exists.	
	if(amount.charAt(0) == " " || (amount.charAt(0) == "-" && amount.charAt(1) == " ")){
		amount = amount.replace(/,/,"");		
	}
	
	//Convert the final amount to
	//two decimal point format and return.
	return amount;
}


//*********************************************************************************
// Title: 				dollarOutputFrNbsp
// Desc: 				Returns French currency format 
//						Using &nbsp; as the thousand seperator so number will be
//						wrapped in two lines
// Created : 			July 8, 2005 (modified dollarOutput)
// Last Modified: 		July 8, 2005
// Accepts:				value - the number to be changed to dollar format.
// Returns:				a number to two decimal places
//*********************************************************************************
function dollarOutputFrNbsp(value){	
	toTwoDecimal(value);
	//Convert value to string and split on the
	//decimal point. tempAmount[0] represents
	//dollars and tempAmount[1] represents cents.
	var tempAmount = (value + "").split(".");
	
	var offset = 1;
	var amount = "";

	//Go through each character in the dollar part
	//of value.
	for(var i = tempAmount[0].length - 1; i >= 0; i--){	
		
		//If current offset is a multiple of 3 add a comma.
		if((offset++ % 3) == 0){
			amount = "&nbsp;" + tempAmount[0].substr(i,1) + amount
		}
		else{	
			amount = tempAmount[0].substr(i,1) + amount
		}	
  }
	
	//If value had digits after the decimal point
	//append those back.
	if(tempAmount.length == 2){
		amount += "," + tempAmount[1];
	}
		
	//Get rid of the leading comma if it exists.	
	if(amount.charAt(0) == " " || (amount.charAt(0) == "-" && amount.charAt(1) == " ")){
		amount = amount.replace(/,/,"");		
	}
	
	//Convert the final amount to
	//two decimal point format and return.
	return amount;
}
//*********************************************************************************
// Title: 				dollarOutputNoDec
// Desc: 				Function dollarOutput(value) returns value
//						coverted to currency format. Commas are
//						inserted as needed. No Decimal places are returned.
// Created : 			July 17, 2003
// Last Modified: 		July 17, 2003
// Accepts:				value - the number to be changed to dollar format.
// Returns:				a number formatted with commas.
//*********************************************************************************
function dollarOutputNoDec(value){	
	
	//Convert value to string and split on the
	//decimal point. tempAmount[0] represents
	//dollars and tempAmount[1] represents cents.
	value = Math.round(value);
	var tempAmount = value + ""
	
	var offset = 1;
	var amount = "";

	//Go through each character in the dollar part
	//of value.
	for(var i = tempAmount.length - 1; i >= 0; i--){	
		
		//If current offset is a multiple of 3 add a comma.
		if((offset++ % 3) == 0){
			amount = "," + tempAmount.substr(i,1) + amount
		}
		else{	
			amount = tempAmount.substr(i,1) + amount
		}	
  }
		
	//Get rid of the leading comma if it exists.	
	if(amount.charAt(0) == "," || (amount.charAt(0) == "-" && amount.charAt(1) == ",")){
		amount = amount.replace(/,/,"");		
	}

	return amount;
	
}

//*********************************************************************************
// Title: 				dollarOutputNoDecFR
// Desc: 				Function ddollarOutputNoDecFR(value) returns value
//						coverted to currency format for French. Spaces are
//						inserted to replace the commas as needed. No Decimal places are returned.
// Created : 			Sept 17, 2003
// Last Modified: 		Sept 17, 2003
// Accepts:				value - the number to be changed to dollar format.
// Returns:				a number formatted with spaces instead of commas.
//*********************************************************************************

function dollarOutputNoDecFR(value){	
	
	//Convert value to string and split on the
	//decimal point. tempAmount[0] represents
	//dollars and tempAmount[1] represents cents.
	value = Math.round(value);
	var tempAmount = value + ""
	
	var offset = 1;
	var amount = "";

	//Go through each character in the dollar part
	//of value.
	for(var i = tempAmount.length - 1; i >= 0; i--){	
		
		//If current offset is a multiple of 3 add a space.
		if((offset++ % 3) == 0){
			amount = " " + tempAmount.substr(i,1) + amount
		}
		else{	
			amount = tempAmount.substr(i,1) + amount
		}	
  }
		
	//Get rid of the leading comma if it exists.	
	if(amount.charAt(0) == "," || (amount.charAt(0) == "-" && amount.charAt(1) == ",")){
		amount = amount.replace(/,/,"");		
	}

	return amount;
	
}



//*********************************************************************************
// Title: 				newWindow
// Desc: 				Opens a new window of standard size.
// Created : 			Unknown
// Last Modified: 		Jan 29, 2004
// Accepts:				help_url - the URL of the page to open
// Returns:				void
//*********************************************************************************
function newWindow(help_url, params) {
	var returnWindow = false;
	if(params){
		if(params["returnWindow"] && params["returnWindow"] == true) returnWindow = true;
	}
	var popupWin;
	popupWin = window.open(help_url,"popupWin","width=620,height=480,scrollbars=yes,menubars=yes,resizable=yes,top="+(screen.availHeight-480)/2+",left="+(screen.availWidth-620)/2);
	popupWin.focus();
	if(returnWindow) return popupWin;
}
//Usage:
//function newWindowMainHelp() { newWindow("help_getting_started.html"); }
//function newWindowEmail() { newWindow("help_getting_started.html#email"); }
//<a href="javascript:newWindowMainHelp()">

//*********************************************************************************
// Title: 				newCustomWindow
// Desc: 				Opens a new window of large size.
// Created : 			Nov 25, 2003
// Last Modified: 		Jan 29, 2004
// Accepts:				pop_url - the URL of the page to open
// Returns:				void
//*********************************************************************************
function newCustomWindow(pop_url,win_width,win_height,win_name) {
	var custWindow;
	if(pop_url.indexOf('/marketing/locators/TeamLocatorSearch') != -1){
		pop_url = '/ca/apply/afp-error.html';
	}
	if(!win_name){
		win_name="custWindow";
	}
	custWindow = window.open(pop_url,win_name,"width="+win_width+",height="+win_height+",scrollbars=yes,menubars=yes,resizable=yes,top="+(screen.availHeight-win_height)/2+",left="+(screen.availWidth-win_width)/2);
	custWindow.focus();	
	//return false;
}
//Usage:
//function newWindowMainHelp() { newCustomWindow("help_getting_started.html","500","500"); }
//function newWindowEmail() { newCustomWindow("help_getting_started.html#email","500","500"); }
//<a href="javascript:newWindowMainHelp()">

//*********************************************************************************
// Title: 				newCustToolbarWindow
// Desc: 				Opens a new window of standard size.
// Created : 			July 14, 2004
// Last Modified: 		July 14, 2004
// Accepts:				pop_url - the URL of the page to open
//						win_width,win_height - height and width
// Returns:				void
//*********************************************************************************
function newCustToolbarWindow(pop_url,win_width,win_height) {
	var toolbr;
	toolbr=window.open(pop_url,"apply","width="+win_width+",height="+win_height+",directories=no,hotkeys=no,location=no,menubar=no,personalbar=no,resizable=yes,scrollbars=yes,status=no,titlebar=no,toolbar=yes,top="+(screen.availHeight-win_height)/2+",left="+(screen.availWidth-win_width)/2);
	toolbr.focus();
	//return false;
}
//Usage:
//function newWindowMainHelp() { newCustNoScrollbarWindow("help_getting_started.html","500","500"); }
//function newWindowEmail() { newCustNoScrollbarWindow("help_getting_started.html#email","500","500"); }
//<a href="javascript:newWindowMainHelp()">

//*********************************************************************************
// Title: 				newCustNoScrollbarWindow
// Desc: 				Opens a new window of standard size.
// Created : 			Sept 25, 2006
// Last Modified: 		Sept 25, 2006
// Accepts:				pop_url - the URL of the page to open
//						win_width,win_height - height and width
//						win_name - name of popup window
// Returns:				void
//*********************************************************************************
function newCustNoScrollbarWindow(pop_url,win_width,win_height,win_name) {
	var toolbr;
	if (!win_name)  win_name = "apply";
	toolbr=window.open(pop_url,win_name,"width="+win_width+",height="+win_height+",directories=no,hotkeys=no,location=no,menubar=no,personalbar=no,resizable=yes,scrollbars=no,status=no,titlebar=no,toolbar=no,top="+(screen.availHeight-win_height)/2+",left="+(screen.availWidth-win_width)/2);
	toolbr.focus();
	//return false;
}
//*********************************************************************************
// Title: 				newCustStatusWindow
// Desc: 				Opens a new window of standard size, with a Status bar.
// Created : 			June 24, 2005
// Last Modified: 		June 24, 2005
// Accepts:				pop_url - the URL of the page to open
//						win_width,win_height - height and width
// Returns:				void
//*********************************************************************************
function newCustStatusWindow(pop_url,win_width,win_height) {
	var statusbar;
	statusbar=window.open(pop_url,"newWin1","width="+win_width+",height="+win_height+",directories=no,hotkeys=no,location=no,menubar=no,personalbar=no,resizable=yes,scrollbars=yes,status=yes,titlebar=no,toolbar=no,top="+(screen.availHeight-win_height)/2+",left="+(screen.availWidth-win_width)/2);
	statusbar.focus();
	//return false;
}

//Usage:
//function newWindowMainHelp() { newCustomWindow("help_getting_started.html","500","500"); }
//function newWindowEmail() { newCustomWindow("help_getting_started.html#email","500","500"); }
//<a href="javascript:newWindowMainHelp()">

//*********************************************************************************
// Title: 				newApplyWindow
// Desc: 				Opens a new window of standard size.
// Created : 			Jan 29, 2004
// Last Modified: 		Jan 29, 2004
// Accepts:				apply_url - the URL of the page to open
// Returns:				void
//*********************************************************************************
function newApplyWindow(apply_url) {
	var apply;
	apply=window.open(apply_url,"apply","width=640,height=470,directories=no,hotkeys=no,location=no,menubar=no,personalbar=no,resizable=yes,scrollbars=yes,status=yes,titlebar=no,toolbar=yes,top="+(screen.availHeight-470)/2+",left="+(screen.availWidth-640)/2);
	apply.focus();
	//return false;
}
//Usage:
//function newWindowMainHelp() { newWindow("help_getting_started.html"); }
//function newWindowEmail() { newWindow("help_getting_started.html#email"); }
//<a href="javascript:newWindowMainHelp()">

//*********************************************************************************
// Title: 				newApplyWindowLarge
// Desc: 				Opens a new window of standard size.
// Created : 			Jan 29, 2004
// Last Modified: 		Jan 29, 2004
// Accepts:				apply_url - the URL of the page to open
// Returns:				void
//*********************************************************************************
function newApplyWindowLarge(apply_url) {
	var applyLarge;
	applyLarge=window.open(apply_url,"applyLarge","width=797,height=550,directories=no,hotkeys=no,location=no,menubar=no,personalbar=no,resizable=yes,scrollbars=yes,status=yes,titlebar=no,toolbar=yes,top="+(screen.availHeight-550)/2+",left="+(screen.availWidth-797)/2);
	applyLarge.focus();
	//return false;
}
//*********************************************************************************
// Title: 				openWindowOpener
// Desc: 			opens the url in the opener window and focuses it. If the opener 
//						window doesn't exist, it opens and focuses a new window.
// Created : 			May 28, 2004
// Accepts:				url - the URL of the page to be redirected / opened
// Returns:				N/A
//*********************************************************************************
function openWindowOpener(url){
	if(top.opener && !top.opener.closed){
		top.opener.location=url;
		top.opener.focus();
	}else{
		replaceOpenerWindow = window.open(url,'newOpener');
		replaceOpenerWindow.focus();
	}
}


//Usage:
//function newWindowMainHelp() { newWindow("help_getting_started.html"); }
//function newWindowEmail() { newWindow("help_getting_started.html#email"); }
//<a href="javascript:newWindowMainHelp()">


//***********Required by surveyOpener*******************
// Created: 			March 1, 2005
// Last Modified: 		October 3, 2008
function surveyNotInterested(cookieName){
	if(document.surveyForm.surveyNone.checked){
		var nowDate = new Date();
		declinedDate = nowDate;
		declinedDate.setMonth(nowDate.getMonth() + 6);
		declinedDate.toGMTString();
		//alert(cookieName);
		setCookie(cookieName, 2, declinedDate);
		//alert(getCookieValue(cookieName));
	}
	document.getElementById('surveyDiv').style.display='none';
	document.getElementById('screenOverlay').style.display='none';
}
//***********Required by surveyOpener*******************
// Created: 			March 1, 2005
// Last Modified: 		October 3, 2008
function surveyTaken(surveyUrl, cookieName){
	surveyWindow = window.open(surveyUrl,'CIBCsurvey','height=580,width=825,top=20,left=20,scrollbars=yes,resizable=yes');
	surveyWindow.focus();
	window.blur();
	document.getElementById('surveyDiv').style.display='none';
	document.getElementById('screenOverlay').style.display='none';
	surveyTakenCookie(cookieName);
	return false;
}
//***********Required by surveyOpener*******************
// Created: 			March 31, 2005
// Last Modified: 		March 31, 2005
function surveyTakenCookie(cookieName){
	var nowDate = new Date();
	takenDate = nowDate;
	takenDate.setMonth(nowDate.getMonth() + 6);
	takenDate.toGMTString();
	setCookie(cookieName, 1, takenDate);
}
//***********Required by surveyOpener*******************
// Created: 			October 1, 2008
// Last Modified: 		October 1, 2008
function surveyNextPage(){
	document.getElementById('surveyPage1').style.display = 'none';
	document.getElementById('surveyPage2').style.display = 'block';
}

//************Required by surveyOpener********************************************
// Title: 				setDocumentProperties
// Desc: 				opens overlay DIV for flyover elements
// Created : 			October 1, 2008
// Last Modified: 		October 1, 2008
// Accepts:				N/A
// Returns:				N/A
//*********************************************************************************
function setDocumentProperties(){
	if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight) ){
		documentTop = document.documentElement.scrollTop;
		documentHeight = document.documentElement.clientHeight;
		documentLeft = document.documentElement.scrollLeft;
		documentWidth = document.documentElement.clientWidth;
	} 
	else{
		documentTop = document.body.scrollTop;
		documentHeight = document.body.clientHeight;
		documentLeft = document.body.scrollLeft;
		documentWidth = document.body.clientWidth;
	}
}
//*********************************************************************************
// Title: 				checkText
// Desc: 				Validates that the value of a field is text.
// Created : 			July 31, 2002
// Last Modified: 		Sept 23, 2002
// Accepts:				field - A reference to the field to be checked.
// Returns:				True if valid. False if not valid.
//*********************************************************************************
function checkText(field){
	var isValid = true;
	//field = eval(field);
	/*setup regular expression to use to validate text.  A backslash is used
	in the regular expression to escape a special regular expression
	character.  Since backslash is a special character within javascript, it
	must also be escaped, hence all the double slashes.  The expression
	includes alphanumerics, all standard puntuation, and extended latin
	characters.*/
	strExp = "^[A-Za-z0-9�-���������,/;:'-=_!@#%&\\\"\\f\\n\\r\\+\\*\\?\\.\\[\\]\\^\\$\\(\\)\\{\\}\\|\\\\\\&\\ ]+$";
	myReg = new RegExp(strExp);
	isValid = myReg.test(field.value);
	if(field.value.length > 0 && isValid){
		return true;
	}
	return false
}

//*********************************************************************************
// Title: 				checkRadio
// Desc: 				Validates that the value of a field is text.
// Created : 			July 31, 2002
// Last Modified: 		Sept 23, 2002
// Accepts:				field - A reference to the field to be checked.
// Returns:				True if valid. False if not valid.
//*********************************************************************************
function checkRadio(field){
	field = eval(field);
	for(var i=0; i<field.length; i++){
		if(field[i].checked){
			return true;
		}
	}
	return false;
}

//*********************************************************************************
// Title: 				isEmpty
// Desc: 				
// Created : 			Unknown
// Last Modified: 		Unknown
// Accepts:				inputStr
// Returns:				True if valid. False if not valid.
//*********************************************************************************
function isEmpty( inputStr )
{
   if ((inputStr!=null)&&(inputStr!="")) { var c='?'; for (var i=0; i < inputStr.length; i++) { c=inputStr.charAt(i); if (c!=" ") return false; } }
   return true;
}

//*********************************************************************************
// Title: 				isNumber
// Desc: 				
// Created : 			Unknown
// Last Modified: 		Unknown
// Accepts:				inputStr
// Returns:				True if valid. False if not valid.
//*********************************************************************************
function isNumber( inputStr )
{
   var c="?";
   for (var i=0; i < inputStr.length; i++) { c=inputStr.charAt(i); if (c!=" ") { if ((c<"0") || (c>"9")) return false; } }
   return true;
}

//*********************************************************************************
// Title: 				submitFeedbackForm
// Desc: 				
// Created : 			Unknown
// Last Modified: 		Unknown
// Accepts:				s
// Returns:				True
//*********************************************************************************
function submitFeedbackForm()
{
   document.feedback.submit(); return true;
}

//*********************************************************************************
// Title: 				isWhitespace
// Desc: 				
// Created : 			Unknown
// Last Modified: 		Unknown
// Accepts:				s
// Returns:				True if valid. False if not valid.
//*********************************************************************************
var whitespace = " \t\n\r";
function isWhitespace (s)
{   
    var i;

    // Is s empty?
    if (isEmpty(s)) return true;

    // Search through string's characters one by one
    // until we find a non-whitespace character.
    // When we do, return false; if we don't, return true.

    for (i = 0; i < s.length; i++)
    {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);

        if (whitespace.indexOf(c) == -1) return false;
    }

    // All characters are whitespace.
    return true;
}


//*********************************************************************************
// Title: 				isEmail
// Desc: 				
// Created : 			Unknown
// Last Modified: 		Unknown
// Accepts:				s
// Returns:				True if valid. False if not valid.
//*********************************************************************************
function isEmail (s)
{   
    if (isEmpty(s)) 
       if (isEmail.arguments.length == 1) return false;
       else return (isEmail.arguments[1] == true);
   
    // is s whitespace?
    if (isWhitespace(s)) return false;
    
    //If 1st character is not an alpha numeric, it is then not a valid email address.
    ch = s.charAt(0);
    if (!((ch >= "a" && ch <= "z") || (ch >= "A" && ch <= "Z" ) ||
          (ch >= "0" && ch <= "9") || (ch == "_") || (ch == "-"))) 
    {

       return false;
    }

    // there must be >= 1 character before @, so we
    // start looking at character position 1 
    // (i.e. second character)
    var i = 1;
    var sLength = s.length;

    // look for @
    while ((i < sLength) && (s.charAt(i) != "@"))
    {
       // ensure character is alpha, numeric, underscore, or a dot
       ch = s.substring(i, i+1);
       if (!((ch >= "a" && ch <= "z") || (ch >= "A" && ch <= "Z" ) ||
             (ch >= "0" && ch <= "9") || (ch == "_") || (ch == ".") || (ch == "-"))) 
       {

          return false;
       }
       if ((s.charAt(i) == ".") && (s.charAt(i+1) == ".")) {
          return false;
       }
       if ((s.charAt(i) == ".") && (s.charAt(i+1) == "@")) {
          return false;
       }
       i++;
    }

    if ((i >= sLength) || (s.charAt(i) != "@")) {
       return false;
    } else if ((s.charAt(i) == "@") && (s.charAt(i+1) == ".")) {
       return false;
    } else {
       i += 1;
    }
    
    // look for at least one dot
    while ((i < sLength) && (s.charAt(i) != "."))
    { 
       // ensure character is alpha, numeric, or underscore
       ch = s.substring(i, i+1);
       if (!((ch >= "a" && ch <= "z") || (ch >= "A" && ch <= "Z" ) ||
             (ch >= "0" && ch <= "9") || (ch == "_") || (ch == "-"))) 
       {
          return false;
       }

       i++;
    }

    // there must be at least one character after the dot
    if ((i >= sLength - 1) || (s.charAt(i) != ".")) return false;

    //ensure there are no consecutive dots.
    if ((s.charAt(i) == ".") && (s.charAt(i+1) == ".")) {
       return false;
    }

    // ensure the rest of the characters after the first "." are alpha, 
    // numeric, underscore, or a dot.
    while ((i < sLength)) {
       ch = s.substring(i, i+1);
       if (!((ch >= "a" && ch <= "z") || (ch >= "A" && ch <= "Z" ) ||
             (ch >= "0" && ch <= "9") || (ch == "_") || (ch == "."))) 
       {
          return false;
       }
       
       if ((s.charAt(i) == ".") && (s.charAt(i+1) == ".")) {
          return false;
       }
       i++;
    }

    // ensure the last character is not a dot
    if (s.charAt(sLength-1) == ".") {
       return false;
    }
    
    return true;
}


//*********************************************************************************
// Title: 				trailingCurrencyEnglish
// Desc: 				To handle maggic numbers like 4.000000002
// Created : 			July 12, 2005
// Last Modified: 		July 12, 2005

//*********************************************************************************
  
	  function trailingCurrencyEnglish(curValue)
  { 
   	    curValue = Math.round(parseFloat(curValue) *100) / 100.00;

		return curValue;
  }


//*********************************************************************************
// Title: 				trailingCurrencyFrench
// Desc: 				To handle maggic numbers like 4.000000002
// Created : 			July 12, 2005
// Last Modified: 		July 12, 2005

//*********************************************************************************
  
	  function trailingCurrencyFrench(curValue)
  {  // var curValue = curValue.toString(); 
   	    curValue = Math.round(parseFloat(curValue) *100) / 100.00;
		return curValue
  }

//*********************************************************************************
// Title: 				selectorFeature
// Desc: 				To handle passing values to the Credit Card Selector
// Created : 			March 10, 2006
// Last Modified: 		March 10, 2006

//*********************************************************************************
 	function selectorFeatureVISAEN() {
		if (document.getElementById('feature1').checked == true) {
			newCustomWindow('/ca/visa/article-tools/cc-selector-1.html?feature=1','740','540');
		}
		else {
			newCustomWindow('/ca/visa/article-tools/cc-selector-1.html?feature=2','740','540');
		}
	}

	function selectorFeatureVISAFR() {
		if (document.getElementById('feature1').checked == true) {
			newCustomWindow('/ca/visa/article-tools/cc-selector-1-fr.html?feature=1','740','540');
		}
		else {
			newCustomWindow('/ca/visa/article-tools/cc-selector-1-fr.html?feature=2','740','540');
		}
	}	

//*********************************************************************************
// Title: 				writeActiveXObject
// Desc: 				To fix IE 6 ActiveX update
// Created : 			May 31, 2006
// Last Modified: 		May 31, 2006

//*********************************************************************************
	function writeActiveXObject(text){
		document.write(text);
	}

//*********************************************************************************
// Title: 				Useful function to retrieve all elements of specified className
// Desc: 				Returns all elements of specified className
// Created : 			Feb 08, 2008
// Last Modified: 		Feb 08, 2008

//*********************************************************************************
	function getElementsByClassName(searchClass, node, tag) {
		var classElements = new Array();
		if (node == null) { node = document; }
		if (tag == null) { tag = '*'; }

		// safari mac 2.0 doesn't support this
		var els = node.getElementsByTagName(tag);

		var elsLen = els.length;
		var pattern = new RegExp("(^|\\s)" + searchClass + "(\\s|$)");
		for (var i = 0, j = 0; i < elsLen; i++) {
			if (pattern.test(els[i].className)) {
				classElements[j] = els[i];
				j++;
			}
		}
		return classElements;
	}

var locale = window.location.href.match(/\-fr\.html/gi) ? "fr" : "en";

/* the following two definitions are used for Class and Object creation */
var Prototype = {
  Version: '1.5.0_pre1',
  ScriptFragment: '(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)',

  emptyFunction: function() {},
  K: function(x) {return x}
}

var Class = {
  create: function() {
    return function() {
      this.initialize.apply(this, arguments);
    }
  }
}

/* checks if an object contains certain class(es) - className can be a string, array or hash */
function hasClass(obj, className){
	try{
		if(obj instanceof Array) for(var i=0,l=obj.length; i<l; i++){ hasClass(obj[i], className); }
		else{
			if(className instanceof Array){
				for(var i=0,l=className.length; i<l; i++){ 
					var result = hasClass(obj, className[i]); 
					if(result) return result;
				}
			}
			else if(className instanceof Object){
				for(_item in className){
					var result = hasClass(obj, className[_item]);
					if(result) return result;
				}
			}
			else return obj.className.match(new RegExp("\\b" + className + "\\b", "g"));
		}
	}catch(e){}
}

/* adds class(es) to object - className can be string, array, hash */
function addClass(obj, className){
	try{
		if(obj instanceof Array) for(var i=0,l=obj.length; i<l; i++){ addClass(obj[i], className); }
		else{
			if(className instanceof Array) for(var i=0,l=className.length; i<l; i++) addClass(obj, className[i]); 
			else if(className instanceof Object) for(_item in className) addClass(obj, className[_item]);
			else !obj.className.match(new RegExp("\\b" + className + "\\b", "gi")) ? obj.className += " " + className : 0; 
		}
	}catch(e){}
}

/* removes class(es) from object - className can be string, array, hash */
function removeClass(obj, className){
	try{
		if(obj instanceof Array) for(var i=0,l=obj.length; i<l; i++){ removeClass(obj[i], className); }
		else{
			if(className instanceof Array) for(var i=0,l=className.length; i<l; i++) removeClass(obj, className[i]);
			else if(className instanceof Object) for(_item in className) removeClass(obj, className[_item]);
			else obj.className = obj.className.replace(new RegExp("\\b" + className + "\\b", "gi"), "");
		}
	}catch(e){}
}

// transform number into proper dollar figure including decimals if left out
function toMoney(money, params){
	var sign = true;
	if(params){ params["sign"] == false ? sign = false : 0 ;}
	var matchPattern = { en:/^(\d+|,)+(\.)?$/, fr:/^(\d+|\s)+(,)?$/ }
	var replacePattern = { en:/(\.\d$)/, fr:/(,\d$)/ }
	var separatorPattern = { en:".", fr:","}

	money = money.replace(/\$/, "");
	money = (money.match(matchPattern[locale]) ?
		money + (RegExp.$1 ? separatorPattern[locale] : "") + "00" : 
		money.replace(replacePattern[locale], "$10"));
	return locale == "en" ? ((sign ? "$" : "") + money) : (money + (sign ? " $" : ""));
}

// add commas in proper places to the number passed in
function commify(num){
	var replacePattern = { en:/,/gi, fr:/ /gi };
	var splitPattern = { en:".", fr:"," };
	var injectPattern = { en:",", fr:" " };

	num = num.toString().replace(replacePattern[locale], "");
	x = num.split(".");
	x1 = x[0];
	x2 = x.length > 1 ? splitPattern[locale] + x[1] : "";
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) { x1 = x1.replace(rgx, "$1" + injectPattern[locale] + "$2"); }
	return x1 + x2;
}

function getNum(num){
	var replacePattern = { en:/[^\d\.]/gi, fr:/[^\d,]/gi }
	num = num.replace(replacePattern[locale], "");
	locale == "fr" ? num = num.replace(/,/, ".") : 0;
	return parseFloat(num);
}

var flyOverObject = null;			// global flyOver object
var wDynLink=null;

/* Generic flyOver code - uses the Prototype and Class methods at the top of the file*/
var FlyOver = Class.create();
FlyOver.prototype = {
	clickedObj:null,		// the clicked Object
	closer:null,			// the object(s) used to close the flyOver
	focus:null,				// specify the intial focus point, otherwise default to the first tabNavigable element
	fOObj:null,				// the flyOver element/block of code
	OVERLAY_TOP_OFFSET:0,	// the # of pixels to display the screen blocker from the top
	params:null				// flyOver global access to setup parameters
}

FlyOver.prototype.initialize = function(params){
	if(params == null) return;
	var self = this;			// need to define "self" to keep the scope of "this" when defining functions
	this.params = params;
	this.getClickedObj(params);

	try{ // treat nested flyOvers according to option passed in
		if(params.replaceFlyOver != null){
			this.parentFlyOver = flyOverObject.fOObj.id == params.flyover ?
				flyOverObject.parentFlyOver :	// opening and closing the same nested flyOver
				flyOverObject;
			this.parentFlyOver.childFlyOver = this;
			params.replaceFlyOver == true ? flyOverObject.fOObj.opener = null : 0;
		}
	}catch(e){}	// flyOver is not nested

	if(this.detachNested()) return; // if clicking the object which has spawned (nested) flyOver(s), do nothing

	this.fOObj = document.getElementById(params.flyover);	// the flyOver obj to attach
	this.fOObj.instance = this;

	if(this.fOObj.opener == this.clickedObj && !params.replaceFlyOver){
		this.fOObj.opener = null;
		return this.detach();
	}
	else this.fOObj.opener = this.clickedObj;

	// calculate the height by which to offset the screenOverly based on the header.  If doesn't exist, choose a worst case scenario height
	try{ 
		this.OVERLAY_TOP_OFFSET = this.params.screenBlockerOffset ? 
			this.params.screenBlockerOffset[1] :
			document.getElementById("contentHeader").offsetHeight; 
	}
	catch(e){ this.OVERLAY_TOP_OFFSET = 0; }

	this.setTabIndexing();
	this.focus = params.focus ? document.getElementById(params.focus) : this.fOObj.tabNavigables.first;

	// ensure that the close link(s) detache(s) the flyOver, if it/they exist(s)
	this.closer = getElementsByClassName("closer", this.fOObj);
		for(_item in this.closer){ this.closer[_item].onclick=function(){
			var child = self.childFlyOver;
			while(child){
				child.detach({enableEvents:true});
				child = child.childFlyOver;
			}
			self.detach({enableEvents:true}); 
		}
	}

	this.fOObj.onmouseup = function(){ 
		this.style.display == "block" && !wDynLink ? self.focusDefault() : 0;
		try{ this.instance.childFlyOver.detach({enableEvents:true}) }catch(e){  }
	}

	// disable the screen if default settings are used or if screenBlocker is set to "true"
	this.disableScreen();
	if(this.params.screenBlocker == false) this.enableScreen();

	setDocumentProperties();

	// show the flyOver and place focus into the first element unless we need to keep it hidden
	if(params.keepHidden == undefined && params.keepHidden != true) { this.setAndFocus(); }

	flyOverObject = this;	// set for global access

	// prevent local events from bubbling up to parent events
	addHandler("mousedown", this.fOObj, stopBubble);
	addHandler("mouseup", this.fOObj, stopBubble);
	addHandler("mouseup", this.clickedObj, stopBubble);

	if(this.params.screenBlocker == undefined ) addHandler("mousedown", this.objOverlay, stopBubble); // default setting only

	// clicking anywhere outside content area detaches the flyOver depending on screenBlocker options set
	document.body.onmousedown = function(){ flyOverObject.detach({enableEvents:true}); }
}

// detach the flyover from the parentNode
FlyOver.prototype.detach = function(params){
	var clickedAnchor = this.clickedObj;
	while(!clickedAnchor.nodeName.match(/^a|button$/i)){ clickedAnchor = clickedAnchor.parentNode };

	if(params && params.enableEvents){
		this.fOObj.opener = null;
		this.parentFlyOver && this.parentFlyOver.fOObj.opener == null ? removeHandler("mousedown", this.clickedObj, stopBubble) : 0;
	}

	flyOverObject = this.parentFlyOver && this.parentFlyOver.fOObj.opener != null ? this.parentFlyOver : null;
	flyOverObject == null ? document.body.onmousedown = null : 0;

	try{ flyOverObject.fOObj.childFlyOver = null; } catch(e){}
	this.enableScreen();
	this.fOObj.style.display = "none";

	if(IE){
		if(IE6){ try{this.fOObj.parentNode.removeChild(this.objIframe);}catch(e){} }
		// FIXME:  probably not needed anymore
		if(IEVersion == 7){ // helps prevent IE7 from crashing after focusing on non floating element
			CIBC.addClass(this.clickedObj, "IE7Floater");
			CIBC.removeClass(this.clickedObj, "IE7Floater");
		}
	}

	setTimeout(function(){ try{clickedAnchor.focus();}catch(e){} }, 0)
}

// detach nested flyOvers if applicable
FlyOver.prototype.detachNested = function(params){
	try{
		var parent = flyOverObject;
		while(parent.parentFlyOver){ parent = parent.parentFlyOver; }

		// if clicking the src element a 2nd time OR launching a flyOver unrelated to current open flyOver
		// then we must detach flyOvers down the chain
		if((parent && parent.clickedObj == this.clickedObj) || (params && params.forceDetach)){
			var child = parent;
			while(child){
				child.detach({enableEvents:true});
				child = child.childFlyOver;
			}
			parent.detach({enableEvents:true});	// this must be here to ensure the originating clickedObj receives final focus
			flyOverObject = null;
			return true;
		}
		else if(!this.parentFlyOver) this.detachNested({forceDetach:true}); // signal an unrelated flyOver opening
		return false;
	}catch(e){ return false; } // flyOver was not spawned by nesting or there are no flyOvers open
}

FlyOver.prototype.enableScreen = function(){ try{ this.objOverlay.style.display="none"; } catch(e){} }

FlyOver.prototype.disableScreen = function(className){
	if (this.objOverlay == null || this.objOverlay == undefined) { this.initOverlay(className); }
	this.objOverlay.style.display="block";
	var self = this;
	if(this.params.screenBlocker == undefined ) this.objOverlay.onclick=function(){ self.focusDefault() } // default option only
}

// create overlay div and hardcode some functional styles (aesthetic styles are in CSS file - scree-post.css)
FlyOver.prototype.initOverlay = function(className){
	// create the overlay element and give it properties
	if(this.params.screenBlockerAttachPoint){
		this.objBody = this.params.screenBlockerAttachPoint	== "body" ? 
			document.body :
			document.getElementById(this.params.screenBlockerAttachPoint);
	}
	else this.objBody = document.getElementById("mainPage");
	

	this.objOverlay = document.createElement("div");
	objOverlayPositioner = document.createElement("div");

	// IE6 needs an iframe to cover select boxes
	if(IE6){
		this.objIframe = document.createElement("iframe");
		this.objIframe.className = "flyOverIframe";
		this.objIframe.frameBorder = "0";
		this.objIframe.src = "/ca/img/spacer.gif"
		this.objIframe.style.display="block";
	}

	objOverlayPositioner.className = "screenOverlayPositioner";
	this.objOverlay.setAttribute("id", "screenOverlay");
	this.objOverlay.className = "screenOverlay" + (this.params.screenBlockerClassName ? " " + this.params.screenBlockerClassName : "");

	// set the positioning of the overlay and display it
	this.objOverlay.style.left = "0";
	this.objOverlay.style.top = this.OVERLAY_TOP_OFFSET + "px";
	this.objOverlay.style.width= this.objBody.offsetWidth + "px";
	this.objOverlay.style.height = (Math.max(this.objBody.offsetHeight, this.objBody.scrollHeight) - this.OVERLAY_TOP_OFFSET) + "px";

	objOverlayPositioner.appendChild(this.objOverlay);
	this.objBody.insertBefore(objOverlayPositioner, this.objBody.firstChild);
	this.objBody.appendChild(this.fOObj);

	this.objOverlay.style.display = "block";	
}

// position the flyOver and set focus into the default location
FlyOver.prototype.setAndFocus = function(){
	this.setFOPosition();
	this.focusDefault(); 
}

// get the object clicked that triggered flyOver activation
FlyOver.prototype.getClickedObj = function(params){
	if(this.params.replaceFlyOver) return this.clickedObj = flyOverObject.clickedObj;
	this.clickedObj = params.e.target || params.e.srcElement;
	addHandler("mousedown", this.clickedObj, stopBubble);
}

// focus in on the default element when the flyOver appears
FlyOver.prototype.focusDefault = function(){
	this.fOObj.style.display = 'block';
	setTimeout(function(){ try{flyOverObject.fOObj.tabNavigables.first.focus()}catch(e){} }, 0)
}

FlyOver.prototype.setTabIndexing = function(){
	this.fOObj.tabNavigables = CIBC.getTabNavigable(this.fOObj);

	// if the flyOver is just plain text, then insert an anchor at the top for accessibility purposes
	if(!this.fOObj.tabNavigables){
		var anchor = document.createElement("a");
		anchor.className = "textOnlyContent";
		anchor.href = "javascript:void(0)";
		this.fOObj.insertBefore(anchor, this.fOObj.childNodes[0]);
		this.fOObj.tabNavigables = { first:anchor, last:anchor, lowest: 0 };
	}

	this.fOObj.tabNavigables.first.tabIndex = this.fOObj.tabNavigables.lowest;

	this.fOObj.onkeydown = function(e){
		e = e || event;
		var keyCode = CIBC.getKeyCode(e);
		var node = e.target || e.srcElement;
		var singleFocusItem = (this.tabNavigables.first == this.tabNavigables.last);
		if(keyCode.key == CIBC.keyEvent.ESC){
			flyOverObject.detach({enableEvents:true});
		}
		else if(node == this.tabNavigables.first && keyCode.key == CIBC.keyEvent.TAB && keyCode.modifiers.shift){ 
			!singleFocusItem ? this.tabNavigables.last.focus() : 0;
			CIBC.stopEvent(e);
		}
		else if(node == this.tabNavigables.last && keyCode.key == CIBC.keyEvent.TAB && !keyCode.modifiers.shift){
			!singleFocusItem ? this.tabNavigables.first.focus() : 0;
			CIBC.stopEvent(e);
		}
	}
}

// calculate the exact position of the obj on screen - does not alter the actual object passed in
FlyOver.prototype.getObjPos = function(obj){
	var leftPos = topPos = 0;
	while (obj.offsetParent){
		topPos += obj.offsetTop;
		leftPos += obj.offsetLeft;
		obj = obj.offsetParent;
	}
	return { left:leftPos, top:topPos };
}

// set the position of the flyOver
// note that Safari needs to the object to be displayed in order to be able to calculate & set the fOObj position
FlyOver.prototype.setFOPosition = function(){
	this.fOObj.style.display = "block";
	var coords = this.getObjPos(this.clickedObj);
	var position = this.params.position;

	if(position){	// position the flyOver against other screen elements or a specific x,y coordinate
		var isArray = position instanceof Array;
		var hObj = vObj = sameObj = 0;

		if(isArray && position.length > 1){ hObj = position[0]; vObj = position[1];	}
		else eval("sameObj=true; hObj = vObj = position" + (isArray && position.length == 1 ? "[0]" : ""));

		var getPosition = function(node){
			return node = typeof(node) == "string" ?
					node.match(/^body$/gi) ? document.documentElement :
					document.getElementById(node) :
					node;
		}

		hObj = getPosition(hObj);
		vObj = sameObj ? hObj : getPosition(vObj);

		var offsetLeft = hObj == document.documentElement || typeof(hObj) == "number" ? 0 : hObj.offsetLeft;
		var offsetTop = vObj == document.documentElement || typeof(vObj) == "number" ? 0 : vObj.offsetLeft;

		if(this.params.offset){
			this.params.offset[0] ? offsetLeft += this.params.offset[0] : 0;
			this.params.offset[1] ? offsetTop += this.params.offset[1] : 0;
		}

		this.fOObj.style.left = (typeof(hObj) == "number" ? hObj :
			(hObj.clientWidth / 2) + offsetLeft - (this.fOObj.offsetWidth / 2)) + "px";

			this.fOObj.style.top = (typeof(vObj) == "number" ? vObj :
			Math.min((vObj.clientHeight, (window.innerHeight || vObj.offsetHeight)) / 2) + offsetTop - (this.fOObj.offsetHeight / 2)) + (window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop) + "px";

	}
	else{	// position the flyOver relative to the clicked object
		try { 
			var offsetLeft = this.params.replaceFlyOver && this.params.replaceFlyOver == true ?
				this.parentFlyOver.params.offset[0] : this.params.offset[0]; 
		} catch(e){ var offsetLeft = 0; }

		this.fOObj.style.left = coords.left + offsetLeft + this.clickedObj.offsetWidth + "px";
		this.fOObj.style.top = this.setFOTop(coords.top) + "px";
	}

	if(IE6){ // place the iframe in the correct location and size it accordingly
		this.fOObj.parentNode.insertBefore(this.objIframe, this.fOObj);
		this.objIframe.style.left = this.fOObj.style.left;
		this.objIframe.style.top = this.fOObj.style.top;
		this.objIframe.style.width = this.fOObj.offsetWidth + "px";
		this.setIframeHeight();
	}
	this.fOObj.style.display = "none";
}
// sets or resets Iframe height, also used by FE development after an error is generated inside a flyover.
FlyOver.prototype.setIframeHeight = function(){ IE6 ? this.objIframe.style.height= this.fOObj.offsetHeight + "px" : 0; }

// makes sure that attaching the flyOver (with any offsets) does not appear below the visible browser area
FlyOver.prototype.setFOTop = function(top){
	topPos = top || this.getObjPos(this.clickedObj).top;
	try{
		var offsetTop = this.params.replaceFlyOver && this.params.replaceFlyOver == true ?
			this.parentFlyOver.params.offset[1] : this.params.offset[1]; 
	} catch(e){ var offsetTop = 0; }

	var result = ((topPos + this.fOObj.offsetHeight) > (documentHeight + documentTop)) && 
		(topPos - (this.fOObj.offsetHeight + offsetTop)) > documentTop ?
		topPos -= this.fOObj.offsetHeight : topPos += offsetTop; 
	return result;
}

var Cibc = Class.create();
Cibc.prototype = {
	initialize	:	function(){},
	keyEvent	:	{ ENTER:13, ESC:27,TAB:9 },
	tabElements	:	{ area:true, button:true, input:true, object:true, select:true, textarea:true }
}

// parses through all descendants to figure out which set of nodes are tab-navigable
Cibc.prototype.getTabNavigable = function(node){
	var first, last, lowest, lowestTabindex, highest, highestTabindex;
	var lowestTabindex = highestTabindex = 0;
	var hasTabNavigable = false;
	var childNodes = node.getElementsByTagName("*");
	for(_item in childNodes){
		child = childNodes[_item];
		try{
			var isTabable = this.isTabNavigable(child);
			if(isTabable){
				hasTabNavigable = true;
				addHandler("mouseup", child, stopBubble);
				var tabindex = isTabable[1];
				if(!tabindex || tabindex == 0){
					!first ? first = child : 0;
					last = child;
				}
				else if(tabindex > 0){
					if(!lowest || tabindex < lowestTabindex){
						lowestTabindex = tabindex;
						lowest = child;
					}
					if(!highest || tabindex >= highestTabindex){
						highestTabindex = tabindex;
						highest = child;
					}
				}
			}
		}catch(e){}
	}
	return hasTabNavigable ? { first:first, last:last, lowest:lowest, highest:highest } : null;
}

// returns true & the tabindex if the object is tab-navigable, false otherwise
Cibc.prototype.isTabNavigable = function(obj){
	if(this.hasAttribute(obj, "disabled") || !this.isObjVisible(obj) || obj.type.match(/hidden/gi)){ return false; }
	var hasTabindex = this.hasAttribute(obj, "tabindex");
	var tabindex = obj.getAttribute("tabindex");
	var name = obj.nodeName.toLowerCase();

	return	(hasTabindex && tabindex >= 0) ||
			(((name == "a" && this.hasAttribute(obj, "href")) || CIBC.tabElements[name]) && (!hasTabindex || tabindex >= 0)) ? 
			[true, tabindex] : false;
}

Cibc.prototype.hasAttribute = function(node, name){
	var attr = node.getAttributeNode(this.fixAttrName(name));
	return attr ? attr.specified : false;
}

// IE6 & 7 will only recognize attribute as tabIndex, other attributes are fine w/o capitalization
Cibc.prototype.fixAttrName = function(name){ return name.match(/tabindex/gi) ? IE && IEVersion < 8 ? "tabIndex" : "tabindex" : name; }

Cibc.prototype.isObjVisible = function(obj){
	return !obj.style.visibility.match(/hidden|collapsed/gi) && !obj.style.display.match(/none/) && !obj.className.match(/hide/gi);
}

Cibc.prototype.getKeyCode = function(e){ 
	var evt = window.event ? event : e;
	return { key:evt.keyCode, modifiers:{alt:evt.altKey, ctrl:evt.ctrlKey, shift:evt.shiftKey} }
}

Cibc.prototype.stopEvent = function(evt){
	if(IE){
		evt = window.event;
		evt.preventDefault = function(){
			this.bubbledKeyCode = this.keyCode;
			if(this.ctrlKey){CIBC._trySetKeyCode(this, 0);}
			this.returnValue = false;
		}
	}
	evt.preventDefault();
}

Cibc.prototype._trySetKeyCode = function(e, code){
	try{ return (e.keyCode = code); } // squelch errors when keyCode is read-only (e.g. if keyCode is ctrl or shift)
	catch(e){ return 0; }
}

/* adds class(es) to object(s) - objects and className can be string, array, hash */
Cibc.prototype.addClass = function (obj, className){ addClass(obj, className); }

/* removes class(es) from object(s) - objects and className can be string, array, hash */
Cibc.prototype.removeClass = function(obj, className){ removeClass(obj, className); }

/* checks if object(s) contains certain class(es) - objects and className can be a string, array or hash */
Cibc.prototype.hasClass = function(obj, className){ hasClass(obj, className); }

CIBC = new Cibc();

function addHandler(whichEvent, whichObject, attachThis){ 
	try{ whichObject.addEventListener(whichEvent, attachThis, 0); }  	// Non-IE
	catch(e){whichObject.attachEvent("on" + whichEvent, attachThis);}	// IE
} 

function removeHandler(whichEvent, whichObject, removeThis){
	try{ whichObject.removeEventListener(whichEvent, removeThis, 0); }	// Non-IE
	catch(e){whichObject.detachEvent("on" + whichEvent, removeThis);}	// IE
}

// prevents firing parent onclick events when clicking on child element
function stopBubble(objEvent){
	try{
		if(!objEvent.stopPropagation){ objEvent = window.event; objEvent.cancelBubble = true; } 
		if(objEvent.stopPropagation){objEvent.stopPropagation();} 
	} catch(e){}
}

//*********************************************************************************
// Title:                       setHighContrast
// Desc: 				Sets the "high contrast mode" stylesheet and sets the cookie to remember it.
// Created : 			July 27, 2009
// Last Modified: 		August 21, 2009
// Returns:				void
//*********************************************************************************

function setHighContrast( IContrast ) {
	try {	// Must fail silently if the <link/> elements aren't present
		if( IContrast == 0 ) {
			document.getElementById( "highContrastLink" ).href = "/ca/norm_contrast.css";

			document.getElementById( "normalContrast" ).className = "contrastOff";
			document.getElementById( "normalContrast" ).removeAttribute( "href" );

			document.getElementById( "highContrast" ).className = "";
			document.getElementById( "highContrast" ).setAttribute( "href", "javascript:setHighContrast(1)" );
		} else {
			document.getElementById( "highContrastLink" ).href = "/ca/high_contrast.css";

			document.getElementById( "normalContrast" ).className = "";
			document.getElementById( "normalContrast" ).setAttribute( "href", "javascript:setHighContrast(0)" );

			document.getElementById( "highContrast" ).className = "contrastOff";
			document.getElementById( "highContrast" ).removeAttribute( "href" );
		}

		setCookie( "CIBC_Contrast", IContrast );
	} catch( err ) {}
}

//*********************************************************************************
// Title: 				textSize
// Desc: 				Loads in a variable "text size" stylesheet and sets the cookie to remember it.
// Created : 			July 27, 2009
// Last Modified: 		August 21, 2009
// Accepts:				ISize: non-negative integral size variable; must have a corresponding textsize-X.css
// Returns:				void
//*********************************************************************************
function textSize( ISize ) {
	try {	// Must fail silently if the <link/> elements aren't present
		if( ISize === null ) {
			ISize = 0;
		}

		document.getElementById( "textSizeLink" ).href = "/ca/textsize-" + ISize + ".css";

		AButtons = getElementsByClassName( "letterButton", null, "img" );
		if( AButtons.length > 0 ) {
			IButtons = AButtons.length;
			for( i = 0; i != IButtons; i++ ) {
				if( i == ISize ) {
					SSelected = "sel";
				} else {
					SSelected = "des";
				}

				AButtons[i].src = "/ca/img/accessibility/" + i + "-" + SSelected + ".gif";
			}
		}

		setCookie( "CIBC_TextSize", ISize );
	} catch( err ) {}
}

//*********************************************************************************
// Title: 				setInitialAccessibility
// Desc: 				Presets the user's contrast and text size modes from the cookie.
// Created : 			July 27, 2009
// Last Modified: 		July 28, 2009
// Returns:				void
//*********************************************************************************
function setInitialAccessibility() {
	var IContrast = getCookieValue( "CIBC_Contrast" );
	if( IContrast === null ) {
		IContrast = 0;
	}

	setHighContrast( IContrast );

	var ISize = getCookieValue( "CIBC_TextSize" );
	textSize( ISize );
}

// add setInitialAccessibility to the window's onLoad chain.
//window.addEventListener( "load", setInitialAccessibility, false );
window.setTimeout( setInitialAccessibility, 100 );

//*********************************************************************************
//Title: 				getFlashVersion
//Desc: 				Returns the browser's version of Shockwave Flash
//Created : 			August 28, 2009
//Last Modified: 		August 28, 2009
//Returns:				int   The major version number
//*********************************************************************************

function getFlashVersion() {
	var IFlashVersion;
	var OFlashPlugin;

	if( navigator.plugins && navigator.plugins.length ) {
		OFlashPlugin = navigator.plugins["Shockwave Flash"];

		if( OFlashPlugin.description ) {
			var AMatches = OFlashPlugin.description.match( /[\d]+/g );
			AMatches.length = 3; // To standardize IE vs FF
			IFlashVersion = AMatches.join( '.' ); 
		}
	} else {
		result = false;
		for( var i = 15; i >= 3 && result != true; i-- ){
			execScript( 'on error resume next: result = IsObject(CreateObject("ShockwaveFlash.ShockwaveFlash.' + i + '"))','VBScript' );
			IFlashVersion = i;
		}
	}

	return parseInt( IFlashVersion );
}

// *********************************************************************************
// Title: 				RotatingAd
// Desc: 				Pseudo-Object to represent a 
// Created : 			August 28, 2009
// Last Modified: 		August 31, 2009
// Accepts:				cookieName - Name of the cookie.
// Returns:			    Object
//*********************************************************************************

function RotatingAd( SSource, STargetURI, SAlternate, STitle, BFlash, BNewWindow, BMultiple ) {
	this.source = SSource;
	this.uri = STargetURI;
	this.alt = SAlternate;
	this.title = STitle;
	this.flash = ( BFlash ? true : false );
	this.newWin = ( BNewWindow ? true : false );
	this.multi = ( BMultiple ? true : false );
}

// *********************************************************************************
// Title: 				generateRotatingSpotlight
// Desc: 				Creates the markup for a 523x213 rotating Spotlight, chosen from a
//                      pre-existing global array of Spotlights. 
// Created : 			March 03, 2010
// Last Modified: 		March 03, 2010
// Requires:            Global array "ARotatingSpots"
// Returns:				string
// *********************************************************************************

ARotatingSpots = new Array();
function generateRotatingSpotlight(spot1,spot2) {
	var SRotatingSpot = '';
	var IAdOffset = ( Math.random().toString().slice( -4 ) % ARotatingSpots.length );
	
	var ASelectedSpot = ARotatingSpots.splice( IAdOffset, 1 );
	var OSelectedSpot = ASelectedSpot[0];
	var spotHeight,spotWidth;
	if ( spot1 != null )  {
		spotWidth = Math.floor( spot1 );
	}
   if ( spot2 != null )  {
		spotHeight = Math.floor( spot2 );
	}
	if( spotWidth == null ) {
		spotWidth = 523;
	}
	if( spotHeight == null ) {
		spotHeight = 213;
	}
	
		if( OSelectedSpot.flash ) {
			
				SRotatingSpot = '<div class="flashAlt">\
				<p>Flash Transcript</p>\
				<p>'+ OSelectedSpot.title +'</p></div>\
				<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="'+ spotWidth +'" height="'+ spotHeight +'" id="myFlashContent" style="float:left;">\
				<param name="movie" value="'+ OSelectedSpot.source +'">\
				<param name="wmode" value="transparent">\
				<!--[if !IE]>-->\
				<object type="application/x-shockwave-flash" data="'+ OSelectedSpot.source +'" width="'+ spotWidth +'" height="'+ spotHeight +'" wmode="transparent">\
				<!--<![endif]-->\
				<a href="'+ OSelectedSpot.uriNoflash +'"><img src="'+ OSelectedSpot.img +'" width="'+ spotWidth +'" height="'+ spotHeight +'" alt="'+ OSelectedSpot.alt +'" style="float:left;" ></a>\
				<!--[if !IE]>-->\
				</object>\
				<!--<![endif]-->\
			</object>';
						
		} else {
			var STarget;

			if( OSelectedSpot.newWin ) {
				STarget = ' target="_blank"';
			} else {
				STarget = '';
			}

			SRotatingSpot = '<div id="spotLightRot"><a href="' + OSelectedSpot.uri + '"' + STarget + '><img border="0" src="' + OSelectedSpot.source + '" width="'+ spotWidth +'" height="'+ spotHeight +'" alt="' + OSelectedSpot.alt +'" title="' + OSelectedSpot.title + '" /></a></div>';
		}

	return SRotatingSpot;
}


// *********************************************************************************
// Title: 				generateRotatingAd
// Desc: 				Creates the markup for a 255x115 rotating ad, chosen from a
//                      pre-existing global array of ad specifications. Removes the
//                      item from the array to prevent displaying multiple copies of
//                      the same ad.
// Created : 			August 28, 2009
// Last Modified: 		September 9, 2009
// Requires:            Global array "ARotatingAds"
// Accepts:				cookieName - Name of the cookie.
// Returns:				string
// *********************************************************************************

ARotatingAds = new Array();
function generateRotatingAd() {
	var SRotatingAd = '';
	var IAdOffset = ( Math.random().toString().slice( -4 ) % ARotatingAds.length );
	
	var ASelectedAd = ARotatingAds.splice( IAdOffset, 1 );
	var OSelectedAd = ASelectedAd[0];
	if( OSelectedAd.uri != '' ) {
		if( OSelectedAd.flash ) {
			if ( getFlashVersion() > 5 ) {
				SRotatingAd = '<object id="rotated" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0" width="255" height="115">\
	<param name="movie" value="' + OSelectedAd.source + '">\
	<param name="FlashVars" value="' + OSelectedAd.uri + '">\
	<param name="bgcolor" value="#FFFFFF">\
	<param name="wmode" value="transparent">\
	<param name="menu" value="false">\
	<param name="quality" value="high">\
	<param name="salign" value="tl">\
	<param name="scale" value="noscale">\
	<embed id="rotated" src="' + OSelectedAd.source + '" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" flashvars="' + OSelectedAd.uri + '" bgcolor="#FFFFFF" menu="false" quality="high" salign="tl" scale="noscale" width="255" height="115" wmode="transparent"></embed>\
</object>';
			} else {
				SRotatingAd = '	<a href="' + OSelectedAd.uri + '"><img src="' + OSelectedAd.alt + '" alt="' + OSelectedAd.title + '" title="' + OSelectedAd.title + '" width="255" height="115" /></a>';
			}
		} else {
			var STarget;

			if( OSelectedAd.newWin ) {
				STarget = ' target="_blank"';
			} else {
				STarget = '';
			}

			SRotatingAd = '<a href="' + OSelectedAd.uri + '"' + STarget + '><img src="' + OSelectedAd.source + '" width="255" height="115" alt="' + OSelectedAd.alt +'" title="' + OSelectedAd.title + '" /></a>';
		}
	}

	return SRotatingAd;
}

var BUTTONDIR = "/ca/img/button/";
var EXPANDTABLE_MINUS_BUTTON = "expandtable-minus.gif";
var EXPANDTABLE_PLUS_BUTTON  = "expandtable-plus.gif";

function collapseRows( SRowClass ) {
	if( SRowClass == "" ) {
		return false;
	}

	ARows = getElementsByClassName( SRowClass, null, "tr" );
	if( ARows.length > 0 ) {
		IRows = ARows.length;
		for( var i = 0; i != IRows; i++ ) {
			ARows[i].style.display = 'none';
		}

		AButtons = getElementsByClassName( "toggleImage", null, "img" );
		if( AButtons.length > 0 ) {
			IButtons = AButtons.length;
			for( i = 0; i != IButtons; i++ ) {
				AButtons[i].src = BUTTONDIR + EXPANDTABLE_PLUS_BUTTON;
			}

			return true;
		} else {
			return false;
		}
	} else {
		return false;
	}
}

function toggleRows( SIDPrefix ) {
	var BFailed = false;
	var IRow = 0;
	var SRowDisplay = "";
	var EThisRow;

	while( BFailed === false ) {
		try {
			EThisRow = document.getElementById( SIDPrefix + IRow );
			EThisRow.style.display = ( EThisRow.style.display == "block" ) ? "none" : "block";
			IRow++;
		} catch( e ) {
			BFailed = true;
		}
	}

	BFailed = null;
	IRow = null;
}

function tableButton( SIDPrefix, SRowClass ) {
	if( document.getElementById( SIDPrefix + "0" ).style.display != "block" ) {
		collapseRows( SRowClass );
	}

	toggleRows( SIDPrefix );

	var EThisRowButton = document.getElementById( SIDPrefix + "Button" );
	EThisRowButton.src = ( EThisRowButton.src.indexOf(EXPANDTABLE_MINUS_BUTTON) != -1 ) ? BUTTONDIR + EXPANDTABLE_PLUS_BUTTON : BUTTONDIR + EXPANDTABLE_MINUS_BUTTON;
}
// *********************************************************************
// Branch Locator - Find Us
// *********************************************************************
function focusInput(obj){
            if(obj.value==obj.title){
                obj.value='';
            }
}

// *********************************************************************************
// Title: 				getIntelliResponseResult
// Desc: 				Sends the IntelliResponse question to the server and
//                      displays the result in a new window.
// Merged into common:  November 3, 2009
// Last Modified: 		November 3, 2009
// Accepts:				SQuestion - String containing the question to send.
//                      SLanguage - String containing the language code to use, "en" or "fr".
// Returns:				void
// *********************************************************************************
function getIntelliResponseResult( SQuestion, SLanguage ){
	var searchForm;  
	var url = "http://cibc.intelliresponse.com/public/" + SLanguage + "/index.jsp?";
	var interfaceID="interfaceID=8";
	var id="id=-1";
	var requestType="requestType=NormalRequest"
	var source="source=1";
	var question="question="+SQuestion;

	searchForm = window.open(url+requestType+'&'+interfaceID+'&'+id+'&'+source+'&'+question,'snivel',"scrollbars=yes,menubars=no,resizable=no, toolbar=no,directories=no,status=no,width=745,height=535,top="+(screen.availHeight-550)/2+",left="+(screen.availWidth-797)/2);
}

// *********************************************************************************
// Title: 				generateIntelliResponse
// Desc: 				Creates the markup for an IntelliResponse box, according to
//      				provided language and width information, with optional "Top
//      				Ten FAQ" Category to send to IntelliResponse.
// Created:				November 2, 2009
// Last Modified: 		November 3, 2009
// Accepts:				MParam1, MParam2, MParam3: parameters can be provided in
//         				either order. Language must specify French as "FR" (default
//         				is English), and width must be in pixels (default is 523)
//         				and represent the width of the parent box. Pixels are
//         				required for proper width calculations. Arguments that
//         				aren't string or numeric will be ignored, and if the first
//         				string argument seen is a language, the last string
//         				argument will be assumed to be the top ten category.
// Returns:				string
// *********************************************************************************
function generateIntelliResponse( MParam1, MParam2, MParam3 ) {
	var SLanguage = "", IWidth, STopTenCat = "";

	if( ( MParam1 != null ) && ( typeof MParam1 == "string" ) ) {
		if( MParam1.length < 3 ) {
			if( MParam1 == "FR" ) {
				SLanguage = "FR";
			} else {
				SLanguage = "EN";
			}
		} else {
			STopTenCat = "&amp;TopTenCategoryName=" + MParam1.replace( /\s/g, "%20" );
		}
	} else if( typeof MParam1 == "number" ) {
		IWidth = Math.floor( MParam1 );
	}

	if( MParam2 != null ) {
		if( typeof MParam2 == "string" ) {
			if( ( MParam2.length < 3 ) && ( SLanguage == "" )  ) {
				if( MParam2 == "FR" ) {
					SLanguage = "FR";
				} else {
					SLanguage = "EN";
				}
			} else {
				STopTenCat = "&amp;TopTenCategoryName=" + MParam2.replace( /\s/g, "%20" );
			}
		} else if( typeof MParam2 == "number" ) {
			IWidth = Math.floor( MParam2 );
		}
	}

	if( MParam3 != null ) {
		if( typeof MParam3 == "string" ) {
			if( ( MParam3.length < 3 ) && ( SLanguage == "" )  ) {
				if( MParam3 == "FR" ) {
					SLanguage = "FR";
				} else {
					SLanguage = "EN";
				}
			} else {
				STopTenCat = "&amp;TopTenCategoryName=" + MParam3.replace( /\s/g, "%20" );
			}
		} else if( typeof MParam3 == "number" ) {
			IWidth = Math.floor( MParam3 );
		}
	}

	if( IWidth == null ) {
		IWidth = 523;
	}

	IWidth -= 27;

	if( SLanguage != "FR" ) {
		SLanguage = "EN";

		SBoxTitle = "Have a question?";
		SPrefillInput = "Type your complete question here";
		SButtonSrc = "/ca/img/button/but-ask-en.gif";
		SButtonAlt = "Ask";
		FFieldSize = ( IWidth - 55.0 - 10 ) / IWidth * 100; // The trailing decimal ensures the fraction is floating point.
		SFinalPara = "Enter your question in sentence form, for example: What is an RRSP?\
			<br/>\
			<a onclick=\"newCustomWindow('http://cibc.intelliresponse.com/public/en/index.jsp?interfaceID=8&amp;requestType=TopQuestionsRequest" + STopTenCat + "','745','535');return false;\" href=\"http://cibc.intelliresponse.com/public/en/index.jsp?interfaceID=8&amp;requestType=TopQuestionsRequest" + STopTenCat + "\">View the top 10 questions</a>";
	} else {
		SBoxTitle = "Vous avez une question?";
		SPrefillInput = "Inscrivez votre question ici";
		SButtonSrc = "/ca/img/button/but-ask-fr.gif";
		SButtonAlt = "Poser la question";
		FFieldSize = ( IWidth - 143.0 - 8 ) / IWidth * 100; // The trailing decimal ensures the fraction is floating point.
		SFinalPara = "Posez une question sous forme de phrase complète telle que&nbsp;: «&nbsp;Qu’est-ce qu’un REER?&nbsp;»\
			<br/>\
			<a onclick=\"newCustomWindow('http://cibc.intelliresponse.com/public/fr/index.jsp?interfaceID=31&amp;requestType=TopQuestionsRequest" + STopTenCat + "','745','535');return false;\" href=\"http://cibc.intelliresponse.com/public/fr/index.jsp?interfaceID=31&amp;requestType=TopQuestionsRequest" + STopTenCat + "\">Voir les dix questions les plus fréquemment posées</a>";
	}

	//The intelliresponse box is formed below
	SOutput = "<div class=\"boxTop intelli\"><div class=\"boxBottom\"><div class=\"boxTopExtended\"><div class=\"boxBottomExtended\">\
	<div class=\"boxTitle\"><h4>" + SBoxTitle + "</h4></div>\
	<div style=\"float: left; width: " + FFieldSize + "%;\"><label for=\"question\" style=\"display:none;\">Have a question?</label><input  type=\"text\" style=\"width: 99.5%;\"  onKeyPress=\"return submitenter(event,'"+ SLanguage.toLowerCase() +"')\"  onfocus=\"this.value='';\" maxlength=\"200\" value=\"" + SPrefillInput + "\" id=\"question\" name=\"question\" class=\"inputBox\"   /></div>\
	<div style=\"float: right; text-align: right; width: " + ( 99.0 - FFieldSize ) + "%;\"><img alt=\""+SButtonAlt+"\" style=\"cursor:hand;cursor:pointer;\" src=\"" + SButtonSrc + "\" border=\"0\" onclick=\"getIntelliResponseResult(document.getElementById('question').value, '" + SLanguage.toLowerCase() + "');\" /></div>\n\
	<br/><br/>\
	<p>" + SFinalPara + "</p>\
	</div></div></div></div>";

	return SOutput;
}

// *********************************************************************************
// Title: 				submitenter
// Desc: 				This function is triggered if the Enter button is pressed 
//						while the "ask a question" textbox has focus. This function
//						is called from generateIntelliResponse function above.
// Created:				December 10, 2009
// Last Modified: 		December 10, 2009
// Accepts:				e is the triggered event
//						langu is the language (En or Fr)
// *********************************************************************************
function submitenter(e,lang)
{
var keycode;
if (window.event) keycode = window.event.keyCode;
else if (e) keycode = e.which;
if (keycode == 13)
{
   getIntelliResponseResult(document.getElementById('question').value,lang);
}
}

// *********************************************************************************
// Title: 				trackClick
// Desc: 				This function is used for webtrends tracking to external links. Called via 
//						onClick, linking to a dummy page that can add the tracking ID.
// Created:				Feb. 16, 2010
// Last Modified: 		Feb. 16, 2010
// Accepts:				url - the dummy page, add ?WT.mc_id=xxxxx after .html.
//						iframeID - add iframe to html and push off page via css. 
// *********************************************************************************
function trackClick(url, iframeID) {
	var iframe = document.getElementById(iframeID);
	iframe.src = url;
}
