<%@page import="org.apache.commons.lang.StringUtils"%>
<%@page import="java.sql.SQLException"%>
<%@page import="java.sql.ResultSet"%>
<%@page import="java.util.ArrayList"%>
<%@page import="kr.co.kihyun.db.CommonDBManager"%>
<%@ page contentType="text/html; charset=UTF-8"
	import="java.net.URLEncoder" import="kr.co.kihyun.lang.MString"
	import="kr.co.kihyun.lang.MLong"
	import="kr.co.kihyun.beans.entity.TotDoc"
	import="kr.co.kihyun.beans.user.HttpSSOLogin"
	import="kr.co.kihyun.text.html.TagFilter"
	import="kr.co.kihyun.lang.StringConverter"
	import="kr.co.kihyun.moumi.Moumi" import="kr.co.kihyun.lang.Encoder"
	import="org.apache.commons.lang.StringEscapeUtils"
	import="javax.jdo.PersistenceManager" import="javax.jdo.Transaction"
	import="kr.co.kihyun.beans.entity.util.*"
	import="kr.co.kihyun.beans.entity.TotDoc"
	import="kr.co.kihyun.beans.entity.TotTable"%>
<%@page import="kr.co.kihyun.beans.entity.TotDoc"%>
<%@page import="kr.co.kihyun.beans.entity.TotDocProcess"%>
<%@ include file="/totsys/common/inc/sec/secure.inc.jsp"%>
<%
PersistenceManager pm = new MPersistenceManager(PMF.get().getPersistenceManager());
Transaction tx = pm.currentTransaction();

