$(document).ready(function () {

  // sticky search box. Will not work in IE 6 
    var panel = $('#search-panel'); 
    var topmargin = 100;
    var panel_y = panel.offset().top-topmargin; 
    var panel_width = panel.width(); 
    var panel_height = panel.height();

    $(window).scroll(function(){ 
      // what the y position of the scroll is 
      var window_y = $(window).scrollTop(); 
      var window_x = $(window).scrollLeft();
      var viewportHeight = $(window).height();

      //handle horizontal scrolling only when using fixed positioning
      if ('fixed' == panel.css('position')) {
        panel.css({marginLeft:-window_x});
      } else {
        panel.css({marginLeft:0});
      };

      if (window_y >= panel_y) {
        // viewport is below the panel area
        if (viewportHeight>(panel_height)+topmargin) {
            //enough space for a margin and the box
            panel.css({position:'fixed',top:topmargin+'px', width: panel_width});
        } else if (viewportHeight>(panel_height) && window_y >= panel_y+topmargin-(viewportHeight-panel_height)) {
            //enough space for the box, but not all the margin
            panel.css({position:'fixed',top:(viewportHeight-panel_height)+'px', width: panel_width});
        } else {
            //not enough space, don't fix the position
            panel.css({position:'relative', top:0}); 
        }
      } else { 
        panel.css({position:'relative', top:0}); 
      } 
    });
  
});
