<%@ page contentType="text/html; charset=UTF-8"
	import="java.net.URLEncoder"
	import="kr.co.kihyun.beans.user.HttpSSOLogin"
        import="java.util.*"
	import="java.net.URLDecoder"
        import="java.io.StringReader"
	import="javax.swing.text.html.parser.ParserDelegator"
	import="kr.co.kihyun.lang.MString"
        import="kr.co.kihyun.lang.MInteger"
	import="kr.co.kihyun.lang.Encoder"
        import="kr.co.kihyun.util.Stopwatch"
	import="kr.co.kihyun.text.html.HtmlUtil"
	import="kr.co.kihyun.text.excel.Excel"
	import="kr.co.kihyun.text.excel.CalculationForm"
	import="kr.co.kihyun.text.html.TagFilter"
	import="kr.co.kihyun.text.html.ServletUtil"
	import="kr.co.kihyun.text.html.CallbackHandler"
        import="kr.co.kihyun.moumi.MoumiConfig"
        autoFlush=""
        import="kr.co.kihyun.moumi.doc.MDoc"
	import="kr.co.kihyun.moumi.doc.table.MTable"
	import="kr.co.kihyun.moumi.doc.table.MTableType"
	import="kr.co.kihyun.moumi.doc.table.TableDefine"
	import="kr.co.kihyun.moumi.doc.table.TableCreation"
	import="kr.co.kihyun.moumi.doc.table.item.MItem"
	import="kr.co.kihyun.moumi.doc.table.item.MItemInfo"
	import="kr.co.kihyun.beans.totsys.doc.table.item.ItemList"%>
