
function getDocument(node) {
	var myDoc = node;
	
	while (myDoc.parentNode != null) {
		myDoc = myDoc.parentNode;
	}
	
	return myDoc;
}

function discardElement(element) {
	if (!document.all) {
		var parent = element.parentNode;
		if (parent)
			parent.removeChild(element);
	}
	else {
		var elmDocument = getDocument(element);
		var garbageBin = elmDocument.getElementById('IELeakGarbageBin');
		if (!garbageBin) {
			garbageBin = elmDocument.createElement('DIV');
			garbageBin.id = 'IELeakGarbageBin';
			garbageBin.style.display = 'none';
			elmDocument.body.appendChild(garbageBin);
		}

		// move the element to the garbage bin
		garbageBin.appendChild(element);
		garbageBin.innerHTML = '';
	}
}

/*
 * Widens the document.domain as much as possible.  This is done to allow JavaScript from other servers to communicate
 * with Mutiny pages.
 *
 * For example: www.mutiny.com -> mutiny.com, demo.mutiny.com -> mutiny.com, www.google.co.uk -> google.co.uk
 */
function widenDomain() {
	var tokens = document.domain.split('.');
	if (tokens.length < 2) {
		return;
	}
	
	var lastT = tokens[tokens.length - 1];
	var preUT = tokens[tokens.length - 2];
	var cnt = tokens.length - 2;
	
	// Check if document.domain is actually an IP address
	if (isNaN(parseInt(lastT)) === false) {
		return;
	}
	// Check if we're dealing with a country domain (eg. *.co.fr)
	//   This only deals with certain obvious situations and should be improved.
	else if ((preUT === "co") || (preUT === "org") || (preUT === "gov")) {
		if (tokens.length < 3) {
			return;
		}
		else {
			cnt = tokens.length - 3;
		}
	}
	if (cnt < 0) {
		cnt = 0;
	}
	
	var wideDomain = tokens[cnt];
	for (var i=cnt + 1; i<tokens.length; i++) {
		wideDomain += '.' + tokens[i];
	}
	
	document.domain = wideDomain;
}


function resizePage() {
	var container = document.getElementById("windowContainer");
	resizeWindowContainer(container);
}

function resizeWindowContainer(container) {
	if (!container)
		return;
	
	$("div.window", container).each( function(i) {
		if (this.resizeContainer) {
			this.resizeContainer();
		}
	});
}

function resizeIconContainer(container) {
	if ((userRole!="mut_admin") || (container === undefined))
		return;
	
	$("div.icon", container).each( function(i) {
		if (this.resizeContainer) {
			this.resizeContainer();
		}
	});
}


function submitForm(number) {
	var submitForm;
	if (number)
		submitForm = document.forms[number];
	else
		submitForm = document.forms[0];

	if (submitForm!=null) {
		cancelRefreshTimer();
		submitForm.submit();
	}
}



function getRootWindow() {
	var topWindow = window;
	
	while (topWindow.parent != topWindow) {
		topWindow = topWindow.parent;
	}
	
	return topWindow;
}

function getTopWindow() {
	var topWindow = getRootWindow();
	
	if (!topWindow.addStatusWindowM) {
		var iframes = topWindow.document.getElementsByTagName("iframe");
		
		for (var i=0; i<iframes.length; i++) {
			var curr = iframes[i];
			
			var currObj;
			if (curr.contentWindow)
				currObj = curr.contentWindow;
			else if (curr.contentDocument)
				currObj = curr.contentDocument.defaultView;
			
			if (currObj) {
				try {
					if (currObj.addStatusWindowM)
						return currObj;
				}
				catch(err) {
					// Can't access iframe contents; carry on to next
				}
			}
		}
	}

	return topWindow;
}


loggingOut = false;

function logoff() {
	loggingOut = true;
	getRootWindow().document.location = "logoff.do";
}


var timeoutLength = 30000;
var adminTimeoutLength = 60000;
//var volatileTimeoutLength = 5000;
var timerID;

function startRefreshTimer(volatileData) {
	//## AWD: Temp. disabled refresh to speed up development
	//return;

	if ((volatileData != null) && (volatileData == true)) {
		if (userRole!="mut_admin") {
			// Only start a refresh timer when we are sure that the user can't edit any data.
			refreshCountdown = 1;
			timerID = setTimeout( doRefreshTimeout, timeoutLength);
		}

		return;
	}
	
	refreshCountdown = 1;

	if (userRole=="mut_admin")
		timerID = setTimeout( doRefreshTimeout, adminTimeoutLength);
	else
		timerID = setTimeout( doRefreshTimeout, timeoutLength);
}


