

/* Operations executed when the page loads
 *
 * University of Ottawa
 * Computing and Communications Services
 */

/* require modern browser by checking for required features */
if (document.getElementById
	&& document.getElementsByTagName
	&& document.createElement
	&& document.createTextNode
	&& typeof window.addDOMLoadEvent == 'function') {

	/* URL Parameters - so far only used for print preview */
    var strQueryString = window.location.search;

	/* fix IE6 bug with old banner */
	addDOMLoadEvent(oldBannerAppendEmptyDiv);

	/* parse the local navigation */
	addDOMLoadEvent(parseLocalNav);

	/* fix centering */
	window.onresize = windowResize;

	/* add rounded corners */
	addDOMLoadEvent(addRoundedCorners);

	/* inititalize page tools */
	addDOMLoadEvent(initPageTools);

	addDOMLoadEvent(initFontResizeTool);

	/* initialize drop-down lists */
	addDOMLoadEvent(initDropDownLists);

	/* Override footer links */
	addDOMLoadEvent(initCustomContactLinks);

	/* Display the ch-lang-url on the old banner */
	addDOMLoadEvent(initDisplayChLangUrlOnOldBanner);

	/* initialize the global site search box */
	addDOMLoadEvent(initGlobalSearch);

	/* initialize the global site search box */
	addDOMLoadEvent(initLocalSearch);

    /* insert text labels to centralized page elements */
    addDOMLoadEvent(addTextLabels);

	/* trackClicks */
	addDOMLoadEvent(trackClicks);
	
	addDOMLoadEvent(setLangCookie);

} /* end browser checking */




/* Helper functions ------------------------------------- */


function windowResize() {
	if (!document.getElementById || !document.getElementsByTagName) return;
	var w = GetWidth();
  var s = 780;
	var r = (w - s) % 2;
	var m = r != 0 && w > s ? 0 : 1;
	if(m != previousMargin){
    previousMargin = m;
  	document.getElementsByTagName("BODY").item(0).style.marginLeft = m+'px';
  }
}

/*  GetWidth() */
function GetWidth() {
	var x = 0;
	if (self.innerHeight){
		x = self.innerWidth;
	}else if (document.documentElement && document.documentElement.clientHeight){
		x = document.documentElement.clientWidth;
	}else if (document.body){
		x = document.body.clientWidth;
	}
	return x;
}

/* Local Navigation
 * - enables expanding of a portion of the navigation menu (requires javascript variable)
 * - adds className "first" to the first list item
 * - adds className "current" to the left menu element which links to the current page
 */

function parseLocalNav() {
	/* requires a javascript variable set by the content owner */
	if (!document.getElementById || !document.getElementsByTagName) return;
	if (!document.getElementById(idList.localNav)) return;

	var localNav = document.getElementById(idList.localNav);

	/* do not run if localnav has already been parsed */
	if (window.localNavParsed == true) return false;
	/* do not run if the localnav is to be generated server-side */
	if (cssjs('check',localNav,cssClasses.serverSide)) return false;

	var localNavLinks = localNav.getElementsByTagName('a'); /* for later */
	var firstLiFound = false;

	for (var i=0; i < localNav.childNodes.length; i++) {
		// mark the first li found inside the local nav ul
		if (!firstLiFound && localNav.childNodes[i].nodeName.toLowerCase() == 'li'){
			cssjs('add',localNav.childNodes[i],cssClasses.first);
			firstLiFound = true;
		}

		// set className of the first level li with id matching the expandNavSection
		if (window.expandNavSection && localNav.childNodes[i].id == window.expandNavSection) {
			// expand the menu if appropriate section is found
			cssjs('add',localNav.childNodes[i],cssClasses.expand);
		}
		else {
			// remove sub-links of all other sections
			for (var j=0; j < localNav.childNodes[i].childNodes.length; j++) {
				if (localNav.childNodes[i].childNodes[j].nodeName.toLowerCase() == 'ul') {
					localNav.childNodes[i].removeChild(localNav.childNodes[i].childNodes[j]);
				}
			}
		}
	}

	/* Find the link that points to the current page */

	/* find proper page href to match against */
	var currentURL = window.location.href;
	if (currentURL.indexOf('#') != -1) {
		currentURL = currentURL.substr(0,currentURL.indexOf('#'));
	}

	for (var i=0; i < localNavLinks.length; i++) {
		if (localNavLinks[i].href == currentURL) {
			cssjs('add',localNavLinks[i],cssClasses.current);
		}
	}

	/* record that the localNav was parsed */
	window.localNavParsed = true;

}

