/*************************************************************************************************
 * 프로그램명 : InsertMTable.java 프로그램설명 : 집계 문서의 입력 양식을 작성해줌 작성자 : 강원중 작성일 : 2003.12.03 변경일 : 2004.09.16
 **************************************************************************************************/
package kr.co.kihyun.moumi.doc.table;

import java.util.StringTokenizer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import kr.co.kihyun.beans.totsys.doc.table.item.ItemList;
import kr.co.kihyun.moumi.MoumiConfig;
import kr.co.kihyun.lang.MString;
import kr.co.kihyun.moumi.doc.table.item.MItem;
import kr.co.kihyun.moumi.report.MReport;

public class InsertMTable {

	private static final Logger LOG = LoggerFactory.getLogger(InsertMTable.class);

	private String form = "";
	private String inputForm = "";
	private StringBuilder putValStrBuf = new StringBuilder();
	private StringBuilder changeAllStrBuf = new StringBuilder();

	public void convert(String form, ItemList itemList, int defItemSize) {
		convert(form, itemList.getNumList(), itemList.getNameList(), itemList.getSizeList(), itemList.getExprList(),
				itemList.getTypeList(), itemList.getDescList(), defItemSize);
	}

	@Deprecated
	public void convert(String form, int[] itemNumList, String[] itemNameList, int[] itemSizeList,
			String[] itemExprList, int[] itemTypeList, String[] itemDescList, String defItemSize) {
		convert(form, itemNumList, itemNameList, itemSizeList, itemExprList, itemTypeList, itemDescList,
				Integer.parseInt(defItemSize));
	}

