// This function should be called when we now that our postback will not cause
// a page refresh (like in the cases where we download a file by postback).
function __clearPostBack() {
	theForm.__EVENTTARGET.value = '';
	theForm.__EVENTARGUMENT.value = '';
}

function GetCredentials(userElementID, passElementID, /*function*/okHandler, /*function*/cancelHandler) {
	if (!_supportsModalDialog) {
		// GetCredentials requires the usage of dialogArguments, so IE, or a browser with proper support of modal dialogs is required.
		alert("This function is not supported by your browser");
		return false;
	}
	var uname = document.getElementById(userElementID);
	var pass = document.getElementById(passElementID);
	SpawnDialog('credentials.htm', { userField: uname, passField: pass }, 400, 200, function (r) {
		if (r) { if (typeof okHandler == 'function') okHandler(); }
		else if (typeof cancelHandler == 'function') cancelHandler();
	});
	return false;
}
function GetFormElement(NamePart) {
	var elm = theForm.elements;
	for (i = 0; i < elm.length; i++) {
		var eid = elm[i].id;
		if (eid.indexOf(NamePart) >= 0)
			return elm[i];
	}
	return null;
}
function CheckTab(el) {
	if (document.all && 9 == event.keyCode && event.ctrlKey) {
		// Cache the selection
		el.selection = document.selection.createRange();
		setTimeout("ProcessTab('" + el.id + "')", 0);
	}
}
function ProcessTab(id) {
	// Insert tab character in place of cached selection
	document.all[id].selection.text = String.fromCharCode(9);
	document.all[id].focus();
}
function SetEventTarget(evt, postbackRef) {
	if (!evt) evt = event;
	if ((evt.keyCode && evt.keyCode == 13) /*IE*/ || (evt.which && evt.which == 13) /*FF*/)	// ENTER is hit
	{
		eval(postbackRef);
		return false; // This cancels the event and prevents weird sounds coming from IE when Enter is hit.
	}
}
var _runsIEonXPSP2 = (window.navigator.userAgent.indexOf("SV1") != -1) ? true : false;
var _ie6 = typeof document.body.style.maxHeight == "undefined";

// Chrome, IE, Firefox (>= 3) and Safari support showModalDialog, but only in IE and Safari works as expected.
// In Chrome the underlying page is accessible (showModalDialog works much like window.open, http://code.google.com/p/chromium/issues/detail?id=4202),
// and in Firefox there is at least one related bug (https://bugzilla.mozilla.org/show_bug.cgi?id=452310).
// The problem with safari is that, as it turns out after testing, it does not spawn modalpopups that are fired from a setTimeout so it is
// not compatible with our handling. This might be due to the Safari popup blocker (http://www.webmaster-talk.com/javascript-forum/105303-about-window-open-in-safari.html).
// So only IE can handle modal popups without any problems.
var _supportsModalDialog = /MSIE/.test(navigator.userAgent); // Reversed _supportsModalDialog meaning (restored logical meaning).

var MDArgs = null;
var MDPage = '';
var MDWidth = 0;
var MDHeight = 0;
function ShowModalDialog(page, args, w, h) {
	if (_runsIEonXPSP2) h += 25;
	MDArgs = { value: args, opener: window };
	MDPage = page;
	MDWidth = w;
	MDHeight = h;
	setTimeout("ShowModalDialogWithTimeout()", 1);
}

function ShowModalDialogWithTimeout() {
	var ret = window.showModalDialog(MDPage, MDArgs, "dialogHeight:" + MDHeight + "px;dialogWidth:" + MDWidth + "px;help:no;scroll:yes;status:no;resizable:yes;");
	//if an event is registered on the page to run after the dialog is closed, execute the event 
	if (ret && typeof (OnDialogClosed) == 'function')
		OnDialogClosed();
	return true;
}

function ShowModalDialogWithoutTimeout(page, args, w, h) {
	if (_ie6) h += 25;
	return window.showModalDialog(page, { value: args, opener: window }, "dialogHeight:" + h + "px;dialogWidth:" + w + "px;help:no;scroll:yes;status:no;resizable:yes;");
}

