// Globals
var gMenuTimer = null;

// ------------------------------------------------------------
// Changes the height of a number of div so they are the same
// height. The input param is an array with div-id:s.
// ------------------------------------------------------------
function adaptDivs(divNameArr, minHeight)
{
    var height = minHeight;
    var divArr = Array();
    
    // Loop over all the divs to get the height if the highest
    for (i = 0; i < divNameArr.length; i++)
    {
        divArr[i] = document.getElementById(divNameArr[i]);
        
        if (divArr[i])
        {
			// We set the height to auto to erase any previously hardcoded pixel
			// values which will otherwise prevent this function from running correctly
			// more than one time. It's useful to be able to call this function
			// again when dynamic content is displayed on the page.
	        divArr[i].style.height = 'auto';
	        
	        if (divArr[i].clientHeight > height)
	        {
				height = divArr[i].clientHeight;
			}
        }
    }    

    // Set the height for all divs
    for (i = 0; i < divArr.length; i++)
    {
        if (divArr[i])
        {
            divArr[i].style.height = height + 'px';
        }
    }
}

// ------------------------------------------------------------
// Shows the specified element
// ------------------------------------------------------------
function showElement(elemId)
{
	var elem = document.getElementById(elemId);
	if (elem)
	{
		elem.style.display = 'block';
	}
}

// ------------------------------------------------------------
// Hides the specified element
// ------------------------------------------------------------
function hideElement(elemId)
{
	var elem = document.getElementById(elemId);
	if (elem)
	{
		elem.style.display = 'none';
	}
}

// ---------------
// Toggles visibility of the specified element.
// ---------------
function toggleVisibility(elemId)
{
	var elem = document.getElementById(elemId);
	
	if (elem)
	{
		if (elem.style.display == 'none')
		{		
			elem.style.display = 'block';
		}
		else
		{			
			elem.style.display = 'none';
		}
	}
}

// ------------------------------------------------------------
// Returns the x coordinate of the specified object
// ------------------------------------------------------------
function findPosX(obj)
{
    var curleft = 0;
    if (obj.offsetParent)
    {
        while (obj.offsetParent)
        {
            curleft += obj.offsetLeft
            obj = obj.offsetParent;
        }
    }
    else if (obj.clientLeft)
    {
        curleft += obj.clientLeft;
    }
    return curleft;
}

// ------------------------------------------------------------
// Returns the y coordinate of the specified object
// ------------------------------------------------------------
function findPosY(obj)
{
    var curtop = 0;
    if (obj.offsetParent)
    {
        while (obj.offsetParent)
        {
            curtop += obj.offsetTop
            obj = obj.offsetParent;
        }
    }
    else if (obj.clientTop)
    {
        curtop += obj.clientTop;
    }
    return curtop;
}

// ------------------------------------------------------------
// This function will fire a click event on the specified control when the 
// enter key is pressed in a text field. Attach this function to the 
// onkeypress-event on the text field like this:
// <input type="text" onkeypress="return fireClickOnEnter(event, 'IdOfControlToFireClickOn');">
// ------------------------------------------------------------
function fireClickOnEnter(evt, controlId)
{
    var control = document.getElementById(controlId);
    var keyCode = (typeof window.event == 'object') ? window.event.keyCode : evt.keyCode;

    // If enter is pressed -> fire click-event on the control
    if (control && (keyCode == 13))
    {
        control.focus();
        control.click();
        return false;
    }
    else
    {
        return true;
    }
}

// ------------------------------------------------------------
// This function will fire a postbackon the specified control when the 
// enter key is pressed in a text field. Attach this function to the 
// onkeypress-event on the text field like this:
// <input type="text" onkeypress="return postbackOnEnter(event, 'IdOfControlToFirePostbackOn');">
// ------------------------------------------------------------
function postbackOnEnter(evt, controlId)
{
    var keyCode = (typeof window.event == 'object') ? window.event.keyCode : evt.keyCode;

    // If enter is pressed -> do a postback
    if (keyCode == 13)
    {
		__doPostBack(controlId,'');
		return false;
    }
    else
    {
        return true;
    }
}

// ---------------
// Returns a parameter from the query string
// ---------------
function getUrlParam(strParamName)
{
	var strReturn = '';
	var strHref = window.location.href;
	if (strHref.indexOf('?') > -1)
	{
		var strQueryString = strHref.substr(strHref.indexOf('?'));
		var aQueryString = strQueryString.split('&');
		for (var iParam = 0; iParam < aQueryString.length; iParam++)
		{
			if (aQueryString[iParam].indexOf(strParamName + '=') > -1)
			{
				var aParam = aQueryString[iParam].split('=');
				strReturn = aParam[1];
				break;
			}
		}
	}
	return strReturn;
}

// ------------------------------------------------------------
// Opens the specified link. Internal links will open in the
// same window. External links will open in a ne window.
// ------------------------------------------------------------
function openLink(url)
{
	if (url && (url != ''))
	{
		if (url.charAt(0) == '/') // Internal
		{
			window.location.href = url;
		}
		else // External
		{
			window.open(url);
		}
	}
}

