<!DOCTYPE html>
<html lang="ko"
	xmlns:th="http://www.thymeleaf.org">
<!--
 *******************************************************************************
 * @source  : PopupListForm.html
 * @desc    : 팝업관리 Page
 *============================================================================
 * STYLE24
 * Copyright(C) 2020 TSIT, All rights reserved.
 *============================================================================
 * VER  DATE         AUTHOR      DESCRIPTION
 * ===  ===========  ==========  =============================================
 * 1.0  2021.3.3     bin2107     최초 작성
 *******************************************************************************
 -->
	<div id="main">
		<!-- 메인타이틀 영역 -->
		<div class="main-title">
		</div>
		<!-- //메인타이틀 영역 -->
		
		<!-- 메뉴 설명 -->
		<div class="infoBox menu-desc">
		</div>
		<!-- //메뉴 설명 -->
		
		<!-- 검색조건 영역 -->
		<form id="searchForm" name="searchForm" action="#" th:action="@{'/display/popup/list'}" onsubmit="$('#btnSearch').trigger('click'); return false;">
			<div class="panelStyle">
				<table class="frmStyle">
					<colgroup>
						<col style="width:10%;"/>
						<col style="width:15%;"/>
						<col style="width:10%;"/>
						<col style="width:15%;"/>
						<col style="width:10%;"/>
						<col style="width:40%;"/>
					</colgroup>
					<tr>
						<th>사이트</th>
						<td>
							<select name="siteCd">
								<option th:if="${siteCdList}" th:each="oneData, status : ${siteCdList}" th:value="${oneData.cd}" th:text="${'[' + oneData.cd + '] ' + oneData.cdNm}"></option>
							</select>
						</td>
						<th>전시화면</th>
						<td>
							<select name="frontGb">
								<option value="">전체</option>
								<option value="P">PC</option>
								<option value="M">모바일</option>
							</select>
						</td>
						<th>전시기간</th>
						<td colspan="5" id="sellTerms">
							<span class="nowrap">
								<input name="dispStdt" id="schStDate" type="text" class="w80 schDate" maxlength="10" required="required" data-valid-name="노출기간 시작일" />
								<select id="schStTimeHour" 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="schStTimeMin" 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="schStTime" type="hidden" data-valid-name="노출기간 시작시간" value='000000' />
								~
								<input name="dispEddt" id="schEdDate" type="text" class="w80 schDate" maxlength="10" required="required" data-valid-name="노출기간 종료일" />
								<select id="schEdTimeHour" 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="schEdTimeMin" 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="schEdTime" type="hidden" data-valid-name="노출기간 종료시간" value='235959' />
							</span>
						</td>
					</tr>
				</table>
				<ul class="panelBar">
					<li class="center">
						<button type="button" class="btn btn-default btn-lg" id="btnInit">초기화</button>
						<button type="button" class="btn btn-base btn-lg" id="btnSearch">조회</button>
					</li>
				</ul>
			</div>
		<!-- 검색조건 영역 -->

		<!-- 리스트 영역 -->
		<div class="panelStyle">
			<!-- 상단영역 START -->
			<ul class="panelBar">
				<li>
					<span style="padding:5.5px 15px; background:#e9ecfb !important; border-top:1px solid #ddd; border-bottom:0.5px solid #dae0fd; font-weight: bold;">미리보기</span>
					<!-- <select name="viewPage" id="viewPageView" onchange="fnChangeViewPage('View')" >
						<option th:if="${viewPageList}" th:each="oneData, status : ${viewPageList}" th:value="${oneData.cd}" th:text="${'[' + oneData.cd + '] ' + oneData.cdNm}"></option>
					</select> -->
					<select name="cateNo" id="cateNoView" class='off' data-valid-name="대카테고리">
						<option value="">[선택]</option>
						<option th:if="${cateNoList}" th:each="oneData, status : ${cateNoList}" th:value="${oneData.cd}" th:text="${'[' + oneData.cd + '] ' + oneData.cdNm}"></option>
					</select>
					<input type="text" class="off w80" name="brandCd" id="brandCdView" placeholder="브랜드그룹번호" required="required" data-valid-name="브랜드"/>
					<button type="button" class="off btn btn-base btn-lg" id="searchBrandGroupView" onclick="fnBrandGroupSearch('View')">브랜드 조회</button>
					<input type="text" class="off w80" name="planSq" id="planSqView" placeholder="기획전번호" required="required" data-valid-name="기획전번호"/>
					<button type="button" class="off btn btn-base btn-lg" id="btnSearchPlanView" onclick="fnPlanSearch('View')">기획전 조회</button>
					<span class="nowrap">
						<input name="viewDate" id="viewDate" type="text" class="w80 schDate" maxlength="10" required="required" data-valid-name="미리보기일자" />
						<select id="viewTimeHour" name="viewTimeHour" required="required" data-valid-name="미리보기 시간">
							<option value="" >시간</option>
							<th:block th:each="num, index  : ${#numbers.sequence(0,24)}">
								<option  th:value="${#numbers.formatInteger(num,2)}" th:text="|${#numbers.formatInteger(num,2)}시|" th:selected="${num == 9}">시간</option>
							</th:block>
						</select>
						<select id="viewTimeMin" name="viewTimeMin" required="required" data-valid-name="미리보기 시간">
							<option value="" >분</option>
							<th:block th:each="num: ${#numbers.sequence(0,59)}">
								<option  th:value="${#numbers.formatInteger(num,2)}"  th:text="|${#numbers.formatInteger(num,2)}분|" th:selected="${num == 0}">분</option>
							</th:block>
						</select>
						<input name="viewTime" id="viewTime" type="hidden" data-valid-name="미리보기 시간" />
					</span>
					<span>
						<button type="button" class="btn btn-info btn-lg" id="btnView">미리보기</button>
					</span>
				</li>
				<li class="right">
					<span class="btnRight">
						<button type="button" class="btn btn-success btn-lg" id="btnReg">적용</button>
					</span>
					<span class="btnRight">
						<button type="button" class="btn btn-danger btn-lg" id="btnDel">삭제</button>
					</span>
					검색결과 : <strong><span id="gridRowTotalCount">0</span> 건</strong>&nbsp;
					쪽번호 <span id="pgNo">0</span>/ <strong id="endPgNo">0</strong>&nbsp;&nbsp;
					<select id="pageSize" name="pageSize">
						<option value="50" selected="selected">50개씩 보기</option>
						<option value="100">100개씩 보기</option>
						<option value="500">500개씩 보기</option>
					</select>
					<input type="hidden" name="pageNo" id="pageNo" value ="1"/>
				</li>
			</ul>
			<!-- 상단영역 END -->
			<div id="gridList" style="width: 100%; height: 470px" class="ag-theme-balham"></div>

			<ul class="panelBar">
				<li class="center">
					<div class="tablePaging" id="popupListPagination"></div>
				</li>
			</ul>
		</div>
		<!-- //리스트 영역 -->
		</form>
		
		<!-- 등록/수정 -->
		<div class="panelStyle">
			<form id="detailForm" name="detailForm" action="#" th:action="@{'/display/popup/save'}">
				<input type="hidden" name="popupGb" value="W"/>	<!--팝업종류-->
				<input type="hidden" name="unexpDays" value="1"/>	<!--미노출일수-->
				<table class="frmStyle">
					<colgroup>
						<col style="width:8%;"/>
						<col style="width:25%;"/>
						<col style="width:8%;"/>
						<col style="width:25%;"/>
						<col style="width:8%;"/>
						<col/>
					</colgroup>
					<tr>
						<th>팝업일련번호</th>
						<td>
							<input type="text" class="w90" name="popupSq" placeholder="자동생성" data-valid-name="팝업일련번호" disabled/>
						</td>
						<th>사이트코드<i class="required" title="필수"></i></th>
						<td class="infoTxt">
							<select name="siteCd">
								<option th:if="${siteCdList}" th:each="oneData, status : ${siteCdList}" th:value="${oneData.cd}" th:text="${'[' + oneData.cd + '] ' + oneData.cdNm}"></option>
							</select>
						</td>
						<th>전시위치<i class="required" title="필수"></i></th>
						<td>
							<select name="viewPage" id="viewPage" onchange="fnChangeViewPage('')" data-valid-name="전시위치">
								<option th:if="${viewPageList}" th:each="oneData, status : ${viewPageList}" th:value="${oneData.cd}" th:text="${'[' + oneData.cd + '] ' + oneData.cdNm}"></option>
							</select>
							<select name="cateNo" id="cateNo" class='off' data-valid-name="대카테고리">
								<option value="">[선택]</option>
								<option th:if="${cateNoList}" th:each="oneData, status : ${cateNoList}" th:value="${oneData.cd}" th:text="${'[' + oneData.cd + '] ' + oneData.cdNm}"></option>
							</select>
							<input type="text" class="off w80" name="brandCd" id="brandCd" placeholder="브랜드그룹번호" data-valid-name="브랜드그룹번호"/>
							<button type="button" class="off btn btn-base btn-lg" id="searchBrandGroup"  onclick="fnBrandGroupSearch('')">브랜드 조회</button>
							<input type="text" class="off w80" name="planSq" id="planSq" placeholder="기획전번호" data-valid-name="기획전번호"/>
							<button type="button" class="off btn btn-base btn-lg" id="btnSearchPlan"  onclick="fnPlanSearch('')">기획전 조회</button>
						</td>
					</tr>
					<tr>
						<th>PC/모바일 구분<i class="required" title="필수"></i></th>
						<td>
							<select name="frontGb" id="frontGb">
								<option value="P">[P] PC</option>
								<option value="M">[M] 모바일</option>
							</select>
						</td>
						<th>우선순위<i class="required" title="필수"></i></th>
						<td>
							<input type="text" class="w90" name="dispOrd" id="dispOrd" required="required" data-valid-type=numeric data-valid-name="우선순위"/>
						</td>
						<th>팝업구분<i class="required" title="필수"></i></th>
						<td>
							<label class="rdoBtn"><input type="radio" name="popupGb" id="popupGbF" value="F" checked="checked" />Full</label>
							<label class="rdoBtn"><input type="radio" name="popupGb" id="popupGbH" value="H"/>Half</label>
							<strong class="cBlue">* PC팝업은 팝업구분 상관없이 Full입니다.</strong>
						</td>
					</tr>
					<tr>
						<th>노출시작일시<i class="required" title="필수"></i></th>
						<td colspan="5">
							<input name="dispStdt" id="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="dispEddt" id="edDate" type="text" class="w80 schDate" maxlength="10" required="required" data-valid-name="노출종료일자" />
							<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>
					</tr>
					<tr>
						<th>이미지<i class="star"></i></th>
						<td colspan="3">
						
							<div id="ImageArea">
								이미지파일 : <span class="uFile w300">
												<input id="file_1" name="file" type="file" class="uFileInput w300"  data-valid-name="이미지파일" onchange="fnFileUpload(this);"/>
												<label for="file_1" class="uFileLabel">파일선택</label>
												<input type="hidden" name="orgFileNm"/>
												<input type="hidden" name="sysFileNm"/>
												<input type="hidden" name="newSysFileNm"/>
											</span>
								&nbsp;&nbsp;&nbsp;&nbsp;LINK : <input type="text" class="w400" name="linkUrl"  maxlength="300" required="required" data-valid-name="LINK" value="#"/>
								<input type="hidden" name="uploadDefaultUrl" id="uploadDefaultUrl" th:value="${@environment.getProperty('upload.image.view')}"/>
								<span id="imgView" class="off">
									<img id="bannerPreViewUrl" src="" style="width:100px"/>
								</span>
							</div>
						</td>
						<th>링크새창구분<i class="required" title="필수"></i></th>
						<td>
							<label class="rdoBtn"><input type="radio" name="linkTarget" id="linkTargetS" value="S" checked="checked" />본창</label>
							<label class="rdoBtn"><input type="radio" name="linkTarget" id="linkTargetN" value="N"/>새창</label>
						</td>
					</tr>
				</table>
			</form>
			
			<!-- 버튼 배치 영역 -->
			<ul class="panelBar">
				<li class="center">
					<button type="button" class="btn btn-info btn-lg" id="btnNew">신규</button>
					<button type="button" class="btn btn-success btn-lg" id="btnSave">저장</button>
				</li>
			</ul>
			<!-- //버튼 배치 영역 -->
		</div>
		<!-- 등록/수정 -->
	</div>

