/*

scrollPoint v1.1.

Eg. :

$('.selector').scrollPoint({
	scrollPoint : 'bottom',
	offset : 100,
	pointClass : 'fixed',
	afterPointCallback : function( $this, amt ){
		console.log('after');
	},
	beforePointCallback : function( $this, amt ){
		console.log('before');
	},
	continualCallback : false
});

*/

(function($){
	$.fn.scrollPoint = function(opts) {
		var o = {
			scrollPoint :			'top', // 'top','bottom', numeric value,
			offset :				0,
			pointClass :			'fixed',
			beforePointCallback :	null,
			afterPointCallback :	null,
			continualCallback :		false
		};
		
		$.extend( true, o, opts );
		var $window					= $(window);
		
		return this.each(function(){


/*==================== CACHE SELECTORS & SET VARS ====================*/

			
			var $this				= $(this);
			$this.data({
				'origPosition' :	$this.offset().top,
				'origHeight' :		$this.outerHeight(true)
			});
			var isAlreadyAfter		= false;


/*==================== BIND EVENTS & CALL INTIAL FUNCTIONS ====================*/

			
			$window.scroll(function(){scrollPointCallback();}).resize(function(){scrollPointCallback();});
			scrollPointCallback();


/*==================== CALL SCROLL & RESIZE CALLBACKS ====================*/
			
			
			function scrollPointCallback(){
				var scrollAmt		= $window.scrollTop();
				var scrollPostion	= getScrollPosition();
				
				// After scrollPoint. //
				if( scrollAmt >= scrollPostion ){
					if( o.continualCallback ){
						if( o.afterPointCallback ) o.afterPointCallback( $this, scrollAmt );
					}else{
						if( !isAlreadyAfter && o.afterPointCallback ) o.afterPointCallback( $this, scrollAmt );
					}
					$this.addClass(o.pointClass);
					isAlreadyAfter	= true;
				
				// Before scrollPoint. //
				}else{
					if( o.continualCallback ){
						if( o.beforePointCallback ) o.beforePointCallback( $this, scrollAmt );
					}else{
						if( isAlreadyAfter && o.beforePointCallback ) o.beforePointCallback( $this, scrollAmt );
					}
					$this.removeClass(o.pointClass);
					isAlreadyAfter	= false;
				}
			}
			

/*==================== CALCULATE SCROLL POSITION ====================*/

			
			function getScrollPosition(){
				var scrollPostion = o.scrollPoint;
				if( o.scrollPoint == 'top' ) scrollPostion = $this.data('origPosition');
				else if( o.scrollPoint == 'bottom' ) scrollPostion = $this.data('origPosition')-$window.height()+$this.data('origHeight');
				
				return scrollPostion+o.offset;
			}
			
			return this;
		});
	};
})(jQuery);

