j$ = jQuery;

var speed = 20;
var sw = 0.35;
var beforeH;

j$(function(){
	j$("[href^='#']").each(function(index){
		j$(this).click(scrollEvent);
	});
	
});


function scrollEvent(eo) {
	var hlId = j$(this).attr('href');
	smoothScroll(hlId);
	return false;
}

function smoothScroll(hlId) {
	var targetH = j$(hlId).offset().top;
	var targetW = j$(hlId).offset().left;
	var w = j$(window);
	var sH = w.scrollTop();
	var wH = w.height();
	
	var delH = sH - targetH;
	
	var offset = delH * sw;
	var nextHeight = sH - offset;
	
	if (delH > 0) {
		if (delH < 10) {
			w.scrollTop(targetH);
		} else {
			w.scrollTop(nextHeight);
			var timerId =  setTimeout( 
				function () {
					smoothScroll(hlId);
					clearTimeout(timerId);
				},speed);
		}
	} else if (delH < 0) {
		if (delH > 10 || (beforeH == nextHeight)) {
			w.scrollTop(targetH);
		} else {
			w.scrollTop(nextHeight);
			var timerId =setTimeout(function () {
					smoothScroll(hlId);
					clearTimeout(timerId);
				},speed);
			beforeH = nextHeight;
		}
	} else {
		w.scrollTop(targetH);
	}
}

