<%@page import="com.ibm.db2.jcc.am.dp"%>
<%
/************************************************************@@
  * Program Name	: top.jsp
  * Description		:
  * Author		:
  * Create Date		:
  * History		:
  *
  * Modify Date         : 2014.08.27 (조영준 - 소스정리 및 디자인 수정)
@@************************************************************/
%>
<%@ page contentType="text/html; charset=UTF-8"
    import="kr.co.kihyun.lang.Execute"
    import="kr.co.kihyun.moumi.Moumi"
    import="kr.co.kihyun.moumi.doc.MDoc"
    import="kr.co.kihyun.lang.MString"
    import="kr.co.kihyun.beans.user.User"
    import="kr.co.kihyun.beans.batch.*"
    import="kr.co.kihyun.lang.Encoder"
    import="kr.co.kihyun.beans.user.HttpSSOLogin"
    import="kr.co.kihyun.beans.user.MultiCheck"
%>
<%@ include file="/totsys/common/inc/sec/secure.inc.jsp"%>
<%
	String usID = HttpSSOLogin.getLoginID(request);
	String deptID = HttpSSOLogin.getDeptID(request);
    int sysAuth = HttpSSOLogin.getSysAuth(request);
    int topStat  = MInteger.parseInt(request.getParameter("topStat"),0);

    int screenWidth = MInteger.parseInt(request.getParameter("screenWidth"),0);
    int screenHeight = MInteger.parseInt(request.getParameter("screenHeight"),0);

    if(screenWidth != 0 && screenHeight != 0){
        int formWidth = screenWidth - 205;
        int totperInsertHeight = screenHeight - 460;
        int totperViewHeight = screenHeight - 400;
        int repoperInsertHeight = screenHeight - 450;
        int repoperViewHeight = screenHeight - 520;
        int docViewHeight = screenHeight - 550;
        int totperDocViewHeight = screenHeight - 630;
        int totperFormDocViewHeight = screenHeight - 400;
        int totperFormModifyHeight = screenHeight - 410;

        session.setAttribute("formWidth",formWidth);
        session.setAttribute("totperInsertHeight",totperInsertHeight);
        session.setAttribute("totperViewHeight",totperViewHeight);
        session.setAttribute("repoperInsertHeight",repoperInsertHeight);
        session.setAttribute("repoperViewHeight",repoperViewHeight);

        session.setAttribute("docViewHeight",docViewHeight); //제출하기 - 기본정보
        session.setAttribute("totperDocViewHeight",totperDocViewHeight); //집계하기 - 기본정보
        session.setAttribute("totperFormDocViewHeight",totperFormDocViewHeight); //집계하기 - 양식함 - 양식정보
        session.setAttribute("totperFormModifyHeight",totperFormModifyHeight); //집계하기 - 양식함 - 양식변경
    }
%>
<%@page import="kr.co.kihyun.lang.MInteger"%>
<%@page import="kr.co.kihyun.lang.MLong"%>

