// Bam Strategy ©2009
// By Simon-Pierre Alepin
// simon@bamstrategy.com / spalepin@gmail.com
// Last modification: 2009/08/26
// v 0.2

// USAGE /////////////////////////////////////////
// At the bottom of your page put within script tag
// $.verticalScrollFollower({id:'menu_follower', idStopper:'menu_follower_limit'});
// 'menu_follower' is the id of the div that will follow vertical scroll
// 'menu_follower_limit' is the empty div that is added as a position scroll limit (blocker)
// 
// It is possible instead to specify minimumY and a maximumY to the scrolling limits
// $.verticalScrollFollower({id:'menu_follower', minY:0, maxY:1000});

jQuery.verticalScrollFollower = function(params)
{
	var id             = (params.id != null) ? params.id:'';
	var idStopper      = (params.id != null) ? params.idStopper:'';
	var minY           = (params.minY != null) ? params.minY:$('#'+id).position().top;
	var maxY		   = (params.maxY != null) ? params.maxY:$('#'+idStopper).position().top;
	var scrollDelay    = (params.scrollDelay != null) ? params.scrollDelay:200;
	var renderingDelay = (params.renderingDelay != null) ? params.renderingDelay:250;
	var autoStart      = (params.autoStart == true || params.autoStart == false) ? params.autoStart:true;
	var timer          = 0;
	
	if(autoStart)
	{
		init();
	}
	
	function init()
	{
		timer = window.setInterval(followScroll, renderingDelay);
	}
	
	function getScrollTop() 
	{
		var pageOffset    = window.pageYOffset ? window.pageYOffset : 0;
		var scrollTop     = document.documentElement ? document.documentElement.scrollTop : 0;
		var bodyScrollTop = document.body ? document.body.scrollTop : 0;
		return scrollFilterResults( pageOffset, scrollTop, bodyScrollTop );
	};
	
	function scrollFilterResults(n_win, n_docel, n_body) {
		var n_result = n_win ? n_win : 0;
		if(n_docel && (!n_result || (n_result > n_docel)))
			n_result = n_docel;
		return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
	};

	function followScroll()
	{
		var currentScrollY = getScrollTop();
		var newPositionY   = -1;
		//alert(maxY);
		if(currentScrollY > minY && currentScrollY < (maxY - $('#'+id).height()))
		{
			newPositionY = currentScrollY;
		}else
		if(currentScrollY < minY)
		{
			newPositionY = minY;
			$('#'+id).css('top', minY+'px');
		}
		if(newPositionY != -1)
		{
			$('#'+id).animate({ top : newPositionY+"px" }, scrollDelay);
		}
	};
};