var MENU_DIV_ID = "qlinks";
var PAGE_HEIGHT = 0;
var prevY = 0;

/**
 * This function will be called on page scroll to position the quick menu.
 */
function moveMenuOnScroll()
{
	var menuDivObj = window.document.getElementById(MENU_DIV_ID);
	var divTop = getTop(menuDivObj.parentNode);
	var scTop = window.pageYOffset || document.body.scrollTop || document.documentElement.scrollTop;
	var menuTop = 0;
	if(scTop > divTop)
	{
		menuTop = scTop - divTop;
		if((getViewportHeight() + scTop) > PAGE_HEIGHT)
		{
			menuTop = PAGE_HEIGHT - getViewportHeight();
		}
	}
	var topDiff = menuTop - prevY;
	while(topDiff != 0)
	{
		setTimeout("setTopPos(" + (menuTop - topDiff) + ")",500);
		topDiff = (topDiff > 0)? (topDiff-1):(topDiff+1);
	}
	prevY = menuTop;
}

function setTopPos(pos)
{
	var menuDivObj = window.document.getElementById(MENU_DIV_ID);
	menuDivObj.style.top = pos + "px";
}

/**
 * This function will be called on page load to get the pages actual height with scroll.
 */
function getPageHeightWithScroll()
{
	// Firefox
	if (window.innerHeight && window.scrollMaxY)
	{
		yWithScroll = window.innerHeight + window.scrollMaxY;
	}
	// all but Explorer Mac
	else if (document.body.scrollHeight > document.body.offsetHeight)
	{ 
		yWithScroll = document.body.scrollHeight;
	}
	// works in Explorer 6 Strict, Mozilla (not FF) and Safari
	else
	{ 
		yWithScroll = document.body.offsetHeight;
  	}
	PAGE_HEIGHT = yWithScroll;
}

/**
 * This function is called on scroll to get the height of the browser window.
 */
function getViewportHeight()
{
	if (window.innerHeight!=window.undefined)
	{
		return window.innerHeight;
	}
	if (document.compatMode=='CSS1Compat')
	{
		return document.documentElement.clientHeight;
	}
	if (document.body)
	{
		return document.body.clientHeight; 
	}
	return window.undefined; 
}

/**
 * This function is called on scroll to get the absolute top value of the quick menu.
 */
function getTop(obj)
{
	var curtop = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	}
	else if (obj.y)
	{
		curtop += obj.y;
	}
	return curtop;
}

function getLeft(obj)
{
	var curleft = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curleft += obj.offsetWidth;
			obj = obj.offsetParent;
		}
	}
	else if (obj.x)
	{
		curleft += obj.x;
	}
	return curleft;
}

/**
 * This function is called to add events to object.
 */
function addEvent(object, evType, func)
{
	if (object.addEventListener)
	{
		object.addEventListener(evType, func, false);
	}
	else if (object.attachEvent)
	{
		object.attachEvent("on"+evType.toString(), func);
	}
}

addEvent(window, "scroll", moveMenuOnScroll);
addEvent(window, "load", getPageHeightWithScroll);