	public void convert(String form, int[] itemNumList, String[] itemNameList, int[] itemSizeList,
			String[] itemExprList, int[] itemTypeList, String[] itemDescList, int defItemSize) {

		this.form = form;

		int itemCount = itemNumList.length;

		String[] itemInputList = new String[itemCount];
		String[] itemOnChangeList = new String[itemCount];
		String[] itemOnFocusList = new String[itemCount];
		String[] itemErrorList = new String[itemCount];
		String itemName = "";
		String itemExpr = "";

		int itemType = 0;
		int itemSize = 0;

		String tmpItemDesc = "";

		StringTokenizer tkItemExpr = null;
		StringBuilder selectBuf = null;
		String value = null;
		StringTokenizer is = null;



		for (int i = 0; i < itemCount; i++) {
			itemName = itemNameList[i].trim();
			itemExpr = itemExprList[i].trim();
			itemType = itemTypeList[i];
			itemSize = itemSizeList[i];
			tmpItemDesc = itemDescList[i].trim();

			LOG.debug("itemName: {}, itemExpr: {}, itemType: {}, itemSize: {}, tmpItemDesc: {}",
					new Object[] {itemName, itemExpr, itemType, itemSize, tmpItemDesc});

			try {
				tmpItemDesc = tmpItemDesc.substring(tmpItemDesc.indexOf(":") + 1, tmpItemDesc.length());
			} catch (Exception e) {
                                //18.시스템 데이터 정보노출 : Update by YOUNGJUN,CHO
				//System.err.println(e);
                                e.printStackTrace();
                                //================================================
			}

			// select 문으로 바뀌는 경우
			if (itemExpr != null && itemExpr.indexOf("^") >= 0)
            {

 				tkItemExpr = new StringTokenizer(itemExpr, "^");
				selectBuf = new StringBuilder();
				selectBuf.append("<center><select name='");
				selectBuf.append(itemName);
				selectBuf.append("' style='width:100%;' $VALUE $ON_FOCUS>");
				for (int j = 0; tkItemExpr.hasMoreTokens(); j++) {
                              		value = tkItemExpr.nextToken();
					selectBuf.append("<option value='");
					selectBuf.append(value);
					selectBuf.append("'>");
					selectBuf.append(value);
					selectBuf.append("</option>");
				}
				selectBuf.append("</select></center>");
				itemInputList[i] = selectBuf.toString();
			}
            else if (itemExpr != null && itemExpr.indexOf("~") > 0)
            {

				// textarea로 바뀌는 경우
				is = new StringTokenizer(itemExpr, "~");
				if (is.countTokens() != 2) {
					itemErrorList[i] += ":" + itemSize + MoumiConfig.getMessageBundle().getString("moumi.message.tot_doc.sizeError");
				} else {
					// 계산버튼(관련)
					itemInputList[i] = "<textarea name='" + itemName + "' cols='" + is.nextToken() + "' rows='"
							+ is.nextToken() + "' $ON_FOCUS style='border: 1 solid #7B84D6;width:100%;height:100%;'></textarea>";
				}
			}
            else
            {// 일반적인 경우
        		//ie10,11 호환성 수정 - 텍스트박스 배경색 적용되게
				if (itemSize == 0)
					itemSize = defItemSize;

				if (itemType == MItem.CHAR) {// 문자
					itemInputList[i] = "<input type='text' name='" + itemName
							+ "' $ON_FOCUS onBlur='checkNum(this, \"" + itemType + "\");' "
							+ " style='background-color: #F5FDFD;width:100%;'" + " itemType='" + itemType + "' >";
				} else if (itemType == MItem.INT) {// 숫자
					itemInputList[i] = "<input type='text' name='" + itemName
							+ "' $ON_FOCUS onclick='this.focus();this.select();'  "
							+ " style='background-color: #F5FDFD;width:100%;' value=0  onBlur='checkNum(this, \"" + itemType
							+ "\");' " + " itemType='" + itemType + "' >";
				} else if (itemType == MItem.DATE) {// 날짜
					itemInputList[i] = "<a onclick=\"showSetWin('dform."
							+ itemName
							+ "');\" ><img style='cursor:hand;' src='/totsys/common/inc/documents/tot_doc/images/date.gif'></a><input type='text' name='"
							+ itemName + "' $ON_FOCUS onclick=\"showSetWin('dform." + itemName
							+ "');\" onBlur='checkNum(this, \"" + itemType + "\");' " + " itemType='" + itemType + "' readonly >";
				}
				if ("empty".equals(tmpItemDesc)) {
					if (itemType == MItem.CHAR) {// 문자
						itemInputList[i] = "<input type='text' name='" + itemName
								+ "' $ON_FOCUS onBlur='checkNum(this, \"" + itemType + "\");' "
								+ " style='background-color: #F5FDFD;width:100%;'" + " itemType='" + itemType + "' >";
					} else if (itemType == MItem.INT) {// 숫자
						itemInputList[i] = "<input type='text' name='" + itemName
								+ "' $ON_FOCUS onclick='this.focus();this.select();'  "
								+ " style='background-color: #F5FDFD;width:100%;' value=0  onBlur='checkNum(this, \"" + itemType
								+ "\");' " + " itemType='" + itemType + "' >";
					} else if (itemType == MItem.DATE) {// 날짜
						itemInputList[i] = "<a onclick=\"showSetWin('dform."
								+ itemName
								+ "');\"><img style='cursor:hand;' src='/totsys/common/inc/documents/tot_doc/images/date.gif'></a><input type='text' name='"
								+ itemName + "' $ON_FOCUS onclick=\"showSetWin('dform." + itemName
								+ "');\" onBlur='checkNum(this, \"" + itemType + "\");' " + " itemType='" + itemType + "' readonly >";
					}
				} else {
					itemInputList[i] = "";
				}
			}
		}// ///for end
		buildExprHandlerScript(itemNameList, itemExprList, itemCount, itemOnChangeList, itemOnFocusList);


		// onchange, onfocus event 처리 부분
		for (int i = 0; i < itemCount; i++) {
			if (MString.checkNull(itemOnFocusList[i]).length() > 0)
            {
				itemInputList[i] = MString.replaceAll(itemInputList[i], "$ON_FOCUS", itemOnFocusList[i]);
			}
            else
            {
				itemInputList[i] = MString.replaceAll(itemInputList[i], "$ON_FOCUS", "");
			}

			if (MString.checkNull(itemOnChangeList[i]).length() > 0)
            {
				itemInputList[i] = MString.replaceAll(itemInputList[i], "$ON_CHANGE", "onchange='"	+ itemOnChangeList[i] + "'");
			}
            else
            {
				itemInputList[i] = MString.replaceAll(itemInputList[i], "$ON_CHANGE", "");
			}
		}
		// ban lower case this.form = form.toLowerCase().replaceAll("width","hh");

		this.form = form.replaceAll("width", "hh");

		this.inputForm = getInputForm(form, itemInputList, itemNumList);

	}

