var stopScroll; // pull these variables out to increase their scope
var yOffset; 
var winwidth;

$(document).ready(function() {
    yOffset = $("#content-leftbar").offset().top;
    var scrollBottom = $(document).height() - $("#footer-wrapper").height();

	stopScroll = scrollBottom - $("#content-leftbar").height();
	/* if the window scrolls past the "stopScroll" point, the nav should no longer be fixed, but absolutely positioned at the point "stopScroll" */

	$(window).resize(function(){
		/* yOffset and the stopScroll point both change depending on the proportions of the window, so it resets them when you resize. */
		yOffset = $("#content-leftbar").offset().top;
		stopScroll = $(document).height() - $("#footer-wrapper").height() - $("#content-leftbar").height();
		var winwidth = $(window).width();
	});
   
    $(window).scroll(function() {
    	if ($(window).width() >= 600){
			/* this just checks first to see whether the window has scrolled past the stopScroll point */
			if($(window).scrollTop() >= stopScroll){
				$("#content-leftbar").css({
					'top': (stopScroll-yOffset),
					'position': 'relative'
				});
			} else if ($(window).scrollTop() > yOffset - 20) {
	    		$("#content-leftbar").css({
					'top': 20,
					'position': 'fixed'
				});
			} else {
	            $("#content-leftbar").css({
	                'top': 0,
	            	'position': 'relative'
				});
			}
		} else {
			$("#content-leftbar").css({
	                'top': 0,
	            	'position': 'relative'
			});
		}
	
	});

});
