(function($) {

  $(document).ready(function() {
    
    // Used by functions below.
    var $thead = $("#models-compare-table .thead"),
        $floatdiv = $("#floatdiv"),
        $floatdivTable = $("#floatdiv table")
    
    refreshFloatingContents();
    
    // Initial positioning.
    var offset = $thead.offset();
    adjustLeftPos(offset);
    correctFloatingDiv();
    showHideBar(offset);
  
    // Events.
    $(window, document).resize(function () {
      correctFloatingDiv();
    });
  
    $(window).scroll(function() {
      // Get the offset once and reuse it, since it is an expensive operation.
      var offset = $thead.offset();
      if (showHideBar(offset)) {
        // Only adjust left pos if bar is visible.
        adjustLeftPos(offset);
      }
    });
  
    
    
    function refreshFloatingContents() {
      $floatdivTable
        .empty()
        .attr("width", $("#models-compare-table").width())
        .html($thead.clone());
      
      var $headers = $("#models-compare-table .thead td");
      $("#floatdiv table .thead td").each(function(i) { 
        var w = $headers.eq(i).width();
        $(this).css("width", w); 
      });
    }
  
    function correctFloatingDiv() {
  
      if($thead.offset() == null)
        return;
  
      // refreshFloatingContents();
      $floatdiv.css({'left':($("#models-compare-table").position().left).toString() + "px"});
  
      //$("#floatdiv table .thead tr td .chanBox .hideChannel .icon").click(function() { hideChannel($(this).parents("td").attr("class")); });
    }
    
    function adjustLeftPos(offset) {
  
      if(offset == null)
        return;
      
      var scrollLeft = $(window).scrollLeft(),
          newLeftMargin = '0';
      
      if(scrollLeft != 0) {
        newLeftMargin = (-1 * scrollLeft).toString() + "px";
      }
      $floatdivTable.css("marginLeft", newLeftMargin);
    }
  
    function showHideBar(offset) {
  
      if(offset == null)
        return;
      //
      // Determine whether floating div needs to be displayed
      //
      if(offset.top < $(window).scrollTop()) {
        $floatdiv.removeClass("hide");
        return true;
      } else {
        if(! $floatdiv.hasClass("hide")) {
          $floatdiv.addClass("hide");
        }
        return false;
      }
    }
    
  });
      
})(jQuery);