function ShowBoolModalDialogWithoutTimeout(page, args, w, h) {
	if (_ie6) h += 25;
	if (window.showModalDialog(page, { value: args, opener: window }, "dialogHeight:" + h + "px;dialogWidth:" + w + "px;help:no;scroll:yes;status:no;resizable:yes;"))
		return true;
	else
		return false;
}

// Copied from the AJAX Control Toolkit.
function GetClientBounds() {
	/// <summary>
	/// Gets the width and height of the browser client window (excluding scrollbars)
	/// </summary>
	/// <returns type="Sys.UI.Bounds">
	/// Browser's client width and height
	/// </returns>
	var clientWidth;
	var clientHeight;
	switch (Sys.Browser.agent) {
		case Sys.Browser.InternetExplorer:
			clientWidth = document.documentElement.clientWidth;
			clientHeight = document.documentElement.clientHeight;
			break;
		case Sys.Browser.Safari:
			clientWidth = window.innerWidth;
			clientHeight = window.innerHeight;
			break;
		case Sys.Browser.Opera:
			clientWidth = Math.min(window.innerWidth, document.body.clientWidth);
			clientHeight = Math.min(window.innerHeight, document.body.clientHeight);
			break;
		default:  // Sys.Browser.Firefox, etc.
			clientWidth = Math.min(window.innerWidth, document.documentElement.clientWidth);
			clientHeight = Math.min(window.innerHeight, document.documentElement.clientHeight);
			break;
	}
	return new Sys.UI.Bounds(0, 0, clientWidth, clientHeight);
}

// Shows a modal dialog and executes a handler after it is closed.
// page: the url of the page to open in the new window.
// args: the arguments to the dialog, will be available as window.dialogArguments.value to the child window.
// w: The width (in pixels) of the new window.
// h: The height (in pixels) of the new window.
// afterCloseHandler: The function to call after the popup is closed. It will be called as afterCloseHandler(returnValue, afterCloseParams).
// afterCloseParams: A parameter to be passed to the afterCloseHandler.
function SpawnDialog(page, args, w, h, afterCloseHandler, afterCloseParams) {
	if (!h) h = 200;
	if (!w) w = 500;
	this._afterCloseHandler = afterCloseHandler;
	this._afterCloseParams = afterCloseParams;

	// dialogArguments is not a good place to store page GET parameters when our pages have to be viewed across multiple browsers. 
	// Browsers assign dialogArguments inconsistently.
	page = page + '?' + args;
	page = page.replace(/\?$/g, ''); // Remove trailing "?"

	// If there is no showModalDialog support, use window.open() instead.
	if (!_supportsModalDialog)
		_emulateShowModalDialog(page, args, w, h);
	else
		_showModalDialog(page, args, w, h);
	return false;
}

function _showModalDialog(page, args, w, h) {
	this._popupSpawner = function () {
		// We have modal dialog support.
		var dialogResult = ShowModalDialogWithoutTimeout(page, args, w, h);
		// Call the afterCloseHandler.
		if (typeof this._afterCloseHandler != 'undefined')
			this._afterCloseHandler(dialogResult, this._afterCloseParams);
	};
	setTimeout(this._popupSpawner, 0);
	return false;
}