	private void buildExprHandlerScript(String[] itemNameList, String[] itemExprList, int itemCount,
			String[] itemOnChangeList, String[] itemOnFocusList) {
		String itemName;
		String itemExpr;
		// 수식처리 부분
		String itmExpr = "";
		String sumSpc = "";// // 최종 결과물
		StringTokenizer tmp10 = null;
		String tmpStart = "";
		String tmpEnd = "";
		String startTail = "";
		int startTailInt = 0;
		char startCh = 0;
		String startCharacter = "";

		char endCh = 0;
		String sumType = "";
		int startTailResult = 0;
		String pEnd = "";
		String exprToken = "";
		StringTokenizer stk99 = null;
		StringTokenizer stkExpr = null;

        for(int ii=0;ii<itemCount;ii++)
        {
            itemExprList[ii]=itemExprList[ii].toUpperCase();
            String tmp=MString.replaceAll(itemExprList[ii],"="," ");
            itemExprList[ii]=tmp.trim();
        }

		for (int i = 0; i < itemCount; i++) {
			itemExpr = itemExprList[i].toUpperCase();
			itemName = itemNameList[i];
			itmExpr = itemExpr;

//System.out.println("********************************************************************** "+itemExpr);
//System.out.println("********************************************************************** "+itemName);
//System.out.println("********************************************************************** "+itmExpr);

			if (!"".equals(MString.checkNull(itemExpr)) && itemExpr.indexOf("^") < 0 && itemExpr.indexOf("~") < 0) {
				// if(!MString.isNull(itemExpr)){

				sumSpc = "";// // 최종 결과물
				if (itemExpr.indexOf(":") > 0) {// // SUM(A1:F1) 일경우
					itemExpr = MString.replaceAll(itemExpr, "+", " ");
					itemExpr = MString.replaceAll(itemExpr, "-", " ");
					itemExpr = MString.replaceAll(itemExpr, "*", " ");
					itemExpr = MString.replaceAll(itemExpr, "/", " ");
					itemExpr = MString.replaceAll(itemExpr, "%", " ");
					itemExpr = MString.replaceAll(itemExpr, "(", " ");
					itemExpr = MString.replaceAll(itemExpr, ")", " ");
					itemExpr = MString.replaceAll(itemExpr, "SUM", " ");

					tmp10 = new StringTokenizer(itemExpr, ":");

					tmpStart = MString.replaceAll(tmp10.nextToken(), " ", "");
					tmpEnd = MString.replaceAll(tmp10.nextToken(), " ", "");
//SUM(B2:BH2)
					startTail = "";
					startTailInt = 0;
					startCh = 0;
					startCharacter = "";

					endCh = 0;

					try
                    {
                        startTail = tmpStart.substring(1, tmpStart.length());
						startTailInt = Integer.parseInt(startTail);
						startCh = tmpStart.charAt(0);
						startCharacter = tmpStart.substring(0, 1);
					}
                    catch (Exception e)
                    {
						startTail = tmpStart.substring(2, tmpStart.length());
						startTailInt = Integer.parseInt(startTail);
						startCh = tmpStart.charAt(1);
						startCharacter = tmpStart.substring(0, 2);
					}

                    char tmpch=tmpEnd.charAt(1);
                    if(tmpch>='A' && tmpch<='Z') endCh = tmpEnd.charAt(1);
                    else
                        endCh = tmpEnd.charAt(0);


					sumType = "";
					if (startCh == endCh)
                    {
						sumType = "v";// // 세로 SUM
					}
                    else
                    {
						sumType = "h";// // 가로 SUM
					}
//System.out.println("startCh================================================================================================>"+startCh);
///System.out.println("endCh================================================================================================>"+endCh);
//System.out.println("sumType================================================================================================>"+sumType);
					if (sumType.equals("v"))
                    {// // SUM(A1:A7) 세로 SUM
						boolean loop = true;
						int startTailIntVal = startTailInt;
						int increment = 0;

						do
                        {
                            if(increment>999) break;
							startTailResult = startTailIntVal + increment;// // 셀 뒷 숫자 증가
							pEnd = startCharacter + "" + startTailResult;
							if(tmpEnd.equals(pEnd)) loop=false;
							if(MReport.findName(pEnd, itemNameList) != -1)
                            {
								sumSpc += pEnd + " ";
								itemExpr = MString.replaceAll(itemExpr, ":", "+");// // 문자열을 치환하여 매끄럽게
								itmExpr = MString.replaceAll(sumSpc.trim(), " ", "+");
							}
                            increment++;
						} while (loop);


					} else
                    {// // SUM(A1:F1) 형식일 경우 가로 SUM
						boolean loop = true;
						startCh--;

						do
                        {
							//String startTail= tmpStart.substring(1, tmpStart.length());//// 셀 뒤숫자
							startCh += 1;// // 문자 증가
                            if(startCh>999) break;
							if ((startCh % 91) == 0) startCh = (char) (startCh + 'A');
							pEnd = MReport.getCharacterMake(startCharacter, startCh) + "" + startTailInt;
							if(tmpEnd.equals(pEnd)) loop=false;
							if(MReport.findName(pEnd, itemNameList) != -1)
                            {
								sumSpc += pEnd + " ";
								itemExpr = MString.replaceAll(itemExpr, ":", "+");// // 문자열을 치환하여 매끄럽게
								itmExpr = MString.replaceAll(sumSpc.trim(), " ", "+");
							}
						} while (loop);

					}
					itemExpr = sumSpc;
				} else if (itemExpr.indexOf(",") > 0) {// // SUM(A1,F1) 형식 일 경우

					itemExpr = MString.replaceAll(itemExpr, "(", " ");
					itemExpr = MString.replaceAll(itemExpr, ")", " ");
					itemExpr = MString.replaceAll(itemExpr, "SUM", " ");
					stk99 = new StringTokenizer(itemExpr, ",");
					while (stk99.hasMoreTokens()) {
						sumSpc += stk99.nextToken() + " ";
					}

					itmExpr = MString.replaceAll(sumSpc.trim(), " ", "+");
					itemExpr = sumSpc;

					itemExpr = MString.replaceAll(itemExpr, "-", "");
					itemExpr = MString.replaceAll(itemExpr, "+", "");
					itemExpr = MString.replaceAll(itemExpr, "*", "");
					itemExpr = MString.replaceAll(itemExpr, "/", "");
					itemExpr = MString.replaceAll(itemExpr, "%", "");
				} else {// // A1+F7 형식일 경우
					itemExpr = MString.replaceAll(itemExpr, "+", " ");
					itemExpr = MString.replaceAll(itemExpr, "-", " ");
					itemExpr = MString.replaceAll(itemExpr, "*", " ");
					itemExpr = MString.replaceAll(itemExpr, "/", " ");
					itemExpr = MString.replaceAll(itemExpr, "%", " ");
					itemExpr = MString.replaceAll(itemExpr, "(", " ");
					itemExpr = MString.replaceAll(itemExpr, ")", " ");
					itemExpr = MString.replaceAll(itemExpr, "SUM", " ");
				}

//System.out.println("********************************************************************** "+itemExpr);
//System.out.println("********************************************************************** "+itemName);
//System.out.println("********************************************************************** "+itmExpr);


				stkExpr = new StringTokenizer(itemExpr);

				int vCount = 0;
				int errorCount = 0;
/*
 *
 */
                int jj=0,order=0;
                String[] tmpp=new String[stkExpr.countTokens()];
                for(int ii=0;ii<tmpp.length;ii++) tmpp[ii]="";
				while (stkExpr.hasMoreTokens())
                {
					exprToken = stkExpr.nextToken();
					if (!MReport.isNum(exprToken))
                    {
						int iNum = MReport.findName(exprToken, itemNameList);
						if (iNum != -1)
                        {
							vCount++;
							//ie10,11 호환성 수식 설정 수정
							//itemOnFocusList[i] = "onfocus='nextblur(\"" + itemNameList[i]
							//		+ "\");' style='background-color: #cbddfb;'";
							itemOnFocusList[i] = "onfocus='nextblur(\"" + itemNameList[i]
									+ "\");' iseval='true'";
							itemOnChangeList[iNum] = MString.checkNull(itemOnChangeList[iNum]) + "change_all();";
//System.out.println("2********************************************************************** "+itmExpr);
                            order=1;
                            for(int ii=0;ii<tmpp.length;ii++) if(tmpp[ii].equals(exprToken)) order++;
                            String tmpStr=findString(order,itmExpr,exprToken);
//System.out.println("order="+order+"::itemExpr="+itmExpr+"::exprToken="+exprToken+"::tmpStr="+tmpStr);
                            /*
							itmExpr = itmExpr.substring(0, itmExpr.indexOf(exprToken))
									+ "parseFloat(dform."
									+ exprToken
									+ ".value)"
									+ itmExpr.substring(itmExpr.indexOf(exprToken) + exprToken.length(),
											itmExpr.length());
                             */
                            itmExpr=tmpStr+"parseFloat(dform."+exprToken+".value)"+itmExpr.substring(tmpStr.length()+exprToken.length(),itmExpr.length());
//System.out.println("3********************************************************************** "+itmExpr);
tmpp[jj++]=exprToken;
						} else errorCount++;
					}
				}

/* */

				if (vCount == 0 && errorCount == 0)
                {
					changeAllStrBuf.append("dform.");
					changeAllStrBuf.append(itemNameList[i]);
					changeAllStrBuf.append(".value=");
					changeAllStrBuf.append(itemExprList[i]);
					changeAllStrBuf.append(";\n");


				}
                else if (errorCount > 0)
                {
					changeAllStrBuf.append("dform.");
					changeAllStrBuf.append(itemNameList[i]);
					changeAllStrBuf.append(".value='");
					changeAllStrBuf.append(MString.replaceAll(itemExprList[i], "'", "\\\'"));
					changeAllStrBuf.append("';\n");


				}
                else
                {
					changeAllStrBuf.append("	dform.");
					changeAllStrBuf.append(itemName);
					changeAllStrBuf.append(".value =");
					changeAllStrBuf.append("(Math$round((").append(itmExpr).append(")*100))/100");
					changeAllStrBuf.append("; \n");
					changeAllStrBuf.append(" if(isNaN(dform.");
					changeAllStrBuf.append(itemName);
					changeAllStrBuf.append(".value)) dform.");
					changeAllStrBuf.append(itemName);
					changeAllStrBuf.append(".value = '0'; \n");
					changeAllStrBuf.append(" if(dform.");
					changeAllStrBuf.append(itemName);
					changeAllStrBuf.append(".value=='Infinity' || dform.");
					changeAllStrBuf.append(itemName);
					changeAllStrBuf.append(".value=='-Infinity') dform.");
					changeAllStrBuf.append(itemName);
					changeAllStrBuf.append(".value = '0'; \n");

				}
//System.out.println("**********************************************************changeAllStrBuf="+changeAllStrBuf);
			}
		}
	}