/* Add Rounded Corners
 * - dynamically adds empty divs in elements that require a rounded corner
 */

function addRoundedCorners() {
	if (!getElementsByClassName || !document.getElementById) return;

	/* Side-bar */
	if (document.getElementById(idList.secondaryContent)) {
		/* create a new div.corner inside #highlight > div.feature */
		var arrFeatures = getElementsByClassName(document.getElementById(idList.secondaryContent),"div","feature");
		for (var i = 0; i < arrFeatures.length; i++) {
/*			arrFeatures[i].appendChild(createCornerDiv());
*/			if (arrFeatures[i].nextSibling != null) {
				arrFeatures[i].parentNode.insertBefore(createCornerDiv(),arrFeatures[i].nextSibling);
			} else {
				arrFeatures[i].parentNode.appendChild(createCornerDiv());
			}
		}
		/* create a new div.corner inside #site-search */
		if (document.getElementById(idList.siteSearch)) {
			var objSiteSearch = document.getElementById(idList.siteSearch);
/*			objSiteSearch.appendChild(createCornerDiv());
*/			if (objSiteSearch.nextSibling) {
				objSiteSearch.parentNode.insertBefore(createCornerDiv(),objSiteSearch.nextSibling);
			} else {
				objSiteSearch.parentNode.appendChild(createCornerDiv());
			}
		}
		/* create a new div.corner inside #highlight > div.grouped-features */
		var arrGroupedFeatures = getElementsByClassName(document.getElementById(idList.secondaryContent),"div","grouped-features");
		for (var i = 0; i < arrGroupedFeatures.length; i++) {
			if (arrGroupedFeatures[i].nextSibling) {
				arrGroupedFeatures[i].parentNode.insertBefore(createCornerDiv(),arrGroupedFeatures[i].nextSibling);
			} else {
				arrGroupedFeatures[i].parentNode.appendChild(createCornerDiv());
			}
		}
	} /* Side-bar */

}

function createCornerDiv() {
	var objCornerDiv = document.createElement("div");
	var objExtraSpan = document.createElement("span"); /* Required for IE */
	objCornerDiv.className = cssClasses.corner;
	objCornerDiv.appendChild(objExtraSpan);
	return objCornerDiv;
}

/* Font Resize Page Tool
 */

function initFontResizeTool () {
	var arrChoices = [idList.resizeOptionSmall, idList.resizeOptionMedium, idList.resizeOptionLarge];
	var strDefaultPreference = arrChoices[0];
	var arrResizePageRegions = [idList.mainContent, idList.sectionDetails, idList.secondaryContent, idList.siteInfo, idList.lastUpdated, idList.footerContact];

	/* create the tool's html scaffold */
	var objResizeTool = createFontResizeTool(arrChoices);

	/* exit if tool isn't present */
	if (!objResizeTool) return;

	/* load preference from cookie (if not set default) */
	var cookie = readCookie(idList.resizeTool); /* the cookie is named after the resize tool's id */
	var strPreference = cookie ? cookie : strDefaultPreference;
	switchFontSize(strPreference, arrChoices, arrResizePageRegions);

	/* hook up event handling */

	addEvent(objResizeTool,'mouseover',function() { cssjs('add',this,cssClasses.over); } );
	addEvent(objResizeTool,'mouseout',function() { cssjs('remove',this,cssClasses.over); } );

	for (var i=0; i < arrChoices.length; i++) {
		addEvent(document.getElementById(arrChoices[i]),'click',function() {
			switchFontSize(this.id, arrChoices, arrResizePageRegions);
		} );
		addEvent(document.getElementById(arrChoices[i]),'mouseover',function() { cssjs('add',this,cssClasses.over); } );
		addEvent(document.getElementById(arrChoices[i]),'mouseout',function() { cssjs('remove',this,cssClasses.over); } );
	}
}

