
<%@
page contentType="text/html; charset=UTF-8"
     import="kr.co.kihyun.beans.user.HttpSSOLogin"
     import="kr.co.kihyun.moumi.Moumi" import="kr.co.kihyun.lang.MString"
     import="kr.co.kihyun.lang.MLong" import="kr.co.kihyun.beans.user.Dept"
     import="kr.co.kihyun.beans.user.PartList"
     %>

<%
    String rootId = request.getParameter("rootID");
    if (rootId == null || rootId == "null") {
        rootId = "ROOT";
    }
    String userYN = request.getParameter("userYN");
    if (userYN == null) {
        userYN = "N";
    } else {
        userYN = "Y";
    }
    //System.out.println("rootId="+rootId+"::::userYN="+userYN);
%>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"></meta>
        <script type="text/javascript" src="/totsys/common/js/jquery-1.12.4.min.js"></script>
        <script type="text/javascript" src="/totsys/common/js/jquery.cookie.js"></script>
		<script type="text/javascript" src="/totsys/common/js/jquery.hotkeys.js"></script>
		<script type="text/javascript" src="/totsys/common/js/jquery.jstree.js"></script>

        <script type="text/javascript" src="/totsys/common/js/jquery.custom.indicator.js"></script>
        <style>
            #newTree { text-align: justify; font-size:9pt; vertical-align:middle; }
        </style>
    </head>
    <body>
        <input type="button" class="button" value="Search"       id="search"      style="display:none" />
        <input type="button" class="button" value="Search clear" id="searchClear" style="display:none" />
        <input type="button" class="button" value="checked Id"   id="checkbtn"    style="display:none" />
        <input type="button" class="button" value="refresh Id"   id="refresh"     style="display:none" />
        <input type="button" class="button" value="focus Move"   id="focusMove"   style="display:none" />
        <div id="searchType" style="display:none"></div>
        <div id="searchWord" style="display:none"></div>
        <div id="moveType"   style="display:none"></div>
        <div id="newTree" class="newTree"></div>

        <script type="text/javascript" class="source">
            var gSearchGubun = "USER";   //default=USER
            //@@@ var gblSearching = false;


            $(function() {
                $("#newTree").jstree({
                    "plugins": ["themes", "json_data", "search", "types", "ui", "core"],
                    "themes": {
                        "theme": "classic",
                        "dots": true,
                        "icons": true,
                        "url": "/totsys/common/js/themes/classic/style.css"
                    },
                    "json_data": {
                        "data": [
                            {
                                "data": "조직도",
                                "state": "closed",
                                "attr": {"id": "ROOT", "rel": "ROOT", "rootid": '<%=rootId%>', "sysAuth": "ROOT"}
                            }
                        ],
                        "ajax": {
                            "url": "/servlet/kr.co.kihyun.tree.Tree",
                            "data": function(n) {
                                var data = {};
                                data.id = n.attr("id");
                                data.rootId = n.attr("rootid");
                                data.gubun = "ORGAN";
                                data.userYN = '<%=userYN%>';
                                data.sysAuth = n.attr("sysAuth");
                                return data;
                            }
                        },
                        "progressive_render": true
                    },
                    "search": {
                        "case_insensitive": true,
                        "ajax": {
                            "type": "POST",
                            "url": "/servlet/kr.co.kihyun.tree.TreeSearch",
                            "data": function(str) {
                                var data = {};
                                data.keyWord = str;
                                data.startId = encodeURIComponent('<%=rootId%>');
                                data.gubun = gSearchGubun;
                                return data;
                            },
                            //"async": false,
                            "async": true,
                            "success": function(data) {
                                //alert("data = " + data);
                                if(data.length == 0 || data == "#" || data == ('#'+'<%=rootId%>')) {
                                    alert('<%=Moumi.getMessageBundle().getString("moumi.message.popup.notSearchUserDept")%>');  //검색된 사용자/부서명이 없습니다.
                                    return;
                                }
                            },
                            "beforeSend" : function() {
                                $.customIndicator.show(window.parent);
                            },
                            "complete" : function() {
                                $.customIndicator.hide(window.parent);
                            }
                        }
                    },
                    "types": {
                        "valid_children": ["ROOT", "DEPT", "USER"],
                        "types": {
                            "ROOT": {
                                "icon": {"image": "/totsys/common/images/pc-user.gif"}
                            },
                            "USER": {
                                "icon": {"image": "/totsys/common/images/person.png"}
                            }
                        }
                    },
                    "core": {'initially_open': ['ROOT', '<%=rootId%>']}
                });

                $("#refresh").click(function() {
                    $("#newTree").jstree("refresh");
                });

                $("#searchClear").click(function() {
                    $("#newTree").jstree("clear_search");
                    $("#searchResult").empty();
                });

                $("#search").click(function() {
                    //@@@ gblSearching = true;
                    gSearchGubun = $('#searchType').text();  //USER,DEPT
                    //alert("gSearchGubun = " + gSearchGubun);
                    $("#newTree").jstree("search", $('#searchWord').text());
                });

                //### 검색을 종료한 후에 실행된다. : 검색된 것이 있으면 최초로 포커스를 이동시킨다.
                $("#newTree").bind("search.jstree", function (e, data) {
                    if(data.rslt.nodes.length > 0) {
                        //1.이전에 선택된 모든 노드를 해제한다.
                        $('#newTree').jstree('deselect_all');

                        //2.검색유형과 다른 것은 style를 제거한다.
                        var tmpRel = "";
                        $("#newTree").find(".jstree-search").each(function() {
                            tmpRel = $(this).parent("li").attr("rel");

                            if(gSearchGubun !== tmpRel) {
                                //alert("rel = " + tmpRel );
                                try {
                                    $(this).removeClass("jstree-search");
                                } catch(e) {
                                    alert(e);
                                }
                            }
                        });

                        $("#moveType").text("down");
                        $("#focusMove").click();
                    }

                    //@@@ gblSearching = false;
                    //alert("Found " + data.rslt.nodes.length + " nodes matching '" + data.rslt.str + "'.");
                });

                $("#newTree").bind("select_node.jstree", function(e, data) {
                    //@@@ if(gblSearching) { return; }
                    //alert(data.inst.get_text(data.rslt.obj) + " - " + data.rslt.obj.attr("id")); // id - Text
                    //alert(data.inst.get_text(data.rslt.obj) + " - " + data.rslt.obj.attr("name")); // name - Text
                    //alert(data.inst.get_text(data.rslt.obj) + " - " + data.rslt.obj.attr("rel")); // rel - Text

                    //부서명으로 검색한 경우에 선택이 되지 않으니까 아래,위로 포커스를 이동시킬 수 없다.
                    /*
                    if(data.rslt.obj.attr("rel") !== "USER") {
                        //alert('<%=Moumi.getMessageBundle().getString("moumi.message.popup.selectUser")%>');  //사용자를 선택하세요!
                        $('#newTree').jstree('deselect_all');
                        //return;
                    }
                    */

                    parent.userList(data.rslt.obj.attr("id"), data.inst.get_text(data.rslt.obj), data.rslt.obj.attr("rel"));
                });



                //조직도에서 검색된 노드로 포커스를 이동시킨다.  strType : down, up
                $("#focusMove").click(function() {
                    var moveType = $("#moveType").text();  //down,up
                    //alert("moveType = " + moveType);

                    //1.현재 선택된 object의 offset.top를 구한다.
                    var NODE = $.jstree._focused().get_selected();
                    var nodeId = $(NODE).attr("id");
                    if (nodeId == undefined) {
                        nodeId = "";
                    }

                    var currentObj = $('#' + nodeId);
                    var currentOffset = currentObj.offset();
                    var currentOffsetTop = -1;
                    if(currentOffset != null) {
                        currentOffsetTop = currentOffset.top;
                    }

                    //2.현재 currentOffsetTop 보다 큰 값에 존재하는 id를 찾아서 리턴한다.
                    var currentNodeId = "";
                    currentNodeId = getDeptUserId(nodeId, currentOffsetTop, moveType);

                    //3.리턴된 id가 없다면 메세지를 띄우고 리턴한다.
                    if(currentNodeId === null || currentNodeId === "") {
                        alert("더 이상 찾을 수 없습니다.");
                        return;
                    }

                    //4.이전에 선택된 모든 노드를 해제한다.
                    $('#newTree').jstree('deselect_all');

                    //5.리턴된 id로 노드를 선택한다.
                    $("#newTree").jstree("select_node", '#' + currentNodeId);   //591
                     try {
                        var selectedObj = $('#' + currentNodeId);
                        var elementOffset = selectedObj.offset();
                        //alert("[offset.top] : " + elementOffset.top + "\n[offset.left] : " + elementOffset.left);
	                    //ie10,11 및 호환성 보기 까지 전부 동작하도록 수정
                        var verticalCenterPosition = $(window).height() / 2;
                        //// 즉시이동
                        //$("html").scrollTop(elementOffset.top - verticalCenterPosition);
                        // 부드럽게 이동(500ms)
                         $("html").animate({
                            scrollTop: elementOffset.top - verticalCenterPosition
                        }, 500);

                    } catch(e) {
                        alert(e);
                    }
                });
            });
            //다운,업 버튼 클릭 시 : 2.현재 currentOffsetTop 보다 큰 값에 존재하는 id를 찾아서 리턴한다.
            function getDeptUserId(strId, intTop, strType) {
                //xxx alert("strId = " + strId + ", intTop = " + intTop + ", strType = " + strType);
                var id = "";
                var idArray = new Array();
                var returnId = "";
                var blSearchOk = false;

                if( strType === "down") {
                    $("#newTree").find(".jstree-search").each(function() {
                        id = $(this).parent("li").attr("id");

                        if(blSearchOk === false && strId !== id) {
                            var selectedObj = $('#' + id);
                            var elementOffset = selectedObj.offset();

                            if(elementOffset.top > intTop) {
                                //xxx alert("[offset.top] : " + elementOffset.top + "\n[offset.left] : " + elementOffset.left);
                                returnId = id
                                blSearchOk = true;
                            }

                        }
                    });
                }

                if( strType === "up") {
                    $("#newTree").find(".jstree-search").each(function() {
                        idArray.push( $(this).parent("li").attr("id") );
                    });
                    idArray.reverse();

                    for(var i= 0; i < idArray.length; i++) {
                        id = idArray[i].toString();

                        if(blSearchOk === false && strId !== id) {
                            var selectedObj = $('#' + id);
                            var elementOffset = selectedObj.offset();

                            if(elementOffset.top < intTop) {
                                //alert("[offset.top] : " + elementOffset.top + "\n[offset.left] : " + elementOffset.left);
                                returnId = id
                                blSearchOk = true;
                            }
                        }
                    }
                }

                return returnId;
            }

        </script>

    </body>
</html>
