﻿/*global ActiveXObject, sidebar, external, 
XMLDocument, XSLTProcessor, Document, Node, XMLSerializer, XPathResult,
defaultTopicId, currentTopicId, appBaseUrl, dhtmlHistory, spBreadcrumbElementId, publicationTitle, publicationUnid, customInit, currentUsername, overrideTopicHeading,
_spSuppressFormOnSubmitWrapper, WebForm_OnSubmit, adjustTopicDocument */

try { document.execCommand('BackgroundImageCache', false, true); } catch (err) { }

var alwaysShowNavigation = false, stealBreadcrumbs = false;

String.map = {};
String.neutralLanguage = "en-US";
String.prototype.localize = function (parameters, language) {
	var s, t, i, u, l;
	if (!language) {
		language = String.language;
	}
	if (typeof (s = String.map[this]) === "object") {
		while (language.length !== 0) {
			if (typeof (t = s[language]) === "string") {
				u = t; break;
			}
			else {
				if ((i = language.lastIndexOf("-")) === -1) { i = 0; }
				language = language.substr(0, i);
			}
		}
		if (language.length === 0 && typeof (t = s[String.neutralLanguage]) === "string") { u = t; }
	}
	if (!u) { u = "[" + this + "]"; }
	if (parameters && parameters.length) {
		for (i = 0, l = parameters.length; i < l; i++) {
			u = u.replace("{" + i.toString() + "}", parameters[i]);
		}
	}
	return u;
};
String.prototype.globalize = function (s) {
	var t, lang;
	if (typeof (t = String.map[this]) !== "object") {
		String.map[this] = s;
	}
	else {
		for (lang in s) {
			if (s.hasOwnProperty(lang)) {
				t[lang] = s[lang];
			}
		}
	}
};

/*
\u0009 — Tab — \t 
\u000a — Line feed — \n — (newline character) 
\u000b — Vertical tab — \v 
\u000c — Form feed — \f 
\u000d — Carriage return — \r — (newline character) 
\u0020 — Space 
\u00a0 — No-break space 
\u1680 — Ogham space mark 
\u180e — Mongolian vowel separator 
\u2000 — En quad 
\u2001 — Em quad 
\u2002 — En space 
\u2003 — Em space 
\u2004 — Three-per-em space 
\u2005 — Four-per-em space 
\u2006 — Six-per-em space 
\u2007 — Figure space 
\u2008 — Punctuation space 
\u2009 — Thin space 
\u200a — Hair space 
\u2028 — Line separator — (newline character) 
\u2029 — Paragraph separator — (newline character) 
\u202f — Narrow no-break space 
\u205f — Medium mathematical space 
\u3000 — Ideographic space
*/
String.spaceSeparators = "\t\n\v\f\r \u00a0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000";
String.leftTrimmer = new RegExp("^[" + String.spaceSeparators + "]+");
String.rightTrimmer = new RegExp("[" + String.spaceSeparators + "]+$");
String.trimmer = new RegExp("^[" + String.spaceSeparators + "]+|[" + String.spaceSeparators + "]+$", "g");
String.prototype.trimLeft = function (ch) {
	if (typeof (ch) === "string" && ch.length === 1) {
		var i = 0;
		while (this.charAt(i) === ch) {
			i++;
		}
		return this.substr(i);
	}
	else {
		return this.replace(String.leftTrimmer, "");
	}
};
String.prototype.trimRight = function (ch) {
	if (typeof (ch) === "string" && ch.length === 1) {
		var i = this.length - 1;
		while (this.charAt(i) === ch) {
			i--;
		}
		return this.substr(0, i + 1);
	}
	else {
		return this.replace(String.rightTrimmer, "");
	}
};
String.prototype.trim = function (ch) {
	if (typeof (ch) === "string" && ch.length === 1) {
		var i = 0;
		while (this.charAt(i) === ch) {
			i++;
		}
		var j = this.length - 1;
		while (this.charAt(j) === ch) {
			j--;
		}
		return this.substring(i, j + 1);
	}
	else {
		return this.replace(String.trimmer, "");
	}
};

var Http = {
	Method: {
		Get: "GET",
		Post: "POST",
		Head: "HEAD",
		Put: "PUT",
		Delete: "DELETE",
		Options: "OPTIONS"
	},

	State: {
		Unsent: 0,
		Open: 1,
		Sent: 2,
		Loading: 3,
		Done: 4
	},

	StatusCode: {
		Local: 0,
		OK: 200,
		NotModified: 304,
		FileNotFound: 404
	}
};

var NodeType = {
	Element: 1,
	Attribute: 2,
	Text: 3,
	CDataSection: 4,
	EntityReference: 5,
	Entity: 6,
	ProcessingInstruction: 7,
	Comment: 8,
	Document: 9,
	DocumentType: 10,
	DocumentFragment: 11,
	Notation: 12
};

if (typeof (XMLSerializer) === "undefined") {
	var XMLSerializer = (function () {
		function constructor() {
		}

		return constructor;
	})();
	XMLSerializer.prototype = {
		serializeToString: function (node) {
			return node.xml;
		}
	};
}