try{
	/********** session내의 userId **********/
	String usID = HttpSSOLogin.getLoginID(request);
	int sysAuth = HttpSSOLogin.getSysAuth(request);
	/********** get Parameter *************/
	Long docID = MLong.parseLong(request.getParameter("docID"),null);
	String gubun = clearXSS(Encoder.toJava(request.getParameter("gubun")),"");

	//String docName = clearXSS(Encoder.toJava(request.getParameter("docName")),"");
	String strPage = clearXSS(request.getParameter("strPage"),"");
	String findOption = clearXSS(request.getParameter("findOption"),"");
	String findWord = clearXSS(Encoder.toJava(request.getParameter("findWord")),"");
	String url = "form";

	/*********** doc value *****************/
	String docForm = "";
	String docName = "";
	if(docID != null){
	TotDoc totDoc = pm.getObjectById(TotDoc.class, docID);
		docForm = totDoc.getForm();
		docForm = TagFilter.convertSingle(docForm);
		docForm = StringConverter.toOneLine(docForm);
		docName = totDoc.getName();
	}

	//수정불가능 인지
	//연계서식까지 같이 수정
	boolean isRep=false;
	boolean hasDone=false;
	CommonDBManager db=new CommonDBManager();
	ResultSet rs = null;
	String sql="select REP_ID from MOUMI_TOT_DOC where id=?";
	ArrayList<Long> docids=new ArrayList<Long>();
	docids.add(docID);
	try {
		rs = db.execQuery(sql, docID);
		if(rs.next()){
			String rep_id=rs.getString(1);
			if(rep_id!=null){
				isRep=true;
			}
		}
		rs.close();
		db.pstmt.close();


		sql="select ID from MOUMI_TOT_DOC where REP_ID=?";
		rs= db.execQuery(sql, docID);
		while (rs.next()) {
			Long did=rs.getLong(1);
			if(!docids.contains(did))docids.add(did);
		}
		rs.close();
		db.pstmt.close();

		sql="select * from MOUMI_TOT_report where doc_id in(seqs) and prss in(5,6) and del_type = 'N'";
		String txtids=StringUtils.join(docids.toArray(),",");
		sql=sql.replace("seqs", txtids);
		rs= db.execQuery(sql);
		if(rs.next()){
			hasDone=true;
		}
		rs.close();
		db.pstmt.close();
	} catch (SQLException e1) {
		// TODO Auto-generated catch block
		e1.printStackTrace();
	} finally{
		rs.close();
		db.execClose();
	}
%>

<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title><%=Moumi.getTitle()%></title>
<%--
<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>
<link rel="stylesheet" href="/totsys/common/css/tabs.css" type="text/css">
<link rel="stylesheet" href="/totsys/common/css/SquareButtons.css" type="text/css">
--%>
<link rel="stylesheet" href="/totsys/common/css/basic.css" type="text/css">
<link rel="stylesheet" href="/totsys/common/css/contentStyle.css" type="text/css">
<script defer="defer" src="/totsys/common/js/util.js"></script>
<script src="/totsys/common/js/jquery-1.12.4.min.js"></script>
<script src="/lib/js/tiny_mce/tiny_mce.js"></script>
<script src="/totsys/common/js/jquery.cookie.js"></script>
<script>
		// General options
		tinyMCE.init({
		mode : "exact",
		elements : "EditCtrl",
		theme : "advanced",
		plugins : "table",
		language: "ko",
		extended_valid_elements : "td[abbr|align<center?char?justify?left?right|axis|bgcolor|char|charoff|class"
												+"|colspan|dir<ltr?rtl|headers|height|id|lang|nowrap<nowrap|onclick"
												+"|ondblclick|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove"
												+"|onmouseout|onmouseover|onmouseup|rowspan|scope<col?colgroup?row?rowgroup"
												+"|style|title|valign<baseline?bottom?middle?top|width"
												+"|*]",
		setup : function(ed) {
		 //html 인코딩된 주석제거,포커스 문제 해결,클릭시 커서 안잡히는거해결
		 	ed.onLoadContent.add(function(ed,e){
		 		initEditCtrl();
		 	});
		 	ed.onChange.add(function(ed,e){
		 		initEditCtrl();
		 	});
			ed.onPaste.add(function(ed,e){
                try{
                   setTimeout(function(){
               	   	initEditCtrl();
               	   	var comment = /<!--[^>](.*?)-->/g; //주석제거
                    var html=tinyMCE.getInstanceById('EditCtrl').getContent();
                   // if(html.search(comment)>-1){
                   // 	html = html.replace(comment,'');
                   // }
                    tinyMCE.getInstanceById('EditCtrl').setContent(html+'<br/>');
                    $($('#EditCtrl_ifr')[0].contentWindow.document.body).find('span').each(function(){
                    	var txt=$(this).text();
                    	if(txt==''||txt==' '){
                        	$(this).html('&nbsp;');
                    	}
                    });
                    var range=$('#EditCtrl_ifr')[0].contentWindow.document.body.createTextRange();
	               	 range.collapse(false);
	               	 range.select();
                   },0);
                }catch(e){}
			});
	        ed.makeReadOnly = function(ro) {
	            var t = this, s = t.settings, DOM = tinymce.DOM, d = t.getDoc();

	            if(!s.readonly && ro) {
	                if (!tinymce.isIE) {
	                    try {
	                        d.designMode = 'Off';
	                    } catch (ex) {
	                        alert(ex);
	                    }
	                } else {
	                    b = t.getBody();
	                    DOM.hide(b);
	                    b.contentEditable = false;
	                    DOM.show(b);
	                }
	                s.readonly = true;
	            } else if(s.readonly && !ro) {
	                if (!tinymce.isIE) {
	                    try {
	                        d.designMode = 'On';
	                        // Design mode must be set here once again to fix a bug where
	                        // Ctrl+A/Delete/Backspace didn't work if the editor was added using mceAddControl then removed then added again
	                        d.designMode = 'Off';
	                        d.designMode = 'On';

	                    } catch (ex) {
	                        alert(ex);
	                    }
	                } else {
	                    b = t.getBody();
	                    DOM.hide(b);
	                    b.contentEditable = true;
	                    DOM.show(b);
	                }
	                s.readonly = false;
	            }
	        };
	    },
/*
		forced_root_block : false,
		force_br_newlines: true,
		force_p_newlines: false,

		theme_advanced_buttons1 : "bold,italic,underline,|,justifyleft,justifycenter,justifyright,justifyfull,|,fontselect,fontsizeselect",
		theme_advanced_buttons2 : "",
		theme_advanced_buttons3 : "",
		theme_advanced_toolbar_location : "top",
		theme_advanced_toolbar_align : "left",
		theme_advanced_fonts : "굴림=굴림;굴림체=굴림체;궁서=궁서;궁서체=궁서체;돋움=돋움;돋움체=돋움체;바탕=바탕;바탕체=바탕체;"
*/
                theme_advanced_buttons1 : ""
		//theme_advanced_buttons2 : "",
		//theme_advanced_buttons3 : "",
		//theme_advanced_toolbar_location : "top",
		//theme_advanced_toolbar_align : "left"
		//theme_advanced_fonts : "굴림=굴림;굴림체=굴림체;궁서=궁서;궁서체=궁서체;돋움=돋움;돋움체=돋움체;바탕=바탕;바탕체=바탕체;"
                });
		function initEditCtrl(){
			$($('#EditCtrl_ifr')[0].contentWindow.document.body).find('span').each(function(){
            	var txt=$(this).text();
            	if(txt==''||txt==' '){
                	$(this).html('&nbsp;');
            	}
            });
			$($('#EditCtrl_ifr')[0].contentWindow.document.body).find('> table').attr({'border':'1','bo':'true'})
				.find('td').each(function(i,o){
					if($(o).closest('table').attr('bo')=='true'){
						$(this).css('border','1px solid #000');
					}
	      		});
			//수정불가문서
			if('<%=isRep%>'=='true'||'<%=hasDone%>'=='true'){
				parent.isDisabled=true;
				docFormCM.docFCM.value = $('#EditCtrl').val();
				docFormCM.submit();
			}
		}
	</script>
<script>
		function docFormContentModify(){
			docFormCM.docFCM.value = tinyMCE.getInstanceById('EditCtrl').getContent();

			if(docFormCM.docFCM.value == ''){
				alert('<%=Moumi.getMessageBundle().getString("moumi.message.popup.notModifyData")%>');
				return;
			}else{
				docFormCM.submit();
				//window.close();
			}
		}
	</script>

<script>
		function docDel(){
			var frm = document.Del;
			if(confirm('<%=Moumi.getMessageBundle().getString("moumi.message.popup.formDelete")%>')){
				frm.submit();
			}
		}

		function formView(){
			location.href="/totsys/totper/mydocbox/formbox/doc_view.jsp?docID=<%=docID%>&strPage=<%=strPage%>&findOption=<%=findOption%>&findWord=<%=findWord%>";
		}

		function reg_use(){
			if(confirm('<%=Moumi.getMessageBundle().getString("moumi.message.popup.reuse")%>'))
				location.href="/totsys/totper/mydocbox/regbox/doc_regist.jsp?reuseDocID=<%=docID%>&reuseDocName=<%=docName%>&isFromFormBox=true";
		}

		function propertiesUpdate(){
			location.href="/totsys/totper/mydocbox/formbox/doc_form_modify.jsp?docID=<%=docID%>&strPage=<%=strPage%>&findOption=<%=findOption%>&findWord=<%=findWord%>";
		}
		function docChangeStructure(){
			var imgsrc=$('#bt_changestructure').attr('src');
			if(imgsrc.indexOf('bt_changestructure')>-1){
				if(!confirm('편집창을 비웁니다.\r\n\r\n계속하시겠습니까?'))return;
				imgsrc=imgsrc.replace('bt_changestructure','bt_restoresturecture');
				tinyMCE.getInstanceById('EditCtrl').setContent('');
				docFormCM.changeStructure.value='true';
			}else{
				if(!confirm('수정중인 서식이 원본서식으로 복원됩니다.\r\n\r\n계속하시겠습니까?'))return;
				imgsrc=imgsrc.replace('bt_restoresturecture','bt_changestructure');
				var html=$('#originalform').html();
				tinyMCE.getInstanceById('EditCtrl').setContent(html);
				docFormCM.changeStructure.value='false';
			}
			$('#bt_changestructure').attr('src',imgsrc);
			initEditCtrl();
		}
        function docFormContentModify2(){
        	//다음단계 이전 수정가능한지 체크
        	if('<%=isRep%>'=='true'){
				alert('연계문서는 수정할 수 없습니다.');
				return;
			}
        	if('<%=hasDone%>'=='true'){
				alert('집계자료의 서식을 수정할 수 없습니다. 제출자료 및 연계자료 중 결재대기중, 결재완료 상태인 제출자료가 있습니다.');
				return;
			}
            docFormCM.docFCM.value = tinyMCE.getInstanceById('EditCtrl').getContent();

            //테스트용
            //docFormCM.target='_blank';

            /*if(docFormCM.docFCM.value == ''){
                    alert('변경할 문서가 없습니다.\\n 다시 확인하시고 변경하여 주십시요.');
                    return;
            }else{
                    docFormCM.submit();
                    //window.close();
            }
            */
			//테이블 없을시 멈춤
            if(docFormCM.docFCM.value == ''||docFormCM.docFCM.value.toLowerCase().indexOf('<table')==-1){
                alert('변경할 문서가 없습니다.\n 다시 확인하시고 변경하여 주십시요.');
                return;
            }

            //++++++++++++++++++++++++++++++++++++++++ Begin +++++++++++++++++++++++++++++++++++++++++++
            // 문서생성시 셀내에 내용이 긴 경우(500 byte가 초과하는 경우)에 저장시 에러가 발생한다.
            // 에러 원인을 사용자에게 노티하기 위해 셀 내의 내용의 길이를 체크하도록 추가함. Add by YOUNGJUN,CHO 2014.12.03

            // 파일집계가 아닌 경우에 체크.
            if (parent.dform.appendType.value != "FILE") {

                // moumi_tot_item 'des' 의 length 제한에 유효한지 여부.(true:유효함(이하), false:유효하지않음(초과))
                var isAvailDes = true;

                // moumi_tot_item 'des' 의 length.
                var totItemDesMaxLength = 2000;  // 테이블의 컬럼 길이를 수정하는 경우 변경필요.
                var desByteSize = 0;            // 오버플로우된 내용의 byte size. (알림용)
                var desText;                   // 오버플로우된 내용의 text. (알림용)

                // 에디터에 작성된 html 을 pastedHtml 변수에 저장.
                //alert(EditCtrl.document.body.innerHTML);
                var pastedHtml = docFormCM.docFCM.value;

                // 모든 td 태그를 탐색.
                $.each( $(pastedHtml).find("td"), function(index) {

                    // td 태그내 html tag 를 제외한 text 의 byte size 를 계산.(한글 3 byte)
                    desByteSize = getByteSize($(this).text());

                    // 입력된 내용의 byte size 가 테이블 컬럼의 길이를 초과하는 경우, 유효하지 않은 des 가 있는 것임. (isAvailDes = false 으로 세팅.)
                    if ( desByteSize > totItemDesMaxLength ) {
                        isAvailDes = false;

                        //alert($(EditCtrl.document.body).find("td:eq("+index+")").html());

                        // 에디터 영역의 td 태그에 input, textarea 처럼 focus 또는 select 이벤트를 발생시킬 수 없다.
                        //$(EditCtrl.document.body).find("td:eq("+index+")").select();

                        // 오버플로우되는 내용을 desText 변수에 저장. (알림용)
                        desText = $(pastedHtml).find("td:eq("+index+")").text();

                        // 알림용 desText 의 텍스트 길이가 긴 경우 생략처리. (임의로 100글자까지로 정함)
                        if (desText.length > 100) {
                            desText = desText.substring(0, 100) + "\n\r..생략..";
                        }

                        return false;   // for문의 break와 동일.
                    }
                });

                // 오버플로우가 발생된 경우, alert 으로 문제원인과 안내 메세지를 출력하고 return 으로 submit 되지 않게 함.
                if (isAvailDes === false) {
                    alert("셀안의 내용이 너무 깁니다. (입력된 내용 : " + desByteSize + " byte)"
                        + "\n\r하나의 셀에는 최대 " + totItemDesMaxLength + " byte 까지의 데이터만 입력가능 합니다."
                        + "\n\n한글기준 166자, 영문/숫자 " + totItemDesMaxLength + "자 이내로 입력해주세요."
                        + "\r\r**************** 셀 내용 일부 ****************"
                        + "\n\r" + desText);
                    return;
                }
            }

            // 이전단계 기능을 위해...
			docFormCM.target='nextifr';
			parent.$('[name=subUpload]').hide();
			parent.$('[name=nextifr]').show();

            docFormCM.submit();
        }
	</script>
</head>
<body style='' bgcolor="#FFFFFF" text="#000000" leftmargin="0"
	topmargin="0" marginwidth="0" marginheight="0">
<div>
<table>

</table>
</div>

<div id="header">
<ul id="primary">
	<!--<li><a href="#" onclick="formView();"><%=TotDocProcess.FORM%><%=Moumi.getMessageBundle().getString("moumi.message.tot_doc.info")%></a></li>-->
	<!--<li><span class="kecttep_menu_focous"><%=TotDocProcess.FORM%><%=Moumi.getMessageBundle().getString("moumi.message.tot_doc.modify")%></span></li>-->
	<!--<li><a href="#" onclick="propertiesUpdate();"><%=Moumi.getMessageBundle().getString("moumi.message.tot_doc.value")%><%=Moumi.getMessageBundle().getString("moumi.message.tot_doc.modify")%></a></li>-->
</ul>
</div>


<div id="main">
<div id="contents">
<table>
<!--
	<tr>
		<td height="10"></td>
	</tr>
-->
	<tr class="center">
		<td style="width: 100%;">
		<table class="llist1">
			<tr class="bgw1">
				<td colspan=3>
				<table>
					<tr>
						<td><textarea id="EditCtrl"
							style="width: 100%;height: 500px;">
						<%if(docID != null){
                                                        //v2. 14.디렉토리 경로 조작(getParameter)_CWE-22/23 : 오탐
							out.write(StringEscapeUtils.escapeHtml(docForm));
															}
						%>
						</textarea>
						<div id="originalform" style="display: none;"><%=docForm%></div>
						</td>
					</tr>
				</table>
				</td>
			</tr>
		</table>
		<br>

		<table>
			<tr>
				<td>
				<span>
                    <a href="#" onclick="javascript:docChangeStructure();"><img src="/totsys/common/images/bt_changestructure.jpg" name="bt_changestructure" border="0" id="bt_changestructure" alt="구조변경" /></a>
                </span>
                <span>
					<a href="#" onclick="javascript:docFormContentModify2();">
                        <img src="/totsys/common/images/bt_nextb.gif" name="bt_enter1" border="0" id="bt_enter1" alt="다음단계" />
                    </a>
                </span>
                </td>
			</tr>
		</table>
		</td>
	</tr>
</table>
</div>
</div>
<!--<form name="docFormCM" action="/servlet/kr.co.kihyun.beans.totsys.doc.HttpFormContentModify" method="post">-->
<form name="docFormCM"
	action="/servlet/kr.co.kihyun.beans.totsys.doc.HttpReFormReader2"
	method="post" encType="multipart/form-data">
		<!-- 구조변경 파라미터 -->
        <input type="hidden" name="changeStructure" value="false">
        <input type="hidden" name="docFCM">
        <input type="hidden" name="docID" value="<%= docID %>">
        <input type="hidden" name="isAdmin" value="form">
</form>
<FORM name="Del"
	action="/servlet/kr.co.kihyun.beans.totsys.doc.HttpDocDeleter"
	method="post"><INPUT type="hidden" name="docID"
	value="<%= docID %>"> <INPUT type="hidden" name="userID"
	value="<%= usID %>"> <INPUT type="hidden" name="url"
	value="<%= url %>"></FORM>
</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();
	}
%>
