import { ApiService } from "../util/apiService.js";

(function ($) {
    var tUtil = function () {
        var collectOpenBranches = function (tree) {
            var options = tUtil.getTreeOptions(tree);
            var ulList = $(tree).find("ul:not(.dmn-c)");
            var array = [];
            if (ulList.length)
                for (var i = 0; i < ulList.length; i++) {
                    var item = ulList[i];
                    var parent = $(item).parent();
                    if (parent)
                        array.push(parent.attr("did"));
                }
            options.expandList = array;
        }
        var openBranches = function (tree) {
            var options = tUtil.getTreeOptions(tree);
            var list = options.expandList;
            if (_h.any(list))
                for (var i = 0; i < list.length; i++) {
                    var li = $(tree).find("[did='" + list[i] + "']");
                    if (li.length) {
                        $(li).find("ul").first().removeClass("dmn-c");
                        $(li).find(".dmn-p").first().addClass("fa-minus text-danger");
                        $(li).find(".dmn-p").first().removeClass("fa-plus");
                        $(li).find(".dmn-fld").first().addClass("fa-folder");
                        $(li).find(".dmn-fld").first().removeClass("fa-folder-open");
                    }
                }
            options.expandList = [];
        }
        var toggleSelectedTag = function (li, withChild) {
            var firstSpan = $(li).find(".dmn-ttl")[0];
            if (withChild) {
                if (_hh.hasClass(li, "dmn-selected")) {
                    $(li).removeClass("dmn-selected");
                    $(li).attr("draggable", "false");
                    $(li).find("li").removeClass("dmn-selected");
                    $(li).find(".dmn-ttl").css("color", "#6a6c6f");
                    $(li).find("li").attr("draggable", "false");
                } else {
                    $(li).find("li").addClass("dmn-selected");
                    $(li).find(".dmn-ttl").css("color", "red");
                    $(li).find("li").attr("draggable", "true");
                    $(li).addClass("dmn-selected");
                    $(li).attr("draggable", "true");
                }
            } else {
                if (_hh.hasClass(li, "dmn-selected")) {
                    $(li).removeClass("dmn-selected");
                    $(li).attr("draggable", "false");
                    $(li).find("li.dmn-selected").removeClass("dmn-selected");
                    $(li).find("li[draggable='true']").attr("draggable", "false");
                    $(li).find(".dmn-ttl").css("color", "#6a6c6f");
                } else {
                    $(li).find("li").removeClass("dmn-selected");
                    $(li).find("li.dmn-selected").removeClass("dmn-selected");
                    $(li).find("li[draggable='true']").attr("draggable", "false");
                    $(li).find(".dmn-ttl").css("color", "#6a6c6f");
                    $(li).addClass("dmn-selected");
                    $(li).attr("draggable", "true");
                    $(firstSpan).css("color", "red");
                }
            }
        };
        var getValidUnselectedItems = function (li) {
            var list = [];
            var unselectedItems = $(li).find("li:not(.dmn-selected)");
            $.each(unselectedItems, function (index, item) {
                if ($(item).attr("dim") === "false" && $(item).attr("dis") === "false") {
                    list.push(item);
                }
            });
            return list;
        }
        var toggleSelectedMappingSrcTag = function (li) {
            var firstSpan;
            if (_hh.hasClass(li, "dmn-selected")) {
                $(li).removeClass("dmn-selected");
                $(li).attr("draggable", "false");
                $(li).css("color", "");
                $(li).find("li").removeClass("dmn-selected");
                $(li).find("li").attr("draggable", "false");
                $(li).find(".dmn-ttl").css("color", "");
                var parents = tUtil.getParents(li);
                if (parents && parents.length)
                    for (var j = 0; j < parents.length; j++) {
                        var parent = parents[j];
                        $(parent).removeClass("dmn-selected");
                        $(parent).attr("draggable", "false");
                        var sPa = $(parent).find(".dmn-ttl")[0];
                        $(sPa).css("color", "");
                    }
            } else {
                var item;
                if ($(li).attr("dim") === "false" && $(li).attr("dis") === "false") {
                    $(li).addClass("dmn-selected");
                    $(li).attr("draggable", "true");
                    firstSpan = $(li).find(".dmn-ttl")[0];
                    $(firstSpan).css("color", "red");
                }
                var unselectList = getValidUnselectedItems(li);
                var selectList = $(li).find("li.dmn-selected");
                if (unselectList.length) {
                    for (var i = 0; i < unselectList.length; i++) {
                        item = unselectList[i];
                        firstSpan = $(item).find(".dmn-ttl")[0];
                        $(item).addClass("dmn-selected");
                        $(item).attr("draggable", "true");
                        $(firstSpan).css("color", "red");
                    }
                } else {
                    if (selectList.length)
                        for (var k = 0; k < selectList.length; k++) {
                            item = selectList[k];
                            $(item).removeClass("dmn-selected");
                            $(item).attr("draggable", "false");
                            var sPau = $(item).find(".dmn-ttl")[0];
                            $(sPau).css("color", "");
                        }
                }
            }
        };
        var toggleNodeSelectedTag = function (li, withChild, options) {
            var firstSpan = $(li).find(".dmn-ttl")[0];
            if (withChild) {
                if (_hh.hasClass(li, "dmn-selected")) {
                    $(li).removeClass("dmn-selected");
                    $(li).find("li").removeClass("dmn-selected");
                    $(li).find(".dmn-ttl").css("color", "#6a6c6f");
                } else {
                    $(li).find("li").addClass("dmn-selected");
                    $(li).find(".dmn-ttl").css("color", "red");
                    $(li).addClass("dmn-selected");
                }
            } else {
                if (_hh.hasClass(li, "dmn-selected")) {
                    $(li).removeClass("dmn-selected");
                    $(li).find("li.dmn-selected").removeClass("dmn-selected");
                    $(li).find(".dmn-ttl").css("color", "#6a6c6f");
                } else {
                    $(li).find("li").removeClass("dmn-selected");
                    $(li).find("li.dmn-selected").removeClass("dmn-selected");
                    $(li).find(".dmn-ttl").css("color", "#6a6c6f");
                    $(li).addClass("dmn-selected");
                    $(firstSpan).css("color", "red");
                }
            }
        };
        var getNode = function (tree, id) {
            return tree.querySelectorAll('[did="' + id + '"]');
        };
        var droppableMappingNode = function (li, obj, options) {
            if (options.permitPeriodEdit && obj.nt === 2 && obj.mp) {
                li.ondragover = function (ev) {
                    ev.preventDefault();
                    var span = $(ev.currentTarget).find(".dmn-ttl")[0];
                    $(span).css("color", "red");
                };
                li.ondragleave = function (ev) {
                    ev.preventDefault();
                    var span = $(ev.currentTarget).find(".dmn-ttl")[0];
                    $(span).css("color", "#6a6c6f");
                    var div = document.getElementById('drag-label');
                    div.style.display = "block";
                };
                li.ondragend = function (ev) {
                    ev.preventDefault();
                    var span = $(ev.currentTarget).find(".dmn-ttl")[0];
                    $(span).css("color", "#6a6c6f");
                    var div = document.getElementById('drag-label');
                    div.style.display = "block";
                };
                li.ondrop = function (ev) {
                    ev.preventDefault();
                    var id = this.getAttribute("did");
                    var tree = tUtil.getTree(this);
                    tUtil.collectOpenBranches(tree);
                    options.onDropCallback(id,
                        options,
                        function (targetId, list, opts) {
                            if (!targetId)
                                return false;
                            if (!list || list.length === 0)
                                return false;
                            var tree = opts.treeEl;
                            var liTarget = getNode(tree, targetId)[0];
                            var ulTraget = $(liTarget).find("ul")[0];
                            $(ulTraget).empty();
                            var span = $(liTarget).find(".dmn-ttl")[0];
                            $(span).css("color", "#6a6c6f");
                            var div = document.getElementById('drag-label');
                            div.style.display = "block";
                            var ulTarget = liTarget.getElementsByTagName("ul")[0];
                            for (var i = 0; i < list.length; i++) {
                                tUtil.buildMappingRow(ulTarget, list[i], opts);
                            }
                            tUtil.openBranches(tree);
                        });
                };
            }
        };
        var droppableMappingDestNode = function (li, obj, options) {
            if (!options.permitPeriodEdit || obj.mp === false)
                return;
            li.ondragover = function (ev) {
                ev.preventDefault();
                var span = ev.currentTarget.getElementsByClassName("dmn-ttl")[0];
                if (span.className.indexOf("dmn-nodrp") === -1 && span.style.color !== "red") {
                    span.style.color = "red";
                }
            };
            li.ondragleave = function (ev) {
                ev.preventDefault();
                var span = ev.currentTarget.getElementsByClassName("dmn-ttl")[0];
                if (span.className.indexOf("dmn-nodrp") === -1 && span.style.color === "red") {
                    $(span).css("color", "#6a6c6f");
                }
            };
            li.ondragend = function (ev) {
                ev.preventDefault();
                var div = document.getElementById('drag-label');
                div.style.display = "none";
            };
            li.ondrop = function (ev) {
                ev.preventDefault();
                var id = this.getAttribute("did");
                options.onDropCallback(Number(id), options,
                    function (targetId, list, opts) {
                        if (!targetId)
                            return false;
                        if (!list || list.length === 0)
                            return false;
                        var tree = opts.treeEl;
                        var liTarget = getNode(tree, targetId)[0];
                        tUtil.setITag(liTarget, true, true);
                        var ulTraget = $(liTarget).find("ul")[0];
                        $(ulTraget).empty();
                        var span = $(liTarget).find(".dmn-ttl")[0];
                        $(span).css("color", "#6a6c6f");
                        var div = document.getElementById('drag-label');
                        div.style.display = "block";
                        var ulTarget = liTarget.getElementsByTagName("ul")[0];
                        for (var i = 0; i < list.length; i++) {
                            tUtil.buildMappingDestRow(ulTarget, list[i], opts);
                        }
                    });
            };
        };
        var setNodeTitle = function (li, obj, tType) {
            var nameSpan = _hh.createElement("span", li);
            var sName = _h.shortName(obj.na);
            switch (obj.nt) {
                case 0:
                    _hh.setInnerHtml(nameSpan, obj.co + "-" + sName[0]);
                    _hh.setClassName(nameSpan, "dmn-ttl dmn-mgl");
                    break;
                case 1:
                    _hh.setInnerHtml(nameSpan, sName[0] + " (" + obj.co + ")");
                    _hh.setClassName(nameSpan, "dmn-ttl dmn-ntmg");
                    break;
                case 2:
                    _hh.setInnerHtml(nameSpan, sName[0] + " (" + obj.co + ")");
                    if (tType === "Mapping") {
                        if (obj.mp) {
                            _hh.setClassName(nameSpan, "dmn-ttl dmn-mg dmn-drp");
                        } else {
                            _hh.setClassName(nameSpan, "dmn-ttl dmn-mg dmn-nodrp");
                        }

                    } else {
                        _hh.setClassName(nameSpan, "dmn-ttl");
                    }
                    break;
            }
            if (sName[1]) {
                _hh.setAttributes(nameSpan, { "title": obj.na });
            }
            nameSpan.onclick = function () {
                var li = this.parentNode;
                var dmp = li.getAttribute("dmp");
                if (dmp === "false" || dmp === false)
                    return;
                var id = li.getAttribute("did");
                var nt = li.getAttribute("dnt");
                var instId = tUtil.getInstanceId(li);
                var opts = tUtil.getOptions(instId);
                var tree = tUtil.getTree(li);
                tUtil.collectOpenBranches(tree);
                opts.onClickItem(id, opts, Number(nt),
                    function (targetId, list, options) {
                        if (!targetId)
                            return false;
                        if (!list || list.length === 0)
                            return false;
                        var tr = opts.treeEl;
                        var liTarget = getNode(tr, targetId)[0];
                        var ulTraget = $(liTarget).find("ul")[0];
                        $(ulTraget).empty();
                        var ulTarget = liTarget.getElementsByTagName("ul")[0];
                        for (var i = 0; i < list.length; i++) {
                            tUtil.buildMappingRow(ulTarget, list[i], options);
                        }
                        var tree = tUtil.getTree(liTarget);
                        tUtil.openBranches(tree);
                    });
            };
        };
        var getInstanceId = function (el) {
            var parent = tUtil.getTree(el);
            return $(parent).attr("tv-id");
        };
        var getTree = function (el) {
            if ($(el).hasClass("dmn-tree"))
                return el;
            return $(el).closest(".dmn-tree");
        };
        var getParents = function (li) {
            var parent = li.parentNode;
            var array = [];
            while (parent.className !== "dmn-tree") {
                var liParent = $(parent).closest("li").get(0);
                array.push(liParent);
                parent = parent.parentNode;
                if (parent.className !== "dmn-tree") {
                    if (parent.nodeName !== "LI")
                        parent = parent.parentNode;
                }
            }
            return array;
        };
        var resetGuidSigns = function (li) {
            var tree = tUtil.getTree(li);
            $(tree).find(".dmn-dot").css("display", "none");
        };
        var setGuidSigns = function (tree, selectList, options) {
            $(tree).find(".dmn-dot").css("display", "none");
            if (selectList.length)
                for (var j = 0; j < selectList.length; j++) {
                    var elm = tree.find("[did='" + selectList[j].value + "']");
                    if (elm.length)
                        tUtil.toggleGuideSign(elm.get(0), true);
                }
        };
        var changeOtherSideSelectedItem = function (tree, items) {
            if (items && items.length)
                for (var i = 0; i < items.length; i++) {
                    var li = $(tree).find("[did='" + items[i].value + "']");
                    if (li.length === 0)
                        continue;
                    tUtil.toggleGuideSign(li.get(0), true);
                    $(li).addClass("dmn-selected");
                    //li.get(0).scrollIntoView();
                    var firstSpan = $(li).find(".dmn-ttl")[0];
                    $(firstSpan).css("color", "red");
                    var parents = tUtil.getParents(li[0]);
                    if (parents && parents.length)
                        for (var j = 0; j < parents.length; j++) {
                            var parent = parents[j];
                            var ul = $(parent).find("ul")[0];
                            var fld = $(parent).find(".dmn-fld")[0];
                            var sign = $(parent).find(".dmn-p")[0];
                            if (fld)
                                _hh.setAttributes($(fld).get(0),
                                    { "class": "dmn-fld fa fa-folder-open" });
                            _hh.setAttributes(sign,
                                { "class": "dmn-p fa fa-minus text-danger" });
                            $(ul).removeClass("dmn-c");
                        }

                }
        };
        var refreshSelectItems = function (tree, items) {
            if (items && items.length)
                for (var i = 0; i < items.length; i++) {
                    var li = $(tree).find("[did='" + items[i].value + "']");
                    tUtil.toggleGuideSign(li.get(0), true);
                    $(li).addClass("dmn-selected");
                    var firstSpan = $(li).find(".dmn-ttl")[0];
                    $(firstSpan).css("color", "red");
                }

        };
        var toggleGuideSign = function (li, action) {
            if (!li)
                return;
            var parent = li.parentNode;
            while (!_hh.hasClass(parent, "dmn-tree")) {
                if (parent.nodeName === "UL" && !_hh.hasClass(parent, "dmn-tree")) {
                    parent = parent.parentNode;
                }
                if (parent.nodeName === "LI") {
                    var tg = $(parent).find(".dmn-dot")[0];
                    if (action)
                        $(tg).css("display", "block");
                    else
                        $(tg).css("display", "none");
                }
                parent = parent.parentNode;
                if (!_hh.hasClass(parent, "dmn-tree")) {
                    if (parent.nodeName !== "LI")
                        parent = parent.parentNode;
                }
            }
        };
        var extractOldClass = function (tag) {
            if ($(tag).hasClass("dmn-add"))
                return "dmn-add";
            if ($(tag).hasClass("dmn-dele"))
                return "dmn-dele";
            if ($(tag).hasClass("dmn-edt"))
                return "dmn-edt";
        };
        var toggleShowChildren = function (tag) {
            var parent = $(tag).parent().find("ul")[0];
            var fld = $(tag).parent().find(".dmn-fld")[0];
            if (parent) {
                var exClass;
                if ($(parent).hasClass('dmn-c')) {
                    if (fld) {
                        exClass = extractOldClass(fld);
                        _hh.setAttributes($(fld).get(0),
                            { "class": "dmn-fld fa fa-folder-open" + " " + exClass });
                    }
                    _hh.setAttributes(tag,
                        { "class": "dmn-p fa fa-minus text-danger" });
                    setTimeout(function () {
                        $(parent).removeClass("dmn-c");
                    },
                        150);
                } else {
                    if (fld) {
                        exClass = extractOldClass(fld);
                        _hh.setAttributes($(fld).get(0),
                            { "class": "dmn-fld fa fa-folder" + " " + exClass });
                    }
                    _hh.setAttributes(tag,
                        { "class": "dmn-p fa fa-plus" });
                    setTimeout(function () {
                        $(parent).addClass("dmn-c");
                    },
                        150);
                }
            }
        };
        var openGuideSign = function (li) {
            var list = $(li).find("li.dmn-selected");
            if (list.length)
                for (var i = 0; i < list.length; i++) {
                    var parent = li;
                    while (parent.className !== "dmn-tree") {
                        var span = parent.getElementsByClassName("dmn-ttl");

                        parent = parent.parentNode;
                        if (parent.className !== "dmn-tree") {
                            if (parent.nodeName !== "LI")
                                parent = parent.parentNode;
                        }
                    }
                }

        };
        var getOptions = function (instanceId) {
            var item = $.fn.treeView.options.instances
                .filter(el => el.id === Number(instanceId));
            return item[0].opts;
        };
        var getTreeOptions = function (li) {
            var instanceId = getInstanceId(li);
            var item = $.fn.treeView.options.instances
                .filter(el => el.id === Number(instanceId));
            return item[0].opts;
        };
        var setSelectedItems = function (tree, options) {
            for (var i = 0; i < options.selectedItems().length; i++) {
                var li = $(tree).find("[did='" + options.selectedItems()[i].value + "']");
                if (options.tType !== "CompanySetting")
                    tUtil.toggleGuideSign(li.get(0), true);
                $(li).addClass("dmn-selected");
                var firstSpan = $(li).find(".dmn-ttl")[0];
                $(firstSpan).css("color", "red");
            }
        };
        var setSelectedItem = function (tree, options) {
            var li = $(tree).find("[did='" + options.selectedItem.value + "']");
            tUtil.toggleGuideSign(li.get(0), true);
            $(li).addClass("dmn-selected");
            var firstSpan = $(li).find(".dmn-ttl")[0];
            $(firstSpan).css("color", "red");
        };
        var getSelectedItemsData = function (li, onlyThisNode) {
            var tree = tUtil.getTree(li);
            if (tree) {
                var array = [];
                tree.find("li.dmn-selected").each(function (index, li) {
                    var span = $(li).find(".dmn-ttl")[0];
                    array.push({
                        value: Number($(li).attr("did")),
                        code: $(li).attr("dco"),
                        text: $(span).text()
                    });
                });
            }
            return array;
        };
        var getConsolidationBranchData = function (id, options, callback) {
            var model = {
                id: id,
                controllerName: options.controllerName,
                depth: 1,
                showMapped: options.showMapped,
                mappingSide: options.mappingSide
            };

            if (options.sheetId) {
                model.sheetId = options.sheetId;
            }
            if (options.periodId) {
                model.period = options.periodId;
            }
            ApiService.request(
                {
                    url: "/api/common/getconsolidationbranch",
                    data: model,
                    success: function (data) {
                        if (data !== null && data !== undefined) {
                            callback(data);
                        }
                    },
                    error: function (data) {
                        callback(null);
                    }
                });
        };
        var getNodeParentId = function (li) {
            var parentUl = li.parentNode;
            var parentLi = parentUl.parentNode;
            return Number(parentLi.getAttribute("did"));
        };
        var createNodePath = function (li, treeName) {
            var path;
            if (treeName)
                path = treeName + " => ";
            else
                path = " :: ";
            var array = [];
            var parent = li;
            while (parent.className !== "dmn-tree") {
                var span = parent.getElementsByClassName("dmn-ttl");
                if (treeName) {
                    var titleTemp = span[0].innerText.substring(0, span[0].innerText.indexOf(" ("));
                    if (array.indexOf(span[0].innerText) === -1)
                        array.push(titleTemp);
                } else {
                    if (array.indexOf(span[0].innerText) === -1)
                        array.push(span[0].innerText);
                }
                parent = parent.parentNode;
                if (parent.className !== "dmn-tree") {
                    if (parent.nodeName !== "LI")
                        parent = parent.parentNode;
                }
            }
            array.reverse();
            var parents = array;
            for (var j = 0; j < parents.length; j++) {
                var target = parents[j];
                path += target;
                if (parents.length - 1 !== j) {
                    path += " => ";
                }
            }
            return path;
        };
        var setPlusMinusAll = function (li) {
            var minusI = _hh.createElement("i", li);
            _hh.setClassName(minusI, "dmn-dirc fa fa-minus-square-o");
            var plusI = _hh.createElement("i", li);
            _hh.setClassName(plusI, "dmn-dirc fa fa-plus-square-o");
            plusI.onclick = function (ev) {
                var li = $(this).parent();
                li.find("ul").removeClass("dmn-c");
                li.find(".dmn-p").addClass("fa-minus text-danger");
                li.find(".dmn-p").removeClass("fa-plus");
                li.find(".dmn-fld").addClass("fa-folder-open");
                li.find(".dmn-fld").removeClass("fa-folder");
            };
            minusI.onclick = function (ev) {
                var li = $(this).parent();
                li.find("ul").addClass("dmn-c");
                li.find(".dmn-p").removeClass("fa-minus text-danger");
                li.find(".dmn-p").addClass("fa-plus");
                li.find(".dmn-fld").removeClass("fa-folder-open");
                li.find(".dmn-fld").addClass("fa-folder");
            };
        };
        var setITag = function (li, insertAfter, type) {
            var iTag = li.getElementsByClassName("dmn-p");
            if (iTag.length) {
                return;
            }
            if (insertAfter) {
                iTag = document.createElement("i");
                li.prepend(iTag);
            } else
                iTag = _hh.createElement("i", li);
            if (!type)
                _hh.setClassName(iTag, "dmn-p fa fa-plus");
            else
                _hh.setClassName(iTag, "dmn-p fa fa-minus text-danger");
            iTag.onclick = function () {
                tUtil.toggleShowChildren(this);
            };
        };
        var refreshMappingDestSubset = function (targetId, list, options, type) {
            if (!targetId)
                return false;
            var tree = options.treeEl;
            var liTarget = tUtil.getNode(tree, targetId);
            if (liTarget.length > 1) {
                for (var j = 0; j < liTarget.length; j++) {
                    if (liTarget[j].getAttribute("dda") == "false") {
                        liTarget = liTarget[j];
                        break;
                    }
                }
            } else {
                liTarget = liTarget[0];
            }
            tUtil.setITag(liTarget, true);
            var ulTraget = $(liTarget).find("ul")[0];
            $(ulTraget).empty();
            if (list && list.length) {
                var span = $(liTarget).find(".dmn-ttl")[0];
                $(span).css("color", "#6a6c6f");
                var div = document.getElementById('drag-label');
                div.style.display = "block";
                var ulTarget = liTarget.getElementsByTagName("ul")[0];
                for (var i = 0; i < list.length; i++) {
                    tUtil.buildMappingDestRow(ulTarget, list[i], options);
                }
            } else {
                var sign = $(liTarget).find("dmn-p")[0];
                $(sign).remove();
            }
        };
        var buildChildren = function (target, obj, options) {
            if (obj.children && obj.children.length)
                for (var i = 0; i < obj.children.length; i++) {
                    if (tUtil["build" + options.tType + "Row"])
                        tUtil["build" + options.tType + "Row"](target, obj.children[i], options);
                    else
                        treeEditor.buildEditorRow(target, obj.children[i], options);
                }
        }
        var setUnlinkTag = function (li, obj) {
            var unlinkTag = _hh.createElement("i", li);
            _hh.setClassName(unlinkTag, "dmn-del fa fa-unlink");
            if ((obj.da && obj.children && obj.children.length) || obj.mp) {
                _hh.setAttributes(unlinkTag,
                    { "title": "حذف گروهی گره های نگاشت" });
                unlinkTag.onclick = function () {
                    var code = null, nodeId = 0;
                    var li = this.parentNode;
                    var da = li.getAttribute("dda") === "true";
                    if (da) {
                        code = li.getAttribute("did");
                        var parents = tUtil.getParents(li);
                        for (var i = 0; i < parents.length; i++) {
                            var parent = parents[i];
                            if (parent.getAttribute("dda") === "false") {
                                nodeId = Number(parent.getAttribute("did"));
                                break;
                            }
                        }
                    } else
                        nodeId = Number(li.getAttribute("did"));
                    var tree = tUtil.getTree(li);
                    var options = tUtil.getTreeOptions(li);
                    var ul = $(li).find("ul");
                    var depth = Number($(ul).attr("dep"));
                    var count = $(ul).find("li[dep='" + (depth + 1) + "']").length;
                    if (!count)
                        return false;
                    tUtil.collectOpenBranches(tree);
                    options.removeItemsFunc(nodeId, count, "multi", code, function (targetId, list) {
                        refreshMappingDestSubset(targetId, list, options);
                        tUtil.openBranches(tree);
                        tUtil.removeUselessSigns(tree);
                    });
                };
            }
            if (obj.da && (!obj.children || obj.children.length === 0)) {
                _hh.setAttributes(unlinkTag,
                    { "title": "حذف  گره نگاشت" });
                unlinkTag.onclick = function () {
                    var code = null, nodeId = 0;
                    var li = this.parentNode;
                    var da = li.getAttribute("dda") === "true";
                    if (da) {
                        code = li.getAttribute("did");
                        var parents = tUtil.getParents(li);
                        for (var i = 0; i < parents.length; i++) {
                            var parent = parents[i];
                            if (parent.getAttribute("dda") === "false") {
                                nodeId = Number(parent.getAttribute("did"));
                                break;
                            }
                        }
                    } else
                        nodeId = Number(li.getAttribute("did"));
                    var tree = tUtil.getTree(li);
                    var options = tUtil.getTreeOptions(li);
                    tUtil.collectOpenBranches(tree);
                    options.removeItemsFunc(nodeId, null, "single", code, function (targetId, list) {
                        refreshMappingDestSubset(targetId, list, options);
                        tUtil.openBranches(tree);
                        tUtil.removeUselessSigns(tree);
                    });
                };
            }

        };
        var createConsolidateTag = function (li, obj) {
            if (obj.nt === 1 && obj.nte === 1 && !obj.cc) {
                var ccTag = _hh.createElement("i", li);
                _hh.setClassName(ccTag, "dmn-ey fa fa-eye");
                ccTag.onclick = function (ev) {
                    var li = this.parentElement;
                    var id = li.getAttribute("did");
                    var eyIcon = li.getElementsByClassName("dmn-ey")[0];
                    var ulTarget = li.getElementsByTagName("ul")[0];
                    var instId = tUtil.getInstanceId(li);
                    var opts = tUtil.getOptions(instId);
                    getConsolidationBranchData(id, opts,
                        function (list) {
                            if (list && list.length) {
                                var oldNodes = $(ulTarget).find("li.dmn-selected");
                                $(ulTarget).empty();
                                for (var i = 0; i < list.length; i++) {
                                    if (tUtil["build" + opts.tType + "Row"])
                                        tUtil["build" + opts.tType + "Row"](ulTarget, list[i], opts);
                                    else
                                        treeEditor.buildEditorRow(ulTarget, list[i], opts);
                                }
                                if (oldNodes.length) {
                                    var parent = tUtil.getTree(ulTarget);
                                    setSelectedItems(parent, opts);
                                }
                            }
                            _hh.removeElement(eyIcon);
                        });
                };
            }
        }
        var createLiTag = function (target, obj, options, targetLi, extraAtt) {
            var li;
            if (targetLi) {
                li = document.createElement("li");
                targetLi.replaceWith(li);
            } else
                li = _hh.createElement("li", target);
            var depth = target.getAttribute("dep");
            if (!depth)
                depth = 0;

            var attributes = {
                "dep": Number(depth) + 1,
                "did": obj.id,
                "dnt": obj.nt
            };
            if (obj.nte)
                attributes.dnte = obj.nte;
            if (obj.cc)
                attributes.dcc = obj.cc;
            if (obj.co)
                attributes.dco = obj.co;
            for (var t in extraAtt) {
                if (extraAtt.hasOwnProperty(t)) {
                    var param = extraAtt[t];
                    attributes[t] = param;
                }
            }
            _hh.setAttributes(li, attributes);
            return [li, depth];
        }
        var createSwitchPart = function (li, obj, options) {
            var att, iTag, folderI, iDot, nt;
            switch (options.tType) {
                case "CompanyAccessUser":
                case "CompanySetting":
                    nt = obj.nt + 1;
                    break;
                default:
                    nt = obj.nt;
                    break;
            }
            switch (nt) {
                case 1:
                    switch (options.tType) {
                        case "NodeSelect":
                            iDot = _hh.createTag({
                                name: "i", className: "dmn-dot fa fa-caret-left", parent: li,
                                onclick: function () {
                                    var li = this.parentElement;
                                    var instId = tUtil.getInstanceId(li);
                                    var opts = tUtil.getOptions(instId);
                                    for (var i = 0; i < opts.selectedItems().length; i++) {
                                        var target = $(li).find("li[did='" + opts.selectedItems()[i].value + "']")[0];
                                        tUtil.openGuideSign(target);
                                    }
                                }
                            });
                            break;
                    }
                    iTag = _hh.createTag({
                        name: "i", className: "dmn-p fa fa-plus", parent: li,
                        onclick: function () {
                            tUtil.toggleShowChildren(this);
                        }
                    });
                    folderI = _hh.createTag({ name: "i", className: "dmn-fld fa fa-folder", parent: li });
                    break;
                case 2:
                    switch (options.tType) {
                        case "Reference":
                        case "Current":
                        case "TreeInfo":
                        case "XbrlConcept":
                        case "NodeSelect":
                        case "MappingSrc":
                            if (_h.any(obj.children))
                                iTag = _hh.createTag({
                                    name: "i", className: "dmn-p fa fa-plus", parent: li,
                                    onclick: function () {
                                        tUtil.toggleShowChildren(this);
                                    }
                                });

                            break;
                    }
                    att = _hh.createTag({ name: "i", className: "dmn-att fa fa-file-text-o", parent: li });
                    break;
            }
            ;
            return [att, iTag, folderI, iDot];
        }
        var changeCheckboxes = function (tree) {
            var list = $(tree).find("[dnt='1']");
            for (let i = 0; i < list.length; i++) {
                var parent = list[i];
                var ul = $(parent).find("ul");
                var checked = $(ul).find("input:checkbox:checked");
                var unChecked = $(ul).find("input:checkbox:not(:checked)");
                var input = $(parent).find("input:checkbox")[0];
                if (checked.length && unChecked.length) {
                    $(input).attr("checked", "checked")
                    $(input).attr("itype", "indeterminate");
                }
                if (checked.length && !unChecked.length) {
                    $(input).attr("checked", "checked")
                    input.removeAttribute("itype");
                }
                if (!checked.length && unChecked.length) {
                    input.checked = false;
                    input.removeAttribute("checked");
                    input.removeAttribute("itype");
                }

                if (!checked.length && !unChecked.length) {
                    input.checked = false;
                    input.removeAttribute("checked");
                    input.removeAttribute("itype");
                }
            }
        }
        var createDragListData = function (tags, options) {
            var list = [];
            for (var j = 0; j < tags.length; j++) {
                var path = tUtil.createNodePath(tags[j], options.rootName);
                list.push({
                    id: Number(tags[j].getAttribute("did")),
                    code: tags[j].getAttribute("dco"),
                    name: $(tags[j]).find(".dmn-ttl")[0].innerText.trim(),
                    path: path,
                    periodId: options.periodId,
                    treeId: options.treeId
                });
            }
            return list;
        }
        var buildMappingRow = function (target, obj, options, targetLi) {
            var unlinkTag, att, iTag, folderI;
            var [li, depth] = tUtil.createLiTag(target, obj, options, targetLi, { "dmp": obj.mp });
            switch (obj.nt) {
                case 0:
                    att = _hh.createTag({
                        name: "i", className: "dmn-att fa fa-file-o",
                        parent: li
                    });
                    if (options.permitPeriodEdit && !options.isEffected) {
                        if (obj.da) {
                            unlinkTag = _hh.createElement("i", li);
                            _hh.setClassName(unlinkTag, "dmn-del fa fa-unlink");
                            _hh.setAttributes(unlinkTag,
                                { "title": "حذف گره نگاشت" });
                            unlinkTag.onclick = function () {
                                var parent = $(this).parent()[0];
                                var liParent = $(parent).parent().parent();
                                var tree = tUtil.getTree(liParent);
                                var id = $(liParent).attr("did");
                                var code = parent.getAttribute("dco");
                                tUtil.collectOpenBranches(tree);
                                options.removeItemsFunc(Number(id), null, "single", code, function (res) {
                                    if (res) {
                                        _hh.removeElement(parent);
                                        tUtil.resetITagSigns(tree);
                                        tUtil.openBranches(tree);
                                    }
                                });
                            };
                        }
                    }
                    break;
                case 1:
                    iTag = _hh.createTag({
                        name: "i", className: "dmn-p fa fa-plus",
                        parent: li
                    });
                    folderI = _hh.createTag({
                        name: "i", className: "dmn-fld fa fa-folder",
                        parent: li
                    });
                    ;
                    iTag.onclick = function () {
                        tUtil.toggleShowChildren(this);
                    };
                    break;
                case 2:
                    iTag = _hh.createTag({
                        name: "i", className: "dmn-p fa fa-plus",
                        parent: li
                    });
                    att = _hh.createElement("i", li);
                    _hh.setClassName(att, "dmn-att fa fa-file-text-o");
                    if (options.permitPeriodEdit && !options.isEffected && obj.mp) {
                        unlinkTag = _hh.createElement("i", li);
                        _hh.setClassName(unlinkTag, "dmn-del fa fa-unlink");
                        _hh.setAttributes(unlinkTag,
                            { "title": "حذف گروهی گره های نگاشت" });
                        unlinkTag.onclick = function () {
                            var parent = $(this).parent()[0];

                            var ul = $(parent).find("ul");
                            var depth = Number($(ul).attr("dep"));
                            var count = $(ul).find("li[dep='" + (depth + 1) + "']").length;
                            if (!count)
                                return false;
                            var tree = tUtil.getTree(parent);
                            var id = parent.getAttribute("did");
                            tUtil.collectOpenBranches(tree);
                            options.removeItemsFunc(Number(id), count, "multi", null, function (res) {
                                if (res) {
                                    var parentul = parent.getElementsByTagName("ul")[0];
                                    parentul.innerHTML = "";
                                    tUtil.resetITagSigns(tree);
                                    tUtil.openBranches(tree);
                                }
                            });
                        };
                    }
                    iTag.onclick = function () {
                        tUtil.toggleShowChildren(this);
                    };
                    break;
            }
            droppableMappingNode(li, obj, options);
            setNodeTitle(li, obj, options.tType);
            tUtil.createConsolidateTag(li, obj);
            if (obj.nt === 1 || obj.nt === 2) {
                var ul = _hh.createTag({
                    name: "ul", className: "dmn-c",
                    parent: li, attributes: { "dep": Number(depth) + 1 }
                });
                tUtil.buildChildren(ul, obj, options);
            }
        };
        var buildMappingDestRow = function (target, obj, options) {
            var unlinkTag, att, iTag, folderI;
            var [li, depth] = tUtil.createLiTag(target, obj, options, null, {
                "dmp": obj.mp,
                "dda": obj.da
            });
            switch (obj.nt) {
                case 1:
                    tUtil.setITag(li);
                    folderI = _hh.createElement("i", li);
                    _hh.setClassName(folderI, "dmn-fld fa fa-folder");
                    break;
                case 2:
                    if (obj.children && obj.children.length) {
                        tUtil.setITag(li);
                    }
                    att = _hh.createElement("i", li);
                    _hh.setClassName(att, "dmn-att fa fa-file-text-o");
                    break;
            }
            if (options.permitPeriodEdit && (obj.mp || obj.da)) {
                tUtil.setUnlinkTag(li, obj);
            }
            var nameSpan = _hh.createElement("span", li);
            var sName = _h.shortName(obj.na);
            if (depth === 0 && obj.nt === 1)
                tUtil.setPlusMinusAll(li);

            _hh.setInnerHtml(nameSpan, sName[0] + " (" + obj.co + ")");
            if (sName[1]) {
                _hh.setAttributes(nameSpan, { "title": obj.na });
            }
            switch (obj.nt) {
                case 1:
                    if (obj.da) {
                        _hh.setClassName(nameSpan, "dmn-ttl dmn-ntmg dmn-mgl");
                    } else {
                        _hh.setClassName(nameSpan, "dmn-ttl");
                    }
                    break;
                case 2:
                    if (obj.mp) {
                        _hh.setClassName(nameSpan, "dmn-ttl dmn-mg dmn-drp");
                    } else {
                        _hh.setClassName(nameSpan, "dmn-ttl dmn-mg dmn-mgl");
                    }
                    break;
            }
            nameSpan.onclick = function () {
                var li = this.parentNode;
                var dmp = li.getAttribute("dmp");
                if (dmp === "false" || dmp === false)
                    return;
                var id = li.getAttribute("did");
                var nt = li.getAttribute("dnt");
                var instId = tUtil.getInstanceId(li);
                var opts = tUtil.getOptions(instId);
                var tree = tUtil.getTree(li);
                tUtil.collectOpenBranches(tree);
                opts.onClickItem(id, opts, Number(nt),
                    function (targetId, list, options) {
                        if (!targetId)
                            return false;
                        if (!list || list.length === 0)
                            return false;
                        var tr = options.treeEl;
                        var liTarget = tUtil.getNode(tr, targetId)[0];
                        var instId = tUtil.getInstanceId(li);
                        var tree = tUtil.getTree(li);
                        var opts = tUtil.getOptions(instId);
                        tUtil.setITag(liTarget, true);
                        var ulTarget = $(liTarget).find("ul");
                        $(ulTarget).empty();
                        for (var i = 0; i < list.length; i++) {
                            tUtil.buildMappingDestRow(ulTarget[0], list[i], options);
                        }
                        tUtil.openBranches(tree);
                    });
            };
            droppableMappingDestNode(li, obj, options);
            tUtil.createConsolidateTag(li, obj);
            var ul = _hh.createTag({
                name: "ul", className: "dmn-c",
                parent: li, attributes: { "dep": Number(depth) + 1 }
            });
            tUtil.buildChildren(ul, obj, options);
            return li;
        };
        var buildBalanceReportRow = function (target, obj, options) {
            var [li, depth] = tUtil.createLiTag(target, obj, options, null, {});
            var [att, iTag, folderI] = createSwitchPart(li, obj, options);
            var nameSpan = _hh.createElement("span", li);
            var sName = _h.shortName(obj.na);
            nameSpan.onclick = function () {
                var li = this.parentNode;
                var parentId = tUtil.getNodeParentId(li);
                var path = tUtil.createNodePath(li);
                var isSelected = _hh.hasClass(li, "dmn-selected");
                var depth = Number(li.getAttribute("dep")) - 1;

                var model = {
                    depth: depth,
                    id: Number(li.getAttribute("did")),
                    nodeType: Number(li.getAttribute("dnt")),
                    code: li.getAttribute("dco"),
                    parentId: parentId,
                    path: path,
                    selected: isSelected
                };
                var instId = tUtil.getInstanceId(li);
                var opts = tUtil.getOptions(instId);
                opts.onClickItem(model, function (res) {
                    if (!isSelected) {
                        li.classList.add("dmn-selected");
                        li.getElementsByClassName("dmn-rp")[0].style.color = "red";
                    } else {
                        li.classList.remove("dmn-selected");
                        li.getElementsByClassName("dmn-rp")[0].style.color = "#6a6c6f";
                    }
                });
            };
            _hh.setInnerHtml(nameSpan, sName[0] + " (" + obj.co + ")");
            _hh.setClassName(nameSpan, "dmn-ttl dmn-rp");
            if (sName[1]) {
                _hh.setAttributes(nameSpan, { "title": obj.na });
            }
            tUtil.createConsolidateTag(li, obj);
            if (obj.nt === 1 || obj.nt === 2) {
                var ul = _hh.createTag({
                    name: "ul", className: "dmn-c",
                    parent: li, attributes: { "dep": Number(depth) + 1 }
                });
                tUtil.buildChildren(ul, obj, options);
            }
        };
        var buildTreeInfoRow = function (target, obj, options) {
            var [li, depth] = tUtil.createLiTag(target, obj, options, null, {});
            var [att, iTag, folderI] = createSwitchPart(li, obj, options);
            var nameSpan = _hh.createElement("span", li);
            var sName = _h.shortName(obj.na);
            _hh.setClassName(nameSpan, "dmn-ttl dmn-rp");
            var title = sName[0];
            var accountType = _h.getEnumText(accountTypes, obj.at);
            title += " ( " + obj.co + " ) ";
            if (!_h.isNullOrEmpty(accountType)) {
                title += "-" + accountType.substring(0, 2);
            }
            if (sName[1]) {
                _hh.setAttributes(nameSpan, { "title": obj.na });
            }
            if (depth === 0 && obj.nt === 1)
                tUtil.setPlusMinusAll(li);
            _hh.setInnerHtml(nameSpan, title);
            nameSpan.onclick = function (ev) {
                var li = this.parentNode;
                if (ev.ctrlKey)
                    tUtil.toggleSelectedTag(li, true);
                else
                    tUtil.toggleSelectedTag(li, false);
                if (!li.ondragstart && li.getAttribute("draggable") === "true") {
                    li.addEventListener('dragstart', function (event) {
                        var treeOpts = tUtil.getTreeOptions(this);
                        var tags = $(this).closest("#tree_view")
                            .find("li.dmn-selected");
                        var length = tags.length;
                        var list = createDragListData(tags, treeOpts);
                        var div = document.getElementById('drag-label');
                        div.style.display = "block";
                        var span = div.getElementsByTagName("span")[0];
                        span.innerText = length;
                        var item = _h.getEnumItem(nodeDisplayTypes, treeOpts.nodeDisplayType());
                        event.dataTransfer.setData('application/json',
                            JSON.stringify({
                                action: "nodeDrag",
                                nodeDisplayType: item.enText,
                                list: list
                            }));
                        event.dataTransfer.setDragImage(div, 60, 0);
                    });

                    li.addEventListener('dragover', function (e) {
                        e.preventDefault();
                    });
                    li.addEventListener('dragleave', function (e) {
                        var div = document.getElementById('drag-label');
                        div.style.display = "none";
                        e.preventDefault();
                    });
                    li.addEventListener('dragend', function (e) {
                        var div = document.getElementById('drag-label');
                        div.style.display = "none";
                        e.preventDefault();
                    });
                }
                if (li.ondragstart && li.getAttribute("draggable") === "false") {
                    li.ondragstart = null;
                    li.ondragover = null;
                    li.ondragleave = null;
                    li.ondragend = null;
                }

            };
            tUtil.createConsolidateTag(li, obj);
            if (obj.nt === 1 || obj.nt === 2) {
                var ul = _hh.createTag({
                    name: "ul", className: "dmn-c",
                    parent: li, attributes: { "dep": Number(depth) + 1 }
                });
                tUtil.buildChildren(ul, obj, options);
            }
        };
        var buildXbrlConceptRow = function (target, obj, options) {
            var [li, depth] = tUtil.createLiTag(target, obj, options, null, {});
            createSwitchPart(li, obj, options);
            var nameSpan = _hh.createElement("span", li);
            var sName = _h.shortName(obj.na);
            _hh.setClassName(nameSpan, "dmn-ttl dmn-rp");
            var title = sName[0];
            if (sName[1]) {
                _hh.setAttributes(nameSpan, { "title": obj.na });
            }
            if (depth === 0 && obj.nt === 1)
                tUtil.setPlusMinusAll(li);
            _hh.setInnerHtml(nameSpan, title);
            nameSpan.onclick = function (ev) {
                var li = this.parentNode;
                var tree = tUtil.getTree(li)[0];
                var options = tUtil.getTreeOptions(li);
                if (_hh.hasClass(li, "dmn-selected")) {
                    $(tree).find("li.dmn-selected").removeClass("dmn-selected");
                    $(li).attr("draggable", "false");
                    $(li).find("li").attr("draggable", "false");
                    $(tree).find(".dmn-ttl").css("color", "");
                    $(li).find(".dmn-ttl").css("color", "");
                } else {
                    $(tree).find("li.dmn-selected").removeClass("dmn-selected");
                    $(tree).find(".dmn-ttl").css("color", "");
                    $(li).addClass("dmn-selected");
                    $(li).find("li").attr("draggable", "false");
                    $(li).attr("draggable", "true");
                    var tar = $(li).find(".dmn-ttl")[0];
                    $(tar).css("color", "red");
                }
                if (!li.ondragstart && li.getAttribute("draggable") === "true") {
                    li.addEventListener('dragstart', function (event) {
                        var tag = $(this).closest("#xbrl_tree_view")
                            .find("li.dmn-selected")[0];
                        var spanTitle = $(tag).find(".dmn-ttl");
                        var data = {
                            id: tag.getAttribute("did"),
                            title: $(spanTitle).attr("data-original-title") || $(spanTitle).text()
                        };
                        var div = document.getElementById('drag-label');
                        div.style.display = "block";
                        var span = div.getElementsByTagName("span")[0];
                        span.innerText = 1;
                        event.dataTransfer.setData('application/json',
                            JSON.stringify({
                                action: "xbrlConcept",
                                model: data
                            }));
                        event.dataTransfer.setDragImage(div, 60, 0);
                    });
                    li.addEventListener('dragover', function (e) {
                        e.preventDefault();
                    });
                    li.addEventListener('dragleave', function (e) {
                        var div = document.getElementById('drag-label');
                        div.style.display = "none";
                        e.preventDefault();
                    });
                    li.addEventListener('dragend', function (e) {
                        var div = document.getElementById('drag-label');
                        div.style.display = "none";
                        e.preventDefault();
                    });
                }
                if (li.ondragstart && li.getAttribute("draggable") === "false") {
                    li.ondragstart = null;
                    li.ondragover = null;
                    li.ondragleave = null;
                    li.ondragend = null;
                }
            };
            if (obj.nt === 1 || obj.nt === 2) {
                var ul = _hh.createTag({
                    name: "ul", className: "dmn-c",
                    parent: li, attributes: { "dep": Number(depth) + 1 }
                });
                tUtil.buildChildren(ul, obj, options);
            }
        };
        var buildNodeSelectRow = function (target, obj, options) {
            var [li, depth] = tUtil.createLiTag(target, obj, options, null, {});
            var [att, iTag, folderI, iDot] = createSwitchPart(li, obj, options);
            var nameSpan = _hh.createElement("span", li);
            var sName = _h.shortName(obj.na);
            _hh.setClassName(nameSpan, "dmn-ttl");
            var title = sName[0];
            var accountType = _h.getEnumText(accountTypes, obj.at);
            title += " ( " + obj.co + " ) ";
            if (!_h.isNullOrEmpty(accountType)) {
                title += "-" + accountType.substring(0, 2);
            }
            if (depth === 0 && obj.nt === 1)
                tUtil.setPlusMinusAll(li);
            _hh.setInnerHtml(nameSpan, title);
            if ((options.substituteNode === true && obj.nt === 2) ||
                (obj.nt === 1 && options.branchSelectable) ||
                (obj.nt === 2 && options.branchSelectable) ||
                (obj.nt === 2 && !options.branchSelectable && obj.children.length === 0)) {
                _hh.setClassName(nameSpan, "dmn-ttl dmn-ntmg");
                nameSpan.onclick = function (ev) {
                    var li = this.parentNode;
                    var ids;
                    var instId = tUtil.getInstanceId(li);
                    var opts = tUtil.getOptions(instId);
                    var tree = tUtil.getTree(li);
                    _hh.hasClass(li, "dmn-selected");
                    if (opts.multi) {
                        if (ev.ctrlKey)
                            tUtil.toggleNodeSelectedTag(li, true);
                        else
                            tUtil.toggleNodeSelectedTag(li, false);

                        ids = tUtil.getSelectedItemsData(li, true);
                        opts.onClickItems(ids);
                    } else {
                        if (_hh.hasClass(li, "dmn-selected")) {
                            $(tree).find("li.dmn-selected").removeClass("dmn-selected");
                            $(tree).find(".dmn-ttl").css("color", "");
                            $(li).find(".dmn-ttl").css("color", "");
                            opts.onClickItem(undefined);
                        } else {
                            $(tree).find("li.dmn-selected").removeClass("dmn-selected");
                            $(tree).find(".dmn-ttl").css("color", "");
                            $(li).addClass("dmn-selected");
                            var tar = $(li).find(".dmn-ttl")[0];
                            $(tar).css("color", "red");
                            ids = tUtil.getSelectedItemsData(li, true);
                            opts.onClickItem(ids[0]);
                        }
                    }
                    ids = tUtil.getSelectedItemsData(li, true);
                    tUtil.setGuidSigns(tree, ids, opts);
                };
            }
            tUtil.createConsolidateTag(li, obj);
            if (obj.nt === 1 || obj.nt === 2) {
                var ul = _hh.createTag({
                    name: "ul", className: "dmn-c",
                    parent: li, attributes: { "dep": Number(depth) + 1 }
                });
                tUtil.buildChildren(ul, obj, options);
            }
            if (sName[1]) {
                _hh.setAttributes(nameSpan, { "title": obj.na });
            }
        };
        var buildReferenceRow = function (target, obj, options) {
            var acceptI, rejectI;
            var [li, depth] = tUtil.createLiTag(target, obj, options, null, {
                "dci": obj.ci,
                "dcht": obj.cht
            });
            var [att, iTag, folderI] = createSwitchPart(li, obj, options);
            var nameSpan = _hh.createElement("span", li);
            _hh.setClassName(nameSpan, "dmn-ttl dmn-ref");
            var sName = _h.shortName(obj.na);
            var title = sName[0] + " ( " + obj.co + " )";
            if (obj.at && obj.at > 0)
                title += " - " + _h.getEnumText(accountTypes, obj.at).substring(0, 2);
            _hh.setInnerHtml(nameSpan, title);
            if (sName[1]) {
                _hh.setAttributes(nameSpan, { "title": obj.na });
            }
            if (obj.nt === 1 && obj.nte === 1 && !obj.cc)
                nameSpan.style.textDecoration = "underline";

            nameSpan.onclick = function (ev) {
                var li = this.parentNode;
                var tree = tUtil.getTree(li)[0];
                var options = tUtil.getTreeOptions(li);
                if (_hh.hasClass(li, "dmn-selected")) {
                    $(tree).find("li.dmn-selected").removeClass("dmn-selected");
                    $(tree).find(".dmn-ttl").css("color", "");
                    $(li).find(".dmn-ttl").css("color", "");
                } else {
                    $(tree).find("li.dmn-selected").removeClass("dmn-selected");
                    $(tree).find(".dmn-ttl").css("color", "");
                    $(li).addClass("dmn-selected");
                    var tar = $(li).find(".dmn-ttl")[0];
                    $(tar).css("color", "red");
                }
                var selectedItems = tree.getElementsByClassName("dmn-selected");
                var array = [];
                if (selectedItems && selectedItems.length)
                    for (var j = 0; j < selectedItems.length; j++) {
                        array.push({ value: selectedItems[j].getAttribute("did") });
                    }
                options.onDeffTreeSelect("ref", array);

            };
            if (obj.cht !== 0) {
                acceptI = _hh.createElement("i", li);
                rejectI = _hh.createElement("i", li);
                _hh.setClassName(acceptI, "dmn-acc fa fa-check");
                _hh.setClassName(rejectI, "dmn-rem fa fa-remove");
                _hh.setAttributes(acceptI,
                    { "title": "اعمال تغییر" });
                _hh.setAttributes(rejectI,
                    { "title": "رد تغییر" });
                acceptI.onclick = function () {
                    var list = [];
                    var li = _hh.getClosest(this, "li");
                    list.push(Number(li.getAttribute("did")));
                    var liList = li.getElementsByTagName("li");
                    if (liList && liList.length)
                        for (var j = 0; j < liList.length; j++) {
                            list.push(Number(liList[j].getAttribute("did")));
                        }
                    options.onApplyItem(list, function (res) {
                        if (res) {
                            _hh.removeElement(this);
                        }
                    });
                };
                rejectI.onclick = function () {
                    var list = [];
                    var li = _hh.getClosest(this, "li");
                    list.push(Number(li.getAttribute("did")));
                    var liList = li.getElementsByTagName("li");
                    if (liList && liList.length)
                        for (var j = 0; j < liList.length; j++) {
                            list.push(Number(liList[j].getAttribute("did")));
                        }
                    options.onRejectItem(list, function (res) {
                        if (res) {
                            _hh.removeElement(this);
                        }
                    });
                };
                switch (obj.cht) {
                    case 1:
                        if (folderI) {
                            folderI.classList.add("dmn-add");
                            _hh.setAttributes(folderI,
                                { "title": "ایجاد" });
                        }
                        if (att) {
                            att.classList.add("dmn-add");
                            _hh.setAttributes(att,
                                { "title": "ایجاد" });
                        }
                        break;
                    case 2:
                        if (folderI) {
                            folderI.classList.add("dmn-edt");
                            _hh.setAttributes(folderI,
                                { "title": "ویرایش" });
                        }
                        if (att) {
                            att.classList.add("dmn-edt");
                            _hh.setAttributes(att,
                                { "title": "ویرایش" });
                        }
                        break;
                    case 3:
                        if (folderI) {
                            folderI.classList.add("dmn-dele");
                            _hh.setAttributes(folderI,
                                { "title": "حذف" });
                        }
                        if (att) {
                            att.classList.add("dmn-dele");
                            _hh.setAttributes(att,
                                { "title": "حذف" });
                        }
                        break;
                }
            }
            if (depth === 0 && obj.nt === 1)
                tUtil.setPlusMinusAll(li);
            if (obj.nt === 1 || obj.nt === 2) {
                var ul = _hh.createTag({
                    name: "ul", className: "dmn-c",
                    parent: li, attributes: { "dep": Number(depth) + 1 }
                });
                tUtil.buildChildren(ul, obj, options);
            }

        };
        var buildCurrentRow = function (target, obj, options) {
            var [li, depth] = tUtil.createLiTag(target, obj, options, null, {
                "dci": obj.ci,
                "dcht": obj.cht
            });
            var [att, iTag, folderI] = createSwitchPart(li, obj, options);
            var nameSpan = _hh.createElement("span", li);
            _hh.setClassName(nameSpan, "dmn-ttl dmn-ref");
            var sName = _h.shortName(obj.na);
            var title = sName[0] + " ( " + obj.co + " )";
            if (obj.at && obj.at > 0)
                title += " - " + _h.getEnumText(accountTypes, obj.at).substring(0, 2);
            _hh.setInnerHtml(nameSpan, title);

            if (obj.nt === 1 && obj.nte === 1 && !obj.cc)
                nameSpan.style.textDecoration = "underline";

            if (sName[1]) {
                _hh.setAttributes(nameSpan, { "title": obj.na });
            }
            nameSpan.onclick = function (ev) {
                var li = this.parentNode;
                var tree = tUtil.getTree(li)[0];
                var options = tUtil.getTreeOptions(li);
                if (_hh.hasClass(li, "dmn-selected")) {
                    $(tree).find("li.dmn-selected").removeClass("dmn-selected");
                    $(tree).find(".dmn-ttl").css("color", "");
                    $(li).find(".dmn-ttl").css("color", "");
                } else {
                    $(tree).find("li.dmn-selected").removeClass("dmn-selected");
                    $(tree).find(".dmn-ttl").css("color", "");
                    $(li).addClass("dmn-selected");
                    var tar = $(li).find(".dmn-ttl")[0];
                    $(tar).css("color", "red");
                }
                var selectedItems = tree.getElementsByClassName("dmn-selected");
                var array = [];
                if (selectedItems && selectedItems.length)
                    for (var j = 0; j < selectedItems.length; j++) {
                        array.push({ value: selectedItems[j].getAttribute("did") });
                    }
                options.onDeffTreeSelect("cr", array);

            };
            if (depth === 0 && obj.nt === 1)
                tUtil.setPlusMinusAll(li);
            if (obj.nt === 1 || obj.nt === 2) {
                var ul = _hh.createTag({
                    name: "ul", className: "dmn-c",
                    parent: li, attributes: { "dep": Number(depth) + 1 }
                });
                tUtil.buildChildren(ul, obj, options);
            }
        };
        var buildMappingSrcRow = function (target, obj, options, targetLi) {
            var [li, depth] = tUtil.createLiTag(target, obj, options, targetLi, {
                "dim": obj.im,
                "dis": obj.dis
            });
            var [att, iTag, folderI] = createSwitchPart(li, obj, options);
            var nameSpan = _hh.createElement("span", li);
            var sName = _h.shortName(obj.na);
            if (obj.im)
                _hh.setClassName(nameSpan, "dmn-ttl dmn-im");
            else
                _hh.setClassName(nameSpan, "dmn-ttl dmn-rp");

            var title = sName[0];
            var accountType = _h.getEnumText(accountTypes, obj.at);
            title += " ( " + obj.co + " ) ";
            if (!_h.isNullOrEmpty(accountType)) {
                title += "-" + accountType.substring(0, 2);
            }
            if (sName[1]) {
                _hh.setAttributes(nameSpan, { "title": obj.na });
            }
            if (depth === 0 && obj.nt === 1)
                tUtil.setPlusMinusAll(li);

            _hh.setInnerHtml(nameSpan, title);
            nameSpan.onclick = function (ev) {
                var li = this.parentNode;
                var dis = li.getAttribute("dis");
                var dim = li.getAttribute("dim");
                var tree = tUtil.getTree(li);
                tUtil.toggleSelectedMappingSrcTag(li, true);
                if (li.ondragstart && dis !== "false" && dim !== "false") {
                    li.ondragstart = null;
                }
                if (!li.ondragstart && dis === "false" && dim === "false") {
                    li.addEventListener('dragstart', function (event) {
                        var tags = $(this).closest(".dmn-tree")
                            .find("li.dmn-selected");
                        var length = tags.length;
                        var div = document.getElementById('drag-label');

                        div.style.display = "block";
                        var span = div.getElementsByTagName("span")[0];
                        span.innerText = length;
                        event.dataTransfer.setDragImage(div, 60, 0);
                    });
                }
            };
            tUtil.createConsolidateTag(li, obj);
            if (obj.nt === 1 || obj.nt === 2) {
                var ul = _hh.createTag({
                    name: "ul", className: "dmn-c",
                    parent: li, attributes: { "dep": Number(depth) + 1 }
                });
                tUtil.buildChildren(ul, obj, options);
            }
        };
        var buildCompanySettingRow = function (target, obj, options) {
            var [li, depth] = tUtil.createLiTag(target, obj, options, null, {
                "dna": obj.na
            });
            var chkDiv = _hh.createElement("div", li);
            _hh.setClassName(chkDiv, "awcheckbox awcheckbox-success awcheckbox-inline treeitem-chkbox");
            var chkInput = _hh.createElement("input", chkDiv);
            if (!obj.selected) {
                _hh.setAttributes(chkInput,
                    {
                        "type": "checkbox",
                        "id": "Com-Sel_" + obj.id,
                        "did": obj.id
                    });
            } else {
                _hh.setAttributes(chkInput,
                    {
                        "type": "checkbox",
                        "id": "Com-Sel_" + obj.id,
                        "did": obj.id,
                        "checked": obj.selected
                    });
            }

            var chkLabel = _hh.createTag({
                name: "label",
                parent: chkDiv, attributes: { "for": "Com-Sel_" + obj.id },
                onclick: function () {
                    var parent = $(this).parent().parent();
                    var input = parent.find("input")[0];
                    var inputs = parent.find("input");
                    var parents = tUtil.getParents(parent[0]);
                    if (!$(input).is(':checked')) {

                        if (inputs && inputs.length)
                            for (var j = 0; j < inputs.length; j++) {
                                if (inputs[j].id !== input.id)
                                    inputs[j].checked = true;
                            }
                        if (parents && parents.length)
                            for (var l = 0; l < parents.length; l++) {
                                var parentInput = $(parents[l]).find("input")[0];
                                parentInput.checked = true;
                            }

                    } else {
                        if (inputs && inputs.length)
                            for (var k = 0; k < inputs.length; k++) {
                                if (inputs[k].id !== input.id)
                                    inputs[k].checked = false;
                            }
                    }
                    return true;
                }
            });
            var [att, iTag, folderI] = createSwitchPart(li, obj, options);
            var sName = _h.shortName(obj.na);
            var nameSpan = _hh.createTag({
                name: "span", className: "dmn-ttl dmn-ref",
                text: sName[0],
                parent: li, attributes: { "dep": Number(depth) + 1 }
            });

            if (sName[1]) {
                _hh.setAttributes(nameSpan, { "title": sName[1] });
            }
            nameSpan.onclick = function (ev) {
                var li = this.parentNode;
                tUtil.toggleSelectedTag(li, true);
            };
            if (depth === 0 && obj.nt === 0)
                tUtil.setPlusMinusAll(li);

            if (obj.nt === 0) {
                var ul = _hh.createTag({
                    name: "ul", className: "dmn-c",
                    parent: li, attributes: { "dep": Number(depth) + 1 }
                });
                tUtil.buildChildren(ul, obj, options);
            }

        };
        var buildPermissionRow = function (target, obj, options) {
            var [li, depth] = tUtil.createLiTag(target, obj, options, null, {
                "dna": obj.na
            });
            var chkDiv = _hh.createElement("div", li);
            _hh.setClassName(chkDiv, "awcheckbox awcheckbox-success awcheckbox-inline treeitem-chkbox");
            var chkInput = _hh.createElement("input", chkDiv);
            if (!obj.selected) {
                _hh.setAttributes(chkInput,
                    {
                        "type": "checkbox",
                        "id": "Com-Sel_" + obj.id,
                        "did": obj.id
                    });
            } else {
                _hh.setAttributes(chkInput,
                    {
                        "type": "checkbox",
                        "id": "Com-Sel_" + obj.id,
                        "did": obj.id,
                        "checked": obj.selected
                    });
            }

            _hh.createTag({
                name: "label",
                parent: chkDiv, attributes: { "for": "Com-Sel_" + obj.id },
                onclick: function () {
                    var parent = $(this).parent().parent();
                    var tree = tUtil.getTree(parent);
                    var input = parent.find("input")[0];
                    var inputs = parent.find("input");
                    var parents = tUtil.getParents(parent[0]);
                    var options = getTreeOptions(parent);
                    if (!$(input).is(':checked')) {

                        if (inputs && inputs.length)
                            for (var j = 0; j < inputs.length; j++) {
                                if (inputs[j].id !== input.id)
                                    inputs[j].checked = true;
                            }
                        if (parents && parents.length)
                            for (var l = 0; l < parents.length; l++) {
                                var parentInput = $(parents[l]).find("input")[0];
                                parentInput.checked = true;
                            }

                    } else {
                        if (inputs && inputs.length)
                            for (var k = 0; k < inputs.length; k++) {
                                if (inputs[k].id !== input.id)
                                    inputs[k].checked = false;
                            }
                    }
                    setTimeout(function () {
                        options.context.onClickItem();
                        tUtil.changeCheckboxes(tree);
                    }, 200);

                    return true;
                }
            });
            var [att, iTag, folderI] = createSwitchPart(li, obj, options);
            var sName = _h.shortName(obj.na);
            var nameSpan = _hh.createTag({
                name: "span", className: "dmn-ttl dmn-ref",
                text: sName[0],
                parent: li, attributes: { "dep": Number(depth) + 1 }
            });

            if (sName[1]) {
                _hh.setAttributes(nameSpan, { "title": obj.na });
            }

            if (obj.nt === 1) {
                var ul = _hh.createTag({
                    name: "ul", className: "dmn-c",
                    parent: li, attributes: { "dep": Number(depth) + 1 }
                });
                tUtil.buildChildren(ul, obj, options);
            }

        };
        var buildCompanyAccessUserRow = function (target, obj, options) {
            var [li, depth] = tUtil.createLiTag(target, obj, options, null, {
                "dal": JSON.stringify(obj.userAccesses)
            });
            var [att, iTag, folderI] = createSwitchPart(li, obj, options);
            var nameSpan = _hh.createElement("span", li);
            _hh.setClassName(nameSpan, "dmn-ttl dmn-ref");
            _hh.setInnerHtml(nameSpan, obj.na);
            if (obj.nt === 0) {
                var ul = _hh.createTag({
                    name: "ul", className: "dmn-c",
                    parent: li, attributes: { "dep": Number(depth) + 1 }
                });
                tUtil.buildChildren(ul, obj, options);
            }
            nameSpan.onclick = function (ev) {
                var li = this.parentNode;
                var tree = tUtil.getTree(li)[0];
                var options = tUtil.getTreeOptions(li);
                var res = false;
                if (_hh.hasClass(li, "dmn-selected")) {
                    $(tree).find("li.dmn-selected").removeClass("dmn-selected");
                    $(tree).find(".dmn-ttl").css("color", "");
                    $(li).find(".dmn-ttl").css("color", "");
                } else {
                    $(tree).find("li.dmn-selected").removeClass("dmn-selected");
                    $(tree).find(".dmn-ttl").css("color", "");
                    $(li).addClass("dmn-selected");
                    var tar = $(li).find(".dmn-ttl")[0];
                    $(tar).css("color", "red");
                    res = true;
                }
                if (res) {
                    var accessBox = document.getElementsByClassName("user-access-list")[0];
                    accessBox.innerHTML = "";
                    var list = JSON.parse(li.getAttribute("dal"));
                    for (let i = 0; i < list.length; i++) {
                        var liTag = _hh.createTag({ name: "li", parent: accessBox });
                        var chkDiv = _hh.createTag({
                            name: "div", parent: liTag,
                            className: "awcheckbox awcheckbox-success awcheckbox-inline",
                            styles: "margin-bottom: 10px;font-size: 10px;"
                        });
                        var attributes = {};
                        if (list[i].selected)
                            attributes = {
                                "type": "checkbox", "checked": list[i].selected, "id": 'AccessU-' + list[i].value,
                                'data-id': list[i].value, 'data-txt': list[i].text
                            };
                        else
                            attributes = {
                                "type": "checkbox",
                                "id": 'AccessU-' + list[i].value,
                                'data-id': list[i].value,
                                'data-txt': list[i].text
                            };
                        _hh.createTag({
                            name: "input", parent: chkDiv,
                            attributes: attributes,
                            onclick: function (ev) {
                                var accessBox = document.getElementsByClassName("user-access-list")[0];
                                var tree = document.getElementById("tree_view_au");
                                var liSelected = $(tree).find("li.dmn-selected");
                                var checkBoxes = $(accessBox).find("input");
                                var array = [];
                                for (let j = 0; j < checkBoxes.length; j++) {
                                    array.push({
                                        "value": Number(checkBoxes[j].getAttribute("data-id")),
                                        "selected": checkBoxes[j].checked,
                                        "text": checkBoxes[j].getAttribute("data-txt")
                                    });
                                }
                                _hh.setAttributes(liSelected[0], { "dal": JSON.stringify(array) });
                            }
                        });
                        _hh.createTag({
                            name: "label", parent: chkDiv,
                            attributes: { 'for': 'AccessU-' + list[i].value },
                            text: list[i].text
                        });


                    }
                }
            };
        };
        var buildCompanyRow = function (target, obj, options) {
            var li = _hh.createElement("li", target);
            var orgObj = obj;
            $(li).data(orgObj);
            obj = ko.toJS(obj);
            obj.nt = obj.nt + 1;
            var depth = target.getAttribute("dep");
            if (!depth)
                depth = 0;
            _hh.setAttributes(li,
                {
                    "dep": Number(depth) + 1,
                    "did": obj.id,
                    "dct": obj.nt,
                    "dst": obj.stateType,
                });

            var [att, iTag, folderI] = createSwitchPart(li, obj, options);
            var nameSpan = _hh.createElement("span", li);
            var nameClass = "dmn-ttl dmn-ref";
            if (obj.stateType === 0) {
                nameClass = "dmn-ttl dmn-ref node-codis";
            }
            if (obj.mainCompany) {
                nameSpan.style.fontWeight = "bold";
            }
            _hh.setClassName(nameSpan, nameClass);
            _hh.setInnerHtml(nameSpan, obj.na);
            if (obj.de) {
                var descTag = _hh.createElement("i", li);
                _hh.setClassName(descTag, "dmn-info fa fa-info-circle");
                _hh.setAttributes(descTag, { "title": obj.de });
            }
            nameSpan.onclick = function (ev) {
                var li = this.parentNode;
                var tree = tUtil.getTree(li)[0];
                var options = tUtil.getTreeOptions(li);
                if (_hh.hasClass(li, "dmn-selected")) {
                    $(tree).find("li.dmn-selected").removeClass("dmn-selected");
                    $(tree).find(".dmn-ttl").css("color", "");
                    $(li).find(".dmn-ttl").css("color", "");
                } else {
                    $(tree).find("li.dmn-selected").removeClass("dmn-selected");
                    $(tree).find(".dmn-ttl").css("color", "");
                    $(li).addClass("dmn-selected");
                    var tar = $(li).find(".dmn-ttl")[0];
                    $(tar).css("color", "red");
                }
                options.context.onTreeNodeSelect($(li).data());
            };
            nameSpan.ondblclick = function (ev) {
                var li = ev.target.parentNode.parentNode;
                var tree = tUtil.getTree(li);
                var options = tUtil.getTreeOptions(li);
                options.actions.onEdit(li.getAttribute("did"), null, li);
            };
            li.oncontextmenu = function (ev) {
                var li = null;
                if (this.nodeName === "LI")
                    li = this;
                if (this.nodeName === "SPAN")
                    li = this.parentNode;
                var pos = _h.getPosition(ev.currentTarget);
                var tree = tUtil.getTree(li);
                var options = tUtil.getTreeOptions(li);

                if (!_h.kocnx().permitPeriodEdit()) {
                    return false
                }

                if (!_hh.hasClass(li, "dmn-selected")) {
                    $(tree).find("li.dmn-selected").removeClass("dmn-selected");
                    $(tree).find(".dmn-ttl").css("color", "");
                    $(li).addClass("dmn-selected");
                    var tar = $(li).find(".dmn-ttl")[0];
                    $(tar).css("color", "red");
                    options.context.onTreeNodeSelect($(li).data());
                }
                var menu = document.getElementsByClassName("context-menu")[0];
                if (menu)
                    menu.parentNode.removeChild(menu);

                var nav = document.createElement('nav');
                document.body.appendChild(nav);
                _hh.setAttributes(nav, {
                    "target": tree[0].getAttribute("tv-id")
                });
                nav.className = "context-menu";
                _hh.setClassName(nav, "context-menu");
                var ul = _hh.createElement("ul", nav);
                _hh.setClassName(ul, "mt-contextmenu");
                for (let i = 0; i < options.context.menuItems().length; i++) {
                    var button = options.context.menuItems()[i];
                    if (!options.context[button.visName]())
                        continue;
                    var lim = _hh.createElement("li", ul);
                    var a = _hh.createElement("a", lim);
                    lim.setAttribute("data-action", button.visName.replace("vis", ""));
                    var caption = _hh.createElement("span", a);
                    caption.innerText = button.text;
                    _hh.setClassName(caption, "mt-contextmenu-text");
                    var iconSpan = _hh.createElement("span", a);
                    _hh.setClassName(iconSpan, "mt-contextmenu-icon");
                    var image = _hh.createElement("img", iconSpan);
                    image.src = "/App/src/images/ico/" + _h.getIcon(button.icon);
                    lim.onclick = function (event) {
                        var dataAction = this.getAttribute("data-action");
                        var actionName = dataAction + "Btn";
                        options.context[actionName]();
                    };
                }
                ev.cancelBubble = true;
                nav.style.top = (pos.top + 30) + "px";
                nav.style.left = pos.right + "px";
                document.onclick = function () {
                    var menu = document.getElementsByClassName("context-menu")[0];
                    if (menu) {
                        menu.parentNode.removeChild(menu);
                    }
                };
                return false;
            };
            if (obj.nt === 1) {
                var ul = _hh.createTag({
                    name: "ul", className: "dmn-c",
                    parent: li, attributes: { "dep": Number(depth) + 1 }
                });
                var children = ko.isObservable(orgObj.children) ? orgObj.children() : orgObj.children;
                for (var i = 0; i < children.length; i++) {
                    tUtil.buildCompanyRow(ul, children[i], options);
                }

                if (obj.isRoot) {
                    var firstSign = $(li).find(".dmn-p")[0];
                    $(firstSign).trigger("click");
                    $(li).addClass("dmn-selected");
                    var tar = $(li).find(".dmn-ttl")[0];
                    $(tar).css("color", "red");
                    options.context.onTreeNodeSelect($(li).data());
                }
            }
        };
        var buildHelpRow = function (target, obj, options) {
            var li = _hh.createElement("li", target);
            $(li).data(obj);
            var depth = target.getAttribute("dep");
            if (!depth)
                depth = 0;
            _hh.setAttributes(li,
                {
                    "dep": Number(depth) + 1,
                    "did": obj.id,
                    "dct": obj.nt
                });
            var [att, iTag, folderI] = createSwitchPart(li, obj, options);
            var nameSpan = _hh.createElement("span", li);
            _hh.setClassName(nameSpan, "dmn-ttl dmn-ref");
            _hh.setInnerHtml(nameSpan, obj.na);
            nameSpan.onclick = function (ev) {
                var li = this.parentNode;
                var tree = tUtil.getTree(li)[0];
                var options = tUtil.getTreeOptions(li);
                if (_hh.hasClass(li, "dmn-selected")) {
                    $(tree).find("li.dmn-selected").removeClass("dmn-selected");
                    $(tree).find(".dmn-ttl").css("color", "");
                    $(li).find(".dmn-ttl").css("color", "");
                } else {
                    $(tree).find("li.dmn-selected").removeClass("dmn-selected");
                    $(tree).find(".dmn-ttl").css("color", "");
                    $(li).addClass("dmn-selected");
                    var tar = $(li).find(".dmn-ttl")[0];
                    $(tar).css("color", "red");
                }
                options.onSelectRow($(li).data());
            };
            if (obj.nt === 1) {
                var ul = _hh.createTag({
                    name: "ul", className: "dmn-c",
                    parent: li, attributes: { "dep": Number(depth) + 1 }
                });
                for (var i = 0; i < orgObj.children().length; i++) {
                    tUtil.buildHelpRow(ul, orgObj.children()[i], options);
                }
            }
        }
        var buildRow = function (target, obj, options) {
            if (tUtil["build" + options.tType + "Row"])
                tUtil["build" + options.tType + "Row"](target, obj, options);
            else
                treeEditor.buildEditorRow(target, obj, options);
        };
        var handleOldVersion = function (options) {
            var item = $.fn.treeView.options.instances
                .filter(el => el.type === options.tType && el.location === options.location);
            if (item.length) {
                item = item[0];
                options.expandList = item.opts.expandList;
                var index = $.fn.treeView.options.instances.indexOf(item);
                delete $.fn.treeView.options.instances[index];
            }
        }
        var build = function (target, options) {
            if (!target.length)
                return false;
            if (options.multi) {
                $(target).addClass("dmn-tree tv-multi");
            } else {
                $(target).addClass("dmn-tree");
            }
            target = target.get(0);
            options.treeEl = target;
            target.innerHTML = "";

            var randomId = Number((Math.random() * (10000000 - 100) + 100).toString().replace(".", ""));
            handleOldVersion(options);
            $.fn.treeView.options.instances.push({ id: randomId, opts: options, type: options.tType });
            _hh.setAttributes(target,
                {
                    "tv-rootId": options.rootId,
                    "tv-id": randomId,
                    "t-type": options.tType
                });
            if (!ko.isObservable(options.nodes)) {
                if (options.nodes && options.nodes.length)
                    for (let i = 0; i < options.nodes.length; i++) {
                        buildRow(target, options.nodes[i], options);
                    }
            } else {
                if (options.nodes() && options.nodes().length)
                    for (let i = 0; i < options.nodes().length; i++) {
                        buildRow(target, options.nodes()[i], options);
                    }
            }
            if (options.selectedItems && options.selectedItems().length) {
                setTimeout(function () {
                    setSelectedItems(target, options);
                }, 150);
            }
            if (options.selectedItem) {
                setTimeout(function () {
                    setSelectedItem(target, options);
                }, 150);
            }
            switch (options.tType) {
                case "Permission":
                    tUtil.changeCheckboxes($(target));
                    break;
            }
            _h.activeTooltip();
        };
        var typeOfRefreshInput = function (input) {
            if (input === "0" || input === 0)
                return "new";
            if (typeof input == 'string' && input.startsWith("U"))
                return "uid";
            if (typeof input == 'string' && $.isNumeric(input))
                return "numberString";
            if (typeof input == 'number')
                return "number";
        };
        var removeUselessSigns = function (tree) {
            var liList = $(tree).find("li:not(:has('li'))");
            if (liList.length)
                for (var i = 0; i < liList.length; i++) {
                    var item = liList[i];
                    var sign = $(item).find(".dmn-p");
                    if (sign.length > 0) {
                        $(item).find(".dmn-p").remove();
                    }
                }
        };
        var resetITagSigns = function (tree) {
            var liList = $(tree).find("li:not(:has('li'))");
            if (liList.length)
                for (var i = 0; i < liList.length; i++) {
                    var item = liList[i];
                    var sign = $(item).find(".dmn-p");
                    if (sign.length > 0) {
                        $(sign).addClass("fa-plus");
                        $(sign).removeClass("fa-minus text-danger");
                        $(item).find("ul").addClass("dmn-c");
                    }
                }
        };
        return {
            build: build,
            buildChildren: buildChildren,
            buildHelpRow: buildHelpRow,
            buildMappingRow: buildMappingRow,
            buildMappingDestRow: buildMappingDestRow,
            buildBalanceReportRow: buildBalanceReportRow,
            buildTreeInfoRow: buildTreeInfoRow,
            buildXbrlConceptRow: buildXbrlConceptRow,
            buildNodeSelectRow: buildNodeSelectRow,
            buildReferenceRow: buildReferenceRow,
            buildCurrentRow: buildCurrentRow,
            buildCompanySettingRow: buildCompanySettingRow,
            buildCompanyAccessUserRow: buildCompanyAccessUserRow,
            buildCompanyRow: buildCompanyRow,
            buildMappingSrcRow: buildMappingSrcRow,
            buildPermissionRow: buildPermissionRow,
            changeCheckboxes: changeCheckboxes,
            createLiTag: createLiTag,
            createConsolidateTag: createConsolidateTag,
            getInstanceId: getInstanceId,
            getOptions: getOptions,
            getTreeOptions: getTreeOptions,
            createNodePath: createNodePath,
            getNodeParentId: getNodeParentId,
            toggleSelectedTag: toggleSelectedTag,
            toggleNodeSelectedTag: toggleNodeSelectedTag,
            openGuideSign: openGuideSign,
            getParents: getParents,
            changeOtherSideSelectedItem: changeOtherSideSelectedItem,
            getSelectedItemsData: getSelectedItemsData,
            setGuidSigns: setGuidSigns,
            toggleGuideSign: toggleGuideSign,
            resetGuidSigns: resetGuidSigns,
            getTree: getTree,
            getNode: getNode,
            refreshSelectItems: refreshSelectItems,
            droppableMappingDestNode: droppableMappingDestNode,
            setITag: setITag,
            toggleSelectedMappingSrcTag: toggleSelectedMappingSrcTag,
            setUnlinkTag: setUnlinkTag,
            setPlusMinusAll: setPlusMinusAll,
            toggleShowChildren: toggleShowChildren,
            getConsolidationBranchData: getConsolidationBranchData,
            typeOfRefreshInput: typeOfRefreshInput,
            removeUselessSigns: removeUselessSigns,
            resetITagSigns: resetITagSigns,
            collectOpenBranches: collectOpenBranches,
            openBranches: openBranches,
            createDragListData: createDragListData
        };
    }();
    var tVMethods = {
        init: function (options) {
            tUtil.build(this, options);
        },
        expandAll: function () {
            this.find("ul").removeClass("dmn-c");
            this.find(".dmn-p").addClass("fa-minus text-danger");
            this.find(".dmn-p").removeClass("fa-plus");
            this.find(".dmn-fld").addClass("fa-folder");
            this.find(".dmn-fld").removeClass("fa-folder-open");
            tUtil.collectOpenBranches(this);
        },
        expand: function (list) {
            if (_h.any(list))
                for (var i = 0; i < list.length; i++) {
                    var li = $(this).find("[did='" + list[i] + "']");
                    if (li.length) {
                        $(li).find("ul").first().removeClass("dmn-c");
                        $(li).find(".dmn-p").first().addClass("fa-minus text-danger");
                        $(li).find(".dmn-p").first().removeClass("fa-plus");
                        $(li).find(".dmn-fld").first().addClass("fa-folder");
                        $(li).find(".dmn-fld").first().removeClass("fa-folder-open");
                    }
                }
        },
        collapseAll: function () {
            this.find("ul").addClass("dmn-c");
            this.find(".dmn-p").removeClass("fa-minus text-danger");
            this.find(".dmn-p").addClass("fa-plus");
            this.find(".dmn-fld").addClass("fa-folder-open");
            this.find(".dmn-fld").removeClass("fa-folder");
            var options = tUtil.getTreeOptions(this);
            options.expandList = [];
        },
        collectOpenBranches: function () {
            var tree = tUtil.getTree(this);
            tUtil.collectOpenBranches(tree);
        },
        openBranches: function () {
            var tree = tUtil.getTree(this);
            tUtil.openBranches(tree);
        },
        clearSelect: function () {
            this.find("li").removeClass("dmn-selected");
            this.find(".dmn-ttl").css("color", "#6a6c6f");
            tUtil.resetGuidSigns(this);
        },
        refreshSelectItems: function (list) {
            this.find("li").removeClass("dmn-selected");
            this.find(".dmn-ttl").css("color", "");
            tUtil.refreshSelectItems(this, list);
        },
        removeTree: function () {
            $(this).empty();
        },
        selectedItems: function () {
            var treeOpts = tUtil.getTreeOptions(this);
            var tags = $(this).find("li.dmn-selected");
            var list = [];
            for (var j = 0; j < tags.length; j++) {
                var path = tUtil.createNodePath(tags[j], treeOpts.rootName);
                list.push({
                    id: Number(tags[j].getAttribute("did")),
                    code: tags[j].getAttribute("dco"),
                    nodeType: Number(tags[j].getAttribute("dnt")),
                    periodType: treeOpts.periodType,
                    path: path
                });
            }
            return list;
        },
        selectedCheckedItems: function () {
            var inputs = $(this).find("input:checked");
            var list = [];
            for (var j = 0; j < inputs.length; j++) {
                var item = Number(inputs[j].getAttribute("did"));
                list.push(item);
            }
            return list;
        },
        refreshTree: function (list, edit) {
            var tree = tUtil.getTree(this);
            var options = tUtil.getTreeOptions(tree);
            if (list && list.length)
                for (var i = 0; i < list.length; i++) {
                    var obj = list[i];
                    var li = 0;
                    var typeOfId = tUtil.typeOfRefreshInput(obj.id);
                    if (obj.uid)
                        typeOfId = tUtil.typeOfRefreshInput(obj.uid);
                    switch (typeOfId) {
                        case "number":
                            li = tUtil.getNode(tree[0], obj.id)[0];
                            break;
                        case "numberString":
                            li = tUtil.getNode(tree[0], Number(obj.id))[0];
                            break;
                        case "uid":
                            if (obj.uid)
                                li = tree[0].querySelectorAll('[duid="' + obj.uid + '"]')[0];
                            else
                                li = tree[0].querySelectorAll('[duid="' + obj.id + '"]')[0];
                            break;
                        case "new":
                            li = tree[0].querySelectorAll('[duid="' + obj.uid + '"]')[0];
                            break;
                    }
                    if (obj.del) {
                        _hh.removeElement(li);
                        continue;
                    }
                    if (!li) {
                        switch (options.tType) {
                            case "MappingSrc":
                                tUtil.buildMappingSrcRow(tree[0], obj, options);
                                break;
                            case "Editor":
                                treeEditor.buildEditorRow(tree[0], obj, options);
                                break;
                            case "Mapping":
                                tUtil.buildMappingRow(tree[0], obj, options);
                                break;
                        }
                    } else {
                        var ulTarget = li.parentNode;
                        switch (options.tType) {
                            case "MappingSrc":
                                tUtil.buildMappingSrcRow(ulTarget, obj, options, li);
                                break;
                            case "Editor":
                                treeEditor.buildEditorRow(ulTarget, obj, options, li, edit);
                                break;
                            case "Mapping":
                                tUtil.buildMappingRow(ulTarget, obj, options, li);
                                break;
                        }
                    }
                }
            _h.activeTooltip();
            if (options.actions)
                options.actions.onCallbackAction();
        },
        changeShowMapped: function (val) {
            var tree = tUtil.getTree(this);
            var options = tUtil.getTreeOptions(tree);
            options.showMapped = val;
        },
        clearSelectItems: function () {
            var liList = this.find("li");
            if (liList && liList.length)
                for (var i = 0; i < liList.length; i++) {
                    var li = liList[i];
                    $(li).removeClass("dmn-selected");
                    li.ondragstart = null;
                    li.ondragover = null;
                    li.ondragleave = null;
                    li.ondragend = null;
                }
            this.find(".dmn-ttl").css("color", "");
        },
        removeItems: function () {
            this.find("li.dmn-selected").remove();
            _h.kocnx().treevm().onCallbackAction();
        },
        selectSubSet: function () {
            var list = this.find("li.dmn-selected");
            if (list && list.length)
                for (var i = 0; i < list.length; i++) {
                    var item = list[i];
                    $(item).find("li").addClass("dmn-selected");
                    $(item).find(".dmn-ttl").css("color", "red");
                }

        },
        getPasteModel: function (inRoot) {
            var inComplex = treeEditor.inComplexStatus();
            var tree = treeEditor.getTree();
            var treeId = tree.getAttribute("tv-rootid");
            var selectedItem = treeEditor.getSelectedElements()[0];
            var model = {
                treeId: Number(treeId),
                idList: [],
                newParentId: 0,
                nodeId: 0,
                type: ""
            };
            if (inComplex.copy) {
                var liList = tree.getElementsByClassName("copy-el");
                if (inRoot) {
                    model.newParentId = Number(treeId);
                } else {
                    model.newParentId = Number(selectedItem.getAttribute("did"));
                }
                model.type = 1;
                if (liList && liList.length)
                    for (var j = 0; j < liList.length; j++) {
                        var id = Number(liList[j].getAttribute("did"));
                        model.idList.push(id);
                    }
            }
            if (inComplex.cut) {
                var li = tree.getElementsByClassName("cut-el")[0];
                model.type = 2;
                model.nodeId = Number(li.getAttribute("did"));
                if (inRoot) {
                    model.newParentId = Number(treeId);
                } else {
                    model.newParentId = Number(selectedItem.getAttribute("did"));
                }
            }

            return model;
        },
        refreshAfterPaste: function (type) {
            var tree = treeEditor.getTree();
            if (type === 1) {
                $(tree).find("li").removeClass("paste-target dmn-temp-selected");
            } else {
                this.find("li").removeClass("dmn-selected");
                this.find(".dmn-ttl").css("color", "");
                $(tree).find("li").removeClass("copy-el paste-target dmn-temp-selected");
                $(tree).find("li.cut-el").remove();
            }

            _h.activeTooltip();
        },
        nodeCreate: function (treeType, assignmentType, accountType, companyId) {
            treeEditor.onCreateNode(treeType, assignmentType, accountType, companyId);
        },
        inComplexMode: function () {
            return treeEditor.inComplexStatus();
        },
        getChangedItems: function () {
            var tree = treeEditor.getTree();
            var options = treeEditor.getOptions();
            var orderChangeList = $(tree).find("li[dpr]");
            var newList = $(tree).find("li[did='0']");
            var changeList = $(tree).find("li[dcng='true'][did!='0']");
            var li, obj, parent;
            var array = [];
            if (newList && newList.length) {
                for (var k = 0; k < newList.length; k++) {
                    li = newList[k];
                    obj = treeEditor.collectObj(li);
                    obj.id = li.getAttribute("duid");
                    if (li.getAttribute("dep") === "1") {
                        obj.pi = options.rootId + "";
                    } else {
                        parent = li.parentNode.parentNode;
                        var pid = parent.getAttribute("did");
                        if (pid === "0")
                            obj.pi = parent.getAttribute("duid");
                        else if (pid === undefined)
                            obj.pi = options.rootId + "";
                        else
                            obj.pi = parent.getAttribute("did");
                    }
                    obj.children = [];
                    var hasObj = array.filter(item => item.id === obj.id).length !== 0;
                    if (!hasObj) {
                        var dpr = li.getAttribute("dpr");
                        if (dpr)
                            obj.pr = dpr;
                        array.push(obj);
                    }
                       
                }
            }
            if (changeList && changeList.length) {
                for (var i = 0; i < changeList.length; i++) {
                    li = changeList[i];
                    obj = treeEditor.collectObj(li);
                    obj.id = obj.id + "";
                    parent = li.parentNode.parentNode;
                    var pid = parent.getAttribute("did");
                    if (pid === "0")
                        obj.pi = parent.getAttribute("duid");
                    else if (pid === undefined)
                        obj.pi = options.rootId + "";
                    else
                        obj.pi = parent.getAttribute("did");
                    obj.children = [];

                    if (li.getAttribute("dep") === "1")
                        obj.pi = options.rootId + "";

                    let hasObj = array.filter(item => item.id === obj.id).length !== 0;
                    if (!hasObj)
                        array.push(obj);
                }
            }
            if (orderChangeList && orderChangeList.length) {
                for (var d = 0; d < orderChangeList.length; d++) {                  
                    li = orderChangeList[d];
                    var elDid = li.getAttribute("did");
                    if (!elDid || elDid === "0")
                        continue;
                    obj = treeEditor.collectObj(li);
                    obj.id = obj.id + "";
                    parent = li.parentNode.parentNode;
                    var pid = parent.getAttribute("did");
                    if (pid === "0")
                        obj.pi = parent.getAttribute("duid");
                    else if (pid === undefined)
                        obj.pi = options.rootId + "";
                    else
                        obj.pi = parent.getAttribute("did");
                    obj.pr = li.getAttribute("dpr");
                    obj.children = [];

                    if (li.getAttribute("dep") === "1")
                        obj.pi = options.rootId + "";

                    let hasObj = array.filter(item => item.id === obj.id).length !== 0;
                    if (!hasObj)
                        array.push(obj);
                    else {
                        array.filter(item => item.id === obj.id).pr = li.getAttribute("dpr");
                    }
                }
            }

            var treefy = _h.buildTree(array);
            return treefy;
        },
        setErrors: function (list) {
            treeEditor.setErrors(list);
        },
        resetErrors: function () {
            var tree = treeEditor.getTree();
            $(tree).find(".dropdown").remove();
        },
        nodeEditTrigger: function () {
            var li = this.find("li.dmn-selected");
            if (li.length > 1)
                return;

            var tree = treeEditor.getTree();
            var options = treeEditor.getOptions(tree);
            var object = treeEditor.collectObj(li);
            var parent = _hh.getClosest(li, "li");
            object.parentNodeTemplate = parent.getAttribute("dnte") === "null" ?
                null : Number(parent.getAttribute("dnte"));
            object.pId = Number(parent.getAttribute("did"));
            options.actions.onEditNode(li, object);
        },
        getDataNode: function (id) {
            var tree = tUtil.getTree(this);
            var treeId = tree.getAttribute("tv-rootid");
            var li = tUtil.getNode(tree[0], id)[0];
            var object = treeEditor.collectObj(li);
            if (li.getAttribute("dep") === "1") {
                object.pId = Number(treeId);
                object.parentNodeTemplate = false;
            } else {
                var parent = _hh.getClosest(li, "li");
                object.parentNodeTemplate = parent.getAttribute("dnte") === "null" ?
                    null : Number(parent.getAttribute("dnte"));
                object.pId = Number(parent.getAttribute("did"));
            }
            return object;
        },
        getToolbarData: function () {
            if (this.find("li").length === 0)
                return [];
            var tree = treeEditor.getTree();
            var options = treeEditor.getOptions();
            var period = options.permitPeriodEdit;
            var inComplex = treeEditor.inComplexStatus();
            var newList = $(tree).find("li[did='0']");
            var changedList = $(tree).find("li[dcng='true']");
            var sortedItems = $(tree).find("li[dpr]");
            var liList = treeEditor.getSelectedElements();
            var allowedActions = treeEditor.getAllowedActions(liList);
            if (!allowedActions)
                allowedActions = [];
            var action;
            if ((changedList.length + newList.length + sortedItems.length) > 0 && period) {
                action = allowedActions.filter(a => a.name === "SaveChange");
                if (!action.length)
                    allowedActions.push({ name: "SaveChange", visible: true });
                else
                    action.visible = true;
            }
            if (liList.length === 0 && period) {
                action = allowedActions.filter(a => a.name === "CreateNode");
                if (!action.length)
                    allowedActions.push({ name: "CreateNode", visible: true });
                else
                    action.visible = true;
            }
            if (liList.length === 0 && period && inComplex.sort === false) {
                allowedActions.push({ name: "Sort", visible: true });
            }
            if (liList.length === 0 && period && inComplex.sort === true) {
                allowedActions.push({ name: "SaveSort", visible: true });
                allowedActions.push({ name: "Cancel", visible: true });
                action = allowedActions.filter(a => a.name === "CreateNode");
                if (action.length)
                    action[0].visible = false;
            }

            if (liList.length === 0 && inComplex.cut) {
                action = allowedActions.filter(a => a.name === "Paste");
                // if (!action.length)
                //     allowedActions.push({name: "Paste", visible: true});
                // else
                //     action.visible = true;
                allowedActions = [{ name: "Paste", visible: true }, { name: "Cancel", visible: true }];

            }
            if (liList.length === 0 && inComplex.copy) {
                // action = allowedActions.filter(a => a.name === "Paste");
                // if (!action.length)
                //     allowedActions.push();
                // else
                //     action.visible = true;
                allowedActions = [{ name: "Paste", visible: true }, { name: "Cancel", visible: true }];
            }


            return allowedActions;
        },
        nodeSort: function () {
            treeEditor.onSort(this);
        },
        removeNewNodes: function () {
            var newList = $(tree).find("li[did='0']");
            if (newList && newList.length)
                for (var i = 0; i < newList.length; i++) {
                    $(newList[i]).remove();
                }
        },
        changeSelectedItem: function (list) {
            this.find("li").removeClass("dmn-selected");
            this.find(".dmn-ttl").css("color", "");
            tUtil.changeOtherSideSelectedItem(this, list);
        },
        exeAction: function (action) {
            var inComplex = treeEditor.inComplexStatus();
            var li = treeEditor.getSelectedElements();
            var tree = treeEditor.getTree();
            var options = treeEditor.getOptions();
            if (li.length === 0 && inComplex.sort)
                li = [tree];

            var inRoot;
            if (action === "Paste") {
                li = tree.getElementsByClassName("dmn-temp-selected");
                $(li).addClass("paste-target");
                $(li).removeClass("dmn-temp-selected");
                inRoot = true;
            }
            if (action === "Sort" && li.length === 0) {
                li = [tree];
            }
            if (treeEditor["on" + action])
                treeEditor["on" + action](li);
            else if (options.actions["on" + action])
                options.actions["on" + action](inRoot);
        },
        setAccessList: function (model) {
            var tag = $(this).find("li.dmn-selected")[0];
            var array = [];
            if (model.list && model.list.length > 0)
                for (var i = 0; i < model.list.length; i++) {
                    if (model.list[i].assign === true)
                        array.push({ companyId: tag.id, accessId: model.list[i].accessId });
                }
            tag.setAttribute("dal", JSON.stringify(array));
        },
        getCompanyAccess: function () {
            var tags = $(this).find("li");
            var array = [];
            for (var i = 0; i < tags.length; i++) {
                var tag = tags[i];
                array.push({
                    id: Number(tag.getAttribute("did")),
                    userAccesses: JSON.parse(tag.getAttribute("dal"))
                });
            }
            return array;
        },
        checkedBoxes: function () {
            var inputs = $(this).find("input");
            for (var i = 0; i < inputs.length; i++) {
                inputs[i].checked = true;
            }
        },
        uncheckedBoxes: function () {
            var inputs = $(this).find("input");
            for (var i = 0; i < inputs.length; i++) {
                inputs[i].checked = false;
            }
        },
        getDragList: function () {
            var treeOpts = tUtil.getTreeOptions(this);
            var tags = $(this).find("li.dmn-selected");
            var length = tags.length;
            var list = tUtil.createDragListData(tags, treeOpts);
            return list;
        }
    };
    var treeEditor = function () {
        var setErrors = function (list) {
            if (!list && !list.length)
                return;
            var tree = treeEditor.getTree();
            $(tree).find(".dropdown").remove();
            var t = '<div class="dropdown col-select" style="float: left;position: absolute;">' +
                '<a data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">' +
                '<img class="icon-image-xxsmall" style="margin-right: -34px;" src="/App/src/images/ico/form-error.png" />' +
                '</a><ul class="dropdown-menu pull-left" style="width: 450px;padding: 0;margin: 0;">' +
                '<li class="tbl-menu-row tbl-menu-header" style="margin: 0;"><span style="font-weight: bold;color: #999;">فهرست خطاها</span></li>' +
                '<li class="tbl-menu-row"><div class="row m-b-lg" style="margin-top: 6px;"><div class="col-lg-12">' +
                '<ul class="error-list"></ul></div></div></li></ul></div>';
            var div = $(t);
            var ul = div.find("ul.error-list");
            for (var i = 0; i < list.length; i++) {
                var li = $(tree).find("li[did='" + list[i].nodeId + "']");
                if (!li || li.length === 0)
                    li = $(tree).find("li[duid='" + list[i].nodeId + "']");
                if (!li || li.length === 0)
                    continue;
                var itemErrors = list[i].errors;
                if (itemErrors.length) {
                    for (var j = 0; j < itemErrors.length; j++) {
                        var target = itemErrors[j];
                        var text = _h.getApiMessage(target.code);
                        var faName;
                        try {
                            faName = _h.getLocalizedText(target.propertyName);
                            text = _h.completeError(text, target);
                        } catch (e) {
                            faName = undefined;
                        }
                        var liError = $('<li class="error-item"><span class="error-title"></span>' +
                            '<span class="error-desc"></span></li>');
                        liError.find(".error-item").text(faName);
                        liError.find(".error-desc").text(text);
                        ul.append(liError);
                    }
                    li.prepend(div);
                }
            }
        };
        var setNodeTitle = function (li, obj, options) {
            var divTitle = _hh.createElement("div", li);
            _hh.setClassName(divTitle, "dmn-tl");
            var nameSpan = _hh.createElement("span", divTitle);
            var sName = _h.shortName(obj.na);
            var title = sName[0];
            _hh.setInnerHtml(nameSpan, title);
            switch (obj.nt) {
                case 1:
                    _hh.setClassName(nameSpan, "dmn-ttl dmn-mg");
                    break;
                case 2:
                    _hh.setClassName(nameSpan, "dmn-ttl dmn-mg");
                    break;
            }
            var codeSpan = _hh.createElement("span", divTitle);
            _hh.setInnerHtml(codeSpan, " ( " + obj.co + " )");
            _hh.setClassName(codeSpan, "dmn-code");
            var divDesc = _hh.createElement("div", li);
            _hh.setClassName(divDesc, "dmn-sline");
            if (_h.contains([0, 1, 4], obj.tt)) {
                var atSpan = _hh.createElement("span", divDesc);
                _hh.setInnerHtml(atSpan, _h.getEnumText(accountTypes, obj.at));
                _hh.setClassName(atSpan, "dmn-at");
                if (obj.nt === 2) {
                    _hh.setClassName(divDesc, "dmn-sline-at");
                }
            } else {
                if (obj.nt === 1) {
                    _hh.setClassName(divDesc, "dmn-sline-vltb");
                } else {
                    _hh.setClassName(divDesc, "dmn-sline-vlt");
                }
            }
            var vlSpan = _hh.createElement("span", divDesc);
            var hasVlEvent = false;
            _hh.setInnerHtml(vlSpan, _h.formatTextIfNull(obj.dv));
            if (options.companyType === 0 && (obj.tt === 2 || obj.tt === 3)) {
                _hh.setClassName(vlSpan, "dmn-vlg link-underline clickable");
                hasVlEvent = true;
            } else {
                _hh.setClassName(vlSpan, "dmn-vl");
            }
            var ccTag;
            if (obj.nt === 1 && obj.nte === 1 && !obj.cc) {
                ccTag = _hh.createElement("i", divDesc);
                _hh.setClassName(ccTag, "dmn-ey fa fa-eye");
            }
            if (obj.de) {
                var descTag = _hh.createElement("i", divDesc);
                _hh.setClassName(descTag, "dmn-info fa fa-info-circle ");
                _hh.setAttributes(descTag, { "title": obj.de });
            }
            treeEditor.eventHandlers(li, nameSpan, ccTag, vlSpan, hasVlEvent);
            if (sName[1]) {
                _hh.setAttributes(nameSpan, { "title": obj.na });
            }
            return nameSpan;
        };
        var eventHandlers = function (li, nameSpan, ccTag, vlSpan, vlEvent) {
            li.oncontextmenu = function (ev) {
                var li = null;
                if (this.nodeName === "LI")
                    li = this;
                if (this.nodeName === "SPAN")
                    li = this.parentNode;
                treeEditor.toggleSelectedTag(li, ev.ctrlKey, true);
                treeEditor.getMenu({ el: ev.currentTarget });
                ev.cancelBubble = true;
                return false;
            };
            if (vlSpan && vlEvent)
                vlSpan.onclick = function (ev) {
                    var li = _hh.getClosest(ev.target, "li");
                    var tree = treeEditor.getTree();
                    var options = treeEditor.getOptions(tree);
                    options.actions.onNodeValuePart(Number(li.getAttribute("did")));
                };
            if (ccTag)
                ccTag.onclick = function (ev) {
                    var li = this.parentNode.parentNode;
                    var id = li.getAttribute("did");
                    if (id === "0")
                        return;
                    var eyIcon = li.getElementsByClassName("dmn-ey")[0];
                    var ulTarget = li.getElementsByTagName("ul")[0];
                    var instId = tUtil.getInstanceId(li);
                    var opts = tUtil.getOptions(instId);
                    tUtil.getConsolidationBranchData(id,
                        opts,
                        function (list) {
                            if (list && list.length) {
                                var oldNodes = $(ulTarget).find("li.dmn-selected");
                                var oldIds = [];
                                if (oldNodes.length)
                                    for (var j = 0; j < oldNodes.length; j++) {
                                        oldIds.push(Number($(oldNodes[j]).attr("did")));
                                    }
                                $(ulTarget).empty();

                                for (var i = 0; i < list.length; i++) {
                                    treeEditor.buildEditorRow(ulTarget, list[i], opts);
                                }
                            }
                            _hh.removeElement(eyIcon);
                        });
                };
            nameSpan.onclick = function (ev) {
                var li = this.parentNode.parentNode;
                treeEditor.toggleSelectedTag(li, ev.ctrlKey);
            };
            nameSpan.ondblclick = function (ev) {
                var li = ev.target.parentNode.parentNode;
                var tree = treeEditor.getTree();

                var treeId = tree.getAttribute("tv-rootid");
                var options = treeEditor.getOptions(tree);
                if (!options.permitPeriodEdit)
                    return;
                var object = treeEditor.collectObj(li);

                if (li.getAttribute("dep") === "1") {
                    object.pId = Number(treeId);
                    object.parentNodeTemplate = false;
                } else {
                    var parent = $(li).parent().parent()[0];
                    object.parentNodeTemplate = parent.getAttribute("dnte") === "null" ?
                        null : Number(parent.getAttribute("dnte"));
                    object.pId = Number(parent.getAttribute("did"));
                }
                options.actions.onEditNode(li, object);
            };
            var iTag = li.getElementsByClassName("dmn-p")[0];
            if (iTag)
                iTag.onclick = function () {
                    tUtil.toggleShowChildren(this);
                };

        };
        var resetEventHandlers = function (li) {
            var liList = li.getElementsByTagName("li");
            var vlSpan, nameSpan, ccTag;
            vlSpan = li.getElementsByClassName("dmn-vlg")[0];
            nameSpan = li.getElementsByClassName("dmn-ttl")[0];
            ccTag = li.getElementsByClassName("dmn-ey")[0];
            treeEditor.eventHandlers(li, nameSpan, ccTag, vlSpan, false);
            if (liList.length > 1) {
                for (var i = 0; i < liList.length; i++) {
                    var liChild = liList[i];
                    vlSpan = liChild.getElementsByClassName("dmn-vlg")[0];
                    nameSpan = liChild.getElementsByClassName("dmn-ttl")[0];
                    ccTag = liChild.getElementsByClassName("dmn-ey")[0];
                    treeEditor.eventHandlers(liChild, nameSpan, ccTag, vlSpan, false);
                }
            }

        };
        var collectObj = function (li) {
            var dnte = li.getAttribute("dnte") === "null" ?
                null : Number(li.getAttribute("dnte"));
            var obj = {
                id: Number(li.getAttribute("did")),
                uid: li.getAttribute("duid"),
                nt: Number(li.getAttribute("dnt")),
                nte: dnte,
                co: li.getAttribute("dco"),
                tt: Number(li.getAttribute("dtt")),
                dep: Number(li.getAttribute("dep")),
                at: Number(li.getAttribute("dat")),
                cfc: Number(li.getAttribute("dcfc")),
                v: li.getAttribute("dv"),
                f: li.getAttribute("df"),
                na: li.getAttribute("dna"),
                ci: Number(li.getAttribute("dci")),
                as: Number(li.getAttribute("das")),
                dv: li.getAttribute("ddv"),
                liTarget: li,
                de: li.getAttribute("dde"),
                gid: li.getAttribute("dgid")
            };
            for (var k in obj) {
                if (obj.hasOwnProperty(k)) {
                    var param = obj[k];
                    if (param === "undefied")
                        param = "";
                    if (param === NaN)
                        param = "";
                }
            }
            return obj;
        };
        var getTree = function () {
            return document.getElementById("tree_view_ed");
        };
        var getOptions = function () {
            var tree = treeEditor.getTree();
            var instanceId = tree.getAttribute("tv-id");
            var item = $.fn.treeView.options.instances
                .filter(el => el.id === Number(instanceId));
            return item[0].opts;
        };
        var getSelectedElements = function () {
            var tree = document.getElementById("tree_view_ed");
            var copy = tree.getElementsByClassName("copy-el").length > 0;
            var cut = tree.getElementsByClassName("cut-el").length > 0;
            if (!cut && !copy)
                return tree.getElementsByClassName("dmn-selected");
            else {
                return tree.getElementsByClassName("paste-target");
            }
        };
        var getMenu = function (data) {
            treeEditor.disposeMenu();
            var pos = _h.getPosition(data.el);
            var tree = tUtil.getTree(data.el);
            var selectedItems = treeEditor.getSelectedElements();
            if (selectedItems.length === 0)
                selectedItems = [data.el];
            var buttons = treeEditor.getAllowedActions(selectedItems);
            if (!buttons && buttons.length === 0)
                return;
            var nav = document.createElement('nav');
            document.body.appendChild(nav);
            _hh.setAttributes(nav, {
                "target": tree[0].getAttribute("tv-id")
            });
            nav.className = "context-menu";
            _hh.setClassName(nav, "context-menu");
            var ul = _hh.createElement("ul", nav);
            _hh.setClassName(ul, "mt-contextmenu");
            for (var i = 0; i < buttons.length; i++) {

                var button = buttons[i];
                if (!button.visible)
                    continue;
                var li = _hh.createElement("li", ul);
                var a = _hh.createElement("a", li);
                li.setAttribute("data-action", button.name);
                var caption = _hh.createElement("span", a);
                caption.innerText = button.caption;
                _hh.setClassName(caption, "mt-contextmenu-text");
                var iconSpan = _hh.createElement("span", a);
                _hh.setClassName(iconSpan, "mt-contextmenu-icon");
                var image = _hh.createElement("img", iconSpan);
                image.src = button.icon;
                li.onclick = function (event) {
                    var inComplex = treeEditor.inComplexStatus();
                    var li = treeEditor.getSelectedElements();
                    var tree = treeEditor.getTree();
                    var options = treeEditor.getOptions();
                    if (li.length === 0 && inComplex.sort)
                        li = [tree];

                    var dataAction = this.getAttribute("data-action");
                    if (dataAction === "Paste") {
                        li = tree.getElementsByClassName("dmn-temp-selected");
                        $(li).addClass("paste-target");
                        $(li).removeClass("dmn-temp-selected");
                    }


                    if (treeEditor["on" + dataAction])
                        treeEditor["on" + dataAction](li);
                    else if (options.actions["on" + dataAction])
                        options.actions["on" + dataAction]();
                };
            }
            nav.style.top = (pos.top + 30) + "px";
            nav.style.left = pos.right + "px";
            document.onclick = function () {
                var menu = document.getElementsByClassName("context-menu")[0];
                if (menu)
                    disposeMenu();
            };
        };
        var disposeMenu = function () {
            var menu = document.getElementsByClassName("context-menu")[0];
            if (menu)
                menu.parentNode.removeChild(menu);
        };
        var toggleSelectedTag = function (li, ctrl, rightClick) {
            var complex = treeEditor.inComplexStatus();
            if (complex.sort)
                return false;
            if (complex.cut || complex.copy) {
                if (!_hh.hasClass(li, "dmn-selected")) {
                    $("li.dmn-temp-selected").removeClass("dmn-temp-selected");
                    $(li).addClass("dmn-temp-selected");
                }

                return false;
            }


            var firstSpan = $(li).find(".dmn-ttl")[0];
            if (ctrl) {
                if (_hh.hasClass(li, "dmn-selected")) {
                    if (rightClick) {
                        $(li).find("li").addClass("dmn-selected");
                        $(li).find(".dmn-ttl").css("color", "red");
                        $(li).addClass("dmn-selected");
                    } else {
                        $(li).removeClass("dmn-selected");
                        $(li).find("li").removeClass("dmn-selected");
                        $(li).find(".dmn-ttl").css("color", "");
                    }
                } else {
                    $(li).find("li").addClass("dmn-selected");
                    $(li).find(".dmn-ttl").css("color", "red");
                    $(li).addClass("dmn-selected");
                }
            } else {
                if (_hh.hasClass(li, "dmn-selected")) {
                    if (rightClick) {
                        $(li).addClass("dmn-selected");
                        $(firstSpan).css("color", "red");
                    } else {
                        $(li).closest(".dmn-tree").find("li.dmn-selected").removeClass("dmn-selected");
                        $(li).closest(".dmn-tree").find(".dmn-ttl").css("color", "");
                    }
                } else {
                    $(li).closest(".dmn-tree").find("li.dmn-selected").removeClass("dmn-selected");
                    $(li).closest(".dmn-tree").find(".dmn-ttl").css("color", "");

                    $(li).addClass("dmn-selected");
                    $(firstSpan).css("color", "red");
                }
            }
            _h.kocnx().treevm().onCallbackAction();
        };
        var buildEditorRow = function (target, obj, options, targetLi, editTag) {
            var li, childNodes;
            if (targetLi) {
                li = document.createElement("li");
                var oldUl = targetLi.getElementsByTagName("ul")[0];
                if (editTag)
                    childNodes = oldUl.childNodes;
                targetLi.replaceWith(li);
            } else
                li = _hh.createElement("li", target);
            if (editTag)
                _hh.setAttributes(li, { "dcng": true });
            var att, iTag, iDot, folderI;
            var depth = target.getAttribute("dep");
            if (!depth)
                depth = 0;
            _hh.setAttributes(li,
                {
                    "dep": Number(depth) + 1,
                    "did": obj.id,
                    "duid": obj.uid,
                    "dnt": obj.nt,
                    "dnte": obj.nte,
                    "dcc": obj.cc,
                    "dco": obj.co,
                    "dtt": obj.tt,
                    "dat": obj.at,
                    "dcfc": obj.cfc,
                    "dv": _h.emptyTextIfNull(obj.v),
                    "df": _h.emptyTextIfNull(obj.f),
                    "dna": obj.na,
                    "dci": obj.ci,
                    "das": obj.as,
                    "ddv": obj.dv,
                    "dde": _h.emptyTextIfNull(obj.de)
                });
            if (obj.gid)
                li.setAttribute("dgid", obj.gid);

            switch (obj.nt) {
                case 1:

                    iTag = _hh.createElement("i", li);
                    _hh.setClassName(iTag, "dmn-p fa fa-plus");

                    folderI = _hh.createElement("i", li);
                    _hh.setClassName(folderI, "dmn-fld fa fa-folder");
                    iTag.onclick = function () {
                        tUtil.toggleShowChildren(this);
                    };
                    break;
                case 2:

                    if (obj.children.length > 0) {
                        iTag = _hh.createElement("i", li);
                        _hh.setClassName(iTag, "dmn-p fa fa-plus");
                    }
                    att = _hh.createElement("i", li);
                    _hh.setClassName(att, "dmn-att fa fa-file-text-o");
                    if (obj.children.length > 0) {
                        iTag.onclick = function () {
                            tUtil.toggleShowChildren(this);
                        };
                    }
                    break;
            }
            if (depth === 0 && obj.nt === 1)
                tUtil.setPlusMinusAll(li);
            setNodeTitle(li, obj, options);
            if (obj.nt === 1 || obj.nt === 2) {
                var ul = _hh.createTag({
                    name: "ul", className: "dmn-c",
                    parent: li, attributes: { "dep": Number(depth) + 1 }
                });
                tUtil.buildChildren(ul, obj, options);
            }
            if (childNodes && childNodes.length && obj.nt === 1) {
                var liUl = li.getElementsByTagName("ul")[0];
                for (var j = 0; j < childNodes.length; j++) {
                    var newClone = childNodes[j].cloneNode(true);
                    liUl.appendChild(newClone);
                }
                treeEditor.resetEventHandlers(li);
            }
        };
        var getAllowedActions = function (liList, actionTarget) {
            var baseUrl = "/App/src/images/ico/";
            if (!liList || liList.length === 0)
                return null;

            var inComplexStatus = treeEditor.inComplexStatus();
            var actions, action, target;
            var options = tUtil.getTreeOptions(liList[0]);
            var period = options.permitPeriodEdit;
            var isRoot = options.companyIsRoot;
            var selectedCount = liList.length;
            var consolidate = null, consolidateBranch = false;
            if (selectedCount === 1) {
                consolidate = liList[0].getAttribute("dcc") !== "null" && Number(liList[0].getAttribute("dcc")) > 0;
            }
            if (selectedCount === 1) {
                consolidateBranch = liList[0].getAttribute("dnte") === "1" && liList[0].getAttribute("dcc") === "null";
            }
            if (inComplexStatus.all) {
                actions = [
                    {
                        name: "Paste",
                        visible: false,
                        icon: baseUrl + _h.getIcon("Paste"),
                        caption: _h.getLocalizedText("paste")
                    },
                    {
                        name: "Cancel",
                        visible: false,
                        icon: baseUrl + _h.getIcon("Cancel"),
                        caption: _h.getLocalizedText("cancel")
                    },
                    {
                        name: "SaveSort",
                        visible: false,
                        icon: baseUrl + _h.getIcon("Save"),
                        caption: _h.getLocalizedText("update")
                    }
                ];
                for (var j = 0; j < actions.length; j++) {
                    action = actions[j];
                    switch (action.name) {

                        case "Paste":
                            var res = false;
                            if (inComplexStatus.copy)
                                res = !_hh.hasClass(liList[0], "copy-el") &&
                                    liList[0].getAttribute("dnt") == 1;

                            if (inComplexStatus.cut)
                                res = !_hh.hasClass(liList[0], "cut-el") &&
                                    liList[0].getAttribute("dnt") == 1;
                            action.visible = res && !inComplexStatus.sort && selectedCount === 1;
                            break;
                        case "Cancel":
                            action.visible = inComplexStatus.all;
                            break;
                        case "SaveSort":
                            action.visible = inComplexStatus.sort;
                            break;
                    }
                    if (action.name === actionTarget)
                        target = action;
                }
                if (actionTarget)
                    return target;
                return actions;
            } else {

                actions = [
                    {
                        name: "CreateNode",
                        visible: false,
                        icon: baseUrl + _h.getIcon("TreeCreate"),
                        caption: _h.getLocalizedText("createNodeCaption")
                    },
                    {
                        name: "DeleteNode",
                        visible: false,
                        icon: baseUrl + _h.getIcon("Delete"),
                        caption: _h.getLocalizedText("deleteNodeCaption")
                    },
                    {
                        name: "DeleteNodes",
                        visible: false,
                        icon: baseUrl + _h.getIcon("Delete"),
                        caption: _h.getLocalizedText("deleteNodesCaption")
                    },
                    {
                        name: "Sort",
                        visible: false,
                        icon: baseUrl + _h.getIcon("Sort"),
                        caption: _h.getLocalizedText("activeOrderSubCaption")
                    },
                    {
                        name: "NodeReport",
                        visible: false,
                        icon: baseUrl + _h.getIcon("NodeReport"),
                        caption: _h.getLocalizedText("nodeReportCaption")
                    },
                    {
                        name: "NodeReports",
                        visible: false,
                        icon: baseUrl + _h.getIcon("NodeReport"),
                        caption: _h.getLocalizedText("nodeReportsCaption")
                    },
                    {
                        name: "Copy",
                        visible: false,
                        icon: baseUrl + _h.getIcon("Copy"),
                        caption: _h.getLocalizedText("copy")
                    },
                    {
                        name: "Cut",
                        visible: false,
                        icon: baseUrl + _h.getIcon("Cut"),
                        caption: _h.getLocalizedText("cut")
                    },
                    {
                        name: "ToBranch",
                        visible: false,
                        icon: baseUrl + _h.getIcon("Up"),
                        caption: _h.getLocalizedText("changeToBranchCaption")
                    },
                    {
                        name: "ToLeaf",
                        visible: false,
                        icon: baseUrl + _h.getIcon("Down"),
                        caption: _h.getLocalizedText("changeToLeafCaption")
                    },
                    {
                        name: "EditNode",
                        visible: false,
                        icon: baseUrl + _h.getIcon("Edit"),
                        caption: _h.getLocalizedText("EditCaption")
                    },
                    {
                        name: "ImportExcel",
                        visible: false,
                        icon: baseUrl + _h.getIcon("ImportExcel"),
                        caption: _h.getLocalizedText("importExcelCaption")
                    },
                    {
                        name: "ExportExcel",
                        visible: false,
                        icon: baseUrl + _h.getIcon("ExportExcel"),
                        caption: _h.getLocalizedText("exportExcel")
                    },
                    {
                        name: "ExportAllExcel",
                        visible: false,
                        icon: baseUrl + _h.getIcon("ExportExcel"),
                        caption: _h.getLocalizedText("exportExcelAll")
                    },
                    {
                        name: "ResetConsolidate",
                        visible: false,
                        icon: baseUrl + _h.getIcon("ResetConsolidate"),
                        caption: _h.getLocalizedText("ResetBranchConsolidateCaption")
                    },
                ];
                for (var i = 0; i < actions.length; i++) {
                    action = actions[i];
                    if (!actionTarget || action.name === actionTarget) {
                        switch (action.name) {
                            case "Copy":
                                var temp = period &&
                                    !inComplexStatus.all;
                                if (selectedCount === 1) {
                                    action.visible = temp && !consolidate;
                                } else {
                                    var gConsolidate = $("li.dmn-selected[dnte='1'][dcc='null']");
                                    var diveInConsolidate = $("li.dmn-selected[dnte='1'][dcc!='null']");
                                    if (gConsolidate.length === 0 && diveInConsolidate.length > 0)
                                        action.visible = false;
                                    else if (gConsolidate.length === 0)
                                        action.visible = temp;
                                    else if (gConsolidate.length > 0) {
                                        var res = true;
                                        for (var k = 0; k < gConsolidate.length; k++) {
                                            res = $(gConsolidate[k]).find("li:not(.dmn-selected)").length === 0;
                                            if (!res)
                                                break;
                                        }
                                        action.visible = temp && res;
                                    }
                                }
                                break;
                            case "Cut":
                                action.visible = period &&
                                    !inComplexStatus.all &&
                                    !consolidate &&
                                    selectedCount === 1;
                                break;
                            case "DeleteNode":
                                var creator = liList[0].getAttribute("dci");
                                //var owner = Number(creator) === options.companyId;
                                action.visible =
                                    period && selectedCount === 1 && ((consolidate && !isRoot) || (!consolidate));
                                break;
                            case "DeleteNodes":
                                action.visible = period && selectedCount > 1;
                                break;
                            case "CreateNode":
                                var nodeTemplate = liList[0].getAttribute("dnte");
                                var att = selectedCount === 1 &&
                                    liList[0].getAttribute("dnt") == 1 &&
                                    (nodeTemplate == null || nodeTemplate == 0 || nodeTemplate == "null");
                                action.visible = period && att;
                                break;
                            case "Sort":
                                var dep = liList[0].getAttribute("dep");
                                var hasChild = $(liList[0]).find("li[dep='" + (Number(dep) + 1) + "']").length > 1;
                                action.visible = period && selectedCount === 1 && hasChild;
                                break;
                            case "NodeReport":
                                action.visible = selectedCount === 1 && liList[0].getAttribute("did") !== "0";
                                break;
                            case "NodeReports":
                                action.visible = selectedCount > 1;
                                break;
                            case "ToBranch":
                                var value = liList[0].getAttribute("dv");
                                var formula = liList[0].getAttribute("df");
                                var hasValue = (!_h.isNullOrEmpty(value) && value !== "" && value !== "null") ||
                                    (!_h.isNullOrEmpty(formula) && formula !== "" && formula !== "null");

                                action.visible = period &&
                                    !hasValue &&
                                    !consolidate &&
                                    selectedCount === 1 &&
                                    liList[0].getAttribute("dnt") == 2;
                                break;
                            case "ToLeaf":
                                action.visible = period &&
                                    selectedCount === 1 &&
                                    liList[0].getElementsByTagName("li").length === 0 &&
                                    liList[0].getAttribute("dnt") == 1 &&
                                    (!consolidate && !(liList[0].getAttribute("dnt") == 1 &&
                                        liList[0].getAttribute("dnte") == 1));
                                break;
                            case "ExportExcel":
                            case "ImportExcel":
                            case "ExportAllExcel":
                                action.visible = period &&
                                    liList[0].getAttribute("dnt") == 1 &&
                                    ((options.companyType === 0 &&
                                        _h.contains([6, 7, 8], Number(liList[0].getAttribute("dtt")))) ||
                                        (options.companyType === 1 &&
                                            _h.contains([2, 3, 6, 7, 8], Number(liList[0].getAttribute("dtt")))));
                                break;
                            case "EditNode":
                                action.visible = period;
                                break;
                            case "ResetConsolidate":
                                action.visible = period && consolidateBranch;
                                break;
                        }
                    }
                    if (action.name === actionTarget)
                        target = action;
                }
                if (actionTarget)
                    return target;
                return actions;
            }
        };
        var fixHelper = function (e, ui) {
            ui.children().each(function () {
                $(this).width($(this).width());
            });
            return ui;
        };
        var onCreateNode = function (treeType, assignmentType, accountType, companyId) {
            var el = treeEditor.getSelectedElements();
            var tree = treeEditor.getTree();
            var options = treeEditor.getOptions();
            if (!options.permitPeriodEdit)
                return;
            var uid = "U-" + _h.createRandomNumber();
            var ul, dep, liCount, obj;
            if (el && el.length === 1) {
                el = el[0];
                if (el.getAttribute("dnt") === "2")
                    return;
                ul = el.getElementsByTagName("ul")[0];
                dep = ul.getAttribute("dep");
                liCount = $(ul).find("li[dep='" + (Number(dep) + 1) + "']").length;
                obj = {
                    id: 0,
                    uid: uid,
                    ri: tree.getAttribute("tv-rootid"),
                    pi: el.getAttribute("did"),
                    co: "",
                    nt: 2,
                    as: el.getAttribute("das"),
                    tt: el.getAttribute("dtt"),
                    at: el.getAttribute("dat"),
                    cfc: el.getAttribute("dcfc"),
                    f: "",
                    v: "",
                    na: "گره جدید",
                    ci: el.getAttribute("dci"),
                    nte: null,
                    cc: el.getAttribute("dcc"),
                    pr: liCount + 1,
                    children: []
                };
            } else {
                ul = tree;
                liCount = $(ul).find("li[dep='" + 1 + "']").length;
                obj = {
                    id: 0,
                    uid: uid,
                    ri: tree.getAttribute("tv-rootid"),
                    pi: tree.getAttribute("tv-rootid"),
                    co: "",
                    nt: 2,
                    as: assignmentType,
                    tt: treeType,
                    at: accountType,
                    cfc: treeType === 1 ? 1 : 0,
                    f: "",
                    v: "",
                    na: "گره جدید",
                    ci: companyId,
                    nte: null,
                    cc: null,
                    pr: liCount + 1,
                    children: []
                };
            }
            buildEditorRow(ul, obj, options);
            options.actions.onCallbackAction();
        };
        var onEditNode = function (li) {
            if (li.length > 1)
                return;
            if (HTMLCollection.prototype.isPrototypeOf(li))
                li = li[0];
            var tree = treeEditor.getTree();
            var options = treeEditor.getOptions(tree);
            var object = treeEditor.collectObj(li);
            var parent = _hh.getClosest(li, "li");
            object.parentNodeTemplate = parent.getAttribute("dnte") === "null" ?
                null : Number(parent.getAttribute("dnte"));
            object.pId = Number(parent.getAttribute("did"));
            options.actions.onEditNode(li, object);
        };
        var onSort = function (li, save) {
            var options = treeEditor.getOptions();
            if (!options.permitPeriodEdit)
                return;
            var ul;
            if (li.length > 0 && li[0].nodeName === "UL") {
                ul = li[0];
            } else if (save !== undefined)
                ul = treeEditor.getTree(li).getElementsByClassName("ui-sortable")[0];
            else
                ul = $(li).find("ul")[0];
            if (!$(ul).hasClass("ui-sortable")) {
                $(ul).sortable({
                    _h: fixHelper
                }).disableSelection();
                setTimeout(function () {
                    options.actions.onCallbackAction();
                },
                    100);

            } else {
                if (save) {
                    var dep = $(ul).attr("dep");
                    if (!dep)
                        dep = 0;
                    var liList = $(ul).find("li[dep='" + (Number(dep) + 1) + "']");
                    for (var i = 0; i < liList.length; i++) {
                        liList[i].setAttribute("dpr", i + 1);
                    }
                } else {
                    var newLiList = $(ul.innerHTML);
                    ul.innerHTML = "";
                    for (var j = 0; j < newLiList.length; j++) {
                        ul.innerHTML += newLiList[j].outerHTML;
                    }
                }
                var tagList = $(".ui-sortable-handle");

                if (tagList && tagList.length)
                    for (var k = 0; k < tagList.length; k++) {

                        treeEditor.resetEventHandlers(tagList[k]);
                    }
                $(ul).sortable("destroy");
                $(".ui-sortable-handle").removeClass("ui-sortable-handle");

                options.actions.onCallbackAction();
            }
        };
        var onCancel = function (li) {
            var options = treeEditor.getOptions();
            var inComplex = treeEditor.inComplexStatus();
            if (inComplex.sort)
                treeEditor.onSort(li, false);
            if (inComplex.copy || inComplex.cut) {
                var tree = treeEditor.getTree();
                $(tree).find("li").removeClass("copy-el cut-el paste-target");

            }
            options.actions.onCallbackAction();
        };
        var onSaveSort = function (li) {
            treeEditor.onSort(li, true);
        };
        var onCopy = function () {
            if (!treeEditor.canCutCopy())
                return;
            var list = treeEditor.getSelectedElements();
            for (var i = 0; i < list.length; i++) {
                list[i].classList.add("copy-el");
            }
            treeEditor.getOptions().actions.onCallbackAction();
        };
        var onCut = function () {
            if (!treeEditor.canCutCopy())
                return;

            var list = treeEditor.getSelectedElements();
            for (var i = 0; i < list.length; i++) {
                list[i].classList.add("cut-el");
            }
            treeEditor.getOptions().actions.onCallbackAction();
        };
        var canCutCopy = function () {
            var tree = treeEditor.getTree();
            var newList = $(tree).find("li[did='0']");
            var changedList = $(tree).find("li[dcng='true']");
            if (newList.length || changedList.length) {
                var text = _h.getApiMessage("NodeEditorUnableToCopy");
                _h.failToast(text);
                return false;
            }
            return true;
        };
        var onToBranch = function () {
            var options = treeEditor.getOptions();
            var li = treeEditor.getSelectedElements();
            if (li.length === 1 && li[0].getAttribute("did") !== "0") {
                options.actions.onToBranch();
            } else {
                li = li[0];
                li.setAttribute("dnt", "1");
                var span = li.getElementsByClassName("dmn-att")[0];

                span.className = "dmn-p fa fa-plus";
                li.getElementsByTagName("ul")[0].className = "dmn-c";
                var folderI = document.createElement("i");

                _hh.setClassName(folderI, "dmn-fld fa fa-folder");
                $(folderI).insertAfter(span);
                span.onclick = function () {
                    tUtil.toggleShowChildren(this);
                };
            }
        };
        var onToLeaf = function () {
            var options = treeEditor.getOptions();
            var li = treeEditor.getSelectedElements();
            if (li.length === 1 && li[0].getAttribute("did") !== "0") {
                options.actions.onToBranch();
            } else {
                li = li[0];
                li.setAttribute("dnt", "2");
                var span = li.getElementsByClassName("dmn-p")[0];
                span.className = "dmn-att fa fa-file-text-o";
                var ul = li.getElementsByTagName("ul")[0];
                ul.className = "dmn-c";
                ul.innerHTML = "";
                var folderI = li.getElementsByClassName("dmn-fld")[0];
                _hh.removeElement(folderI);
            }
        };
        var onDeleteNode = function () {
            treeEditor.onDeleteNodes();
        };
        var onDeleteNodes = function () {
            var tree = treeEditor.getTree();
            var options = treeEditor.getOptions();
            var list = $(tree).find("li.dmn-selected[did='0']");
            var serverlist = $(tree).find("li.dmn-selected[did!='0']");
            if (list.length) {
                for (var i = 0; i < list.length; i++) {
                    _hh.removeElement(list[i]);
                }
                _h.kocnx().treevm().onCallbackAction();
            }
            if (serverlist.length)
                options.actions.onDeleteNode();
        };
        var onResetConsolidate = function () {
            var options = treeEditor.getOptions();
            var li = treeEditor.getSelectedElements();
            if (li.length === 1 && li[0].getAttribute("did") !== "0")
                options.actions.onResetConsolidate(li[0].getAttribute("did"));
        };
        var inComplexStatus = function () {
            var tree = treeEditor.getTree();
            var sort = tree.getElementsByClassName("ui-sortable").length > 0;
            if (_hh.hasClass(tree, "ui-sortable"))
                sort = true;
            var copy = tree.getElementsByClassName("copy-el").length > 0;
            var cut = tree.getElementsByClassName("cut-el").length > 0;

            return {
                all: sort || cut || copy,
                sort: sort,
                cut: cut,
                copy: copy
            };
        };
        return {
            onDeleteNode: onDeleteNode,
            onDeleteNodes: onDeleteNodes,
            canCutCopy: canCutCopy,
            buildEditorRow: buildEditorRow,
            getAllowedActions: getAllowedActions,
            getMenu: getMenu,
            onCreateNode: onCreateNode,
            disposeMenu: disposeMenu,
            toggleSelectedTag: toggleSelectedTag,
            getTree: getTree,
            getOptions: getOptions,
            onSort: onSort,
            onCancel: onCancel,
            onSaveSort: onSaveSort,
            onToBranch: onToBranch,
            onToLeaf: onToLeaf,
            inComplexStatus: inComplexStatus,
            getSelectedElements: getSelectedElements,
            onCopy: onCopy,
            onEditNode: onEditNode,
            collectObj: collectObj,
            onCut: onCut,
            setErrors: setErrors,
            eventHandlers: eventHandlers,
            resetEventHandlers: resetEventHandlers,
            onResetConsolidate: onResetConsolidate
        };
    }();
    $.fn.treeView = function (methodOrOptions) {
        if (tVMethods[methodOrOptions]) {
            return tVMethods[methodOrOptions].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof methodOrOptions === 'object' || !methodOrOptions) {

            return tVMethods.init.apply(this, arguments);
        } else {
            $.error('Method ' + methodOrOptions + ' does not exist on jQuery.treeView');
        }
    };
    $.fn.treeView.options = {
        instances: []
    };
})(jQuery);