<%@ include file="/totsys/common/inc/sec/secure.inc.jsp"%>
<%@ include file="/totsys/common/inc/documents/tot_doc/reload_expr.jsp"%>
<%
	try {
		/********** parameter **********/
		request.setCharacterEncoding("UTF-8");
		String docName = URLDecoder.decode(MString.checkNull(request.getParameter("docName")), "UTF-8");
		String tableTypes = clearXSS(request.getParameter("tableTypes"), "");
		String itemExprs = clearXSS(URLDecoder.decode(MString.checkNull(request.getParameter("itemExprs")), "UTF-8"), "");
		String itemTypes = clearXSS(URLDecoder.decode(MString.checkNull(request.getParameter("itemTypes")), "UTF-8"), "");
		String backDash = clearXSS(URLDecoder.decode(MString.checkNull(request.getParameter("backDash")), "UTF-8"), "");
		String docForm = HtmlUtil.toLowerCase((String) session.getAttribute("docForm"));
		String tableForm = docForm;

		tableForm = tableForm.replaceAll("<p>&nbsp;", "");

		/********** 파싱 **********/
		//올린 파일을 String Reader를 이용해서 읽는다.
		CallbackHandler cbHandler = new CallbackHandler();

		new ParserDelegator().parse(new StringReader(MTable.getTables(docForm)), cbHandler, true);
		List<Hashtable<String, String>> tdList = cbHandler.getTDs();
		int tdCount = tdList.size();

		//표가 존재 하지 않을때..
		if (tdCount < 1) {
			out.println("<script language=javascript>\n");
			out.println("	alert('"+MoumiConfig.getMessageBundle().getString("moumi.message.popup.notTable")+"');\n");
			out.println("	document.location.replace('./doc_regist.jsp');\n");
			out.println("</script>");
			return;
		}

		//생성할 배열의 사이즈 계산
		int allRowCount = 0;
		int allColCount = 0;
		int rowCount = 0;
		int colCount = 0;
		for (int i = 0; i < tdCount; i++) {
			rowCount = Integer.parseInt(tdList.get(i).get("row"));
			colCount = Integer.parseInt(tdList.get(i).get("col"));
			if (allRowCount < rowCount)
				allRowCount = rowCount;
			if (allColCount < colCount)
				allColCount = colCount;
		}

		++allRowCount; //배열이라 0부터 시작 한다.
		++allColCount; //배열이라 0부터 시작 한다.

		//각각의 셀에 있는 Text 를 tdTextList 라는 배열에 저장한다.
		boolean isDynaTable = true;

		String tdName = "";
		String tableNumList = "";
		String tdText = "";
		String tdTextList[][] = new String[allRowCount][allColCount];
		StringBuffer itemValueListBuff = new StringBuffer();
		MTableType tableType = new MTableType(allRowCount); //table type value

		Long reuseDocID = ((Long) session.getAttribute("reuseDocID"));

		String[] itemNameList = null;
		String[] itemExprList = null;
		int[] itemTypeList = null;

		if (!MString.isNull(itemTypes) && !itemTypes.equals("")) {
			isDynaTable = !clearXSS(request.getParameter("isDynaTable"), "").equals("false");

			MItemInfo itemInfo = new MItemInfo();

			itemInfo.itemInfo(
                            clearXSS(URLDecoder.decode(MString.checkNull(request.getParameter("itemNames")), "UTF-8"), ""),
                            clearXSS(URLDecoder.decode(MString.checkNull(request.getParameter("itemSizes")), "UTF-8"), ""),
                            itemExprs, clearXSS(URLDecoder.decode(MString.checkNull(request.getParameter("itemDescs")), "UTF-8"), ""),
                            itemTypes, clearXSS(URLDecoder.decode(MString.checkNull(request.getParameter("tableNums")), "UTF-8"), ""),
                            clearXSS(URLDecoder.decode(MString.checkNull(request.getParameter("colNums")), "UTF-8"), ""),
                            clearXSS(URLDecoder.decode(MString.checkNull(request.getParameter("rowNums")), "UTF-8"), ""),
                            10
			);
			itemNameList = itemInfo.getItemNameList();
			itemExprList = itemInfo.getItemExprList();
			itemTypeList = itemInfo.getItemTypeList();

			int[] itemNumList = itemInfo.getItemNumList();
			int[] itemSizeList = itemInfo.getItemSizeList();
			String[] itemDescList = itemInfo.getItemDescList();
			int[] intTableNumList = itemInfo.getTableNumList();
			int[] rowNumList = itemInfo.getRowNumList();
			int[] colNumList = itemInfo.getColNumList();

			if (backDash.equals("back")) //make by 구경모 #이전단계로 이동시 수식값 변환내용을 유지
				itemExprs = reloadExpr(itemExprs, itemExprList,
						itemNameList);

			for (int i = 0; i < itemNameList.length; i++) {
				itemValueListBuff.append("totForm.itemList[" + i + "].itemName = '" + itemNameList[i] + "';\n");
				itemValueListBuff.append("totForm.itemList[" + i + "].size = '';\n");
				itemValueListBuff.append("totForm.itemList[" + i + "].tableNum = '" + Integer.toString(intTableNumList[i]) + "';\n");
				itemValueListBuff.append("totForm.itemList[" + i + "].rowNum = '" + rowNumList[i] + "';\n");
				itemValueListBuff.append("totForm.itemList[" + i + "].colNum = '" + colNumList[i] + "';\n");
				itemValueListBuff.append("totForm.itemList[" + i + "].desc = '" + itemDescList[i] + "';\n");
				itemValueListBuff.append("totForm.itemList[" + i + "].type = '" + getTypeName(itemTypeList[i]) + "';\n");
				itemValueListBuff.append("totForm.itemList[" + i + "].expr = '" + itemExprList[i] + "';\n");
			}
		} else {
			if (reuseDocID != null) {
				ItemList itemList = new ItemList();
				itemList.executeQuery(reuseDocID);
				itemTypeList = itemList.getTypeList();
				itemExprList = itemList.getExprList();
			} else {
				itemExprList = CalculationForm.getExprList(tableForm).toArray(new String[tdCount]);
			}

			for (int i = 0; i < tdCount; i++) {
				tdName = tdList.get(i).get("name");
				tableNumList = tdList.get(i).get("table");
				tdText = tdList.get(i).get("text");

				// 복사양식일때..
				// 어떤 이유에선지, 첫번째 셀이 "emptyempty" 형식으로 넘어오기 때문...
				int colNum = Integer.parseInt(tdList.get(i).get("col"));
				int rowNum = Integer.parseInt(tdList.get(i).get("row"));

				tdTextList[rowNum][colNum] = tdText;

				//Item정보를 저장할때 Excel과 같이 1부터 시작 하기 위해 1씩 추가
				++colNum;
				++rowNum;
				itemValueListBuff.append("totForm.itemList[" + i + "].itemName = '" + tdName + "';\n");
				itemValueListBuff.append("totForm.itemList[" + i + "].size = '';\n");
				itemValueListBuff.append("totForm.itemList[" + i + "].tableNum = '" + tableNumList + "';\n");
				itemValueListBuff.append("totForm.itemList[" + i + "].rowNum = '" + rowNum + "';\n");
				itemValueListBuff.append("totForm.itemList[" + i + "].colNum = '" + colNum + "';\n");

				//// 공백인것을 empty 문자로 바꾼다.
				if (tdText != null && tdText.trim().equals("")) {
					itemValueListBuff.append("totForm.itemList[" + i + "].desc = 'empty';\n");
					tableType.setStartTRNum(rowNum);
				} else if (tdText != null && !MString.isNull(itemExprList[i])) {
					itemValueListBuff.append("totForm.itemList[" + i + "].desc = 'empty';\n");
					tableType.setStartTRNum(rowNum);
					tableForm = TagFilter.deleteTdText(tableForm, i);
				} else {
					tdText = tdText.replaceAll("\'", "\"");
					if (tdText.indexOf("<") > 0
							|| tdText.indexOf("/>") > 0)
						itemValueListBuff.append("totForm.itemList[" + i + "].desc = 'empty';\n");
					else
						itemValueListBuff.append("totForm.itemList[" + i + "].desc = '" + tdText + "';\n");
				}

				itemValueListBuff
						.append("totForm.itemList[" + i + "].type = '"
								+ (reuseDocID == null ? MItem.getTypeName(MItem.INT) : MItem.getTypeName(itemTypeList[i]))
								+ "';\n");
				itemValueListBuff.append("totForm.itemList[" + i + "].expr = '"
						+ MString.checkNull(itemExprList[i]).replaceAll("'", "\\'") + "';\n");
			}

			//양식이 동적인 표인지 정적인 표인지 파악
			isDynaTable = tableType.isDynaTable();
		}
		/********** form 필터링 **********/
		int sumSusig = TagFilter.getSumSusig(tableForm);
		int comboBox = TagFilter.getComboBox(tableForm);

		if (!backDash.equals("back")) {//이전단계 돌아온것 아닐때만 실행함.
			if (sumSusig != -1)
				itemValueListBuff.append(CalculationForm.getCalculationForms("totForm.itemList", "expr", tableForm));
		}
		if (comboBox != -1)
			itemValueListBuff.append(TagFilter.excelComboBoxImport(tableForm));
		int tableCount = HtmlUtil.getTableCount(tableForm);

		tableForm = TagFilter.tdTextToSpace(tableForm);
		byte[] formBytes = docForm.getBytes();
		session.setAttribute("docForm", tableForm);
		TableDefine tableDefine = new TableDefine();
		String strTableInfo = tableDefine.insertDiv(tableForm, tdList, cbHandler.getTRCount());
%>

<script src="/totsys/common/js/rollover.js"></script>
<script src="/totsys/common/js/popup.js"></script>
<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%>, <%=tdList.size()%>);
	<%=itemValueListBuff.toString()%>
	<%if (!MString.isNull(tableTypes))
        {
                String[] typeList = tableTypes.split(",");
                for (int k = 0; k < typeList.length; k++)
          {%>
                totForm.tableList[<%=k+1%>].type=<%=typeList[k]%>;
	  <%}
	}%>

	//on load시 자동 실행
	//function exprSetup(){//itemExprList 변경
	if(<%=tableCount%> > 1){//itemExprList 변경
		var rowNum = 1;
		var addRowNum = 0; //첫번째 table의 더할 행의 수가 0부터 시작하기 때문
		for(var i=0; i < totForm.itemCount; i++){
			if(i > 0 && tableNumList[i] > tableNumList[i-1]) //다음 테이블로 넘어갔다면 현재 이전의 레코드 번호가 이전 테이블까지의 레코스 수임
					addRowNum = (rowNumList[i]-1);
			if(itemExprList[i].length > 0 && itemExprList[i].indexOf("^") < 0)	//숫자일때
				itemExprList[i] = getCalculationForm(itemExprList[i], addRowNum, "add");
		}
	}

	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 %>';
		}
		return item_count;
	}

	function preview(){
		totForm.correctCellTypes();
		item_count = setDform();

		if (item_count > 0) {
			var farwindow = null;
			//(url, target, width, height, align, valign, scroll, resize)
			farwindow = getOpener('', 'preview', 900, 600, 'center', 'middle', 'yes', 'yes');//window.open('','preview','width=800,height=600,left=0,top=0,status=no,scrollbars=yes,resizable=yes');
			dform.submit();
			farwindow.focus();
		} else {
			alert('<%=MoumiConfig.getMessageBundle().getString("moumi.message.popup.inputModifyCellCheck")%>');
		}
	}

	function nextStep(){
		totForm.correctCellTypes();
		item_count = setDform();

		if (item_count > 0)
			dform.submit();
		else
			alert('<%=MoumiConfig.getMessageBundle().getString("moumi.message.popup.inputModifyCellCheck")%>');
	}

	function beforeStep(){
		item_count = setDform();
		dform.docName.value="<%=docName%>";
		dform.submit();
	}
