/**
 * Triggers the corresponding button if return is pressed inside a text or password field.
 * @class dtRewireSubmitButtons
 **/

/*jslint strict:false, plusplus:false*/
/*global DT:false*/

DT.CORE.register('dtRewireSubmitButtons', function (io, $) {
	return {
		init: function () {
			var inputs = $('input').filter('[type=text], [type=password], [type=submit]'),
				KB_RETURN = 13,
				bindTrigger = function (element, buttonId) {
					element.keypress(function (e) {
						if (e.keyCode === KB_RETURN) {
							$('#' + buttonId).trigger('click');
							return false;
						}
						return true;
					});
				},
				i, lastButton, current, type;
			for (i = inputs.length; i--;) {
				current = $(inputs[i]);
				type = current.attr('type');
				if (type === 'submit') {
					lastButton = current.attr('id');
				} else if (lastButton && (type === 'text' || type === 'password')) {
					bindTrigger(current, lastButton);
				}
			}
		}
	};
});
