<%@ page contentType="text/html; charset=UTF-8"
	import="java.io.StringReader" import="java.util.*"
	import="java.util.regex.*"
	import="javax.swing.text.html.parser.ParserDelegator"
	import="java.net.URLEncoder" import="java.net.URLDecoder"
	import="kr.co.kihyun.lang.MLong" import="kr.co.kihyun.lang.MString"
	import="kr.co.kihyun.lang.Encoder"
	import="kr.co.kihyun.text.html.CallbackHandler"
	import="kr.co.kihyun.text.html.HtmlUtil"
	import="kr.co.kihyun.text.html.TagFilter"
	import="kr.co.kihyun.text.html.ServletUtil"
	import="kr.co.kihyun.moumi.Moumi"
	import="kr.co.kihyun.moumi.report.MReport"
	import="kr.co.kihyun.moumi.doc.MDoc"
	import="kr.co.kihyun.moumi.doc.table.MTable"
	import="kr.co.kihyun.moumi.doc.table.MTableAnalysis"
	import="kr.co.kihyun.moumi.doc.table.TableCreation"
	import="kr.co.kihyun.moumi.doc.table.TableDefine"
	import="kr.co.kihyun.moumi.doc.table.item.MItem"
	import="kr.co.kihyun.beans.totsys.doc.Doc"
	import="kr.co.kihyun.beans.totsys.doc.table.item.ItemList"
	import="kr.co.kihyun.beans.user.HttpSSOLogin"
	import="kr.co.kihyun.lang.MInteger"
	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"%>