    public String findString(int order,String src,String findStr)
    {
        int inx1=0,inx2=0;
        String ret="";
        for(int ii=0;ii<order;ii++)
        {
            inx1=src.indexOf(findStr,inx1);
            if(inx1>-1) inx1+=findStr.length();
            else return "";
        }
        return src.substring(0,inx1-findStr.length());
    }

	public String getForm() {
		return form;
	}

	public String getInputForm() {
		return inputForm;
	}

	public String getInputForm(String form, String[] itemInputList, int[] itemNumList) {

		if (form == null)
			return null;

		StringBuilder insertBuf = new StringBuilder();

		int tdCount = 0;
		int stTDIndex;
		int edTDIndex;
		int index = 0;

		while (true) {
			if (index > itemNumList.length - 1)
				break;
			stTDIndex = form.indexOf("<td");
			if (stTDIndex == -1)
				break;
			edTDIndex = form.indexOf(">", stTDIndex + 1);
			if (edTDIndex == -1)
				break;

			if (tdCount == itemNumList[index] && !MString.isNull(itemInputList[index]))
            { // 입력 셀
				insertBuf.append(form.substring(0, edTDIndex + 1));
				insertBuf.append(itemInputList[index]);
				form = form.substring(edTDIndex + 1, form.length());
				index++;
			}
            else if (tdCount == itemNumList[index] && MString.isNull(itemInputList[index]))
            { // 타이틀 셀
				insertBuf.append(form.substring(0, edTDIndex));
				insertBuf.append(">");

				form = form.substring(edTDIndex + 1, form.length());
				index++;
			}
            else
            {
				insertBuf.append(form.substring(0, edTDIndex + 1));
				form = form.substring(edTDIndex + 1, form.length());
			}

			tdCount++;
		}

		insertBuf.append(form);
		return insertBuf.toString();
	}

