<!DOCTYPE html>
<html lang="ko"
	xmlns:th="http://www.thymeleaf.org">
<!--
 *******************************************************************************
 * @source  : GoodsContentsForm.html
 * @desc    : 상품 상세 컨텐츠 관리 Page
 *============================================================================
 * STYLE24
 * Copyright(C) 2020 TSIT, All rights reserved.
 *============================================================================
 * VER  DATE         AUTHOR      DESCRIPTION
 * ===  ===========  ==========  =============================================
 * 1.0  2021.07.14   eskim     최초 작성
 *******************************************************************************
 -->
	<div id="main">
		<!-- 메인타이틀 영역 -->
		<div class="main-title">
		</div>
		<!-- //메인타이틀 영역 -->
		
		<!-- 메뉴 설명 -->
		<div class="infoBox menu-desc">
		</div>
		<!-- //메뉴 설명 -->
		
		<!-- 검색조건 영역 -->
		<div class="panelStyle">
			<!-- TITLE -->
			<div class="panelTitle">
				<h3><i class="fa fa-info-circle"></i>아래 검색조건 중 하나를 꼭 입력해 주세요.</h3>
			</div>
			<!-- //TITLE -->
			<form id="searchForm" name="searchForm" action="#" th:action="@{'/goods/contents/list'}" >
				<input type="hidden" id="searchGb" name="searchGb" />
			<div class="panelContent">	
				<table class="frmStyle" aria-describedby="검색조건">
					<colgroup>
						<col width="8%"/>
						<col width="17%"/>
						<col width="8%"/>
						<col width="17%"/>
						<col width="8%"/>
						<col width="17%"/>
						<col width="8%"/>
						<col/>
					</colgroup>
					<tr>
						<th>컨텐츠유형</th>
						<td>
							<select name="goodsContentsType" id="goodsContentsType">
								<option th:if="${goodsContentsTypeList}" th:each="oneData, status : ${goodsContentsTypeList}" th:value="${oneData.cd}" th:text="${'[' + oneData.cd + '] ' + oneData.cdNm}" th:selected="${status.first}"></option>
							</select>
						</td>
						<th>업체</th>
						<td>
							<input type="text" class="w100" name="supplyCompSearchTxt" id="supplyCompSearchTxt" maxlength="20" />
							<button type="button" class="btn icn" id="btnSearchSupplyComp"><i class="fa fa-search"></i></button>
							<span id="supplyCompText"></span>
							<input type="hidden" name="supplyCompList"/>
						</td>
						<th>브랜드</th>
						<td>
							<input type="text" class="w100" name="searchTxt" id="searchTxt" maxlength="20" />
							<button type="button" class="btn icn" id="btnSearchBrand"><i class="fa fa-search"></i></button>
							<span id="brandText"></span>
							<input type="hidden" name="brandList"/>
						</td>
						<th  rowspan="3">키워드</th>
						<td  rowspan="3">
							<select name="search" id="search">
								<option value="searchGoodsCd">상품코드</option>
								<option value="searchGoodsNm">상품명</option>
							</select>
							<textarea class="textareaR3 w60p" name="condition" id="condition"></textarea>
						</td>
					</tr>
					<tr>
						<th>컨텐츠제목</th>
						<td colspan="3">
							<input name="noticeTitle" type="text" maxlength="200"/>
						</td>
						<th>사용여부</th>
						<td>
							<select name="useYn">
								<option value="">[전체]</option>
								<option value="Y">[Y] Yes</option>
								<option value="N">[N] No</option>
							</select>
						</td>
					</tr>
					<tr>
						<th>노출기간</th>
						<td colspan="5" id="sellTerms">
						</td>
					</tr>
				</table>
				<ul class="panelBar">
					<li class="center">
						<button type="button" class="btn btn-gray btn-lg" onclick="$('#searchForm')[0].reset();">초기화</button>
						<button type="button" class="btn btn-base btn-lg" id="btnSearch">조회</button>
					</li>
				</ul>
			</div>	
			</form>
		</div>
		<!-- 검색조건 영역 -->
		<!-- 리스트 영역 -->
		<div class="panelStyle">
			<div id="gridContentsList" style="width: 100%; height: 400px" class="ag-theme-balham"></div>
		</div>
		<!-- //리스트 영역 -->
		<form id="goodsContentsForm" name="goodsContentsForm" action="#" th:action="@{'/goods/contents/save'}">
		<input type="hidden" name="goodsList" />
		<!-- 등록/수정 -->
		<div class="panelStyle" >
			<ul>
				<li>
					<table class="w100p">
						<colgroup>
							<col style="width:65%;"/>
							<col style="width:1%;"/>
							<col/>
						</colgroup>
						<tr>
							<td style="vertical-align:top;">
								<table class="frmStyle" aria-describedby="등록/수정 폼">
									<colgroup>
										<col style="width:10%;"/>
										<col style="width:40%;"/>
										<col style="width:10%;"/>
									</colgroup>
									<tr>
										<th>컨텐츠번호</th>
										<td>
											<input type="text" class="w100" name="goodsContentsSq" placeholder="자동부여" readonly="readonly"/>
										</td>
										<th>컨텐츠유형<i class="required" title="필수"></i></th>
										<td>
											<select name="goodsContentsType" id="goodsContentsType">
												<option th:if="${goodsContentsTypeList}" th:each="oneData, status : ${goodsContentsTypeList}" th:value="${oneData.cd}" th:text="${'[' + oneData.cd + '] ' + oneData.cdNm}" th:selected="${status.first}"></option>
											</select>
										</td>
										
									</tr>
									<tr>	
										<th>노출기간<i class="required" title="필수"></i></th>
										<td>
											<input type="text" class="schDate w100" name="goodsContentsStdt" maxlength="10" th:value="${#calendars.format(#calendars.createNow(), 'yyyy-MM-dd')}"/>
											~
											<input type="text" class="schDate w100" name="goodsContentsEddt" maxlength="10" th:value="${#calendars.format(#calendars.createNow(), 'yyyy-MM-dd')}"/>
										</td>
										<th>사용여부</th>
										<td>
											<input type="hidden" name="useYn"/>
											<label class="chkBox"><input type="checkbox" name="chkUseYn" checked="checked" value="Y"/>사용</label>
										</td>
									</tr>
									<tr>
										<th>제목<i class="required" title="필수"></i></th>
										<td colspan="3">
											<input type="text" name="goodsContentsTitle" required="required" data-valid-name="제목"/>
										</td>
									</tr>
									<tr id="videoArea">
										<th>동영상구분</th>
										<td colspan="3">
											<select name="goodsContentsVideoGubun" id="goodsContentsVideoGubun" data-valid-name="동영상구분">
												<!-- <option value="">[선택]</option> -->
												<option value="Y" selected="selected">[Y] 유투브</option>
												<option value="M">[M] MP4</option>
											</select>
										</td>
									</tr>
									<tr id="youtubeArea">
										<th>동영상URL<em class="required" title="필수"></em></th>
										<td class="infoTxt" colspan="3">
											<em><i class="fa fa-info-circle"></i>유투브의 경우 빨간색 표시로 되어있는 값만 넣으세요.</em><br/>
											예시 : https://www.youtube.com/embed/<em><strong>5YqYG71bQ3s</strong></em>?showinfo=0&amp;rel=0&amp;vp=hd1080&amp;fs=0&amp;wmode=opaque&amp;enablejsapi=1
											<br/>
											<input type="text" class="w400" id="kmcKey" name="kmcKey" maxlength="100" >
											<button type="button" class="btn btn-dark btn-lg" onclick="cfnOpenGoodsVideoPopup('filmVideoView','kmcKey', '#detailForm', $('#videoGb').val());">미리보기</button>
										</td>
									</tr>
									<tr id="videofileArea" style="display:none;">
										<th>파일첨부<em class="required" title="필수"></em></th>
										<td class="infoTxt" colspan="3">
											<div class="uFile w300" id="videoFile">
												<input id="file" name="file" type="file" class="uFileInput w300"/>
												<label for="file" class="uFileLabel">파일선택</label>
												<input type="hidden" name="kufKey"/>
												<input type="hidden" name="kmcKey"/>
											</div>
											<div id="keyArea">미디어키 : <input type="text" class="w200"  name="hkmcKey" disabled> upload키 : <input type="text" class="w200"  name="hkufKey" disabled></div>
											<button type="button" class="btn btn-dark btn-lg" onclick="cfnOpenGoodsVideoPopup('filmVideoView','kmcKey', '#detailForm', $('#videoGb').val());">미리보기</button>
											
										</td>
									</tr>
									<tr id="imgfileArea" style="display:none;">
										<th>파일첨부<em class="required" title="필수"></em></th>
										<td class="infoTxt" colspan="3">
											이미지파일 : <span class="uFile w300" id="imgFile">
												<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="imgPath"/>
												<input type="hidden" name="newImgPath"/>
														</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>
											
										</td>
									</tr>
									<tr id="imglinkArea" style="display:none;">
										<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>
							</td>
							<td>&nbsp;</td>
							<td>
							<ul class="panelBar">
								<li class="left">
									<button type="button" class="btn btn-danger btn-lg" id="btnDeleteContentsGoods">삭제</button>
								</li>
								<li class="right">
									<button type="button" class="btn btn-base btn-lg" id="btnSearchExcel">엑셀조회</button>
									<button type="button" class="btn btn-info btn-lg" id="btnSearchGoods">상품조회</button>
								</li>
							</ul>
							<ul>
								<li id="gridContentsGoodsList" style="width: 100%; height: 450px;" class="ag-theme-balham"></li>
							</ul>
							</td>
						</tr>
					</table>
				</li>
			</ul>
			<!-- 버튼 배치 영역 -->
			<ul class="panelBar">
				<li class="right">
					<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>
		<!-- 등록/수정 -->
		</form>
	</div>

