var nmu_activeMenu = "";
var nmu_activeSubMenuIDs = new Array();
var nmu_menuFadeDelay = 0.5;
//var nmu_menuFadeDelay = 0.5;
var nmu_clockValue = 0;
var nmu_tickingMenu = "";
var nmu_ticker;
var nmu_fire;
var nmu_normalStyle = "UnselectedMenuStyle";
var nmu_hoverStyle = "SelectedMenuStyle";
var nmu_linkNormalStyle = "UnselectedMenuLink";
var nmu_linkHoverStyle = "SelectedMenuLink";
var nmu_firstMenuFired = true;

// Check client browser
function nmu_InitBrowser()
{
	this.Moz = false;
	this.IE = false;
	this.NS4 = false;
	this.Opera = false;
	this.Mac = false;
	
	this.ua = navigator.userAgent;
	this.NS4 = (document.layers) ? 1:0;
	this.Opera = /opera [56789]|opera\/[56789]/i.test(this.ua);
	this.IE = !this.Opera && /msie [456789]/i.test(this.ua);
	this.Moz = !this.Opera && /mozilla\/[56789]/i.test(this.ua);
	this.Dom = (document.getElementById) ? 1:0;
	this.Mac = (this.ua.toLowerCase().indexOf( "mac" ) > -1) ? true:false;
}


var client = new nmu_InitBrowser();

// Sets style to menu container
function nmu_applyStyleInfoToElement( element, className )
{
	element.className = className;
}

// hides/shows all dropdown boxes in the page when a menu is pulled down/up
// This is because of a bug in IE: Dropdown boxes are always displayed
// on top of other controls, i.e. on top of this menu
function mnu_setDropDownControlsVisibility(show)
{
	// Do nothing for other browsers than IE
	if (!client.IE)
		return;
		
	var i;
	var theForm;
	theForm = document.forms[0];

	for (i = 0; i < theForm.elements.length; i++)
	{
		var theElement;
		theElement = theForm.elements[i];
		
		if (theElement.tagName == "SELECT") {
			theElement.style.visibility = (show ? "visible" : "hidden");
		}
	}
}


// Menu hovering
function nmu_mousedOverMenu( menuID, parentID, displayVertical, showSubMenu )
{

	// Set elements for menu, parent, link and submenu
	var menu = document.getElementById( menuID );
	var parent = document.getElementById( parentID );
	var lnk = document.getElementById( menuID + "_link" );
	var submenu = document.getElementById( menuID + "_subMenu" );
	var submenuOffsetLeft = (client.IE) ? -1 : -1; //Org. -1 : -1
	var submenuOffsetTop = (client.IE) ? 10 : 10; //Org. 2 : 1
	var submenuOffsetLeftVertical = (client.IE) ? 2 : 0;
	var submenuOffsetTopVertical = (client.IE) ? 3 : 3;

	// Set cursor
	menu.style.cursor = (client.Moz) ? "pointer":"hand";

	// Hover menu and all parent-menus
	nmu_applyStyleInfoToElement( lnk, nmu_linkHoverStyle );
	nmu_applyStyleInfoToElement( menu, nmu_hoverStyle );

	
//	if( nmu_firstMenuFired )
//	{
//		nmu_firstMenuFired = false;
//		nmu_fire = setTimeout("nmu_mousedOverMenu( '" + menuID + "','" + parentID + "'," + displayVertical + "," + showSubMenu + " );", 400 );
//		return;
//	}
//	else
//		clearTimeout( nmu_fire );

	// Stäng tidigare aktiv menu	
	//alert( menuID + " - " + nmu_activeMenu );
	if( nmu_activeMenu != "" )
		nmu_mousedOutMenu( nmu_activeMenu );

	// Hide all other menus
	nmu_stopTick();
	nmu_closeSubMenus( menuID, menuID );

	if( nmu_activeMenu && nmu_activeMenu.length > 0 && nmu_activeMenu == menuID )
		return;
	
	// Set classname for hovering
	nmu_activeMenu = menuID;

	// Hover menu and all parent-menus
	nmu_applyStyleInfoToElement( lnk, nmu_linkHoverStyle );
	nmu_applyStyleInfoToElement( menu, nmu_hoverStyle );
	
	// Show submenu if exists
	if( submenu != null && ( showSubMenu || !nmu_firstMenuFired ))
	{
		// Hide dropdown boxes when the menu pulls down
		
		// MAC Performance: 2-3 ms
		mnu_setDropDownControlsVisibility(false);
		
		nmu_firstMenuFired = false;

		// Set submenu as active
		nmu_activeSubMenuIDs[nmu_activeSubMenuIDs.length] = submenu.id;

		// Position submenu
		if( displayVertical ) {
			submenu.style.left = nmu_getAscendingLefts(parent) + parent.offsetWidth + submenuOffsetLeftVertical;
			submenu.style.top = nmu_getAscendingTops(menu) + submenuOffsetTopVertical;
		} else {
			
			/*
			
			// FOR DEBUGGING PURPOSES

			var o = document.getElementById( "TestPositionDiv" );
			if( o == null ) {
				o = document.createElement( "div" );
				o.style.position = "absolute";
				o.style.backgroundColor = "red";
				o.style.posLeft = posLeft;
				o.style.top = "0px;"
				o.style.width = "10px";
				o.style.height = "10px";
				document.body.appendChild( o );
			}
			*/
			
			var offsetAdjustmentX = 0;
			
			if( client.IE && client.Mac ) {
				var o = submenu;
				var s = "";
				
				var offsetLeft = 0;
				var tagName = "";
				
				while( o != null ) {
					o = o.parentElement;
					
					offsetLeft = o.offsetLeft;
					tagName = o.tagName.toLowerCase();
					
					if( tagName == "table" && offsetLeft > 0 )
						offsetAdjustmentX += offsetLeft;
					
					if( tagName == "body" )
						break;
				}
			}
			
			submenu.style.left = nmu_getAscendingLefts(menu) + submenuOffsetLeft - offsetAdjustmentX;
			submenu.style.top = nmu_getAscendingTops(parent) + parent.offsetHeight + submenuOffsetTop;
		}
		
		// Set styles for hovering
		submenu.style.position = 'absolute';
		submenu.style.display = 'block';
	}
}


