<!DOCTYPE html>
<html lang="ko"
	xmlns:th="http://www.thymeleaf.org">
<!--
 *******************************************************************************
 * @source  : MainListForm.html
 * @desc    : 메인전시관리 Page
 *============================================================================
 * STYLE24
 * Copyright(C) 2020 TSIT, All rights reserved.
 *============================================================================
 * VER  DATE         AUTHOR      DESCRIPTION
 * ===  ===========  ==========  =============================================
 * 1.0  2021.2.22    bin2107     최초 작성
 *******************************************************************************
 -->
	<div id="main">
		<!-- 메인타이틀 영역 -->
		<div class="main-title">
		</div>
		<!-- //메인타이틀 영역 -->
		
		<!-- 메뉴 설명 -->
		<div class="infoBox menu-desc">
		</div>
		<!-- //메뉴 설명 -->
		
		<!-- 검색조건 영역 START -->
		<div class="panelStyle">
			<form id="searchForm" name="searchForm" action="#">
				<table class="frmStyle">
<!--					<colgroup>-->
<!--						<col style="width: 25%;"/>-->
<!--						<col style="width: 25%;"/>-->
<!--						<col style="width: 25%;"/>-->
<!--						<col style="width: 25%;"/>-->
<!--					</colgroup>-->
					<tr>
						<th>대분류</th>
						<td>
							<select name="cate1No" id="cate1No" onchange="fnGetMainDisplayList('cate1');">
								<option value="">[선택]</option>
								<option th:if="${mainCategoryList}" th:each="oneData, status:${mainCategoryList}" th:value="${oneData.cateNo+','+oneData.leafYn}" th:text="${'['+oneData.cateNo+']'+oneData.cateNm}"></option>
							</select>
						</td>
						<th>중분류</th>
						<td name="cate2Select" style="display:block;">
							<select name="cate2No" id="cate2No" onchange="fnGetMainDisplayList('cate2');">
								<option value="">[선택]</option>
							</select>
						</td>
						<td name="cate2Search" style="display:none;">
							<input type="text" class="w200" name="brandGroupNo" value="" />
							<button type="button" class="btn btnRight btn-success btn-lg" onclick="fnSearchBrandGroup();">브랜드조회</button>
						</td>
					</tr>
				</table>
			</form>
		</div>
		<!-- 검색조건 영역 END -->

		<!-- 리스트 영역 START -->
		<div class="panelStyle">
			<div class="boxTitle"></div>
			<form id="mainDisplayForm">
				<ul class="boxContent">
					<li class="boxContentTop">
						<div class="panelContent" style="overflow: hidden;">
							<th:block th:if="${sessionInfo.roleCd == 'G001_0000'}">
								<ul class="panelBar">
									<li>
										<span class="btnLeft" style="">
											<span style="padding:5.5px 15px; background:#d8eafc !important; border-top:1px solid #ddd; border-bottom:0.5px solid #dae0fd; font-weight: bold;">추가 열</span>
											<select id="addColCnt" required="required">
												<th:block th:each="num: ${#numbers.sequence(1,10)}">
												<option th:value="${num}"  th:text="${num}"></option>
												</th:block>
											</select>
											<button type="button" class="btn btn-base btn-lg" id="btnAddRow">행 추가</button>
										</span>
									</li>
									<li class="right">
										<span class="btnRight" style="">
											<span><button type="button" class="btn btn-success btn-lg" id="btnSave">레이아웃 저장</button></span>
										</span>
									</li>
								</ul>
							</th:block>
							<ul class="panelBar">
								<th:block th:if="${sessionInfo.roleCd == 'G001_0000'}">
									<li>
										<span class="cBlue">* 마우스 드래그&드랍으로 레이아웃 순서 변경 가능하며 X 버튼으로 삭제 가능합니다.</span>
									</li>
								</th:block>
								<li id="viewUl" class="off aC">
									<span>
										<input name="viewDate" id="viewDate" type="text" class="w80 schDate" maxlength="10" data-valid-name="미리보기일자" data-valid-type="calendar"/>
										<select id="viewTimeHour" name="viewTimeHour" data-valid-name="미리보기 시간">
											<th:block th:each="num, index  : ${#numbers.sequence(0,24)}">
											<option  th:value="${#numbers.formatInteger(num,2)}" th:text="|${#numbers.formatInteger(num,2)}시|" >시간</option>
											</th:block>
										</select>
										<select id="viewTimeMin" name="viewTimeMin" 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="viewTime" id="viewTime" type="hidden" data-valid-name="미리보기 시간" />
										<input type="hidden" name="uploadDefaultUrl" id="uploadDefaultUrl" th:value="${@environment.getProperty('upload.image.view') + '/mainLayout/'}"/>
									</span>
									<span>
										<button type="button" class="btn btn-info btn-lg" id="btnView">미리보기</button>
										<button type="button" class="btn btn-default btn-lg" id="btnAllUpd">일괄적용</button>
									</span>
								</li>
								<th:block th:if="${sessionInfo.roleCd == 'G001_0000'}">
									<li class="right">
										<span class="cRed">* 레이아웃 저장 버튼 클릭 시 수정 및 삭제 된 레이아웃이 즉시 적용 됩니다.</span><br/>
										<span class="cRed">* 화면 캡처파일 관리는 SUPER관리자, 어드민관리자만 가능합니다.</span>
									</li>
								</th:block>
							</ul>
						</div>
						<table class="frmStyle" id="mainSortable">
							<tbody>
								<tr style="height:150px;">
									<td colspan="8" style="text-align: center">
										<span>카테고리를 선택해 주세요.</span>
									</td>
								</tr>
							</tbody>
						</table>
					</li>
				</ul>
			</form>
		</div>
		<!-- 리스트 영역 END -->
	</div>