function _emulateShowModalDialog(page, args, w, h) {
	this._tagsWithTabIndex = Array('A', 'AREA', 'BUTTON', 'INPUT', 'OBJECT', 'SELECT', 'TEXTAREA', 'IFRAME');
	this._disableTabs = function () {
		var tagElements;
		this._saveTabIndexes = new Array();
		var k = 0;
		for (var i = 0; i < this._tagsWithTabIndex.length; i++) {
			tagElements = document.getElementsByTagName(this._tagsWithTabIndex[i]);
			for (var j = 0; j < tagElements.length; j++, k++) {
				this._saveTabIndexes[k] = { tag: tagElements[j], index: tagElements[j].tabIndex };
				tagElements[j].tabIndex = "-1";
			}
		}
	};
	this._enableTabs = function () {
		for (var i = 0; i < this._saveTabIndexes.length; i++)
			this._saveTabIndexes[i].tag.tabIndex = this._saveTabIndexes[i].index;
	};

	if (_ie6) h += 25;
	if (!this._popup) {
		this._resizeHandler = function () {
			var scrollLeft = (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft);
			var scrollTop = (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);
			var clientBounds = GetClientBounds();
			var clientWidth = clientBounds.width;
			var clientHeight = clientBounds.height;
			this._cover.style.width = Math.max(Math.max(document.documentElement.scrollWidth, document.body.scrollWidth), clientWidth) + 'px';
			this._cover.style.height = Math.max(Math.max(document.documentElement.scrollHeight, document.body.scrollHeight), clientHeight) + 'px';
		}
		// Create a protective layer that won't allow interaction with the page while the popup is shown (code based on the ModalPopupExtender behavior).
		if (!this._cover)
			this._cover = document.createElement('div');
		this._cover.style.position = 'absolute';
		this._cover.style.left = '0px';
		this._cover.style.top = '0px';
		this._cover.style.display = 'none';
		this._cover.style.visibility = 'hidden';
		$addHandler(window, 'resize', this._resizeHandler);
		this._cover.style.zIndex = 10000;
		document.body.appendChild(this._cover);
		this._cover.style.display = 'block';
		this._cover.style.visibility = 'visible';
		this._resizeHandler();
		this._disableTabs();
		this._cleanup = function () {
			if (this._popup.closed) {
				// Stop the timer.
				this._interval = clearInterval(this._interval);
				// Remove the covering div.
				$removeHandler(window, 'resize', this._resizeHandler);
				this._cover.style.visibility = 'hidden';
				this._cover.style.display = 'none';
				this._cover.parentNode.removeChild(this._cover);
				this._enableTabs();
				// Call the afterCloseHandler.
				if (typeof this._afterCloseHandler != 'undefined')
					this._afterCloseHandler(this._returnValue, this._afterCloseParams);
				this._popup = null;
			}
		};
		// Open the window.
		var top = (screen.height - h) / 2;
		var left = (screen.width - w) / 2;
		// Create a number that represents the popup nesting level (to support popups from popups).
		var nestlevel = 0;
		var win = window.top;
		while (win.dialogArguments && win.dialogArguments.opener) {
			nestlevel++;
			win = win.dialogArguments.opener;
		}
		this._popup = window.open(null, 'popup' + nestlevel, "height=" + h + ",width=" + w + ",left=" + left + ",top=" + top + ",help=no,scroll=auto,status=no,resizable=yes,replace=yes");
		this._popup.dialogArguments = { value: args, opener: window };
		// Arrange for polling of the window status. Once it is closed, we need to remove the top layer and run afterCloseHandler.
		this._interval = setInterval(this._cleanup, 200);

		// Open the page inside the new window.
		this._popup.location.replace(page);
	}
}

// Closes the current window and sets its returnValue.
function CloseDialog(returnValue) {
	if (!_supportsModalDialog) // We were opened as a window, set the value in the opener, as closing the window will discard it.
		top.opener._returnValue = returnValue;
	else
		top.returnValue = returnValue;
	top.close();
	// We must not return anything. If we do, there will be problems with onbeforeunload handlers and frames in FireFox.
}

function ShowMessageWithoutTimeout(msg) {
	alert(msg);
}

function ShowMessage(msg) {
	var strFn = "alert('" + msg + "')";
	if (msg != null && (msg != ""))
		setTimeout(strFn, 1);
}
//-------------------------------------------------------------
// Select all the checkboxes (Hotmail style) in the DataGrid
//-------------------------------------------------------------
function SelectAllCheckboxes(theBox) {

	var xState = theBox.checked;

	var elm = theBox.form.elements;
	//Find the last occurance of "_"
	var cLen = theBox.id.lastIndexOf("_");
	var containerID = theBox.id.substring(0, cLen);
	//redo the above to find the next last occurance of "_".
	cLen = containerID.lastIndexOf("_");
	//This should return the grid id.
	containerID = theBox.id.substring(0, cLen);

	for (i = 0; i < elm.length; i++) {
		var elmContainerID = elm[i].id.substring(0, cLen);
		if (elm[i].type == "checkbox" && elm[i].id != theBox.id && elmContainerID == containerID) {
			//elm[i].click();
			if (elm[i].checked != xState) {
				elm[i].checked = xState;
				HighlightRow(elm[i]);
			}
			//elm[i].checked=xState;
		}
	}
}