<script language="JavaScript">
    var menuarray = null;

    function menuView(id,sys_auth){
    	var menuarray = $("div[id^=menu]");
        for(i=1; i<menuarray.length; i++){	// skip wz_tooltip, left.jsp에서 참조하는 wz_tooltip.js의 div가 첫번째 div이므로 건너뜀.
        	$("div[id=menu"+i+"]").hide();
        }
        
        $("div[id=menu"+id+"]").show();
        //parent.frames['left'].document.getElementById(menuarray[id].id).style.display='';
		//권한 6,5추가 by wonseok Lee 20171101
        if((sys_auth == 2 || sys_auth == 9 || sys_auth == 7 || sys_auth == 6 || sys_auth == 5) && id == 1 ) {	// 문서등록버튼이 아닌 진행함을 첫 화면으로
        	location.href=document.getElementById('linkd'+id+'2').href;
        }else{
        	location.href=document.getElementById('linkd'+id+'1').href;
        }
    }

    function menuSelect(menu){
        menuView(menu,'<%=sysAuth%>');
        for(i=1; i<menuarray.length; i++) {	// skip wz_tooltip, left.jsp에서 참조하는 wz_tooltip.js의 div가 첫번째 div이므로 건너뜀.
            lowlight(i);
        }
        highlight(menu);
    }

    function highlight(menu) {
        document.getElementById('topmenu'+menu).className = 'mediumButton mediumHighlight';	// for IE
        document.getElementById('topmenu'+menu).setAttribute('class', 'mediumButton mediumHighlight');
    }

    function lowlight(menu) {
        document.getElementById('topmenu'+menu).className = 'mediumButton';	// for IE
        document.getElementById('topmenu'+menu).setAttribute('class', 'mediumButton');
    }

    function initMenus() {
        menuarray = $("div[id^=menu]");
        menuRow = document.getElementById('menuPanel').rows[0];
        var tmpStrMenu; //로그인 세션권한에 상관없이 집계자료,제출자료,게시판으로 고정값 넣는다.

        for(i=menuarray.length; i>=1; i--){	// skip wz_tooltip, left.jsp에서 참조하는 wz_tooltip.js의 div가 첫번째 div이므로 건너뜀.
            cell = menuRow.insertCell(0);
            if(i==1){
                tmpStrMenu = "<%= Moumi.getMessageBundle().getString("moumi.message.tot_doc") %>";
            }else if(i==2){
                tmpStrMenu = "<%= Moumi.getMessageBundle().getString("moumi.message.tot_report.submitted.report_data") %>";
            }else if(i==3){
                tmpStrMenu = "<%= Moumi.getMessageBundle().getString("moumi.message.board") %>";
            }
                menuHtml =
                    '<a id="topmenu'+i+'" class="mediumButton " href="#" onclick="menuSelect('+i+');">\
                            <span class="buttonWrapper">'+tmpStrMenu+'</span>\
                    </a>';
                cell.innerHTML = menuHtml;
                if($("div[id=menu"+i+"]").css("display") == '') {
                    highlight(i);
                } else {
                    lowlight(i);
                }
        }
    }

    function sizeSet(){
        topForm.screenWidth.value = window.screen.width;
        topForm.screenHeight.value = window.screen.height;
        topForm.submit();
    }
    <%if(HttpSSOLogin.getSysAuth(request) != Moumi.TOTPER){%>
    function userModify(){
        window.open("/totsys/sysadm/user/user_modify.jsp?userID=<%=usID%>","","width=440, height=350, toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no");
    }
    <%}%>

     function logOut(){
        url="http://<%= request.getServerName().replace("neis", "ats") %>/";
        if(confirm("로그아웃하시겠습니까?")){
//                            location.href = "./logOut.jsp";
//                            top.window.close();
        }
    }

    //겸임부서선택
    var multihtml,multiloading=false;
    var deptID='<%=deptID%>';
    function dualPostDetpSelect() {
    	if(multiloading)return;
    	multiloading=true;
    	$('#multideptwrap').html('겸임부서확인중...');
        //2014.08.21 Add by KWON,HAN : 겸임부서가 없으면 "겸임부서가 존재하지 않습니다." 메세지를 띄운다.
        var iResult = 0;
        $.ajax({
            url : "/servlet/kr.co.kihyun.beans.user.HttpMultiCheckCount",
            type : 'GET',
            dataType : 'text',
            data : "userId=<%=usID%>",
            timeout : 10000,
            async : true,
            success : function(data) {
                iResult = parseInt(data);
                /*if(iResult <= 1) {
                    alert("<%=Moumi.getMessageBundle().getString("moumi.message.popup.dualPostNotExist")%>");   //겸임부서가 존재하지 않습니다.
                    multiloading=false;
                    $('#multideptwrap').html('');
                    return false;
                 }else{
                 */
                 	$('#multideptwrap').html('부서목록 확인중...');
                 	//window.open('/totsys/login/popup_dept.jsp?id=<%=usID%>');
                 	$.post('/totsys/login/popup_dept.jsp',{id:'<%=usID%>'},function(data){
                 		multihtml='<select onchange="selectDeptLogin(this[this.selectedIndex]);">';
						multihtml+='<option selected="selected" >' + "[겸임부서목록]" + '</option>';
         				$(data).find('label').each(function(i,o){
         					var mdid=$(o).find('input:first').val();
         					var txt=$(o).text();
         					var isorigin=txt.indexOf('(원소속)')>-1?' isorigin="Y" ':' isorigin="N" ';
         					//var iscurrent=mdid==deptID?' selected="selected" ':' ';
         					multihtml+='<option '+isorigin +' value="'+mdid+'">'+txt+'</option>';
         				});
                 		multihtml+='</select>';
         				$('#multideptwrap').html(multihtml);
         				multiloading=false;
         				dualPostDetpSelect=function(){};
                 	},'html');
                 //}
            },
            error : function() {
                iResult = -1;
                alert("<%=Moumi.getMessageBundle().getString("moumi.message.popup.serverError")%>");   //서버 에러가 발생하였습니다.
                multiloading=false;
                $('#multideptwrap').html('');
            }
        });

        //alert("iResult === " + iResult);
        //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

        //겸임부서 새창으로 뜨지 않게
//        window.open("/indexSSOupdate.jsp?id=<%=usID%>","");
//        window.open("./multiCheck.jsp?id=<%=usID%>","");
		/* if($('#multicheckifr').length==0){
			$('<iframe id="multicheckifr" src="" style="display:none"/>').appendTo('body');
		}else{

		} */
		//parent.location.href="./multiCheck.jsp?id=<%=usID%>";

        /* if (/MSIE/.test(navigator.userAgent)) {
            if(navigator.appVersion.indexOf("MSIE 7.0")>=0 || navigator.appVersion.indexOf("MSIE 8.0")>=0 || navigator.appVersion.indexOf("MSIE 9.0")>=0) {
                parent.window.open('about:blank','_self').close();
            } else {
                parent.window.close();
            }
        } */
    }
    function selectDeptLogin(opt){
   		opt=$(opt);
   		if(typeof(opt.attr('value')) == "undefined" || opt.attr('value') == null){
   			return;
   		}
    	if(confirm('부서를 변경하시겠습니까?')){
    		var usid='<%=usID%>';
    		var isorigin=opt.attr('isorigin');
    		//alert(isorigin);
    	    $.get('dept_update.jsp?deptId='+opt.val()+'&id='+usid+'&orignDeptFlag='+isorigin,function(data){
    	    	alert('선택한 겸임부서로 변경되었습니다.');
    	    	parent.location.href='/servlet/kr.co.kihyun.beans.user.HttpSSOLogin'
    	    			//+'?deptID='+$('#multideptwrap option:selected').val()+'&id=<%=usID%>';
    	    			+'?id=<%=usID%>';
    	    });
    	}else{
    		opt.parent().find('[value=<%=deptID%>]').attr('selected','selected');
    	}

    }

	function modal(pop){
		var blockhtml='<div onclick="parent.frames.topx.pop.focus();" class="popframeblock" style="text-align: center; color: #000; background-color: #fff; font-family: dotum; font-size: 13px; font-weight: bold;position: absolute;top:0;left:0;width:100%;height:'+opener.parent.$('frameset').prop('scrollHeight')+'px; z-index: 1001; opacity: 0.5;-ms-filter:\'progid:DXImageTransform.Microsoft.Alpha(Opacity=50)\';filter:alpha(opacity=50);">'
		+'&nbsp;'
		+'</div>';
		for(var i=0;i<opener.parent.frames.length;i++){
	        if(opener.parent.$(opener.parent.frames[i].document.body).find('.popframeblock').length==0){
				opener.parent.$(opener.parent.frames[i].document.body).append(blockhtml);
	        }
		}
		if(pop&&!pop.closed){
			setTimeout(function(){modal(pop);},100);
		}else{
			for(var i=0;i<opener.parent.frames.length;i++){
		        opener.parent.$(opener.parent.frames[i].document.body).find('.popframeblock').remove();
			}
		}

	}
	var pop=null;
    function person(){
        pop=window.open("/totsys/sysadm/user/user_view_per.jsp?userID=<%=usID%>", "pop_dept", "width=450 ,height=250 ,toolbar=no, directories=no, status=no, menubar=no, resizable=no");
        //setTimeout(function(){modal(pop);},100);
    }

    function onOk() {
    	//
		alert("테스트 서버에서는 제외되는 기능입니다.");
    	return;
        // 기존 방식
        //document.conctUp.submit();

        // 2014.10.22 By YoungJun Cho.
        // 조직사용자갱신 실행시 indicator 띄우기 frameset 구조라서 'window.self' 로 실행시 top.jsp 영역(페이지 상단) 에만 indicator가 보이므로
        // target 을 'top.frames["main"].window' 로 실행한다.
        try {
            var targetWindow = top.frames["main"].window;

            if (!targetWindow.jQuery) {
                // main frame 내 document 에 jquery 가 삽입되어 있지 않은 경우 동적으로 추가.
                var headTag = targetWindow.document.getElementsByTagName("head")[0];
                var newScript = targetWindow.document.createElement("script");

                newScript.async = true;
                newScript.type = "text/javascript";
                newScript.src = "/totsys/common/js/jquery-1.12.4.min.js";
                headTag.appendChild(newScript);

                // appendChild 후 jquery 를 바로 사용이 안되는 현상이 있어서 100ms 후에 indicator 를 실행하도록 처리함.
                setTimeout( function(){ $.customIndicator.show( targetWindow ); },100);

            } else {
                // main frame 내 document 에 jquery 가 이미 삽입되어있는 경우 indicator 바로 실행.
                $.customIndicator.show( targetWindow );
            }
        } catch(e) {
            alert("indicator 처리시 스크립트 에러가 발생하였습니다.\n\r조직사용자갱신은 정상 실행됩니다.");
        } finally {
            //ui 조작(jquery로 indicator 띄우기)에 실패하더라도 조직사용자갱신 실행은 되어야 한다.
            document.conctUp.submit();
        }
    }

    $(window).load(function() {

        // 2014.10.22 By YoungJun Cho.
        // 조직사용자갱신 실행 후, top.jsp 가 reload 되므로 onload 이벤트에서 indicator 를 hide 한다.
        try {
            var targetWindow = top.frames["main"].window;
            $.customIndicator.hide( targetWindow );
            //clock();
        } catch(e) {
            //alert("indicator 처리에 문제가 발생하였습니다.");
            //alert(e);
        } finally {
        }
    });
    function clock(){
    	var date=new Date();
    	var year=date.getFullYear();
    	var mon=(date.getMonth()+1)
    	var dt=date.getDate();
    	var hour=date.getHours();
    	var min=date.getMinutes();
    	var sec=date.getSeconds();
    	var arr=[year,mon,dt,hour,min,sec];
    	for(var i=0;i<arr.length;i++){
    		if(arr[i]<10)arr[i]='0'+arr[i];
    	}
    	try{
    		$('.clock').text(arr[0]+'-'+arr[1]+'-'+arr[2]+' '+arr[3]+':'+arr[4]+':'+arr[5]);
    	}catch(e){
    	}
    	setTimeout(clock,1000);
    }
