<!DOCTYPE html>
<html lang="ko"
	xmlns:th="http://www.thymeleaf.org">
<!--
 *******************************************************************************
 * @source  : PollListForm.html
 * @desc    : POLL관리화면 Page
 *============================================================================
 * SISUN
 * Copyright(C) 2019 TSIT, All rights reserved.
 *============================================================================
 * VER  DATE         AUTHOR      DESCRIPTION
 * ===  ===========  ==========  =============================================
 * 1.0  2021.02.19   sowon		   최초 작성
 *******************************************************************************
 -->
	<div id="main">
		<div class="main-title">
		</div>

		<div class="panelStyle">
			<form id="pollSearchForm" name="pollSearchForm" action="#" th:action="@{'/marketing/poll/list'}" onsubmit="$('#btnSearch').trigger('click'); return false;">
			<input type="hidden" name="maskingYn" value="Y"/>
				<table class="frmStyle">
					<colgroup>
						<col style="width:10%;"/>
						<col style="width:10%;"/>
						<col style="width:10%;"/>
						<col style="width:30%;"/>
						<col style="width:10%;"/>
						<col/>
					</colgroup>
					<tbody>
						<tr>
							<th>사이트</th>
							<td>
								<select name="siteCd">
									<option th:if="${siteList}" th:each="oneData, status : ${siteList}" th:value="${oneData.cd}" th:text="${oneData.cdNm}|"></option>
								</select>
							</td>
							<th>POLL 제목</th>
							<td>
								<input type="text" name="pollTitle" id="pollTitle"/>
							</td>
						</tr>
						<tr>
							<th>등록기간</th>
							<td id="terms" colspan="3"></td>
						</tr>
					</tbody>
				</table>
				<ul class="panelBar">
					<li class="center">
						<input type="button" value="초기화" class="btn btn-gray btn-lg" id="btnReset" onclick="fnReset();"/>
						<input type="button" value="조회" class="btn btn-base btn-lg" id="btnSearch" onclick="fnSearch();"/>
					</li>
				</ul>
			</form>
		</div>

		<div class="panelStyle">
			<ul class="division">
				<li style="width:60%">
					<div class="panelBar">
						<h4>POLL 목록</h4>
					</div>
					<div id="gridListPoll" style="width: 100%; height: 500px; float: left;" class="ag-theme-balham"></div>
				</li>
				<li style="width:40%">
					<div class="panelBar">
						<ul class="panelBar">
						<!-- <h4 id="pollQtitle">투표자 수</h4> -->
							<li class="right">
								<button type="button" class="btn btn-default btn-lg" id="btnExcel">엑셀다운로드</button>
							</li>
						</ul>
					</div>
					<div id="gridListVote" style="width: 100%; height: 500px; float: right;" class="ag-theme-balham"></div>
				</li>
			</ul>
		</div>

		<div class="panelStyle">
			<div class="boxTitle"></div>
			<form id="registerForm" name="registerForm">
				<input type="hidden" name="pollSq"/>
				<ul class="panelBar">
					<li class="right">
						<span class="btnRight">
							<button type="button" class="btn btn-info btn-lg" onclick="fnReset();">신규</button>
							<button type="button" class="btn btn-success btn-lg" onclick="fnPollSave();">저장</button>
						</span>
					</li>
				</ul>
				<ul class="boxContent">
					<li class="boxContentTop">
						<table class="frmStyle">
							<colgroup>
								<col style="width:5%;"/>
								<col style=""/>
								<col style=""/>
								<col style=""/>
								<col style=""/>
								<col style=""/>
							</colgroup>
							<tbody>
								<tr>
									<th>POLL 제목<em class="required" title="필수"></em></th>
									<td>
										<input type="text" name="pollTitle" id="pollTitle"/>
									</td>

									<th>투표참여기간<em class="required" title="필수"></em></th>
									<td>
										<input name="stDate" type="text" class="w80 schDate" maxlength="10" required="required" data-valid-name="투표시작일자">
										<select id="stTimeHour" required="required" data-valid-name="투표기간 시작시간">
											<th:block th:each="num, index  : ${#numbers.sequence(0,23)}">
											<option  th:value="${#numbers.formatInteger(num,2)}" th:text="|${#numbers.formatInteger(num,2)}시|" >시간</option>
											</th:block>
										</select>
										<select id="stTimeMin" required="required" data-valid-name="투표기간 시작시간">
											<th:block th:each="num: ${#numbers.sequence(0,59)}">
											<option  th:value="${#numbers.formatInteger(num,2)}"  th:text="|${#numbers.formatInteger(num,2)}분|" >분</option>
											</th:block>
										</select>
										<input name="dispStTime" id="stTime" type="hidden" data-valid-name="투표기간 시작시간" value='000000' />
										~
										<input name="edDate" type="text" class="w80 schDate" maxlength="10" data-valid-type="calendar">
										<select id="edTimeHour" required="required" data-valid-name="투표기간 종료시간">
											<th:block th:each="num: ${#numbers.sequence(0,23)}">
											<option  th:value="${#numbers.formatInteger(num,2)}"  th:text="|${#numbers.formatInteger(num,2)}시|" th:selected="${#numbers.formatInteger(num,2)}==23 ? 'true'">시</option>
											</th:block>
										</select>
										<select id="edTimeMin" required="required" data-valid-name="투표기간 종료시간">
											<th:block th:each="num: ${#numbers.sequence(0,59)}">
											<option  th:value="${#numbers.formatInteger(num,2)}"  th:text="|${#numbers.formatInteger(num,2)}분|" th:selected="${#numbers.formatInteger(num,2)}==59 ? 'true'">분</option>
											</th:block>
										</select>
										<input name="dispEdTime" id="edTime" type="hidden" data-valid-name="투표기간 종료시간" value='235959' />
									</td>

									<th>사이트</th>
									<td colspan="3">
										<select name="siteCd">
											<option th:if="${siteList}" th:each="oneData, status : ${siteList}" th:value="${oneData.cd}" th:text="${oneData.cdNm}|"></option>
										</select>
									</td>
									
								</tr>
								<tr>
									<th>중복참여<i class="star"></i></th>
									<td>
										<select name="dupPartiYn">
											<option th:if="${useYnList}" th:each="oneData, status : ${useYnList}" th:value="${oneData.cd}" th:selected="${oneData.cd} == 'N'" th:text="|${oneData.cdNm}|"></option>
										</select>
									</td>
									<th>선착순<i class="star"></i></th>
									<td>
										<select name="fstComYn">
											<option th:if="${useYnList}" th:each="oneData, status : ${useYnList}" th:value="${oneData.cd}" th:selected="${oneData.cd} == 'N'" th:text="|${oneData.cdNm}|"></option>
										</select>
									</td>	
									<th>선착순 인원<i class="star"></i></th>
									<td>
										<input type="text" name="partiCnt" id="partiCnt" disabled="disabled" data-valid-type="numeric"/>
									</td>
									<th>URL</th>
									<td>
										<input type="text" name="url" id="url" disabled="disabled"/>
									</td>
								</tr>
								<tr style="height: 250px;">
									<th>문항<em class="required" title="필수"></em></th>
									<td colspan="7">
										<button type="button" class="btn btn-info btn-lg" onclick="fnAddQuestion();">문항추가</button>
										<button type="button" class="btn btn-info btn-lg" onclick="fnDeleteQuestion();">문항삭제</button>
										<div id="questionDiv" class="btn_left" style="width: 100%; height: 300px; overflow: yes; overflow-x: scroll; overflow-y: auto;">
											<table class="tableStyle" id="questionTable" width="100%" style="overflow-x: scroll; overflow-y: auto;">
												<colgroup>
													<col width="2%">
													<col width="10%">
													<col width="">
													<col width="">
													<col width="">
													<col width="">
													<col width="">
													<col width="">
													<col width="">
													<col width="">
													<col width="">
													<col width="">
													<col width="">
												</colgroup>
												<tbody>
													<tr align="center" style="background-color: #EEEEEE;">
														<td>선택</td>
														<td>문항 제목</td>
														<td>문제 유형</td>
														<td>문항 참고값 1</td>
														<td>문항 참고값 2</td>
														<td>문항 참고값 3</td>
														<td>문항 참고값 4</td>
														<td>문항 참고값 5</td>
														<td>문항 참고값 6</td>
														<td>문항 참고값 7</td>
														<td>문항 참고값 8</td>
														<td>문항 참고값 9</td>
														<td>문항 참고값 10</td>
													</tr>
												</tbody>
											</table>
										</div>
									</td>
								</tr>
							</tbody>
						</table>
					</li>
					<li class="boxContentBtnB">
						<span class="btnRight">
						</span>
					</li>
				</ul>
			</form>
		</div>

	</div>