function cancelRefreshTimer() {
	if (timerID != null)
		clearTimeout(timerID);
}

var refreshCountdown = -1;

function isPageRefreshEnabled() {
	return (refreshCountdown >= 0);
}

function enablePageRefresh() {
	if (userRole != "mut_admin")
		refreshCountdown = 6;
	else
		refreshCountdown = 12;
}

function doRefreshTimeout() {
	if (refreshCountdown > 1) {
		refreshCountdown--;
	}
	else if (refreshCountdown == 1) {
		enablePageRefresh();
		document.location.reload(false);
	}

	/*if (refreshCountdown > 0) {
		refreshCountdown--;

		if (refreshCountdown == 0) {
			enablePageRefresh();
			document.location.reload(true);
		}
	}*/

	/*if (containsVolatileWindow(windowContainer)) {
		timerID = setTimeout( doRefreshTimeout, volatileTimeoutLength);
	}
	else {
		document.location.reload();
	}*/
}



clearCurrentViewPositions = false;

function autoArrangeLayout() {
	if (userRole!="mut_admin")
		return;

	if (document.getElementById('iconContainer') == null)
		return;

	var arrangeConfirmed = confirm('Auto-Arranging this view will completely remove the\nicon positioning for this view for all users.\n\nAre you sure that you want to auto-arrange this view?');

	if (!arrangeConfirmed)
		return;


	var saveLayoutForm;
	var positions;

	for (var i=0; i<document.forms.length; i++) {
		if (document.forms[i].name=="saveLayoutForm") {
			saveLayoutForm = document.forms[i];
			break;
		}
	}

	if (!saveLayoutForm)
		return;

	var positions;
	for (var i=0; i<saveLayoutForm.elements.length; i++) {
		if (saveLayoutForm.elements[i].name=="positions") {
			positions = saveLayoutForm.elements[i];
			break;
		}
	}

	if (!positions)
		return;

	positions.value = "auto_arrange";
	clearCurrentViewPositions = true;

	saveLayoutForm.submit();
}



function saveLayout() {
	var iconContainerElement = document.getElementById('iconContainer');
	
	if (userRole!="mut_admin")
		return;


	if (!iconContainerElement)
		return;

	var saveConfirmed = confirm('Saving this layout will change the layout for this view for all users.\n\nAre you sure that you want to save this layout?');

	if (!saveConfirmed)
		return;


	var saveLayoutForm;
	var positions;

	for (var i=0; i<document.forms.length; i++) {
		if (document.forms[i].name=="saveLayoutForm") {
			saveLayoutForm = document.forms[i];
			break;
		}
	}

	if (!saveLayoutForm)
		return;

	var positions;
	for (var i=0; i<saveLayoutForm.elements.length; i++) {
		if (saveLayoutForm.elements[i].name=="positions") {
			positions = saveLayoutForm.elements[i];
			break;
		}
	}

	if (!positions)
		return;

	//## AWD: Saving position of all icons means that the saved layout is consistent
	//        before and after save.
	//        However you do also lose some of benefits of the automatic positioning.
	var positionsStr = "";
	$("div.icon", iconContainerElement).each( function(i) {
		positionsStr += this.id + ":" + this.offsetTop + ":" + this.offsetLeft + ":" + this.style.zIndex + "/";
	});

/*
	// ## AWD: Simple code to test maximum number of positions that can be submitted at
	//         once.  Its at least 1000.
	//         Therefore I would guess that the web interface would break down first.
	for (var i=0; i<1000; i++) {
		positionsStr += "dsjfkldsajlkaassddq:100:100:1/"
	}
*/


	positions.value = positionsStr;
	clearCurrentViewPositions = true;

	saveLayoutForm.submit();
}


/*
function changeCustomView() {
	var mainViewForm;

	for (var i=0; i<document.forms.length; i++) {
		if (document.forms[i].name=="mainViewForm") {
			mainViewForm = document.forms[i];
			break;
		}
	}

	if (!mainViewForm)
		return;

	mainViewForm.submit();
}
*/