	public String getInputTitleForm(String form) {
		boolean isDynaTable = false;
		return getInputTitleForm(form, isDynaTable);
	}

	public String getInputTitleForm(String form, boolean isDynaTable) {
		if (form == null)
			return null;
		int stTR = 0;
		int edTR = 0;
		int edTREnd = 0;
		int inIndex = 0;
		int startIndex = 0;
		int endIndex = 0;
        int[] ind=new int[3];

        /********************************************************************
		inIndex = form.indexOf("<input type");
		if (inIndex == -1)	inIndex = form.indexOf("<textarea ");
		if (inIndex == -1)	inIndex = form.indexOf("<select ");
       *************************************************************/
        ind[0]=form.indexOf("<input type");
        ind[1]=form.indexOf("<textarea ");
        ind[2]=form.indexOf("<select ");
        int min=1000000;
        for(int ii=0;ii<3;ii++)
        {
            if(ind[ii]>-1) min=(min>ind[ii])?ind[ii]:min;
        }
        inIndex=min;




		String inputTitleForm = null;
		startIndex = form.indexOf("<tr");

		while (true)
        {
			stTR = form.indexOf("<tr", stTR + 2);
			if (stTR == -1)	break;

			edTR = form.indexOf("</tr", stTR + 2);
			if (edTR == -1)	break;

			edTREnd = form.indexOf(">", edTR + 2);

			if (edTREnd == -1) break;
			if (stTR < inIndex && inIndex < edTR)
            {
				endIndex = stTR;
				if (isDynaTable) inputTitleForm = form.substring(startIndex, endIndex);
				else inputTitleForm = form.substring(0, endIndex);

				break;
			}
		}

		return inputTitleForm;
	}