<!-- 문항 Start --------------------------------------------------------------->
<table class="frmStyle" style="display: none;" id="rowQuestion">
	<tr id="trRowQuestion">
	<td>
		<input type="checkbox" name="chkIdx" style="top: 50%; width: 18px; height: 18px;"/>
		<input type="hidden" name="crud" value="C"/>
		<input type="hidden" name="pollQsq" value=""/>
	</td>
	<td>
		<input type="text" name="pollQtitle" class="type-text" style="width: 100%;"onkeyup="chkChar(this)"/>
	</td>
	<td>
		<select name="pollQtype">
			<option th:if="${pollQtype}" th:each="oneData, status : ${pollQtype}" th:value="${oneData.cd}" th:text="${oneData.cdNm}|"></option>
		</select>
	</td>
	<td>
		<input type="text" name="pollQval1" class="type-text" onkeyup="chkChar(this)" style="width: 100%;"/>
	</td>
	<td>
		<input type="text" name="pollQval2" class="type-text" onkeyup="chkChar(this)" style="width: 100%;"/>
	</td>
	<td>
		<input type="text" name="pollQval3" class="type-text" onkeyup="chkChar(this)"style="width: 100%;"/>
	</td>
	<td>
		<input type="text" name="pollQval4" class="type-text" onkeyup="chkChar(this)" style="width: 100%;"/>
	</td>
	<td>
		<input type="text" name="pollQval5" class="type-text" onkeyup="chkChar(this)" style="width: 100%;"/>
	</td>
	<td>
		<input type="text" name="pollQval6" class="type-text" onkeyup="chkChar(this)" style="width: 100%;"/>
	</td>
	<td>
		<input type="text" name="pollQval7" class="type-text" onkeyup="chkChar(this)" style="width: 100%;"/>
	</td>
	<td>
		<input type="text" name="pollQval8" class="type-text" onkeyup="chkChar(this)" style="width: 100%;"/>
	</td>
	<td>
		<input type="text" name="pollQval9" class="type-text" onkeyup="chkChar(this)" style="width: 100%;"/>
	</td>
	<td>
		<input type="text" name="pollQval10" class="type-text" onkeyup="chkChar(this)" style="width: 100%;"/>
	</td>
	</tr>