<script th:inline="javascript">
/*<![CDATA[*/
	var roleCd = [[${sessionInfo.roleCd}]];
	var tdWidth = 800;
	//var mainCategoryList = [[${mainCategoryList}]];
	var brandCdList = [[${brandCdList}]];
	var contentsLocArr = gagajf.convertToArray([[${contentsLocList}]]);

	/**
	* 대분류/중분류 선택시
	*/
	var fnGetMainDisplayList = function (cate){
		if(cate=='cate1'){
			var cate1Val = $("#searchForm select[name=cate1No] option:selected").val().split(',')[0];		//1700,Y

			if((!gagajf.isNull(cate1Val)&&cate1Val=='1711') || (!gagajf.isNull(cate1Val)&&cate1Val=='1721')){
				$("#searchForm").find("td[name=cate2Select]").css('display','none');
				$("#searchForm").find("td[name=cate2Search]").css('display','block');
			}else{
				$("#searchForm").find("td[name=cate2Select]").css('display','block');
				$("#searchForm").find("td[name=cate2Search]").css('display','none');
				$("#searchForm").find("td[name=cate2Search]").find("input[name=brandGroupNo]").val('');
				$("#searchForm select[name=cate2No]").html('<option value="">[선택]</option>');
			}
		}
		$("#viewUl").addClass("off");
		var val = $("#searchForm select[name=cate1No]").val();
		if(gagajf.isNull(val)||val.split(',')[0]=='0'){
			var html = '<tbody><tr style="height:170px;"><td colspan="8" style="text-align:center;"><span>카테고리를 선택해 주세요</span></td></tr></tbody>';
			$("#mainSortable").html(html);
		}else{
			$("#mainSortable").html('');
			if(val.split(',')[1]=='N' && gagajf.isNull($("#searchForm select[name=cate2No]").val())){
				$("#searchForm select[name=cate2No]").html('<option value="">[선택]</option>');
				var data = {
					cateNo : val.split(',')[0]
					,clsLvl : 2
				};
				var jsonData = JSON.stringify(data);
				gagajf.ajaxJsonSubmit('/display/main/category/list', jsonData, fnCate2NoCallBack);
			}else{
				$("#viewUl").removeClass("off");
				var cateNo = "";
				var brandGroupNo = "";
				var cate1Val = $("#searchForm select[name=cate1No] option:selected").val().split(',')[0];		//1700,Y
				/*if((!gagajf.isNull(cate1Val)&&cate1Val=='1711') || (!gagajf.isNull(cate1Val)&&cate1Val=='1721')){
					cateNo = $("#searchForm").find("td[name=cate2Search]").find("input[name=brandGroupNo]").val();
				}else{
					cateNo = val.split(',')[0];
					if(!gagajf.isNull($("#searchForm select[name=cate2No]").val())){
						cateNo = $("#searchForm select[name=cate2No]").val().split(',')[0];
					}
				}*/
				cateNo = val.split(',')[0];
				if(!gagajf.isNull($("#searchForm select[name=cate2No]").val())){
					cateNo = $("#searchForm select[name=cate2No]").val().split(',')[0];
				}
				if((!gagajf.isNull(cate1Val)&&cate1Val=='1711') || (!gagajf.isNull(cate1Val)&&cate1Val=='1721')){
					cateNo = $("#searchForm select[name=cate1No] option:selected").val().split(',')[0];
					brandGroupNo = $("#searchForm").find("td[name=cate2Search]").find("input[name=brandGroupNo]").val();
				}
				
				/*else{
					var data = {
						cateNo : cateNo
					};
				}*/
				var data = {
					cateNo : cateNo
					, brandGroupNo : brandGroupNo
				};

				console.log('cateNo::'+cateNo);
				console.log('brandGroupNo::'+brandGroupNo);

				var jsonData = JSON.stringify(data);
				// 레이아웃 조회 로직
				gagajf.ajaxJsonSubmit('/display/main/layout/list', jsonData, fnLayoutCallBack);
			}
		}
	}

	var fnSearchBrandGroup = function (){
		cfnOpenBrandGroupListPopup("fnCallBackBrandGroup", "S", "S");
	}

	var fnCallBackBrandGroup = function (result){
		$("#searchForm").find("td[name=cate2Search]").find("input[name=brandGroupNo]").val(result[0].brandGroupNo);
		fnGetMainDisplayList('cate2');
	}

	/**
	 * 레이아웃 조회
	 */
	var fnLayoutCallBack = function (result){
		var html = '';
		var imgSrc = '';
		var orgFileNm = '';
		var sysFileNm = '';
		var onOff = 'off';
		var cate1No = $("#searchForm select[name=cate1No]").val().split(',')[0];

		for(var i=0; i<result.length; i++){
			var colCnt = result[i].colCnt;
			var colNo = result[i].colNo
			var colspan = parseInt(5/Number(colCnt), 10);
			var colspanAdd = 5 - (colspan * colCnt);
			var tdSize = 10;

			if(colCnt>5){
				tdSize = parseInt((colCnt/2), 10)+1;
				colspan = parseInt(5/(colCnt/2), 10);
				colspanAdd = 5 - (colspan * parseInt((colCnt/2), 10));
			}

			if(colCnt==1 || colNo==1){
				html += '<tbody><tr style="height:170px;">\n';
			}else if(colNo==tdSize){
				html += '<tr style="height:170px;">\n';
			}

			if(colNo>=tdSize){
				colspanAdd = (5 - (colspan * Math.round(colCnt/2))) + parseInt(colCnt/2, 10);
			}
			html += '<td colspan="';
			colspanAdd -= (colNo-1);
			if(colspanAdd>0){
				html += colspan + 1;
			}else{
				html += colspan;
			}

			let maxWidth = parseInt(tdWidth/Number(colCnt), 10);
			if(maxWidth == 0){
				maxWidth = 800;
			}
			// if(colCnt>5){
			// 	maxWidth = parseInt(tdWidth/(Number(colCnt)/tdSize), 10);
			// }
			html += '" style="text-align:center; max-width:'+maxWidth+'px;">\n';
			html += '<div><span style="font-weight:bold">'+result[i].contentsLoc+'</span></div><div><span>[ '+gagaAgGrid.lookupValue(contentsLocArr, result[i].contentsLoc)+' ]</span></div>\n';
			html += '<input type="text" class="w200" name="contentsTitle" placeholder="메인타이틀" value="'+result[i].contentsTitle+'"/>\n';
			html += '<br/>\n';
			if(result[i].contentsYn=='C' || result[i].contentsYn=='A'){
				html += '<button type="button" class="btn btn-success btn-lg" onclick="fnChangeContents(this);">수정</button>\n';
				html += '<button type="button" class="btn btn-default btn-lg" onclick="fnUpdateContents(\''+result[i].contentsLoc+'\');">적용</button>\n';
			}else if(result[i].contentsYn=='G'){
				// if(result[i].contentsYn=='A'){
				// 	html += '<button type="button" class="btn btn-success btn-lg" onclick="fnChangeContents(this);">수정</button>';
				// 	html += '<button type="button" class="btn btn-default btn-lg" onclick="fnUpdateContents(\''+result[i].contentsLoc+'\');">적용</button>';
				// 	html += '<br/>';
				// }
					html += '<button type="button" class="btn btn-success btn-lg" onclick="fnSearchCategory(\''+result[i].contentsLoc+'\');">상품관리</button>\n';
			}else{
				html += '<li>위치설정</li>\n';
			}
			html += '<input type="hidden" name="contentsLoc" value="'+result[i].contentsLoc+'"/>\n';
			html += '<input type="hidden" name="colCnt" value="'+result[i].colCnt+'"/>\n';
			html += '<input type="hidden" name="colNo" value="'+result[i].colNo+'"/>\n';
			html += '<input type="hidden" name="contentsYn" value="'+result[i].contentsYn+'"/>\n';
			html += '</td>\n';

			if(colNo=='1'){
				if(result[i].orgFileNm!=null && result[i].orgFileNm!='null' && result[i].orgFileNm!="" ){
					orgFileNm = result[i].orgFileNm;
					sysFileNm = result[i].sysFileNm;
					imgSrc = $("#uploadDefaultUrl").val()+orgFileNm;
					onOff = 'on';
				}else{
					orgFileNm = '';
					sysFileNm = '';
					imgSrc = '';
					onOff = 'off';
				}
			}
			if(tdSize==10){
				if(colCnt==1 || colNo==colCnt){
					html += '<td name="imgTd" style="width:300px;">\n';
					html += '<div id="imgView_'+i+'" class="'+onOff+'">\n';
					html += '<img id="bannerPreViewUrl_'+i+'" src="'+imgSrc+'" style="width:300px; height:120px"  onclick="cfnOpenImagePreViewPopup(\'bannerPreimgViewPop\',\''+imgSrc+'\');"/>\n';
					html += '</div>\n';
					// SUPER관리자,어드민관리자만 파일관리 가능
					if(roleCd=='G001_0000' || roleCd=='G001_A000'){
						html += '<div class="uFile w300">\n';
						html += '<input id="file_'+i+'" name="file" type="file" class="uFileInput w300" onchange="fnFileUpload(this, '+i+');"/>\n';
						html += '<label for="file_'+i+'" class="uFileLabel">파일선택</label>\n';
						html += '<input type="hidden" name="orgFileNm" value="'+orgFileNm+'"/>\n';
						html += '<input type="hidden" name="sysFileNm" value="'+sysFileNm+'"/>\n';
						html += '<input type="hidden" name="newSysFileNm" value=""/>\n';
						html += '</div>\n';
					}
					html += '</td>\n';
					html += '<td name="deleteTd" style="max-width:50px;">\n';
					if(roleCd=='G001_0000'){
						html += '<button type="button" class="btn icn" onclick="fnDeleteRow(this);"><i class="fa fa-times" aria-hidden="true"></i></button>\n';
					}
					html += '</td></tr></tbody>\n';
				}
			}else{
				if(colNo==(tdSize-1)){
					html += '<td name="imgTd" rowspan="2" style="width:300px;">\n';
					html += '<div id="imgView_'+i+'" class="'+onOff+'">\n';
					html += '<img id="bannerPreViewUrl_'+i+'" src="'+imgSrc+'" style="width:300px; height:120px"  onclick="cfnOpenImagePreViewPopup(\'bannerPreimgViewPop\',\''+imgSrc+'\');"/>\n';
					html += '</div>\n';
					// SUPER관리자,어드민관리자만 파일관리 가능
					if(roleCd=='G001_0000' || roleCd=='G001_A000'){
						html += '<div class="uFile w300">\n';
						html += '<input id="file_'+i+'" name="file" type="file" class="uFileInput w300" onchange="fnFileUpload(this, '+i+');"/>\n';
						html += '<label for="file_'+i+'" class="uFileLabel">파일선택</label>\n';
						html += '<input type="hidden" name="orgFileNm" value="'+orgFileNm+'"/>\n';
						html += '<input type="hidden" name="sysFileNm" value="'+sysFileNm+'"/>\n';
						html += '<input type="hidden" name="newSysFileNm" value=""/>\n';
						html += '</div>\n';
					}
					html += '</td>\n';
					html += '<td name="deleteTd" rowspan="2" style="max-width:50px;">\n';
					if(roleCd=='G001_0000'){
						html += '<button type="button" class="btn icn" onclick="fnDeleteRow(this);"><i class="fa fa-times" aria-hidden="true"></i></button>\n';
					}
					html += '</td></tr>\n';
				}else if(colNo==colCnt){
					html += '</tr></tbody>\n';
				}
			}
		}

		$("#mainSortable").html(html);
		if(roleCd=='G001_0000'){
			$("#mainSortable").sortable();
		}
	}

	/**
	 * 중분류 리스트
	 */
	var fnCate2NoCallBack = function (result){
		var html = '<option value="">[선택]</option>\n';
		for (var i=0; i<result.length; i++){
			html += '<option value="'+result[i].cateNo+','+result[i].leafYn+'">['+result[i].cateNo+']'+result[i].cateNm+'</option>\n';
		}
		$("#searchForm select[name=cate2No]").html(html);
		// grid 높이 조절
		//uifnFitGrid();
	}

	var fnTest = function (obj,idx){
		var $obj = $(obj);
		var index = $("#contentsBox"+idx+" option").index($("#contentsBox"+idx+" option:selected"));
		var contentsType = $("#contentsBox"+idx+" option:eq("+index+")").attr('data-idx');
		console.log(index);
		console.log(contentsType);
		// var dataSelect = document.getElementsByName("contentsLocEdit");
		// var value = dataSelect.options[document.getElementsByName("contentsLocEdit").selectedIndex].value;
		// $("select[name=contentsLocEdit]").val();
		console.log($(obj).val());
		// $("#id").val("1").prop("selected", true);
		$("#contentsYn"+idx).val(contentsType).prop('selected',true);
	}

	/**
	* 레이아웃 행추가 버튼
	*/
	let contentsIdx = 0;
	$("#btnAddRow").on("click", function (){
		var val = $("#searchForm select[name=cate1No]").val();
		var cate1No = val.split(',')[0];
		//console.log('val>>'+val);
		//console.log('cate1No>>'+cate1No);
		//console.log('leafYn>>>'+val.split(',')[1]);

		if(gagajf.isNull(val) || cate1No=='0' || val.split(',')[1]=='N' && gagajf.isNull($("#searchForm select[name=cate2No]").val())){
			mcxDialog.alert('카테고리를 선택해 주세요.');
			return;
		}

		var html = '';
		var colCnt = $("#addColCnt").val();
		var colspan = parseInt(5/Number(colCnt), 10);
		var tdSize = 10;
		if(colCnt>5){
			tdSize = parseInt(colCnt/2, 10) + 1;
			colspan = parseInt(5/parseInt(colCnt/2, 10), 10);
		}
		var contentsLocHtml = '<option value="">[선택]</option>';
		var contentsLocList = [[${contentsLocList}]];
		var clocPrefix ='';
		var mainCategoryList = [[${mainCategoryList}]];

		$.each(mainCategoryList, function(idx, data) {
			if(cate1No==data.cateNo){
				clocPrefix = data.clocPrefix;
			}
		});

		if(cate1No=='1700'){
			contentsLocHtml += '<option value="SGNB001" data-idx="C">[SGNB001] STYLE24MALL > GNB > TOP배너</option>';
			contentsLocHtml += '<option value="SGNB002" data-idx="C">[SGNB002] STYLE24MALL > GNB > TOP배너(모바일)</option>';
			contentsLocHtml += '<option value="STAB001" data-idx="C">[STAB001] STYLE24MALL > GNB > 브랜드</option>';
			contentsLocHtml += '<option value="STAB002" data-idx="C">[STAB002] STYLE24MALL > GNB > 카테고리</option>';
			contentsLocHtml += '<option value="SKEY001" data-idx="C">[SKEY001] STYLE24MALL > GNB > 검색어</option>';
		}
		if(cate1No=='1720'){
			contentsLocHtml += '<option value="SGNB002" data-idx="C">[SGNB002] STYLE24MALL > GNB > TOP배너(모바일)</option>';
			contentsLocHtml += '<option value="STAB001" data-idx="C">[STAB001] STYLE24MALL > GNB > 브랜드</option>';
			contentsLocHtml += '<option value="STAB002" data-idx="C">[STAB002] STYLE24MALL > GNB > 카테고리</option>';
			contentsLocHtml += '<option value="SKEY001" data-idx="C">[SKEY001] STYLE24MALL > GNB > 검색어</option>';
		}
		for(var i=0; i<contentsLocList.length; i++){
			var contentsLocCd = contentsLocList[i].cd;
			contentsLocCd = contentsLocCd.replace(/[0-9]/g, "");
			if(contentsLocCd==clocPrefix){
				if(cate1No=='1700'){
					if(contentsLocList[i].cd != 'SMM012'){
						contentsLocHtml += '<option value="'+contentsLocList[i].cd+'" data-idx="'+contentsLocList[i].cdDesc+'">['+contentsLocList[i].cd+'] '+contentsLocList[i].cdNm+'</option>';
					}
				}else if(cate1No=='1720'){
					if(contentsLocList[i].cd != 'SMM009'){
						contentsLocHtml += '<option value="'+contentsLocList[i].cd+'" data-idx="'+contentsLocList[i].cdDesc+'">['+contentsLocList[i].cd+'] '+contentsLocList[i].cdNm+'</option>';
					}
				}else{
					contentsLocHtml += '<option value="'+contentsLocList[i].cd+'" data-idx="'+contentsLocList[i].cdDesc+'">['+contentsLocList[i].cd+'] '+contentsLocList[i].cdNm+'</option>';
				}
			}
		}

		for(var j=0; j<colCnt; j++){
			var colNo = (j+1);
			var colspanAdd = 5 - (colspan * colCnt);
			var maxWidth = parseInt(tdWidth/Number(colCnt), 10);
			if(colCnt>5){
				maxWidth = parseInt(tdWidth/(Number(colCnt)/tdSize), 10);
				colspanAdd = 5 - (colspan * parseInt(colCnt/2, 10));
			}
			if(colCnt==1 || colNo==1){
				html += '<tbody><tr style="height:170px;">';
			}else if(colNo==tdSize){
				html += '<tr style="height:170px;">';
			}
			if(colNo>=tdSize){
				colspanAdd = (5 - (colspan * Math.round(colCnt/2))) + parseInt(colCnt/2, 10);
			}
			html += '<td colspan="';
			colspanAdd -= j;
			if(colspanAdd>0){
				html += colspan + 1;
			}else{
				html += colspan;
			}

			html += '" style="text-align:center; max-width:'+maxWidth+'px;">';
			html += '<div>';
			html += '<select name="contentsLocEdit" id="contentsBox'+contentsIdx+'" required="required" style="max-width:300px;" data-valid-name="컨텐츠 위치" onchange="fnTest(this,'+contentsIdx+');">'+contentsLocHtml+'</select>';
			html += '</div>';
			html += '<select name="contentsYn" id="contentsYn'+contentsIdx+'" required="required" style="max-width:160px;" data-valid-name="컨텐츠 타입" disabled="disabled"><option value="C">[C] 컨텐츠</option><option value="G">[G] 상품</option><option value="A">[A] 컨텐츠 + 상품</option><option value="E">[E] 위치설정</option></select>';
			html += '<input type="hidden" name="contentsLoc" value=""/>';
			html += '<input type="hidden" name="colCnt" value="'+colCnt+'"/>';
			html += '<input type="hidden" name="colNo" value="'+colNo+'"/>';
			html += '<input type="hidden" name="contentsYn" value=""/>';
			html += '<input type="text" class="w200" name="contentsTitle" placeholder="메인타이틀" value=""/>';
			html += '</td>';

			var i = $("#mainSortable tbody").length;
			if(tdSize==10){
				if(colCnt==1 || colNo==colCnt){
					html += '<td name="imgTd" style="width:300px;">';
					// SUPER관리자,어드민관리자만 파일관리 가능
					if(roleCd=='G001_0000' || roleCd=='G001_A000'){
						html += '<div class="uFile w300">';
						html += '<input id="file_'+i+'" name="file" type="file" class="uFileInput w300" onchange="fnFileUpload(this, '+i+');"/>';
						html += '<label for="file_'+i+'" class="uFileLabel">파일선택</label>';
						html += '<input type="hidden" name="orgFileNm"/>';
						html += '<input type="hidden" name="sysFileNm"/>';
						html += '<input type="hidden" name="newSysFileNm"/>';
						html += '</div>';
					}
					html += '<div id="imgView_'+i+'" class="off">';
					html += '<img id="bannerPreViewUrl_'+i+'" src="" style="width:300px; height:120px"/>';
					html += '</div>';
					html += '</td>';
					html += '<td name="deleteTd" style="max-width:50px;">';
					if(roleCd=='G001_0000'){
						html += '<button type="button" class="btn icn" onclick="fnDeleteRow(this);"><i class="fa fa-times" aria-hidden="true"></i></button>';
					}
					html += '</td></tr><tbody>';
				}
			}else{
				if(colNo==(tdSize-1)){
					html += '<td name="imgTd" rowspan="2" style="width:300px;">';
					// SUPER관리자,어드민관리자만 파일관리 가능
					if(roleCd=='G001_0000' || roleCd=='G001_A000'){
						html += '<div class="uFile w300">';
						html += '<input id="file_'+i+'" name="file" type="file" class="uFileInput w300" onchange="fnFileUpload(this, '+i+');"/>';
						html += '<label for="file_'+i+'" class="uFileLabel">파일선택</label>';
						html += '<input type="hidden" name="orgFileNm"/>';
						html += '<input type="hidden" name="sysFileNm"/>';
						html += '<input type="hidden" name="newSysFileNm" value=""/>';
						html += '</div>';
					}
					html += '<div id="imgView_'+i+'" class="off">';
					html += '<img id="bannerPreViewUrl_'+i+'" src="" style="width:300px; height:120px"/>';
					html += '</div>';
					html += '</td>';
					html += '<td name="deleteTd" rowspan="2" style="max-width:50px;">';
					if(roleCd=='G001_0000'){
						html += '<button type="button" class="btn icn" onclick="fnDeleteRow(this);"><i class="fa fa-times" aria-hidden="true"></i></button>';
					}
					html += '</td></tr>';
				}else if(colNo==colCnt){
					html += '</tr></tbody>';
				}
			}
		}
		$("#mainSortable").prepend(html);
		if(roleCd=='G001_0000'){
			$("#mainSortable").sortable();
		}
		//uifnFitGrid();
		contentsIdx ++;
	});

	/**
	* 레이아웃 행 삭제
	*/
	var fnDeleteRow = function (obj){
		$(obj).closest("tbody").remove();
	}

	function fnCate2BrandCheck(){
		var cateBrand = $("#searchForm").find("td[name=cate2Search]").find("input[name=brandGroupNo]").val();
		if(gagajf.isNull(cateBrand)){
			mcxDialog.alert('브랜드코드를 조회해주세요.');
			return false;
		}

		return true;
	}

	/**
	 * 레이아웃 저장
	 */
	$("#btnSave").on("click",function(){
		var val = $("#searchForm select[name=cate1No]").val();
		if(gagajf.isNull(val) || (val.split(',')[1]=='N' && gagajf.isNull($("#searchForm select[name=cate2No]").val())) ){
			mcxDialog.alert('카테고리를 선택해 주세요.');
			return;
		}
		if(!gagajf.validation("#mainDisplayForm")){
			return;
		}
		var cateNo = '';
		var cateNm = '';
		var brandGroupNo = '';
		if(val.split(',')[1]=='Y'){
			cateNo = val.split(',')[0];
		}else{
			cateNo = $("#searchForm select[name=cate2No]").val().split(',')[0];
		}

		if(cateNo == '1711' || cateNo == '1721'){
			if(!fnCate2BrandCheck()){
				return false;
			}
			brandGroupNo = $("#searchForm").find("td[name=cate2Search]").find("input[name=brandGroupNo]").val();
		}

		var dataArr = [];
		var contentLocArr = [];
		var contentLocCheck = true;

		$("#mainSortable tbody").each(function(ind){

			var orgFileNm = $(this).find('input:hidden[name="orgFileNm"]').val();
			var sysFileNm = $(this).find('input:hidden[name="sysFileNm"]').val();
			var newSysFileNm = $(this).find('input:hidden[name="newSysFileNm"]').val();
			$(this).find('td').each(function(index){
				if($(this).attr("name")!="imgTd" && $(this).attr("name")!="deleteTd"){
					if($(this).find('input:hidden[name="contentsLoc"]').val()==''){
						if(contentLocArr.indexOf($(this).find('select[name="contentsLocEdit"]').val())>-1){
							$(this).find('select[name="contentsLocEdit"]').focus();
							contentLocCheck = false;
							return;
						}else{
							$(this).find('input:hidden[name="contentsLoc"]').val($(this).find('select[name="contentsLocEdit"]').val());
							contentLocArr.push($(this).find('input:hidden[name="contentsLoc"]').val());
						}
					}else{
						if(contentLocArr.indexOf($(this).find('input:hidden[name="contentsLoc"]').val())>-1){
							contentLocCheck = false;
							return;
						}else{
							contentLocArr.push($(this).find('input:hidden[name="contentsLoc"]').val());
						}
					}
					if($(this).find('input:hidden[name="contentsYn"]').val()==''){
						$(this).find('input:hidden[name="contentsYn"]').val($(this).find('select[name="contentsYn"]').val());
					}
					var data = {cateNo : cateNo
						, contentsLoc : $(this).find('input:hidden[name="contentsLoc"]').val()
						, colCnt : $(this).find('input:hidden[name="colCnt"]').val()
						, colNo : $(this).find('input:hidden[name="colNo"]').val()
						, contentsYn : $(this).find('input:hidden[name="contentsYn"]').val()
						, dispOrd : (ind+1)
						, orgFileNm : orgFileNm
						, sysFileNm : sysFileNm
						, newSysFileNm : newSysFileNm
						, brandGroupNo : brandGroupNo
						, contentsTitle : $(this).find('input[name="contentsTitle"]').val()
					};
					dataArr.push(data);
				}
			});
			if(!contentLocCheck){
				return;
			}
		});
		if(!contentLocCheck){
			// mcxDialog.alert('위치코드가 중복 되었습니다.');
			mcxDialog.alert('이미 레이아웃 설정된 컨텐츠입니다.');
			return;
		}

		if(dataArr.length==0){
			mcxDialog.alert("저장할 데이터가 없습니다.");
			return;
		}
		//console.log(dataArr);
		var jsonData = JSON.stringify(dataArr);
		mcxDialog.confirm('레이아웃을 저장 하시겠습니까?', {
			cancelBtnText: "취소",
			sureBtnText: "확인",
			sureBtnClick: function(){
				gagajf.ajaxJsonSubmit('/display/main/layout/save', jsonData, fnGetMainDisplayList);
			}
		});
	});

	/**
	 * 레이아웃 수정 버튼 > 팝업
	 */
	var fnChangeContents = function (obj){
		var val = $("#searchForm select[name=cate1No]").val();
		var cateNo = '';
		var brandGroupNo = '';
		if(val.split(',')[1]=='Y'){
			cateNo = val.split(',')[0];
		}else{
			cateNo = $("#searchForm select[name=cate2No]").val().split(',')[0];
		}
		if(cateNo=='1711' || cateNo=='1721'){
			brandGroupNo = $("#searchForm").find("input[name=brandGroupNo]").val();
		}

		var contentsLoc = $(obj).closest("td").find('input:hidden[name="contentsLoc"]').val();

		// 브랜드픽, MD추천 다른 팝업 사용
		if(contentsLoc=='SMM007'||contentsLoc=='SMM009'||contentsLoc=='SMM012'||contentsLoc=='SMM003'||contentsLoc=='SBM007'||contentsLoc=='SBM008'||contentsLoc=='SBM009'
			||contentsLoc=='SBM017'||contentsLoc=='SBM018'||contentsLoc=='SBM019'||contentsLoc=='SOM002'||contentsLoc=='SOM003'||contentsLoc=='SCM002'||contentsLoc=='SCM003'){
			cfnOpenMainMultiContentsPopup(cateNo, contentsLoc, brandGroupNo);
		}else if(contentsLoc=='STAB001' || contentsLoc=='STAB002' || contentsLoc=='SBM002' || contentsLoc=='SBMM002'){
			cfnOpenMainGnbContentsPopup(cateNo, contentsLoc, brandGroupNo);
		}else{
			cfnOpenMainContentsPopup(cateNo, contentsLoc, brandGroupNo);
		}
	}

	/**
	 * 첨부파일 등록
	 */
	var fnFileUpload = function (obj, ind){
		var file = obj.files[0];
		file.name = 'test';
		if (typeof(file) == 'undefined'){
			return;
		}
		gagajf.ajaxFileUpload('/common/file/upload?subDir=/mainLayout'
				, 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_"+ind).attr('src', $("#uploadDefaultUrl").val()+result.newFileName);
					$("#imgView_"+ind).removeClass("off").addClass("on");
					//uifnFitGrid();
				}
				, 'image'
		);
	};

	/**
	 * 개별 적용 버튼
	 */
	var fnUpdateContents = function (contentsLoc){
		mcxDialog.confirm('컨텐츠를 적용 하시겠습니까?', {
			cancelBtnText: "취소",
			sureBtnText: "확인",
			sureBtnClick: function(){
				if(contentsLoc=='STAB002') {
					var data = {
						gtabGb: 'C'
					};
					var jsonData = JSON.stringify(data);
					gagajf.ajaxJsonSubmit('/display/contents/gnbtab/save', jsonData);
				}else if(contentsLoc=='SBM002'){
					var val = $("#searchForm select[name=cate1No]").val();
					var cateNo = '';
					var brandGroupNo = '';
					if(val.split(',')[1]=='Y'){
						cateNo = val.split(',')[0];
					}else{
						cateNo = $("#searchForm select[name=cate2No]").val().split(',')[0];
					}
					if(cateNo=='1711' || cateNo=='1721'){
						brandGroupNo = $("#searchForm").find("input[name=brandGroupNo]").val();
					}
					var data = {
						gtabGb: 'B'
						,brandGroupNo : brandGroupNo
					};
					var jsonData = JSON.stringify(data);
					gagajf.ajaxJsonSubmit('/display/contents/gnbtab/save', jsonData);
				}else{
					var val = $("#searchForm select[name=cate1No]").val();
					var cateNo = '';
					var brandGroupNo = '';
					if(val.split(',')[1]=='Y'){
						cateNo = val.split(',')[0];
					}else{
						cateNo = $("#searchForm select[name=cate2No]").val().split(',')[0];
					}
					if(cateNo=='1711' || cateNo=='1721'){
						brandGroupNo = $("#searchForm").find("input[name=brandGroupNo]").val();
					}
					var data = { contentsLocArr : [contentsLoc]
						,cateNo : cateNo
						,brandGroupNo : brandGroupNo
					};
					var jsonData = JSON.stringify(data);
					gagajf.ajaxJsonSubmit('/display/contents/save', jsonData);
				}
			}
		});
	}

	/**
	 * 일괄적용 버튼
	 */
	$("#btnAllUpd").on("click", function(){
		mcxDialog.confirm('컨텐츠를 일괄적용 하시겠습니까?', {
			cancelBtnText: "취소",
			sureBtnText: "확인",
			sureBtnClick: function(){
				var val = $("#searchForm select[name=cate1No]").val();
				var cateNo = '';
				var brandGroupNo = '';
				if(val.split(',')[1]=='Y'){
					cateNo = val.split(',')[0];
				}else{
					cateNo = $("#searchForm select[name=cate2No]").val().split(',')[0];
				}
				if(cateNo=='1711' || cateNo=='1721'){
					brandGroupNo = $("#searchForm").find("input[name=brandGroupNo]").val();
				}
				var contentsLocArr = [];
				$("input:hidden[name=contentsLoc]").each(function(){
					contentsLocArr.push($(this).val());
				});

				var data = { contentsLocArr : contentsLocArr
					,cateNo : cateNo
					,brandGroupNo : brandGroupNo
				};
				var jsonData = JSON.stringify(data);
				gagajf.ajaxJsonSubmit('/display/contents/save', jsonData);
			}
		});
	});

	/**
	 * 상품관리
	 */
	var fnSearchCategory = function (contentsLoc){
		var val = $("#searchForm select[name=cate1No]").val();
		var cate1No = '';

		/*if(val.split(',')[1]=='Y'){
			if(val.split(',')[0]=='1711' || val.split(',')[0]=='1721'){
				cate1No = '2100';
			}else if(val.split(',')[0]=='1713' || val.split(',')[0]=='1723'){
				cate1No = '3000';
			}else{
				cate1No = val.split(',')[0];
			}
		}else{
			cate1No = $("#searchForm select[name=cate2No]").val().split(',')[0];
		}*/
		if(val.split(',')[1]!='Y'){
			cate1No = $("#searchForm select[name=cate2No]").val().split(',')[0];
		}

		var data = {
			contentsLoc : contentsLoc
			,cate1No : cate1No
		};
		var jsonData = JSON.stringify(data);
		gagajf.ajaxJsonSubmit('/display/category4srch/list', jsonData, fnGoodsMng);
	};

	var fnGoodsMng = function (result){
		var selLvl = 6;
		if(gagajf.isNull(result.cate4No)){
			selLvl = 5;
		}
		if(gagajf.isNull(result.cate3No)){
			selLvl = 4;
		}
		if(gagajf.isNull(result.cate2No)){
			selLvl = 3;
		}

		console.log('mainListForm result cateCd>>'+result.leafCateNo);

		var params = 'cateGb='+result.cateGb;
		params += '&cateType='+result.cateType;
		params += '&cate1No='+result.cate1No;
		params += '&cate2No='+result.cate2No;
		params += '&cate3No='+result.cate3No;
		params += '&cate4No='+result.cate4No;
		params += '&selLvl='+selLvl;
		params += '&cateCd='+result.leafCateNo;
		params += '&goodsAddYn=Y';
		params += '&contentsLoc='+result.contentsLoc;
		params += '&brandGroupNo='+$("#searchForm input[name=brandGroupNo]").val();

		cfnOpenGoodsDispOrdChangePopup('', params);
	};

	$("#btnView").on("click", function (){
		if(gagajf.isNull($("#viewDate").val())){
			mcxDialog.alert("미리보기 일시를 입력해 주세요")
			return;
		}

		var val = $("#searchForm select[name=cate1No]").val();
		var cateNo = '';
		var brandGroupNo = '';
		if(val.split(',')[1]=='Y'){
			cateNo = val.split(',')[0];
		}else{
			cateNo = $("#searchForm select[name=cate2No]").val().split(',')[0];
		}
		if(cateNo=='1711' || cateNo=='1721'){
			brandGroupNo = $("#searchForm").find("input[name=brandGroupNo]").val();
		}

		var uriMap = new Map();
		uriMap.set("1700", "/display/mall/main/form?mobileYn=N");
		uriMap.set("1720", "/display/mall/main/form?mobileYn=Y");
		uriMap.set("1712", "/display/category/main/form?mobileYn=N&cateGb=G032_101&cate1No="+cateNo);
		uriMap.set("1722", "/display/category/main/form?mobileYn=Y&cateGb=G032_101&cate1No="+cateNo);
		uriMap.set("1711", "/display/brand/main/form?mobileYn=N&brandGroupNo="+brandGroupNo);
		uriMap.set("1721", "/display/brand/main/form?mobileYn=Y&brandGroupNo="+brandGroupNo);
		//uriMap.set("22", "/display/brand/list/form?mobileYn=Y");
		uriMap.set("1713", "/display/outlet/main/form?mobileYn=N&cateGb=G032_103&cate1No="+cateNo);
		uriMap.set("1723", "/display/outlet/main/form?mobileYn=Y&cateGb=G032_103&cate1No="+cateNo);
		// uriMap.set("1714", "/goods/detail/form?mobileYn=N&goodsCd=HQM72NJ60G_MT&adminYn=Y");
		// uriMap.set("1724", "/goods/detail/form?mobileYn=Y&goodsCd=HQM72NJ60G_MT&adminYn=Y");
		// _front = [[${@environment.getProperty('domain.front')}]];
		window.open("about:blank").location.href= _frontUrl + uriMap.get(cateNo) + "&preview=Y&viewDt="+$("#viewDate").val().replace(/-/gi, '')+$("#viewTimeHour").val()+$("#viewTimeMin").val()+"00";

	});

	$(document).ready(function() {
		var today = new Date(_today);
		var yesterDay = new Date(today.getFullYear(), today.getMonth(), today.getDate()+1).format("YYYY-MM-DD");
		$("#viewDate").val(yesterDay);
		$("#viewTimeHour").val("09");
		// Create a agGrid
		$("#mainSortable").disableSelection();
		//uifnFitGrid();
	});
/*]]>*/
</script>

</html>
