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;
        }
    });
    $('#addDiv').hide();
    $('#editDiv').hide();
    $('#delDiv').hide();
    $('#ulMoain').css('height', $(window).height() - 260);
    $('#jstree').jstree({
        core: {
            check_callback: true,
            data: ajaxTree({
                loading: true,
                url: "AccountingApi/GetAccountingTree",
                data: function (node) {
                    return JSON.stringify({
                        id: (node.id == '#' ? null : node.id),
                        depth: (node.original ? node.original.depth : 0),
                        text: (node.id == '#' ? '' : node.text),
                        level: (node.original ? node.original.level : -1)
                    });
                },
            })
        }
    }).bind("loaded.jstree", function () {
        selectRootNode();
    });

    $('#jstree').on("changed.jstree", function (e, data) {
        if (data.selected.length > 0 && data.node) {
            selectedData = data;
            refreshNodeInfo();
        }
    });
    $("#jstree").on("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();
    $('#levelDiv').hide();
    $('#levelGroup').hide();
    $('#divLinkedMoain').hide();
    $('#shenase').html("---");
    $('#name').html(window.top.tafsil);
    $("#jstree").jstree('open_node', codeHedear);
}
function refreshNodeInfo(text, childId, id) {
    $('#name').html(selectedData.node.text);

    $('#levelDiv').hide();
    $('#levelGroup').hide();
    $("#divCurrencyType").hide();

    if (selectedData.node.original.depth == 1) {
        $('#addDiv').hide();
        $('#editDiv').hide();
        $('#delDiv').hide();
        $('#levelDiv').hide();
        $('#levelGroup').hide();
        $('#divLinkedMoain').hide();
        $('#shenase').html("---");
    }
    else if (selectedData.node.original.depth == 2) {
        $('#levelDiv').hide();
        $('#levelGroup').hide();
        $('#divLinkedMoain').hide();
        $('#addDiv').show();
        $('#editDiv').hide();
        $('#delDiv').hide();
        $('#shenase').html(selectedData.node.id);
    }
    else if (selectedData.node.original.depth == 3) {

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

        $('#type').html(selectedData.node.original.textParent.split("/")[0]);
        $('#code').html(selectedData.node.original.textParent.split("/")[1]);
        $('#shenase').html(selectedData.node.id.length == 6 ? selectedData.node.id.substring(3, 6) : selectedData.node.id);
        $('#name').html(selectedData.node.text.replace(selectedData.node.id.length == 6 ? selectedData.node.id.substring(3, 6) : selectedData.node.id, '').replace(/\&nbsp;/g, ''));
        $('#levelDiv').show();
        $('#levelGroup').show();
        $('#divLinkedMoain').show();
        var tafsilGroupCode = selectedData.node.original.id;
        if (tafsilGroupCode.length === 10)
            tafsilGroupCode = tafsilGroupCode.substring(0, 6);
        ajax({
            loading: true,
            url: "AccountingApi/GetMoainLinkedTafsilGroup",
            data: { tafsilGroupCode: tafsilGroupCode },
            success: function (msg) {
                closeLoading();
                $('#ulMoain').empty();

                for (var i = 0; i < msg.length; i++) {
                    $('#ulMoain').append(' <li style="padding-top:8px">(' + msg[i].Code + ') ' + msg[i].Name + '</li>');
                }

                if ($('#ulMoain').find('li').length == 0)
                    $('#ulMoain').append(' <li style="list-style-type:none;padding-top:8px;color:#797979;padding-right:34%;">' + window.top.noLinkMoain + '</li>');
            }
        });
    }
    else if (selectedData.node.original.depth == 4) {
        $('#addDiv').hide();
        $('#editDiv').show();
        $('#delDiv').show();

        if (selectedData.node.original.code.toString().substring(0, 3) == "992")
            $('#type').html(window.top.tafsil);
        else if (selectedData.node.original.code.toString().substring(0, 3) == "991")
            $('#type').html(window.top.hazineh);
        else if (selectedData.node.original.code.toString().substring(0, 3) == "990")
            $('#type').html(window.top.project);

        $('#code').html(selectedData.node.original.textParent.split("/")[1]);
        $('#levelDiv').show();
        $('#levelGroup').show();
        $("#divCurrencyType").show();
        $('#shenase').html(selectedData.node.original.id == id || id == undefined ? selectedData.node.original.id : id);
        $('#name').html(selectedData.node.text.replace(selectedData.node.original.id == id || id == undefined ? selectedData.node.original.id : id, '').replace(/\&nbsp;/g, ''));
        $("#currencyType").html(selectedData.node.original.currencyTypeName);
        $('#divLinkedMoain').hide();
    }
}
function search() {
    filterModel = null;
    nextFind();
}
function nextFind() {
    var strFilter = $('#txtSearch').val();
    ajax({
        loading: true,
        url: "AccountingApi/FindAccountingNode",
        data: {
            text: strFilter,
            oldFilter: filterModel
        },
        success: function (msg) {
            filterModel = msg;
            resultSearch();
        }
    });
}
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;

                /*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('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;
        }
    }
}
function clearTextFind() {
    $('#txtSearch').val('');
    $('#imgSvgPrevious').hide();
    $('#divError').hide();
    $('#closeImg').hide();
    $('#imgSvg').show();
    filterModel = null;
    filterSelectNode = null;
}
function openModal(operation) {
    var title = window.top.tafsilGroup;
    var depth = selectedData.node.original.depth;
    var parent = selectedData.node.parent;
    var parentLevel = 0;
    var height = "320";
    var width = "600";
    var src;
    if (operation === 'insert') {
        if (depth === 2 || depth === 3) {
            if (depth === 2)
                title = window.top.tafsilGroupDefinition;
            else {
                title = window.top.tafsilDefinition;
                parentLevel = $('#jstree').jstree().get_node(parent).original.level;
            }
            src = "Accounting/TafsilGroupSave?code=" + selectedData.node.original.code + "&depth=" + (depth + 1) + "&text=" + selectedData.node.text + "&level=" + selectedData.node.original.level + "&parentLevel=" + parentLevel;
            openInModal('', src, title, width, height, false);
        }
        else {
            showMsgModal(0, window.top.addError);
        }
    }
    else if (operation === 'edit') {
        if (depth === 3 || depth === 4) {
            if (depth === 3)
                title = window.top.tafsilGroupEdit;
            else {
                title = window.top.tafsilEdit;
                parent = $('#jstree').jstree().get_node(parent).parent;
                parentLevel = $('#jstree').jstree().get_node(parent).original.level;
            }
            src = "Accounting/TafsilGroupSave?code=" + selectedData.node.original.code + "&id=" + selectedData.node.id + "&depth=" + depth + "&text=" + selectedData.node.text.replace(/\&nbsp;/g, '') + "&level=" + selectedData.node.original.level + "&currencyTypeCode=" + selectedData.node.original.currencyTypeCode + "&parentLevel=" + parentLevel;
            openInModal('', src, title, width, height, false);
        }
        else {
            showMsgModal(0, window.top.editError);
        }
    }
}
function addNodeToTree(parentId, childId, text, id, currencyCode, currencyName) {
    debugger;
    var src = "";
    if (selectedData.node.original.depth == 2) {
        src = "../img/level3.png";
        id = childId.toString().substring(3, 6);
    }
    else if (selectedData.node.original.depth == 3) {
        src = "../img/level4.png";
    }
    if (selectedData.node.children.length == 0 && selectedData.node.original.hasChild) {
        $("#jstree").jstree('open_node', selectedData.node.id);
    }
    else {
        $('#jstree').jstree().create_node(selectedData.node.id, {
            "code": childId,
            "id": id,
            "text": id + "  " + text,
            "icon": src,
            "textParent": selectedData.node.text + "/" + text,
            "depth": selectedData.node.original.depth + 1,
            "codeParent": selectedData.node.id,
            "currencyTypeCode": currencyCode,
            "currencyTypeName": currencyName,
        }, "last", function (e) { });
    }
    $('#jstree').jstree(true).deselect_all();
    $('#jstree').jstree(true).select_node(id);
}
function editNodeToTree(text, childId, id, currencyTypeCode, currencyTypeName) {
    if (selectedData.node.original.depth === 3) {
        if (id.length === 1)
            id = "00" + id;
        else if (id.length === 2)
            id = "0" + id;
    }
    selectedData.node.original.id = id;
    if (selectedData.node.original.depth === 3) {
        selectedData.node.original.code = selectedData.node.original.code.toString().substr(0, 3) + id;
    }
    else if (selectedData.node.original.depth === 4) {
        selectedData.node.original.currencyTypeCode = currencyTypeCode;
        selectedData.node.original.currencyTypeName = currencyTypeName;
    }

    $('#jstree').jstree('rename_node', selectedData.node, id + " " + text);
    $('#jstree').jstree(true).set_id(selectedData.node, id);
    refreshNodeInfo(text, childId, id);
}
function deleteNodeToTree(operation) {
    var depth = Number(selectedData.node.original.depth);
    if (depth === 3 || depth === 4) {
        if (confirm(window.top.deleteConfirm)) {
            var methodName = "";
            var code = selectedData.node.original.code;
            if (depth === 3)
                methodName = "DeleteMoain";
            else
                methodName = "DeleteTafsil";
            ajax({
                loading: true,
                url: "AccountingApi/" + methodName,
                data: { code: code },
                success: function (msg) {
                    var ref = $('#jstree').jstree(true);
                    var sel = ref.get_selected();
                    if (sel) {
                        if (!sel.length) { return false; }
                        if (sel.length === 1)
                            ref.delete_node(sel);
                        else
                            ref.delete_node(sel[1]);
                    }
                    $('#jstree').jstree(true).deselect_all();
                    $('#jstree').jstree(true).select_node(selectedData.node.original.codeParent);
                    if (selectedData.node.children.length === 0)
                        selectedData.node.original.hasChild = false;
                }
            });
        }
    }
    else {
        showMsgModal(0, window.top.deleteError);
    }
}



