var scrollTimer;

function _getScrollX(){
	if(document.documentElement && !isNaN(document.documentElement.scrollLeft) && document.documentElement.scrollLeft > 0){return document.documentElement.scrollLeft;}
	else if(document.body && !isNaN(document.body.scrollLeft) && document.body.scrollLeft > 0){return document.body.scrollLeft;}
	else if(!isNaN(window.pageXOffset) && window.pageXOffset > 0){return window.pageXOffset;}
	else if(!isNaN(window.scrollX) && window.scrollX > 0){return window.scrollX;}
	else{return 0;}
}

function _getScrollY(){
	if(document.documentElement && !isNaN(document.documentElement.scrollTop) && document.documentElement.scrollTop > 0){return document.documentElement.scrollTop;}
	else if(document.body && !isNaN(document.body.scrollTop) && document.body.scrollTop > 0){return document.body.scrollTop;}
	else if(!isNaN(window.pageYOffset) && window.pageYOffset > 0){return window.pageYOffset;}
	else if(!isNaN(window.scrollY) && window.scrollY > 0){return window.scrollY;}
	else{return 0;}
}

function stepScrollToTop(frame_count, wait_time, current_x, current_y){
	if(isNaN(frame_count) || frame_count < 0){frame_count = 3;}
	if(isNaN(wait_time)   || wait_time   < 0){wait_time   = 50;}
	if(!current_x){current_x = _getScrollX();}
	if(!current_y){current_y = _getScrollY();}
	
	if(scrollTimer){
		window.clearTimeout(scrollTimer);
		scrollTimer = null;
	}
	
	var scroll_x;
	var scroll_y;
	scroll_x = _getScrollX();
	scroll_y = _getScrollY();
	var next_x;
	var next_y;
	next_x = (scroll_x > 0) ? current_x + scroll_x * -1 / frame_count : 0;
	next_y = (scroll_y > 0) ? current_y + scroll_y * -1 / frame_count : 0;
	if(next_x < 0){next_x = 0;}
	if(next_y < 0){next_y = 0;}
	
	window.scrollTo(Math.floor(next_x), Math.floor(next_y));
	
	if(next_x != 0 || next_y != 0){
		scrollTimer = window.setTimeout(
			"stepScrollToTop("+
			frame_count+", "+
			wait_time+", "+
			next_x+", "+
			next_y+
			")",
			wait_time);
	}
}

