// pixels per frame
var scroll_speed = 75;

// Starts scroll
function autoScroll(id) {	
	// Get amount of scroll needed to get to correct area
	if (id == 'top') {
		var y = 0;
	}
	else {
		obj = document.getElementById(id);
		var y = absPos(obj, 1);
	}
	
	/* If item position's scroll exceeds height of document,
	 set scroll to the scroll at the end of the doc */
	if (window.innerHeight) {
		var end_scroll = document.documentElement.offsetHeight - window.innerHeight;
	}
	else {
		var end_scroll = document.documentElement.scrollHeight - document.documentElement.clientHeight;
	}
	
	if (end_scroll < y) {
		y = end_scroll;
	}
	
	// Set original scroll position for easing
	origY = getY();
	
	// Start animation
	if (origY <= y) {
		scrollDownTo(y);
	}
	else {
		scrollUpTo(y);
	}
}

var origY;
function scrollDownTo(y) {
	// Get value of scroll Y
	cur_scroll = getY();
	
	// Calculate amount to scroll (with easing)
	var perc = (y - cur_scroll) / (y - origY);
	var dist = Math.ceil(scroll_speed - (scroll_speed * (1 - perc))) + 1;
	
	// If scroll hasn't reached anchor, do another frame of animation
	if (cur_scroll + dist < y) {
		var scroll_to = cur_scroll + dist;
		
		// Go to new scroll value
		window.scrollTo(0, scroll_to);
		
		// Call recursively for animation
		setTimeout('scrollDownTo(' + y + ')', 30);
	}
	// Otherwise, set scroll to the exact position of the anchor
	else {
		window.scrollTo(0, y);
	}
}

function scrollUpTo(y) {
	// Get value of scroll Y
	cur_scroll = getY();
	
	// Calculate amount to scroll (with easing)
	var perc = (cur_scroll - y) / (origY - y);
	var dist = Math.ceil(scroll_speed - (scroll_speed * (1 - perc))) + 1;
	
	// If scroll hasn't reached anchor, do another frame of animation
	if (cur_scroll - dist > y) {
		var scroll_to = cur_scroll - dist;
		
		// Go to new scroll value
		window.scrollTo(0, scroll_to);
		
		// Call recursively for animation
		setTimeout('scrollUpTo(' + y + ')', 30);
	}
	// Otherwise, set scroll to the exact position of the anchor
	else {
		window.scrollTo(0, y);
	}
}

// Returns current scroll amount
function getY() {
	if (document.documentElement.scrollTop) {
		return document.documentElement.scrollTop;
	}
	else {
		return document.body.scrollTop
	}
}

// Returns absolute position of an object
function absPos(obj, axis) { // 0 is X, 1 is Y
	var o = 0;
	if (axis == 0) {
		while (obj) {
			o += obj.offsetLeft;
			obj = obj.offsetParent;
		}
	}
	else {
		while (obj) {
			o += obj.offsetTop;
			obj = obj.offsetParent;
		}
	}
	return o;
}