function createFontResizeTool(arrChoices) {

	/* exit if page tools element not found or if resize tool exists */
	if (!document.getElementById(idList.pageTools)) return false;

	/* exit if tool already exists */
	if (document.getElementById(idList.resizeTool)) return document.getElementById(idList.resizeTool);

	/* create basic elements */
	var objResizeTool = document.createElement('div');
	var objResizeToolLabel = document.createElement('label');
	var objResizeToolChoiceList = document.createElement('ul');
	objResizeTool.id = idList.resizeTool;
	objResizeToolLabel.id = idList.resizeToolLabel;
	/* assemble the parts */
	objResizeTool.appendChild(objResizeToolLabel);
	objResizeTool.appendChild(objResizeToolChoiceList);
	/* add the choices */
	for (var i=0; i < arrChoices.length; i++) {
		objResizeToolChoiceList.appendChild(createResizeChoice(arrChoices[i]));
	}

	/* insert resize tool in DOM */
	document.getElementById(idList.pageTools).appendChild(objResizeTool);

	return objResizeTool;
}

function createResizeChoice(id) {
	var objItem = document.createElement('li');
	var objLink = document.createElement('a');
	objLink.id = id;
	objItem.appendChild(objLink);
	return objItem;
}

function switchFontSize(strPreference, arrChoices, arrResizePageRegions) {

	var el = document.getElementById(strPreference);

	/* change the font-size for selected page regions */
	switch(el.id) {
		case idList.resizeOptionSmall:  resizeRegions(arrResizePageRegions, "100%"); break;
		case idList.resizeOptionMedium: resizeRegions(arrResizePageRegions, "125%"); break;
		case idList.resizeOptionLarge:  resizeRegions(arrResizePageRegions, "150%"); break;
		default: break;
	}

	/* highlight chosen option */
	cssjs('add',el,cssClasses.current);

	/* remove highlight from other options */
	for (var i=0; i < arrChoices.length; i++) {
		if (arrChoices[i] != el.id) {
			cssjs('remove',document.getElementById(arrChoices[i]),cssClasses.current);
		}
	}

	/* Save the preference in a cookie */
	saveFontResizePreference();
}

function resizeRegions (arrResizePageRegions, size) {
	for (var i=0; i < arrResizePageRegions.length; i++) {
		if(document.getElementById(arrResizePageRegions[i])) {
			document.getElementById(arrResizePageRegions[i]).style.fontSize = size;
		}
	}
}

function saveFontResizePreference () {
	if (!document.getElementById(idList.resizeTool)) return;
	var strPreference = getElementsByClassName(document.getElementById(idList.resizeTool),'a',cssClasses.current)[0].id;

	var domain = (typeof(window["DEFAULT_DOMAIN"] != "undefined"))? DEFAULT_DOMAIN: false;
	createCookie(idList.resizeTool, strPreference, 365, domain);

	/* if the cookie wasn't successfully set, try a more specific domain, or the full domain if not in uottawa.ca */
	var intDomainPos = window.location.hostname.indexOf(domain); /* position of default domain inside current hostname */

	while(readCookie(idList.resizeTool) != strPreference && domain != window.location.hostname) {
		if (intDomainPos != -1) {
			/* find position of previous "." before the domain */
			if (window.location.hostname.charAt(intDomainPos) == ".") intDomainPos--; /* skip this . */
			while(window.location.hostname.charAt(intDomainPos)!="." && intDomainPos >= 0) {
				domain = window.location.hostname.substr(intDomainPos);
				intDomainPos--;
			}
		} else { /* e.g. www.geegees.ca */
			domain = window.location.hostname;
		}
		/* try again */
		createCookie(idList.resizeTool, strPreference, 365, domain);
	}
}

