

function $__Scroll() {
    this.initialize();
}

$__Scroll.prototype.initialize = function() {
	var self = this;
	var node = document.getElementById('gototop').getElementsByTagName('a')[0];
	node.ref = node.getAttribute('href', 2).replace(/.*#/, '');
	node.href = 'javascript:void(0);';
	node.onclick = function() { self.slideTo(this.ref); }
}


$__Scroll.prototype.slideTo  = function(node) {
	var self = this;
	var targetNode = document.getElementById(node);
	if(!targetNode) { return; }

	var getNodePosition = function() {
		var position = {
			x: 0,
			y: 0
		};
		return position;
	}

	var getPageProperty = function() {
		var property = {};

		property.inner = {
			width : window.innerWidth  || document.documentElement.clientWidth  || document.body.clientWidth,
			height: window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight
		}

		property.maximum = {
			width : document.body.scrollWidth || document.body.offsetWidth,
			height: window.innerHeight + window.scrollMaxY || document.body.scrollHeight || document.body.offsetHeight
		}

		property.offset = {
			x: window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft,
			y: window.pageYOffset || document.documentElement.scrollTop  || document.body.scrollTop
		}

		return property;
	}

	var slideY = function() {
		var duration = 30;
		var millisec = 10;
		var count = 0;

		var pageProperty = getPageProperty();
		var nodePosition = getNodePosition();
		var scrollLimitY = pageProperty.maximum.height - pageProperty.inner.height;
		var finishPoint  = Math.min(nodePosition.y, scrollLimitY);
		
		var motion = setInterval(
			function() {
				var prop = getPageProperty();
				var offsetPoint = prop.offset.y;
				var offsetDelta = Math.abs(offsetPoint - finishPoint);
				var offsetRatio = Math.floor( Math.max(offsetDelta / duration) * count++ ) + 1;
				
				var direction   = ((offsetPoint - finishPoint) > 0) ? -1 : 1;
				var variation   = Math.min(offsetRatio, offsetDelta) * direction;

				window.scrollBy(0, variation);
				if(offsetDelta <= 1) {
					clearInterval(motion);
					//if(!self.isSafari) { location.hash = node; }
				}
			},
			millisec
		);
		
		setTimeout(
			function() { clearInterval(motion); },
			duration * millisec * 3
		);
	}
	
	slideY();
}

$__Scroll.prototype.isSafari = Boolean(navigator.appVersion.indexOf('KHTML') > -1);


new $__Scroll();


