/*
 * stickyfloat - jQuery plugin for verticaly floating anything in a constrained area
 * 
 * Example: jQuery('#menu').stickyfloat({duration: 400});
 * parameters:
 * 		duration 	- the duration of the animation
 *		startOffset - the amount of scroll offset after it the animations kicks in
 *		offsetY		- the offset from the top when the object is animated
 *		lockBottom	- 'true' by default, set to false if you don't want your floating box to stop at parent's bottom
 * $Version: 05.16.2009 r1
 * Copyright (c) 2009 Yair Even-Or
 * vsync.design@gmail.com
 */

$.fn.stickyfloat = function(options)
{
	if (!this.length || !window.XMLHttpRequest)
	{
		return;
	};
	
	var $sticky = this;
	var opts = $.extend({
		contentElement: null,
		cloneProperties: ['float']
	}, options);
	
	if (!opts.contentElement || !opts.contentElement.length)
	{
		return;
	}

	var sticky = {
		'top': $sticky.offset().top,
		'height': $sticky.outerHeight()
	};
	var content = {
		'top': $(opts.contentElement).offset().top,
		'height': $(opts.contentElement).outerHeight()
	}
	sticky.bottom = sticky.top+sticky.height;
	content.bottom = content.top+content.height;
	
	if (sticky.bottom >= content.bottom)
	{
		return;
	}
	
	var clone = $('<div class="sfClone"></div>');
	clone.css({'height': content.height, 'width': $sticky.outerWidth()});
	
	for (var i = 0; i < opts.cloneProperties.length; i++) {
		clone.css(opts.cloneProperties[i], $sticky.css(opts.cloneProperties[i]));
	};
	
	$sticky.css({'position':'absolute','top':sticky.top});
	$sticky.after(clone);
	
	var handler = function ()
	{ 
		$sticky.stop(); // stop all calculations on scroll event
		
		if (document.documentElement.scrollTop > sticky.top)
		{
			if ((document.documentElement.scrollTop + sticky.height) >= content.bottom)
			{
				$sticky.css({'position':'absolute', 'top': content.bottom - sticky.height});
			}
			else
			{
				$sticky.css({'position':'fixed', 'top':'0'});
			}
		}
		else
		{
			$sticky.css({'position':'absolute', 'top':'auto'});
		}
	}
	
	$(window).scroll(handler);
	handler();
};