<script type="text/javascript" src="/ux/plugins/gaga/gaga.paging.js?v=2019072202"></script>
<script th:inline="javascript">
/*<![CDATA[*/
	var siteCdList = [[${siteCdList}]];
	var viewPageList = [[${viewPageList}]];
	var cateNoList = [[${cateNoList}]];

	var imgDivLen = 1;	//이미지 추가 액션수관리

	let columnDefs = [
		{width: 40, minWidth: 40, cellClass: 'text-center', headerCheckboxSelection: true, checkboxSelection: true, filter: false},
		{headerName: "팝업일련번호", field: "popupSq", width: 100, cellClass: 'text-center'
			,cellRenderer: function(params) {
				return '<a href="javascript:void(0);">' + params.value + '</a>';
			}
		},
		{headerName: "적용여부", field: "displayYn", width: 80, cellClass: 'text-center'},
		{headerName: "전시위치", field: "viewPage", width: 150, cellClass: 'text-center'
			,valueFormatter: function (params) { return !gagajf.isNull(params.value) ? "["+params.value+"] "+params.data.viewPageNm : '';}
		},
		{headerName: "카테고리", field: "cateNo", width: 130, cellClass: 'text-center'},
		{headerName: "브랜드", field: "brandCd", width: 130, cellClass: 'text-center'},
		{headerName: "기획전번호", field: "planSq", width: 130, cellClass: 'text-center'},
		{headerName: "PC/모바일", field: "frontGb", width: 100, cellClass: 'text-center'
			,valueFormatter: function(params) {
				if (params.data.frontGb == 'A') {
					return '전체';
				}else if(params.data.frontGb == 'P'){
					return 'PC';
				}else{
					return '모바일';
				}
			}
		},
		{headerName: "팝업구분", field: "popupGb", width: 100, cellClass: 'text-center'
			,valueFormatter: function(params) {
				if (params.data.popupGb == 'F') {
					return 'Full';
				}else{
					return 'Half';
				}
			}
		},
		{headerName: "우선순위", field: "dispOrd", width: 100, cellClass: 'text-center'},
		{headerName: "전시시작일", field: "dispStdt", width: 100, cellClass: 'text-center'},
		{headerName: "전시시작시간", field: "dispStTime", width: 100, cellClass: 'text-center'},
		{headerName: "전시종료일", field: "dispEddt", width: 100, cellClass: 'text-center'},
		{headerName: "전시종료시간", field: "dispEdTime", width: 100, cellClass: 'text-center'},
		{headerName: "등록자", field: "regNm", width: 150, cellClass: 'text-center'},
		{headerName: "등록일시", field: "regDt", width: 150, cellClass: 'text-center'}
	];

	let gridOptions = gagaAgGrid.getGridOptions(columnDefs);
	gridOptions.rowSelection = "multiple";

	// ROW Click
	gridOptions.onCellClicked = function(event) {
		var popupSq = event.data.popupSq;
		if (event.colDef.field == "popupSq"){
			$("#btnNew").click();
			var formId = '#detailForm';
			$(formId + " input[name=popupSq]").val(event.data.popupSq);
			$(formId + " select[name=siteCd]").val(event.data.siteCd);
			$(formId + " select[name=viewPage]").val(event.data.viewPage);
			fnChangeViewPage('');
			$(formId + " select[name=cateNo]").val(event.data.cateNo).attr("selected", true);
			$(formId + " input[name=brandCd]").val(event.data.brandCd);
			$(formId + " input[name=planSq]").val(event.data.planSq);
			$(formId + " select[name=frontGb]").val(event.data.frontGb);
			if (event.data.popupGb == "F"){
				$(formId + " input:radio[name=popupGb]:input[value='F']").trigger('click');
			}else{
				$(formId + " input:radio[name=popupGb]:input[value='H']").trigger('click');
			}
			$(formId + " input[name=unexpDays]").val(event.data.unexpDays);
			if (event.data.linkTarget == "S"){
				$(formId + " input:radio[name=linkTarget]:input[value='S']").trigger('click');
			}else{
				$(formId + " input:radio[name=linkTarget]:input[value='N']").trigger('click');
			}
			$(formId + " input[name=dispOrd]").val(event.data.dispOrd);
			var dispStdt = event.data.dispStdt.replace(/[^0-9]/g, '');
			$(formId + " input[name=dispStdt]").val(dispStdt.substr(0,4)+"-"+dispStdt.substr(4,2)+"-"+dispStdt.substr(6,2));
			var dispStTime = event.data.dispStTime.replace(/[^0-9]/g, '');
			$("#stTime").val(dispStTime);
			$("#stTimeHour").val(dispStTime.substr(0,2));
			$("#stTimeMin").val(dispStTime.substr(2,2));
			var dispEddt = event.data.dispEddt.replace(/[^0-9]/g, '');
			$(formId + " input[name=dispEddt]").val(dispEddt.substr(0,4)+"-"+dispEddt.substr(4,2)+"-"+dispEddt.substr(6,2));
			var dispEdTime = event.data.dispEdTime.replace(/[^0-9]/g, '');
			$("#edTime").val(dispEdTime);
			$("#edTimeHour").val(dispEdTime.substr(0,2));
			$("#edTimeMin").val(dispEdTime.substr(2,2));
			
			$(formId + " input[name=linkUrl]").val(event.data.linkUrl1);
			
			var popupImg = event.data.imgUrl1;
			if(!gagajf.isNull(popupImg)){
				$(formId + " input[name=orgFileNm]").val(popupImg);
				$(formId + " input[name=sysFileNm]").val(popupImg);
				$("#bannerPreViewUrl").attr('src', $("#uploadDefaultUrl").val()+popupImg);
				$("#imgView").removeClass("off").addClass("on");
			}else {
				$(formId + " input[name=orgFileNm]").val('');
				$(formId + " input[name=sysFileNm]").val('');
				$("#bannerPreViewUrl").attr('src', '');
				$("#imgView").removeClass("on").addClass("off");
				
			}
			$(".uFileLabel").text('');
		}
	}

	/**
	 * 조회
	 */
	$('#btnSearch').on('click', function (){
		
		if (!gagajf.isNull($("#searchForm input[name=dispStdt]").val()) || !gagajf.isNull($("#searchForm input[name=dispEddt]").val())){
			
			if (gagajf.isNull($("#searchForm input[name=dispStdt]").val()) || gagajf.isNull($("#searchForm input[name=dispEddt]").val())){
				mcxDialog.alertC("전시기간 조회시 시작일자와 종료일자를 입력하세요.", {
					sureBtnText: "확인",
					sureBtnClick: function() {
						$('#searchForm input[name=dispStdt]').focus();
					}
				});
				return false;
			}
			
		
			var fromDate = $("#searchForm input[name=dispStdt]").val().replaceAll('-', '')+ $("#searchForm select[name=schStTimeHour]").val()+ $("#searchForm select[name=schStTimeMin]").val();
			var toDate = $("#searchForm input[name=dispEddt]").val().replaceAll('-', '')+ $("#searchForm select[name=schEdTimeHour]").val()+ $("#searchForm select[name=schEdTimeMin]").val();
	
			if (fromDate > toDate) {
				mcxDialog.alertC("전시기간의 시작일시는 종료일시 보다 클 수 없습니다.", {
					sureBtnText: "확인",
					sureBtnClick: function() {
						$('#searchForm input[name=dispStdt]').focus();
					}
				});
				return false;
			}
		}
		
		
		$("#searchForm input[name=dispStTime]").val($('#searchForm #schStTimeHour').val()+$('#searchForm #schStTimeMin').val()+'00');
		$("#searchForm input[name=dispEdTime]").val($('#searchForm #schEdTimeHour').val()+$('#searchForm #schEdTimeMin').val()+'59');
		fnSearch();
	});

	var fnSearch = function(){
		gagaPaging.init('searchForm', fnSearchCallBack, 'popupListPagination', $('#searchForm').find('#pageSize').val());
		gagaPaging.load(1);
	};

	var fnSearchCallBack = function(result){
		$('#searchForm').find('#gridRowTotalCount').html(result.pageing.pageable.totalCount.addComma());
		$('#searchForm').find('#pageNo').val(result.pageing.pageable.pageNo.addComma());
		$('#searchForm').find('#pgNo').html(result.pageing.pageable.pageNo.addComma());
		$('#searchForm').find('#endPgNo').html(result.pageing.pageable.totalPage.addComma());
		gridOptions.api.setRowData(result.popupList);
		gagaPaging.createPagination(result.pageing.pageable);
	}

	// 미리보기위치 선택
	var fnChangeViewPage = function(sub){
		if($("#viewPage"+sub).val()=="G037_30"){
			$("#cateNo"+sub).removeClass("off").addClass("on");
			$("#brandCd"+sub).removeClass("on").addClass("off");
			$("#searchBrandGroup"+sub).removeClass("on").addClass("off");
			$("#planSq"+sub).removeClass("on").addClass("off");
			$("#btnSearchPlan"+sub).removeClass("on").addClass("off");
		}else if($("#viewPage"+sub).val()=="G037_31"){
			$("#cateNo"+sub).removeClass("on").addClass("off");
			$("#brandCd"+sub).removeClass("off").addClass("on");
			$("#searchBrandGroup"+sub).removeClass("off").addClass("on");
			$("#planSq"+sub).removeClass("on").addClass("off");
			$("#btnSearchPlan"+sub).removeClass("on").addClass("off");
		}else if($("#viewPage"+sub).val()=="G037_40"){
			$("#cateNo"+sub).removeClass("on").addClass("off");
			$("#brandCd"+sub).removeClass("on").addClass("off");
			$("#searchBrandGroup"+sub).removeClass("on").addClass("off");
			$("#planSq"+sub).removeClass("off").addClass("on");
			$("#btnSearchPlan"+sub).removeClass("off").addClass("on");
		}else{
			$("#cateNo"+sub).removeClass("on").addClass("off");
			$("#brandCd"+sub).removeClass("on").addClass("off");
			$("#searchBrandGroup"+sub).removeClass("on").addClass("off");
			$("#planSq"+sub).removeClass("on").addClass("off");
			$("#btnSearchPlan"+sub).removeClass("on").addClass("off");
		}
		$("#cateNo"+sub).val('');
		$("#brandCd"+sub).val('');
		$("#planSq"+sub).val('');
	};

	// 검색조건 초기화
	$('#btnInit').on('click', function() {
		$("#searchForm")[0].reset();
		gagajf.setDate('schStDate', 'schEdDate', 't');
	});

	// 신규 버튼 클릭
	$("#btnNew").on("click", function(){
		$("#detailForm")[0].reset();
		$("#ImageAddArea").empty();
		$("#linkUrl").val('#');
		$('#detailForm input[name=imgUrl]').val('');
		$('#detailForm input[name=imgUrl]').closest('div').find('label').text('파일선택');
		//$('#detailForm #imgFileNm1').html('');
		$('#detailForm input[name=orgFileNm]').val('');
		$('#detailForm input[name=sysFileNm]').val('');
		$('#detailForm input[name=newSysFileNm]').val('');
		$("#cateNo").removeClass("on").addClass("off");
		$("#searchBrandGroup").removeClass("on").addClass("off");
		$('#detailForm input[name=brandCd]').removeClass("on").addClass("off");
		$("#btnSearchPlan").removeClass("on").addClass("off");
		$('#detailForm input[name=planSq]').removeClass("on").addClass("off");
		$(".uFileLabel").text('');
		$("#imgView").removeClass("on").addClass("off");
		imgDivLen = 1;
	});

	// 미리보기
	$("#btnView").on("click", function(){
		if($("#viewDate").val()==""){
			mcxDialog.alert("미리보기 일시를 입력해 주세요")
			return;
		}
		
		var selectRowData = gagaAgGrid.selectedRowData(gridOptions);
		
		if (selectRowData.length == 0) {
			mcxDialog.alert('미리보기 할 팝업을 선택하세에요.');
			return;
		}else if (selectRowData.length > 1) {
			mcxDialog.alert('미리보기 할 팝업만 선택하세에요.');
			return;
		}
		
		var viewPage = selectRowData[0].viewPage;
		var cateNo = selectRowData[0].cateNo;
		var brandCd = selectRowData[0].brandCd;
		var planSq = selectRowData[0].planSq;
		
		var uriMap = new Map();
		uriMap.set("G037_10", "/display/mall/main/form?");
		uriMap.set("G037_20", "/display/mall/main/form?");
		uriMap.set("G037_30", "/display/category/main/form?cateGb=G032_101&cate1No="+cateNo);
		uriMap.set("G037_31", "/display/brand/main/form?brandGroupNo="+brandCd);
		uriMap.set("G037_32", "/display/outlet/main/form?cateGb=G032_103");
		uriMap.set("G037_40", "/planning/detail/form?planSq="+planSq);
		_mall = [[${@environment.getProperty('domain.front')}]];
		window.open("about:blank").location.href= _mall + uriMap.get(viewPage) + "&viewPage=" + viewPage + "&preview=Y&viewDt="+$("#viewDate").val().replace(/-/gi, '')+$("#viewTimeHour").val()+$("#viewTimeMin").val()+"00";
	});
	
	
	// 데이터 validation 체크
	function dataValidation(){
		// 날짜체크
		var fromDate = $('#detailForm input[name=dispStdt]').val().replace(/[^0-9]/g, '')+$('#detailForm #stTimeHour').val()+$('#detailForm #stTimeMin').val();
		var toDate = $('#detailForm input[name=dispEddt]').val().replace(/[^0-9]/g, '')+$('#detailForm #edTimeHour').val()+$('#detailForm #edTimeMin').val();
		if(fromDate > toDate){
			mcxDialog.alert('노출 시작일자는 종료일자 보다 클 수 없습니다.');
			return false;
		}

		//전시위치 체크(30,31,40)
		var selectViewPage = $('#detailForm select[name=viewPage]').val();

		if(selectViewPage=='G037_30'){
			if(gagajf.isNull($('#detailForm select[name=cateNo]').val())){
				mcxDialog.alert('카테고리를 선택해 주세요.');
				return false;
			}
		}else if(selectViewPage=='G037_31'){
			if(gagajf.isNull($('#detailForm input[name=brandCd]').val())){
				mcxDialog.alert('브랜드 코드를 입력해 주세요.');
				return false;
			}
		}else if(selectViewPage=='G037_40'){
			if(gagajf.isNull($('#detailForm input[name=planSq]').val())){
				mcxDialog.alert('기획전 번호를 입력해 주세요.');
				return false;
			}
		}

		var orgFileNm = $('#detailForm input[name=sysFileNm]').val()
		var imgFileNm = $('#detailForm input[name=newSysFileNm]').val();
		if(gagajf.isNull(orgFileNm)){
			if(gagajf.isNull(imgFileNm)){
				mcxDialog.alert('이미지파일을 선택해 주세요.');
				return false;
			}
		}

		return true;
	}

	// 이미지 첨부
	var fnFileUpload = function (obj){
		var file = obj.files[0];
		file.name = 'test';
		if (typeof(file) == 'undefined'){
			return;
		}
		gagajf.ajaxFileUpload('/common/file/upload?subDir=/popup'
				, file
				, function(result) {
					$(obj).closest('div').find('input:hidden[name=sysFileNm]').val(result.oldFileName);
					$(obj).closest('div').find('input:hidden[name=newSysFileNm]').val(result.newFileName);
					$("#bannerPreViewUrl").attr('src', $("#uploadDefaultUrl").val()+"/popup/"+result.newFileName);
					$("#imgView").removeClass("off").addClass("on");
				}
		);
	};

	//이미지 클릭시 미리보기
	$("#bannerPreViewUrl").click(function(){
		cfnOpenImagePreViewPopup('bannerPreimgView',$('#bannerPreViewUrl').attr('src'));
	});
	
	/**
	 * 저장
	 */
	$("#btnSave").on('click',function(){
		// 필수값 validation 체크
		if (!gagajf.validation('#detailForm')) {
			return false;
		}

		// 데이터 validation 체크
		if(!dataValidation()){
			return false;
		}

		// 이미지 파일 체크
		var imgUrl = '';
		var orgFileNm = $('#detailForm input[name=orgFileNm]').val();
		var sysFileNm = $('#detailForm input[name=sysFileNm]').val();
		var newSysFileNm = $('#detailForm input[name=newSysFileNm]').val();

		var fromDate = $('#detailForm input[name=dispStdt]').val().replace(/[^0-9]/g, '')+$('#detailForm #stTimeHour').val()+$('#detailForm #stTimeMin').val()+'00';
		var toDate = $('#detailForm input[name=dispEddt]').val().replace(/[^0-9]/g, '')+$('#detailForm #edTimeHour').val()+$('#detailForm #edTimeMin').val()+'59';

		var popupGb = $('#detailForm input[name=popupGb]:checked').val();
		var linkTarget = $('#detailForm input[name=linkTarget]:checked').val();
		
		var data = {
			popupSq : $('#detailForm input[name=popupSq]').val()
			,popupGb : popupGb
			,siteCd : $('#detailForm select[name=siteCd]').val()
			,viewPage : $('#detailForm select[name=viewPage]').val()
			,cateNo : $('#detailForm select[name=cateNo]').val()
			,brandCd : $('#detailForm input[name=brandCd]').val()
			,planSq : $('#detailForm input[name=planSq]').val()
			,frontGb : $('#detailForm select[name=frontGb]').val()
			,unexpDays : $('#detailForm input[name=unexpDays]').val()
			,linkTarget : linkTarget
			,dispOrd : $('#detailForm input[name=dispOrd]').val()
			,dispStdt : fromDate
			,dispEddt : toDate
			,orgFileNm : orgFileNm
			,sysFileNm : sysFileNm
			,newSysFileNm : newSysFileNm
			,linkUrl1 : $('#detailForm input[name=linkUrl]').val()
			,useYn : 'Y'
		};

		var jsonData = JSON.stringify(data);

		gagajf.ajaxJsonSubmit($('#detailForm').prop('action'), jsonData, fnPopupSaveCollback);
	});

	var fnPopupSaveCollback = function (result){
		$("#btnNew").click();
		$('#btnSearch').trigger('click');
	}

	// 브랜드 조회
	var formNm = "";
	var fnBrandGroupSearch = function(sub){
		if(!gagajf.isNull(sub)){
			formNm = "searchForm";
		}else{
			formNm = "detailForm";
		}
		cfnOpenBrandGroupListPopup("callBackBrandGroup", "S", "S");
	}

	var callBackBrandGroup = function(result){
		$("#"+formNm+" input[name=brandCd]").val(result[0].brandGroupNo);
	}

	// 기획전 조회
	var planFormNm = "";
	var fnPlanSearch = function (sub){
		if(!gagajf.isNull(sub)){
			planFormNm = "searchForm";
		}else{
			planFormNm = "detailForm";
		}
		cfnOpenPlanPopup("callBackPlan");
	}

	var callBackPlan = function (result){
		$("#"+planFormNm+" input[name=planSq]").val(result[0].planSq);
	}

	/**
	 * 삭제
	 */
	$("#btnDel").on('click',function(){
		var selectRowData = gagaAgGrid.selectedRowData(gridOptions);
		if (selectRowData.length > 0) {
			mcxDialog.confirm('삭제하시겠습니까?', {
				cancelBtnText: "취소",
				sureBtnText: "확인",
				sureBtnClick: function(){
					var selectDataArr = [];
					$.each(selectRowData, function(idx, item) {
						selectDataArr.push(item.popupSq);
					});

					var data = {
						selectDataArr : selectDataArr
					};

					var jsonData = JSON.stringify(data);
					gagajf.ajaxJsonSubmit('/display/popup/delete', jsonData, fnPopupSaveCollback);
				}
			});
		}else{
			mcxDialog.alert('선택된 행이 없습니다.');
			return;
		}
	});

	/**
	 * 적용
	 */
	$("#btnReg").on('click',function(){
		var selectRowData = gagaAgGrid.selectedRowData(gridOptions);
		if (selectRowData.length > 0) {
			mcxDialog.confirm('적용하시겠습니까?', {
				cancelBtnText: "취소",
				sureBtnText: "확인",
				sureBtnClick: function(){
					var selectDataArr = [];
					$.each(selectRowData, function(idx, item) {
						selectDataArr.push(item.popupSq);
					});

					var data = {
						selectDataArr : selectDataArr
					};

					var jsonData = JSON.stringify(data);
					gagajf.ajaxJsonSubmit('/display/popupfront/save', jsonData, fnPopupSaveCollback);
				}
			});
		}else{
			mcxDialog.alert('프론트에 적용할 행을 선택해주세요.');
			return;
		}
	});
	
	$(document).ready(function() {
		// Create a agGrid
		gagaAgGrid.createGrid('gridList', gridOptions);
	});
/*]]>*/
</script>

</html>
