﻿$(document).ajaxStart(function () {
 $("#ajax-busy").show();
 });
 $(document).ajaxStop(function (){
 $("#ajax-busy").hide();
 });

$(function () {

    $("#btn-submit").click(function () {
        // validate and process form here  

        if (ValidateFields()) {

            var myMailerRequest = { name: $("input#contact-name").val(), email: $("input#contact-email").val(),
                phone: $("input#contact-phone").val(), message: $("textarea#contact-message").val()
            };

            var data = $.toJSON(myMailerRequest)

            $.ajax({
                type: "POST",
                url: "dataService.asmx" + "/" + "SubmitBooking",
                data: data,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    if (response.d) {
                        $('#contact-form').hide()
                        $('#contact-form').html("<div id='message'></div>");
                        $('#contact-form').fadeIn(500, function () {
                            $('#message').html("<h3>Thank you for your enquiry!</h3>")
                            .append("<p>We will be in touch soon.</p>")
                        });
                    } else {
                        $('#contact-form').html("<div id='message'></div>");
                        $('#message').html("<h3>Your enquery was rejected!</h3>")
                        .append("<p>Please try again later.</p>")
                    }
                },
                error: function (errormessage) {
                    $('#contact-form').html("<div id='message'></div>");
                    $('#message').html("<h3>An error has occurred!</h3>")
                        .append("<p>Please try again later.</p>")

                }
            });
        }
    });


    function ValidateFields() {
        // Start validation:
        $.validity.setup({ outputMode: "modal" });
        $.validity.start();

        // Validate fields
        $("input#contact-name").require();
        $("input#contact-phone").require();
        $("input#contact-email")
        .require()
        .match("email");

        // All of the validator methods have been called:
        // End the validation session:
        var result = $.validity.end();

        // Return whether it's okay to proceed with the Ajax:
        return result.valid;
    }

});

