<%@page import="kr.co.kihyun.io.FileUtil"%>
<%@page import="java.util.ArrayList"%>
<%@page import="kr.co.kihyun.text.html.TagFilter"%>
<%            /**********************************************************************************
            프로그램명		: board_modify.jsp
            프로그램설명	: 집계문서에관한 공지 글 쓰기
            작 성 자			: 강 원 중
            작 성 일			: 2004. 06.07
            최신변경일		: 2005. 05.11
             ***********************************************************************************/
%>
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ page import="kr.co.kihyun.text.html.ServletUtil"%>
<%@ page import="kr.co.kihyun.beans.user.HttpSSOLogin"%>
<%@ page import="java.net.URLEncoder"%>
<%@ page import="kr.co.kihyun.moumi.Moumi"%>
<%@ page import="kr.co.kihyun.lang.Encoder"%>
<%@ page import="kr.co.kihyun.lang.MString"
         import="kr.co.kihyun.lang.MLong" import="javax.jdo.PersistenceManager"
         import="javax.jdo.Transaction"
         import="kr.co.kihyun.beans.entity.util.*"
         import="kr.co.kihyun.beans.entity.Board"%>
<%@ page import="java.util.Map.Entry"%>
<%@ page import="java.util.List"%>

<%@ include file="/totsys/common/inc/sec/secure.inc.jsp"%>