/* Add text labels
 * Inspired by http://www.thinkvitamin.com/features/dev/the-importance-of-maintainable-javascript
 */
function addTextLabels () {
    var lang = document.getElementsByTagName('html')[0].lang;
    if (!lang || !locales) return;
    for(i in locales[lang]) {
	if(document.getElementById(i)){
	    if(document.getElementById(i).tagName == 'INPUT') {
		document.getElementById(i).value = locales[lang][i];
	    } else {
		document.getElementById(i).appendChild(document.createTextNode(locales[lang][i]));
		/* append <span> tag; used for css image replacement */
		document.getElementById(i).appendChild(document.createElement('span'));
	    }
	}
    }
}

/** **/
function initCustomContactLinks() {
	/* initialize */
	objGeneral = document.getElementById(idList.genFeedbackLink);
	objTechnical = document.getElementById(idList.techFeedbackLink);

	/* General feedback link */
	if (objGeneral && objGeneral.tagName == "A") {
		if (window.genFeedbackLink) { objGeneral.href = window.genFeedbackLink; }
		if (window.genFeedbackLabel) { objGeneral.firstChild.nodeValue = window.genFeedbackLabel; }
	}

	/* Technical feedback link */
	if (objTechnical && objTechnical.tagName == "A") {
		if (window.techFeedbackLink) { objTechnical.href = window.techFeedbackLink; }
		if (window.techFeedbackLabel) { objTechnical.firstChild.nodeValue = window.techFeedbackLabel; }
	}
}

function initDisplayChLangUrlOnOldBanner() {
	/* initialize */
	if (!idList.mainBanner) { return; }
	var objMainContainer = document.getElementById(idList.mainContainer);
	var objPageBody = document.getElementsByTagName('body')[0];

	if (!document.getElementById(idList.mainBanner)) {
		cssjs('add',objMainContainer,cssClasses.oldBanner);
		cssjs('add',objPageBody,cssClasses.oldBanner);
	}
}

function initPageTools() {

	if (typeof window.initPrintTool == 'function') {
		initPrintTool();
    }

    if (typeof window.initEmailTool == 'function') {
		initEmailTool();
    }

	 /* detect print preview */
    if (strQueryString.indexOf('print=true') > -1 && typeof window.initPrintPreview == 'function') {
		initPrintPreview();
    }
}

/* Global Search Box (top banner) */

