var selectedData;
var codeHedear = "999999999999999";
var filterModel = null;
var filterSelectNode = null;
$(document).ready(function () {
    document.onkeydown = function (event) {
        if (event.keyCode === 114)//f3 
        {
            showLoading();
            nextFind();
            event.preventDefault();
        }
        else if (event.keyCode === 112) //f1 
        {
            window.top.showHelpForm();
            event.preventDefault();
        }
    }
    $('#txtSearch').keydown(function (e) {
        var code = e.which;
        if (code === 13) {
            $('#jstree').jstree(true).deselect_all();
            search();
            return false;
        }
    });
    $('#jstree').jstree({
        core: {
            check_callback: true,
            rename_node: false,
            data: ajaxTree({
                url: "AccountingApi/GetHeadingTree",
                data: function (node) {
                    return JSON.stringify({
                        id: (node.id == '#' ? null : node.id),
                        depth: (node.original ? node.original.depth : 0),
                        text: (node.id == '#' ? '' : node.text),
                        parentId: (node.id == '#' ? '' : node.id)
                    });
                }
            })
        }
    }).bind("loaded.jstree", function () {
        selectRootNode();
    }).bind("changed.jstree", function (e, data) {
        if (data.selected.length > 0 && data.node) {
            selectedData = data;
            refreshNodeInfo();
        }
    }).bind("open_node.jstree", function (e, data) {
        if (filterSelectNode != null && filterModel != null && filterModel.Level3.Id > filterSelectNode) {
            $("#jstree").jstree('open_node', filterSelectNode);
            filterSelectNode = filterModel.Level3.Id;
        }
        else if (filterSelectNode != null) {
            $('#jstree').jstree(true).select_node(filterSelectNode);
            filterSelectNode = null;
        }
    });
});
function selectRootNode() {
    $('#jstree').jstree(true).select_node(codeHedear);
    $('#addDiv').hide();
    $('#editDiv').hide();
    $('#delDiv').hide();
    $('#divNature').hide();
    $('#divTafsils').hide();
    $('#divMoain').hide();
    $("#jstree").jstree('open_node', codeHedear);
}
function refreshNodeInfo() {
    ajax({
        loading: true,
        url: "AccountingApi/GetHeadingNodeInfo",
        data: {
            id: selectedData.node.id,
            depth: (selectedData.node.original ? selectedData.node.original.depth : 0)
        },
        success: function (msg) {
            $('#type').html(msg.DataInfo.Type != '' ? msg.DataInfo.Type : '------');
            $('#name').html(msg.DataInfo.Name != '' ? msg.DataInfo.Name : '------');
            $('#code').html(msg.DataInfo.AccNo > 0 ? msg.DataInfo.AccNo : '------');
            var code = msg.DataInfo.AccNo;
            if (selectedData.node.original.depth == 0) {
                $('#addDiv').show();
                $('#editDiv').hide();
                $('#delDiv').hide();
                $('#divNature').hide();
                $('#divTafsils').hide();
                $('#divMoain').hide();
            }
            else if (selectedData.node.original.depth == 1) {
                $('#divNature').hide();
                $('#divTafsils').hide();
                $('#divMoain').hide();

                $('#addDiv').show();
                $('#editDiv').show();
                $('#delDiv').show();

            }
            else if (selectedData.node.original.depth == 2) {

                $('#addDiv').show();
                $('#editDiv').show();
                $('#delDiv').show();

                /// bestankar = بستانکار در سود و زیان ; bitacir = بی تاثیر در سود و زیان ;bedehkar=بدهکاری در سود و زیان

                if (msg.DataInfo.StateId == 0) {

                    $("#bitacir").css({ "font-weight": "bold", "color": "#0277bd" });
                    $("#bestankar").css({ "font-weight": "400", "color": "#969696" });
                    $("#bedehkar").css({ "font-weight": "400", "color": "#969696" });
                }
                else if (msg.DataInfo.StateId == 1) {
                    $("#bestankar").css({ "font-weight": "bold", "color": "#0277bd" });
                    $("#bitacir").css({ "font-weight": "400", "color": "#969696" });
                    $("#bedehkar").css({ "font-weight": "400", "color": "#969696" });
                }
                else if (msg.DataInfo.StateId == 2) {
                    $("#bedehkar").css({ "font-weight": "bold", "color": "#0277bd" });
                    $("#bestankar").css({ "font-weight": "400", "color": "#969696" });
                    $("#bitacir").css({ "font-weight": "400", "color": "#969696" });
                }


                $('#divNature').show();
                $('#divTafsils').hide();
                $('#divMoain').hide();
                $("#divFinancialStatementName").text(msg.DataInfo.FinancialStatementName);
            }
            else if (selectedData.node.original.depth == 3) {

                $('#addDiv').hide();
                $('#editDiv').show();
                $('#delDiv').show();

                $('#amountState').html(msg.DataInfo.AmountState);
                $('#divNature').hide();

                $('#divTafsils').show();

                $('#divMoain').show();
                $('#tafsil').empty();
                $('#CostCenterLsit').empty();
                $('#Project').empty();
                $('#tafsilUl').empty();
                $('#markazHazinelUl').empty();
                $('#projectUl').empty();
                $('#state').html(msg.DataInfo.IsActive);
                //-------
                $('#tafsilUl').empty();
                $('#markazHazinelUl').empty();
                $('#projectUl').empty();
                var tag = "";
                for (var i = 0; i < msg.MoainLinked.length; i++) {
                    tag = '<div style="col-xs-12;padding-top: 8px">● (' + msg.MoainLinked[i].Code.toString().substr(3, 6) + ') ' + msg.MoainLinked[i].Name + '</div>';
                    if (msg.MoainLinked[i].Level == 21)
                        $('#tafsilUl').append(tag);
                    else if (msg.MoainLinked[i].Level == 22)
                        $('#projectUl').append(tag);
                    else if (msg.MoainLinked[i].Level == 20)
                        $('#markazHazinelUl').append(tag);
                }
                if ($('#tafsilUl').find("div").length == 0)
                    $('#tafsilUl').append('<div style="col-xs-12;padding-top: 41%;text-align: center;color: #797979;">' + window.top.noTafsil + '</div>');
                if ($('#markazHazinelUl').find("div").length == 0)
                    $('#markazHazinelUl').append('<div style="col-xs-12;padding-top: 41%;text-align: center;color: #797979;">' + window.top.noHazineh + '</div>');
                if ($('#projectUl').find("div").length == 0)
                    $('#projectUl').append('<div style="col-xs-12;padding-top: 41%;text-align: center;color: #797979;">' + window.top.noProject + '</div>');

            }
        }
    });
}

