// auto clearing of fields on click
function resetField(FieldObj, DefaultText) {
if (FieldObj.value=="") 
    FieldObj.value=DefaultText;
}
function clearField(FieldObj, DefaultText) {
	if (FieldObj.value==DefaultText)
    FieldObj.value='';	
}
function resetSearch(_Obj) 
{
	resetField(_Obj, 'Site Search');
}
function clearSearch(_Obj) 
{
	clearField(_Obj, 'Site Search');
}


function OpenWindow(url, width, height)
{
	var PopupWidth = width;
	var PopupHeight = height;
  var PopupLeft = (screen.width - PopupWidth) / 2;
  var PopupTop = (screen.height - PopupHeight) / 3;
		 
	newwindow=window.open(url,'name','top='+PopupTop+',left='+PopupLeft+',width='+PopupWidth+',height='+PopupHeight+',resizable=yes,scrollbars=no');
	if (window.focus) {newwindow.focus()}
}



function otherMouseOver(_Id)
{
	Obj = document.getElementById(_Id);
	addClassName(Obj, 'hover');
}
function otherMouseOut(_Id)
{
	Obj = document.getElementById(_Id);
	removeClassName(Obj, 'hover');
}



// edit menu config line below: 
// menu built using these settings on very last line of this file
DropdownSettings = {navId:"nav",tabClass:"tab",menuDivClass: "tab_submenu",subMenusDivClass: "tab_subsubmenu"};

// do not edit below here:

//
// Custom dropdowns
var MenuTimerID = Array();

// fix for firefox and back button,
window.onload = WindowOnLoader;
window.onunload = function(){var i=1;}; // FF ignores onload unless onunload is also there

var MenuHideTimeout;
var CurMouseOverId = "";
var DropDownMenus = new Object;

// offsets
var Nav_LeftOffset = 0;
var Nav_LeftOffset_IE7orLower = 0; /* remove me as not needed? */
var SubNav_TopOffset = 1;
var SubNav_TopOffset_IE8orHigher = 2; 
var Shadow_Bottom_Offset = -7; /* make room for bottom right edge, based on width of .shadow_br */
var SubNav_LeftShadow_TopOffset = -4;

//fixme pull this out into setup code
var SubNav_ArrowXOffset = 17; /* num pixels from right edge */
var SubNav_ArrowYPos = 9;

// images to preload (if css not good method, like for menu arrows)
var ImagesToPreload = ['/images/template/nav/nav_sub_arrow_hover.gif'];

///////////////////////////////////////////
function WindowOnLoader()
{
	if (getInternetExplorerVersion() != 6)
		HideAllSubmenusIfNoMouseover();
	
	//SetupExternalLinks();
}

///////////////////////////////////////////
// finds all rel="external" links on page and opens them in new windows
function SetupExternalLinks()
{
	if ( ! document.getElementsByTagName) return;   
	var anchors = document.getElementsByTagName("a");   
	for (var i=0; i<anchors.length; i++) 
	{   
		var anchor = anchors[i];   
		if (anchor.getAttribute("href") && anchor.getAttribute("rel") == "external")   
     anchor.target = "_blank";   
	}   	
}

///////////////////////////////////////////
function setupMainNav(_Params)
{
	// verify all params given
	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);

	preloadImages();
}

///////////////////////////////////////////
function preloadImages()
{
	var PreloadedImages = new Array();
	for (i=0; i<ImagesToPreload.length; i++)
	{
		PreloadedImages[i] = new Image();
		PreloadedImages[i].src = ImagesToPreload[i];
	}
}