</script>

<body onload=""
	LEFTMARGIN="0" TOPMARGIN="0" MARGINWIDTH="0" MARGINHEIGHT="0"
	style="background: transparent url('/totsys/common/images/sky.png') no-repeat top left; display: block; height: 80px;">
<form name="topForm" method="post" action="./top.jsp">
    <input type="hidden" name="topStat" value="" />
    <input type="hidden" name="screenWidth">
    <input type="hidden" name="screenHeight">
</form>
<FORM name="conctUp" action="/servlet/kr.co.kihyun.beans.batch.HttpUpdate" method="post"></FORM>
<!--
    <div id="systemName">
        <span style="color: #1a56a5;"><%//= Moumi.getMessageBundle().getString("moumi.message.firstname") %></span>
    </div>
-->
<table width="100%" cellspacing="0" cellpadding="0" style="border: 0; margin: 20px 0 0 7px;">
<!--
    <tr>
        <td width="7px" rowspan="2">&nbsp;</td>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
    </tr>
-->
    <tr>
        <td class="largeButton" style="width:100%;">
           <!-- ie10,11 호환성 수정 -->
            <div class="buttonWrapper" style="min-width: 1500px; height: 34px;">
		<table id="menuPanel" border="0" align="left">
                    <tr width="1000">
                        <td><a id="topmenu1" class="mediumButton" href="#" onclick="menuSelect(1);"><span class="buttonWrapper">
                        	<%= Moumi.getMessageBundle().getString("moumi.message.tot_doc") %></span></a>
                        	</td>
                        <td><a id="topmenu2" class="mediumButton" href="#" onclick="menuSelect(2);"><span class="buttonWrapper">
                        	<%= Moumi.getMessageBundle().getString("moumi.message.tot_report.submitted.report_data") %></span></a>
                        </td>
                        <td><a id="topmenu3" class="mediumButton" href="#" onclick="menuSelect(3);"><span class="buttonWrapper">
                        	<%= Moumi.getMessageBundle().getString("moumi.message.board") %></span></a>
                        </td>
                    </tr>
		</table>
                <table border="0" align="left">
                    <tr width="1000">
                        <td style="padding: 0 3px 0 40px;" nowrap>
                            <span id="welcome">
                                <span class="welcome_dept"><%= HttpSSOLogin.getDeptName(request)%></span>
                                <span class="welcome_username"><%= MString.isNull(usID) ? "" : new User().getName(usID)+" 님" %></span>
                                <span class="welcome_greeting">환영합니다.</span>
                                <span class="clock"></span>
                                <span class="welcome_close">
                                    <img src="/totsys/common/inc/board/doc/images/bt_close.gif" style="" onclick="javascript:top.window.close()" alt="닫기" />
                                </span>
                                <!--
                                <font><%//= HttpSSOLogin.getDeptName(request)%></font>&nbsp;
                                <font color="#aacdd8"><b><%//= MString.isNull(usID) ? "" : new User().getName(usID)+" 님" %></b></font>&nbsp;좋은 하루 보내세요.
                                <img src="/totsys/common/inc/board/doc/images/bt_close.gif" style="vertical-align: middle; cursor: pointer;" onclick="javascript:top.window.close()" alt="닫기">
                                -->
                            </span>
                        </td>
                        <td nowrap>
                            <div id="top_other_menu">
                                <!--//겸임 버튼시작//-->
                                <%
                                    //겸임부서유무체크
                                    /*MultiCheck mc = new MultiCheck();
                                    mc.IdCheck(usID);
                                    int tmpCount = mc.getCount();
                                    if(tmpCount>1){*/
                                %>
