/*
 * jQuery intoViewport Plugin
 * Scrolls an set of Elements into the browsers viewport, but only if neccesary and only minimum amount
 * @author Bernhard Häussner
 * @version 1.0
 * @url 
 * @licence http://www.gnu.org/licenses/gpl.html
 * @example $('a').eq(4).intoViewport(); // this ensures the 4th link on page is visible to user
 * Default Options: $('a').eq(4).intoViewport({duration:200,   easing:"swing" });
 * Example Options: $('a').eq(4).intoViewport({duration:"slow",easing:"linear"});
 * For all options see http://docs.jquery.com/Effects/animate#paramsoptions
 */
(function($) {
	jQuery.fn.intoViewport = function(options) {
		options = $.extend({
			// Configuration
			// Add whatever options animate schould get by default
			duration:  200,
			easing: "swing"
		}, options || {});
		return this.each(function(){
			// scroll to certain destination:
			function scrTo(dest) {
				$("html,body").stop().animate({ scrollTop: dest}, options );
			}
			var
				//current viewport Y-position
				scr=$(document).scrollTop()||$(window).scrollTop() 
				// viewport Y-size
				wheight=$(window).height(),
				// element Y-position
				top=$(this).offset().top,
				// element Y-size
				eheight=$(this).outerHeight();
			// case element before viewport:
			if (scr>top) {
				scrTo(top); // scroll up to element
			// case viewport before element (bottom part of e. outside):
			} else if (scr!=top && top+eheight>scr+wheight) { 
				// scroll down till everything is inside
				scrTo(top+Math.min(eheight-wheight,0));
				//              ^ but don't hide top part again
			}
		});
	};
})(jQuery); //compatibility