<%          PersistenceManager pm = new MPersistenceManager(PMF.get().getPersistenceManager());
            Transaction tx = pm.currentTransaction();
            try {
                /*********** User HttpSSOLogin check ***********/
                if (!HttpSSOLogin.isLogin(request)) {
                    String connURL = "opener.location='/totsys/login/login.jsp';";
                    out.println(ServletUtil.getJavaScript(connURL));
                    out.println(ServletUtil.getJavaScript("window.close();"));
                    return;
                }

                /********** session내의 userId **********/
                String usID = HttpSSOLogin.getLoginID(request);

                /****** Parameter ******/
                Long boardID = null;
                String strPage  = clearXSS(request.getParameter("strPage"), "");
                String findOption = clearXSS(request.getParameter("findOption"),null);
                String findWord = clearXSS(Encoder.toJava(request.getParameter("findWord")),null);
                boardID = MLong.parseLong(request.getParameter("boardID"), null);

                /*********** Board View vlaues ***********/
                Board board = null;
                String userID = "";
                String boardTitle = "";
                String boardContents = "";
                String usrFilenames = "";
                String svrFilenames = "";
                String boardGroupID = "";
                int fileCount = 0;

                tx.begin();

                board = boardID == null ? null : pm.getObjectById(Board.class, boardID);
                userID = board.getUser(pm) == null ? null : board.getUser(pm).getId();

                tx.rollback();

                boardTitle = TagFilter.unconvertedMeta(board.getTitle());
                boardContents = board.getContents();
                boardContents = TagFilter.unconvertedMeta(boardContents);
                String checkPopup = board.getPopupYn();
                /*
                for (Entry<String, List<Byte>> entry : board.getAttachments().entrySet()) {
                    usrFilenames += entry.getKey() + ";";
                    svrFilenames += entry.getKey() + ";";
                }
                fileCount = board.getAttachments().size();
                */
                //파일에서 로드
                ArrayList<String> fns= FileUtil.getBoardAttachmentsFileNames(board.getId(), request, false);
				for (String fn : fns) {
					usrFilenames += fn + ";";
					svrFilenames += fn + ";";
				}
				fileCount=fns.size();

                boardGroupID = board.getCategory().getId();
                String boardType = "";

                if ("ID_SYSTEM_NOTICE".equals(boardGroupID)) {
                    boardType = Moumi.getMessageBundle().getString("moumi.message.board.notice");
                } else if ("ID_FAQ".equals(boardGroupID)) {
                    boardType = Moumi.getMessageBundle().getString("moumi.message.board.faq");
                } else if ("ID_QNA".equals(boardGroupID)) {
                    boardType = Moumi.getMessageBundle().getString("moumi.message.board.qna");
                } else if ("ID_PDS".equals(boardGroupID)) {
                    boardType = Moumi.getMessageBundle().getString("moumi.message.board.pds");
                }

                /*********** append file name vlaues ***********/
                String[] usrFilenameList = usrFilenames.split(";");
                String[] svrFilenameList = svrFilenames.split(";");

                session.setAttribute("modifyTargetURI", "location.replace('/totsys/sysadm/board/board_view.jsp?boardID=" + boardID + "&boardUserID=" + userID + "')");
%>
<!DOCTYPE html>
<html lang="ko">
	<head>
		<meta charset="UTF-8">
		<title><%=Moumi.getTitle()%></title>
		<link rel="stylesheet" href="/totsys/common/css/contentStyle.css" type="text/css">
		<link rel="stylesheet" href="/totsys/common/css/basic.css" type="text/css">
        <link rel="stylesheet" href="/totsys/common/css/text.css" type="text/css">
        <link rel="stylesheet" href="/totsys/common/css/kecttep.css" type="text/css">
        <script src="/totsys/common/js/rollover.js"></script>
        <script src="/totsys/common/js/util.js"></script>
        <script src="/totsys/common/js/jquery-1.12.4.min.js"></script>
        <script src="/totsys/common/js/jquery.custom.indicator.js"></script>
        <script>
            <!--
            function checkUser(isManager){
                if(isManager == "false"){
                    alert("공지사항에 대한 쓰기 권한이 없습니다.");
                    window.close();
                }
            }
            if('<%=userID%>' != '<%=usID%>' && '<%=HttpSSOLogin.getSysAuth(request)%>'=='<%=Moumi.TOTPER%>'){
                alert("정상적인 방법으로 이용해주시기 바랍니다.");
                location.replace('/totsys/sysadm/board/board_list.jsp?boardGroupID=<%=boardGroupID%>')
            }

            num = <%= fileCount%>;
            usrFilenames = "<%= usrFilenames%>";
            svrFilenames = "<%= svrFilenames%>";
            fileInfos = "";
            userFilePath = "";

            /********** userfile list와 serverfile list를 배열로 저장 **********/
            function checkFile(Filename, Filename2){
                frm = document.multiUpload;
                mkFileList(Filename, Filename2, 'add');
                num++;
                frm.fileCount.value = num;
            }

            function mkFileList(Filename, Filename2, size, mode) {
                var tmpSvrFilenames = "";
                var tmpUsrFilenames = "";
                var tmpFileInfos = "";
                //var nList4 = "";

                if (!mode){
                    mode = "add";
                }

                subFilename = Filename;
                subFilename2 = cut_str( 1, Filename2, "/");
                subinfo = size;

                svrFilenameList = svrFilenames.split(";", num);
                usrFilenameList = usrFilenames.split(";", num);
                fileInfoList = fileInfos.split(";", num);

                if (mode == "add") {
                    if (svrFilenames && usrFilenames) {
                        for (i=0; i<num; i++) {
                            tmpSvrFilenames += svrFilenameList[i] + ";";
                            tmpUsrFilenames += usrFilenameList[i] + ";";
                            tmpFileInfos += fileInfoList[i] + ";";
                        }
                        tmpSvrFilenames += subFilename;
                        tmpUsrFilenames += subFilename2;
                        tmpFileInfos += subinfo;
                    } else {
                        tmpSvrFilenames = subFilename;
                        tmpUsrFilenames = subFilename2;
                        tmpFileInfos = subinfo;
                    }
                } else {
                    for (i=0; i<num; i++) {
                        if (subFilename == svrFilenameList[i])
                            continue;
                        else {
                            tmpSvrFilenames += svrFilenameList[i] + ";";
                            tmpUsrFilenames += usrFilenameList[i] + ";";
                            tmpFileInfos += fileInfoList[i] + ";";
                        }
                    }
                }

                svrFilenames = tmpSvrFilenames;
                usrFilenames = tmpUsrFilenames;
                fileInfos = tmpFileInfos;
            }

            function cut_str( state, value, separator ) {

                if (!separator){
                    separator = ".";
                }

                if ( state == 0 ){
                    return value.substring(0, value.lastIndexOf(separator));
                }

                if ( state == 1 ){
                    return value.substring(value.lastIndexOf(separator)+1, value.length );
                }
            }

            function delFrm() {

                var list = document.subUpload.delFrm.fileList;
                var a = list.options[list.selectedIndex].value;
                var no = -1;

                svrFilenameList = svrFilenames.split(";", num);
                usrFilenameList = usrFilenames.split(";", num);

                for(i=0; i<num; i++) {
                    if (a == svrFilenameList[i]) {
                        no = i;
                        mkFileList(svrFilenameList[i], usrFilenameList[i], 0,"delete");
                    }
                }

                if (no != -1) {
                    frm = document.multiUpload;

                    dname = "uForm_" + no;

                    if (num > 0){
                        num--;
                    }

                    frm2 = document.subUpload.delFrm;
                    frm2.submit();
                }
            }

            function checkForm(){
                var frm = document.multiUpload;
                //if (!num || !svrFilenames || !usrFilenames){
                //	alert ("첨부된 파일이 없습니다. 다시 시도해 주세요.");
                //} else {
                if (frm.title.value == "") {
                    alert("제목을 입력해 주세요.");
                    frm.title.focus();
                    return;
                }

                if(getByteSize(frm.title.value) > 200) {
                    alert("제목의 길이는 한글기준 66자 이내여야 합니다.");
                    frm.title.focus();
                    return;
                }

                if (frm.title.value.indexOf("\\") > -1) {
                    alert("제목에는 특수기호 역슬래시(\\) 문자를 사용할 수 없습니다.");
                    frm.title.focus();
                    return;
                }

                if(frm.contents.value == ""){
                    alert("내용을 입력해 주세요.");
                    frm.contents.focus();
                    return;
                }

                /*frm.fileCount.value = num;
                frm.svrFilenames.value = svrFilenames;
                frm.usrFilenames.value = usrFilenames;
                frm.fileInfos.value = fileInfos;*/

                $.customIndicator.show(window.self);
                frm.target = "hiddenFrame";
                frm.submit();
            }

            function checkPop(checkBox){
            	document.multiUpload.checkPopup.value = checkBox.checked ? "Y" : "N";
            }

            /*
            * 상세보기페이지로 이동처리하는 함수
            * @param {type} p_boardId
            * @returns {undefined}
            */
           function fn_goToView() {
               document.f_view.submit();
           }
            //-->
        </script>
    </head>

    <body>
<form name="f_view" method="post" action="./board_view.jsp">
    <input type="hidden" name="boardID" value="<%= boardID %>">
    <input type="hidden" name="strPage" value="<%= strPage %>">
    <input type="hidden" name="boardGroupID" value="<%= boardGroupID %>">
    <input type="hidden" name="findWord" value="<%= findWord %>">
    <input type="hidden" name="findOption" value="<%= findOption %>">
</form>
        <table>
            <jsp:include page="/totsys/common/inc/sysadm/top/top.jsp" flush="true" />
            <tr>
                <td></td>
                <td>
                    <table>
                        <jsp:include page="/totsys/common/inc/title/title.jsp" flush="true">
                            <jsp:param value='<%= URLEncoder.encode(boardType, "UTF-8")%>' name="title" />
                            <jsp:param value='<%= URLEncoder.encode(boardTitle, "UTF-8")%>' name="desc" />
                        </jsp:include>
                        <tr>
                            <td class="vTop">
                                <FORM name="multiUpload" action="/servlet/kr.co.kihyun.beans.totsys.board.HttpBoardModify" method="post">
                                    <INPUT type="hidden" name="userID" value="<%= userID%>">
                                    <INPUT type="hidden" name="boardGroupID" value="<%= boardGroupID%>">
                                    <INPUT type="hidden" name="fileCount" value="<%=MString.isNull(usrFilenameList[0]) == true ? 0 : svrFilenameList.length%>">
                                    <INPUT type="hidden" name="usrFilenames" value="<%= usrFilenames%>">
                                    <INPUT type="hidden" name="svrFilenames" value="<%= svrFilenames%>">
                                    <INPUT type="hidden" name="fileInfos">
                                    <input type="hidden" name="boardID" value="<%=boardID%>">
                                    <input type="hidden" name="callbackFunc" value="parent.fn_goToView()">
                                    <table class="kecttep_list_table">

                                        <!-- 제목 시작 -->
                                        <tr>
                                            <td class="kecttep_tdmenu_middle" style="padding-left:20px; width: 120px; height: 25px;">
                                                제목
                                            </td>
                                            <td class="kecttep_last_graytd" style="padding-left: 5px; text-align: center;">
                                                <input style="width: 99%" name="title" class=inputtxt value="<%= boardTitle%>" style="ime-mode: active;" />
                                            </td>
                                        </tr>
                                        <!-- 제목 끝 -->

                                        <!-- 내용 시작 -->
                                        <tr class="vTop">
                                            <td class="kecttep_tdmenu_middle" style="padding-top: 10px; padding-left:20px; width: 120px; height: 25px;">
                                                내용
                                            </td>
                                            <td class="kecttep_last_graytd">
                                                <textarea class="inputtxt" style="margin: 10px 10px 10px 10px; width: 99%; height: 320px; ime-mode: active" name="contents"><%= boardContents%></textarea>
                                            </td>
                                        </tr>
                                        <!-- 내용 끝 -->

                                        <!-- 파일첨부 -->
                                        <tr>
                                            <td class="kecttep_tdmenu_middle" style="padding-top: 10px; padding-left:20px; width: 120px; vertical-align: middle;">
                                                관련자료 첨부
                                            </td>
                                            <td class="kecttep_last_graytd vTop">
                                                <iframe src="/totsys/common/inc/board/doc/write_file_upload.jsp?boardGroupID=<%=boardGroupID%>&execMode=init&mode=sysadm&boardID=<%=boardID%>"
                                                    name='subUpload' width="100%" frameborder=0 height="70px"></iframe>
                                            </td>
                                        </tr>
                                        <!-- 파일첨부 끝 -->

                                        <!-- 팝업공지 체크 -->
                    <% if("ID_SYSTEM_NOTICE".equals(boardGroupID)) { %>
                                        <tr>
                                            <td class="kecttep_tdmenu" style="padding-left:20px; width: 120px; height: 25px;">
                                                팝업공지
                                            </td>
                                            <td class="kecttep_last_graytd_bottom tal" style="padding-left: 5px;">
                                                <label>
                                                    <input type="checkbox" id="checkPopup" name="checkPopup" onclick="checkPop(this);" <% if ("Y".equals(checkPopup)) {%> checked <% }%> >&nbsp;로그인시 팝업으로 공지함
                                                </label>
                                            </td>
                                        </tr>
                    <% } %>
                                        <!-- 팝업공지 체크 -->
                                    </table>
                                </FORM>
                            </td>
                        </tr>
                        <tr>
                            <td style="height: 10px;"></td>
                        </tr>
                        <tr>
                            <td>
                                <table>
                                    <!--  버튼 (확인, 취소) -->
                                    <tr>
                                        <td class="tac">
<!--                                            <a href="#" onclick="javascript:checkForm();"
                                                           onMouseOut="MM_swapImgRestore()"
                                                           onMouseOver="MM_swapImage('bt_enter','','./images/bt_enter.gif',1)"><img
                                                    name="bt_enter" border="0" src="./images/bt_enter.gif"></a>-->
                                            <a href="#" onclick="javascript:checkForm();" title="저장">
                                                <img name="bt_enter" border="0" src="/totsys/common/images/bt_save.gif" alt="저장" />
                                            </a>
<!--                                            <a
                                                href="./board_view.jsp?boardID=<%= boardID%>&strPage=<%= strPage%>&findOption=<%= findOption%>&findWord=<%= findWord%>"
                                                onMouseOut="MM_swapImgRestore()"
                                                onMouseOver="MM_swapImage('bt_cancel3.gif','','./images/bt_cancel3.gif',1)"><img
                                                    name="bt_cancel3.gif" border="0" src="./images/bt_cancel3.gif"></a>-->
                                            <a href="javascript:fn_goToView();" title="취소">
                                                <img class="ml_5" name="bt_cancel3.gif" src="/totsys/common/images/bt_cancle.gif" alt="취소" />
                                            </a>
                                        </td>
                                    </tr>
                                </table>
                            </td>
                        </tr>
                    </table>
                </td>
                <td style="width: 10px;">&nbsp;</td>
            </tr>
            <!-- top menu start -->
            <!--%@ include file="/totsys/common/inc/buttom/buttom.jsp"%-->
            <!-- top menu end -->
        </table>
        <iframe name='hiddenFrame' width=0 height=0 style='display:none;'></iframe>
    </BODY>
</HTML>

<%
            } catch (Exception ex) {
                //38.오류메세지를 통한 정보 노출(getMessage)_CWE-209 : Update by YOUNGJUN,CHO
                //out.println(ex);//앤개
                ex.printStackTrace();
                //out.println("<html><body style='overflow=auto' bgcolor='white'><h1>Can't contact servlet runner</h1><br><br>Message : " + ex.getMessage() + "</body></html>");
                //out.println("<META HTTP-EQUIV='refresh' CONTENT='0.1; URL=/error/exception.jsp'>");
                //================================================
            } finally {
                if (tx.isActive()) {
                    tx.rollback();
                }
                pm.close();
            }
%>
