﻿(function ($) {

    function revalidate(control) {
        if (typeof window.ValidatorOnChange === "function") {
            window.ValidatorOnChange({ target: control });
        }
    }

    /* N.B. numberOfResults is limited to 50 in the location lookup service */
    $.fn.locationAutoComplete = function () {
        return this.each(function () {
            var $this = $(this);
            $this.autocomplete({
                delay: 100,
                minLength: 2,
                source: function (request, response) {
                    $.ajax({
                        type: "POST",
                        url: "/WebServices/LookupService/LookupService.asmx/GetAutoSuggestLocations",
                        data: '{lookupText: "' + request.term + '", numberOfResults: 50}',
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (data) {
                            data = data.d || data;
                            if (!data.Items) {
                                response([]);
                            } else {
                                response(data.Items);
                            }
                        }
                    });
                },
                select: function (ev, ui) {
                    // TK: We need to set selected value before validation kicks in.
                    // Because autocomplete plugin does not set the input value until this callback returns.
                    $(this).val(ui.item.value);
                    revalidate(this);
                }
            });
        });
    };

})(jQuery);
