(function()
{
	var getBounds = function(_elm)
	{
		if(_elm==null) _elm = document.getElementsByTagName("body")[0];
		var width = _elm.offsetWidth;
		var height = _elm.offsetHeight;
		var left = _elm.offsetLeft;
		var top = _elm.offsetTop;
		while(_elm.offsetParent)
		{
			_elm = _elm.offsetParent;
			left += _elm.offsetLeft;
			top += _elm.offsetTop;
		}
		var right = left + width;
		var bottom = top + height;
		return {left:left, top:top, right:right, bottom:bottom, width:width, height:height};
	}
	var execute = function(e)
	{
		var nodelist = document.getElementsByTagName("a");
		for(var i=0; i<nodelist.length; i++)
		{
			var elm = nodelist[i];
			if(elm.href.match(/([html|\/]\#.+)/))
			{
				var onclick = (function(_elm)
				{
					return function(e)
					{
						if(e.preventDefault) e.preventDefault();
						else event.returnValue = false;
						
						var speed = 0.5;
						var bounds = getBounds(
							document.getElementById(
								_elm.href.substring(
									_elm.href.indexOf("#")+1
								)
							)
						);
						
						var scrollBottom = document.documentElement.scrollHeight
										   -document.documentElement.clientHeight;
						var destination = (bounds.top<scrollBottom)
										  ?bounds.top
										  :scrollBottom;
						if(destination<0) destination = 0;
						
						var old = null;
						var interval = setInterval(function()
						{
							var current = document.documentElement.scrollTop||document.body.scrollTop;
							var distance = (destination - current);
							
							window.scrollTo(0, current+distance*speed);
							
							if(Math.abs(distance)<(1/speed)||current==destination)
							{
								window.scrollTo(0, destination);
								clearInterval(interval);
							}
							old = current;
							
						}, 33);
					}
					
				})(elm);
				
				if(elm.addEventListener) elm.addEventListener("click", onclick, false);
				else if(elm.attachEvent) elm.attachEvent("onclick", onclick);
			}
		}
	}
	if(window.addEventListener) window.addEventListener("load", execute, false);
	else if(window.attachEvent) window.attachEvent("onload", execute);
})();