<!--                                 <img src="/totsys/common/images/folder.gif"><a href="#" onclick="dualPostDetpSelect();" title="겸임부서선택">겸임부서선택</a>&nbsp; -->
<!--                                 <div id="multideptwrap" style="display: inline;color:rgb(177, 188, 206);"></div> -->
                                <%//}else{%>
                                <%//}%>
                                <img src="/totsys/common/images/folder.gif"><a href="#" onclick="person();" title="개인정보">개인정보</a>&nbsp;
                                <%
                                    //1. Cookie 가져오기
                                    Cookie[] c = request.getCookies();
                                    //2. Cookie 출력하기
                                    //[모든 쿠키값 출력]
                                    //쿠키값이 배열 형태로 넘어오기 때문에 루프를 돌면서 값을 풀력하면 모든 쿠키의 값을 출력할수 있다.
                                    /*  for(int i=0; i<c.length; i++){
                                     System.out.println("   c["+i+"].getName()::::"+c[i].getName()+"\n");
                                     System.out.println(" WAS명:" + c[i].getValue() + "");
                                    }*/

                                    String cookieName = "JSESSIONID";
                                    int cookieFind = -1;

                                    for(int i=0;i<c.length;i++){
                                        if(c[i].getName().equals(cookieName)){
                                            cookieFind = i;
                                            //out.println(" c["+i+"].getName()::::"+c[i].getName()+"\n");
                                            //out.println(" WAS명:" + c[i].getValue() + "");
                                            //break;
                                        String strTemp =  c[i].getValue();
                                        boolean isFirst = true;//처음인지 검사
                                            while(true)       {
                                                int index = strTemp.indexOf("-");//찾는 문자열 위치 찾기
                                                if(index == -1) break;//없다면 루프 종료
                                                if(!isFirst)//처음이 아닐때만 '/' 출력
                                                {
                                                    System.out.print(" / ");
                                                }else {
                                                    isFirst = false;
                                                }
                                                strTemp = strTemp.substring(index+5);
                                                int eindex = strTemp.indexOf("_");//추출할 문자열 끝 위치 찾기
                                                out.print(strTemp.substring(0, eindex));//추출한 문자열 출력
                                            }
                                        }
                                    }
                                %>
                                <% if(HttpSSOLogin.getSysAuth(request) != Moumi.SYSADM){ %>
                                    &nbsp;
                                <%}else{%>
                                    <img src="/totsys/common/images/folder.gif"><a href="#" onclick="onOk();" title="조직사용자갱신">조직사용자갱신</a>
                                <%}%>
                            </div>
                        </td>
                    </tr>
		</table>
            </div>
        </td>
    </tr>
</table>
</body>
