(function($) {
  // Disables a related field based on the status of the checkbox this 
  // plugin is attached to.
  $.fn.disableField = function(field, options) {
    var opts = $.extend({}, $.fn.disableField.defaults, options);
    
    return this.each(function() {
      var $this = $(this);
      if ($this.length) {
        var checkbox_value = $this.click(function(e) {
          toggleRelatedField($this.attr('checked'), e);
        }).attr('checked');
        toggleRelatedField(checkbox_value);
      };
    });

    // private function for debugging
    function debug($obj) {
      if (window.console && window.console.log)
        window.console.log($obj);
    };
    
    function toggleRelatedField (checked, event) {
      var related_field = $(field).attr('disabled', checked);
      if (checked) {
        if (event) opts.beforeDisable.call();
        related_field.addClass('disabled');
        if (event) opts.afterDisable.call();
      } else {
        if (event) opts.beforeEnable.call();
        related_field.removeClass('disabled');
        if (event) opts.afterEnable.call();
      }
    };
    
  };
  
  $.fn.disableField.defaults = {
    beforeDisable : function() {},
    afterDisable  : function() {},
    beforeEnable  : function() {},
    afterEnable   : function() {}
  };
  
})(jQuery);

// This plugin design pattern taken from: http://www.learningjquery.com/2007/10/a-plugin-development-pattern
