
var favoriteHandler;

var currentMapInstance_view; 		// 맵 인스턴스
var currentLocationMarker_view;		// 현재 위치를 표시하는 마커 인스턴스
var customOverlay_view;				// 오버레이 객체 인스턴스(매장정보)

//매장 정보 > 이달의 상품 찾기
var listData2 			= { currentPage : 1, pageCnt : 6, strCd : "" }
//매장 정보 > 이달의 상품 찾기 > 전체 리스트 개수
var listCnt2			= -1;

var jsStoreView = {

	storeInfo: {},

	viewArsYn: false,

	appYn: "N",
	curLat: null,
	curLon: null,

	init: function() {

	},

	info: function(bizNo, handler,curLat, curLon) 
	{
		if(handler) favoriteHandler = handler;
		viewStore = $('#popupStoreInformation_store');

		// 매장 정보 > 이달의 상품 찾기
		jsStoreView.getStroeMonthGdsList( bizNo );
		
		// 매장 정보 > 오늘 픽업 바로가기 버튼 노출 체크
		jsStoreView.getTodayPickupStoreCheck( bizNo );
		
		$.ajax({
			url: '/api/store/info/' + bizNo,
			data: { deliveryStoreYn: "N" },
			type: 'GET',
			dataType: 'json',

			success: function(data, status, xhr) {
                if(data.storeInfo == null){
                    openAlertPopup("선택하신 매장의 정보가 존재하지 않습니다. 다른매장을 선택해주세요.");
                    return false;
                }
                
                $("#userBizNo").val(data.storeInfo[0].bizNo);
				$("#userBizName").val(data.storeInfo[0].bizName);
				
                // 매장명
				$(viewStore).find("#store_name").html(data.storeInfo[0].bizName);

				// 주소
				$(viewStore).find("#address_store").html(data.storeInfo[0].address);

				// 각 해당하는 매장의 지도보여주기
				var url = 'map.kakao.com/link/to/' + data.storeInfo[0].bizName + ',' + data.storeInfo[0].latitude + ',' + data.storeInfo[0].longitude;
				var load_html = "<br/> <button type=\"button\" class=\"link_txt open_map\" title=\"" + data.storeInfo[0].bizName + " 카카오맵으로 이동\" onclick=\"emartBridge('loadBrowser', {'message' : '" + url + "'});\"><em>길찾기</em></button>";
				$(viewStore).find("#address_store").append(load_html);

				// 영업시간
				var startTime = data.storeInfo[0].startTime;
				var startMin = data.storeInfo[0].startMin;
				var endTime = data.storeInfo[0].endTime;
				var endMin = data.storeInfo[0].endMin;
				var Time = startTime + ':' + startMin + ' ~ ' + endTime + ':' + endMin;

				$(viewStore).find("#store_time").html(Time);

				var html = "";
				var isLoginYn = "";

				// 단골매장 여부 -- 로그인 했을때만 노출(KIS쪽에 감추기 위함)
				if(data.loginSession == "Y")
				{
					isLoginYn = "Y";
					if (data.isFavoriteStore == true) {
					$(viewStore).find(".btn_area button").addClass("on")
					html += '<button type="button" class="btn_favorite_store on" id="ui_favoriteMark" '
					html += 'onclick="jsStoreView.clickFavoriteStore(\'' + data.storeInfo[0].bizNo + '\', \'' + data.storeInfo[0].bizName + '\', \'' + data.storeInfo[0].latitude + '\', \'' + data.storeInfo[0].longitude + '\'); return false;" title="단골매장설정">';
					html += '	<i class="ico"></i><em>단골</em><span class="blind">단골매장 활성</span>';
					html += '</button>';
					$(viewStore).find(".btn_area").html(html);

					} else {
						$(viewStore).find(".btn_area button").addClass("off")
						html += '<button type="button" class="btn_favorite_store off" id="ui_favoriteMark"'
						html += 'onclick="jsStoreView.clickFavoriteStore(\'' + data.storeInfo[0].bizNo + '\', \'' + data.storeInfo[0].bizName + '\', \'' + data.storeInfo[0].latitude + '\', \'' + data.storeInfo[0].longitude + '\'); return false;" title="단골매장설정">';
						html += '	<i class="ico"></i><em>단골</em><span class="blind">단골매장 비활성</span>';
						html += '</button>';
						$(viewStore).find(".btn_area").html(html);
					}
				}
				else
				{
					isLoginYn = "N";
					$(viewStore).find(".btn_area").hide();
				}

				// 대표전화
				if (data.storeInfo[0].phone != null && data.storeInfo[0].phone != "") { // 해당 매장의 전화번호가 있는 경우
					$(viewStore).find("#store_phoneNum").html("<a style='cursor:pointer;' href='javascript:emartBridge(\"requestPhoneCall1\", {\"message\" : \"" + data.storeInfo[0].phone + "\"});' class='link_txt phone fc_point02'>" + phoneNumberAddDash(data.storeInfo[0].phone) + "</a>");
				} else { // 없다면 대표전화로 통일
					$(viewStore).find("#store_phoneNum").html("<a style='cursor:pointer;' href='javascript:emartBridge(\"requestPhoneCall1\", {\"message\" : \"0269161500\"});' class='link_txt phone fc_point02'>02-6916-1500</a>");
				}
				
				// bsd 배달문의 
				if(data.storeInfo[0].bsdTelNo != null && data.storeInfo[0].bsdTelNo != ""){
					$(viewStore).find("#bsd_tel_no_dl").show();
					$(viewStore).find("#store_bsdTelno").html("<a style='cursor:pointer;' href='javascript:emartBridge(\"requestPhoneCall1\", {\"message\" : \"" + data.storeInfo[0].bsdTelNo + "\"});' class='link_txt fc_point02'>" + phoneNumberAddDash(data.storeInfo[0].bsdTelNo) + "</a>");
				}else {
					$(viewStore).find("#bsd_tel_no_dl").hide();
				}
				/*if(data.storeInfo[0].phone != null && data.storeInfo[0].phone != ""){ // 해당 매장의 전화번호가 있는 경우
					$(viewStore).find("#store_phoneNum").html("<a href='tel:"+data.storeInfo[0].phone+"' class='link_txt fc_point02'>02-6916-1500</a>");
				}else{ // 없다면 대표전화로 통일
					$(viewStore).find("#store_phoneNum").html("<a href='tel:02-6916-1500' class='link_txt fc_point02'>02-6916-1500</a>");
				}*/

				// 무인운영여부 체크
				if (data.storeInfo[0].mnlsTgetCd == "1" && data.storeInfo[0].mnlsFormCd == "2" && data.storeInfo[0].bizNo != "02982") {
					if (data.storeInfo[0].bizNo == "20762") { // 해당 점포에 대한 옵션 추가
						$(viewStore).find("#option_info").show();
						$(viewStore).find("#option_info dt").html("무인운영시간 (주말무인운영)");
						$(viewStore).find("#auto_time").html(data.storeInfo[0].mnlsStTm + ' ~ ' + data.storeInfo[0].mnlsEdTm);
					} else {
						$(viewStore).find("#option_info").show();
						$(viewStore).find("#auto_time").html(data.storeInfo[0].mnlsStTm + ' ~ ' + data.storeInfo[0].mnlsEdTm);
					}
				} else {
					$(viewStore).find("#option_info").hide();
				}

				var html = "", used = [];

				//  서비스
				var svr24 = data.storeInfo[0].svr24;
				var svrAuto = data.storeInfo[0].svrAuto;
				var svrParcel = data.storeInfo[0].svrParcel;
				var svrAtm = data.storeInfo[0].svrAtm;
				var svrWine = data.storeInfo[0].svrWine;
				var svrCoffee = data.storeInfo[0].svrCoffee;
				var svrSmooth = data.storeInfo[0].svrSmooth;
				var svrChicken = data.storeInfo[0].svrChicken;
				var svrNoodle = data.storeInfo[0].svrNoodle;
				var svrApple = data.storeInfo[0].svrApple;
				var svrToto = data.storeInfo[0].svrToto;
				var svrPickup = data.storeInfo[0].svrPickup;

                // 노브랜드 여부
				var nbrLicsYn = data.storeInfo[0].nbrLicsYn;

				if(nbrLicsYn == '1'){
					html += '<li><div class="store_service nobrand"><i class="ico"></i><span class="txt">노브랜드</span></div></li>';
				}

				if(svr24!=null && svr24=='1'){
					html += '<li><div class="store_service hours24 on"><i class="ico"></i><span class="txt">24시간</span></div></li>';
				}

				if(svrAuto!=null && svrAuto=='1'){
					html += '<li><div class="store_service unmanned on"><i class="ico"></i><span class="txt">무인매장</span></div></li>';
				}

				if(svrParcel!=null && svrParcel=='1'){
					html += '<li><div class="store_service delivery on"><i class="ico"></i><span class="txt">택배</span></div></li>';
				}

				if(svrAtm!=null && svrAtm=='1'){
					html += '<li><div class="store_service atm on"><i class="ico"></i><span class="txt">ATM</span></div></li>';
				}

				if(svrWine!=null && svrWine=='1'){
					html += '<li><div class="store_service wine on"><i class="ico"></i><span class="txt">와인</span></div></li>';
				}

				if(svrCoffee!=null && svrCoffee=='1'){
					html += '<li><div class="store_service coffee on"><i class="ico"></i><span class="txt">커피</span></div></li>';
				}

				if(svrSmooth!=null && svrSmooth=='1'){
					html += '<li><div class="store_service smoothieking on"><i class="ico"></i><span class="txt">스무디킹</span></div></li>';
				}

				if(svrApple!=null && svrApple=='1'){
					html += '<li><div class="store_service apple on"><i class="ico"></i><span class="txt">애플악세사리</span></div></li>';
				}

				if(svrToto!=null && svrToto=='1'){
					html += '<li><div class="store_service toto on"><i class="ico"></i><span class="txt">스포츠토토</span></div></li>';
				}

				if(svrPickup!=null && svrPickup=='1'){
					html += '<li><div class="store_service preorder on"><i class="ico"></i><span class="txt">예약픽업</span></div></li>';
				}

				// var services = data.storeInfo[0].service + (data.storeInfo[0].addService || '');
				// var bgfDlvYn = data.BgfDlvYn;
				/*
				$.each(services.split(","), function(idx, item) {
					item = item.trim();
					
					// 중복 처리를 위한 서비스값 통일 (23,26번 == 택배) (12번 == 커피) (25번 == 무인매장)
					if(item == "23" || item == '26') item = "3";
					if(item == "12") item = "1";
					if(item == "25") item = "10";

					//  중복노출되지 않도록 처리
					if (used[item]) {
						return true;
					}
					used[item] = true;
					
					
					if (item == "0")
						html += '<li><div class="store_service hours24 on"><i class="ico"></i><span class="txt">24시간</span></div></li>';
					else if (item == "1")
						html += '<li><div class="store_service coffee on"><i class="ico"></i><span class="txt">커피</span></div></li>';
					// else if (item == "3")
					// 	html += '<li><div class="store_service delivery on"><i class="ico"></i><span class="txt">택배</span></div></li>';
					else if (item == "4")
						html += '<li><div class="store_service toto on"><i class="ico"></i><span class="txt">스포츠토토</span></div></li>';
					else if (item == "5")
						html += '<li><div class="store_service atm on"><i class="ico"></i><span class="txt">ATM</span></div></li>';
					/!*else if (item == "6")
						html += '<li><div class="store_service cashout on"><i class="ico"></i><span class="txt">현금인출</span></div></li>';*!/
					/!*else if (item == "09")
						html += '<li><div class="store_service tax on"><i class="ico"></i><span class="txt">세금환급</span></div></li>';*!/
					else if (item == "10")
						html += '<li><div class="store_service unmanned on"><i class="ico"></i><span class="txt">무인매장</span></div></li>';
					/!*else if (item == "11")
						html += '<li><div class="store_service wifi on"><i class="ico"></i><span class="txt">무료와이파이</span></div></li>';*!/
					/!*else if (item == "27")
						html += '<li><div class="store_service traffic on"><i class="ico"></i><span class="txt">교통카드충전</span></div></li>';*!/
					/!*else if (item == "28")
						html += '<li><div class="store_service hipass on"><i class="ico"></i><span class="txt">하이패스충전</span></div></li>';*!/
					/!*else if (item == "29")
						html += '<li><div class="store_service socar on"><i class="ico"></i><span class="txt">쏘카</span></div></li>';*!/
					/!*else if (item == "13")
						html += '<li><div class="store_service reserve on"><i class="ico"></i><span class="txt">리저브매장</span></div></li>';*!/
					else if (item == "30")
						html += '<li><div class="store_service preorder on"><i class="ico"></i><span class="txt">예약픽업</span></div></li>';
					else if (item == "17")
						html += '<li><div class="store_service smoothieking on"><i class="ico"></i><span class="txt">스무디킹</span></div></li>';
					else if (item == "22")
						html += '<li><div class="store_service apple on"><i class="ico"></i><span class="txt">애플악세사리</span></div></li>';
					else if (item == "24")
						html += '<li><div class="store_service wine on"><i class="ico"></i><span class="txt">와인</span></div></li>';
				});
				*/
				/*if(bgfDlvYn == "Y"){
					html += '<li><div class="store_service delivery on"><i class="ico"></i><span class="txt">택배</span></div></li>';
				}*/

				// 해당되는 매장의 서비스 표시
				$("#ui_storeService").html(html);

				// 상세정보 지도 그리기 (최초 1회)
				jsStoreView.drawMapShopDefault(data.storeInfo[0].latitude, data.storeInfo[0].longitude);
				
				jsStoreView.drawMainShopStore(data.storeInfo[0].latitude, data.storeInfo[0].longitude, data.storeInfo[0].bizName, data.isFavoriteStore);
				
				openModal('#popupStoreInformation_store');
				
				if(isLoginYn == 'Y'){
					$.ajax({
						type: "GET",
						url: "/api/strNotice/mainlist",
						async: false,
						data: {
							strCd: $("#userBizNo").val(),
							mainYn: "Y",
							count: 3
						},
						success: function(result) {
							var noticeList = result.noticeList;
							
							if (noticeList.length == 0) {
								var html = '<dl>점포 메인 공지가 없습니다.</dl>';
							}else{
								var html = '';
								
								for(var i=0;i<noticeList.length;i++){
									html += '<dl>';
									html += '<dt>'+ noticeList[i].title +'</dt>';
									html += '</dl>';
								}
							}
							$("#strNoticeArea").html(html);
							
							connexionStrUse(bizNo);
							
						},
						error: function(xhr, ajaxOptions, thrownError) {
							openAlertPopup("일시적으로 서비스를 사용할 수 없습니다. 잠시 후 다시 시도해 주세요.");
				//			console.log(xhr);
						}
					});
				}else{
					$("#connexionBtnTestArea").hide();
					$("#strNoticeTestArea").hide();
				}
			},
			
			error: function(data, status, xhr) {
				openAlertPopup("매장 위치를 확인할 수 없습니다.");
			}
		});
		
	},
	
	drawMapShopDefault: function(curLat, curLon)
	{
		if ( currentMapInstance_view ) return;	// 맵이 이미 존재하고 있으면 취소
		daumMap.level = 3;
		currentMapInstance_view = daumMap.drawMap(document.getElementById('ui_map_store'), curLat, curLon);
	} ,

	drawMainShopStore: function(curLat, curLon, bizName, isFavoriteStore) 
	{
		if( currentLocationMarker_view ) currentLocationMarker_view.setMap(null);
		if( customOverlay_view ) customOverlay_view.setMap(null);

		var src = isFavoriteStore ? '/assets/images/renew.common/pin_favorit_store_select.png' : '/assets/images/renew.common/pin_store_select.png';
		
		currentLocationMarker_view = daumMap.drawImageMarker2(curLat, curLon, { src: src, width: 44, height: 44 }, currentMapInstance_view);
		
		var itemName_view = '<div class="customoverlay on"><span class="title">' + bizName + '</span></div>';
		var MapPosition = new kakao.maps.LatLng(curLat, curLon);
		customOverlay_view = new kakao.maps.CustomOverlay( { position: MapPosition, content: itemName_view });
		customOverlay_view.setMap( currentMapInstance_view );
		
		currentMapInstance_view.setCenter ( MapPosition );
	},

	getContextPath: function() {
		var cp = window.location.pathname.substring(0, window.location.pathname.indexOf("/", 2));
		return (cp == '/admin' || cp == '/cms') ? cp : '';
	},

	//  신규매장 여부 확인
	isNewStore: function(dt) {
		var date = new Date(dt.substring(0, 4), parseInt(dt.substring(4, 6)) - 1, dt.substring(6, 8));
		var now = new Date();

		date.setMonth(date.getMonth() + 1);
		if (now < date)
			return true;
		return false;
	},


	//  현위치에서 매장까지의 거리
	upateDistance: function() {
		$("#ui_distance").html("현재 위치를 확인 중입니다.");

		try {
			$("#ui_enableLocInfo").css("display", "none");

			var cp = jsStoreView.getContextPath();
			var lat = jsStoreView.storeInfo.latitude;
			var lon = jsStoreView.storeInfo.longitude;

			var curLat = jsStoreView.curLat;
			var curLon = jsStoreView.curLon;

			if (curLat == null || curLon == null) {
				daumMap.getCurrentPosition(function(result, curLat, curLon) {
					if (result == false) {
						$("#ui_distance").html("현재 위치를 확인할 수 없습니다.");
						return;
					}

					//  현재위치 마커
					daumMap.drawImageMarker(curLat, curLon, {
						src: cp + '/assets/images/common/icon_mylocation.png',
						width: 80,
						height: 80
					});

					//  거리
					var dist = daumMap.calcCrow(lat, lon, curLat, curLon);

					if (dist < 1.0) {
						$("#ui_distance").html("현재 위치에서 " + parseInt(dist * 1000) + " m");
					} else {
						$("#ui_distance").html("현재 위치에서 " + dist + " km");
					}
				});
			} else {
				//  현재위치 마커
				daumMap.drawImageMarker(curLat, curLon, {
					src: cp + '/assets/images/common/icon_mylocation.png',
					width: 80,
					height: 80
				});

				//  거리
				var dist = daumMap.calcCrow(lat, lon, curLat, curLon);

				if (dist < 1.0) {
					$("#ui_distance").html("현재 위치에서 " + parseInt(dist * 1000) + " m");
				} else {
					$("#ui_distance").html("현재 위치에서 " + dist + " km");
				}
			}
		} catch (exception) {
			$("#ui_distance").html("현재 위치를 확인할 수 없습니다.");
		}
	},


	//  지도 그리기
	updateMap: function(curLat, curLon, isFavoriteStore, bizName) {
		var cp = jsStoreView.getContextPath();
		var lat = curLat;
		var lon = curLon;
		if (!lat || !lon) {
			openAlertPopup("매장 위치를 확인할 수 없습니다.");
			return;
		}

		try {

			daumMap.level = 3;
			daumMap.drawMap(document.getElementById('ui_map_store'), curLat, curLon);

			if (isFavoriteStore == true) {
				daumMap.drawImageMarker(curLat, curLon, {
					src: cp + '/assets/images/renew.common/pin_favorit_store_select.png',
					width: 44,
					height: 44
				});
				var itemName = '<div class="customoverlay on"><span class="title">' + bizName + '</span></div>';
			} else {
				daumMap.drawImageMarker(curLat, curLon, {
					src: cp + '/assets/images/renew.common/pin_store_select.png',
					width: 44,
					height: 44
				});
				var itemName = '<div class="customoverlay on"><span class="title">' + bizName + '</span></div>';
			}

		}
		catch (exception) {
			$("#ui_enableLocInfo").css("display", "none");
			$("#ui_distance").html("지도 서비스를 사용할 수 없습니다.");
		}
	},


	//  매장유형 및 서비스
	updateServices: function() {

		var html = "", used = [];

		//  서비스
		var services = jsStoreView.storeInfo.service + (jsStoreView.storeInfo.addService || '');
		// 노브랜드 여부
		var nbrLicsYn = jsStoreView.storeInfo.nbrLicsYn;

		if(nbrLicsYn == '1'){
			html += '<li class="store_service nobrand"><i class="ico"></i><span class="txt">노브랜드</span></li>';
		}

		$.each(services.split(","), function(idx, item) {
			item = item.trim();

			//  중복노출되지 않도록 처리
			if (used[item]) {
				return true;
			}
			used[item] = true;

			if (item == "0")
				html += '<li class="store_service hours24 on"><i class="ico"></i><span class="txt">24시간</span></li>';
			else if (item == "1")
				html += '<li class="store_service coffee on"><i class="ico"></i><span class="txt">원두커피</span></li>';
			else if (item == "3")
				html += '<li class="store_service delivery on"><i class="ico"></i><span class="txt">택배</span></li>';
			else if (item == "4")
				html += '<li class="store_service toto on"><i class="ico"></i><span class="txt">스포츠토토</span></li>';
			else if (item == "5")
				html += '<li class="store_service atm on"><i class="ico"></i><span class="txt">ATM</span></li>';
			else if (item == "27")
				html += '<li class="store_service traffic on"><i class="ico"></i><span class="txt">교통카드충전</span></li>';
			else if (item == "28")
				html += '<li class="store_service hipass on"><i class="ico"></i><span class="txt">하이패스충전</span></li>';
			else if (item == "29")
				html += '<li class="store_service socar on"><i class="ico"></i><span class="txt">쏘카</span></li>';
			else if (item == "13")
				html += '<li class="store_service reserve on"><i class="ico"></i><span class="txt">리저브매장</span></li>';
			else if (item == "30")
				html += '<li class="store_service preorder on"><i class="ico"></i><span class="txt">예약픽업</span></li>';
			else if (item == "17")
				html += '<li class="store_service smoothieking on"><i class="ico"></i><span class="txt">스무디킹</span></li>';
			else if (item == "22")
				html += '<li class="store_service apple on"><i class="ico"></i><span class="txt">애플악세사리</span></li>';
			else if (item == "23")
				html += '<li class="store_service app_parcel on"><i class="ico"></i><span class="txt">앱택배</span></li>';
			else if (item == "24")
				html += '<li class="store_service wine on"><i class="ico"></i><span class="txt">와인</span></li>';
			else if (item == '25')
				html += '<li class="store_service qrenter on"><i class="ico"></i><span class="txt">QR출입</span></li>';
		});
		$("#ui_storeService").html(html);
	},


	//  연관 Vod
	updateRelatedVod: function(element) {

		$.ajax({
			type: "POST",
			url: "/store/getRelatedVod",
			async: false,
			data: {
				bizNo: jsStoreView.storeInfo.bizNo
			},
			success: function(result) {
				if (result.length == 0) {
					$("#ui_relatedVod").css("display", "none");
				}

				var html = '';
				$.each(result, function(idx, item) {
					html += '<li class="swiper-slide">';
					html += '<a href="/e24tv/detail_view/' + item.id + '">';
					html += '<div class="img">';
					html += '<div class="clip_time">';
					html += '<em class="font_gotham">' + item.vodDuration + '</em>';
					html += '</div>';
					html += '<img src="/file/download?id=' + item.vodThumImg + '&seq=' + item.maxFileSeq + '" alt=".">';
					html += '</div>';
					html += '<div class="info">';
					html += '<strong class="tit">' + item.vodTitle + '</strong>';
					html += '<div class="clip_number_info">';
					html += '<em class="play">' + item.vodViewCount + '</em>';
					html += '<em class="like">' + item.vodLikeCount + '</em>';
					html += '</div>';
					html += '</div>';
					html += '</a>';
					html += '</li>';
				});
				$("#ui_e24tv").html(html);
				storeTV();
			},
			error: function(xhr, ajaxOptions, thrownError) {
				openAlertPopup("일시적으로 서비스를 사용할 수 없습니다. 잠시 후 다시 시도해 주세요.");
//				console.log(xhr);
			}
		});
	},


	//  SNS 공유
	shareToKakaoTalk: function() {
		var image = $("#ui_storeImages img:eq(0)").attr("src");
		if (image.substr(0, 6) == "/file/") {
			image = "/file/view/" + $("#ui_storeImages img:eq(0)").data("idx");
		}

		shareSns.toKakaoTalk(jsStoreView.storeInfo.bizName, image);
		return false;
	},


	shareToKakaoStory: function() {
		var image = $("#ui_storeImages img:eq(0)").attr("src");
		if (image.substr(0, 6) == "/file/") {
			image = "/file/view/" + $("#ui_storeImages img:eq(0)").data("idx");
		}

		shareSns.toKakaoStory(jsStoreView.storeInfo.bizName, image, "");
		return false;
	},


	shareToFacebook: function() {
		shareSns.toFacebook();
		return false;
	},


	copyUrl: function() {
		shareSns.copyUrl($("#ui_copyUrl"));
		openAlertPopup("주소가 복사되었습니다.");
		return false;
	},


	//  단골매장
	clickFavoriteStore: function(bizNo, bizName, curLat, curLon) {
		var isMarked = $("#ui_favoriteMark").hasClass("on"); // 단골매장으로 선택되어있는 상태
		let passFlag = false;
		if(!isMarked) {
			fn_favoriteStore();
			if(!passFlag) {
				openAlertPopup("등록가능한 단골매장은 최대 3개입니다.");
				return false;
			}
		}
		$.ajax({
			type: "POST",
			url: (isMarked ? "/store/deleteFavoriteStore" : "/store/insertFavoriteStore"),
			async: false,
			data: { bizNo: bizNo },
			success: loadOk,
			error: loadError
		});

		function loadOk(result) {
			if (result.result == -1) {
				openAlertPopup("로그인이 필요한 서비스입니다.");
				location.href = "/login";
				return;
			}
			else {
				$(viewStore).find("#ui_favoriteMark").removeClass("off").removeClass("on");
				
				// 오버레이 & 마커 초기화
				if (currentLocationMarker_view) currentLocationMarker_view.setMap(null);
				if (customOverlay_view) customOverlay_view.setMap(null);

				// 이미지 경로
				var imgSrc;

				// 정상적인 경우
				if (isMarked) {
					$(viewStore).find("#ui_favoriteMark").addClass("off");
					$("#ui_favoriteMark > span").text("단골매장 비활성");
					imgSrc = '/assets/images/renew.common/pin_store_select.png';
					//emartBridge('removeFavoriteStore', {'message' : bizNo});
					emartBridge('removeFavoriteStore', {'bizNo' : bizNo, 'regularStore' : result.favoriteStoresCount});
					
					openAlertPopup("단골점포를 해제했습니다.");
				}
				else { // off -> on
					$(viewStore).find("#ui_favoriteMark").addClass("on");
					$("#ui_favoriteMark > span").text("단골매장 활성");
					imgSrc = '/assets/images/renew.common/pin_favorit_store_select.png';
					//emartBridge('addFavoriteStore', {'message' : bizNo});
                    emartBridge('addFavoriteStore', {'bizNo' : bizNo, 'regularStore' : result.favoriteStoresCount});

					openAlertPopup("단골점포로 선택했습니다.");
				}
				
				currentLocationMarker_view = daumMap.drawImageMarker2(curLat, curLon, { src: imgSrc, width: 44, height: 44 }, currentMapInstance_view);
				
				var itemName_view = '<div class="customoverlay on"><span class="title">' + bizName + '</span></div>';
				var position_view = new kakao.maps.LatLng(curLat, curLon);
				customOverlay_view = new kakao.maps.CustomOverlay({
					position: position_view,
					content: itemName_view
				});
				customOverlay_view.setMap(currentMapInstance_view);
				
				try 
				{
					favoriteHandler(bizNo, isMarked);
				}
				catch (e)
				{
					
				}
			}

		}

		function fn_favoriteStore() {
			$.ajax({
				type: 'GET'
				, url: '/store/FavoriteStore'
				, async: false
				, headers: 'charset=utf-8'
				, success: function (data, status, xhr) {
					console.log('12121211212');
					console.log(data['cnt']);
					if(data['cnt'] >= 3) passFlag = false;
					else passFlag = true;
					return false;
				}
				, error: function (data, status, xhr) {
					openAlertPopup("일시적으로 서비스를 사용할 수 없습니다. 잠시 후 다시 시도해 주세요.");
					return false;
				}
			});
		}

		function loadError(xhr, ajaxOptions, thrownError) {
			openAlertPopup("일시적으로 서비스를 사용할 수 없습니다. 잠시 후 다시 시도해 주세요.");
//			console.log(xhr);
		}
	},
	
	// 매장 정보 > 이달의 상품 찾기
	getStroeMonthGdsList: function( bizNo )
	{
		tabViewFn('#storeInfoTabCont'); //탭뷰 처리
		// 매장 정보 > 이달의 상품 찾기 추가
		// 무한 스크롤 함수 생성
		var targetScroll = $(".tab_inner .list_product");
		targetScroll.scroll( scrollFn );
		function scrollFn ( e )
		{ 
			var scrolltop , height , height_win;
		        scrolltop 	= targetScroll.scrollTop(); // 스크롤top 위치
		        height 		= targetScroll.find("ul").height() + 139;
		        height_win 	= targetScroll.innerHeight();

		   	//스크롤 하단 감지
		   	if (Math.ceil(scrolltop) + height_win >= height  ) 
			{
		   		var totalPages = parseInt ( listCnt2 / listData2.pageCnt );
		   		if ( listData2.currentPage > totalPages ) return;
		   		
		   		listData2.currentPage++;
		   		getStroeProuctList( listData2.strCd );
		   	}
		}
		
		
		$(".tab_inner .list_product ul").empty(); // 리스트 초기화
		listData2.currentPage = 1; // 현재 페이지 초기화
		
		// 이달의 상품 호출
		getStroeProuctList( bizNo );
		
		//매장 정보 > 이달의 상품 찾기
		function getStroeProuctList ( bizNo )
		{
			commonLoadingShow();
			listData2.strCd = bizNo;
			$.ajax (
			{   
				type        : "GET", 
				url         : "/api/month/gds/listV2",
				async       : true,
				data        : listData2,  
				success     : sendSuccess,
				error       : sendError
			} );
			
			function sendSuccess(data)
			{
				if ( data.totalCnt == 0 ) $("#no_gds_data2").show();
				else $("#no_gds_data2").hide();
					
				if ( listData2.currentPage == 1 ) listCnt2 = data.totalCnt;
				
				$.each(data.monthGdsList, function(key, row)
				{
					var stockQty = row.stockQty*1 < 1 ? "0" : row.stockQty;
					
					var html = "";
					html += '<li>';
					html += '	<div class="item_product">';
					html += '		<a href="javascript:void(0);" class="item">';
					html += '			<div class="img_area">';
					html += '				<div class="label_group">';
	//	 			html += '					<span class="label03 label_new"><em>new</em></span>';
	//	 			html += '					<div class="label03 label_age19"><em>19</em></div>';
					html += '				</div>';
					// html += '				<img class="img" src="'+ row.imgUrl +'" alt="">';
					// 이오피스 이미지 불러옴
					html += '				<img class="img" src="https://msave.emart24.co.kr/cmsbo/upload/nHq/plu_image/500x500/'+ row.gdsCd +'.JPG" alt="" style="width: 80%">';
					html += '			</div>';
					html += '			<div class="info_area">';
					html += '				<div class="tit">'+ row.gdsNm +'</div>';
					html += '				<div class="price_group">';
					if (row.reprSupPrc*1 > 0)
					{
						html += '				<span class="origin"><span class="blind">정상가</span><em>'+ emart24.util.numComma(row.reprSalPrc) +'</em>원</span>';
						html += '				<div class="sale_price">';
						html += '					<span class="sale"><span class="blind">할인율</span><em>'+ Math.round((1-row.reprSupPrc*1/row.reprSalPrc*1)*100) +'</em><span>%</span></span>';
						html += '					<span class="final"><span class="blind">구매금액</span><em>'+ emart24.util.numComma(row.reprSupPrc) +'</em><span>원</span></span>';
						html += '				</div>';
					}
					else
					{
						html += '				<span class="final"><span class="blind">구매금액</span><em>'+ emart24.util.numComma(row.reprSalPrc) +'</em><span>원</span></span>';
					}
					html += '				</div>';
					html += '			</div>';
					html += '			<div class="label_group">';
					html += '				<span class="label03 color05">';
					html += '					<em>잔여수량 : '; 
					html += '						<i>'+ stockQty +'</i>개';
					html += '					</em>';
					html += '				</span>';
					html += '			</div>';
					html += '		</a>';
					html += '	</div>';
					html += '</li>';
					$(".tab_inner .list_product ul").append(html);
				});
				commonLoadingHide();
			}
			
			function sendError()
			{
				openAlertPopup("일시적으로 서비스를 사용할 수 없습니다. 잠시 후 다시 시도해 주세요.");
				commonLoadingHide();
			}
		}
	},
	
	// 매장 정보 > 이달의 상품 찾기 > 오늘 픽업 운영 매장 확인
	getTodayPickupStoreCheck: function( bizNo )
	{
		todayPickupStoreCheck( bizNo );
		$("#todayPickupBtn").empty(); // 초기화
		
		// 오늘 픽업 운영 매장 확인 호출
		function todayPickupStoreCheck ( bizNo )
		{
			$.ajax (
			{   
				type        : "GET", 
				url         : "/api/month/gds/todayPickup/store",
				async       : true,
				data        : "bizNo=" + bizNo,  
				success     : sendSuccess,
				error       : sendError
			} );
			
			function sendSuccess(data)
			{
				var todayPickupStoreYn = data*1 < 1 ? "N" : "Y";
				var html = "";
				
				if ( todayPickupStoreYn == "Y" )
				{
					html += '<div class="btn_group">';
					html += '	<a href="todayPickup/main" class="btn_main btn_xlg active"><em>오늘픽업 바로가기</em></a>';
					html += '</div>';
					$("#todayPickupBtn").append(html);
				}
			}
			
			function sendError()
			{
				openAlertPopup("일시적으로 서비스를 사용할 수 없습니다. 잠시 후 다시 시도해 주세요.");
			}
		}
	}
	
};