function UpdateSelectAllCheckedState(chkB) {
	var allTrue = true;
	var containerID = chkB.parentNode.parentNode.parentNode.parentNode.id; // checkbox.td.tr.tbody.table
	var elmSelectAll = null;
	var elms = chkB.form.elements;
	for (i = 0; i < elms.length; i++) {
		var elm = elms[i];
		if (elm.id.substring(0, containerID.length) != containerID)
			continue;

		if (elm.id.indexOf('SelectAll') > -1) {
			elmSelectAll = elm;
			continue;
		}

		if (elm.type == "checkbox" && !elm.checked) {
			allTrue = false;
			break;
		}
	}

	elmSelectAll.checked = allTrue;
}

function HighlightRow(chkB) {

	xState = chkB.checked;
	if (xState)
		chkB.parentNode.parentNode.style.backgroundColor = 'lightgrey';
	else
		chkB.parentNode.parentNode.style.backgroundColor = 'white';
}

function OpenMemberSections(mode, memberID, postbackReference) {
	return SpawnDialog('membersections.htm', 'mode=' + mode + '&id=' + memberID, 800, 600, function (returnValue, args) {
		returnValue && eval(args);
	}, postbackReference);
}

function OpenSectionAccounts(sectionID, postbackRef) {
	return SpawnDialog('sectionaccounts.htm', 'id=' + sectionID, 800, 600, function (result, args) { result && eval(args); }, postbackRef);
}

function OpenSectionWorkLists(sectionID, postbackRef) {
	return SpawnDialog('sectionworklists.htm', 'id=' + sectionID, 800, 600, function (result, args) { result && eval(args); }, postbackRef);
}

function OpenMemberProcedures(mode, memberID, postbackRef) {
	return SpawnDialog('memberprocedures.htm', 'mode=' + mode + '&id=' + memberID, 770, 710, function (result, args) { result && eval(args); }, postbackRef);
}

// Sets/resets the checked state of all checkboxes inside the container identified by the given container id.
function SetCheckboxes(formId, containerId, checkedState) {
	var form = document.getElementById(formId);
	var elements = form.elements;
	for (var i = 0; i < elements.length; i++) {
		var e = elements[i];
		if (e.type == "checkbox" && e.id.indexOf(containerId) == 0) {
			if (e.checked != checkedState)
				e.click();
		}
	}
}

function HighLightChecked(formId, containerId, highlighter) {
	var form = document.getElementById(formId);
	var elements = form.elements;
	for (var i = 0; i < elements.length; i++) {
		var e = elements[i];
		if ((e.type == "checkbox" || e.type == "radio") && e.id.indexOf(containerId) == 0) {
			if (e.checked == true)
				eval(highlighter);
		}
	}
}

function OpenWebHelp(root, title) {
	var location = root + "/help/Admin_Portal_Help.htm#" + title;
	var winWebHelp = window.open(location, "wcWebHelp", "width=950,height=650,menubar=0,toolbar=0,status=0,location=0,resizable=1,scrollbars=1");
	winWebHelp.location.reload();
	winWebHelp.location.href = location;
	winWebHelp.focus();
}

// Enables/Disables a link.
// (See http://geekswithblogs.net/timh/archive/2006/01/19/66396.aspx)
function DisableAnchor(anchorNode, disable) {
	DisableAnchor(anchorNode, disable, false);
}
function DisableAnchor(anchorNode, disabled, keepHref) {
	if (disabled) {
		anchorNode.enabledState = { onclick: anchorNode.onclick, href: anchorNode.href };
		anchorNode.onclick = 'javascript:void(0);';
		// If we want the disabled anchor to do postback, we must keep the href.
		// This is the case in importautotext.aspx
		if (!keepHref)
			anchorNode.removeAttribute('href');
		anchorNode.setAttribute('disabled', 'disabled');
	}
	else if (anchorNode.enabledState !== undefined) {
		var es = anchorNode.enabledState;
		anchorNode.onclick = es.onclick;
		if (es.href !== undefined)
			anchorNode.setAttribute('href', es.href);
		anchorNode.enabledState = undefined;
		anchorNode.removeAttribute('disabled');
	}
}

