<!DOCTYPE html>
<html lang="ko"
	xmlns:th="http://www.thymeleaf.org">
<!--
 *******************************************************************************
 * @source  : SearchLayerWeb.html
 * @desc    : 검색 레이어 Page
 *============================================================================
 * STYLE24
 * Copyright(C) 2020 TSIT, All rights reserved.
 *============================================================================
 * VER  DATE         AUTHOR      DESCRIPTION
 * ===  ===========  ==========  =============================================
 * 1.0  2021.05.11   bin2107     최초 작성
 *******************************************************************************
 -->
<h2 class="sr-only">통합검색</h2>
<div class="cont_search">
	<div class="area_input">
		<form id="searchMainForm" name="searchMainForm">
			<input type="hidden" name="brandGroupNo" th:value="${brandGroupNo}"/>
			
			<fieldset>
				<legend>통합검색</legend>
				<input type="text" name="keyword" value="" placeholder="검색어를 입력하세요." class="search_input" title="검색어 입력" maxlength="100" required="required" data-valid-name="검색어" autocomplete="off" onkeyup="fnOnkeyupKeyword(this);"/>
				<button type="button" class="sch_btn" id="btnSearchKeyword"><i class="ico ico_search"><em>검색</em></i></button>
			</fieldset>
		</form>
	</div>
	<div class="area_result">
		<!-- 검색결과 입력 전 -->
		<div class="default_box">
			<div class="recent_blk">
				<h3>최근 검색어</h3>
				<!-- 최근검색어 있을 시 노출 -->
				<div class="list_recent_keword" th:if="${not #lists.isEmpty(recentlyKeywordList)}">
					<ul>
						<li th:if="${recentlyKeywordList}" th:each="oneData, status : ${recentlyKeywordList}">
							<a href="javascript:void(0);" th:text="${oneData}" th:onclick="fnSearchKeyword([[${oneData}]])">슬랙스</a>
							<button type="button" class="btn_delete" th:onclick="fnDeleteCookie(this,[[${oneData}]]);" ><span>삭제</span></button>
						</li>
					</ul>
				</div>
				<button type="button" class="btn_underline" th:if="${not #lists.isEmpty(recentlyKeywordList)}"><span>전체삭제</span></button>
				<!-- //최근검색어 있을 시 노출 -->
				<!-- 최근검색어 없을 시 노출 -->
				<div class="empty_txt" th:if="${#lists.isEmpty(recentlyKeywordList)}">
					최근 검색어가 없습니다.
				</div>
				<!-- //최근검색어 없을 시 노출 -->
			</div>
			<div class="popular_blk" th:if="${brandGroupNo==null}">
				<h3>STYLE24에서 검색되고 있어요</h3>
				<div class="list_popular_keword">
					<ul id="popularKeyArea">
					</ul>
				</div>
			</div>
			<div class="realtime_blk">
				<h3>지금 고객님들이 많이 보고 있어요</h3>
				<div class="modify_timer">
					<button type="button" onclick="fnRealtimeGoodsList();"><span><em class="time" th:text="${#calendars.format(#calendars.createNow(), 'HH:mm')}">17:30</em> 기준</span></button>
				</div>
				<div class="realtime_wrap">
				
					<div class="swiper-container">
	           			<div class="swiper-wrapper itemsGrp" id="itemViewArea">
							<th:block th:each="item, status : ${realtimeGoodsList}">
								<div class="swiper-slide">
									<div class="item_prod">
										<div class="item_state">
											<a th:href="${item.itemUrl}" class="itemLink">
												<div class="itemPic">
													<img alt="" class="vLHTC pd_img" th:src="${item.imageUrl}">
												</div>
												<div class="itemName" th:text="${item.itemName}"></div>
												<div class="viewCount"><span th:text="${item.count < 10 ? '10명 미만' : item.count + '명 보는중'}"></span></div>
											</a>
										</div>
									</div>
								</div>
							</th:block>
						</div>
						<div class="swiper-controls">
			                <div class="swiper-scrollbar"></div>
			            </div>
						
					</div>
				</div>
			</div>
		</div>
		<!-- //검색결과 입력 전 -->
		<!-- 검색결과 입력 후 -->
		<div class="searching_box" style="display:none;">
			<div class="autokeyword_blk" th:if="${brandGroupNo==null}">
			</div>
			<div class="exfind_blk" th:if="${brandGroupNo==null}">
				<!-- 검색어 매칭 브랜드 있을 시 노출  -->
				<div class="find_brand">
				</div>
				<!-- //검색어 매칭 브랜드 있을 시 노출  -->
				<!-- 검색어 매칭 카테고리 있을 시 노출  -->
				<div class="find_category">
				</div>
				<!-- //검색어 매칭 카테고리 있을 시 노출  -->
			</div>

			<div class="pd_list relate" id="relateGoodsDiv">
				<h3>관련상품</h3>
				<div class="realtime_wrap">
					<div class="itemsGrp">
					</div>
				</div>
			</div>
		</div>
		<!-- //검색결과 입력 후 -->

		<!-- 검색결과 없을때 노출 -->
		<div class="empty_box" style="display: none">
			<div class="">
				<div class="nodata">
					<p>
						<span class="keyword" id="noDataKeyword"></span>에 맞는 상품을 찾지 못했습니다.<br>
						검색어를 변경해 보세요.
					</p>
				</div>
				<div class="pd_list recommend">
					<h3>이런 상품은 어떤가요?</h3>
					<div class="itemsGrp" id="recommendItemArea">
					</div>
				</div>
			</div>
		<!-- //검색결과 없을때 노출 -->
		</div>
	</div>