function goFavoriteStoreConnexion(){
	var userBizNo = $("#userBizNo").val();
	
	$.ajax ({
		type: "POST",
        url: "/mypage/myFavoriteStoresChk",
        async: false,
		data: {bizNo: userBizNo},
		success: function(result)
		{
			var myFavoriteResult = result.result;
			
			if(myFavoriteResult.length == 0){
				 openAlertPopup("고객님의 단골점포가 아닙니다 단골점포 등록 진행 부탁드립니다");
			}else{
				var userBizNo = $("#userBizNo").val();
				var userBizName = $("#userBizName").val();
				
				location.href = '/mypage/favoriteStoreConnexion?bizNo=' + encodeURIComponent(userBizNo) + '&bizName=' + encodeURIComponent(userBizName);
				
			}
		}
	});
}

function goStrNoticeList(){
	var userBizNo = $("#userBizNo").val();
	var userBizName = $("#userBizName").val();
	
	location.href = '/mypage/strNotice/list?bizNo=' + encodeURIComponent(userBizNo) + '&bizName=' + encodeURIComponent(userBizName);
}

//점포의 단골라운지 사용 권한 조회
function connexionStrUse(bizNo){
	$.ajax({
		type: "GET",
		url: "/mypage/connexionStrUseCnt",
		async: false,
		data: {
			strCd: bizNo
		},
		success: function(result) {
			var result = Number(result.resultCnt);
			
			if(result > 0){
				$("#connexionBtnTestArea").show();
				$("#strNoticeTestArea").show();
			}else{
				$("#connexionBtnTestArea").hide();
				$("#strNoticeTestArea").hide();
			}
			
		},
		error: function(xhr, ajaxOptions, thrownError) {
			openAlertPopup("일시적으로 서비스를 사용할 수 없습니다. 잠시 후 다시 시도해 주세요.");
		}
	});
	
}

