﻿$(document).ajaxStart(function () {
    $("#ajax-busy").show();
});
$(document).ajaxStop(function () {
    $("#ajax-busy").hide();
});

$(function () {

    $("#btnsubscribe").click(function () {
        // validate and process form here  

        if (ValidateFields()) {

            var myMailerRequest = { email: $("input#subscriber-email").val() };
            var data = $.toJSON(myMailerRequest)

            $.ajax({
                type: "POST",
                url: "/services/dataService.asmx" + "/" + "SubmitEmail",
                data: data,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    if (response.d) {
                        $('#box-subscribe').hide()
                        $('#box-subscribe').html("<div id='message'></div>");
                        $('#box-subscribe').fadeIn(500, function () {
                            $('#message').html("<h3>Thank you for subscribing!</h3>")
                        });
                    } else {
                        $('#box-subscribe').html("<div id='message'></div>");
                        $('#message').html("<h3>Your enquery was rejected!</h3>")
                        .append("<p>Please try again later.</p>")
                    }
                },
                error: function (errormessage) {
                    $('#box-subscribe').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#subscriber-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;
    }

});