function initGlobalSearch () {
	/* requirements */
	if (!document.getElementById) { return; }

	var objMainBanner;
	if (!(objMainBanner = document.getElementById(idList.mainBanner))) { return; }

	var objSecondaryNav;
	if (!(objSecondaryNav = document.getElementById(idList.secondaryNav))) { return; }

	var lang = document.getElementsByTagName('html')[0].lang;
	if (!lang || !locales) return;

	/* if the search form is already on the page, don't add it */
	if (document.getElementById(idList.globalSearch)) { return; }

	/* if the page already has a form as one of the parents, don't add the search form */
	objFormFoundInAncestors = isFormInAncestors(objMainBanner);

	/* create basic elements */
	var objSearchLabel = document.createElement('label');
	var objSearchInput = document.createElement('input');
	var objSearchCharset = document.createElement('input');
	var objSearchSubmit = document.createElement('input');
	var objSearchHint = document.createElement('label');

	/* if the page already has a form, use a div instead */
	var objSearchForm;
	if (objFormFoundInAncestors) {
		objSearchForm = document.createElement('div');
	} else {
		objSearchForm = document.createElement('form');
	}

	/* assign id's */
	objSearchForm.id = idList.globalSearch;
	objSearchLabel.id = idList.globalSearchLabel;
	objSearchInput.id = idList.globalSearchInput;
	objSearchHint.id = idList.globalSearchHint;
	objSearchSubmit.id = idList.globalSearchSubmit;

	/* add other properties */
	objSearchLabel.setAttribute('for', idList.globalSearchInput);

	objSearchInput.setAttribute('type', 'text');
	objSearchInput.setAttribute('value', '');
	objSearchInput.setAttribute('name', 'q');

	objSearchCharset.setAttribute('type', 'hidden');
	objSearchCharset.setAttribute('name', 'ie');
	objSearchCharset.setAttribute('value', detectPageCharset());

	objSearchHint.setAttribute('for', idList.globalSearchInput);
	objSearchHint.firstinnerHTML = locales[lang]['global-site-search-hint'];
	// In IE you have to use 'attachEvent' rather than the standard 'addEventListener'.
	if (objSearchHint.attachEvent){
  		objSearchHint.attachEvent('onclick', function(){document.getElementById(idList.globalSearchInput).focus();});
	}

	if(objFormFoundInAncestors){
		objSearchSubmit.setAttribute('type', 'button');
	} else {
		objSearchSubmit.setAttribute('type', 'submit');
	}

	objSearchSubmit.setAttribute('value', '');

	cssjs('add', objSearchSubmit, 'submit');
	objSearchSubmit.setAttribute('title', locales[lang]['global-site-search-submit-title']);

	/* add form interactivity (or simulate if form already in DOM) */
	if (!objFormFoundInAncestors) {
		objSearchForm.setAttribute('action', locales[lang]['global-site-search-action']);
		objSearchForm.setAttribute('method', 'get');
	} else {
		addEvent(objSearchInput,'keypress',function(e) {
			/* if enter is pressed */
			if (e.keyCode=='13') { submitSearchWithNoForm(); preventDefault(e); }
		});
		addEvent(objSearchSubmit,'click',function(e) {
			submitSearchWithNoForm();
			preventDefault(e);
		});
	}

	/* assemble the parts */
	objSearchForm.appendChild(objSearchLabel);
	objSearchForm.appendChild(objSearchInput);
	objSearchForm.appendChild(objSearchHint);
	objSearchForm.appendChild(objSearchCharset);
	objSearchForm.appendChild(objSearchSubmit);

	/* insert in DOM */
	document.getElementById(idList.mainBanner).insertBefore(objSearchForm, objSecondaryNav);

	// if field is empty, add hint
	if (objSearchInput.value == "") {
		cssjs('add',objSearchHint,cssClasses.empty);
	}

	// onfocus: remove hint
	addEvent(objSearchInput,'focus',function() {
		cssjs('remove',objSearchHint,cssClasses.empty);
	});
	// onblur: add hint again if empty
	addEvent(objSearchInput,'blur',function() {
		if (objSearchInput.value == "") {
			cssjs('add',objSearchHint,cssClasses.empty);
		}
	});
}

function initLocalSearch () {

	/* requirements */
	if (!document.getElementById || !idList || !idList.siteSearch) { return; }
	/* if the local search form isn't on the page, stop */
	if (!document.getElementById(idList.siteSearch)) { return; }

	var objLocalSearchForm = document.getElementById(idList.siteSearch);

	var objSearchCharset = document.createElement('input');
	objSearchCharset.setAttribute('type', 'hidden');
	objSearchCharset.setAttribute('name', 'ie');
	objSearchCharset.setAttribute('value', detectPageCharset());

	objLocalSearchForm.appendChild(objSearchCharset);
}

