(function($) {

$.extend($.fn, {
  submitLocker: function( options ) {
    if (!this[0]) return;
    var submitLocker = $.data(this[0], 'submitLocker');
		if (submitLocker) { return submitLocker }
    submitLocker = new $.submitLocker( options, this[0] );
    $.data(this[0], 'submitLocker', submitLocker);
    return submitLocker;
  }
})

$.submitLocker = function( options, button ) {
	this.settings = $.extend( {}, $.submitLocker.defaults, options );
	this.button = $(button);
	this.init();
};

$.extend($.submitLocker, {
	defaults: {
    submitText: "Please wait..."
  },

  prototype: {
		init: function() {
      this.button.bind("click", { submitLocker: this }, function(event) {
        event.data.submitLocker.lock();
      });

      // jquery.validate.js integration: automatically unlock the button when
      // form validation has failed so that the user may re-submit.
      $(this.button[0].form).bind("invalid-form", { submitLocker: this }, function(event) {
        event.data.submitLocker.unlock();
      });

      this.originalButtonState = {
        name: this.button.attr("name"),
        value: this.button.val()
      }

      this.lockedButtonState = {
        name: this.originalButtonState.name +"DISABLED",
        value: this.settings.value
      }
    },

    // Based on the LGPL licensed jQuery.lockSubmit.js v 1.02 from
    // http://blog.leenix.co.uk/2009/09/jquery-plugin-locksubmit-stop-submit.html
    lock: function() {
      this.lockedButtonState.hiddenReplacement = this.button.after(
        "<input type='hidden' name='"+this.originalButtonState.name+"' value='"+this.originalButtonState.value+"'>"
      ).next();

			if (this.lockedButtonState.value) { this.button.val(this.lockedButtonState.value); }

			this.button.attr("name", this.lockedButtonState.name);
    },

    unlock: function() {
      if (this.lockedButtonState.hiddenReplacement) { this.lockedButtonState.hiddenReplacement.remove() }

			this.button.attr("name", this.originalButtonState.name);
      this.button.val(this.originalButtonState.value)
    }
  }
});

})(jQuery);