</script>
<script language='JavaScript'>
	function saveform() {
		dform.action = '/servlet/kr.co.kihyun.beans.totsys.doc.HttpDocRegister';
		dform.target = '_self';
		dform.submit();
	}

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

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

	function formSubmit(){
		if(!formValidation())
			return false;
		var tableType = "";
		for(var i=1; i<= <%=tableCount%> && <%=tableCount%> > 0; i++){
			if(i != 1 )
				tableType+=",";
			tableType+=totForm.tableList[i].type;
		}

		//dform.action = '/servlet/kr.co.kihyun.beans.totsys.doc.HttpDocRegister';
		dform.action = '/totsys/common/web/documents/tot_doc/inform_preview_form.jsp';
		dform.target = '_self';
		dform.tableTypes.value = tableType;

		nextStep();
	}

	function beforeSubmit(){
		if(totForm.exprCheck()) return; //수식에 오류가 있다면 정지해라~~
		//dform.action = '/servlet/kr.co.kihyun.beans.totsys.doc.HttpDocRegister';
		dform.action = '/totsys/totper/mydocbox/formbox/doc_regist.jsp';
		dform.target = '_self';
		beforeStep();
	}

	function checkFormSize(formBytes, deptCount){
		var maxSize = <%=MDoc.MAX_DOC_SIZE%>;
		if((formBytes * deptCount/1024/1024) > maxSize){
			alert('<%=MoumiConfig.getMessageBundle().getString("moumi.message.popup.warningCount")%>'+maxSize+'<%=MoumiConfig.getMessageBundle().getString("moumi.message.popup.warningCountSub")%><%=MoumiConfig.getMessageBundle().getString("moumi.message.popup.divideTable")%>');
		}
	}

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


	// DEBUG
	/*
	function test() {
		totForm.correctCellTypes();
	}
	*/