function detectPageCharset() {
	if (!document.getElementById) { return; }

	if (document.characterSet) {
		// if standards-compliant browser (IE8 doesn't return this)
		return document.characterSet;
	}

	// else, it's an IE browser, and find the character set specified in the meta content-type
	var charset = "";
	var matches = null;
	var head = document.getElementsByTagName('head')[0];
	var metaElements = head.getElementsByTagName('meta');
	for (var i=0; i<metaElements.length; i++) {
		if (metaElements[i].httpEquiv
			&& metaElements[i].httpEquiv.match(/Content-Type/i)) {
			matches = null;
			if (matches = metaElements[i].content.match(/charset=(.*)/i)) {
				charset = matches[1];
				return charset;
			}
		}
	}

	// else, return iso-8859-1 (Western European), which is normally the default on IE browsers
	return "iso-8859-1";
}

function submitSearchWithNoForm() {
	/* requirements */
	if (!document.getElementById) { return; }

	var objSearchForm;
	if (!(objSearchForm = document.getElementById(idList.globalSearch))) { return; }

	var objSearchInput;
	if (!(objSearchInput = document.getElementById(idList.globalSearchInput))) { return; }

	var lang = document.getElementsByTagName('html')[0].lang;
	if (!lang || !locales) return;

	/* instead of submitting the page's main form, use a redirection to go to search results */
	document.location = locales[lang]['global-site-search-action'] + "?"
		+ objSearchInput.name + "=" + encodeURI(objSearchInput.value)
		+ "&ie=utf-8"; // encodeURI is always in UTF-8-encoded escape characters
}

function isFormInAncestors(obj) {
	var objPageBody, objAncestor;

	var objPageBody = document.getElementsByTagName('body')[0];
	var objAncestor = obj;

	while (objAncestor != objPageBody) {
		if (objAncestor.tagName.toLowerCase() == 'form') {
			return objAncestor;
		}
		objAncestor = objAncestor.parentNode;
	}
	return false;
}

function oldBannerAppendEmptyDiv () {

	/* By adding zoom: 1; on section-container to "have layout",
	   it caused the previous position: absolute items (global nav, secondary nav)
	   to disappear, because of a weird IE-only bug.

	   The fix is to introduce an empty div element before section-container,
	   and we'll do it through javascript.

	   Source: IE7-/Win: A box with position:absolute next to a float may disappear
	   http://www.brunildo.org/test/IE_raf3.html
	 */

	/* Require IE 6 or 7 */
	var IE6searchString = "MSIE";
	var indexOfMSIE = navigator.userAgent.indexOf(IE6searchString);
	if (indexOfMSIE == -1) return; /* It's not IE */

	var IEversion = parseFloat(navigator.userAgent.substring(indexOfMSIE+IE6searchString.length+1));
	if (IEversion > 7 || IEversion < 6) return; /* It's not IE 6 or 7 */

	/* If new banner found, don't do anything */
	if(!idList.mainBanner || document.getElementById(idList.mainBanner)) { return; }

	/* Find main-container, section-container objects in DOM */
	var objMainContainer;
	if (!(objMainContainer = document.getElementById(idList.mainContainer))) { return; }

	var objSectionContainer;
	if (!(objSectionContainer = document.getElementById(idList.sectionContainer))) { return; }

	/* Add empty div before section-container */
	var objEmptyDiv = document.createElement("div");
	objMainContainer.insertBefore(objEmptyDiv, objSectionContainer);
}

