{% load i18n %}

<div class="ml-4 mb-4">
    <input id="tree-search-input" class="form-control" type="text" placeholder="{% trans 'Search' %}"/>
</div>
<div id="tree-root">
    {% include 'konova/widgets/tree/radio/radio-tree-select-content.html' %}
</div>

<script>
    function toggleSelectedCssClass(element){
        element = $(element);
        var cssClass = "badge rlp-r"

        // Find all already tagged input elements and reset them to be untagged
        var allTaggedInputs = $("#tree-root").find(".badge.rlp-r")
        allTaggedInputs.removeClass(cssClass)

        // Find all parents of selected element
        var parentElements = element.parents(".tree-element-children")

        // Tag parents of element
        var parentLabels = parentElements.siblings(".tree-label");
        parentLabels.addClass(cssClass);
    }

    function changeHandler(event){
        toggleSelectedCssClass(this);
    }

    function searchInputHandler(event){
        var elem = $(this);
        var val = elem.val()
        var allTreeElements = $(".tree-element")
        var allTreeElementsContain = $(".tree-element").filter(function(){
            var reg = new RegExp(val, "i");
            return reg.test($(this).text());
            }
        );
        if(val.length > 0){
            // Hide everything
            allTreeElements.hide()
            // Now show again everything matching the query
            allTreeElementsContain.show()
        }else{
            // Show everything if no query exists
            allTreeElements.show()
        }
    }

    // Add event listener on search input
    $("#tree-search-input").keyup(searchInputHandler)

    // Add event listener on changed checkboxes
    $(".tree-input").change(changeHandler);

    // initialize all pre-checked checkboxes (e.g. on an edit form)
    var preCheckedElements = $(".tree-input:checked");
    preCheckedElements.each(function (index, element){
        toggleSelectedCssClass(element);
    })
</script>