<script th:inline="javascript">
/*<![CDATA[*/
	var videoGbList = {'Y':'유투브', 'M':'MP4'};
	var goodsContentsTypeList = gagajf.convertToArray([[${goodsContentsTypeList}]]);
	var columnContentsDefs = [
		{headerName: 'No', width: 60, cellClass: 'text-center', valueGetter: function(params) { return params.node.rowIndex + 1 }},
		{headerName: "컨텐츠번호", field: "goodsContentsSq", width: 90, cellClass: 'text-center'},
		{headerName: "컨텐츠제목", field: "goodsContentsTitle", width: 250,
			cellRenderer: function(params) { return '<a href="javascript:void(0);">' + params.value + '</a>'; }
		},
		{headerName: "컨텐츠유형", field: "goodsContentsType", width:150, cellClass: 'text-center',
			cellRenderer: function (params) { return !gagajf.isNull(params.value) ? gagaAgGrid.lookupValue(goodsContentsTypeList, params.value) : '';}
		},
		{headerName: "동영상구분", field: "goodsContentsVideoGubun", width:150, cellClass: 'text-center',
			cellRenderer: function (params) { return !gagajf.isNull(params.value) ? gagaAgGrid.lookupValue(videoGbList, params.value) : '';}
		},
		{headerName: "사용여부", field: "useYn", width:90, cellClass: 'text-center'},
		{headerName: "노출시작일", field: "goodsContentsStdt", width:150, cellClass: 'text-center',
			cellRenderer: function(params) { return gagaAgGrid.toDateFormat(params.value); }
		},
		{headerName: "노출종료일", field: "goodsContentsEddt", width:150, cellClass: 'text-center',
			cellRenderer: function(params) { return gagaAgGrid.toDateFormat(params.value); }
		},
		{headerName: "등록자", field: "regNm", width:90, cellClass: 'text-center'},
		{headerName: "등록일자", field: "regDt", width:150, cellClass: 'text-center',
			cellRenderer: function(params) { return gagaAgGrid.toDateFormat(params.value); }
		},
		{headerName: "수정자", field: "updNm", width:90, cellClass: 'text-center'},
		{headerName: "수정일자", field: "updDt", width:150, cellClass: 'text-center',
			cellRenderer: function(params) { return gagaAgGrid.toDateFormat(params.value); }
		}
	];
	
	var columnContentsGoodsDefs = [
		{width: 40, minWidth: 40, cellClass: 'text-center', headerCheckboxSelection: true, checkboxSelection: true, filter: false},
		{headerName: 'No', width: 60, cellClass: 'text-center', valueGetter: function(params) { return params.node.rowIndex + 1 }},
		{headerName: "CRUD", field: "crud", width: 75, minWidth: 75, hide: true},
		{headerName: "상품코드", field: "goodsCd", width: 140, cellClass: 'text-center'},
		{headerName: "상품명", field: "goodsNm", width: 260, cellClass: 'text-left'}
	];

	var gridContentsOptions = gagaAgGrid.getGridOptions(columnContentsDefs);
	var gridContentsGoodsOptions = gagaAgGrid.getGridOptions(columnContentsGoodsDefs);

	gridContentsGoodsOptions.rowSelection = 'multiple';
	gridContentsGoodsOptions.suppressRowClickSelection = true;
	
	// Cell click
	gridContentsOptions.onCellClicked = function(event) {
		$("#btnNew").click();
		if (event.colDef.field != 'goodsContentsTitle')
			return;
		
		$('#goodsContentsForm input[name=goodsContentsSq]').val(event.data.goodsContentsSq);
		$('#goodsContentsForm select[name=goodsContentsType]').val(event.data.goodsContentsType);
		if (event.data.useYn == 'Y') {
			$('#goodsContentsForm input:checkbox[name=chkUseYn]').prop('checked', true);
			$('#goodsContentsForm input:checkbox[name=chkUseYn]').parent("label").addClass("checked");
		} else {
			$('#goodsContentsForm input:checkbox[name=chkUseYn]').prop('checked', false);
			$('#goodsContentsForm input:checkbox[name=chkUseYn]').parent("label").removeClass("checked");
		}
		
		$('#goodsContentsForm input[name=goodsContentsStdt]').val(event.data.goodsContentsStdt);
		$('#goodsContentsForm input[name=goodsContentsEddt]').val(event.data.goodsContentsEddt);
		$('#goodsContentsForm input[name=goodsContentsTitle]').val(event.data.goodsContentsTitle);
		
		
		var contentsImg = event.data.imgPath;
		if(!gagajf.isNull(contentsImg)){
			$('#goodsContentsForm select[name=goodsContentsVideoGubun]').val('').trigger('click');
			$("#goodsContentsForm input[name=imgPath]").val(contentsImg);
			$("#bannerPreViewUrl").attr('src', $("#uploadDefaultUrl").val()+contentsImg);
			$("#imgView").removeClass("off").addClass("on");
			$("#goodsContentsForm input[name=linkUrl]").val(event.data.linkUrl);
			if (event.data.linkTarget == "S"){
				$("#goodsContentsForm input:radio[name=linkTarget]:input[value='S']").trigger('click');
			}else{
				$("#goodsContentsForm input:radio[name=linkTarget]:input[value='N']").trigger('click');
			}
		}else {
			$("#goodsContentsForm input[name=imgPath]").val('');
			$("#bannerPreViewUrl").attr('src', '');
			$("#imgView").removeClass("on").addClass("off");
			
			$('#goodsContentsForm select[name=goodsContentsVideoGubun]').val(event.data.goodsContentsVideoGubun).trigger('click');
			
			if ("Y" == event.data.goodsContentsVideoGubun){
				$('#goodsContentsForm input[name=kmcKey]').val(event.data.kmcKey);
			}else{
				$('#goodsContentsForm input[name=kmcKey]').val(event.data.kmcKey);
				$('#goodsContentsForm input[name=kufKey]').val(event.data.kufKey);
				$('#goodsContentsForm input[name=hkmcKey]').val(event.data.kmcKey);
				$('#goodsContentsForm input[name=hkufKey]').val(event.data.kufKey);
			}
			
		}
		$(".uFileLabel").text('');
		

		// 상품 목록
		fnGetContentsGoodsList(event.data.goodsContentsSq);
	}

	// 검색
	$('#btnSearch').on('click', function() {
		if(!fnConditionCheck()) return;
		gagaAgGrid.fetch($('#searchForm').prop('action'), gridContentsOptions, '#searchForm');
	});
	
	//검색 조건 확인
	var fnConditionCheck = function(){
		var formId = '#searchForm';
		var form = document.searchForm;

		var searchFlag = false;
		var cnt = 0;

		for (i = 0; i < form.elements.length; i++ ) {
			var el = form.elements[i];

			if ($(el).prop("type") == "text" || ($(el).prop("type") == "select-one" && el.name != "search" && el.name != "pageSize")) {
				if (!(el.value == null || el.value == "")) {
					cnt++;
				}
			}
		}
			
		if(cnt > 0) searchFlag = true;

		if(searchFlag == false){
			mcxDialog.alert("검색조건을 입력하세요.");
			return false;
		}
		
		var fromDate = $('#searchForm input[name=stDate]').val();
		var toDate = $('#searchForm input[name=edDate]').val();
		
		if (!gagajf.isNull(fromDate) || !gagajf.isNull(toDate)) {
			
			if (gagajf.isNull(fromDate) || gagajf.isNull(toDate)) {
				mcxDialog.alertC("공지기간 조회시 시작일자와 종료일자를 입력하세요.", {
					sureBtnText: "확인",
					sureBtnClick: function(){
						$('#searchForm input[name=stDate]').focus();
					}
				});
				return false;
			}

			if (fromDate > toDate) {
				mcxDialog.alertC("공지기간 시작일자는 종료일자 보다 클 수 없습니다.", {
					sureBtnText: "확인",
					sureBtnClick: function(){
						$('#goodsContentsForm input[name=stDate]').focus();
					}
				});
				return false;
			} 
		}

		return true;
	}
	
	// 상품 목록 조회
	var fnGetContentsGoodsList = function(goodsContentsSq) {
		var actionUrl = '/goods/contents/goods/list/' + goodsContentsSq;
		gagaAgGrid.fetch(actionUrl, gridContentsGoodsOptions);
	}
	
	// 컨텐츠유형 변경시
	$('#goodsContentsForm select[name=goodsContentsType]').on('change', function() {
		var goodsContentsType = $(this).val();
		//동영상
		if ("G086_1" == goodsContentsType){
			$('#goodsContentsForm select[name=goodsContentsVideoGubun]').val('Y').trigger('click');
/* 			$('#videoArea').show();
			$('#imgfileArea').hide(); */
		}else{
			$('#goodsContentsForm select[name=goodsContentsVideoGubun]').val('').trigger('click');
			/* $('#videoArea').hide();
			$('#videofileArea').hide();
			$('#imgfileArea').show(); */
		}
		
	});
	
	// 동영상구분 변경시
	$('#goodsContentsForm select[name=goodsContentsVideoGubun]').on('click', function() {
	
		fnSetContents();
	});
	
	var fnSetContents = function(){
		var goodsContentsVideoGubun = $('#goodsContentsForm select[name=goodsContentsVideoGubun]').val();
		if ("Y" == goodsContentsVideoGubun){
			$('#videoArea').show();
			$('#youtubeArea').show();
			$('#videofileArea').hide();
			$('#keyArea').hide();
			$('#imgfileArea').hide();
			$('#imglinkArea').hide();
		}else if ("M" == goodsContentsVideoGubun){
			$('#videoArea').show();
			$('#youtubeArea').hide();
			$('#videofileArea').show();
			$('#keyArea').show();
			$('#imgfileArea').hide();
			$('#imglinkArea').hide();
 		}else{
			$('#youtubeArea').hide();
			$('#videofileArea').hide();
			$('#keyArea').hide();
			$('#videoArea').hide();
			$('#imgfileArea').show();
			$('#imglinkArea').show();

		}
	}
	
	// 동영상파일 선택 시
	$('#goodsContentsForm input[name=file]').on('change', function() {
		var file = this.files[0];
		gagaKollus.upload('GoodsDesc', file, $('input[name=kufKey]'));
	});
	
	// 이미지 첨부
	var fnFileUpload = function (obj){
		var file = obj.files[0];
		file.name = 'test';
		if (typeof(file) == 'undefined'){
			return;
		}
		gagajf.ajaxFileUpload('/common/file/upload?subDir=/goodscontents'
				, file
				, function(result) {
					$(obj).closest('div').find('input:hidden[name=imgPath]').val(result.oldFileName);
					$(obj).closest('div').find('input:hidden[name=newImgPath]').val(result.newFileName);
					$("#bannerPreViewUrl").attr('src', $("#uploadDefaultUrl").val()+"/goodscontents/"+result.newFileName);
					$("#imgView").removeClass("off").addClass("on");
				}
		);
	};

	//이미지 클릭시 미리보기
	$("#bannerPreViewUrl").click(function(){
		cfnOpenImagePreViewPopup('bannerPreimgView',$('#bannerPreViewUrl').attr('src'));
	});
	
	
	// 업체 조회 선택시
	$('#btnSearchSupplyComp').on('click', function() {
		cfnOpenCompanyListPopup('fnSetSupplyCompInfo', 'M');
	});
	
	// 업체 조회 팝업에서 호출
	var fnSetSupplyCompInfo = function(result) {
		var arrSupplyComp = [];
		var supplyCompText = "";
		var sIndex = 0;
		$('#searchForm').find('#supplyCompText').html('');
		$('#searchForm input[name=supplyCompSearchTxt]').val('');
		result.forEach(function(supplyComp){
			sIndex++; 
			arrSupplyComp.push(supplyComp.supplyCompCd);
		});

		// 조회값이 하나일 경우 화면에 코드 노출 그외는 갯수 처리 
		if (sIndex == 1) {
			$('#searchForm input[name=supplyCompSearchTxt]').val(arrSupplyComp[0]);
		}else{
			supplyCompText = sIndex + " 개";
			$('#searchForm').find('#supplyCompText').html(supplyCompText);	
		}
		var jsonData = JSON.stringify(arrSupplyComp);
		$("#searchForm input[name=supplyCompList]").val(jsonData);
	}
	
	// 브랜드 조회 팝업에서 호출
	var fnSetBrandInfo = function(result) {
		var arrbrandCd = [];
		var brandText = "";
		var bIndex = 0;
		$('#searchForm').find('#brandText').html('');
		$('#searchForm input[name=searchTxt]').val('');
		result.forEach(function(brand){
			bIndex++; 
			arrbrandCd.push(brand.brandCd);
		});

		// 조회값이 하나일 경우 화면에 코드 노출 그외는 갯수 처리 
		if (bIndex == 1) {
			$('#searchForm input[name=searchTxt]').val(arrbrandCd[0]);
		}else{
			brandText = bIndex + " 개";
			$('#searchForm').find('#brandText').html(brandText);	
		}
		var jsonData = JSON.stringify(arrbrandCd);
		$("#searchForm input[name=brandList]").val(jsonData);
	}
	
	// 브랜드 조회 선택시
	$('#btnSearchBrand').on('click', function() {
		/* if (gagajf.isNull($("#searchForm input[name=searchTxt]").val())){
			mcxDialog.alert('브랜드 검색어를 입력하세요.');
			return false;
		} */
		cfnOpenBrandListPopup('fnSetBrandInfo', 'M');
	});
	
	
	//엑셀 상품 조회
	$('#btnSearchExcel').on('click', function() {
		cfnExcelUploadPopup('goodsContentsExcelUpload', 'goodsContentsExcelUpload');
	});

	var goodsContentsExcelUpload = function(result){
		var data = {procJob : result.procJob
			,excelFileNm : result.excelFileNm
		};
		var jsonData = JSON.stringify(data);
		gagajf.ajaxJsonSubmit('/goods/search/excelupload/save', jsonData, fnGoodsContentsExcelUploadCallBack);
	}
	
	var fnGoodsContentsExcelUploadCallBack = function(result){
		gagajf.ajaxJsonSubmit('/goods/excel/upload/goods/list', '', fnExcelSearchCallBack);
	}
	
	// 상품 엑셀 조회 콜백함수
	var fnExcelSearchCallBack = function(result) {
		if (result.goodsExcelList.length < 1) return;
		var oldData = gagaAgGrid.getAllRowData(gridContentsGoodsOptions);
		$.each(result.goodsExcelList, function(idx, item) {
			var isInvalid = false;
			if (oldData != null && oldData.length != 0){
				oldData.forEach(function(oneData){
					if(oneData.goodsCd == item.goodsCd){
						isInvalid = true;
						return true;
					}
				});
				if(isInvalid){
					return isInvalid;
				}
			}
			gagaAgGrid.addRowData(gridContentsGoodsOptions, {"goodsCd" : item.goodsCd, "goodsNm" : item.goodsNm, "crud" : "C"});
		});
		return;
	};
	
	// 상품 조회 클릭 시
	$('#btnSearchGoods').on('click', function() {
		cfnOpenGoodsPopup('fnSearchCallBack');
	});

	// 상품 조회 콜백함수
	var fnSearchCallBack = function(result) {
		if (result.length < 1) return;
		var oldData = gagaAgGrid.getAllRowData(gridContentsGoodsOptions);
		$.each(result, function(idx, item) {
			var isInvalid = false;
			if (oldData != null && oldData.length != 0){
				oldData.forEach(function(oneData){
					if(oneData.goodsCd == item.goodsCd){
						isInvalid = true;
						return true;
					}
				});
				if(isInvalid){
					return isInvalid;
				}
			}
			gagaAgGrid.addRowData(gridContentsGoodsOptions, {"goodsCd" : item.goodsCd, "goodsNm" : item.goodsNm, "crud" : "C"});
		});
		uifnPopupClose('popupGoods');
		return;
	};
	
	// 상품 삭제
	$('#btnDeleteContentsGoods').on('click', function() {
		
		var selectedData = gridContentsGoodsOptions.api.getSelectedRows();
		if (selectedData.length == 0) {
			mcxDialog.alert('선택된 행이 없습니다.');
			return;
		}
		
		// 신규 상세 공지일경우 화면에서만 삭제
		if (gagajf.isNull($('#goodsContentsForm input[name=goodsContentsSq]').val())){
			var removedData = gagaAgGrid.removeRowData(gridContentsGoodsOptions, false);
			return;
		}
		
		mcxDialog.confirm('삭제하시겠습니까?',  {
			cancelBtnText: "취소",
			sureBtnText: "확인",
			sureBtnClick: function(){
				var removedData = gagaAgGrid.removeRowData(gridContentsGoodsOptions, false);
				var arrGoodsCd = [];
				$.each(selectedData, function(idx, item) {
					arrGoodsCd.push(item.goodsCd);
				});
				
				var data = {arrGoodsCd : arrGoodsCd
							,goodsContentsSq : $('#goodsContentsForm input[name=goodsContentsSq]').val()
			};
			
			var jsonData = JSON.stringify(data);
			gagajf.ajaxJsonSubmit('/goods/contents/goods/delete', jsonData);
			}
		});
	});
	
	// 신규 버튼 클릭
	$("#btnNew").on("click", function(){
		$('#goodsContentsForm')[0].reset();
		
		// 그리드 초기화
		gridContentsGoodsOptions.api.setRowData(null);
		 
		$('#goodsContentsForm input[name=goodsContentsSq]').val('');
		$('#goodsContentsForm input[name=goodsContentsStdt]').val(_today);
		$('#goodsContentsForm input[name=goodsContentsEddt]').val(_today);
		
		$('#goodsContentsForm select[name=goodsContentsVideoGubun]').val('Y').trigger('click');
		$('#videoArea').show();
		$('#imgfileArea').hide();
		$('#imglinkArea').hide();
		$(".uFileLabel").text('');
	});
	
	// 저장
	$("#btnSave").on("click", function() {
		// 날짜 체크
		if (gagajf.isNull($('#goodsContentsForm input[name=goodsContentsStdt]').val())) {
			mcxDialog.alertC('노출 시작일자를 입력해 주세요.', {
				sureBtnText: "확인",
				sureBtnClick: function() {
					$('#goodsContentsForm input[name=goodsContentsStdt]').focus();
				}
			});
			return;
		}

		if (gagajf.isNull($('#goodsContentsForm input[name=goodsContentsEddt]').val())) {
			mcxDialog.alertC('노출 종료일자를 입력해 주세요.', {
				sureBtnText: "확인",
				sureBtnClick: function() {
					$('#goodsContentsForm input[name=goodsContentsEddt]').focus();
				}
			});
			return;
		}
		var stDate = $('#goodsContentsForm input[name=goodsContentsStdt]').val().toDate('YYYY-MM-DD');
		var edDate = $('#goodsContentsForm input[name=goodsContentsEddt]').val().toDate('YYYY-MM-DD');

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

		// validation
		/* if (!gagajf.validation('#goodsContentsForm'))
			return false; */

		if (gagajf.isNull($('#goodsContentsForm input[name=goodsContentsTitle]').val())) {
			mcxDialog.alertC('제목을 입력해 주세요.', {
				sureBtnText: "확인",
				sureBtnClick: function() {
					$('#goodsContentsForm input[name=goodsContentsTitle]').focus();
				}
			});
			return;
		}	
			
		// 이미지 첨부확인
		if ("G086_2" == $('#goodsContentsForm select[name=goodsContentsType]').val() ){
			var orgFileNm = $('#goodsContentsForm input[name=imgPath]').val()
			var imgFileNm = $('#goodsContentsForm input[name=newImgPath]').val();
			if(gagajf.isNull(orgFileNm)){
				if(gagajf.isNull(imgFileNm)){
					mcxDialog.alert('이미지파일을 선택해 주세요.');
					return false;
				}
			}
			
			if(gagajf.isNull($('#goodsContentsForm input[name=linkUrl]').val())){
				mcxDialog.alert('링크 경로를 확인해 주세요. 없을시 #으로 입력해 주세요.');
				return false;
			}
			
		}else{
			
			if ("Y" == $('#goodsContentsForm select[name=goodsContentsVideoGubun]').val() ){
				if (gagajf.isNull($('#goodsContentsForm input[name=kmcKey]').val())){
					mcxDialog.alert('동영상 정보를 확인해 주세요.');
					return false;
				}
				if($('#goodsContentsForm input[name=kmcKey]').val().indexOf("http")>-1){
					mcxDialog.alert('동영상 정보를 확인해 주세요.');
					return;
				}
			}else{
				if (gagajf.isNull($('#goodsContentsForm input[name=kufKey]').val())){
					mcxDialog.alert('동영상 정보를 확인해 주세요.');
					return false;
				}
			}
			
		}	
		
		$('#goodsContentsForm input[name=useYn]').val($('#goodsContentsForm input:checkbox[name=chkUseYn]').is(":checked") ? 'Y' : 'N');

		mcxDialog.confirm('저장하시겠습니까?', {
			cancelBtnText: "취소",
			sureBtnText: "확인",
			sureBtnClick: function(){
				
				var imgPath = $('#goodsContentsForm input[name=imgPath]').val();
				var newImgPath = $('#goodsContentsForm input[name=newImgPath]').val();
				var linkUrl = $('#goodsContentsForm input[name=linkUrl]').val();
				var linkTarget = $('#goodsContentsForm input[name=linkTarget]:checked').val();
				var kmcKey = $('#goodsContentsForm input[name=kmcKey]').val();
				var kufKey = $('#goodsContentsForm input[name=kufKey]').val();
				if ("G086_1" == $('#goodsContentsForm select[name=goodsContentsType]').val()){
					imgPath = "";
					newImgPath = "";
					linkUrl = "";
					linkTarget = "";
				}else{
					kmcKey = "";
					kufKey = "";
				}
				
				//var goodsAllData = gagaAgGrid.getAllRowData(gridContentsGoodsOptions);
				var goodsAllData = gagaAgGrid.getChangedData(gridContentsGoodsOptions);
				
				var jsonGoodsData = JSON.stringify(goodsAllData);
				$('#goodsContentsForm input[name=goodsList]').val(jsonGoodsData);
				
				var data = {
						goodsContentsSq : $('#goodsContentsForm input[name=goodsContentsSq]').val()
						,goodsContentsType : $('#goodsContentsForm select[name=goodsContentsType]').val()
						,goodsContentsTitle : $('#goodsContentsForm input[name=goodsContentsTitle]').val()
						,goodsContentsStdt : $('#goodsContentsForm input[name=goodsContentsStdt]').val()
						,goodsContentsEddt : $('#goodsContentsForm input[name=goodsContentsEddt]').val()
						,goodsContentsVideoGubun : $('#goodsContentsForm select[name=goodsContentsVideoGubun]').val()
						,useYn : $('#goodsContentsForm input[name=useYn]').val()
						,imgPath : imgPath
						,newImgPath : newImgPath
						,linkUrl : linkUrl
						,linkTarget : linkTarget
						,kmcKey : kmcKey
						,kufKey : kufKey
						,goodsList : $('#goodsContentsForm input[name=goodsList]').val()
					};
				
				var jsonData = JSON.stringify(data);
				gagajf.ajaxJsonSubmit($('#goodsContentsForm').prop('action'), jsonData, function() {
					$('#btnSearch').trigger('click');
					$("#btnNew").trigger('click');
					//fnGetContentsGoodsList($('#goodsContentsForm input[name=goodsContentsSq]').val());
					
				});
			}
		});
	});
	
	$(document).ready(function() {
		
		cfnCreateCalendar('#sellTerms', 'stDate', 'edDate', true, '공지일', 'X');
		
		// Create a agGrid
		gagaAgGrid.createGrid('gridContentsList', gridContentsOptions);
		gagaAgGrid.createGrid('gridContentsGoodsList', gridContentsGoodsOptions);
		

		
	});
	
/*]]>*/
</script>

</html>