function trim(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g, "");
}

var _openReportPreviewByOrderIDWindow;
function OpenReportPreview(orderID) {
	var location = "../admin/reportpreview.aspx?oid=" + orderID;
	if (null != _openReportPreviewByOrderIDWindow && false == _openReportPreviewByOrderIDWindow.closed) {
		_openReportPreviewByOrderIDWindow.focus();
		_openReportPreviewByOrderIDWindow.location = location;

	}
	else
		_openReportPreviewByOrderIDWindow = window.open(location, "wcAccession", "width=950,height=700,menubar=0,toolbar=0,status=0,location=0,resizable=1,scrollbars=1");

	return _openReportPreviewByOrderIDWindow;
}

var _openReportPreviewByReportIDWindow;
function OpenReportPreviewByReportID(reportID) {
	var location = "reportpreview.aspx?rid=" + reportID;
	if (null != _openReportPreviewByReportIDWindow && false == _openReportPreviewByReportIDWindow.closed) {

		_openReportPreviewByReportIDWindow.location = location;
		_openReportPreviewByReportIDWindow.focus();
	}
	else
		_openReportPreviewByReportIDWindow = window.open(location, "wcEvents", "width=850,height=700,menubar=0,toolbar=0,status=0,location=0,resizable=1,scrollbars=1");

	return _openReportPreviewByReportIDWindow;
}

var Portal = function () {
	this.initialize();
};

Portal.prototype = {
	_isIE6: typeof document.body.style.maxHeight == "undefined",

	initialize: function () {
		// Nothing to do here for the moment.
		_self = this;
	},

	// http://weblogs.asp.net/asmith/archive/2003/09/10/27063.aspx
	disableElement: function (element, alternateText) {
		if (element == undefined || element == null)
			return;

		// For buttons, this is enought.
		element.setAttribute('disabled', 'disabled');
		element.enabledState = {};

		switch (element.nodeName) {
			case 'A':
				// For links disabling the link is not enough. The __doPostBack() method
				// is stored in the href so we must prevent the href from executing.
				element.enabledState.onclick = element.onclick;
				element.onclick = function () { return false; };
				if (alternateText != undefined && alternateText != null) {
					element.enabledState.originalText = element.innerHTML;
					element.innerHTML = alternateText;
				}

				if (this._isIE6) {
					// IE6 work arround.
					element.style.cursor = 'text';
					element.style.textDecoration = 'none';
				}
				break;
			case 'INPUT':
				if (alternateText != undefined && alternateText != null) {
					element.enabledState.originalText = element.value;
					element.value = alternateText;
				}
				break;
		}
	},

	enableElement: function (element) {
		if (element == undefined || element == null)
			return;

		element.removeAttribute('disabled');
		var state = element.enabledState;
		if (!state)
			return;

		switch (element.nodeName) {
			case 'A':
				element.onclick = state.onclick;
				if (state.originalText != undefined)
					element.innerHTML = state.originalText;
				if (this._isIE6) {
					// IE6 work arround.
					element.style.cursor = 'text';
					element.style.textDecoration = 'none';
				}
				break;
			case 'INPUT':
				if (state.originalText != undefined)
					element.value = state.originalText;
				break;
		}

		element.enabledState = undefined;
	},

	setEnabled: function (element, enabled) {
		if (element == undefined || element == null)
			return;
		if (enabled)
			_self.enableElement(element);
		else
			_self.disableElement(element);
	},

	// Until we can use jQuery..
	getElementsByClassName: function (classname, node) {
		if (!node) node = document.getElementsByTagName("body")[0];
		var a = [];
		var re = new RegExp('\\b' + classname + '\\b');
		var els = node.getElementsByTagName("*");
		for (var i = 0, j = els.length; i < j; i++)
			if (re.test(els[i].className)) a.push(els[i]);
		return a;
	}
};

var portal = new Portal();

