(function ($) {
	$.fn.fieldsetsubmit = function (options) {
		/// <summary>
		///	Creates an event listener for fieldsets listening for the enter/return key.
		/// If the enter/return key is pressed when the fieldset has focus, the action of the first a, button or input element
		/// with a class name matching the supplied class name prefix is fired.
		/// </summary>

		// settings. defaults are overridden by available options. options argument is not modified.
		var settings = $.extend({}, $.fn.fieldsetsubmit.defaults, options);
		var classnamePrefixLength = settings.classPrefix.length;

		var initFormSubmitKeyListener = function (element) {
			$(element).find('fieldset[class*=' + settings.classPrefix + ']').bind('keypress', function (e) {
				var i;
				var classname;
				var classnames;
				var $button;
				var $buttons;
				var $parentFieldset;
				var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
				var target = e.target.tagName.toLowerCase();

				if (target !== 'input') {
					// do nothing if the focused element isn't an input element.
					return;
				}

				if (key !== 13) {
					// do nothing if the key pressed isn't enter/return.
					return;
				}

				e.preventDefault();
				$parentFieldset = $(e.target).parents('fieldset').filter('[class*=' + settings.classPrefix + ']').eq(0);

				if ($parentFieldset.length < 1) {
					return;
				}

				classnames = $parentFieldset.attr('class').split(' ');

				for (i = 0; classname = classnames[i]; i++) {
					if (classname.slice(0, classnamePrefixLength) === settings.classPrefix) {
						$buttons = $($parentFieldset.find('a.' + classname + ', button.' + classname + ', input.' + classname, $(this)).eq(0));

						if ($buttons.length > 0) {
							$button = $($buttons.get(0));

							if (typeof ($button.onclick) === 'function') {
								// the button has a listener bound to its click event, we trigger the click.
								$button.trigger('click');
							} else if ($button.attr('href')) {
								// the button is an a element with a href attribute, we follow its url.
								window.self.location = $button.attr('href');
							} else {
								// simulate a click.
								$button.trigger('click');
							}
						}

						break;
					}
				}
			});
		};

		return this.each(function () {
			initFormSubmitKeyListener(this);
		});
	};
	
	// default settings.
	$.fn.fieldsetsubmit.defaults = {
		classPrefix: 'defaultsubmit-' // The prefix of a classname of an input element.
	};
	
})(jQuery);