// Menu reset
function nmu_mousedOutMenu( menuID, parentID )
{
	// Set elements for menu and link
	var menu = document.getElementById( menuID );
	var link = document.getElementById( menuID + "_link" );

	// Set default cursor
	menu.style.cursor = "default";

	// Reset hovering
	nmu_applyStyleInfoToElement( link, nmu_linkNormalStyle );
	nmu_applyStyleInfoToElement( menu, nmu_normalStyle );

	// Start menu close action
	nmu_activeMenu = "";
	nmu_stopTick();
	nmu_doTick( menuID, parentID );

	clearTimeout( nmu_fire );
}

// Close all menus
function nmu_closeSubMenus( menuID, parentID )
{
	if( nmu_subMenuIDs.length > 0 )
	{
		for( var i = 0; i < nmu_activeSubMenuIDs.length; i++ )
		{
			if( parentID.indexOf( nmu_activeSubMenuIDs[i] ) != 0 && nmu_activeSubMenuIDs[i] != "" )
			{
				document.getElementById( nmu_activeSubMenuIDs[i] ).style.display = 'none';
				nmu_activeSubMenuIDs[i] = "";
			}
		}
	}
}

// Starts clock to close entire menu
function nmu_doTick( menuID, parentID )
{
	//alert( nmu_clockValue + " - " + (nmu_menuFadeDelay*1000) );
	//return;

	nmu_tickingMenu = menuID;

	if( nmu_clockValue >= nmu_menuFadeDelay )
	{
		nmu_stopTick();
		nmu_closeSubMenus( menuID, parentID );
		nmu_activeSubMenuIDs = new Array();
		nmu_firstMenuFired = true;

		// Show dropdown boxes again when the menu dissapears
		mnu_setDropDownControlsVisibility(true);
	}
	else
	{
		nmu_clockValue++;
		var tickerDelay = parseInt( nmu_menuFadeDelay*1000 );
		nmu_ticker = setTimeout("nmu_doTick( '" + menuID + "','" + parentID + "' );", tickerDelay );
	}
}

// Stops clock
function nmu_stopTick()
{
	nmu_tickingMenu = "";
	nmu_clockValue = 0;
	clearTimeout( nmu_ticker );
}

// Returns left position of menu
function nmu_getAscendingLefts( elem )
{
	if( elem == null )
		return 0;
	else
		return elem.offsetLeft + nmu_getAscendingLefts(elem.offsetParent);
}

// Returns top position of menu
function nmu_getAscendingTops( elem )
{
	if( elem == null )
		return 0;
	else
		return elem.offsetTop + nmu_getAscendingTops(elem.offsetParent);
}

// Set parent hovering
function nmu_setParentHovering( menuID, hover )
{
	var tmpID = menuID;
	var tmpLink;
	var pos = tmpID.lastIndexOf( "_subMenu" );
	while( pos != -1 )
	{
		tmpID = menuID.substr(0,pos);
		tmpMenu = document.getElementById( tmpID );
		tmpLink = document.getElementById( tmpID + "_link" );
		if( tmpMenu != null )
		{
			if( hover )
			{
				nmu_applyStyleInfoToElement( tmpLink, nmu_linkHoverStyle );
				nmu_applyStyleInfoToElement( tmpMenu, nmu_hoverStyle );
			}
			else
			{
				nmu_applyStyleInfoToElement( tmpLink, nmu_linkNormalStyle );
				nmu_applyStyleInfoToElement( tmpMenu, nmu_normalStyle );
			}
		}

		pos = tmpID.lastIndexOf( "_subMenu" );
	}
}