if (typeof (Document) !== "undefined" && typeof (Node) !== "undefined") {
	var NamespaceResolver = (function () {
		function constructor(document) {
			this._prefixMap = {};
			this._normalResolver = document.createNSResolver(document.documentElement);
		}

		return constructor;
	})();
	NamespaceResolver.prototype = {
		addNamespaceURI: function (prefix, uri) {
			if (typeof (prefix) === "string" && typeof (uri) === "string") {
				this._prefixMap[prefix] = uri;
			}
		},
		lookupNamespaceURI: function (prefix) {
			var uri = this._prefixMap[prefix];
			return typeof (uri) === "string" ? uri : this.normalResolver.lookupNamespaceURI(prefix);
		}
	};

	Document.prototype.getNSResolver = function () {
		return this.nsResolver || (this.nsResolver = new NamespaceResolver(this));
	};
	Document.prototype.setProperty = function (name, value) {
		if (typeof (name) !== "string" || typeof (value) !== "string") { return; }
		if (name === "SelectionNamespaces") {
			var resolver = this.getNSResolver();
			var rex = /xmlns:([A-Za-z_][\w]*)\s*=\s*(['"])([^<&'"]+)\2/g, match;
			while ((match = rex.exec(value))) {
				resolver.addNamespaceURI(match[1], match[3]);
			}
		}
	};

	Node.prototype.selectSingleNode = function (xpathExpression) {
		var xpe = this.ownerDocument || this;
		var result = xpe.evaluate(xpathExpression, this, xpe.getNSResolver(),
			XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
		return result;
	};
	Node.prototype.selectNodes = function (xpathExpression) {
		var xpe = this.ownerDocument || this;
		var iter = xpe.evaluate(xpathExpression, this, xpe.getNSResolver(),
			XPathResult.ORDERED_NODE_ITERATOR_TYPE, null);
		var nodes = [], i;
		while ((i = iter.iterateNext())) {
			nodes.push(i);
		}
		return (nodes);
	};
}

function getXmlHttpRequest() {
	if (typeof (ActiveXObject) !== "undefined") {
		try {
			return new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e1) { }

		try {
			return new ActiveXObject("Microsoft.XMLHTTP");
		}
		catch (e2) { }
	}

	// If this fails just let the error bubble.
	return new XMLHttpRequest();
}

var sharedHttpRequest = null;
function getSharedXmlHttpRequest() {
	if (!sharedHttpRequest) {
		sharedHttpRequest = getXmlHttpRequest();
	}
	return sharedHttpRequest;
}

function urlEncode(s) {
	var result = "";
	for (var i = 0, l = s.length; i < l; i++) {
		var ch = s.charAt(i);
		if ('A' <= ch && ch <= 'Z' || 'a' <= ch && ch <= 'z' || '0' <= ch && ch <= '9' || ch === '-' || ch === '_' || ch === '.' || ch === '~') {
			result += ch;
		}
		else {
			var chval = ch.charCodeAt();
			if (chval < 0x10) {
				result += '%0' + ch.charCodeAt().toString(16).toUpperCase();
			}
			else if (chval < 0x100) {
				result += '%' + ch.charCodeAt().toString(16).toUpperCase();
			}
			else if (chval < 0x1000) {
				result += '%u0' + ch.charCodeAt().toString(16).toUpperCase();
			}
			else {
				result += '%u' + ch.charCodeAt().toString(16).toUpperCase();
			}
		}
	}
	return result;
}

function urlDecode(s) {
	var result = "";
	var i = 0, l = s.length;
	while (i < l) {
		var ch = s.charAt(i++);
		if (ch === '%') {
			if (s[i] === 'u') {
				i++;
				result += String.fromCharCode(parseInt(s.substr(i, 4), 16));
				i += 4;
			}
			else {
				result += String.fromCharCode(parseInt(s.substr(i, 2), 16));
				i += 2;
			}
		}
		else {
			result += ch;
		}
	}
	return result;
}

function hasClass(element, className) {
	var rex = new RegExp("\\b(" + className + ")\\b");
	return rex.test(element.className);
}

function replaceClass(element, oldClassName, newClassName) {
	var rex = new RegExp("\\b(" + oldClassName + ")\\b"), result;
	if ((result = rex.test(element.className))) {
		element.className = element.className.replace(rex, newClassName);
	}
	return result;
}

function removeClass(element, className) {
	var rex = new RegExp("\\b(\\s" + className + ")|(" + className + "\\s?)\\b", "g"), result;
	if ((result = rex.test(element.className))) {
		element.className = element.className.replace(rex, "");
	}
	return result;
}

function addClass(element, className) {
	var rex = new RegExp("\\b(" + className + ")\\b");
	if (!rex.test(element.className)) {
		if (element.className) {
			element.className = element.className + " " + className;
		}
		else {
			element.className = className;
		}
	}
}

function toggleClasses(element, classNameA, classNameB) {
	var result,
		rex1 = new RegExp("\\b(" + classNameA + ")\\b"),
		rex2 = new RegExp("\\b(" + classNameB + ")\\b");
	if (rex1.test(element.className)) {
		element.className = element.className.replace(rex1, classNameB);
		return classNameB;
	}
	else if (rex2.test(element.className)) {
		element.className = element.className.replace(rex2, classNameA);
		return classNameA;
	}
	else {
		return null;
	}
}

function toggleClass(element, className) {
	var elmClass = element.className;
	if (elmClass) {
		var rex = new RegExp("\\b(\\s" + className + ")|(" + className + "\\s?)\\b");
		if (!rex.test(elmClass)) {
			element.className = elmClass + " " + className;
		}
		else {
			element.className = elmClass.replace(rex, "");
		}
	}
	else {
		element.className = className;
	}
}

function includeStyleSheet(url) {
	var headElements = document.documentElement.getElementsByTagName("head");
	if (headElements.length === 1) {
		var headElement = headElements[0];
		var linkElements = headElement.getElementsByTagName("link");
		var linkCount = linkElements.length, linkElement, i;
		for (i = 0; i < linkCount; i++) {
			linkElement = linkElements[i];
			if (linkElement.rel.toLowerCase() === "stylesheet" && linkElement.href === url) {
				break;
			}
		}
		if (i === linkCount) {
			linkElement = document.createElement("link");
			linkElement.rel = "stylesheet";
			linkElement.href = url;
			linkElement.type = "text/css";
			headElement.appendChild(linkElement);
		}
		return linkElement;
	}
}

function addBookmark(title, url) {
	if (typeof (sidebar) === "function") {
		sidebar.addPanel(title, url);
	} else if (typeof (external) !== "undefined") {
		external.AddFavorite(url, title);
	} else if (typeof (opera) !== "undefined" && typeof (print) !== "undefined") {
	}
}

function attachEventHandler(element, eventName, eventHandler, context) {
	if (element && typeof (eventName) === "string" && typeof (eventHandler) === "function") {
		var handler = eventHandler;
		if (typeof (context) === "object") {
			handler = function () {
				return eventHandler.apply(context, arguments);
			};
			handler.context = context;
			handler.innerHandler = eventHandler;
			if (typeof (element.wrappedHandlers) === "undefined") {
				element.wrappedHandlers = [];
			}
			element.wrappedHandlers.push(handler);
		}
		if (typeof (element.addEventListener) === "function") {
			element.addEventListener(eventName, handler, false);
		} else if (typeof (element.attachEvent) === "object") {
			element.attachEvent("on" + eventName, handler);
		} else {
			element["on" + eventName] = handler;
		}
	}
}

function detachEventHandler(element, eventName, eventHandler, context) {
	if (element && typeof (eventName) === "string" && typeof (eventHandler) === "function") {
		var handler = eventHandler;
		if (typeof (context) === "object") {
			var handlerList = element.wrappedHandlers;
			if (!handlerList) { return; }
			var found = false;
			for (var i = 0, len = handlerList.length; !found && i < len; i++) {
				var wrappedHandler = handlerList[i];
				if (wrappedHandler.context === context && wrappedHandler.innerHandler === eventHandler) {
					handler = wrappedHandler;
					handlerList.splice(i, 1);
					found = true;
				}
			}
			if (!found) { return; }
		}
		if (typeof (element.removeEventListener) === "function") {
			element.removeEventListener(eventName, handler, false);
		} else if (typeof (element.attachEvent) === "object") {
			element.detachEvent("on" + eventName, handler);
		} else {
			element["on" + eventName] = null;
		}
	}
}

function clearElement(element) {
	if (element) {
		var node;
		while ((node = element.lastChild)) {
			element.removeChild(node);
		}
	}
}

function getElementText(element) {
	if (element) {
		if (typeof (element.innerText) !== "undefined") {
			// IE HTML
			return element.innerText;
		}
		else if (typeof (element.text) !== "undefined") {
			// IE XML
			return element.text;
		}
		else if (typeof (element.textContent) !== "undefined") {
			// Mozilla
			return element.textContent;
		}
	}
}

function setElementHtml(element, htmlFragment) {
	if (element) {
		// Element.removeNode is IE-specific
		if (htmlFragment && typeof (element.removeNode) !== "undefined") {
			// Add the html like a pre element - and then remove it again
			var wrappedFragment = "<pre>" + htmlFragment + "</pre>";
			element.innerHTML = wrappedFragment;
			var preElement = element.firstChild;
			preElement.removeNode(false);
		}
		else {
			// Assume that other browsers will preserve whitespace correctly
			element.innerHTML = htmlFragment;
		}
	}
}

var ElementWrapper = (function () {
	function constructor(element) {
		this._element = element;
	}

	return constructor;
})();
ElementWrapper.prototype = {
	clear: function () {
		clearElement(this._element);
	},
	setHtml: function (html) {
		setElementHtml(this._element, html);
	},
	appendHtmlNode: function (node) {
		this._element.appendChild(node);
	},
	appendParagraph: function (text) {
		var paragraph = document.createElement("p");
		if (typeof (text) === "string" && text.length !== 0) {
			paragraph.appendChild(document.createTextNode(text));
		}
		this.appendHtmlNode(paragraph);
		return paragraph;
	},
	prependHtmlNode: function (node) {
		var firstChild;
		if ((firstChild = this._element.firstChild) === null) {
			this._element.appendChild(node);
		}
		else {
			this._element.insertBefore(node, firstChild);
		}
	}
};

var Cursor = {
	getPagePosition: function (evt) {
		if (!evt) throw "Event object argument required";
		var x = 0, y = 0;
		if (typeof (evt.pageX) === "number") {
			x = evt.pageX;
			y = evt.pageY;
		}
		else {
			var de = document.documentElement;
			var b = document.body;
			x = evt.clientX + (de.scrollLeft || b.scrollLeft) - (de.clientLeft || 0);
			y = evt.clientY + (de.scrollTop || b.scrollTop) - (de.clientTop || 0);
		}
		return { x: x, y: y };
	},
	getViewportPosition: function (evt) {
		if (!evt) throw "Event object argument required";
		return { x: evt.clientX, y: evt.clientY };
	}
};

var Viewport = {
	getSize: function () {
		var width = 0, height = 0, de = document.documentElement, b = document.body;
		if (typeof (innerWidth) === "number") {
			width = innerWidth;
			height = innerHeight;
		}
		else if (de && de.clientWidth) {
			width = de.clientWidth;
			height = de.clientHeight;
		}
		else {
			width = b.clientWidth;
			height = b.clientHeight;
		}
		return { width: width, height: height };
	},
	getWidth: function () {
		var de = document.documentElement;
		if (typeof (innerWidth) === "number") {
			return innerWidth;
		}
		else if (de && de.clientWidth) {
			return de.clientWidth;
		}
		else {
			return document.body.clientWidth;
		}
	},
	getHeight: function () {
		var de = document.documentElement;
		if (typeof (innerHeight) === "number") {
			return innerHeight;
		}
		else if (de && de.clientHeight) {
			return de.clientHeight;
		}
		else {
			return document.body.clientHeight;
		}
	}
};

function stopEvent(evt) {
	if (evt) {
		if (typeof (evt.stopPropagation) === "function") {
			evt.stopPropagation();
		} else {
			evt.cancelBubble = true;
		}
		if (typeof (evt.preventDefault) === "function") {
			evt.preventDefault();
		}
		else {
			evt.returnValue = false;
		}
	}
	return false;
}

var Windows = {};
var Window = (function () {
	/*private static*/
	var _counter = 1;

	function constructor(parent, id, className, title, properties) {
		parent = parent || document.body;
		if (typeof (parent) === "object" && parent.nodeType === 1) {
			this._parent = parent;
		}
		else if (typeof (parent) === "string") {
			this._parent = document.getElementById(parent);
		}

		this._parentBackgroundColor = null;

		this._windowNumber = _counter++;
		this._regionElement = document.createElement("div");
		this._windowElement = document.createElement("div");
		this._titleBarElement = document.createElement("div");
		this._iconElement = document.createElement("div");
		this._titleElement = document.createElement("div");
		this._titleParaElement = document.createElement("p");
		this._controlsElement = document.createElement("div");
		this._closeButtonElement = document.createElement("a");
		this._toolBarElement = document.createElement("div");
		this._contentElement = document.createElement("div");
		this._statusBarElement = document.createElement("div");

		this._dimBlock = document.createElement("div");
		this._dimBlock.className = "dimBlock";
		this._parent.appendChild(this._dimBlock);

		this._regionElement.className = "windowRegion";
		attachEventHandler(this._regionElement, "mouseover", this._mouseOverHandler, this);
		attachEventHandler(this._regionElement, "mouseout", this._mouseOutHandler, this);
		this._windowElement.id = id || ("window_" + _counter.toString());
		this._windowElement.className = "window" + (className ? " " + className : "");
		this._regionElement.style.zIndex = 2 * this._windowNumber;
		this._titleBarElement.className = "titleBar";
		this._iconElement.className = "icon";
		this._titleElement.className = "title fullWidth";
		attachEventHandler(this._titleElement, "mousedown", this._mouseDownHandler, this);

		this._titleParaElement.appendChild(document.createTextNode(title || "UntitledWindowTitle{0}".localize([_counter])));
		this._controlsElement.className = "controls";
		this._closeButtonElement.className = "closeButton";
		this._closeButtonElement.title = "WindowCloseTitle".localize();
		attachEventHandler(this._closeButtonElement, "click", this._closeClickHandler, this);
		this._toolBarElement.className = "toolBar";
		this._contentElement.className = "content fullSize";
		this._statusBarElement.className = "statusBar fullWidth";

		this._regionElement.appendChild(this._windowElement);
		this._windowElement.appendChild(this._titleBarElement);
		this._titleBarElement.appendChild(this._iconElement);
		this._titleBarElement.appendChild(this._titleElement);
		this._titleElement.appendChild(this._titleParaElement);
		this._titleBarElement.appendChild(this._controlsElement);
		this._controlsElement.appendChild(this._closeButtonElement);
		this._windowElement.appendChild(this._toolBarElement);
		this._windowElement.appendChild(this._contentElement);
		this._windowElement.appendChild(this._statusBarElement);

		if (properties) {
			this._visible = properties.visible || false;
			this._width = properties.width || 200;
			this._height = properties.height || 200;
			this._titleBarVisible = properties.titleBarVisible !== false;
			this._toolBarVisible = properties.toolBarVisible || false;
			this._enableStatusBar = properties.enableStatusBar || false;
			this._left = properties.left || 0;
			this._top = properties.top || 0;
			this._outerPadding = properties.outerPadding || 0;
		}
		else {
			this._visible = false;
			this._width = 200;
			this._height = 200;
			this._titleBarVisible = true;
			this._toolBarVisible = false;
			this._statusBarVisible = false;
			this._left = 0;
			this._top = 0;
			this._outerPadding = 0;
		}
		this._autoHide = false;

		var pad = this._outerPadding, dblpad = 2 * this._outerPadding;
		this._regionElement.style.width = (dblpad + this._width).toString() + "px";
		this._regionElement.style.height = (dblpad + this._height).toString() + "px";
		this._regionElement.style.left = (this._left - pad).toString() + "px";
		this._regionElement.style.top = (this._top - pad).toString() + "px";

		this._windowElement.style.width = this._width.toString() + "px";
		this._windowElement.style.height = this._height.toString() + "px";
		this._windowElement.style.left = pad.toString() + "px";
		this._windowElement.style.top = pad.toString() + "px";

		this._regionElement.style.visibility = this._visible ? "" : "hidden";

		var contentTop = 0, contentBottom = 0;
		if (this._titleBarVisible) {
			contentTop += 29;
		}
		if (this._toolBarVisible) {
			contentTop += 29;
		}
		if (this._statusBarVisible) {
			contentBottom += 25;
		}
		this._titleBarElement.style.display = this._titleBarVisible ? "block" : "none";
		this._toolBarElement.style.display = this._toolBarVisible ? "block" : "none";
		this._statusBarElement.style.display = this._statusBarVisible ? "block" : "none";

		this._contentElement.style.top = contentTop.toString() + "px";
		this._contentElement.style.bottom = contentBottom.toString() + "px";

		this._parent.appendChild(this._regionElement);

		this.content = new ElementWrapper(this._contentElement);
		this.toolbar = new ElementWrapper(this._toolBarElement);

		Windows[id] = this;
	}

	return constructor;
})();

Window.prototype = {
	_closeClickHandler: function (evt) {
		evt = evt || event;
		if (evt) {
			this.hide();
			return stopEvent(evt);
		}
	},
	_mouseDownHandler: function (evt) {
		evt = evt || event;
		if (evt && (evt.which === 1 || evt.button === 1)) {
			if (this._visible) {
				this._dragStart = { x: evt.clientX, y: evt.clientY };
				this._dragOffset = { x: this._left, y: this._top };
				this._dragging = true;

				attachEventHandler(document, "mousemove", this._mouseMoveHandler, this);
				attachEventHandler(document, "mouseup", this._mouseUpHandler, this);

				return stopEvent(evt);
			}
		}
	},
	_mouseMoveHandler: function (evt) {
		if (this._dragging) {
			evt = evt || event;
			if (evt) {
				this.setLocation(this._dragOffset.x - this._dragStart.x + evt.clientX, this._dragOffset.y - this._dragStart.y + evt.clientY);

				return stopEvent(evt);
			}
		}
	},
	_mouseOverHandler: function (evt) {
		var target = evt.target || evt.srcElement;
		var related = evt.relatedTarget || evt.fromElement;
		while (related && related !== this._regionElement) {
			related = related.parentNode;
		}
		if (!related && this.hideTimeoutId) {
			clearTimeout(this.hideTimeoutId);
			this.hideTimeoutId = null;
		}
	},
	_mouseOutHandler: function (evt) {
		var target = evt.target || evt.srcElement;
		var related = evt.relatedTarget || evt.toElement;
		while (related && related !== this._regionElement) {
			related = related.parentNode;
		}
		if (!related && this._autoHide) {
			this.hide();
		}
	},
	_mouseUpHandler: function (evt) {
		if (!this._mouseMoveHandler(evt)) {
			detachEventHandler(document, "mousemove", this._mouseMoveHandler, this);
			detachEventHandler(document, "mouseup", this._mouseUpHandler, this);
			return false;
		}
	},
	getIsVisible: function () {
		return this._visible;
	},
	setIcon: function (url) {
		if (url) {
			this._iconElement.style.backgroundImage = "url('" + url + "')";
		}
		else {
			this._iconElement.style.backgroundImage = "";
		}
	},
	show: function (focusContent, autoHide) {
		if (!this._visible) {
			this._regionElement.style.visibility = "";
			if (focusContent !== false) {
				this._contentElement.focus();
			}
			this._visible = true;
			this._autoHide = autoHide || false;
		}
	},
	showModal: function () {
		if (!this._visible) {
			this._dimBlock.style.display = "block";
			this._modal = true;

			this.show();
		}
	},
	hide: function () {
		if (this._visible) {
			this._visible = false;
			this._regionElement.style.visibility = "hidden";

			if (this._modal) {
				this._dimBlock.style.display = "none";
				this._modal = false;
			}
		}
	},
	center: function () {
		var d = document.documentElement, b = document.body;
		this.setLocation((d.scrollLeft + b.scrollLeft) + (d.offsetWidth - this._windowElement.offsetWidth) / 2,
			(d.scrollTop + b.scrollTop) + (d.offsetHeight - this._windowElement.offsetHeight) / 2);
	},
	setLocation: function (left, top) {
		this._left = left;
		this._top = top;

		this._regionElement.style.left = (this._left - this._outerPadding).toString() + "px";
		this._regionElement.style.top = (this._top - this._outerPadding).toString() + "px";
	},
	getSize: function () {
		return { width: this._width, height: this._height };
	},
	setSize: function (width, height) {
		this._width = width;
		this._height = height;

		var dblpad = 2 * this._outerPadding;
		this._regionElement.style.width = (dblpad + this._width).toString() + "px";
		this._regionElement.style.height = (dblpad + this._height).toString() + "px";
		this._windowElement.style.width = this._width.toString() + "px";
		this._windowElement.style.height = this._height.toString() + "px";
	},
	setRelativeSize: function (relativeWidth, relativeHeight) {
		var size = Viewport.getSize();
		this.setSize(relativeWidth * size.width, relativeHeight * size.height);
	}
};

var activeTreeNode = null;
var contentElement, headingElement, breadcrumbElement, treeNavigationElement, publicationContainerElement;
var informationPaneElement, showToCToolElement, tocControllerElement;
var previousToolButton, nextToolButton;
var loadingTopicId = null, topicHeading = "", displayTopicHeading = "", currentTopicId = null;
var searchResultWindow, glossaryWindow;

function bookmark() {
	var url = location.href;
	var hash = location.hash;
	var title;
	if (hash === "#" || hash === "#ToC") {
		var idx = url.indexOf("#");
		url = url.substr(0, idx);
		title = document.title;
	}
	else if (displayTopicHeading) {
		title = displayTopicHeading;
	}
	else {
		title = document.title;
	}
	addBookmark(title, url);
}

function div(node, className) {
	var block = document.createElement("div");
	block.className = className || "";
	if (node) {
		block.appendChild(node);
	}
	return block;
}

function para(node, className) {
	var line = document.createElement("p");
	line.className = className || "";
	if (typeof (node) === "object") {
		line.appendChild(node);
	}
	else if (typeof (node) === "string") {
		line.appendChild(document.createTextNode(node));
	}
	return line;
}

function createLabel(text, forId) {
	var label = document.createElement("label");
	label.htmlFor = forId;
	label.appendChild(document.createTextNode(text));
	return label;
}

function createTextInput(id, value, properties) {
	var input = document.createElement("input");
	input.type = "text";
	input.id = id;
	input.value = value;
	if (properties) {
		input.readOnly = properties.readonly || false;
		input.disabled = properties.disabled || false;
	}
	return input;
}

function createButtonInput(text) {
	var input = document.createElement("input");
	input.type = "button";
	input.value = text;
	input.className = "button";
	return input;
}

function createSelect(id, values, selectedIndex) {
	var selectElement = document.createElement("select");
	selectElement.id = id;
	for (var i = 0, len = values.length; i < len; i++) {
		var value = values[i];
		var optionElement = new Option(value, value);
		selectElement.options[i] = optionElement;
	}
	if (typeof (selectedIndex) === "number") {
		selectElement.selectedIndex = selectedIndex;
	}
	return selectElement;
}

function createTextArea(id, cols, rows, text) {
	var textAreaElement = document.createElement("textarea");
	textAreaElement.id = id;
	if (typeof (cols) === "number") {
		textAreaElement.cols = cols;
	}
	if (typeof (rows) === "number") {
		textAreaElement.rows = rows;
	}
	textAreaElement.value = text || "";
	return textAreaElement;
}

var 
	inputFocusHandler = function () { if (typeof (this.changed) === "undefined") { this.select(); } },
	inputChangeHandler = function () {
		this.changed = true;
	},
	inputKeyPressHandler = function () {
		if (typeof (this.changed) === "undefined") { this.select(); this.changed = true; }
	};

function applySelectAllOnEnter(inputElement) {
	attachEventHandler(inputElement, "focus", inputFocusHandler, inputElement);
	attachEventHandler(inputElement, "change", inputChangeHandler, inputElement);
	attachEventHandler(inputElement, "keypress", inputKeyPressHandler, inputElement);
}

function submitFeedback(createLibrary) {
	var fbwin = Windows.feedbackWindow;

	// Update digest value
	var suppressValue = _spSuppressFormOnSubmitWrapper;
	try {
		_spSuppressFormOnSubmitWrapper = true;
		WebForm_OnSubmit.call();
	}
	finally {
		_spSuppressFormOnSubmitWrapper = suppressValue;
	}

	var formDigestElement = document.getElementById("__REQUESTDIGEST"), formDigestValue;
	if (!formDigestElement || formDigestElement.tagName.toLowerCase() !== "input" ||
		formDigestElement.type.toLowerCase() !== "hidden" || !(formDigestValue = formDigestElement.value)) {
		alert("Form digest could not be found");
		return;
	}

	var postData = "__REQUESTDIGEST=" + encodeURIComponent(formDigestValue) +
		"&createlibrary=" + encodeURIComponent(createLibrary === true ? "true" : "false") +
		"&publication=" + encodeURIComponent(document.getElementById('publicationInput').value) +
		"&topic=" + encodeURIComponent(document.getElementById('topicInput').value) +
		"&subject=" + encodeURIComponent(document.getElementById('subjectInput').value) +
		"&sender=" + encodeURIComponent(document.getElementById('senderInput').value) +
		"&type=" + encodeURIComponent(document.getElementById('typeSelect').value) +
		"&referrer=" + encodeURIComponent(location.href) +
		"&message=" + encodeURIComponent(document.getElementById('messageInput').value);

	var request = getXmlHttpRequest();
	request.open(Http.Method.Post, appBaseUrl + "Feedback.ashx", true);
	request.onreadystatechange = function () {
		if (request.readyState === Http.State.Done) {
			fbwin.setIcon(null);
			switch (request.status) {
				case 200:
					fbwin.content.clear();
					fbwin.content.appendHtmlNode(para("MessageSentText".localize()));
					fbwin.content.appendHtmlNode(para("FeedbackAppreciatedText".localize()));
					break;

				case 500:
					var knownError = request.responseText.split(',');
					if (knownError.length >= 2 && knownError[0] === "ke") {
						switch (knownError[1]) {
							case "NoList":
								if (confirm("NoListQueryCreateText{0}".localize([knownError[2]]))) {
									//resend request
									fbwin.setIcon(appBaseUrl + "Images/loading.gif");
									setTimeout(function () { submitFeedback(true); }, 0);
								}
								break;

							case "NotLibrary":
								alert("ListNotLibraryText{0}".localize([knownError[2]]));
								break;

							case "Non-existingFolder":
								alert("NonexistingFolder{0}".localize([knownError[2]]));
								break;
						}
					}
					else {
						alert(request.responseText);
					}
					break;

				default:
					alert(request.responseText);
					break;
			}
		}
	};
	request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	request.setRequestHeader("Content-length", postData.length);
	request.send(postData);
}

function feedback(evt) {
	evt = evt || event;
	var w1 = Windows.feedbackWindow;
	if (!w1) {
		w1 = new Window(publicationContainerElement, "feedbackWindow", "feedback form", "FeedbackWindowTitle".localize());
	}
	var introText = document.createElement("p");
	introText.className = "intro";
	introText.appendChild(document.createTextNode("FeedbackIntroText".localize()));
	var labelColumn = document.createElement("div");
	labelColumn.className = "column label";
	var inputColumn = document.createElement("div");
	inputColumn.className = "column input";

	labelColumn.appendChild(para(createLabel("PublicationLabel".localize(), "publicationInput")));
	inputColumn.appendChild(para(createTextInput("publicationInput", publicationTitle, { readonly: true, disabled: true })));

	labelColumn.appendChild(para(createLabel("TopicLabel".localize(), "topicInput")));
	inputColumn.appendChild(para(createTextInput("topicInput", topicHeading, { readonly: true, disabled: true })));

	labelColumn.appendChild(para(createLabel("SubjectLabel".localize(), "subjectInput")));
	var subjectInput = createTextInput("subjectInput", "TypeMessageSubject".localize());
	applySelectAllOnEnter(subjectInput);
	inputColumn.appendChild(para(subjectInput));

	labelColumn.appendChild(para(createLabel("SenderLabel".localize(), "senderInput")));
	var senderInput = createTextInput("senderInput", currentUsername);
	applySelectAllOnEnter(senderInput);
	inputColumn.appendChild(para(senderInput));

	labelColumn.appendChild(para(createLabel("TypeLabel".localize(), "typeSelect")));
	var typeSelect = createSelect("typeSelect",
		["GeneralFeedbackType".localize(), "ChangeRequestType".localize(), "QuestionType".localize(), "CommentType".localize()], 0);
	inputColumn.appendChild(para(typeSelect));

	var textArea = createTextArea("messageInput", 20, 2, "EnterMessageText".localize());
	applySelectAllOnEnter(textArea);

	var sendButton = createButtonInput("SubmitFeedbackButtonText".localize());
	attachEventHandler(sendButton, "click", function () {
		w1.setIcon(appBaseUrl + "Images/loading.gif");
		setTimeout(submitFeedback, 0);
	});

	w1.content.clear();
	w1.content.appendHtmlNode(introText);
	w1.content.appendHtmlNode(labelColumn);
	w1.content.appendHtmlNode(inputColumn);
	w1.content.appendHtmlNode(textArea);
	w1.content.appendHtmlNode(para(sendButton));
	w1.setSize(529, 367);
	placeWindowAroundCursor(w1, evt);
	w1.show();

	subjectInput.focus();
}

function sendMail(to, recipientName, from, senderName, subject, htmlMessage, callback) {
	var postData = "to=" + encodeURIComponent(to);
	if (recipientName !== null) {
		postData += "&recipient=" + encodeURIComponent(recipientName);
	}
	if (from !== null) {
		postData += "&from=" + encodeURIComponent(from);
	}
	if (senderName !== null) {
		postData += "&sender=" + encodeURIComponent(senderName);
	}
	if (subject !== null) {
		postData += "&subject=" + encodeURIComponent(subject);
	}
	if (htmlMessage !== null) {
		postData += "&message=" + encodeURIComponent(htmlMessage);
	}

	var request = getXmlHttpRequest();
	request.open(Http.Method.Post, appBaseUrl + "Mail.ashx", true);
	request.onreadystatechange = function () {
		if (request.readyState === Http.State.Done) {
			if (typeof (callback) === "function") {
				callback(request.status, request.responseText);
			}
		}
	};
	request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	request.setRequestHeader("Content-length", postData.length);
	request.send(postData);
}

function submitNotification() {
	var win = Windows.notifyWindow;

	var senderValue = document.getElementById("notifySenderInput").value;
	var userMessage = document.getElementById("notifyMessageInput").value;
	var message = "NotificationMessage{7}".localize(
		[publicationTitle, topicHeading, senderValue,
		location.href, location.href, userMessage, siteTitle,
		Publication.editor]);

	sendMail(document.getElementById('notifyAddressInput').value,
		null,
		null, senderValue,
		document.getElementById('notifySubjectInput').value,
		message, function (status, responseText) {
			win.setIcon(null);
			switch (status) {
				case 200:
					win.content.clear();
					win.content.appendHtmlNode(para("NotificationSentText".localize()));
					break;
				case 500:
				default:
					alert(responseText);
					break;
			}
		});
}

function sendToFriend(evt) {
	evt = evt || event;
	var w1 = Windows.notifyWindow;
	if (!w1) {
		w1 = new Window(publicationContainerElement, "notifyWindow", "notify form", "NotifyWindowTitle".localize());
	}
	var introText = document.createElement("p");
	introText.className = "intro";
	introText.appendChild(document.createTextNode("NotifyIntroText".localize()));
	var labelColumn = document.createElement("div");
	labelColumn.className = "column label";
	var inputColumn = document.createElement("div");
	inputColumn.className = "column input";

	labelColumn.appendChild(para(createLabel("SenderLabel".localize(), "notifySenderInput")));
	var senderInput = createTextInput("notifySenderInput", currentUsername);
	applySelectAllOnEnter(senderInput);
	inputColumn.appendChild(para(senderInput));

	labelColumn.appendChild(para(createLabel("SendToLabel".localize(), "notifyAddressInput")));
	var recipientAddressInput = createTextInput("notifyAddressInput", "RecipientAddress".localize());
	applySelectAllOnEnter(recipientAddressInput);
	inputColumn.appendChild(para(recipientAddressInput));

	labelColumn.appendChild(para(createLabel("SubjectLabel".localize(), "notifySubjectInput")));
	var subjectInput = createTextInput("notifySubjectInput", "NotifyMessageSubject{0}".localize([publicationTitle]));
	applySelectAllOnEnter(subjectInput);
	inputColumn.appendChild(para(subjectInput));

	var textArea = createTextArea("notifyMessageInput", 20, 2, "EnterMessageText".localize());
	applySelectAllOnEnter(textArea);

	var sendButton = createButtonInput("SubmitNotificationButtonText".localize());
	attachEventHandler(sendButton, "click", function () {
		w1.setIcon(appBaseUrl + "Images/loading.gif");
		setTimeout(submitNotification, 0);
	});

	w1.content.clear();
	w1.content.appendHtmlNode(introText);
	w1.content.appendHtmlNode(labelColumn);
	w1.content.appendHtmlNode(inputColumn);
	w1.content.appendHtmlNode(textArea);
	w1.content.appendHtmlNode(para(sendButton));
	w1.setSize(529, 367);
	placeWindowAroundCursor(w1, evt);
	w1.show();

	recipientAddressInput.focus();
}

function understood(evt) {
	// Update digest value
	var suppressValue = _spSuppressFormOnSubmitWrapper;
	try {
		_spSuppressFormOnSubmitWrapper = true;
		WebForm_OnSubmit.call();
	}
	finally {
		_spSuppressFormOnSubmitWrapper = suppressValue;
	}

	var formDigestElement = document.getElementById("__REQUESTDIGEST"), formDigestValue;
	if (!formDigestElement || formDigestElement.tagName.toLowerCase() !== "input" ||
		formDigestElement.type.toLowerCase() !== "hidden" || !(formDigestValue = formDigestElement.value)) {
		alert("Form digest could not be found");
		return;
	}

	var postData = "__REQUESTDIGEST=" + encodeURIComponent(formDigestValue) +
		"&source=" + encodeURIComponent(location.href);

	var request = getXmlHttpRequest();
	request.open(Http.Method.Post, appBaseUrl + "Understood.ashx", true);
	request.onreadystatechange = function () {
		if (request.readyState === Http.State.Done) {
			switch (request.status) {
				case 200:
					alert("Read and Understood registered sucessfully");
					break;

				case 500:
					var knownError = request.responseText.split(',');
					if (knownError.length >= 2 && knownError[0] === "ke") {
						switch (knownError[1]) {
							case "Non-existingList":
								alert("NonexistingList{0}".localize([knownError[2]]));
								break;

							case "NotList":
								alert("ListNotGenericText{0}".localize([knownError[2]]));
								break;

							case "Non-existingFolder":
								alert("NonexistingFolder{0}".localize([knownError[2]]));
								break;
						}
					}
					else {
						alert(request.responseText);
					}
					break;

				default:
					alert(request.responseText);
					break;
			}
		}
	};
	request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	request.setRequestHeader("Content-length", postData.length);
	request.send(postData);
}

function toggleTreeNavigation() {
	if (treeNavigationElement) {
		if (alwaysShowNavigation) {
			treeNavigationElement.style.display = "block";
		}
		else {
			if (treeNavigationElement.style.display === "none") {
				treeNavigationElement.style.display = "block";
			}
			else {
				treeNavigationElement.style.display = "none";
			}
		}
	}
}

function hideTreeNavigation() {
	if (treeNavigationElement) {
		if (alwaysShowNavigation) {
			treeNavigationElement.style.display = "block";
		}
		else {
			treeNavigationElement.style.display = "none";
		}
	}
}

function showTreeNavigation() {
	if (treeNavigationElement) {
		treeNavigationElement.style.display = "block";
	}
}

function tocControllerClick(evt) {
	evt = evt ? evt : event;
	toggleTreeNavigation();
	return stopEvent(evt);
}

function toggleInformationPane(evt) {
	evt = evt || event;
	if (informationPaneElement) {
		var w1 = Windows.informationWindow;
		if (!w1) {
			w1 = new Window(publicationContainerElement, "informationWindow", "information", "InformationWindowTitle".localize());
			w1.content.clear();
			while (informationPaneElement.hasChildNodes()) {
				w1.content.appendHtmlNode(informationPaneElement.firstChild);
			}
		}

		if (w1.getIsVisible()) {
			w1.hide();
		}
		else {
			w1.setRelativeSize(0.4, 0.3);
			placeWindowAroundCursor(w1, evt);
			w1.show();
		}
	}
}

function clearDynamicBreadcrumbs() {
	if (breadcrumbElement) {
		var node;
		while ((node = breadcrumbElement.lastChild)) {
			if (node.nodeType === NodeType.Element && node.tagName.toLowerCase() === "span" && hasClass(node, "staticcrumb")) {
				break;
			}
			else {
				breadcrumbElement.removeChild(node);
			}
		}
	}
}

function setStyleBlock(id, content) {
	var styleElement = document.getElementById(id);
	if (!styleElement) {
		styleElement = document.createElement("style");
		styleElement.id = id;
		styleElement.type = "text/css";

		document.getElementsByTagName("head")[0].appendChild(styleElement);
	}
	var styleSheet;
	if (typeof (styleElement.styleSheet) === "object") {
		styleSheet = styleElement.styleSheet;
	}
	else {
		styleSheet = styleElement;
	}
	if (typeof (styleSheet.cssText) !== "undefined") {
		styleSheet.cssText = content;
	}
	else {
		styleSheet.textContent = content;
	}
}

function createCrumbLink(title, href, isStatic, clickHandler) {
	var spanElement = document.createElement("span");
	spanElement.className = isStatic ? "staticcrumb" : "dyncrumb";
	var linkElement = document.createElement("a");
	linkElement.setAttribute("title", title);
	linkElement.setAttribute("href", href);
	attachEventHandler(linkElement, "click", clickHandler);
	linkElement.appendChild(document.createTextNode(title));
	spanElement.appendChild(linkElement);
	return spanElement;
}

function createCrumbArrow(isStatic) {
	var arrowElement = document.createElement("span");
	arrowElement.className = isStatic ? "staticcrumb" : "dyncrumb";
	arrowElement.appendChild(document.createTextNode(" > "));
	return arrowElement;
}

function focusAnchor(anchor) {
	if (anchor) {
		if (typeof (anchor) === "string") {
			if (anchor.charAt(0) === "#") {
				anchor = anchor.substr(1);
				var anchorList = document.getElementsByName(anchor);
				if (anchorList && anchorList.length !== 0) {
					anchorList[0].scrollIntoView();
				}
			}
			else {
				var elm = document.getElementById(anchor);
				if (elm) {
					elm.scrollIntoView();
				}
			}
		}
		else if (typeof (anchor) === "object") {
			if (anchor.nodeType === NodeType.Element) {
				anchor.scrollIntoView();
			}
		}
	}
}

function buildDynamicBreadcrumbs(breadcrumbElement, topicDocument) {
	if (breadcrumbElement) {
		var ancestorReferences = topicDocument.selectNodes("/x:html/x:head/x:link[@rev='up']");
		if (ancestorReferences !== null) {
			var ancestorCount = ancestorReferences.length;
			for (var i = 0; i < ancestorCount; i++) {
				var ancestorReference = ancestorReferences[i];
				breadcrumbElement.appendChild(createCrumbArrow(false));
				var breadcrumbLink = createCrumbLink(ancestorReference.getAttribute("title"), ancestorReference.getAttribute("href"), false, breadcrumbClickHandler);
				if (typeof (adjustBreadcrumbLink) === "function") {
					adjustBreadcrumbLink(breadcrumbLink);
				}
				breadcrumbElement.appendChild(breadcrumbLink);
			}
		}
	}
}

function breadcrumbClickHandler(evt) {
	evt = evt || event;
	if (evt) {
		var handled = false;
		var target = evt.target ? evt.target : evt.srcElement;
		while (target) {
			if (target.nodeType === NodeType.Element) {
				if (target.tagName.toLowerCase() === "a") {
					var reference = target.getAttribute("href");
					if (reference.charAt(0) === '@') {
						reference = reference.substring(1);
						if (reference.length === 0) {
							reference = defaultTopicId;
						}
						internalLink(reference, '');
						handled = true;
					}
				}
				else {
					target = target.parentNode;
					continue;
				}
			}
			break;
		}

		if (handled) {
			return stopEvent(evt);
		}
	}
}

function endLoadTopic(request, anchor) {
	if (treeNavigationElement) {
		if (hasClass(treeNavigationElement, "virtual")) {
			replaceClass(treeNavigationElement, "virtual", "overlap");
			tocControllerElement.style.visibility = "visible";
		}
	}

	hideTreeNavigation();

	clearDynamicBreadcrumbs();

	if (request.status === 200) {
		var topicDocument = request.responseXML;
		topicDocument.setProperty("SelectionNamespaces", "xmlns:x='http://www.w3.org/1999/xhtml'");

		var styleElement = topicDocument.selectSingleNode("/x:html/x:head/x:style");

		setStyleBlock("topicStyle", styleElement ? getElementText(styleElement) : "");

		clearElement(headingElement);

		topicHeading = getElementText(topicDocument.selectSingleNode("/x:html/x:head/x:title"));
		if (typeof (overrideTopicHeading) === "function") {
			displayTopicHeading = overrideTopicHeading(topicHeading);
		}
		else {
			displayTopicHeading = topicHeading;
		}
		headingElement.appendChild(document.createTextNode(displayTopicHeading));

		buildDynamicBreadcrumbs(breadcrumbElement, topicDocument);

		// This method is defined in PreIE7.js
		if (typeof (topicPngFix) === "function") {
			topicPngFix(topicDocument);
		}

		// Customization opportunity
		if (typeof (adjustTopicDocument) === "function") {
			adjustTopicDocument(topicDocument);
		}
		var divNode = topicDocument.selectSingleNode("/x:html/x:body/x:div");
		var html = (new XMLSerializer()).serializeToString(divNode);
		setElementHtml(contentElement, html);

		if (anchor) {
			focusAnchor(anchor);
		}
		else {
			focusAnchor(document.body);
		}
	}
	else if (request.status === 404) {
		setStyleBlock("topicStyle", "");
		headingElement.innerHTML = "TopicNotFoundHeading".localize();
		contentElement.innerHTML = "TopicNotFoundMessage".localize();
		focusAnchor(publicationContainerElement);
	}
	else {
		setStyleBlock("topicStyle", "");
		headingElement.innerHTML = request.status + " " + request.statusText;
		contentElement.innerHTML = request.responseText;
		focusAnchor(publicationContainerElement);
	}
}

function beginLoadTopic(topicId, anchor, suppressHistory) {
	topicId = topicId || defaultTopicId;
	if (!topicId) { return; }

	if (loadingTopicId !== topicId) {
		var request = getSharedXmlHttpRequest();
		if (Http.State.Unsent < request.readyState && request.readyState < Http.State.Done) {
			request.abort();
		}

		if (!suppressHistory) {
			dhtmlHistory.add(topicId, null);
		}

		if (topicId === "ToC") {
			if (treeNavigationElement) {
				setStyleBlock("topicStyle", "");
				clearElement(headingElement);
				clearDynamicBreadcrumbs();

				if (!hasClass(treeNavigationElement, "virtual")) {
					clearElement(contentElement);
					replaceClass(treeNavigationElement, "overlap", "virtual");
					tocControllerElement.style.visibility = "hidden";
				}
				showTreeNavigation();
				removeClass(document.body, "busy");
				loadingTopicId = null;
			}
		}
		else {
			loadingTopicId = topicId;
			addClass(document.body, "busy");
			var url = appBaseUrl + "Topic.ashx?id=" + encodeURIComponent(topicId) + "&pid=" + encodeURIComponent(publicationUnid);
			if (window.isPreIE7) { url += "&preie7=true"; }
			request.open(Http.Method.Get, url, true);

			request.onreadystatechange = function () {
				if (request.readyState === Http.State.Done) {
					removeClass(document.body, "busy");
					currentTopicId = loadingTopicId;
					loadingTopicId = null;
					if (request.status === 200) {
						if (request.responseXML.documentElement === null) {
							request.responseXML.preserveWhiteSpace = true;
							request.responseXML.load(request.responseStream);
						}
					}
					endLoadTopic(request, anchor);
				}
			};
			request.send(null);
		}
	}
}

function getTreeNodeLink(treeNode) {
	var children = treeNode.childNodes;
	for (var i = 0, childCount = children.length; i < childCount; i++) {
		var child = children[i];
		if (child.nodeType === NodeType.Element && child.tagName.toLowerCase() === "span") {
			var grandChildren = child.childNodes;
			for (var j = 0, grandChildCount = grandChildren.length; j < grandChildCount; j++) {
				var grandChild = grandChildren[j];
				if (grandChild.nodeType === NodeType.Element && grandChild.tagName.toLowerCase() === "a") {
					return grandChild;
				}
			}
		}
	}
	return null;
}

function getTreeNodeLinkValue(linkElement) {
	if (linkElement && linkElement.nodeType === NodeType.Element && linkElement.tagName.toLowerCase() === "a") {
		var value = linkElement.href;
		var idx = value.indexOf('@');
		if (idx !== -1) {
			return value.substr(idx + 1);
		}
	}
	return null;
}

function setToolButtonEnabled(toolButton, enabled) {
	if (toolButton) {
		if (enabled) {
			removeClass(toolButton, "disabled");
		}
		else {
			addClass(toolButton, "disabled");
		}
	}
}

function activateTreeNode(treeNode, treeNodeLink) {
	if (activeTreeNode !== treeNode) {
		if (activeTreeNode) {
			var activeLinkElement = getTreeNodeLink(activeTreeNode);
			removeClass(activeLinkElement, "selected");
		}
		activeTreeNode = treeNode;
		if (treeNode) {
			setToolButtonEnabled(previousToolButton, !hasClass(treeNode, "begin"));
			setToolButtonEnabled(nextToolButton, !hasClass(treeNode, "end"));
			if (!treeNodeLink) {
				treeNodeLink = getTreeNodeLink(treeNode);
			}
			addClass(treeNodeLink, "selected");
			var value = getTreeNodeLinkValue(treeNodeLink);
			beginLoadTopic(value, null, false);
		}
		else {
			setToolButtonEnabled(previousToolButton, true);
			setToolButtonEnabled(nextToolButton, true);
		}
	}
}

function tocClick(evt) {
	var handled = false;
	evt = evt ? evt : event;
	if (evt) {
		var target = evt.target ? evt.target : evt.srcElement;
		if (target) {
			var treeNode;
			switch (target.tagName.toLowerCase()) {
				case "li":
					handled = true;
					break;

				case "a":
					if (!target.className || target.className === "selected") {
						treeNode = target.parentNode.parentNode;
						replaceClass(treeNode, "collapsed", "expanded");
						activateTreeNode(treeNode, target);
						handled = true;
					}
					break;

				case "span":
					treeNode = target.parentNode;
					toggleClasses(treeNode, "collapsed", "expanded");
					handled = true;
					break;
			}
		}
	}
	if (handled) {
		return stopEvent(evt);
	}
	else {
		return true;
	}
}

function ensureTreeNodeVisible(treeNode) {
	var node = treeNode.parentNode;
	while (node && node.nodeType === NodeType.Element) {
		var tagName = node.tagName.toLowerCase();
		if (tagName === "div") {
			break;
		}
		else if (tagName === "li") {
			replaceClass(node, "collapsed", "expanded");
		}
		node = node.parentNode;
	}
}

function selectTreeNode(treeNode, treeNodeLink) {
	if (activeTreeNode !== treeNode) {
		if (activeTreeNode) {
			var activeLinkElement = getTreeNodeLink(activeTreeNode);
			removeClass(activeLinkElement, "selected");
		}
		activeTreeNode = treeNode;
		if (treeNode) {
			ensureTreeNodeVisible(treeNode);
			setToolButtonEnabled(previousToolButton, !hasClass(treeNode, "begin"));
			setToolButtonEnabled(nextToolButton, !hasClass(treeNode, "end"));
			if (!treeNodeLink) {
				treeNodeLink = getTreeNodeLink(treeNode);
			}
			addClass(treeNodeLink, "selected");
		}
		else {
			setToolButtonEnabled(previousToolButton, true);
			setToolButtonEnabled(nextToolButton, true);
		}
	}
}

function getPreviousSibling(node) {
	do {
		node = node.previousSibling;
	} while (node && node.nodeType !== NodeType.Element);
	return (node && node.nodeType === NodeType.Element) ? node : null;
}

function getNextSibling(node) {
	do {
		node = node.nextSibling;
	} while (node && node.nodeType !== NodeType.Element);
	return (node && node.nodeType === NodeType.Element) ? node : null;
}

function getFirstSelectableDescendant(element) {
	for (var i = 0, l = element.childNodes.length; i < l; i++) {
		var node = element.childNodes[i];
		if (node.nodeType === NodeType.Element) {
			if (node.tagName.toLowerCase() === "li") {
				return node;
			}
			var subChild = getFirstSelectableDescendant(node);
			if (subChild) { return subChild; }
		}
	}
	return null;
}

function getNextSelectableNode(currentNode) {
	var child = getFirstSelectableDescendant(currentNode);
	if (child) { return child; }
	var sibling = getNextSibling(currentNode);
	while (sibling === null) {
		do {
			currentNode = currentNode.parentNode;
		} while (currentNode && currentNode.tagName.toLowerCase() !== "div" && currentNode.tagName.toLowerCase() !== "li");
		if (!currentNode || currentNode.tagName.toLowerCase() === "div") { return null; }
		sibling = getNextSibling(currentNode);
	}
	return sibling;
}

function selectNextTreeNode() {
	if (treeNavigationElement) {
		var nextTreeNode;
		if (activeTreeNode) {
			nextTreeNode = getNextSelectableNode(activeTreeNode);
		} else {
			nextTreeNode = getFirstSelectableDescendant(treeNavigationElement);
		}

		if (nextTreeNode) {
			activateTreeNode(nextTreeNode, null);
			ensureTreeNodeVisible(nextTreeNode);
		}
	}
}

function getLastSelectableDescendant(element) {
	var i = element.childNodes.length;
	while (0 < i--) {
		var node = element.childNodes[i];
		if (node.nodeType === NodeType.Element) {
			var subChild = getLastSelectableDescendant(node);
			if (subChild) { return subChild; }
			if (node.tagName.toLowerCase() === "li") {
				return node;
			}
		}
	}
	return null;
}

function getPreviousSelectableNode(currentNode) {
	var sibling = getPreviousSibling(currentNode);
	if (sibling) {
		var child = getLastSelectableDescendant(sibling);
		if (child) { return child; }
	}
	else {
		do {
			currentNode = currentNode.parentNode;
		} while (currentNode && currentNode.tagName.toLowerCase() !== "div" && currentNode.tagName.toLowerCase() !== "li");
		if (!currentNode || currentNode.tagName.toLowerCase() === "div") { return null; }
		sibling = currentNode;
	}
	return sibling;
}

function selectPreviousTreeNode() {
	if (treeNavigationElement) {
		var previousTreeNode;
		if (activeTreeNode) {
			previousTreeNode = getPreviousSelectableNode(activeTreeNode);
		} else {
			previousTreeNode = getLastSelectableDescendant(treeNavigationElement);
		}

		if (previousTreeNode) {
			activateTreeNode(previousTreeNode, null);
			ensureTreeNodeVisible(previousTreeNode);
		}
	}
}

function getTreeNodeLinkByTopicId(topicId) {
	if (topicId) {
		var rex = new RegExp("@" + topicId + "\\b");
		var candidateLinks = treeNavigationElement.getElementsByTagName("a");
		for (var i = 0, len = candidateLinks.length; i < len; i++) {
			var candidateLink = candidateLinks[i];
			if (rex.test(candidateLink.href)) {
				return candidateLink;
			}
		}
	}
	return null;
}

function internalLink(topicId, anchor) {
	if (treeNavigationElement) {
		var treeNodeLink = getTreeNodeLinkByTopicId(topicId);
		if (treeNodeLink) {
			selectTreeNode(treeNodeLink.parentNode.parentNode, treeNodeLink);
		}
		else {
			selectTreeNode(null, null);
		}
	}
	searchResultWindow.hide();
	beginLoadTopic(topicId, anchor, false);
}

function externalLink(databaseName, publicationTitle, topicHeading, additional) {
	var request = getXmlHttpRequest();
	var url = appBaseUrl + "Link.ashx?publication=" + encodeURIComponent(publicationTitle) +
		"&topic=" + encodeURIComponent(topicHeading) +
		"&refid=" + encodeURIComponent(publicationUnid) +
		"&tid=" + new Date().getTime().toString(16); // Avoid browser client cache
	if (databaseName) { url += "&database=" + encodeURIComponent(databaseName); }
	request.open(Http.Method.Get, url, true);
	request.onreadystatechange = function () {
		if (request.readyState === Http.State.Done) {
			switch (request.status) {
				case 200:
					location.href = request.responseText;
					break;

				case 404:
					alert(request.responseText);
					break;

				case 500:
					alert(request.responseText);
					break;

				default:
					alert(request.responseText);
					break;
			}
		}
	};
	request.send(null);
}

function PopupShow(popupid, evt) {
	evt = evt || event;
	if (evt) {
		var target = evt.target || evt.srcElement;
		if (target) {
			var targetParent = target.offsetParent;
			var popupElement = document.getElementById(popupid);
			var left = evt.x, top = evt.y, popupParent = popupElement;
			popupElement.style.left = left.toString() + "px";
			popupElement.style.top = top.toString() + "px";
			if (popupElement) {
				target.contentElement = popupElement;
				popupElement.style.display = "block";
				popupElement.style.visibility = "visible";
			}
		}
	}
}

function PopupHide(evt) {
	evt = evt || event;
	if (evt) {
		var target = evt.target || evt.srcElement;
		if (target) {
			var popupElement = target.contentElement;
			if (popupElement) {
				popupElement.style.visibility = "hidden";
			}
		}
	}
}

function openAttachment(topic) {
	window.open(appBaseUrl + "Blob.ashx?topicid=" + encodeURIComponent(topic) + "&pid=" + encodeURIComponent(publicationUnid), "_blank", "menubar=1,scrollbars=1,resizable=1");
}

var loadingGlossaryReference;
var tid = new Date().getTime().toString(16);
function beginGetGlossaryContent(reference) {
	var request = getXmlHttpRequest();
	if (loadingGlossaryReference !== reference) {
		if (Http.State.Unsent < request.readyState && request.readyState < Http.State.Done) {
			request.abort();
		}

		loadingGlossaryReference = reference;
		glossaryWindow.content.clear();
		glossaryWindow.content.appendHtmlNode(document.createTextNode("LoadingBusyMessage".localize()));
		var url = appBaseUrl + "Glossary.ashx?reference=" + encodeURIComponent(reference) + "&tid=" + tid;
		if (window.isPreIE7) { url += "&preie7=true"; }
		request.open(Http.Method.Get, url, true);

		request.onreadystatechange = function () {
			if (request.readyState === Http.State.Done) {
				glossaryWindow.reference = loadingGlossaryReference;
				loadingGlossaryReference = null;
				if (request.status === 200) {
					if (request.responseXML.documentElement === null) {
						request.responseXML.preserveWhiteSpace = true;
						request.responseXML.load(request.responseStream);
					}
					var glossaryDocument = request.responseXML;
					glossaryDocument.setProperty("SelectionNamespaces", "xmlns:x='http://www.w3.org/1999/xhtml'");

					var styleElement = glossaryDocument.selectSingleNode("/x:html/x:head/x:style");
					setStyleBlock("glossaryStyle", styleElement ? getElementText(styleElement) : "");

					var divNode = glossaryDocument.selectSingleNode("/x:html/x:body/x:div");
					var html = (new XMLSerializer()).serializeToString(divNode);
					glossaryWindow.content.setHtml(html);

					var headingElement = document.createElement("h2");
					headingElement.appendChild(document.createTextNode(
						getElementText(glossaryDocument.selectSingleNode("/x:html/x:head/x:title"))));
					glossaryWindow.content.prependHtmlNode(headingElement);
				}
				else {
					glossaryWindow.content.clear();
					var pElement = document.createElement("p");
					pElement.className = "glossaryRetrievalError";
					pElement.appendChild(document.createTextNode(request.responseText));

					glossaryWindow.content.appendHtmlNode(pElement);
				}
			}
		};
		request.send(null);
	}
}

function hideGlossaryWindow() {
	if (glossaryWindow) {
		if (glossaryWindow.currentLinkElement) {
			detachEventHandler(glossaryWindow.currentLinkElement, "mouseout", exitGlossaryItem);
			glossaryWindow.currentLinkElement = null;
		}
		glossaryWindow.hide();
		glossaryWindow.hideTimeoutId = null;
	}
}

function exitGlossaryItem(evt) {
	if ((evt = evt || event)) {
		var target = evt.target || evt.srcElement;
		if (!evt.shiftKey && target && glossaryWindow && !glossaryWindow.hideTimeoutId) {
			glossaryWindow.hideTimeoutId = setTimeout(hideGlossaryWindow, 500);
		}
	}
}

function placeWindowAroundCursor(window, evt) {
	var pagePosition = Cursor.getPagePosition(evt);
	var viewportPosition = Cursor.getViewportPosition(evt);
	var area = Viewport.getSize();
	var size = window.getSize();
	var position = { x: 0, y: 0 }, offset = 5;
	if (viewportPosition.y >= size.height) {
		// Above
		position.y = pagePosition.y - size.height - offset;
	}
	else if (area.height - viewportPosition.y >= size.height) {
		// Below
		position.y = pagePosition.y + offset;
	}
	else {
		// Centered
		position.y = pagePosition.y - size.height / 2;
		if (position.y < 0) {
			position.y = 0;
		}
	}
	if (viewportPosition.x < area.width / 2) {
		// Right-of
		position.x = pagePosition.x + offset;
	}
	else {
		// Left-of
		position.x = pagePosition.x - size.width - offset;
		if (position.x < 0) {
			position.x = 0;
		}
	}
	window.setLocation(position.x, position.y);
}

function hnLink(evt, type, title, heading) {
	if (type === "Glossary") {
		if ((evt = evt || event)) {
			var handled = false;
			var target = evt.target || evt.srcElement;
			if (!evt.shiftKey && target && glossaryWindow) {
				handled = true;

				if (glossaryWindow.currentLinkElement) {
					if (glossaryWindow.currentLinkElement === target && glossaryWindow.getIsVisible()) {
						return;
					}
					else {
						if (evt.type === "mouseover") {
							detachEventHandler(glossaryWindow.currentLinkElement, "mouseout", exitGlossaryItem);
						}
					}
				}
				glossaryWindow.currentLinkElement = target;
				if (evt.type === "mouseover") {
					attachEventHandler(target, "mouseout", exitGlossaryItem);
				}

				/*** Place ***/
				placeWindowAroundCursor(glossaryWindow, evt);

				/*** Set initial content ***/
				glossaryWindow.content.clear();

				beginGetGlossaryContent(urlDecode(heading));

				glossaryWindow.show(false, evt.type === "mouseover");
			}
			if (evt.type === "click" && handled) {
				return stopEvent(evt);
			}
			else {
				return true;
			}
		}
	}
	else {
		externalLink("", decodeURIComponent(title), decodeURIComponent(heading));
	}
	return true;
}

function hidePops() {
	if (glossaryWindow) {
		glossaryWindow.hide();
	}
	if (treeNavigationElement) {
		if (alwaysShowNavigation) {
			treeNavigationElement.style.display = "block";
		}
		else {
			if (hasClass(treeNavigationElement, "overlap")) {
				treeNavigationElement.style.display = "none";
			}
		}
	}
}

function updateUI(topicId) {
	if (treeNavigationElement) {
		topicId = topicId || defaultTopicId;
		var treeNodeLink = getTreeNodeLinkByTopicId(topicId);
		if (treeNodeLink) {
			selectTreeNode(treeNodeLink.parentNode.parentNode, treeNodeLink);
		}
		else {
			selectTreeNode(null, null);
		}
	}
	beginLoadTopic(topicId, null, true);
}

function handleHistoryChange(newLocation, historyData) {
	// use the history data to update our UI
	updateUI(newLocation);
}

function placeBreadcrumbs() {
	var spBreadcrumbElement = document.getElementById(spBreadcrumbElementId);
	if (breadcrumbElement) {
		if (spBreadcrumbElement && spBreadcrumbElement.className === "breadcrumb" && stealBreadcrumbs) {
			var crumbNode, first = true;
			while ((crumbNode = spBreadcrumbElement.firstChild)) {
				if (crumbNode.nodeType === NodeType.Element && crumbNode.tagName.toLowerCase() === "span") {
					addClass(crumbNode, "staticcrumb");

					if (hasClass(crumbNode, "breadcrumbCurrent")) {
						var linkElement = document.createElement("a");
						while (crumbNode.firstChild) {
							linkElement.appendChild(crumbNode.firstChild);
						}
						linkElement.setAttribute("href", "..");
						crumbNode.appendChild(linkElement);
					}

					if (first) {
						breadcrumbElement.appendChild(createCrumbArrow(true));
						first = false;
					}
					breadcrumbElement.appendChild(crumbNode);
				}
				else {
					spBreadcrumbElement.removeChild(crumbNode);
				}
			}
		}
		breadcrumbElement.appendChild(createCrumbArrow(true));
		var breadcrumbLink = createCrumbLink(publicationTitle, "@", true, breadcrumbClickHandler);
		if (typeof (adjustBreadcrumbLink) === "function") {
			adjustBreadcrumbLink(breadcrumbLink);
		}
		breadcrumbElement.appendChild(breadcrumbLink);
	}
}

function createXmlDocument() {
	if (typeof document.implementation.createDocument === "function")
		return document.implementation.createDocument("", "", null);
	if (typeof XMLDocument !== "undefined") {
		try {
			return new XMLDocument();
		}
		catch (e) { return null; }
	}
}

var XslTransform = function () {
	this._styleSheetUrl = null;
	this._sourceDocumentUrl = null;

	this._styleSheetReady = false;
	this._sourceDocumentReady = false;

	if (typeof (ActiveXObject) !== "undefined") {
		this._styleSheetLoader = new ActiveXObject("Msxml2.XMLHTTP");
		this._styleSheet = new ActiveXObject("Msxml2.FreeThreadedDOMDocument");

		this._template = new ActiveXObject("Msxml2.XSLTemplate");

		this._processor = null;

		this._sourceDocumentLoader = new ActiveXObject("Msxml2.XMLHTTP");
		this._sourceDocument = new ActiveXObject("Msxml2.DOMDocument");
	}
	else {
		this._styleSheetLoader = new XMLHttpRequest();
		this._styleSheet = createXmlDocument();

		this._template = null;

		this._processor = new XSLTProcessor();
		this._processor.addParameter = function (name, value, nameSpace) {
			this.setParameter(nameSpace || null, name, value);
		};

		this._sourceDocumentLoader = new XMLHttpRequest();
		this._sourceDocument = createXmlDocument();
	}
	this._styleSheet.async = false;
	this._sourceDocument.async = false;

	this._parameters = {};

	this.onTransformComplete = null;
};

XslTransform.prototype.setStyleSheetUrl = function (styleSheetUrl) {
	if (this.styleSheetUrl !== styleSheetUrl) {
		var self = this;
		this.styleSheetUrl = styleSheetUrl;
		this._styleSheetReady = false;

		this._styleSheetLoader.open(Http.Method.Get, styleSheetUrl, true);
		this._styleSheetLoader.onreadystatechange = function () {
			if (self._styleSheetLoader.readyState === Http.State.Done) {
				if (self._styleSheetLoader.status === 200) {
					if (self._styleSheetLoader.responseXML.documentElement === null) {
						self._styleSheet.load(self._styleSheetLoader.responseStream);
					}
					else {
						if (typeof self._styleSheet.load === "unknown") {
							self._styleSheet.load(self._styleSheetLoader.responseXML);
						}
						else {
							self._styleSheet = self._styleSheetLoader.responseXML;
						}
					}

					if (self._template) {
						self._template.stylesheet = self._styleSheet;
						self._processor = self._template.createProcessor();
						if (self._sourceDocumentReady) {
							self._processor.input = self._sourceDocument;
						}
					}
					else {
						self._processor.clearParameters();
						self._processor.importStylesheet(self._styleSheet);
					}

					for (name in self._parameters) {
						if (self._parameters.hasOwnProperty(name)) {
							self._processor.addParameter(name, self._parameters[name], undefined);
						}
					}

					self._styleSheetReady = true;

					self._update();
				}
			}
		};
		this._styleSheetLoader.send(null);
	}
};

XslTransform.prototype.setSourceDocumentUrl = function (sourceDocumentUrl) {
	if (this.sourceDocumentUrl !== sourceDocumentUrl) {
		var self = this;
		this.sourceDocumentUrl = sourceDocumentUrl;
		this._sourceDocumentReady = false;

		this._sourceDocumentLoader.open(Http.Method.Get, sourceDocumentUrl, true);
		this._sourceDocumentLoader.onreadystatechange = function () {
			if (self._sourceDocumentLoader.readyState === Http.State.Done) {
				if (self._sourceDocumentLoader.status === 200) {
					if (self._sourceDocumentLoader.responseXML.documentElement === null) {
						self._sourceDocument.load(self._styleSheetLoader.responseStream);
					}
					else {
						self._sourceDocument = self._sourceDocumentLoader.responseXML;
					}
					if (self._processor) {
						self._processor.input = self._sourceDocument;
					}

					self._sourceDocumentReady = true;

					self._update();
				}
			}
		};
		this._sourceDocumentLoader.send(null);
	}
};

XslTransform.prototype.setParameter = function (name, value) {
	this._parameters[name] = value;
	if (this._processor) {
		this._processor.addParameter(name, value);
		this._update();
	}
};

XslTransform.prototype.setParameters = function (params) {
	this._parameters = params;
	if (this._processor) {
		for (name in this._parameters) {
			if (this._parameters.hasOwnProperty(name)) {
				this._processor.addParameter(name, this._parameters[name]);
			}
		}
		this._update();
	}
};

XslTransform.prototype._update = function () {
	if (this._styleSheetReady && this._sourceDocumentReady) {
		if (this._processor.readyState === 2 || this._processor.transformToDocument) {
			var outputDocument;
			if (typeof (ActiveXObject) !== "undefined") {
				outputDocument = new ActiveXObject("Msxml2.DOMDocument");
				outputDocument.setProperty("SelectionLanguage", "XPath");
				this._processor.output = outputDocument;
				this._processor.transform();
			}
			else {
				outputDocument = this._processor.transformToDocument(this._processor.input);
			}
			if (typeof (this.onTransformComplete) === "function") {
				this.onTransformComplete(outputDocument.documentElement);
			}
		}
	}
};

var searchResultTransform;
function executeSearch(evt, searchText) {
	searchText = searchText || "";
	if (searchText.length !== 0) {
		if (!searchResultTransform) {
			searchResultTransform = new XslTransform();
			var pageUrl = location.href, idx;
			if ((idx = pageUrl.lastIndexOf("#")) !== -1) {
				pageUrl = pageUrl.substr(0, idx);
			}
			searchResultTransform.setParameter("publicationUrl", pageUrl);
			searchResultTransform.setParameter("noResultsText", "NoResultsText".localize());
			searchResultTransform.setStyleSheetUrl(appBaseUrl + "SearchResultsToXHTML.xslt");
		}
		searchResultWindow.setRelativeSize(0.5, 0.5);
		var elm = document.getElementById("topicSearch");
		if (elm) {
			var left = 0, top = elm.offsetHeight, offsetParent = searchResultWindow.offsetParent;
			do {
				left += elm.offsetLeft;
				top += elm.offsetTop;
			} while ((elm = elm.offsetParent) !== offsetParent && elm);
			searchResultWindow.setLocation(left, top);
		}
		else {
			searchResultWindow.center();
		}
		searchResultWindow.showModal();

		searchResultTransform.onTransformComplete = function (result) {
			var normalizedSearchText = result.selectSingleNode("input[@name='searchText']/@value");
			if (normalizedSearchText.value !== searchText) {
				var searchTextElement = document.getElementById("searchText");
				searchTextElement.value = normalizedSearchText.value;
			}

			var resultSize = parseInt(result.selectSingleNode("input[@name='resultSize']/@value").value, 10);
			var toolbarText = (resultSize === 1 ? "SingleResultText{0}" : "MultiResultText{0}").localize([resultSize]);
			searchResultWindow.toolbar.clear();
			searchResultWindow.toolbar.appendHtmlNode(document.createTextNode(toolbarText));

			var html = (new XMLSerializer()).serializeToString(result);
			searchResultWindow.content.setHtml(html);
		};

		var queryUrl = "Search.ashx?pubunid=" + encodeURIComponent(publicationUnid) +
			"&text=" + encodeURIComponent(searchText) + "&uq=" + encodeURIComponent(new Date().getTime().toString(16));
		searchResultTransform.setSourceDocumentUrl(appBaseUrl + queryUrl);
	}
}

function searchTextKeyPress(evt) {
	evt = evt || event;
	if (evt) {
		var target = evt.target || evt.srcElement;
		if (target && evt.keyCode === 13) {
			executeSearch(evt, target.value);
		}
	}
}

function searchButtonClick(evt) {
	evt = evt || event;
	var handled = false;
	var searchTextElement = document.getElementById("searchText");
	if (searchTextElement) {
		executeSearch(evt, searchTextElement.value);
		handled = true;
	}
	if (handled) {
		return stopEvent(evt);
	}
	return !handled;
}

function openThumbnail(evt, url) {
	evt = evt || event;
	window.open(url, "_blank");
}

function createWindows() {
	var mainElement;
	// Window.constructor(parent, id, className, title, properties)
	searchResultWindow = new Window(document.body, "searchResultWindow", "searchResult", "SearchResultsWindowTitle".localize(), { width: 600, height: 500, toolBarVisible: true });
	glossaryWindow = new Window(document.body, "glossaryWindow", "glossaryArea", "GlossaryWindowTitle".localize(), { width: 300, height: 300 });
}

function populateInformationPane() {
	if (informationPaneElement && typeof (additionalInformationPaneData) === "function") {
		var infoPaneData = {}, propElm;
		additionalInformationPaneData(infoPaneData);
		for (var name in infoPaneData) {
			if (infoPaneData.hasOwnProperty(name)) {
				propElm = document.createElement("div");
				propElm.className = "property";
				propElm.appendChild(para(name, "heading"));
				propElm.appendChild(para(infoPaneData[name], "data"));
				informationPaneElement.appendChild(propElm);
			}
		}
	}
}

function initialize() {
	headingElement = document.getElementById("topicHeading");
	contentElement = document.getElementById("topicContent");
	treeNavigationElement = document.getElementById("treeNavigation");
	publicationContainerElement = document.getElementById("publicationContainer");
	informationPaneElement = document.getElementById("informationPane");
	breadcrumbElement = document.getElementById("breadcrumbs");
	showToCToolElement = document.getElementById("showToCTool");
	tocControllerElement = document.getElementById("tocController");
	previousToolButton = document.getElementById("previousToolButton");
	nextToolButton = document.getElementById("nextToolButton");

	attachEventHandler(document.body, "click", hidePops);
	attachEventHandler(document.body, "resize", hidePops);

	placeBreadcrumbs();
	populateInformationPane();
	createWindows();

	var publicationTitleElement = document.getElementById("publicationTitle");
	publicationTitleElement.appendChild(document.createTextNode(publicationTitle));

	if (typeof (customInit) === "function") {
		customInit();
	}

	dhtmlHistory.initialize();
	dhtmlHistory.addListener(handleHistoryChange);
	var initialLocation = dhtmlHistory.getCurrentLocation();
	// if no location specified, use the default
	if (!initialLocation) {
		initialLocation = "";
	}
	// now initialize our starting UI
	updateUI(initialLocation, null);
}

attachEventHandler(window, "load", initialize);