</script>
<body style=''
	onload="checkFormSize('<%=formBytes.length%>', '<%=clearXSS(request.getParameter("deptCount"), "")%>');configStart();scrollObjectContent('formDiv');">
<tr>
	<td height="31" 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" style="padding-top: 10; padding-bottom: 25;">
					<div id="formDiv"
						style="width: <%=session.getAttribute("formWidth") %>; overflow-x: auto;">
					<!-------------------------------------- 업로드한 표 보기 start -------------------------------------->
					<%=TableCreation.insertTypeButtons("totForm",
								strTableInfo, tableTypes)%> <!--------------------------------------- 업로드한 표 보기 end --------------------------------------->
					</div>
					</td>
				</tr>
			</table>
			</td>
		</tr>
		<!---- 양식 셀 정의 끝 ---->
	</table>
	</td>
</tr>

<!---- 버튼(미리보기/취소) 시작 ---->
<tr>
	<td align="center">
	<table height="25" border="0" cellpadding="0" cellspacing="0">
		<tr>
			<td><a href="#"><img onclick="beforeSubmit();"
				src="/totsys/common/inc/documents/tot_doc/images/bt_pre.gif"
				name="bt_pre" border="0"></a></td>
			<td>&nbsp;</td>
			<td><a href="#"><img onclick="formSubmit();"
				src="/totsys/common/inc/documents/tot_doc/images/bt_preview.gif"
				name="bt_next" border="0"></a></td>
		</tr>
	</table>
	</td>
