// pass in jQuery so we can use $ shortcut
(function($) {
	$.fn.follow = function(boundary, offset, paddingTop, paddingBottom) {
		if (offset == null)
		{
			offset = 0;
		}

		if (paddingTop == null)
		{
			paddingTop = 0;
		}
		
		if (paddingBottom == null)
		{
			paddingBottom = 0;
		}

		return this.each(function() {
			var follower = $(this);
			var container = follower.parent();

			container.css("position", "relative");
			follower.css("position", "absolute");

			$(window).scroll(function() {
				var scrollTop = $(document).scrollTop() + offset;
				var scrollBottom = scrollTop + follower.height();
				var boundaryTop = boundary.offset().top;
				var boundaryBottom = boundaryTop + boundary.height() - paddingBottom;
				var top = 0;
				
				if (scrollTop >= boundaryTop && scrollBottom <= boundaryBottom)
				{
					top = scrollTop - boundaryTop;
				}
				// too low
				else if (scrollBottom > boundaryBottom)
				{
					top = boundaryBottom - boundaryTop - follower.height();
				}
				// too high
				else if (scrollTop < boundaryTop)
				{
					top = 0;
				}
				
				follower.stop().animate({ top:top }, "fast");
			});
		});
	};
})(jQuery);