/*
 * stickyfloat - jQuery plugin for verticaly floating anything in a constrained area
 * 
 * Example: jQuery('#menu').stickyfloat(100, 200, 300, 400);
 * parameters:
 * 		containerTop 	- Y location of top of object
 *		contanerHeight	- height of scrollable area
 *		offsetY			- the offset from the top when the object is animated
 *		duration		- animation speed
 * $Version: 05.16.2009 r1
 * Original Copyright (c) 2009 Yair Even-Or 
 * vsync.design@gmail.com
 */

$.fn.stickyfloat = function(containerTop, containerHeight, offsetY, duration) {
	
	var $obj = this;
	
	$obj.css({ position: 'absolute' });
	

	var bottomPos = containerHeight - $obj.height() + containerTop;
	if( bottomPos < 0 )
	{
		bottomPos = 0;
	}
	
	$(window).scroll(function () { 
		$obj.stop(); // stop all calculations on scroll event

		var pastStartOffset			= $(document).scrollTop() > containerTop;	// check if the window was scrolled down more than the start offset declared.
		var objFartherThanTopPos	= $obj.offset().top > containerTop;	// check if the object is at it's top position (starting point)
		var objBiggerThanWindow 	= $obj.outerHeight() < $(window).height();	// if the window size is smaller than the Obj size, then do not animate.
		
		// if window scrolled down more than startOffset OR obj position is greater than
		// the top position possible (+ offsetY) AND window size must be bigger than Obj size
		if( (pastStartOffset || objFartherThanTopPos) && objBiggerThanWindow ){ 
			var newpos = ($(document).scrollTop() + offsetY);
			if ( newpos > bottomPos )
				newpos = bottomPos;
			if ( $(document).scrollTop() < containerTop ) // if window scrolled < starting offset, then reset Obj position (opts.offsetY);
				newpos = containerTop;

			$obj.animate({ top: newpos }, duration );
		}
	});
};