function trackClicks () {

	if (typeof window._gat == 'undefined') {
		(function() {
		    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
		    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
		    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
		  })();
	}

	try {
		_gaq = window._gaq || [];
		
		_gaq.push(
			['uottawa._setAccount','UA-6980640-11']
		,	['uottawa._setDomainName','.uottawa.ca']
		
		,	['uottawa._setCustomVar',1,'font-size',readCookie(idList.resizeTool),1]
		,	['uottawa._setCustomVar',2,'page-lang',document.getElementsByTagName('html')[0].lang,3]
		,	['uottawa._setCustomVar',3,'template-version','2',3]
		,	['uottawa._setCustomVar',4,'is-home',(isHome())?"true":"false",3]
		
		,	['uottawa._trackPageview',pathWithProtocolAppended()]
		);
		
		if (!window._gaq) window._gaq = _gaq;
	} catch(err) {}

	if (typeof window._gaTrackClicks == 'undefined') { return; }

	_gaTrackClicks._parseElement(document.getElementById('main-banner'),'header');
	_gaTrackClicks._parseElement(document.getElementById('section-container'),'content');
	_gaTrackClicks._parseElement(document.getElementById('main-siteinfo'),'footer');
	_gaTrackClicks._parseElement(document.getElementById('main-statements-contact'),'footer');

}

function pathWithProtocolAppended() {
	return window.location.pathname + window.location.search + "&_gaProtocol=" + window.location.protocol;
}

function isHome() {
	if (!document.getElementById('main-container')) return false;
	
	return cssjs('check',document.getElementById('main-container'),'section-home');
}

