var topbar;
var bottomPosition = 50;

$(function()
  {
    $(window).resize(function() {
      windowscroll(true); 
    });
    
    topbar = $('#topbar');
    windowscroll(false);
  }
);

$(function()
  {
    $(window).scroll(function() {
      windowscroll(true); 
    });
    
    topbar = $('#topbar');
    windowscroll(false);
  }
);

function windowscroll(animate)
{
  
  //$('#txtdebug').html('Window height: ' + $(window).height() + ' Scrollposition: ' + $(document).scrollTop());

  var windowHeight = $(window).height();
  var scrollposition = $(document).scrollTop();
  
  var margintop = windowHeight + scrollposition - bottomPosition - 170;
  if(margintop < 0)
    margintop = 0;
  
  if(animate) {
    topbar.stop().animate({top: margintop+'px'});
  } else {
    topbar.css('top', margintop+'px');
  }
}