///////////////////////////////////////////
function recursiveSetupMainNav(_Node, _TabClass, _MenuDivClass, _SubmenuDivClass)
{
	var childNodes = _Node.childNodes;              
	var prevAnchorNode;
	
	// loop through all child nodes for the _Node param
  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];

		// skip nodes without classnames
		if (childNode.className == undefined || childNode.className == "")
			continue;
		
		// split className up by spaces 
		var ClassNames = childNode.className.split(" ");

		// loop through classnames
		for (var cn=0; cn < ClassNames.length; cn++)
		{
			// skip everything besides menu or submenu divs
			if ( ! ((ClassNames[cn] == _MenuDivClass || ClassNames[cn] == _SubmenuDivClass) && prevAnchorNode != undefined))
				continue;
				
			// give some alerts if menu setup incorrectly
			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 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.');

			// insert into lookup info for the child node
			DropDownMenus[childNode.id] = new Object;
			DropDownMenus[childNode.id]["parentAnchorId"] = prevAnchorNode.id;
			DropDownMenus[childNode.id]["parentMenuId"] = _Node.id;
			isSubMenu = (ClassNames[cn] == _SubmenuDivClass) ? true : false;
			DropDownMenus[childNode.id]["isSubMenu"] = isSubMenu;

			// add drop shadow divs to this menu div
			setupDropShadowDivs(childNode);

			// setup mouse events for parent link and menu div
//fixme, remove last param if not needed (old TabAnchorID)	
			setupMenuMouseEvents(prevAnchorNode, childNode);
			
			// perform any dynamic position / size adjustments
			setupPositionSizeAdjustments(childNode, isSubMenu, ClassNames[cn], prevAnchorNode, _TabClass, _MenuDivClass, _SubmenuDivClass);
		}

		recursiveSetupMainNav(childNode, _TabClass, _MenuDivClass, _SubmenuDivClass);
  }
	
	// last "prev anchor" needs to have a class added to specify it as the bottom link in that menu
	if (prevAnchorNode != undefined)
		prevAnchorNode.className += (prevAnchorNode.className ? " " : "") + 'last_link';
}

///////////////////////////////////////////
var _cache_ShowSubMenu = new Array();
function ShowSubMenu(_id, _TabAnchorID)
{
	//EoDebug('ShowSubMenu('+_id);	
		
	// bubble up fix
	if (CurMouseOverId != "")
		return;
	
	clearTimeout(MenuHideTimeout);
			
	CurMouseOverId = _id;

	var nodeData = DropDownMenus[_id];
	if (nodeData == undefined)
		alert("Popup Menu Error: can't show submenu "+_id+" because its not setup correctly" );

	var nodeParentAnchorId = nodeData.parentAnchorId;
	var nodeParentMenuId = nodeData.parentMenuId;
	var isNodeSubmenu = nodeData.isSubMenu;
	
	// make array of all id's that should be displayed, node to parent
	DisplayIds = new Array(_id);
		
	// diplay all node's parents
	curNodeData = nodeData;
	while ((parentMenuId = curNodeData.parentMenuId) != undefined)
	{
		if (strtrim(parentMenuId) == "" || DropDownMenus[parentMenuId] == undefined)
			break;
		DisplayIds.push(parentMenuId);
		curNodeData = DropDownMenus[parentMenuId];
	}
	
	// go through all menu id's, display those needed and hide all others
	ShowHideMenus(DisplayIds);

	// only run adjustment code below here once
	if (_cache_ShowSubMenu[_id] != undefined)
		return; 
	_cache_ShowSubMenu[_id] = true;
	
	//
	// update menu top & drop shadows here
	// (can't do in menu builder as offsetHeight doesn't work there
	Submenu = document.getElementById(_id);

	// update the height of the left shadow
	// only needs to be done on first display so ok here
	LeftShadowDiv = document.getElementById(_id+"_shadowl");
	BottomShadowDiv = document.getElementById(_id+"_shadowb");
	BottomLeftShadowDiv = document.getElementById(_id+"_shadowbl");
		
	// offset the left & top from parent
	if (nodeParentAnchorId == undefined)
		return;

//fixme, cache below so doesn't keep running?, can we put it in the main menu walking code instead (recursive builder)?

	ParentTag = document.getElementById(nodeParentAnchorId);
	if (ParentTag != null)
	{
		BottomShadowDiv.style.width = (Submenu.offsetWidth + Shadow_Bottom_Offset)+"px";
		BottomLeftShadowDiv.style.display = (getInternetExplorerVersion() == 6) ? "none" : "block";
//EoDebug('getInternetExplorerVersion()'+getInternetExplorerVersion());

		if (isNodeSubmenu)
		{			
			// adjust top offset
			var Offset = SubNav_TopOffset;
			if (getInternetExplorerVersion() >= 8)
				Offset = SubNav_TopOffset_IE8orHigher;

			SubmenuTop = ParentTag.offsetTop - Offset;

			Submenu.style.top = SubmenuTop + "px";			

			ParentMenu = document.getElementById(nodeParentMenuId);
			ParentSubLeftOverlap = ParentMenu.offsetHeight - SubmenuTop;
			LeftShadowTop = ParentSubLeftOverlap + SubNav_LeftShadow_TopOffset;
			LeftShadowDiv.style.top = LeftShadowTop +"px";
			LeftShadowHeight = Math.max(0, (Submenu.offsetHeight - LeftShadowTop)); 
			LeftShadowDiv.style.height = LeftShadowHeight +"px";			

			// hide bottom left shadow if no left shadow displayed
			if (LeftShadowHeight <= 0)
				BottomLeftShadowDiv.style.display = "none";
		}
		else // is first level of dropdown
		{
			// give it full height left shadow (never have to worry about it covering another nav)
			LeftShadowDiv.style.height = (Submenu.offsetHeight-1)+"px";			
		}
	}
//	EoDebug("showing top:"+Submenu.style.top+", left:"+Submenu.style.left);
}

