RightFollow = {
	init: function(){
		if($('#right-follow').length==1){
			var top = $('#right-follow').offset().top - parseFloat($('#right-follow').css('marginTop').replace(/auto/, 0));
			$(window).scroll(function (event) {
				var rightFollow = $('#right-follow');
				var container = $('body > .container');
				var containerBottom = container.offset().top + container.height();
			    var scrollTop = $(this).scrollTop();
			    var thisTop = rightFollow.offset().top;			    
			    var parentTop = rightFollow.parent().offset().top;
			    var thisHeight = rightFollow.outerHeight();
			    var thisBottom = thisTop + thisHeight;
			    var availableTop = thisTop - scrollTop;
			    var isFixedBottom = rightFollow.hasClass("fixed-bottom");
			    var isFixed = rightFollow.hasClass("fixed");
			    var isScrolledPast = scrollTop >= top;
			    var isScrollTopAvailable = (availableTop > 0 && ((thisBottom + 20 - availableTop) < containerBottom));
			    var isScrolledToBottom = (thisBottom + 20) >= containerBottom;
			    var isScrolledToTop = scrollTop < top;
			    
			    if(!isFixed && !isFixedBottom){
			    	if(isScrolledPast){
				    	rightFollow.css('top','0px');
				    	rightFollow.addClass('fixed');
			    	}
			    }else if(isFixed){
			    	if(isScrolledToBottom){
			    		rightFollow.removeClass('fixed');			    		
			    		rightFollow.css('top', (containerBottom - 20 - thisHeight - parentTop));
			    		rightFollow.addClass('fixed-bottom');
			    	}else if(isScrolledToTop){
			    		rightFollow.removeClass('fixed');
			    		rightFollow.css('top', '0px');
			    	}
			    }else if(isFixedBottom){
			    	if(isScrollTopAvailable){
			    		rightFollow.removeClass('fixed-bottom');
				    	rightFollow.css('top','0px');
				    	rightFollow.addClass('fixed');
			    	}
			    }
			});
		}
	}
};
$(document).ready(function () {  
  	RightFollow.init();
});
