(function($){
    $.fn.authform = function(options) {
        var opts = $.extend({
            onBefore: null,
            onAfter: null
        }, options || {}),

        form = null,
        isAuthByPhone = true,

        reset = function() {
            $("input:submit", form).attr("disabled", "disabled");
            isAuthByPhone = true;
            $("#auth-switcher span", form).addClass("pseudo-link");
            $("#switcher-phone", form).removeClass("pseudo-link");
            $("#auth-phone-block, #auth-email-block", form).hide();
            $("#auth-phone-block", form).show();
            $("#auth-phone, #auth-email, #auth-password", form).val("");
            $("#auth-error", form).html("").hide();
        },

        switcher = function(){
            $("#switcher-phone, #switcher-email").addClass("pseudo-link").bind("click", switcher);
            $(this).removeClass("pseudo-link").unbind("click", switcher);

            var id = $(this).attr("id").slice(9);
            isAuthByPhone = id == "phone" ? true : false;
            $("#auth-phone, #auth-email").val("").parent().hide();
            $("#auth-" + id).parent().show();
            validate();
        },

        validate = function() {
            var reg = {
                notempty : /\S+/,
                numbers : /^[0-9]+$/,
                email : /^([^@]+@.+\.[^.]+)$/,
                phone : /^[\+\(0-9][\s\-\(\)0-9]*$/
            },
            isPassword = reg.notempty.test($("#auth-password", form).val()),
            isValid = isAuthByPhone ? reg.numbers.test($("#auth-phone", form).val()) : reg.email.test($("#auth-email", form).val());

            $("input:submit", form).attr("disabled", "disabled");
            $("#switcher-phone, #switcher-email, label[for=auth-password]").removeClass("error");

            if (!isPassword) {
                $("label[for=auth-password]", form).addClass("error");
            }

            if (!isValid) {
                if (isAuthByPhone) {
                    $("#switcher-phone", form).addClass("error");
                } else {
                    $("#switcher-email", form).addClass("error");
                }
            }

            if (isValid && isPassword) {
                $("input:submit", form).removeAttr("disabled");
                $("#switcher-phone, #switcher-email, label[for=auth-password]", form).removeClass("error");
            }
        };

        return this.each(function() {
            form = $(this);
            reset();
            $("#switcher-phone, #switcher-email").bind("click", switcher);
            $("#auth-phone, #auth-email, #auth-password").bind("keyup blur", validate);
            validate();
        });
    };
})(jQuery);