var _gaTrackClicks = {

	eventCategory: 'Clicks on ' + location.hostname,
	pageTrackerVarName: 'window._gaq',

	_parseElement : function (element, label) {
		if (!element || !document.getElementById || !addEvent) return;

		var eventCategory = _gaTrackClicks.eventCategory;
		var eventAction = _gaTrackClicks.trimAndClean(label);

		if (element.tagName.toLowerCase() == 'a'
			|| element.tagName.toLowerCase() == 'area') {
			var eventLabel = (_gaTrackClicks.getTextContent(element) != "")? _gaTrackClicks.trimAndClean(_gaTrackClicks.getTextContent(element)) + " " : "";
			eventLabel += _gaTrackClicks.trimAndClean(element.href);
			addEvent(element,'click', new Function(_gaTrackClicks.pageTrackerVarName + ".push(['uottawa._trackEvent','" + eventCategory + "', '" + eventAction + "', '" + eventLabel + "']);"));

		} else {
			var links = element.getElementsByTagName('a');
			for (j=0; j<links.length; j++) {
				var eventLabel = (_gaTrackClicks.getTextContent(links[j]) != "")? _gaTrackClicks.trimAndClean(_gaTrackClicks.getTextContent(links[j])) + " " : "";
				eventLabel += _gaTrackClicks.trimAndClean(links[j].href);
				var eventTrackCall = _gaTrackClicks.pageTrackerVarName + ".push(['uottawa._trackEvent','" + eventCategory + "', '" + eventAction + "', '" + eventLabel + "']);";
				addEvent(links[j],'click', new Function(eventTrackCall));
				eventLabel = "";
			}
			var imagemap_areas = element.getElementsByTagName('area');
			for (j=0; j<imagemap_areas.length; j++) {
				var eventLabel = (imagemap_areas[j].getAttribute('alt') && imagemap_areas[j].getAttribute('alt') != "")? _gaTrackClicks.trimAndClean(imagemap_areas[j].getAttribute('alt')) + " " : "";
				eventLabel += _gaTrackClicks.trimAndClean(imagemap_areas[j].href);
				addEvent(imagemap_areas[j],'click', new Function(_gaTrackClicks.pageTrackerVarName + ".push(['uottawa._trackEvent','" + eventCategory + "', '" + eventAction + "', '" + eventLabel + "']);"));
			}
		}
	},

	/**
	*  Used to trim out any whitespace surrounding the links / labels
	*  Taken from http://www.webtoolkit.info/
	**/
	trim : function (str, chars) {
		return _gaTrackClicks.ltrim(_gaTrackClicks.rtrim(str, chars), chars);
	},

	ltrim : function (str, chars) {
		chars = chars || "\\s";
		return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
	},

	rtrim : function (str, chars) {
		chars = chars || "\\s";
		return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
	},

	/**
	 * Trims whitespace around a string, and escapes ', ", (, and )
	 */
	trimAndClean : function (text) {
		text = _gaTrackClicks.trim(text);
		text = text.replace(/'/g, "\\'");
		text = text.replace(/"/g, '\\"');
		text = text.replace(/\(/g, ' '); // remove parentheses
		text = text.replace(/\)/g, ' '); // remove parentheses
		text = text.replace(/\s+/g, ' '); // remove extra whitespaces
		return text;
	},

	/**
	 * Gets the text content of the specified element.
	 * @param element {HTMLElement} The html element
	 * @return {String} The string content of the specified element.
	 * source: http://dandean.com/category/category/javascript/
	 */
	getTextContent : function (element) {
		if (typeof element.textContent != "undefined") {
			return element.textContent;
		}
		return element.innerText;
	}
}

function dropDownList(el) {

	this.objDropDown = el;
	if (!this.objDropDown) return;

	/* Dropdown methods */

	this.objDropDown.expand = function() {
		/* collapse any already-expanded list */
		if (window.currentDropDown) { window.currentDropDown.collapse(); }
		window.cssjs('add',this,cssClasses.expand);
		window.currentDropDown = this;
	}

	this.objDropDown.collapse = function() {
		window.cssjs('remove',this,cssClasses.expand);
		window.currentDropDown = null;
	}


	/* toggle expand/collapse onclick */

	addEvent(this.objDropDown,'click',function(e) {
		if (window.cssjs('check',this,cssClasses.expand)) {
			this.collapse();
		} else {
			this.expand();
		}
	} );

	/* expand if tabbed into */

	/* add expand and collapse functions to all elements */
	var arrAllElements = this.objDropDown.getElementsByTagName('*');
	for (var i=0; i < arrAllElements.length; i++) {
		arrAllElements[i].expand = function() { this.parentNode.expand(); }
		arrAllElements[i].collapse = function() { this.parentNode.collapse(); }
	}

	var arrQuickPicksLinks = this.objDropDown.getElementsByTagName('a');
	for (var i=0; i < arrQuickPicksLinks.length; i++) {
		addEvent(arrQuickPicksLinks[i],'focus',function() {
			this.expand();
		} );
		addEvent(arrQuickPicksLinks[i],'blur',function() {
			this.collapse();
		} );
	}

}

function initCollapseOnPageBodyClick() {

	var objPageBody = document.getElementsByTagName('body')[0];

	/* collapse currently expanded drop down */
	addEvent(objPageBody,'click',function(e) {
		if (!window.currentDropDown) { return; }

		/* if you click on the dropdown tool itself, do nothing */
		if( (e.target && e.target == window.currentDropDown )
			|| (e.srcElement && e.srcElement == window.currentDropDown)) return;

		/* if you click on an element of the dropdown tool itself, do nothing */
		if( (e.target && e.target.parentNode == window.currentDropDown )
			|| (e.srcElement && e.srcElement.parentNode == window.currentDropDown)) return;

		/* if you click anywhere else, collapse the tool */
		if (window.cssjs('check',window.currentDropDown,cssClasses.expand)) {
			window.currentDropDown.collapse();
		}
	} );

}

function initDropDownLists() {
	var objSecondaryNavMoreLinks = new dropDownList(document.getElementById('secondarynav-more'));

	initCollapseOnPageBodyClick();

	/* if javascript if enabled, display the dropdowns */
	window.cssjs('add',document.getElementsByTagName('body')[0],cssClasses.jsEnabled);
}

function setLangCookie() {
	/* Set the cookie to the page's language */
	var lang = document.getElementsByTagName('html')[0].lang;
	lang = (lang != "" && typeof lang != 'undefined')? lang : "en";
	
	createCookie('lang-prev-page', lang, 365, '.uottawa.ca');

	/* Remove lang cookie: no longer needed as it conflicted with some tools */
	createCookie('lang', '', -1, '.uottawa.ca');
}
