// copyright 2010 by eostudios.com, contact for licensing info
// programmed by John Buckner
//
// Custom dropdowns
var MenuTimerID = Array();

// fix for firefox and back button, 
window.onload = HideAllSubmenusIfNoMouseover; 
window.onunload = function(){}; // FF ignores onload unless onunload is also there

var MenuHideTimeout;
var CurMouseOverId = "";
var DropDownMenus = new Object;
var InternetExplorerVersion = getInternetExplorerVersion();

///////////////////////////////////////////
function setupMainNav(_Params)
{
	if (_Params.navId == undefined || _Params.tabClass == undefined || _Params.menuDivClass == undefined || _Params.subMenusDivClass == undefined)
		alert('Popup Menu Error: setupMainNav(..) - You must pass an object with navId, tabClass, menuDivClass, and subMenusDivClass parameters');
	
	NavDiv = document.getElementById(_Params.navId);

	recursiveSetupMainNav(NavDiv, _Params.tabClass, _Params.menuDivClass, _Params.subMenusDivClass);
}

///////////////////////////////////////////
function recursiveSetupMainNav(_Node, _TabClass, _MenuDivClass, _SubmenuDivClass)
{
	var childNodes = _Node.childNodes;              
	var prevAnchorNode;
	
  for (var i=0; i < childNodes.length; i++)
  {
		// if last childNode was an anchor tag, save it as the prev anchor node
		if (childNode != undefined && childNode.tagName != undefined && childNode.tagName.toLowerCase() == "a")
			prevAnchorNode = childNode;
			
    var childNode = childNodes[i];

		if (childNode.className != undefined && childNode.className != "")
		{
			// split className up by spaces and loop through each
			var ClassNames = childNode.className.split(" ");

			for (var cn=0; cn < ClassNames.length; cn++)
			{
				if ((ClassNames[cn] == _MenuDivClass || ClassNames[cn] == _SubmenuDivClass) && prevAnchorNode != undefined)
				{	
					if (prevAnchorNode.id == undefined || strtrim(prevAnchorNode.id) == "")
						alert('Popup Menu Error: you must give an id for each anchor link that has a submenu (missing parent id for submenu '+childNode.id+')');
					else if (childNode.id == undefined || strtrim(childNode.id) == "")
						alert('Popup Menu Error: you must give an id for each div that is a submenu.');
					else
					{						
						var childNodeId = childNode.id;
						var prevAnchorId = prevAnchorNode.id;
												
						DropDownMenus[childNodeId] = new Object;
							
						DropDownMenus[childNodeId]["parentAnchorId"] = prevAnchorId;
						DropDownMenus[childNodeId]["parentMenuId"] = _Node.id;
						var isSubMenu = false;
						if (ClassNames[cn] == _SubmenuDivClass)
							isSubMenu = true;
						DropDownMenus[childNodeId]["isSubMenu"] = isSubMenu;
						
						// add arrow class to anchor that has submenu, as long as _TabClass not present
						if ( ! in_array(_TabClass, prevAnchorNode.className.split(" ")))
							prevAnchorNode.className += (prevAnchorNode.className ? " " : "") + "tab_submenu_arrow";

						// setup mouse events 
						prevAnchorNode.mouse_event_param = childNodeId;
						prevAnchorNode.onmouseover = function(){ShowSubMenu(this.mouse_event_param)};
						prevAnchorNode.onmouseout = function(){OffSubMenu(this.mouse_event_param)};
						childNode.mouse_event_param = childNodeId;
						childNode.onmouseover = function(){ShowSubMenu(this.mouse_event_param)};
						childNode.onmouseout = function(){OffSubMenu(this.mouse_event_param)};
					}
				}
			}
		}
		
  	recursiveSetupMainNav(childNode, _TabClass, _MenuDivClass, _SubmenuDivClass);
  }
}