// ------------------------------------------------------------
// Called from the onload-event on the body-tag
// ------------------------------------------------------------
function adaptMainDivs()
{
	return;
	var arrDivs = Array('leftareadiv', 'rightareadiv');
	adaptDivs(arrDivs, 300);

	arrDivs = Array('BreadCrumbLeftMenuFakeDiv', 'BreadCrumbDiv');
	adaptDivs(arrDivs, 0);
}

// ------------------------------------------------------------
// Opens the language pop-up menu.
// ------------------------------------------------------------
function openLanguageMenu()
{
	var languageImg  = document.getElementById('LanguageImage');
	var languageMenu = document.getElementById('LanguageMenuDiv');
	
	if (languageImg && languageMenu)
	{
		stopCloseMenuTimer();
		languageMenu.style.left		= findPosX(languageImg) + 'px';
		languageMenu.style.top		= (findPosY(languageImg) + 16) + 'px';
		languageMenu.style.display	= 'block';
	}
}

// ------------------------------------------------------------
// Opens a sub-menu in the page top menu.
// ------------------------------------------------------------
function openPageTopSubMenu(pageId)
{
	var menuItem = document.getElementById('PageTopMenuItem' + pageId);
	var subMenu  = document.getElementById('PageTopSubMenu' + pageId);
	
	if (menuItem && subMenu)
	{
		stopCloseMenuTimer();
		subMenu.style.left		= (findPosX(menuItem) - 2)+ 'px';
		subMenu.style.top		= (findPosY(menuItem) + 29) + 'px';
		subMenu.style.display	= 'block';
	}
}

// ------------------------------------------------------------
// Starts a timer that will close the specified popup menu
// ------------------------------------------------------------
function closePopupMenu(menuId)
{
    if (gMenuTimer == null)
    {
        gMenuTimer = window.setTimeout('hideElement(\'' + menuId + '\')', 200);
    }
}

// ------------------------------------------------------------
// Stops the closemenu-timer
// ------------------------------------------------------------
function stopCloseMenuTimer()
{
    if (gMenuTimer != null)
    {
        window.clearTimeout(gMenuTimer);
        gMenuTimer = null;
    }
}

// ------------------------------------------------------------
// Fires search when search button is clicked.
// ------------------------------------------------------------
function fireQuickSearch(languageCode)
{
	var searchField = document.getElementById('QuickSearchField');
	if (searchField && (searchField.value != ''))
	{
		url = "http://afconsult.siteseeker.se?q=" + escape(searchField.value) + 
			((languageCode != 'SV') ? '&i=en' : '');
			
		window.location.href = url;			
	}
}

// ------------------------------------------------------------
// Fires search when enter is pressed in search field
// ------------------------------------------------------------
function fireQuickSearchOnEnter(evt, languageCode)
{
    var keyCode = (typeof window.event == 'object') ? window.event.keyCode : evt.keyCode;

    // If enter is pressed -> fire the search
    if (keyCode == 13)
    {
		fireQuickSearch(languageCode);
        return false;
    }
    else
    {
        return true;
    }
}

// ------------------------------------------------------------
// Builds an html-page for printing
// ------------------------------------------------------------
function printPage(pageTitle, pageFooter) 
{
	if (!window.print)
	{
		window.status = 'No print';
		return;
	}

	// Get the main content area and other stuff we need
	var contentdiv = document.getElementById('contentdiv');

	if (contentdiv)
	{
		var contentHtml = '<div style="width: 475px">' + contentdiv.innerHTML + '</div>';
		var footerHtml = '<div style="width: 475px"><br /><hr />' + pageFooter + '</div>';

		var beginHtml = 
			  '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">' +
		      '<html>' +
			  '<head>' +
			  '<link rel="stylesheet" type="text/css" href="' + gAppRoot + 'styles/structure.css">' +
			  '<link rel="stylesheet" type="text/css" href="' + gAppRoot + 'styles/main.css">' +
			  '<link rel="stylesheet" type="text/css" href="' + gAppRoot + 'styles/units.css">' +
			  '<style> .PrintExclude { visibility: hidden; position: absolute; top: 0px; height: 0px } </style>' +
			  '<title>' + pageTitle + '</title>' +
			  '</head>' +
			  '<body style="margin: 20px; background-color: #fff; background-image: none">';

		var endHtml = '</body></html>';

		var printWin = window.open('about:blank','','width=700,height=600,scrollbars=yes,toolbar=yes');
		printWin.document.open();
		printWin.document.write(beginHtml + 
		                        contentHtml + 
		                        footerHtml + 
		                        endHtml);
		printWin.document.close();

		printWin.print();
		printWin.close();
	}
}
//Writes flash to div.
function AddStaticFlash( flashSrc, width, height, targetElementId, flashVersion, clickUrl )
{
	flashVersion = flashVersion || "7";
	clickUrl = clickUrl || "";
    var so = new SWFObject(flashSrc, "header", width, height, flashVersion, "#FFFFFF");
	so.addParam("quality", "high");
	
	if (clickUrl.length > 0)
		so.addVariable("linkUrl", escape(clickUrl));
	
	//Write to div.
	so.write(targetElementId)
}

var Url = {
 
	// public method for url encoding
	encode : function (string) {
		return escape(this._utf8_encode(string));
	},
 
	
	// private method for UTF-8 encoding
	_utf8_encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";
 
		for (var n = 0; n < string.length; n++) {
 
			var c = string.charCodeAt(n);
 
			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}
 
		}
 
		return utftext;
	}
}
