﻿(function ($) {

    var useAsyncRequest = true;

    // When user pressed the enter key, we perform server-side validation synchronously.
    // This resolves the need to press enter again after async vsalidation request returns.
    window.ValidatedTextBoxOnKeyPress = function (event) {
        var ev = $.event.fix(event);
        if (ev.which === 13) {
            useAsyncRequest = false;
            window.ValidatorOnChange(event);
            var vals = ev.target.Validators;
            return !window.Page_BlockSubmit && window.AllValidatorsValid(vals);
        }
        return true;
    };

    // When user clicks submit, we perform server-side validation synchronously.
    // This resolves the need to click submit again after async vsalidation request returns.
    var __Page_ClientValidate = window.Page_ClientValidate;
    window.Page_ClientValidate = function (validationGroup) {
        useAsyncRequest = false;
        return __Page_ClientValidate(validationGroup);
    };

    window.AjaxValidator_Validate = function (val, args, options) {

        if (options.preValidate) {
            options.preValidate(val, args);
        }

        // block form submission until we have a validation result
        window.Page_BlockSubmit = true;

        var value = args.Value.toLowerCase();
        var validationResult = options.cache[value];
        if (validationResult) {
            args.IsValid = validationResult.IsValid;
            if (options.postValidate) {
                options.postValidate(val, validationResult);
            }
            // unblock form submission
            window.Page_BlockSubmit = false;
            return;
        }

        options.cache[value] = { IsValid: false, Value: value };

        $.ajax({
            type: "POST",
            url: options.url,
            async: useAsyncRequest,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            data: options.data(val, args),
            success: function (result) {
                validationResult = result.d;
                options.cache[value] = validationResult;
                // re-validate
                window.ValidatorValidate(val);
                window.ValidatorUpdateIsValid();
            },
            error: function () {
                validationResult = { IsValid: true, Value: value };
                options.cache[value] = validationResult;
            }
        });

        if (useAsyncRequest) {
            // return as valid so that we don't get error message until ajax call returns
            args.IsValid = true;
        } else {
            useAsyncRequest = true;
            args.IsValid = validationResult.IsValid;
        }
    };

})(jQuery);