<%@ include file="/totsys/common/inc/sec/secure.inc.jsp"%>
<%@ include file="/totsys/common/inc/documents/tot_doc/reload_expr.jsp"%>
<%
PersistenceManager pm = new MPersistenceManager(PMF.get().getPersistenceManager());
try{
	/********** parameter **********/	
	Long docID = MLong.parseLong(request.getParameter("docID"),null);

	/****** 서브 집계 문서인지 판단 ******/
	Doc doc = new Doc();
	String repDocID = doc.getRepID(docID);
	
	if(!MString.isNull(repDocID) && !repDocID.equals(docID)){
		String connURL="./doc_view.jsp?docID="+docID+"&strPage="+clearXSS(request.getParameter("strPage"),"")+"&findOption="+clearXSS(request.getParameter("findOption"),"")+"&findWord="+clearXSS(request.getParameter("findWord"),"");
		out.println(ServletUtil.alert(Moumi.getMessageBundle().getString("moumi.message.popup.subDocNotAuth")));
		out.println(ServletUtil.redirect(connURL));	
		return;
	}

	/********** doc values **********/
	TotDoc totDoc = pm.getObjectById(TotDoc.class, docID);
	String docForm = TagFilter.convertPAll(totDoc.getForm());
	TotTable totTable = totDoc.getTotTables().iterator().next();
	String tableTypes = totDoc.getTotTables().iterator().next().getTypes();
	int tableCount = HtmlUtil.getTableCount(docForm);

	session.setAttribute("docForm", docForm);
	
	ItemList itemList = new ItemList();
	itemList.executeQuery(docID);	
	int itemCount = itemList.getCount();
	String[] itemNameList = itemList.getNameList();
	String[] itemDescList = itemList.getDescList();
	int[] itemNumList = itemList.getNumList();
	int[] itemSizeList = itemList.getSizeList();
	int[] tableNumList = itemList.getTableNumList();
	int[] colNumList = itemList.getFieldNumList();
	int[] rowNumList = itemList.getRecordNumList();
	int[] itemBNWList = itemList.getBNWList();
	String[] itemTypeNameList = itemList.getTypeNameList();
	String[] itemExprList = itemList.getExprList();
	int[] itemTypeList = itemList.getTypeList();

	int tmp = MInteger.parseInt(request.getParameter("tmp"));
	String backDash = clearXSS(request.getParameter("backDash"),"");

	if(backDash.equals("back")){ //make by 구경모 #이전단계로 이동시 수식값 변환내용을 유지
		String itemExprs = clearXSS(URLDecoder.decode(request.getParameter("itemExprs"), "UTF-8"),"");
		String itemTypes = clearXSS(URLDecoder.decode(request.getParameter("itemTypes"), "UTF-8"),"");
		tableTypes = clearXSS(URLDecoder.decode(request.getParameter("tableTypes"), "UTF-8"),"");

		//step 1. 앞글자 0: 를 없앤다.
		itemExprs = itemExprs.substring(2,itemExprs.length()); 
		itemTypes = itemTypes.substring(2,itemTypes.length()); 

		//step 2. 번호: 를 없앤다. (step 1,2를 하는이유는 0: 과 100: 에서 0:가 공통으로 들어가는문제가 있기때문.)
		for(int i=0; i<itemCount; i++){
			itemExprs = itemExprs.replaceAll(MItem.LIST_DELIM+i+":",MItem.LIST_DELIM);
			itemTypes = itemTypes.replaceAll(MItem.LIST_DELIM+i+":",MItem.LIST_DELIM);
		}

		//step 3. 특수문자 MItem.LIST_DELIM 기준으로 배열에 넣는다. 이때, itemTypeNameList 배열을 사용한다는것에 주의.
		itemExprList = itemExprs.split(MItem.LIST_DELIM);
		itemTypeNameList = itemTypes.split(MItem.LIST_DELIM);

		//step 4. 마지막 수식적용한 번지~배열끝까지 사이가 모두 null일때 배열이 중간에 끊기는현상 보완
		String[] itemExprList_temp = itemExprList;
		itemExprList = new String[itemCount];
		for(int i=0; i<itemCount; i++){
			if(i<itemExprList_temp.length){
				itemExprList[i]=itemExprList_temp[i];
			}else{
				itemExprList[i]="";
			}
		}
	}

	StringBuffer dataBuf = new StringBuffer();
	for(int i=0; i < itemCount; i++){
		dataBuf.append("totForm.itemList["+i+"].expr='"+itemExprList[i].replaceAll("'","\\'")+"';\n\t\t\t");		
		dataBuf.append("totForm.itemList["+i+"].type = '"+itemTypeNameList[i]+"';\n\t\t\t");
		dataBuf.append("\n\t\t\t");		
		dataBuf.append("totForm.itemList["+i+"].itemName='"+itemNameList[i]+"';\n\t\t\t");
		dataBuf.append("totForm.itemList["+i+"].size='"+itemSizeList[i]+"';\n\t\t\t");
		dataBuf.append("totForm.itemList["+i+"].tableNum='"+tableNumList[i]+"';\n\t\t\t");
		dataBuf.append("totForm.itemList["+i+"].colNum='"+colNumList[i]+"';\n\t\t\t");
		dataBuf.append("totForm.itemList["+i+"].rowNum='"+rowNumList[i]+"';\n\t\t\t");
		dataBuf.append("totForm.itemList["+i+"].desc='"+itemDescList[i].replaceAll("'","\\'")+"';\n\t\t\t");
		dataBuf.append("\n");
	}
	TableDefine tableDefine = new TableDefine();
	docForm = tableDefine.insertDiv(docForm, itemNumList);
	String tableForm = MReport.getRemoveErrTable(docForm);
	tableForm = TagFilter.tdTextToSpace(tableForm);
	%>
<link rel="stylesheet" href="/totsys/common/css/text.css"
	type="text/css">
<script src="/totsys/common/js/formConfig.js"></script>
<script src="/totsys/common/js/drag.js"></script>
<script language='JavaScript'>
var totForm = new TotForm('totForm', <%= tableCount %>, <%= itemCount %>);				
var defItemSize = '<%= totTable.getItemSize() %>';

<%= dataBuf.toString() %>

//tableTypes 추가된것(동적,정적 선택)
<%
if(!MString.isNull(tableTypes)){
	String[] typeList=tableTypes.split(",");
	for(int k=0; k<typeList.length; k++){
%>
		totForm.tableList[<%=k+1%>].type=<%=typeList[k]%>;
<%
	}
}
%>

function setDform() {
	dform.itemNames.value = '';
	dform.itemSizes.value = '';
	dform.itemDescs.value = '';				
	dform.itemExprs.value = '';
	dform.itemTypes.value = '';
	dform.colNums.value = '';
	dform.rowNums.value = '';
	dform.tableNums.value = '';
	var item_count = 0;
	for (i=0;i<totForm.itemCount;i++){
		if(totForm.itemList[i].itemName != undefined){
			dform.itemNames.value  = dform.itemNames.value  + i + ':' + totForm.itemList[i].itemName + '<%= MItem.LIST_DELIM %>';
			dform.itemSizes.value  = dform.itemSizes.value  + i + ':' + totForm.itemList[i].size + '<%= MItem.LIST_DELIM %>';
			dform.itemDescs.value  = dform.itemDescs.value  + i + ':' + totForm.itemList[i].desc + '<%= MItem.LIST_DELIM %>';
			dform.itemExprs.value  = dform.itemExprs.value  + i + ':' + totForm.itemList[i].expr + '<%= MItem.LIST_DELIM %>';
			dform.itemTypes.value  = dform.itemTypes.value  + i + ':' + totForm.itemList[i].type + '<%= MItem.LIST_DELIM %>';
			dform.colNums.value    = dform.colNums.value    + i + ':' + totForm.itemList[i].colNum + '<%= MItem.LIST_DELIM %>';
			dform.rowNums.value    = dform.rowNums.value    + i + ':' + totForm.itemList[i].rowNum + '<%= MItem.LIST_DELIM %>';
			dform.tableNums.value  = dform.tableNums.value  + i + ':' + totForm.itemList[i].tableNum + '<%= MItem.LIST_DELIM %>';
			item_count ++;
		}
	}
	dform.tableDefines.value = '';
	for(i=0; i<<%= tableCount %>; i++){
		dform.tableDefines.value = dform.tableDefines.value + (i+1) +':rowdiv:rowdiv<%= MItem.LIST_DELIM %>';
	}
	var tableType = "";
	for(var i=1; i<= <%=tableCount%> && <%=tableCount%> > 0; i++){
		if(i != 1 )
			tableType+=",";
		tableType+=totForm.tableList[i].type;
	}
	dform.tableTypes.value = tableType;
	return item_count;
}

function preview() {
	if(!totForm.isValid()){
		alert('<%=Moumi.getMessageBundle().getString("moumi.message.popup.inputCellCheck")%>');
		return;
	}
	if(totForm.exprCheck()) return; //수식에 오류가 있다면 정지해라~~
	setDform();

	var farwindow = null;
	dform.submit();
}

function configStart(){
	for(i=0; i<totForm.itemCount; i++)
		totForm.reShowValue(i);
}

</script>
<body onload="configStart();scrollObjectContent('formDiv');">
<!--form name="dform" method="post" action="/totsys/common/web/documents/tot_doc/modify_inform_preview.jsp"-->
<form name="dform" method="post"
	action="<%if(HttpSSOLogin.getSysAuth(request) == Moumi.SYSADM){%>/totsys/sysadm/prssbox/doc_form_preview.jsp<%}else{%>/totsys/totper/mydocbox/formbox/doc_form_preview.jsp<%}%>">
<input type='hidden' name='docID' value='<%= docID %>'> <input
	type='hidden' name='docName' value='<%= totDoc.getName() %>'> <input
	type='hidden' name='docGroupID'
	value="<%= totDoc.getType().ordinal() %>"> <input type='hidden'
	name='tableCount' value="<%= tableCount %>"> <input
	type='hidden' name='itemNames'> <input type='hidden'
	name='itemSizes'> <input type='hidden' name='itemDescs'>
<input type='hidden' name='itemExprs'> <input type='hidden'
	name='itemTypes'> <input type='hidden' name='colNums'>
<input type='hidden' name='rowNums'> <input type='hidden'
	name='tableNums'> <input type="hidden" name="tableTypes">
<input type="hidden" name="backDash" value="back"> <input
	type='hidden' name='tableDefines'> <input type='hidden'
	name='mode' value='modify'> <input type="hidden"
	name="tmpDefItemSize"> <input type="hidden" name="defItemSize"
	value="3"></form>


<tr>
	<td valign="top">
	<table width="100%" border="0" cellspacing="0" cellpadding="0">
		<tr height="10">
			<td height="10"></td>
			<td></td>
			<td width="149"></td>
			<td width="331"></td>
		</tr>
		<!---- 양식 셀 정의 시작---->

		<tr>
			<td colspan="4">
			<table width="100%" border="0" cellspacing="0" cellpadding="0">
				<tr>
					<td valign="top">
					<div id="formDiv"
						style="padding-left: 10; padding-top:15; width: <%=session.getAttribute("formWidth") %>; overflow-x: auto;">
					<!-------------------------------------- 업로드한 표 보기 start -------------------------------------->
					<%= TableCreation.insertTypeButtons("totForm", docForm, tableTypes) %>
					<!--------------------------------------- 업로드한 표 보기 end --------------------------------------->
					</div>
					</td>
				</tr>
			</table>
			</td>
		</tr>
		<!---- 양식 셀 정의 끝 ---->
	</table>
	</td>
</tr>
<%if(HttpSSOLogin.getSysAuth(request) == Moumi.SYSADM || MString.checkNull(request.getParameter("type")).equals("formbox")){%>
<!---- 버튼(이전단계/다음단계) 시작 ---->
<%if(tmp == 1){%>
<%}else{%>
<tr>
	<td height="50" align="center">
	<table height="25" border="0" cellpadding="0" cellspacing="0">
		<tr>
			<!--td><a href="#" onMouseOut="MM_swapImgRestore()"
					onMouseOver="MM_swapImage('bt_pre','','/totsys/common/inc/documents/tot_doc/images/bt_pre.gif',1)"><img
					onclick="history.go(-2);"
					src="/totsys/common/inc/documents/tot_doc/images/bt_pre.gif"
					name="bt_pre" border="0"></a></td>
				<td width="5">&nbsp;</td-->
			<td><a href="#" onMouseOut="MM_swapImgRestore()"
				onMouseOver="MM_swapImage('bt_preview','','/totsys/common/inc/documents/tot_doc/images/bt_preview.gif',1)"><img
				onclick="preview();"
				src="/totsys/common/inc/documents/tot_doc/images/bt_preview.gif"
				name="bt_preview" border="0"></a></td>
		</tr>
	</table>
	</td>
</tr>
<%}%>
<%}%>
</body>
<%
}catch(Exception ex){ex.printStackTrace();
	out.println(kr.co.kihyun.text.html.ServletUtil.getJavaScript("location='/servlet/kr.co.kihyun.beans.user.HttpSSOLogin?mode=logout';"));
}finally{
    pm.close();
}
%>
