jQuery(document).ready(function($) {
    var waiting = false;
    var lastSelected = null;

    function update_waiting_value(val = false) {
        waiting = val;
    }
    $.fn.searchUsers = function(entry) {
        var element = $(this);
        if (entry.length >= 1) {
            update_waiting_value(true);
            setTimeout(function() {
                var new_entry = $(element).val();
                if (entry !== new_entry) {
                    $(element).searchUsers(new_entry);
                    return;
                }
                var id = $(element).closest(".chosen-container").attr("id").replace("_chosen", "");
                var default_options = $("#container_" + id).data("defaultOptions");
                var query_settings = $("#container_" + id).data("querySettings");
                var loader = document.createElement("img");
                loader.src = "app/images/ajax-loader.gif";
                loader.width = 100;
                loader.style.display = "block";
                loader.style.position = "absolute";
                loader.style.margin = "auto";
                loader.style.top = "-32px";
                loader.style.right = "-70px";
                $("#" + id).parent().append(loader);
                $.ajax({
                    type: "post",
                    url: "app/includes/ajax.php",
                    data: { action: "search_users", search_term: entry, query_settings: query_settings }
                }).done(function(data) {
                    $(loader).remove();
                    try {
                        data = JSON.parse(data);
                        if (data.length > 0) {
                            $("#" + id).find('option').not(':selected').remove();
                            $.each(default_options, function(i, v) {
                                var existing = $("#" + id).find("option[value=\"" + v + "\"]");
                                if (existing.length === 0) {
                                    $("#" + id).append("<option value=\"" + v + "\">" + i + "</option>");
                                }
                            });
                            $.each(data, function(i, v) {
                                var existing = $("#" + id).find("option[value=\"" + v.id + "\"]");
                                if (existing.length === 0) {
                                    $("#" + id).append("<option value=\"" + v.id + "\">" + v.surname + " " + v.other_names + "</option>");
                                }
                            });
                            $("#" + id).trigger("chosen:updated");
                            // $(element).val(entry);
                        }
                    } catch (err) {
                        console.log(err);
                        console.log(data);
                    } finally {
                        update_waiting_value(false);
                    }
                });
            }, 500);

        } else {
            update_waiting_value(false);
        }
    }
    $(document).on("keyup", ".search-users .chosen-search-input", function(e) {
        var entry = $(this).val();
        if (!waiting) {
            $(this).searchUsers(entry);
        }

    })
    $(document).on("change", ".search-users .standardSelect", function(e) {
        if ($(this).data("multiple") === "no") {
            var element = $(this);
            if (lastSelected !== null) {
                $(lastSelected).remove();
            }
            lastSelected = $("option:selected:last", element)
            var latest_value = $(lastSelected).val();
            $(element).val("").trigger('chosen:updated');
            $(element).val([latest_value]).trigger('chosen:updated');

        }
    });

})