</tr>
<form name="dform" method="post"
	action="/totsys/common/web/documents/tot_doc/popup_inform_preview.jsp"
	target="preview"><input type="hidden" name="docName"
	value='<%= URLEncoder.encode(docName, "UTF-8") %>'> <input
	type="hidden" name="stDate"
	value="<%=clearXSS(request.getParameter("stDate"), "")%>"> <input
	type="hidden" name="edDate"
	value="<%=clearXSS(request.getParameter("edDate"), "")%>"> <input
	type="hidden" name="deptIDs"
	value="<%=clearXSS(request.getParameter("deptIDs"), "")%>"> <input
	type="hidden" name="deptNames"
	value="<%=clearXSS(Encoder.toJava(MString.checkNull(request.getParameter("deptNames"))), "")%>">
<input type="hidden" name="userIDs"
	value='<%=clearXSS(URLDecoder.decode(MString.checkNull(request.getParameter("userIDs")), "UTF-8"), "")%>'>
<input type="hidden" name="userNames"
	value="<%=clearXSS(Encoder.toJava(MString.checkNull(request.getParameter("userNames"))), "")%>">
<input type="hidden" name="accAuth"
	value="<%=clearXSS(request.getParameter("accAuth"), "")%>"> <input
	type="hidden" name="repDocID"
	value="<%=clearXSS(request.getParameter("repDocID"), "")%>"> <input
	type="hidden" name="docGroupID"
	value="<%=clearXSS(request.getParameter("docGroupID"), "")%>">
<input type="hidden" name="isFromFormBox"
	value="<%=request.getParameter("isFromFormBox")%>"> <input
	type="hidden" name="tableCount" value="<%=tableCount%>"> <input
	type="hidden" name="isDynaTable" value="<%=isDynaTable%>"> <input
	type="hidden" name="mode" value="regist"> <input type="hidden"
	name="tableDefines"> <input type="hidden" name="itemNames">
<input type="hidden" name="tableNums"> <input type="hidden"
	name="colNums"> <input type="hidden" name="rowNums"> <input
	type="hidden" name="itemSizes"> <input type="hidden"
	name="itemDescs"> <input type="hidden" name="itemExprs">
<input type="hidden" name="itemTypes"> <input type="hidden"
	name="tableTypes"> <input type="hidden" name="backDash"
	value="back"> <input type="hidden" name="docForm"> <input
	type="hidden" name="tableType" value="0"> <input type="hidden"
	name="defItemSize" value="3"></form>
<%
	} 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 {
	}
%>
