/**
 * Created by Hassan on 11/09/2019.
 */

(function($) {
    "use strict";

    if (jQuery().validate && jQuery().ajaxSubmit) {

        jQuery.validator.addMethod("phoneNumber", function (value, element) {
            return this.optional(element) || /^\s*(?:\+?(\d{1,3}))?([-. (]*(\d{3})[-. )]*)?((\d{3})[-. ]*(\d{2,4})(?:[-.x ]*(\d+))?)\s*$/.test(value);
        }, "Please specify the correct phone number");

        /* Contact Form Handler */
        var contact_loader = $('#contact-loader'),
            response_container = $('#response-container'),
            error_container = $("#error-container"),
            submit_button = $('#contact-form-submit'),
            contact_form = $('#contact_form');

        contact_loader.fadeOut('fast');

        var contact_options = {
            beforeSubmit: function () {
                contact_loader.fadeIn('fast');
                response_container.fadeOut('fast');
                submit_button.attr('disabled', 'disabled');
                contact_loader.fadeOut('fast');
            },
            success: function (ajax_response, statusText, xhr, $form) {
                var response = $.parseJSON(ajax_response);
                contact_loader.fadeOut('fast');
                submit_button.removeAttr('disabled');
                if (response.success) {
                    $form.resetForm();
                    response_container.html(response.message).fadeIn('fast');
                } else {
                    error_container.html(response.message).fadeIn('fast');
                }
            }
        };

        contact_form.validate({
            errorLabelContainer: error_container,
            submitHandler: function (form) {
                $(form).ajaxSubmit(contact_options);
            }
        });
    }

}(jQuery));