(function($) {
    // Look for an element based on ID or name
    var check_element = function(name) {
        var obj = null;
        var check_id = $('#' + name);
        var check_name = $('input[name=' + name + ']');
        if(check_id.length)
            obj = check_id;
        else if(check_name != undefined)
            obj = check_name;
        return obj;
    };

  
    /**
 * Provides the autotabbing mechanism for the supplied element and passes
 * any formatting options to autotab_filter.
 * 
 * Refer to autotab_filter's description for a detailed explanation of
 * the options available.
 * 
 * @name	autotab
 * @param	options
 * @example	$('#phone').autotab({ format: 'number' });
 * @example	$('#username').autotab({ format: 'alphanumeric', target: 'password' });
 * @example	$('#password').autotab({ previous: 'username', target: 'confirm' });
 */
    $.fn.autotab = function(options) {
        var defaults = {
            target: null,
            previous: null
        };

        $.extend(defaults, options);

        // Sets targets to element based on the name or ID
        // passed if they are not currently objects
        if(typeof defaults.target == 'string')
            defaults.target = check_element(defaults.target);

        if(typeof defaults.previous == 'string')
            defaults.previous = check_element(defaults.previous);

        // Go to the previous element when backspace
        // is pressed in an empty input field
        return $(this).bind('keydown', function(e) {
            if(e.shiftKey && e.which ==9 && defaults.previous){
                defaults.previous.focus();
            } else if(e.which ==9 && defaults.target){
                defaults.target.focus();
                return false;
            }
        });
    };

})(jQuery);
