var AjaxForm = {
    init: function (element) {
        this.form = $(element);
        this.inputs = this.form.find('input[type=text], textarea');
        this.submit = this.form.find("input[id$=saveContact]")
        this.errorMessage = this.form.find('.error_message');

        this.attachEvents(element);
        this.clearInputs();
    },

    attachEvents: function (element) {
        var that = this;

        this.submit.click(function () {
            var valid = that.validation();
            if (valid) {
                that.errorMessage.hide();
                return true;
            }
            else {
                that.errorMessage.show();
                return false;
            }
        });

    },

    validation: function () {
        var required = $('.required'),
        valid = true,
        errorCheck = [],
        that = this;

        $(required).each(function () {
            has_error = that.hasError(this);
            errorCheck.push(has_error);
        });

        $(errorCheck).each(function (error) {
            valid = valid && errorCheck[error];
        });

        return valid;
    },

    hasError: function (input) {
        // Regex 
        var email_regex = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;

        if ($(input).val() == '') {
            $(input).addClass('error');
        } else {
            $(input).removeClass('error');
        }


        if (!$("input[id$=txtEmail]").val().match(email_regex)) {
            $("input[id$=txtEmail]").addClass('error');
            $('#email_exception').show();
        } else {
            $("input[id$=txtEmail]").removeClass('error');
            $('#email_exception').hide();
        }

        return !!(!$(input).hasClass('error'));
    },

    clearInputs: function () {
        this.inputs.each(function () {
            $(this).val('');
        });
    }
};

$(AjaxForm.init('#contactUs_Form'));

