;(function ($){
  
  /**
   * jQuery plugin for the basic materials and technology comparators. Pass in
   * the maximum number of items allowed to be compared.
   *
   * @param int
   * @return jQuery
   */
  $.fn.comparator = function (max_checked_items){
    return this.each(function (){
      var $self = $(this);
      var $checkboxes = $self.find(":checkbox").attr({ checked: false });
      
      /**
       * Checks whether we've reached the maximum number of checked checkboxes,
       * and if so, disables all the unchecked ones. And if none is checked,
       * disables the submit button(s) as well.
       */
      function checkMarkedBoxes(){
        var nchecked = $checkboxes.filter(":checked").size();

        if (nchecked >= max_checked_items){
          $checkboxes
            .not(":checked")
              .attr("disabled", true)
              .closest("label")
                .attr("title", "Only " + max_checked_items + " items can be compared at a time.");
        } else {
          $checkboxes.attr("disabled", false).closest("label").attr("title", "");
        }
        
        // probably multiple submit buttons
        var $button = $self.closest("form").find(":submit");
        if (nchecked == 0){
          $button.attr({ disabled: true, title: "Please select at least one item from the table below." });
        } else {
          $button.attr({ disabled: false, title: "" });
        }

      }

      // bind the event handler
      $checkboxes
        .click(checkMarkedBoxes)
        .each(function (){

          // all we're trying to do here is give users a big click target
          var $self = $(this);
          var $parent = $self.closest("td");

          // pseudo-centering, plus a little fudge
          var px = Math.floor(($parent.width() - $self.width()) / 2) - 15;
          // var py = Math.floor(($parent.height() - $self.height()) / 2) - 5;
          var py = 20;

          $self.wrap($("<label>").css("padding", py + "px " + px + "px"));
        });

      // some browsers keep forms filled out upon reload
      checkMarkedBoxes();
    });
  };
})(jQuery);