///////////////////////////	////////////////
function setupPositionSizeAdjustments(_MenuDiv, _isSubMenu, _DivClassName, _ParentAnchor, _TabClass, _MenuDivClass, _SubmenuDivClass)
{
	var ParentDiv = _ParentAnchor.parentNode;

	// main dropdown (1st level) only need to left align them and skip everything else
	if (in_array(_TabClass, _ParentAnchor.className.split(" ")))
	{
		var LeftOffset = Nav_LeftOffset; // 3 to make room for drop shadow, was 0
		if (getInternetExplorerVersion() < 8 && getInternetExplorerVersion() != -1)
			LeftOffset = Nav_LeftOffset_IE7orLower;

		_MenuDiv.style.left = (_ParentAnchor.offsetLeft + LeftOffset)+"px";
		
		return;
	}

	// since only care about menu divs, return if anything else
	if ( ! (in_array(_MenuDivClass, ParentDiv.className.split(" ")) || in_array(_SubmenuDivClass, ParentDiv.className.split(" "))))
		return;

	// adjust subnavs below:
	//
	
	_ParentAnchor.className += (_ParentAnchor.className ? " " : "") + "tab_submenu_arrow";

	// DOM - div unless IE, then its DIV
	DivTag = (getInternetExplorerVersion() == -1 || getInternetExplorerVersion() >= 9) ? 'div' : 'DIV'; 
								
	// update the subnav left (and arrow position) to match its parent div width
	ParentDivWidth = 200; // better than 0 default value just in case

	// parent div width embedded as style="" in tag
	if (ParentDiv.style.width != "")
		ParentDivWidth = parseInt(ParentDiv.style.width)
	// parent div as explicit css id settig (div#id)
	else if (getClassParam(DivTag+"#"+ParentDiv.id, 'width') != "")
		ParentDivWidth = parseInt(getClassParam(DivTag+"#"+ParentDiv.id, 'width'));
	// parent div as css class (div.classname)
	else if (getClassParam(DivTag+"."+_DivClassName, 'width') != "")
		ParentDivWidth = parseInt(getClassParam(DivTag+"."+_DivClassName, 'width'));

	//
	// update arrow positions (for links with submenus)
	
	// use offset depending on if its a submenu or not
	if (_isSubMenu)
	{
		ArrowXOffset = SubNav_ArrowXOffset;
		ArrowYPos = SubNav_ArrowYPos;
	} 
	else // 1st level dropdown
	{
		//update 2 below once subnav font/lineheights change from 1st level dropdown
		ArrowXOffset = SubNav_ArrowXOffset; 
		ArrowYPos = SubNav_ArrowYPos;
	}

	// update the arrow image bg position to deal with custom width
	_ParentAnchor.style.backgroundPosition = (ParentDivWidth - ArrowXOffset)+"px "+ArrowYPos+"px";

	//
	// update left position to match width of parent div	
//EoDebug(ParentDivWidth);	
	_MenuDiv.style.left = ParentDivWidth +"px";
}