///////////////////////////////////////////
function ShowSubMenu(_id)
{
	// bubble up fix
	if (CurMouseOverId != "")
	{
		return;
	}
	
	clearTimeout(MenuHideTimeout);
			
	CurMouseOverId = _id;

	var nodeData = DropDownMenus[_id];
	var nodeParentId = nodeData.parentAnchorId;
	var nodeParentDivId = nodeData.parentMenuId;
	var isNodeSubmenu = nodeData.isSubMenu;
	isParentDivSubmenu = false;
	if (DropDownMenus[nodeParentDivId] != undefined)
		var isParentDivSubmenu = DropDownMenus[nodeParentDivId].isSubMenu;

	if (nodeData == undefined)
		alert("Popup Menu Error: can't show submenu "+_id+" because its not setup correctly" );

	// make array of all id's that should be displayed, node to parent
	DisplayIds = new Array(_id);
		
	// diplay all node's parents
	curNodeData = nodeData;
	var parentId;
	while ((parentMenuId = curNodeData.parentMenuId) != undefined)
	{
		if (strtrim(parentMenuId) == "")
			break;
		DisplayIds.push(parentMenuId);
		curNodeData = DropDownMenus[parentMenuId];
	}
	
	// go through all menu id's, display those needed and hide all others
	ShowHideMenus(DisplayIds);

	// offset the left & top from parent
	if (nodeParentId == undefined)
		return;

	ParentTag = document.getElementById(nodeParentId);
	if (isNodeSubmenu && ParentTag != null)
	{
		Submenu = document.getElementById(_id);
		
		if (isParentDivSubmenu)
		{
			var Offset = -2;
			
			if (InternetExplorerVersion >= 8)
				Offset -= 1;
		}
		else
		{
			var Offset = 1;
			if (InternetExplorerVersion < 8 && InternetExplorerVersion > 0)
				Offset -= 1;
			if (InternetExplorerVersion >= 8)
				Offset -= 2;			
		}
		
		Submenu.style.top = (ParentTag.offsetTop + Offset)+"px";
	}
}

///////////////////////////////////////////
function ShowHideMenus(_DisplayIds)
{
	if (_DisplayIds == undefined)
		_DisplayIds = new Array();
		
	for (NodeId in DropDownMenus)
	{		
		Submenu = document.getElementById(NodeId);		

		if (in_array(NodeId, _DisplayIds))
		{
			// show
			Submenu.style.display = "block";	
			Submenu.style.visibility = "visible";
		}
		else
		{
			// hide
			Submenu.style.display = "none";	
			Submenu.style.visibility = "hidden";
		}
	}	
}

///////////////////////////////////////////
function HideAllSubmenusIfNoMouseover()
{
	if (CurMouseOverId == "")
		HideAllSubmenus();
}

///////////////////////////////////////////
function HideAllSubmenus()
{	
//Debug('-----HideAllSubmenus');
	clearTimeout(MenuHideTimeout);
	ShowHideMenus();
}

///////////////////////////////////////////
function OffSubMenu(_id)
{
	// bubble up workaround
	if (_id == CurMouseOverId)
		CurMouseOverId = '';
	
	clearTimeout(MenuHideTimeout);
	MenuHideTimeout = setTimeout('HideAllSubmenus()', 750);
}

/* not using string prototype so this can work with other js libs */
function strtrim(str) {
	var	str = str.replace(/^\s\s*/, ''),
		ws = /\s/,
		i = str.length;
	while (ws.test(str.charAt(--i)));
	return str.slice(0, i + 1);
}
function in_array(string, array)
{
	for (i = 0; i < array.length; i++)
	{
		if(array[i] == string)
			return true;
	}

	return false;
}



function ResetField(FieldObj, DefaultText) 
{
	if (FieldObj.value=="") 
		FieldObj.value=DefaultText; 
}

function ClearField(FieldObj, DefaultText) 
{
	if (FieldObj.value==DefaultText) 
		FieldObj.value="";	
}



function togglediv(in_State, in_Div)
{
	if(document.getElementById)
	{
		var obj = document.getElementById(in_Div);
		obj.style.display = in_State;//iState ? "show" : "hidden";
	}
}
function getInternetExplorerVersion() {
    var rv = -1; // Return value assumes failure.
    if (navigator.appName == 'Microsoft Internet Explorer') {
        var ua = navigator.userAgent;
        var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
        if (re.exec(ua) != null)
            rv = parseFloat(RegExp.$1);
    }
    return rv;
}

// Debugging functions
function Debug(_Msg)
{
return;	
        var Debug = document.getElementById('debug_console');
        if (Debug == undefined)
		{
        	AddDebugConsole();
	        Debug = document.getElementById('debug_console');
		}
		
        Time = new Date();
        //_Msg = Time.getMinutes()+Time.getSeconds()+": "+ _Msg;
        _Msg = ": "+ _Msg;

        Debug.innerHTML = _Msg+"<br>"+Debug.innerHTML;
}
function AddDebugConsole()
{
        // add debug div
        var DebugConsole = document.createElement('div');
        DebugConsole.id = "debug_console";
        DebugConsole.style.position = "absolute";
        DebugConsole.style.top = 0;
        DebugConsole.style.left = 0;
        DebugConsole.style.width = "300px";
        DebugConsole.style.height = "600px";

        // add debug window to top left of browser
        document.body.insertBefore(DebugConsole, document.body.firstChild);
}