</table>
<!-- 문항 End ----------------------------------------------------------------->

<script th:inline="javascript">
/*<![CDATA[*/
	var fistFlag = true;
	var siteCdList = gagajf.convertToArray([[${siteList}]]);

	var columnDefsPoll = [
		{headerName: "사이트"			, field:'siteCd'	, width:100, cellClass: 'text-center',
			cellEditor: 'agRichSelectCellEditor',
			cellEditorParams: { values: gagaAgGrid.extractValues(siteCdList) },
			valueFormatter: function (params) { return gagaAgGrid.lookupValue(siteCdList, params.value); },
			valueParser: function (params) { return gagaAgGrid.lookupKey(siteCdList, params.newValue); }
		},
		{headerName: 'POLL번호'	, field:'pollSq'	, width:100, cellClass: 'text-center'
			, cellRenderer: function(params) { return fnSetColumn(params); }
		},
		{headerName: 'POLL제목'	, field:'pollTitle'	, width:200, cellClass: 'text-left'
			, cellRenderer: function(params) { return fnSetColumn(params); }
		},
		 {headerName: '문항유형'		, field:'pollQtypeNm', width:100, cellClass: 'text-center'},
		 {headerName: '문항제목'		, field:'pollQtitle', width:230, cellClass: 'text-center'},
		 {headerName: '등록일'		, field:'regDt'	, width:200, cellClass: 'text-center'},
	];

	var columnDefsVote = [
		{headerName: 'ID'			, field:'maskingCustId'	, width:100, cellClass: 'text-center',enableValue: true},
		{headerName: '이름'			, field:'maskingCustNm'	, width:100, cellClass: 'text-center',enableValue: true},
		{headerName: '투표일시'		, field:'voteDt'	, width:100, cellClass: 'text-center',enableValue: true},
		{headerName: 'ques1'	    , field:'dummy1'	, width:200, cellClass: 'text-center',enableValue: true},
		{headerName: 'ques2'	    , field:'dummy2'	, width:200, cellClass: 'text-center',enableValue: true},
		{headerName: 'ques3'	    , field:'dummy3'	, width:200, cellClass: 'text-center',enableValue: true},
		{headerName: 'ques4'	    , field:'dummy4'	, width:200, cellClass: 'text-center',enableValue: true},
		{headerName: 'ques5'	    , field:'dummy5'	, width:200, cellClass: 'text-center',enableValue: true},
		{headerName: 'ques6'	    , field:'dummy6'	, width:200, cellClass: 'text-center',enableValue: true},
		{headerName: 'ques7'	    , field:'dummy7'	, width:200, cellClass: 'text-center',enableValue: true},
		{headerName: 'ques8'	    , field:'dummy8'	, width:200, cellClass: 'text-center',enableValue: true},
		{headerName: 'ques9'	    , field:'dummy9'	, width:200, cellClass: 'text-center',enableValue: true},
		{headerName: 'ques10'	    , field:'dummy10'	, width:200, cellClass: 'text-center',enableValue: true},
		
	];

	var gridOptionsPoll = gagaAgGrid.getGridOptions(columnDefsPoll);
	var gridOptionsVote = gagaAgGrid.getGridOptions(columnDefsVote);

	// 컬럼 설정
	var fnSetColumn = function(params) {
		var allData = gagaAgGrid.getAllRowData(gridOptionsPoll);

		// 첫번째 일 때
		if (params.rowIndex == 0) {

			if (params.colDef.field == 'pollTitle') {
				return '<a href="javascript:void(0);">' + params.value + '</a>'
			} else {
				return params.value;
			}
		} else {

			if (allData[params.rowIndex - 1].pollSq != params.data.pollSq) {
				if (params.colDef.field == 'pollTitle') {
					return '<a href="javascript:void(0);">' + params.value + '</a>'
				} else {
					return params.value;
				}
			}
		}
	}
		

	// 셀 클릭 시
	var selectPoll = [];
	gridOptionsPoll.onCellClicked = function(event)  {
		if (event.colDef.field == 'pollTitle') {
			$('#registerForm input[name=pollTitle]').focus();
			fnAllDeleteQuestion();
			fnSetDetail(event);
			fnSearchVote(event.data);
			
		} /* else if (event.colDef.field == 'pollQtitle') {
			fnSearchVote(event.data);
		} */ else if (event.colDef.field == 'pollQtypeNm'){
			if(event.data.pollQtypeNm == '단수형' || event.data.pollQtypeNm == '복수형'){
				var actionUrl = "/marketing/poll/voter/list/popup/form?pollQsq=" + event.data.pollQsq +"&pollQtype=" + event.data.pollQtype;
				cfnOpenModalPopup(actionUrl, 'pollVoteRatePopup');
			}
		}
	}

	// 투표자 조회
	var fnSearchVote = function(data) {
		for (var i = 1; i <= 10 ; i++) {
			gagaAgGrid.setColumnHeaderName(gridOptionsVote, 'dummy' + i, "ques"+ i);
		}
		var params = new Object();
		params.pollQsq = data.pollQsq;
		params.pollSq = data.pollSq;
	
		var jsonData = JSON.stringify(params);
		gagajf.ajaxJsonSubmit('/marketing/poll/voter/list', jsonData, function(dataList) {
			// 컬럼 이름 변경
			$.each(dataList.questionList, function(idx, item) {
				gagaAgGrid.setColumnHeaderName(gridOptionsVote, 'dummy' + (idx+1), item.pollQtitle);
			});
			
			gridOptionsVote.columnApi.resetColumnState();
			gridOptionsVote.api.setRowData(dataList.pollList);
			
		});

	}

	// 상세 설정
	var fnSetDetail = function(event) {
		var pollSq = event.data.pollSq;
		var data = event.data;
		var allData = gagaAgGrid.getAllRowData(gridOptionsPoll);

		$(allData).each(function(idx) {
			if (allData[idx].pollSq == pollSq) {
				fnAddQuestion(allData[idx]);
				selectPoll.push(allData[idx]);
			}
		});

		$('#registerForm input[name=pollSq]').val(pollSq);
		$('#registerForm input[name=pollTitle]').val(data.pollTitle);

		// 시작 기간 설정
		var sttime = data.pollStdt.split(" ");
		var stime = sttime[1].split(":")
		$('#registerForm input[name=stDate]').val(sttime[0]);
		$('#stTimeHour').val(stime[0]);
		$('#stTimeMin').val(stime[1]);

		// 종료 기간 설정
		var edtime = data.pollEddt.split(" ");
		var etime = edtime[1].split(":")
		$('#registerForm input[name=edDate]').val(edtime[0]);
		$('#edTimeHour').val(etime[0]);
		$('#edTimeMin').val(etime[1]);

		$('#registerForm select[name=siteCd]').val(data.siteCd);
		
		$('#registerForm select[name=dupPartiYn]').val(data.dupPartiYn);
		$('#registerForm select[name=fstComYn]').val(data.fstComYn);
		$('#registerForm input[name=partiCnt]').val(data.partiCnt);
		if(data.planSq != null){
			// url 변경해야함 
			$('#registerForm input[name=url]').val("http://ldfront.style24.com/planning/event/poll/form?planSq=" + data.planSq);
		}
		
		
		if($('#registerForm select[name=fstComYn]').val() == 'Y'){
			$("#partiCnt").attr("disabled",false);
		}else{
			$("#partiCnt").attr("disabled",true);
			$("#partiCnt").val('');
		}
	}

	// 검색
	var fnSearch = function() {
		var formId = '#pollSearchForm';
		gagaAgGrid.fetch('/marketing/poll/list', gridOptionsPoll, formId);
	}
	
	// 선착순 y/n여부 따라 인원  input 활성화
	$('#registerForm select[name=fstComYn]').change(function(){
		if($('#registerForm select[name=fstComYn]').val() == 'Y'){
			$("#partiCnt").attr("disabled",false);
		}else{
			$("#partiCnt").attr("disabled",true);
			$("#partiCnt").val('');
		}
		
	})
	
	
	// 유효성
	function validationPoll() {
		if($('#registerForm input[name=pollTitle]').val() == ''){
			mcxDialog.alert('POLL 제목을 입력하세요');
			return;
		}
		if($('#registerForm input[name=stDate]').val() == '' || $('#registerForm input[name=sdDate]').val() == '' ){
			mcxDialog.alert('POLL 날짜를 설정하세요');
			return;
		}
		if($('#registerForm select[name=fstComYn]').val() == 'Y'){
			if($('#registerForm input[name=partiCnt]').val() == ''){
				mcxDialog.alert('선착순 인원을 설정하세요.');
				return;
			}
		}
	};
	 
	



	// 문항추가
	var fnAddQuestion = function(data) {
		if ($('#questionTable tr').length > 10) {
			mcxDialog.alert('문항은 최대 10개까지 등록 가능합니다.');
			return;
		}
		if (typeof data == 'undefined') {
			var cnt = $('#questionTable tr').length;

			// 태그 복사
			var tTbody = $('#questionTable')[0].tBodies[0];
			var oNewTR = $('#trRowQuestion')[0].cloneNode(true);

			// id 삭제
			$(oNewTR).attr('id', 'questionTable' + cnt);
			// id 변경
			var val1 = $(oNewTR).find('.uFileInput');
			$(val1).attr('id' , cnt + '_val1');
			$(val1).attr('name' , cnt + '_val1');
			$(val1).off('change');

			var label = $(oNewTR).find('label');
			$(label).attr('for', cnt + '_val1');

			// 행 추가
			tTbody.appendChild(oNewTR);

		} else {
			if (gagajf.isNull(data.pollQtitle)) return;
			var cnt = $('#questionTable tr').length;

			// 태그 복사
			var tTbody = $('#questionTable')[0].tBodies[0];
			var oNewTR = $('#trRowQuestion')[0].cloneNode(true);

			// id 삭제
			$(oNewTR).attr('id', 'questionTable' + cnt);
			// id 변경
			var val1 = $(oNewTR).find('.uFileInput');
			$(val1).attr('id' , cnt + '_val1');
			$(val1).attr('name' , cnt + '_val1');
			$(val1).off('change');

			var label = $(oNewTR).find('label');
			$(label).attr('for', cnt + '_val1');

			// 값 설정
			$(oNewTR).find("input[name=crud]").val('R');
			$(oNewTR).find("input[name=pollQsq]").val(data.pollQsq);
			$(oNewTR).find("input[name=pollQtitle]").val(data.pollQtitle);
			$(oNewTR).find("select[name=pollQtype]").val(data.pollQtype);
			$(oNewTR).find("input[name=pollQval1]").val(data.pollQval1);
			$(oNewTR).find("input[name=pollQval2]").val(data.pollQval2);
			$(oNewTR).find("input[name=pollQval3]").val(data.pollQval3);
			$(oNewTR).find("input[name=pollQval4]").val(data.pollQval4);
			$(oNewTR).find("input[name=pollQval5]").val(data.pollQval5);
			$(oNewTR).find("input[name=pollQval6]").val(data.pollQval6);
			$(oNewTR).find("input[name=pollQval7]").val(data.pollQval7);
			$(oNewTR).find("input[name=pollQval8]").val(data.pollQval8);
			$(oNewTR).find("input[name=pollQval9]").val(data.pollQval9);
			$(oNewTR).find("input[name=pollQval10]").val(data.pollQval10);

			// 행 추가
			tTbody.appendChild(oNewTR);
		}
	}

	// 문항삭제
	// 알림문구 추가 해야하지 않을가..(문항삭제를 할 경우 즉시 삭제됩니다..?)
	var fnDeleteQuestion = function() {
		var tags = $('input[name=chkIdx]');

		for (var idx = 0; idx < tags.length; idx++) {
			var checkYn = tags[idx].checked;
			var pollQsq = $(tags[idx]).closest('tr').find("input[name='pollQsq']").val(); 
			if (checkYn) {
				$(tags[idx]).closest('tr').remove();
				data = {pollQsq : pollQsq};
				var jsonData = JSON.stringify(data);
				gagajf.ajaxJsonSubmit('/marketing/poll/question/remove', jsonData, function(result) {
				});
				
			}
		}
	}

	// 문항 내용 전체 삭제
	var fnAllDeleteQuestion = function() {
		selectPoll = [];
		$($('#questionTable')[0].rows).each(function(idx, item) {
			if ( idx != 0) {
				item.remove();
			}
		});
	}

	// 저장
	var fnPollSave = function() {
		var dataList = [];
		if (selectPoll.length > 0) { // 저장
			mcxDialog.confirm('저장 하시겠습니까?' , {
				cancelBtnText: "취소",
				sureBtnText: "확인",
				sureBtnClick: function() {
					var pollTitle = $('#registerForm input[name=pollTitle]').val();
					var siteCd = $('#registerForm select[name=siteCd]').val();
					var pollStdt = $('#registerForm input[name=stDate]').val() + ' ' + $('#stTimeHour').val() + ':' + $('#stTimeMin').val() + ':' + '00';
					var pollEddt = $('#registerForm input[name=edDate]').val() + ' ' + $('#edTimeHour').val() + ':' + $('#edTimeMin').val() + ':' + '59';
					var dupPartiYn = $('#registerForm select[name=dupPartiYn]').val();
					var fstComYn = $('#registerForm select[name=fstComYn]').val();
					var partiCnt = $('#registerForm input[name=partiCnt]').val();

					$('#questionTable tr').each(function(index, tr) {
						if (index < 1) return;
						var pollQsq = $(tr).find("input[name=pollQsq]").val();
						var crud = $(tr).find("input[name=crud]").val();

						if (crud == 'R') { // 기존 데이터
							$(selectPoll).each(function(idx) {
								selectPoll[idx].pollTitle = pollTitle;
								selectPoll[idx].siteCd = siteCd;
								selectPoll[idx].pollStdt = pollStdt;
								selectPoll[idx].pollEddt = pollEddt;
								selectPoll[idx].dupPartiYn = dupPartiYn;
								selectPoll[idx].fstComYn = fstComYn;
								selectPoll[idx].partiCnt = partiCnt;

								if (selectPoll[idx].pollQsq == pollQsq) {
									selectPoll[idx].pollQtitle = $(tr).find('input[name=pollQtitle]').val();
									selectPoll[idx].pollQtype = $(tr).find("select[name=pollQtype]").val();
									selectPoll[idx].pollQval1 = $(tr).find('input[name=pollQval1]').val();
									selectPoll[idx].pollQval2 = $(tr).find('input[name=pollQval2]').val();
									selectPoll[idx].pollQval3 = $(tr).find('input[name=pollQval3]').val();
									selectPoll[idx].pollQval4 = $(tr).find('input[name=pollQval4]').val();
									selectPoll[idx].pollQval5 = $(tr).find('input[name=pollQval5]').val();
									selectPoll[idx].pollQval6 = $(tr).find('input[name=pollQval6]').val();
									selectPoll[idx].pollQval7 = $(tr).find('input[name=pollQval7]').val();
									selectPoll[idx].pollQval8 = $(tr).find('input[name=pollQval8]').val();
									selectPoll[idx].pollQval9 = $(tr).find('input[name=pollQval9]').val();
									selectPoll[idx].pollQval10 = $(tr).find('input[name=pollQval10]').val();
									
									dataList.push(selectPoll[idx]);
								}
							});
						} else if (crud == 'C') { // 추가 된 데이터
							var newData = new Object();
							newData.pollTitle = pollTitle;
							newData.siteCd = siteCd;
							newData.pollStdt = pollStdt;
							newData.pollEddt = pollEddt;
							newData.dupPartiYn = dupPartiYn;
							newData.fstComYn = fstComYn;
							newData.partiCnt = partiCnt;
							newData.pollQsq = gagajf.isNull(pollQsq) ? '' : pollQsq;
							newData.pollSq = $('#registerForm input[name=pollSq]').val();
							newData.pollQtitle = $(tr).find('input[name=pollQtitle]').val();
							newData.pollQtype = $(tr).find("select[name=pollQtype]").val();
							newData.pollQval1 = $(tr).find('input[name=pollQval1]').val();
							newData.pollQval2 = $(tr).find('input[name=pollQval2]').val();
							newData.pollQval3 = $(tr).find('input[name=pollQval3]').val();
							newData.pollQval4 = $(tr).find('input[name=pollQval4]').val();
							newData.pollQval5 = $(tr).find('input[name=pollQval5]').val();
							newData.pollQval6 = $(tr).find('input[name=pollQval6]').val();
							newData.pollQval7 = $(tr).find('input[name=pollQval7]').val();
							newData.pollQval8 = $(tr).find('input[name=pollQval8]').val();
							newData.pollQval9 = $(tr).find('input[name=pollQval9]').val();
							newData.pollQval10 = $(tr).find('input[name=pollQval0]').val();
							

							dataList.push(newData);
						}

					}); // 태그 끝
					
					if (dataList.length < 1) {
						mcxDialog.alert('저장 할 문항이 없습니다.');
						return;
					}
					if($('#registerForm input[name=stDate]').val() == '' || $('#registerForm input[name=edDate]').val() == '') {
						mcxDialog.alert('투표 참여기간을 설정하세요.');
						return;
					}
					
					var stDate = $('#registerForm input[name=stDate]').val().replaceAll("-", "");
					var edDate = $('#registerForm input[name=edDate]').val().replaceAll("-", "");

					if (Number(stDate) > Number(edDate)) {
						mcxDialog.alert('종료일자는 시작일자 보다 클 수 없습니다.');
						return;
					}

					/* if (Number(stDate) < Number(toDate) && mode == 'N') {
						mcxDialog.alert('시작일자는 오늘포함 이후로 등록해주세요.');
						return;
					} */
					
					if (fstComYn == 'Y') {
						if (partiCnt == '' || partiCnt == null){
							mcxDialog.alert('선착순 인원을 설정하세요.');
							return;
						}
						
					}

					var jsonData = JSON.stringify(dataList);
					gagajf.ajaxJsonSubmit('/marketing/poll/create', jsonData, function() {
						fnReset();
						fnSearch();
					});
					
				}
			});
		} else { // 신규
			mcxDialog.confirm('저장 하시겠습니까?' , {
				cancelBtnText: "취소",
				sureBtnText: "확인",
				sureBtnClick: function() {
					var pollTitle = $('#registerForm input[name=pollTitle]').val();
					var siteCd = $('#registerForm select[name=siteCd]').val();
					var pollStdt = $('#registerForm input[name=stDate]').val() + ' ' + $('#stTimeHour').val() + ':' + $('#stTimeMin').val() + ':' + '00';
					var pollEddt = $('#registerForm input[name=edDate]').val() + ' ' + $('#edTimeHour').val() + ':' + $('#edTimeMin').val() + ':' + '59';
					var dupPartiYn = $('#registerForm select[name=dupPartiYn]').val();
					var fstComYn = $('#registerForm select[name=fstComYn]').val();
					var partiCnt = $('#registerForm input[name=partiCnt]').val();

					$('#questionTable tr').each(function(index, tr) {
						if (index < 1) return;
						var pollQsq = $(tr).find("input[name=pollQsq]").val();

						var newData = new Object();
						newData.pollTitle = pollTitle;
						newData.siteCd = siteCd;
						newData.pollStdt = pollStdt;
						newData.pollEddt = pollEddt;
						newData.dupPartiYn = dupPartiYn;
						newData.fstComYn = fstComYn;
						newData.partiCnt = partiCnt;
						newData.pollQsq = gagajf.isNull(pollQsq) ? '' : pollQsq;
						newData.pollSq = $('#registerForm input[name=pollSq]').val();
						newData.pollQtitle = $(tr).find('input[name=pollQtitle]').val();
						newData.pollQtype = $(tr).find("select[name=pollQtype]").val();
						newData.pollQval1 = $(tr).find('input[name=pollQval1]').val();
						newData.pollQval2 = $(tr).find('input[name=pollQval2]').val();
						newData.pollQval3 = $(tr).find('input[name=pollQval3]').val();
						newData.pollQval4 = $(tr).find('input[name=pollQval4]').val();
						newData.pollQval5 = $(tr).find('input[name=pollQval5]').val();
						newData.pollQval6 = $(tr).find('input[name=pollQval6]').val();
						newData.pollQval7 = $(tr).find('input[name=pollQval7]').val();
						newData.pollQval8 = $(tr).find('input[name=pollQval8]').val();
						newData.pollQval9 = $(tr).find('input[name=pollQval9]').val();
						newData.pollQval10 = $(tr).find('input[name=pollQval10]').val();

						dataList.push(newData);

					}); // 태그 끝
			
					
					if (dataList.length < 1) {
						mcxDialog.alert('저장 할 문항이 없습니다.');
						return;
					}
					if($('#registerForm input[name=stDate]').val() == '' || $('#registerForm input[name=edDate]').val() == '') {
						mcxDialog.alert('투표 참여기간을 설정하세요.');
						return;
					}
					
					var stDate = $('#registerForm input[name=stDate]').val().replaceAll("-", "");
					var edDate = $('#registerForm input[name=edDate]').val().replaceAll("-", "");

					if (Number(stDate) > Number(edDate)) {
						mcxDialog.alert('종료일자는 시작일자 보다 클 수 없습니다.');
						return;
					}

					/* if (Number(stDate) < Number(toDate) && mode == 'N') {
						mcxDialog.alert('시작일자는 오늘포함 이후로 등록해주세요.');
						return;
					}
					 */
					if (fstComYn == 'Y') {
						if (partiCnt == '' || partiCnt == null){
							mcxDialog.alert('선착순 인원을 설정하세요.');
							return;
						}
						
					}
					
					var jsonData = JSON.stringify(dataList);
					gagajf.ajaxJsonSubmit('/marketing/poll/create', jsonData, function() {
						fnReset();
						fnSearch();
					});
				}
			});
		}
	}

	function chkChar(obj){
	    var RegExp = /[\{\}\[\]\/?.,;:|\)*~`!^\-_+┼<>@\#$%&\'\"\\\(\=]/gi;	//정규식 구문
	    if (RegExp.test(obj.value)) {
	      // 특수문자 모두 제거    
	      obj.value = obj.value.replace(RegExp , '');
	    }
  	}
	 
	$('#stTimeHour').on('change', function() {
		$('#stTime').val($(this).val() + ':' + $('#stTimeMin').val() + ':' + '00');
	});

	$('#stTimeMin').on('change', function() {
		$('#stTime').val($('#stTimeHour').val() + ':' + $(this).val() + ':' + '00');
	});

	$('#edTimeHour').on('change', function() {
		$('#edTime').val($(this).val() + ':' + $('#edTimeMin').val() + ':' + '59');
	});

	$('#edTimeMin').on('change', function() {
		$('#edTime').val($('#edTimeHour').val() + ':' + $(this).val() + ':' + '59');
	});

	var fnReset = function() {
		$('#pollSearchForm')[0].reset();
		selectPoll = [];
		$('#registerForm input[name=pollSq]').val('');
		$('#questionTable tr').each(function(index, tr) {

			if (index > 0) {
				$(tr).remove();
			}
		});

	}
	
	// 엑셀다운로드
	$('#btnExcel').on('click', function() {
		gagaAgGrid.exportToExcel('투표자 목록', gridOptionsVote);
	});

	$(document).ready(function() {
		
		// 날짜 셋팅
		cfnCreateCalendar('#terms', 'stDate', 'edDate', false);

		// 그리드 셋팅
		gagaAgGrid.createGrid('gridListPoll', gridOptionsPoll);
		gagaAgGrid.createGrid('gridListVote', gridOptionsVote);

	});


/*]]>*/
</script>

</html>