$j=jQuery.noConflict();
j$=jQuery.noConflict();

// Sidebar-hud
$j(document).ready(function(){
  
  // checks if sidebar-hud is even present
  if($j("#sidebar-hud").length > 0){
  
    //variables set on load
    var top = $j('#sidebar-hud').offset().top-20 - parseFloat($j('#sidebar-hud').css('margin-top').replace(/auto/, 0));
    var sdmargin = 70;
    var sidebarheight = $j('#sidebar-hud').height() + sdmargin;
    var footerheight = $j('#footer').height() + 35;
    
      
    $j (window).scroll(function () {
      
        //Variables set durring scroll
        var y = $j(window).scrollTop(); 
        var documentheight = $j(document).height(); 

      

        if (y >= top && $j(window).height() > sidebarheight) {          	
            	if (documentheight - sidebarheight - footerheight <= y)  {
            	  // when it reaches bottom
                $j('#sidebar-hud').removeClass('fixed');
                $j('.sidebar-hud-wrapper').addClass('fixedtobottom');
              } else {
                // the top where it begins scolling
                $j('#sidebar-hud').addClass('fixed');
              	$j('.topofpage').show('fast');
                $j('.sidebar-hud-wrapper').removeClass('fixedtobottom');      
              }
            
          	
        } else {
            // when top is reached
            $j('.topofpage').hide('fast');
            $j('#sidebar-hud').removeClass('fixed');
            $j('.sidebar-hud-wrapper').removeClass('fixedtobottom');
        }
      

      
      
  }); // ends windos.scroll
  
 }; // ends if sidebar exists
  
});