function search() {
    filterModel = null;
    nextFind();
}
function nextFind() {
    ajax({
        loading: true,
        url: "AccountingApi/FindHeadingNode",
        data: {
            text: $('#txtSearch').val(),
            oldFilter: filterModel
        },
        success: function (msg) {
            filterModel = msg;
            resultSearch();
        }
    });
}
function clearTextFind() {
    $('#txtSearch').val('');
    $('#imgSvgPrevious').hide();
    $('#divError').hide();
    $('#closeImg').hide();
    $('#imgSvg').show();
    filterModel = null;
    filterSelectNode = null;
}
function resultSearch() {
    filterSelectNode = null;
    $('#jstree').jstree(true).deselect_all();
    $('#divError').hide();
    $('#imgSvg').hide();
    $('#closeImg').hide();
    $('#imgSvgPrevious').hide();
    if (filterModel == null) {
        $('#divError').show();
        $('#imgSvg').show();
        selectRootNode();
    }
    else {
        $('#closeImg').show();
        $('#imgSvgPrevious').show();

        if (filterModel.Level1.Id > 0)
            filterSelectNode = filterModel.Level1.Id;
        if (filterModel.Level2.Id > 0) {
            if ($('#jstree').jstree().get_node(filterSelectNode).original.hasChild && $('#jstree').jstree().get_node(filterSelectNode).children.length == 0) {
                $("#jstree").jstree('open_node', filterSelectNode);
                filterSelectNode = filterModel.Level2.Id;
            }
            else {
                $("#jstree").jstree('open_node', filterSelectNode);
                filterSelectNode = filterModel.Level2.Id;
                if (filterModel.Level3.Id > 0) {
                    if ($('#jstree').jstree().get_node(filterSelectNode).original.hasChild && $('#jstree').jstree().get_node(filterSelectNode).children.length == 0) {
                        $("#jstree").jstree('open_node', filterSelectNode);
                        filterSelectNode = filterModel.Level3.Id;
                    }
                    else {
                        $("#jstree").jstree('open_node', filterSelectNode);
                        filterSelectNode = filterModel.Level3.Id;
                        $('#jstree').jstree(true).select_node(filterSelectNode);
                        filterSelectNode = null;
                    }
                }
                else {
                    $('#jstree').jstree(true).select_node(filterSelectNode);
                    filterSelectNode = null;
                }
            }
        }
        else {
            $('#jstree').jstree(true).select_node(filterSelectNode);
            filterSelectNode = null;
        }
    }
    closeLoading();
}

