var g_closeTabURL = "/NexusAdapter/nexus-close-tab";
var g_openTabURL = "/NexusAdapter/nexus-open-tab";

function getNexusHost()
{
	var cookie = document.cookie;
	var index = cookie.indexOf("NexusSessionHost=");
	var nexusHost = null;
	
	if (index >= 0)
	{
		var pos = cookie.indexOf(";", index);
		
		if (pos < 0)
		{
			pos = cookie.length;
		}
		
		nexusHost = cookie.substring(index + 17, pos)
	}
	return unescape(nexusHost);	
}

function createFrame()
{
	var iframeNode = document.getElementById("nexus_frame");
	
	if (iframeNode == null)
	{
		var bodyNodeList = document.getElementsByTagName("body");
		
		iframeNode = document.createElement("iframe");
		iframeNode.setAttribute("id", "nexus_frame");
		iframeNode.setAttribute("width", "0");
		iframeNode.setAttribute("height", "0");
		iframeNode.setAttribute("style", "position:absolute; visibility:hidden;");
		if (bodyNodeList != null)
		{			
			bodyNodeList[0].appendChild(iframeNode);
		}
		else
		{
			alert("Malformed HTML");
			bodyNodeList = document.getElementsByTagName("html");
			if (bodyNodeList != null)
			{			
				bodyNodeList[0].appendChild(iframeNode);
			}
			else
			{
				alert("Really malformed HTML");
				document.appendChild(iframeNode);
			}
		}
	}
	return iframeNode;

}

function closeNexusTab(_frameName)
{
	var nexusHost = getNexusHost();
	var iframeNode = null;
	
	if (nexusHost != null)
	{
		iframeNode = createFrame();
		if (iframeNode != null)
		{
			var frameURL = nexusHost + g_closeTabURL;
			
			if ((_frameName != null) && (_frameName.length > 0))
			{
				frameURL += "?frame_id=" + escape(_frameName);
			}
	
			iframeNode.src = frameURL;
		}
	}
	else
	{
		alert("The Nexus Server is currently unavailable. Please try again later.");
	}
}


function openNexusTab(_frameName, _targetURL, _hint, _imageIndex)
{
	var nexusHost = getNexusHost();
	var iframeNode = null;
	
	if (nexusHost != null)
	{
		if ((_frameName == null) || (_frameName.length == 0))
		{
			alert("ID for new frame cannot be empty");
			return;
		}
		
		if ((_targetURL == null) || (_targetURL.length == 0))
		{
			alert("URL for new frame cannot be empty");
			return;
		}
	
		iframeNode = createFrame();
		if (iframeNode != null)
		{
			var frameURL = nexusHost + g_openTabURL;
			
			if (_frameName != null)
			{
				frameURL += "?frame_id=" + escape(_frameName) + 
					"&target_url=" + escape(_targetURL);
					
				if ((_hint != null) && (_hint.length > 0))
				{
					frameURL += "&hint_tx=" + escape(_hint);
				}
				
				if ((_imageIndex != null) && (_imageIndex.length > 0))
				{
					frameURL += "&image_id=" + escape(_imageIndex);
				}
	
				if ((_hint != null) && (_hint.length > 0))
				{
					frameURL += "&hint_tx=" + escape(_hint);
				}
			}
			iframeNode.src = frameURL;
		}
	}
	else
	{
		alert("The Nexus Server is currently unavailable. Please try again later.");
	}
}