///////////////////////////////////////////
function ShowHideMenus(_DisplayIds)
{
	if (_DisplayIds == undefined)
		_DisplayIds = new Array();
		
	for (NodeId in DropDownMenus)
	{		
		Submenu = document.getElementById(NodeId);		

		// if not submenu, then its the main drop down
		isMainDropdown = ! DropDownMenus[NodeId]["isSubMenu"];
			
		if (in_array(NodeId, _DisplayIds))
		{
			// show
//EoDebug("* show "+NodeId);			
			Submenu.style.display = "block";	
			Submenu.style.visibility = "visible";
			
			// if main dropdown, then parentanchor is tab graphic so add hover class
			if (isMainDropdown)
				addClassName(document.getElementById(DropDownMenus[NodeId]["parentAnchorId"]), "hover");
		}
		else
		{
			// hide
//EoDebug("* hide "+NodeId);			
			Submenu.style.display = "none";	
			Submenu.style.visibility = "hidden";

			// if main dropdown, then parentanchor is tab graphic so remove hover class
			if (isMainDropdown)
				removeClassName(document.getElementById(DropDownMenus[NodeId]["parentAnchorId"]), "hover");
		}
	}	
}

///////////////////////////////////////////
function addClassName(_Obj, _ClassName)
{
	// skip if classname already there
	if (in_array(_ClassName, _Obj.className.split(" ")))
		return; 

	_Obj.className += (_Obj.className ? " " : "") + _ClassName;
}

///////////////////////////////////////////
function removeClassName(_Obj, _RemoveClassName)
{
	// rebuild className without _ClassName
	var NewClassNames = '';
	
	var CurClassNames = _Obj.className.split(" ");
	
	for (i=0; i<CurClassNames.length; i++)
	{
		NewClassNames += (NewClassNames == "") ? "" : " ";
		
		if (CurClassNames[i] != _RemoveClassName)
			NewClassNames += CurClassNames[i];
	}
//Debug('removeClassName');	
	_Obj.className = NewClassNames;
}

///////////////////////////////////////////
function HideAllSubmenusIfNoMouseover()
{
	if (CurMouseOverId == "")
		HideAllSubmenus();
}
///////////////////////////////////////////
function HideAllSubmenus()
{	
//Debug('-----HideAllSubmenus');
	clearTimeout(MenuHideTimeout);
	ShowHideMenus();
}
///////////////////////////////////////////
function OffSubMenu(_id, _TabAnchorID)
{
	// bubble up workaround
	if (_id == CurMouseOverId)
		CurMouseOverId = '';
	
	clearTimeout(MenuHideTimeout);
	MenuHideTimeout = setTimeout('HideAllSubmenus()', 750);
}
/*
function print_r(theObj, label)
{
	if (label == undefined)
		label = "";

	if(theObj.constructor == Array ||
     theObj.constructor == Object){
	
		Debug(label+"--start--")
    for(var p in theObj){
      if(theObj[p].constructor == Array||
         theObj[p].constructor == Object)
			{
				Debug("obj["+p+"] => "+typeof(theObj));
        print_r(theObj[p]);
      } else {
				Debug("leaf["+p+"] => "+theObj[p]);
      }
    }
    Debug(label+"--end--");
  }
}*/
///////////////////////////////////////////
function setupDropShadowDivs(_childNode)
{
	// left edge
	var Shadow_Left = document.createElement('div');
	Shadow_Left.className = "shadow_l";
	Shadow_Left.id = _childNode.id+"_shadowl"; 
	_childNode.appendChild(Shadow_Left);
						
	// bottom
	var Shadow_Bottom = document.createElement('div');
	Shadow_Bottom.className = "shadow_b";
	Shadow_Bottom.id = _childNode.id+"_shadowb"; 
	_childNode.appendChild(Shadow_Bottom);

	// bottom right
	var Shadow_Bottom_Right = document.createElement('div');
	Shadow_Bottom_Right.className = "shadow_br";
	_childNode.appendChild(Shadow_Bottom_Right);

	// bottom left
	var Shadow_Bottom_Left = document.createElement('div');
	Shadow_Bottom_Left.className = "shadow_bl";
	Shadow_Bottom_Left.id = _childNode.id+"_shadowbl"; 
	_childNode.appendChild(Shadow_Bottom_Left);
}

