

function showLocationStructureBox() {
    var txtfield = document.getElementById("LocationStructureDescr");
    var userbox = document.getElementById("LocationStructure");

    if (userbox.style.visibility != "visible") {
        loadLocationStructure();
        var spantop = absTop(txtfield);
        var spanleft = absLeft(txtfield);
        var spanwidth = txtfield.offsetWidth;
        var spanheight = txtfield.offsetHeight;

        spantop = spantop + spanheight;
        spanwidth = spanwidth - 2;

        userbox.style.width = spanwidth + "px";
//        userbox.style.left = spanleft + "px";
//        userbox.style.top = spantop + "px";

        userbox.style.visibility = "visible";
        userbox.style.display = "block";
    } else {
        userbox.style.visibility = "hidden";
        userbox.style.display = "none";
    }
}
jQuery(document).ready(function () {
    //loadLocationStructure();
})



function getLocationStructure() { }

function isJson(str) {
    try {
        JSON.parse(str);
    } catch (e) {
        return false;
    }
    return true;
}

function loadLocationStructure() {
    //Baum re-initialisieren, da sonst die bisherigen fancytree-options verwendet werden:
    $("#LocationStructureResult").remove();
    $("#LocationStructure").append('<div id="LocationStructureResult" class="DropDownResult" ></div>');
    
    LocationLogGroupID = parseInt($("#LocationLogGroupID").val()) || 0;    
    ContactID = $("#contact_id").val();
    //console.log("URL: index.php?module=structure&event=showfulltree&selected=" + LocationLogGroupID + "&contactid=" + ContactID);
    /*
    $.get('index.php?module=structure&event=showfulltree&selected=' + LocationLogGroupID + '&contactid=' + ContactID, function(data){
        if(!isJson(data)){
            return false;
        }
    });
    */
   // ContactID = 1;
    if ($.fn.fancytree) {
        $("#LocationStructureResult").fancytree({
            source: {
                url: "index.php?module=structure&event=showfulltree&selected=" + LocationLogGroupID + "&contactid=" + ContactID
            },
            
            extensions: ["glyph", "filter"],
            activeVisible: true,
            glyph: glyph_opts,            
            checkbox: false,
            autoActivate: true, // Automatically activate a node when it is focused (using keys).
            selectMode: 1, // 1:single, 2:multi, 3:multi-hier
            activeVisible: true,
            autoScroll: true, // Automatically scroll nodes into visible area
            filter: {  // override default settings
                counter: false, // No counter badges
                mode: "hide",  // "dimm": Grayout unmatched nodes, "hide": remove unmatched nodes
                autoExpand: true,
                highlight: true,
            },
            activate: function (event, data) {
                // A node was activated: display its title:
                var node = data.node;
                setLocationStructure(node.key, node.title, node.data.reftype, node.data.loggroupid);
                $("#LocationStructure").hide();
            },
           
            init: function (e, data) {
                var activeJumpNode = data.tree.getActiveNode();
                if (activeJumpNode) {
                    $("#LocationStructureDescr").val(activeJumpNode.title);
                    $("#LocationRefType").val(activeJumpNode.data.reftype);
                    $("#LocationLogGroupID").val(activeJumpNode.data.loggroupid);
                    $("#LocationStructureID").val(activeJumpNode.key);
                }
            }
            
        }).show();

        $("#filterInput").on("input", function () {
            const tree = $.ui.fancytree.getTree("#LocationStructureResult");
            const val = $(this).val();
            if (val) {
                tree.filterNodes(val);
            } else {
                tree.clearFilter();
            }
        });
    }
}



function setLocationStructure(sid, name, reftype, loggroupid) {
    //document.getElementById('LocationStructureDescr').value = name;
    $('#LocationStructureDescr').val(name);
    //showLocationStructureBox();
    $("#LocationStructureID").val(sid);
    $("#LocationRefType").val(reftype);
    $("#LocationLogGroupID").val(loggroupid);

    if (typeof TicketID !== "undefined") {
        $.post("index.php?module=ticket&event=changeLocationStructure&LocationStructureID=" + sid + "&tid=" + TicketID + '&LocationRefType=' + reftype + '&LocationLogGroupID=' + loggroupid + '&Draft=' + IsDraft, {

        }).done(function (json) {
            noty({
                text: json.message,
                type: json.error ? 'error' : 'success',
                timeout: notifyTimeout
            });
            $("#LocationStructure").hide();
        });
    }

    $("#delLocationStructureDescr").show();
}

function clearLocationStructure() {
    //document.getElementById('LocationStructureDescr').value = '';
    $('#LocationStructureDescr').val('');
    $("#LocationStructureID").val("");
    $("#delLocationStructureDescr").hide();
    $("#LocationLogGroupID").val("");
    setLocationStructure(0, '', '', 0);
}

/**
 * updateLocationID
 */
function updateLocationID() {
    LocationStructureID = $("#LocationStructureID").val();
//    alert(LocationStructureID);
}


function reloadLocationStructure() {
    var tree = $("#LocationStructureResult").fancytree("getTree");
    var LocationLogGroupID = parseInt($("#LocationLogGroupID").val()) || 0;
    var ContactID = $("#contact_id").val();

    tree.reload({
        url: "index.php?module=structure&event=showfulltree&selected=" + LocationLogGroupID + "&contactid=" + ContactID
    }).done(function () {
        // Nach dem Reload aktiven Node setzen
        var activeNode = null;
        tree.visit(function (node) {
            if (node.data && node.data.active) {
                activeNode = node;
                return false; // stop visiting
            }
        });

        if (activeNode) {
            activeNode.setActive(true);
            activeNode.makeVisible();

            $("#LocationStructureDescr").val(activeNode.title);
            $("#LocationRefType").val(activeNode.data.reftype);
            $("#LocationLogGroupID").val(activeNode.data.loggroupid);
            $("#LocationStructureID").val(activeNode.key);
        }
    });
}
