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,
            data: ajaxTree({
                loading: true,
                url: "SaleApi/GetProductGroupTree",
                data: function (node) {
                    return JSON.stringify({
                        parentCode: (node.original ? node.original.code : 0),
                        depth: (node.original ? 1 : 0)
                    });
                }
            })
        }
    }).bind("loaded.jstree", function (e, data) {
        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('open_node', "ul > li:first");
    $("#jstree").jstree('select_node', "ul > li:first");
}
function refreshNodeInfo() {
    var code = Number(selectedData.node.original.code);
    if (code)
        $("[data-dept=1]").show();
    else {
        $("[data-dept=1]").hide();
        $('#addDiv').show();
    }

    $('#lblName').text(selectedData.node.original.Name);
    $('#lblCode').text(code || "---");
    if (code) {
        $("#lblId").text(selectedData.node.original.GroupId || "---");
        if (selectedData.node.original.ProductCount > 0 || selectedData.node.parents.length >= 4)
            $('#addDiv').hide();
        else
            $('#addDiv').show();
        $("#divLinkedProduct").show();
        loadGrid();
    }
    else
        $("#divLinkedProduct").hide();
}
function loadGrid(gridId, objectParameter) {
    var isExportExcel = objectParameter && objectParameter.exportExcel ? true : false;
    var code = selectedData.node.original.code;
    var gridBuilder = $("#gridProductGroup").gridBuilder();
    ajax({
        gridBuilder: gridBuilder,
        url: "SaleApi/GetProductLinkedGroup",
        data: {
            code: code,
            filter: gridBuilder.getFilter(),
            sort: gridBuilder.getSortFields(),
            pageNo: isExportExcel ? -1 : gridBuilder.getCurrentPageNumber()
        },
        success: function (data) {
            if (isExportExcel) {
                exportExcel(data, gridBuilder.getColumns(), gridBuilder.getColumnsCaption());
            }
            else
                gridBuilder.loadData(data);
        }
    });
}
function edit() {
    var code = selectedData.node.original.code;
    openModal(code);
}
function openModal(code) {
    var depth = selectedData.node.parents.length - (code === -1 ? 0 : 1);
    var parentCode = code !== -1 ? selectedData.node.original.codeParent : selectedData.node.original.code;
    var title = code === -1 ? window.top.productGroup : window.top.editProductGroup;
    var src = "Sale/ProductGroupSave?depth=" + depth + "&p=" + (Number(parentCode) || "") + (code > 0 ? "&code=" + code : "");
    openInModal('', src, title, 450, 350, false);
}
function deleteRow() {
    var code = Number(selectedData.node.original.code);
    if (!code) {
        showMsgModal(0, window.top.chooseItem);
        return;
    }
    if (confirm(window.top.deleteConfirm)) {
        ajax({
            loading: true,
            url: "SaleApi/DeleteProductGroup",
            data: { code: code },
            success: function (result) {
                showMsgModal(2, result.FinalMessage);
                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 || "0");
                if (selectedData.node.children.length === 0)
                    selectedData.node.original.hasChild = false;
            }
        });
    }
}
function addNodeToTree(code, text, groupId) {
    var parentCode = selectedData.node.original.code;
    $('#jstree').jstree().create_node(selectedData.node.id, {
        "code": code,
        "id" : code, 
        "hasChild": false,
        "children": false,
        "text": text + (groupId ? "(" + groupId + ")" : ""),
        "icon": "../img/open.png",
        "codeParent": Number(parentCode) || "",
        "GroupId": groupId,
        "ProductCount": 0,
        "Name": text
    }, "last", function (node) {});
    $('#jstree').jstree(true).deselect_all();
    $('#jstree').jstree(true).select_node(parentCode);
}
function editNodeToTree(text,groupId) {
    $('#jstree').jstree('rename_node', selectedData.node, text + (groupId ? "(" + groupId + ")" : ""));
    selectedData.node.original.GroupId = groupId;
    refreshNodeInfo();
}
function search() {
    filterModel = null;
    nextFind();
}
function nextFind() {
    var strFilter = $('#txtSearch').val();
    ajax({
        loading: true,
        url: "SaleApi/FindProductGroupNode",
        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;
            }
            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;
}






