var name					= "#menu";
var top_limit 		= 200;
var bottom_limit 	= 30;
var margin    = 10;
var slide_duration= 10;

var lastscroll=0;
var lastoffset=0;

$(window).scroll(function() { 
  // height of div
  divh = $(name).outerHeight();
  // height of document
  doch = $(document).height();
  // height of window
  winh = $(window).height();
  // scroll pos of document
  docs = $(document).scrollTop();
  // direction
  if (lastscroll>docs)
    dir = -1;
  else
    dir = 1;
  lastscroll = docs;
  offset = 0;
  // scrolled down past top limit  
  if (docs > top_limit) {
    if (winh>divh) {
      offset = lastoffset = docs+margin;
    } else {
	    // scrolled down past end of div
	    if (((docs-top_limit+winh) > divh) && (dir == 1)) {
        offset = lastoffset= docs-divh+winh-margin-bottom_limit;
	    }
	    // scrolling up
	    if (((docs-top_limit+winh) > 0) && (dir == -1)) {
	      // going up
	      if ((docs+margin)<lastoffset)  {
	        offset = docs+margin;
	        lastoffset=offset;
	      	$(name).animate({top:offset},{duration:slide_duration,queue:false});
	      }    
	    } 
	  }
  } else {
    offset = lastoffset = top_limit;
  }
  if (offset!=0)
  	$(name).animate({top:offset},{duration:slide_duration,queue:false});

});

var balken					= "#balken_unten";
var alles					= "#alles";
var slide_duration= 10;

function move_balken () { 
  // height of document
  doch = $(document).height();
  allh = $(alles).height();
  // balken is positioned under all other content
  // if content is smaller than window position it absolute to bottom of window 
  if (allh < doch) {
  	$(balken).css("position","absolute");
  	$(balken).css("bottom","0px");
  } else {
  	$(balken).css("position","static");
  }
}

$(window).resize(move_balken);
$(window).ready(move_balken);


