<script>
    $(document).ready(function() {
    

        $(".filter-field").each(function() {
            var name = $(this).attr('key');
            $(this).select2({
                tokenizer: function(input, s2, callback) {
                    var term = input.term;
                    if (term.indexOf(',') < 0) return input; // Exit if no tokens
                    var parts = term.split(",");
                    for (var i = 0; i < parts.length; i++) {
                        var part = parts[i].trim();
                        if (part.length > 2) {
                            $.ajax({
                                url: s2.options.ajax.url,
                                dataType: s2.options.ajax.dataType,
                                data: s2.options.ajax.data({
                                    term: part
                                }),
                                async: false, // If async then unable to return unmatched tokens
                                success: function(data) {
                                    var pr = s2.options.ajax.processResults(data, {
                                        term: part
                                    });
                                    if (pr.results[0].value != 0) {
                                        callback(pr.results[0]);
                                        parts.splice(i--, 1);
                                    }
                                }
                            });
                        }
                    }
                    return {
                        term: parts.join(',')
                    }; // Rejoin unmatched tokens
                },
                minimumInputLength: 1,
                multiple: true,
                ajax: {
                    url: '/get-filter-fields',
                    dataType: "json",
                    data: function(params) {
                        var query = {
                            search: params.term,
                            type: name
                        };
                        return query;
                    },
                    processResults: function(data) {
                        return {
                            results: data
                        };
                    },
                }
            });
        });

    });
</script>
