/**
*	@requires jQuery.keys
*	@requires jQuery.caret
*	
*	NOTE
*	The attr() method doesn't work when trying to set or return the value of the 'tabindex' in IE 
*	so we have to use $(selector).get(index).tabIndex for setting and returning. This might be only 
*	in the case when the tabIndex not predefined but added after the page loads via Javascript.
*/
(function($) {
	$.fn.extend({
		autoTab: function() {
			$$ = $(this);
			$$.each(function() {
				var i = $(this);
				// disallow any function keys
				var disallowedKeys = new Array(
					8, 9, 13, 16, 17, 18, 19, 20, 27,
					33, 34, 35, 36, 37, 38, 39, 40, 45, 
					46, 47, 92, 93, 112, 113, 114,
					115, 116, 117, 118, 119, 120, 121,
					122, 123, 144, 145
				);
				i.keydown(function(e) {
					var k = $.keyCode(e);
					if (i.val().length === 0 && k === 8)
						$$.filter(function(index) {
							return parseInt($$.get(index).tabIndex) == parseInt(i.get(0).tabIndex) - 1;
						})
						.focus()
						.caretToEnd();
					if (i.val().length === parseInt(i.attr('maxlength')) && $.inArray(k, disallowedKeys) === -1)
						$$.filter(function(index) {
							return parseInt($$.get(index).tabIndex) == parseInt(i.get(0).tabIndex) + 1;
						})
						.focus()
						.caretToEnd();
				});
				i.keyup(function(e) {
					var k = $.keyCode(e);
					if (i.val().length === parseInt(i.attr('maxlength')) && $.inArray(k, disallowedKeys) === -1)
						$$.filter(function(index) {
							return parseInt($$.get(index).tabIndex) == parseInt(i.get(0).tabIndex) + 1;
						})
						.focus()
						.caretToEnd();
				});
			});
			return $(this);
		},
		
		autoTabIndex: function() {
			$$ = $(this);
			for (var i = 0; i < $$.length; i++)
				$$.get(i).tabIndex = i+1;
		}
	});
})(jQuery)