(function () {
    var $Coveo = jQuery.noConflict();
    var typeAheadOptions = {
        hint: true,
        highlight: true,
        minLength: 1,
    };

    function getSourceFunction(url) {
        if (url.indexOf('?') !== -1) {
            url = url + '&';
        } else {
            url = url + '?';
        }

        return function (query, _syncResults, asyncResults) {
            $Coveo.ajax({
                url: `${url}filter=${query}`,
                success: function (data) {
                    asyncResults(data);
                },
            });
        };
    }

    function getTypeaheadFieldDataSet(element) {
        var parameters = [];

        if (!!element.data('sort')) {
            parameters.push('sort=true');
        }
        if (!!element.data('number')) {
            if (!!element.data('date')) {
                parameters.push('isNumericOrDate=true');
            } else {
                parameters.push('isNumeric=true');
            }
        }
        if (!!element.data('facet')) {
            parameters.push('isFacet=true');
        }

        var source = '/coveo/rest/fields' + (parameters.length > 0 ? '?' + parameters.join('&') : '');

        return {
            display: 'SitecoreFieldName',
            limit: 15,
            source: getSourceFunction(source),
        };
    }

    $Coveo(document).ready(function () {
        $Coveo('.FieldTypeAhead').each(function () {
            var dataSet = getTypeaheadFieldDataSet($Coveo(this));
            $Coveo(this).typeahead(typeAheadOptions, dataSet);
        });
    });
})();
