// Custom Static Sidebar
//
// By Soap Media
$(document).ready(function () {  

	if ($('#right-sidebar').length) { // Check if the sidebar exists - implies *not* zero...
    
	var top = $('#right-sidebar').offset().top - parseFloat($('#right-sidebar').css('marginTop').replace(/auto/, 0));

  $(window).scroll(function (event) {
	  
    // What the y position of the scroll is
    var y = $(this).scrollTop();
	
	// Get all the other measurements
	var sidebar = jQuery('#right-sidebar');
	var tp = y + jQuery(sidebar).height();
	var w = jQuery(window).width();
	var d = 332; // Distance from bottom in pixels for when to stop scrolling
	var h = jQuery(document).height(); 
	
	if (y >= top) {
		jQuery(sidebar).css('top','0px');
		$('#right-sidebar').addClass('fixed');
	} else {
		$('#right-sidebar').removeClass('fixed');
	}
	
	if (tp >= (h-d)){
		$('#right-sidebar').removeClass('fixed');
      	jQuery(sidebar).css('top',h-d-top-jQuery(sidebar).height());
	}
	
	// turn this off for IE6 as it doesn't support fixed positions
	if ($.browser.msie && $.browser.version.substr(0,1) === '6') {
      $('#right-sidebar').css("position","absolute");
	}

  });
	
  }

});