///////////////////////////////////////////
function	setupMenuMouseEvents(_prevAnchorNode, _childNode)
{
	_prevAnchorNode.mouse_event_param = _childNode.id;
	_prevAnchorNode.onmouseover = function(){ShowSubMenu(this.mouse_event_param)};
	_prevAnchorNode.onmouseout = function(){OffSubMenu(this.mouse_event_param)};
	_childNode.mouse_event_param = _childNode.id;
	_childNode.onmouseover = function(){ShowSubMenu(this.mouse_event_param)};
	_childNode.onmouseout = function(){OffSubMenu(this.mouse_event_param)};
}

///////////////////////////////////////////
var _global_getClassParam_cache = new Array();
function getClassParam(_ClassName, _Param) 
{	
	// since our js doesn't change stylesheet settings we can cache the value
	if (_global_getClassParam_cache[_ClassName] != undefined && _global_getClassParam_cache[_ClassName][_Param] != undefined)
		return _global_getClassParam_cache[_ClassName][_Param];
	
	
	var CssAccessor;	
	for (var i=0; i<document.styleSheets.length; i++)
	{
		styleSheet = document.styleSheets[i];
		if (CssAccessor == undefined)
		{
			if (styleSheet['rules'])
				CssAccessor = 'rules';
			else if (styleSheet['cssRules'])
				CssAccessor = 'cssRules';
		}
		
		// loop through rules
//		if (styleSheet[CssAccessor] == undefined)
//			EoDebug('cant access stylesheet '+styleSheet.title);
			
		if (styleSheet[CssAccessor] != undefined )
		{
			for (var j=0; j<styleSheet[CssAccessor].length; j++)
			{
				if (styleSheet[CssAccessor][j].selectorText == _ClassName)
				{
					ParamValue = styleSheet[CssAccessor][j].style[_Param];
	
					// save it to the cache for faster access next time
					if (_global_getClassParam_cache[_ClassName] == undefined)
						_global_getClassParam_cache[_ClassName] = new Array();
					_global_getClassParam_cache[_ClassName][_Param] = ParamValue;
	
					return ParamValue;
				}
			}	
		}
	}
	return '';
}
/* 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(_item, _array)
{
	for (i = 0; i < _array.length; i++)
	{
		if(_array[i] == _item)
			return true;
	}
	
	return false;
}

///////////////////////////////////////////
var _cache_getInternetExplorerVersion;
function getInternetExplorerVersion() 
{
	if (_cache_getInternetExplorerVersion != undefined)
		return _cache_getInternetExplorerVersion;
	
  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)
		{
			VersionNum = parseFloat(RegExp.$1);
			_cache_getInternetExplorerVersion = VersionNum;
			return VersionNum;
		}
  }
		
	// is not ie
	_cache_getInternetExplorerVersion = -1;
  return -1; 
}

// Debugging functions
///////////////////////////////////////////
function EoDebug(_Msg)
{
        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 = "500px";
        DebugConsole.style.height = "600px";

        // add debug window to top left of browser
        document.body.insertBefore(DebugConsole, document.body.firstChild);
}
