/**
 * Name of the current history cookie.
 */
var currentHistoryCookieName = "ARCHIVE_HISTORY_CURRENT";

/**
 * Name of the new history cookie.
 */
var newHistoryCookieName = "ARCHIVE_HISTORY_NEW";

/**
 * Default history that is used when current history could not be determined.
 */
var defaultCurrentHistory = "/arkisto/";

/**
 * Blacklist containing patterns for locations that
 * are not allowed in location history.
 */
var blacklist = new Array();
blacklist[0] = /^.*\/arkisto\/artikkeli.*$/;

/**
 * String trimming function.
 */
function trim(str)
{
	str = str.replace(/^[ ]+(.*)$/, "$1");
	str = str.replace(/^(.*)[ ]+$/, "$1");
	return str;
}

/**
 * Reads the value of specified cookie.
 */
function getCookie(name)
{
	// default to null
	var ret = null;

	// construct cookie start string
	var cookieStart = name + "=";

	// process each cookie
	var cookieArray = document.cookie.split(';');

	for(var i=0;i < cookieArray.length;i++)
	{
		// see if current cookie has correct start
		var cookie = trim(cookieArray[i]);

		if(cookie.indexOf(cookieStart) == 0)
		{
			ret = cookie.substring(cookieStart.length, cookie.length);
		}
	}

	return ret;
}

/**
 * Sets the value for specified cookie.
 */
function setCookie(name, value)
{
	document.cookie = name+"="+value+"; path=/";
}


/**
 * Determines if location is allowed to be placed to history.
 */
function isAllowedInHistory(location)
{
	// default to true
	var ret = true;

	// see if location matches with blacklist
	for(i=0;i<blacklist.length;i++)
	{
		if(blacklist[i].test(location))
		{
			ret = false;
			break;
		}
	}
	return ret;
}

/**
 * Returns the new history location.
 */
function getNewHistory()
{
	var newHistory = getCookie(newHistoryCookieName);
	return newHistory;
}

/**
 * Sets the new history location.
 */
function setNewHistory(location)
{
	setCookie(newHistoryCookieName, location);
}

/**
 * Returns the current history location.
 */
function getCurrentHistory()
{
	var currentHistory = getCookie(currentHistoryCookieName);
	return currentHistory;
}

/**
 * Sets the current history location.
 */
function setCurrentHistory(location)
{
	setCookie(currentHistoryCookieName, location);
}

/**
 * Updates the history.
 */
function updateHistory()
{
	/*
	 * Swap new history location to current history location.
	 */
	var newHistory = getNewHistory();

	if(newHistory != null)
	{
		setCurrentHistory(newHistory);
	}
	else
	{
		setCurrentHistory(defaultCurrentHistory);
	}

	/*
	 * Update new history location if current location is allowed.
	 */
	var currentLocation = window.location;

	if(isAllowedInHistory(currentLocation))
	{
		setNewHistory(currentLocation);
	}
}

