﻿$(document).ready(function () {
    $("input[data-autocomplete-service-url]").each(function (index, element) {
        var current = $(element);
        var serviceUrl = current.attr("data-autocomplete-service-url");
        var textParamName = current.attr("data-autocomplete-text-param");
        if (!textParamName)
            textParamName = "term";
        var countParamName = current.attr("data-autocomplete-count-param");
        if (!countParamName)
            countParamName = "count";
        var count = current.attr("data-autocomplete-count");
        if (!count) 
            count = 10;
        var textMinLength = current.attr("data-autocomplete-min-length");
        if (!textMinLength) 
            textMinLength = 3;
            
        current.autocomplete({
            minLength: textMinLength,
            source: function (term, response) {
                var params = {};
                params[textParamName] = current.val();
                params[countParamName] = count;
                $.ajax({
                    url: serviceUrl,
                    data: params,
                    context: document.body,
                    success: function (data) { response(data); },
                    error: function (data) { response([]); }
                });
            }
        });
    });
});