	public String getInputBodyForm(String form) {
		if (form == null)
			return "";
//			throw new NullPointerException("Given form is null.");

		int stTR = 0;
		int edTR = 0;
		int edTREnd = 0;

		int firstTR = 0;
		int lastTR = 0;
		/****************** 가장 첫 입력란 위치 찾기 ******************/
		int inIndex = 0;
		int lastInIndex = 0;

		int iptIndex = form.indexOf("<input type");
		int selIndex = form.indexOf("<select ");
		int txtIndex = form.indexOf("<textarea ");

		if (selIndex <= txtIndex && (selIndex != -1)) {
			if (iptIndex <= selIndex && (iptIndex != -1)) {
				inIndex = iptIndex;
			} else {
				inIndex = selIndex;
			}
		} else if (iptIndex <= txtIndex && (iptIndex != -1)) {
			inIndex = iptIndex;
		} else if (txtIndex != -1) {
			inIndex = txtIndex;
		} else {
			if (iptIndex <= selIndex && (iptIndex != -1)) {
				inIndex = iptIndex;
			} else if (selIndex != -1) {
				inIndex = selIndex;
			} else {
				inIndex = iptIndex;
			}
		}
		iptIndex = form.lastIndexOf("<input type");
		selIndex = form.lastIndexOf("<select ");
		txtIndex = form.lastIndexOf("<textarea ");

		if (selIndex >= txtIndex) {
			if (iptIndex >= selIndex) {
				lastInIndex = iptIndex;
			} else {
				lastInIndex = selIndex;
			}
		} else {
			if (iptIndex >= txtIndex) {
				lastInIndex = iptIndex;
			} else {
				lastInIndex = txtIndex;
			}
		}
		String inputBodyForm = null;

		/************
		 * 가장 첫 입력란이 들어가 있는
		 * <tr>
		 * 태그 위치 찾기
		 ***********/
		for (int i = 0; true; i++) {
			stTR = form.indexOf("<tr", stTR + 2);
			if (stTR == -1)
				return form;
//				throw new NullPointerException("Start of TR could not be found. stTR: " + stTR + " form: " + MString.getEllipsis(form, 500));

			edTR = form.indexOf("</tr", stTR + 2);

			// </tr>이 없을때.. 임시 방편
			// 원칙은 </tr>이 꼭 있어야 한다.
			if (edTR == -1) {
				edTR = form.indexOf("<tr", stTR + 2);
				if (edTR == -1)
					edTR = form.indexOf("</table", stTR + 2);
			}
			if (edTR == -1)
				return form;
//				throw new NullPointerException("End of TR could not be found. form: " + MString.getEllipsis(form, 500));

			edTREnd = form.indexOf(">", edTR + 2);
			if (edTREnd == -1)
				return form;
//				throw new NullPointerException("End of TR could not be found. form: " + MString.getEllipsis(form, 500));
			if (stTR < inIndex && inIndex < edTR) {
				firstTR = stTR;
				break;
			}
		}

		if (stTR == -1 || edTR == -1 || edTREnd == -1)
			return form;
//			throw new NullPointerException("start TR is null or end TR is null. form: " + MString.getEllipsis(form, 500));
		stTR = form.length();

		for (int i = 0; true; i++) {
			stTR = form.lastIndexOf("<tr", stTR - 2);
			if (stTR == -1)
				break;

			edTR = form.indexOf("</tr", stTR);

			// </tr>이 없을때.. 임시 방편
			// 원칙은 </tr>이 꼭 있어야 한다.
			if (edTR == -1) {
				edTR = form.indexOf("<tr", stTR + 2);
				if (edTR == -1)
					edTR = form.indexOf("</table", stTR + 2);
			}
			if (edTR == -1)
				break;

			edTREnd = form.indexOf(">", edTR + 2);
			if (edTREnd == -1)
				break;

			if (stTR < lastInIndex && lastInIndex < edTR) {
				// inputBodyForm = form.substring(stTR, edTREnd+1);
				lastTR = edTREnd + 1;
				break;
			} else if (lastInIndex > edTR) {
				return form;
//				throw new NullPointerException("Last Input Index exceeds end TR tag.");
			}
		}

		if (stTR == -1 || edTR == -1 || edTREnd == -1)
			return form;
//			throw new NullPointerException("start TR is null or end TR is null.");
		/************ 가장 마지막 입력란이 들어가 있는 </tr> 태그 위치 찾기 ***********/

		inputBodyForm = form.substring(firstTR, lastTR);
		// return null;
		return inputBodyForm;
	}

