// Create a cookie to keep track of all the open child browser windows.
// The cookie contains a list of window names that we update as we
// open and close windows. Using these window names, we can get a handle
// to each window when we want to close them, i.e. on logout.
function setOpenWindowsCookie(value) {
	document.cookie = "openWindows=" + escape(value);
}
function addToOpenWindowsCookie(valueToAdd) {
	var value = getOpenWindowsCookie();
	if (value != undefined) {
		value += valueToAdd + ",";
	} else {
		value = valueToAdd + ",";
	}
	setOpenWindowsCookie(value);
}
function getOpenWindowsCookie() {
	if (document.cookie.length > 0)	{ // if there are any cookies
		var search = "openWindows=";
		var offset = document.cookie.indexOf(search);
		if (offset != -1) { // if cookie exists 
			offset += search.length;
			var end = document.cookie.indexOf(";", offset);
			if (end != -1) {
				return (unescape)(document.cookie.substring(offset, end));
			}
		}
	}
}
function addOpenWindow() {
	var existingWindows = getOpenWindowsCookie();
	if (existingWindows == undefined) {
		addToOpenWindowsCookie(100);
		return 100;
	}
	for(i=100;i<199;i++) {
		if (existingWindows.indexOf(i) == -1) {
			addToOpenWindowsCookie(i);
			return i;
		}
	}
}
function removeOpenWindow(name) {
	var openWindows = getOpenWindowsCookie();
	if (openWindows != undefined) {
		var start = openWindows.indexOf(name + ",");
		if (start == -1) {
		} else if (start == 0) {
			setOpenWindowsCookie(openWindows.substring(4, openWindows.length));
		} else if (start+3 == openWindows.length) {
			setOpenWindowsCookie(openWindows.substring(0, start));
		} else {
			var substr1 = openWindows.substring(0, start);
			var substr2 = openWindows.substring(start+4, openWindows.length);
			setOpenWindowsCookie(substr1+substr2);
		}
	}
}
function closeOpenWindows() {
	var openWindows = getOpenWindowsCookie();
	while(openWindows != undefined && openWindows.length > 2) {
		var windowName = openWindows.substring(0, 3);
		var windowHandle = window.open('', windowName);
		windowHandle.close();
		removeOpenWindow(windowName);
		openWindows = getOpenWindowsCookie();
	}
}