function openModal(operation) {

    var depth = 0;
    var title = window.top.headlines;
    var width = "803";
    var height = "";

    if (operation === 'insert') {
        if (selectedData.node.original.depth === 0 || selectedData.node.original.depth === 1 || selectedData.node.original.depth === 2) {
            depth = selectedData.node.original.depth + 1;
        }
    }
    else if (operation === 'edit') {
        if (selectedData.node.original.depth === 1 || selectedData.node.original.depth === 2 || selectedData.node.original.depth === 3) {
            depth = selectedData.node.original.depth;
        }
    }
    if (depth > 0) {
        var src = '';
        switch (depth) {
            case 1:
                src = 'Accounting/GroupSave';
                title = operation === 'insert' ? window.top.groupDefinition : window.top.groupEdit;
                height = '300';
                width = '600';
                break;
            case 2:
                src = 'Accounting/KolSave';
                title = operation === 'insert' ? window.top.kolDefinition : window.top.kolEdit;
                height = '500';
                break;
            case 3:
                src = 'Accounting/MoainSave';
                title = operation === 'insert' ? window.top.moainDefinition : window.top.moainEdit;
                break;
        }
        src += '?' + (operation === 'insert' ? 'pid' : 'id') + '=' + selectedData.node.id + "&pText=" + selectedData.node.original.textParent;
        openInModal('', src, title, width, height);
    }
    else {
        showMsgModal(0, window.top.addError);

    }
}
function addNodeToTree(parentId, childId, text, name) {

    var urlIcon = '';
    var depth = selectedData.node.original.depth + 1;
    if (depth == 1)
        urlIcon = "../img/group.png";
    else if (depth == 2)
        urlIcon = "../img/kol.png";
    else if (depth == 3)
        urlIcon = "../img/tafsil.png";

    var textParent = selectedData.node.original.textParent != null ? selectedData.node.original.textParent.replace(selectedData.node.original.textParent.split("/")[selectedData.node.original.textParent.split("/").length - 1], "(" + childId + ")" + "  " + text) : window.top._accounts;

    if (selectedData.node.original.textParent != null) {
        if (selectedData.node.children.length == 0) {
            if (selectedData.node.original.hasChild)
                $("#jstree").jstree('open_node', selectedData.node.id);
            else {
                $('#jstree').jstree().create_node(selectedData.node.id, { "id": childId, "text": childId + " " + text, "icon": urlIcon, "depth": depth, "textParent": textParent, "codeParent": selectedData.node.id }, "last", function () { });
                $("#jstree").jstree('open_node', selectedData.node.id);
            }
        }
        else {
            $('#jstree').jstree().create_node(selectedData.node.id, { "id": childId, "text": childId + " " + text, "icon": urlIcon, "depth": depth, "textParent": textParent, "codeParent": selectedData.node.id }, "last", function () { });
        }
    }
    else {
        $('#jstree').jstree().create_node(selectedData.node.id, { "id": childId, "text": childId + " " + text, "icon": urlIcon, "depth": depth, "textParent": textParent, "codeParent": selectedData.node.id }, "last", function () { });
    }
    $('#jstree').jstree(true).deselect_all();
    $('#jstree').jstree(true).select_node(childId);
}
function editNodeToTree(text, childId) {
    selectedData.node.original.textParent = selectedData.node.original.textParent.replace(selectedData.node.original.textParent.split("/")[selectedData.node.original.textParent.split("/").length - 1], "(" + childId + ")" + "  " + text);
    $('#jstree').jstree('rename_node', selectedData.node, childId + " " + text);
    $('#jstree').jstree(true).set_id(selectedData.node, childId);
    refreshNodeInfo();
}
function deleteNodeTrees() {
    if (confirm(window.top.deleteConfirm)) {
        var depth = Number(selectedData.node.original.depth);
        var methodName = "";
        switch (depth) {
            case 1:
                methodName = "DeleteGroup";
                break;
            case 2:
                methodName = "DeleteKol";
                break;
            case 3:
                methodName = "DeleteMoain";
                break;
        }
        ajax({
            loading: true,
            url: "AccountingApi/" + methodName,
            data: { code: selectedData.node.id },
            success: function (result) {
                showMsgModal(2, result.FinalMessage);
                var ref = $('#jstree').jstree(true);
                var sel = ref.get_selected();
                if (sel != null) {
                    if (!sel.length) { return false; }

                    if (sel.length == 1)
                        ref.delete_node(sel);
                    else
                        ref.delete_node(sel[1]);
                }
                if (selectedData.node.children.length == 0)
                    selectedData.node.children.hasChild = false;
                selectRootNode();
            }
        });
    }
}