	public String getPutValScript() {
		return putValStrBuf.toString();
	}

	public String getChangeAllScript() {
		return changeAllStrBuf.toString();
	}

	public String getChangeAllScript(String baseScript, int endNumber, int rowCount) {
		if (baseScript.trim().length() == 0)
			return "";
		StringBuilder strbuf = new StringBuilder();
		String newScript = "";

		int startIndex = 0;
		int dot = 0;
		String firstItemName = "";
		String formName = "dform.";

		for (int i = 0; i < rowCount; i++) {
			newScript = baseScript;
			while (true) {
				startIndex = newScript.indexOf(formName);
				if (startIndex == -1)
					break;
				dot = newScript.indexOf(".", startIndex + formName.length());
				if (dot == -1)
					break;
				firstItemName = newScript.substring(startIndex + formName.length(), dot).replaceAll("[0-9]", "");// [A-Z][a-z]
				strbuf.append(newScript.substring(0, startIndex + formName.length()));
				strbuf.append(firstItemName);
				strbuf.append(endNumber);
				newScript = newScript.substring(dot, newScript.length());
			}
			endNumber = endNumber + 1;
			strbuf.append(newScript);
		}

		return strbuf.toString();
	}

	public String getChangeAllScript(String baseScript, String[] stItemNameList, String[] stItemNumList,
			int[] tableColNumList, String[] tableRowList) {

//System.out.println("*************************************************************************** base="+baseScript);
		if (baseScript.trim().length() == 0)
			return "";
		String newScript = "";

		String[] baseList = baseScript.split("[.]"); // 기본 스크립트를 .(dot)를 기준으로 각 배열로 나눈다.
		String cellname = "";
		String cellnum = "";
		String position = "";

		/******************************************************************************
		 * for문을 사용하여 기본 스크립트를 아래처럼 만든다 cellname = "F,G,H,F,F ...."; cellnum = "5,5,5,6,6 ..."; position =
		 * "1,3,5,7,9 ..."; <- 기본 스크립트 배열에서 각 셀네임이 있던 인덱스 위치
		 ******************************************************************************/
		for (int baseIdx = 0; baseIdx < baseList.length; baseIdx++)
        {
			for (int y = 0; y < stItemNameList.length; y++)
            {
				if (baseList[baseIdx].equals(stItemNameList[y] + stItemNumList[y]))
                {
					if (cellname.length() == 0)
                    {
						cellname = stItemNameList[y];
						cellnum = stItemNumList[y];
						position = Integer.toString(baseIdx);
					} else
                    {
						cellname = cellname + "," + stItemNameList[y];
						cellnum = cellnum + "," + stItemNumList[y];
						position = position + "," + Integer.toString(baseIdx);
					}
				}
			}
		}


		String[] cellnameList = cellname.split(",");
		String[] cellnumList = cellnum.split(",");
		String[] positionList = position.split(",");

		String newCellname = "";
		String newCellnum = "";
		String newPosition = "";
		int here = 0;
		/******************************************************************************
		 * 늘어난 각 테이블의 행 숫자 만큼 그 테이블에 해당하는 cellname과 각 해당하는 cellnum를 만들어서 newCell...으로 만들어 준다.
		 ******************************************************************************/
		for (int i = 0; i < tableRowList.length; i++) {
			for (int stp = 0; stp < Integer.parseInt(tableRowList[i]); stp++) {
				int gap = 0;

				int min = minNum(stItemNumList, here, here + tableColNumList[i]);
				int max = maxNum(stItemNumList, here, here + tableColNumList[i]);

				if (stp != 0) {
					gap = getGap(stItemNumList, here, here + tableColNumList[i]);
					for (int nn = here; nn < stItemNumList.length; nn++) {
						stItemNumList[nn] = Integer.toString(Integer.parseInt(stItemNumList[nn]) + gap);
					}
					for (int b = 0; b < cellnumList.length; b++) {
						if (min <= Integer.parseInt(cellnumList[b]))
							cellnumList[b] = Integer.toString(Integer.parseInt(cellnumList[b]) + gap);
					}
				}

				min = minNum(stItemNumList, here, here + tableColNumList[i]);
				max = maxNum(stItemNumList, here, here + tableColNumList[i]);

				int startf = 100000;
				int endf = 0;
				int readyEnd = 0;
				for (int a = 0; a < cellnumList.length; a++) {
					if (min <= Integer.parseInt(cellnumList[a]) && max >= Integer.parseInt(cellnumList[a])) {
						if (baseList[Integer.parseInt(positionList[a]) + 1].indexOf("=") != -1) {
							if (startf > a)
								startf = a;
							readyEnd = a;
						}
					}
					if (max < Integer.parseInt(cellnumList[a])) {
						if ((baseList[Integer.parseInt(positionList[a]) + 1]).indexOf("=") != -1) {
							if (readyEnd > endf)
								endf = a - 1;
						}
					}
				}
				if (readyEnd > endf)
					endf = cellnumList.length - 1;

				for (int incell = startf; incell <= endf; incell++) {
					if (newCellname.length() == 0) {
						newCellname = cellnameList[incell];
						newCellnum = cellnumList[incell];
						newPosition = positionList[incell];
					} else {
						newCellname = newCellname + "," + cellnameList[incell];
						newCellnum = newCellnum + "," + cellnumList[incell];
						newPosition = newPosition + "," + positionList[incell];
					}
				}
			}
			here = here + tableColNumList[i];
		}

		/*** script로 다시 만들기 ***/
		String[] newCellnameList = newCellname.split(",");
		String[] newCellnumList = newCellnum.split(",");
		String[] newPositionList = newPosition.split(",");

		int cellhere = 0;
		for (int m = 0; m < baseList.length; m++) {
			if (cellhere < newCellnameList.length && m == Integer.parseInt(newPositionList[cellhere])) {
				if (baseList[m - 1].indexOf(";") > 0) {
					String[] tmpS = baseList[m - 1].split(";");
					if (baseList[m + 1].indexOf(";") > 0) {
						String[] tmpE = baseList[m + 1].split(";");
						newScript = newScript + tmpS[1] + "." + newCellnameList[cellhere] + newCellnumList[cellhere]
								+ "." + tmpE[0] + ";";
					} else {
						newScript = newScript + tmpS[1] + "." + newCellnameList[cellhere] + newCellnumList[cellhere]
								+ ".";
					}
				} else {
					if (baseList[m + 1].indexOf(";") > 0) {
						String[] tmpE = baseList[m + 1].split(";");
						newScript = newScript + baseList[m - 1] + "." + newCellnameList[cellhere]
								+ newCellnumList[cellhere] + "." + tmpE[0] + ";";
					} else {
						newScript = newScript + baseList[m - 1] + "." + newCellnameList[cellhere]
								+ newCellnumList[cellhere] + ".";
					}
				}
				cellhere++;
			}
			if (cellhere < newCellnameList.length && (m + 1) >= baseList.length)
				m = -1;
		}
		newScript.replaceAll("[..]", "[.]");

		return newScript;
	}

	public int getGap(String[] startNum, int start, int end) {
		int top = -1;
		int bottom = 100000;
		for (int i = start; i < end; i++) {
			if (bottom > Integer.parseInt(startNum[i]))
				bottom = Integer.parseInt(startNum[i]);
			if (top < Integer.parseInt(startNum[i]))
				top = Integer.parseInt(startNum[i]);
		}
		if (top - bottom < 0)
			return 0;
		return (top - bottom + 1);
	}

	public int minNum(String[] startNum, int start, int end) {
		int bottom = 100000;
		for (int i = start; i < end; i++) {
			if (bottom > Integer.parseInt(startNum[i]))
				bottom = Integer.parseInt(startNum[i]);
		}
		return bottom;
	}

	public int maxNum(String[] startNum, int start, int end) {
		int top = -1;
		for (int i = start; i < end; i++) {
			if (top < Integer.parseInt(startNum[i]))
				top = Integer.parseInt(startNum[i]);
		}
		return top;
	}
}
