/*****************************************************************************************
** This file contains fucntions to manipulate querystring and to get values from them.	**
******************************************************************************************/

//Get the position of the & character in an url
function getAmpPos(pvUrl, pvPos)
{
	var lvContinue = true;
	var lvPos = pvPos;

	while (lvContinue && lvPos < pvUrl.length)
	{
		var lvChar = pvUrl.charAt(lvPos);
		lvContinue = (lvChar != "&");
		if (lvContinue)
		{
			lvPos++;
		}
	}

	return lvPos;
}

//Get part of an url after the & character
function getPostUrl(pvUrl, pvPos)
{
	return pvUrl.substring(getAmpPos(pvUrl, pvPos));
}

//Add a value to an url
function addToQueryString(pvUrl, pvKey, pvValue)
{
	var lvUrl = pvUrl;
	var lvPos = lvUrl.indexOf(pvKey + "=");

	if (lvPos == -1)
	{
		if (lvUrl.indexOf("?") == -1)
		{
			lvUrl += "?";
		}
		else
		{
			lvUrl += "&";
		}
		lvUrl += pvKey + "=" + pvValue;
	}
	else
	{
		lvPos += pvKey.length + 1;
		var lvPre = lvUrl.substring(0, lvPos);
		lvUrl = lvPre + pvValue + getPostUrl(lvUrl, lvPos);
	}
	return lvUrl;
}

//Remove a value from an url
function removeFromQueryString(pvUrl, pvKey)
{
	var lvUrl = pvUrl;
	var lvPos = lvUrl.indexOf(pvKey + "=");
	if (lvPos > -1)
	{
		var lvPre = lvUrl.substring(0, lvPos - 1);
		lvPos += pvKey.length + 1;
		lvUrl = lvPre + getPostUrl(lvUrl, lvPos);
		if ((lvUrl.indexOf("?") == -1) && (lvUrl.indexOf("&") > -1))
		{
			lvUrl = lvUrl.replace("&", "?");
		}
	}

	return lvUrl;
}

//Get the value of a parameter in an url as string
function queryVal(pvUrl, pvKey)
{
	var lvVal = "";
	var lvStartPos = pvUrl.indexOf(pvKey + "=");

	if (lvStartPos > -1)
	{
		lvStartPos += pvKey.length + 1;
		lvVal = pvUrl.substring(lvStartPos, getAmpPos(pvUrl, lvStartPos));
	}

	return lvVal;
}

//Get the value of a parameter in an url as integer
function queryValAsInteger(pvUrl, pvKey, pvDef)
{
	var lvInt = parseInt(queryVal(pvUrl, pvKey));
	return isNaN(lvInt) ? pvDef : lvInt;
}

function addActiveSectionQueryValue(pvUrl)
{
	var lvNewUrl = pvUrl;
	var lvActiveSection = "";

	if (window.activesection != null && window.activesection != "")
	{
		lvNewUrl = addToQueryString(lvNewUrl, "ac", window.activesection)
	}

	return lvNewUrl;
}