// Handle menu action
function nmu_Action( link )
{
	if( link != "" )
	{
		document.location.href = link;
		return false;
	}
	else
		return;
}

function previewImage( imgUrl )
{
	previewImg = new Image();
	previewImg.src = imgUrl;
	windowWidth = previewImg.width + 20;
	windowHeight = previewImg.height + 20;
	windowParams = "width=" + windowWidth + ",height=" + windowHeight + ",titlebar=no,scrollbars=yes,resizable=yes,dependent=yes,toolbar=no,directories=no,menubar=yes,status=no,location=no,alwaysRaised=yes"
	imgPreviewWindow = window.open( "", "PreviewImage", windowParams );
	imgPreviewWindow.document.write("<html><head><title>Visa bild</title></head>");
	imgPreviewWindow.document.write("<body style='margin: 0px;'><img src='" + imgUrl + "'></body></html>");
}

// Sets input focus to a HTML control whose name is "ControlName".
function SetFocus(ControlName)
{
	// Replace all occurrances of ":" with "_"
	var From = /:/g;
	ControlName = ControlName.replace(From, "_");
	
	// alert("ControlName: " + ControlName);
	
	try
	{
		if (document.all)
		{
			document.all[ControlName].focus();
		}
		else if (document.getElementById)
		{
			document.getElementById(ControlName).focus();
		}
		else if (document.layers)
		{
			document.layers[ControlName].focus();
		}
	}
	catch(er)
	{
	}
}

// Can be added to the attributes of a text field as an "onKeyDown" event to force focus to
// a button when the user presses the ENTER key.
function SetFocusOnEnter(theEvent, ButtonName)
{
	if (theEvent.keyCode == 13)
	{
		SetFocus(ButtonName);
	}
}


// Can be added to the attributes of a button as an "onClick" event to hide the button
// when it is clicked. Hiding only takes place if the form is validated OK. This is
// useful to prevent "double clicks" on buttons when the processing on the server is slow
// and a second or third click creates unwanted actions, e.g. creates multiple rows in 
// a database table. Disabling the button instead of hiding it does not work (the
// postback will never be called in that case)
// Note:
// Does not work in netscape, since that browser uses server validation!
function HideWhenClicked(TheButton)
{
	// alert("HideWhenClicked");
	
	if (Page_ClientValidate())
	{
		TheButton.style.visibility = "hidden";
	}
}


function CheckDate( DateValue )
{
	var RtnVal = true;
	var TheDate = DateValue;

	// Extract the year, month, day and the delimiters from the date string
	var TheYear = TheDate.substring(0, 4);
	var Delim1 = TheDate.substring(4, 5);
	var TheMonth = TheDate.substring(5, 7);
	var Delim2 = TheDate.substring(7, 8);
	var TheDay = TheDate.substring(8, 10);

	// Check if the delimiters are "-"
	if (Delim1 == "-" && Delim2 == "-")
	{
		// Try to construct a date object using the extracted values
		var TestDate1 = new Date(TheYear, TheMonth, TheDay);
		var MilliSecs = TestDate1.valueOf()
		
		// Check if date object could be constructed
		if (isNaN(MilliSecs))
		{
			RtnVal = false;
		}
		else
		{
			// Check if the date is out of bounds, e.g. "2004-12-32"
			var TestDate2 = new Date(MilliSecs);
			RtnVal = (TheDay == TestDate2.getDate());
		}	
	}
	else
	{
		RtnVal = false;
	}

	return RtnVal;
}

// Date validation function to be connected to the CustomValidator ASP control.
// To use the validator, set the following attribute in the control:
// ClientValidationFunction="ValidateDate"
function ValidateDate(source, arguments)
{
	arguments.IsValid = CheckDate( arguments.Value );
}

// Sets a cookie
function setCookie(name, value, expires, path, domain, secure)
{
	var setPath;
	var curCookie = name + "=" + escape(value) +
		((expires) ? "; expires=" + expires.toGMTString() : "") +
		((path) ? "; path=" + path : "") +
		((domain) ? "; domain=" + domain : "") +
		((secure) ? "; secure" : "");
	document.cookie = curCookie;
}

// Gets the value for a cookie
function getCookie(name)
{
	var dc = document.cookie;
	var prefix = name + "=";
	var begin = dc.indexOf("; " + prefix);

	if (begin == -1) {
		begin = dc.indexOf(prefix);
		if (begin != 0) return null;
	}else
		begin += 2;

	var end = document.cookie.indexOf(";", begin);
	if (end == -1)
		end = dc.length;

	return unescape(dc.substring(begin + prefix.length, end));
}

// Deletes a cookie
function deleteCookie(name, path, domain)
{
	if (getCookie(name)) {
		document.cookie = name + "=" + 
		((path) ? "; path=" + path : "") +
		((domain) ? "; domain=" + domain : "") + 
		"; expires=Thu, 01-Jan-70 00:00:01 GMT";
	}
}