</div>
<button type="button" class="btn_close_search" onclick="fnClose();"><span>닫기</span></button>

<script src="/ux/plugins/gaga/gaga.paging.js"></script>
<script th:inline="javascript">
	/*<![CDATA[*/
	var enterBool = false;
	var trendKeywordList = [[${trendKeywordList.trendList}]];

	var fnClose = function() {
		$("body").removeClass("lock");
		$("#layer_search").removeClass('active');
	}
	
	// 검색어 입력 후 엔터키
	$('#searchMainForm input[name=keyword]').keypress(function (event) {
		if (event.which === 13) {
			event.preventDefault();
			$('#btnSearchKeyword').trigger('click');
		}
	});
	
	var ckKeyword = "st24ck_today_keyword";
	var fnSetKeywordCookie = function(keyword) {
		var arrKeyword = new Array;
		var arrTempKeyword = new Array;
		var j = 0;

		arrKeyword = gagajf.getCookie(ckKeyword).split(",");

		if (arrKeyword.length > 0) {
			for (var i = 0; i < arrKeyword.length; i++) {
				// 쿠키에 없으면
				if (arrKeyword[i] != keyword && arrKeyword[i] != "") {
					arrTempKeyword[j++] = arrKeyword[i];
				}
			}

			arrTempKeyword[j++] = keyword;
		} else {
			gagajf.setCookie(ckKeyword, keyword, 1);
		}

		gagajf.setCookie(ckKeyword, arrTempKeyword, 1);
	}
	
	// 키워드 검색
	$('#btnSearchKeyword').on('click', function() {
		if (!gagajf.validation($('#searchMainForm'))) {
			return false;
		}
		
		// 검색결과 상품목록 호출(있으면 검색결과 페이지로 이동)
		gagajf.ajaxFormSubmit("/display/search/goods/list_cnt", document.searchMainForm, function(result) {
			if( "0" == result.response_cnt){
				$('.common_search .area_result .default_box').hide();
				$('.common_search .area_result .searching_box').hide();
				$('.common_search .area_result .empty_box').show();
				$('.empty_box .nodata').find('#noDataKeyword').text("'"+$("#searchMainForm").find('input[name=keyword]').val()+"'");
				
				// 검색결과 페이지에서 검색팝업 띄웠을때 (검색결과 페이지에 정의되어있으므로 내용 안뜨는 오류)
				console.log("= "+$("input[name=keyword]").length);
				if( 1 == $("input[name=keyword]").length ){
					$(".common_search .recommend").show();
					// 검색어 연관 상품 추천
					fnRecommendItemList($("#searchMainForm").find('input[name=keyword]').val());
				}else{
					$(".common_search .recommend").hide();
				}
				
			}else{
				let keyword = encodeURIComponent($('#searchMainForm input[name=keyword]').val());
				
				// 쿠키 세팅
				fnSetKeywordCookie(keyword);
				
				let actionUrl = _PAGE_SEARCH_GOODS + '?keyword=' + keyword + '&brandGroupNo=' + $('#searchMainForm input[name=brandGroupNo]').val();
				cfnGoToPage(actionUrl);
			}
		});
	});

	var submain_slide;
	$(document).ready( function() {
		$("#layer_search").addClass('active');

		if (trendKeywordList.length > 0) {
			$("#popularKeyArea").html('');
			trendKeywordList.forEach(function (item, idx) {
				if(item.keyword.indexOf("테스트") < 0){
					var tag = '';
					if (idx < 10) {
						tag += '<li>';
						tag += '	<a href="javascript:void(0);" onclick="fnSearchKeyword(\''+item.keyword+'\');">'+ item.keyword +'</a>';
						tag += '</li>';
					}
					$("#popularKeyArea").append(tag);
				}
			});
		}else{
			$("#popularKeyArea").html('');
		}

		//통합검색 - 검색어 입력 시
		//
		
		// 지금 고객님들이 많이 보고 있어요
		//210730_ 추가 : 지금 고객님들이 많이 보고 있어요 슬라이드 swiper 옵션 추가.
		submain_slide = new Swiper('.realtime_wrap .swiper-container', {
			slidesPerView: 5,
			watchOverflow:true,
			freeMode:true,
			observer: true,
			observeParents: true,
			speed:1000,
			scrollbar: {
				el: '.realtime_wrap .swiper-scrollbar',
				hide: false,
			},
		});
	});

	// 검색어 찾기
	var fnGetAutoSearch = function (){
		gagajf.ajaxFormSubmit("/display/search/auto/complete", document.searchMainForm, fnAutoCompleteList);
	}

	// 검색어 찾기 결과
	var fnAutoCompleteList = function (result){
		if( enterBool ) return;
		
		if(result.autoKeywords.length==0 && gagajf.isNull(result.brand.brandGroupNo) && result.cateList.length == 0 && gagajf.isNull(result.goodsList)){
			$('.common_search .area_result .default_box').hide();
			$('.common_search .area_result .searching_box').hide();
				
		}else{
			$('.common_search .area_result .default_box').hide();
			$('.common_search .area_result .searching_box').show();
			$('.common_search .area_result .empty_box').hide();
			// 자동완성 키워드
			if(result.autoKeywords != null && result.autoKeywords.length > 0){
				$(".autokeyword_blk").html('');
				let tag = '';
				tag += '<ul>\n';
				$.each(result.autoKeywords, function (idx, item){
					//<a href="javascript:void(0);"><em>가</em>을컬리수</a>
					tag += '<li><a href="javascript:void(0);" onclick="fnSearchKeyword(\''+result.autoKeywords[idx]+'\');">'+result.autoKeywords[idx]+'</a></li>\n';
				});
				tag += '</ul>\n';
				$(".autokeyword_blk").append(tag);
			}else{
				$(".autokeyword_blk").html('');
				let tag = '';
				tag += '<ul>\n';
				tag += '<li></li>\n';
				tag += '</ul>\n';
				$(".autokeyword_blk").append(tag);
			}

			if(result.brand != null && !gagajf.isNull(result.brand.brandGroupNo)){
				$(".find_brand").html('');
				let tag = '';
				tag += '<h3><a href="javascript:void(0);" onclick="cfnGoToBrandMain('+result.brand.brandGroupNo+');">'+result.brand.brandGroupNm+' 샵 바로가기</a></h3>\n';
				$(".find_brand").append(tag);
			}else{
				$(".find_brand").html('');
			}

			if(result.cateList != null && result.cateList.length > 0){
				$(".find_category").html('');
				let tag = '';
				tag += '<ul>\n';
				$.each(result.cateList, function (idx, item){
					tag += '<li>\n';
					tag += '	<span class="category_txt">카테고리</span>\n';
					tag += '	<a href="javascript:void(0);" onclick="cfnGoToGoodsList(0,\'G032_101\' ';
					if(item.cate1No != null){
						tag += ', '+item.cate1No;
					}
					if(item.cate2No != null){
						tag += ', '+item.cate2No;
					}
					if(item.cate3No != null){
						tag += ', '+item.cate3No;
					}
					if(item.cate4No != null){
						tag += ', '+item.cate4No;
					}
					if(item.cate5No != null){
						tag += ', '+item.cate5No;
					}
					tag += ');">\n';
					if(item.cate1Nm != null){
						tag += '		<span>'+item.cate1Nm+'</span>\n';
					}
					if(item.cate2Nm != null){
						tag += '		<span>'+item.cate2Nm+'</span>\n';
					}
					if(item.cate3Nm != null){
						tag += '		<span>'+item.cate3Nm+'</span>\n';
					}
					if(item.cate4Nm != null){
						tag += '		<span>'+item.cate4Nm+'</span>\n';
					}
					if(item.cate5Nm != null){
						tag += '		<span>'+item.cate5Nm+'</span>\n';
					}
					tag += '	</a>\n';
					tag += '</li>\n';
				});
				tag += '</ul>\n';
				$(".find_category").append(tag);
			}else{
				$(".find_category").html('');
			}
			if(!gagajf.isNull(result.goodsList)){
				$("#relateGoodsDiv").show();
				$(".pd_list .realtime_wrap .itemsGrp").html('');
				let tag = '';
				$.each(result.goodsList, function (idx, item){
					if(idx<5) {
						tag += '<div class="item_prod">\n';
						tag += '	<div class="item_state">\n';
						tag += '		<a href="javascript:void(0);" class="itemLink" onclick="cfnGoToGoodsDetail(\'' + item.goodsCd + '\',\'' + item.colorCd + '\');">\n';
						tag += '			<div class="itemPic">\n';
						tag += '				<img alt="" class="vLHTC pd_img" src="' + item.sysImgNm + '">\n';
						tag += '			</div>\n';
						tag += '			<p class="itemBrand">' + item.brandGroupNm + '</p>\n';
						tag += '			<div class="itemName">' + item.goodsFullNm + '</div>\n';
						tag += '			<p class="itemPrice cols">\n';
						if (item.listPrice != item.currPrice) {
							tag += '				<span class="itemPrice_original">' + item.listPrice.addComma() + '</span>\n';
						}
						tag += item.currPrice.addComma();
						if (item.listPrice != item.currPrice) {
							tag += '				<span class="itemPercent">' + Math.round((item.listPrice - item.currPrice) / (item.listPrice * 1.0) * 100) + '%</span>\n';
						}
						tag += '			</p>\n';
						tag += '		</a>\n';
						tag += '	</div>\n';
						tag += '</div>\n';
					}
				});

				$(".pd_list .realtime_wrap .itemsGrp").append(tag);
			}else{
				$(".pd_list .realtime_wrap .itemsGrp").html('');
				$("#relateGoodsDiv").hide();
			}
		}
	}

	var fnOnkeyupKeyword = function (obj){
		if( 13 != event.keyCode){
			enterBool = false;
			var searchValue = $(obj).val();
			if(searchValue.length > 0) {
				fnGetAutoSearch();
			} else if (searchValue.length == 0) {
				$('.common_search .area_result .searching_box').hide();
				$('.common_search .area_result .default_box').show();
				$('.common_search .area_result .empty_box').hide();
			}
		}else{
			// 엔터친 후, 그 전에 검색한 결과가 오고있으므로 
			enterBool = true;	
		}
	}

	// 선택 단어 검색
	var fnSearchKeyword = function (obj){
		$("#searchMainForm").find("input[name=keyword]").val(obj);
		$('#btnSearchKeyword').trigger('click');
	}

	// 선택 단어 삭제
	var fnDeleteCookie = function (obj, keyword){
		$(obj).closest('li').remove();
		gagajf.setCookie('st24ck_today_keyword',keyword, -1);
	}

	// 실시간 상품 새로고침
	var fnRealtimeGoodsList = function (){
		$("#itemViewArea").html('');
		var html = '';
		$.getJSON('/display/realtime/goods/list', function (result){
			if(result.length > 0){
				$.each(result, function (idx, item){
					html += '<div class="swiper-slide">\n';
					html += '	<div class="item_prod">\n';
					html += '		<div class="item_state">\n';
					html += '			<a href="'+item.itemUrl+'" class="itemLink">\n';
					html += '				<div class="itemPic">\n';
					html += '					<img alt="" class="vLHTC pd_img" src="'+item.imageUrl+'">\n';
					html += '				</div>\n';
					html += '				<div class="itemName">'+item.itemName+'</div>\n';
					if(item.count < 10){
						html += '			<div class="viewCount"><span>10명</span> 미만</div>\n';
					}else{
						html += '			<div class="viewCount"><span>'+item.count.addComma()+'</span>명 보는중</div>\n';
					}
					html += '			</a>\n';
					html += '		</div>\n';
					html += '	</div>\n';
					html += '</div>\n';
									
				});
			}
			$("#itemViewArea").append(html);
			
			// 슬라이드 사이즈 때문에 재설정함
			submain_slide = new Swiper('.realtime_wrap .swiper-container', {
				slidesPerView: 5,
				watchOverflow:true,
				freeMode:true,
				observer: true,
				observeParents: true,
				speed:1000,
				scrollbar: {
					el: '.realtime_wrap .swiper-scrollbar',
					hide: false,
				},
			});
		});
	}

	// 검색어 연관 상품 추천
	var fnRecommendItemList = function (keyword){
		if(gagajf.isNull(keyword)){
			keyword = "";
		}
		var data = {keyword : keyword.trim()};
		var html = '';

		$.getJSON('/display/recommend/item/list', data, function (result){
			$("#recommendItemArea").html('');
			$("#recommendItemArea").show();
			
			if(result.length > 0){
				$.each(result, function (idx, item){
					html += '<div class="item_prod">\n';
					html += '	<div class="item_state">\n';
					html += '		<a href="'+item.product.itemUrl+'" class="itemLink">\n';
					html += '			<div class="itemPic">\n';
					html += '				<img alt="" class="vLHTC pd_img" src="'+item.product.itemImage+'">\n';
					html += '			</div>\n';
					html += '			<p class="itemBrand">'+item.product.brandName+'</p>\n';
					html += '			<div class="itemName">'+item.product.itemName+'</div>\n';
					html += '			<p class="itemPrice cols">\n';
					if(item.product.salePrice < item.product.originalPrice) {
						html += '			<span class="itemPrice_original">'+ item.product.originalPrice.addComma() +'</span>\n';
					}
					html += item.product.salePrice.addComma() ;
					if(item.product.salePrice < item.product.originalPrice) {
						html += '			<span class="itemPercent">' + Math.round((item.product.originalPrice - item.product.salePrice) / (item.product.originalPrice * 1.0) * 100) + '%</span>\n';
					}
					html += '			</p>\n';
					html += '		</a>\n';
					html += '	</div>\n';
					html += '</div>\n';
				});
				
				$("#recommendItemArea").append(html);
				
			}else{
				$("#recommendItemArea").html('');
				$("#recommendItemArea").hide();
			}
		});
	}
	/*]]>*/
</script>
</html>