﻿
$(document).ready(function() {
	$("div.category>a:eq(0)").click();

	$("a").click(function(e) {
		if ($(this).attr("href") == "#")
			e.preventDefault();
	}).focus(function() {
		$(this).blur();
	});

	// 탭
	generateTabs("div.best-seller>p a", "div.best-seller>ul"); // Best Seller
	//generateTabs("div.side-pro>ul.tab a", "div.side-pro>ul.side-list"); // 우측 중간
	//generateTabs("div.prolist-block>ul.tab-list a", "div.prolist-block>ul.pro-list"); // 하단
	generateTabs("div.side-pro>ul>li>a", "ul.side-list"); // 카테고리 우측
	generateTabsWithContent("categoryBottom"); // 카테고리 바닥
	generateTabsWithContent("categorySmall");

	skinTypeRecommand.init(); //스킨타입 추천제품

	initSlider(); // 스마트서치
});

if (typeof console == "undefined") {
	var console = {
			log: function(args) {
				/*if (typeof setLog == "function")
			return setLog(args);*/
		}
	}
}

function generateTabs(titleElm, contentElm, effectSpeed) {
	/*
	* generateTabs / 번거롭고 귀찮은 탭 스크립팅 한방에..
	- args
	titleElm    : $(selector)   / 필수.탭 제목
	contentElm  : $(selector)   / 필수.탭 내용
	effectSpeed : String or Int / 옵션.이펙트 속도(2000, "slow" ...)
	- author
	saystone@wylielab.co.kr
	- needed
	jQuery 1.3.x or higher
	*/

	if (effectSpeed == null) effectSpeed = "";

	var hasTitleImg = $(titleElm).eq(0).children("img").length == 1 ? true : false;
	//console.log(hasTitleImg);

	$(titleElm).each(function(i) {
		$(this).click(function(e) {
			$(contentElm).hide(effectSpeed);
			$(contentElm).eq(i).show(effectSpeed);

			// 타이틀 이미지가 바뀌어야 할때
			if (hasTitleImg) {
				$(titleElm).each(function(i) {
					var strImg = $(this).children("img").attr("src");
					//console.log(strImg);
					strImg = strImg.replace(/\_on./gi, "_off.");
					$(this).children("img").attr("src", strImg);
				});

				var strImg = $(titleElm).eq(i).children("img").attr("src");
				strImg = strImg.replace(/\_off./gi, "_on.");
				$(titleElm).eq(i).children("img").attr("src", strImg);
			}

			$(titleElm).parent().removeClass("on");
			$(titleElm).eq(i).parent().addClass("on");
		});
	});

	$(contentElm).not(":first").hide();
}

// ajax 컨텐츠 불러오는 탭
function generateTabsWithContent(type) {
	var titleElm, contentElm;

	switch (type) {
		case "bestSeller":
			titleElm = "div.best-seller>p a";
			contentElm = "div.best-seller>ul";
			break;
		case "categorySmall":
			titleElm = "div.side-pro>ul.tab a";
			contentElm = "div.side-pro>ul.side-list";
			break;
		case "categoryBottom":
			titleElm = "div.prolist-block>ul.tab-list a";
			contentElm = "div.prolist-block>ul.pro-list";
			break;

	}

	var hasTitleImg = $(titleElm).eq(0).children("img").length == 1 ? true : false; // A01:타이틀이 이미지 일때
	//console.log(hasTitleImg);

	$(titleElm).each(function(i) {
		$(this).click(function(e) {
			$(titleElm).each(function(i) { // 비활성화 이미지로 교체
				if (hasTitleImg) { // A01:타이틀 이미지가 바뀌어야 할때
					//var strImg = $(this).children("img").attr("src");
					var strImg = $(titleElm + ":eq(" + i + ")>img").attr("src");

					//console.log(strImg);
					strImg = strImg.replace(/\_on./gi, "_off.");

					//$(this).children("img").attr("src", strImg);
					$(titleElm + ":eq(" + i + ")>img").attr("src", strImg);
				}

				//console.log($(contentElm).eq(i).data("loaded"));
				if (type == "bestSeller") {
					if (i != 0) {
						if ($(contentElm).eq(i).data("loaded") == undefined) {
							$(contentElm).eq(i).data("loaded", false);
						}
					}
				}else if (type == "categorySmall") {
					if (i != 0) {
						if ($(contentElm).eq(i).data("loaded") == undefined) {
							$(contentElm).eq(i).data("loaded", false);
						}
					}
				}
				else if (type == "categoryBottom") {
					if (i != 0) {
						if ($(contentElm).eq(i).data("loaded") == undefined) {
							$(contentElm).eq(i).data("loaded", false);
						}
					}
				}
				if ($(contentElm).eq(i).data("loaded") == undefined) {
					$(contentElm).eq(i).data("loaded", false);
				}

				//console.log($(contentElm).eq(i).data("loaded"));
			});

			if (hasTitleImg) { // A01:타이틀 이미지가 바뀌어야 할때
				// 현재 인덱스 활성 이미지로 교체
				//var strImg = $(titleElm).eq(i).children("img").attr("src");
				var strImg = $(titleElm + ":eq(" + i + ")>img").attr("src");

				strImg = strImg.replace(/\_off./gi, "_on.");

				//$(titleElm).eq(i).children("img").attr("src", strImg);
				$(titleElm + ":eq(" + i + ")>img").attr("src", strImg);
			}

			$(titleElm).parent().removeClass("on"); // 전체 타이틀 텍스트 비활성화 클래스 적용
			$(titleElm).eq(i).parent().addClass("on"); // 현재 타이틀 타이틀 텍스트 활성화 클래스 적용

			//console.log($(contentElm).eq(i).html());
			if ($(contentElm).eq(i).data("loaded") == false) { // 한번만 로드
				if(type == "categorySmall"){
					getResult(i, type, $(titleElm).eq(i).parent().attr("rel"));
				}else{
					getResult(i, type); // 해당하는 컨텐츠 인덱스 노드에 데이터 뿌려둠
				}
			}

			$(contentElm).hide();
			$(contentElm).eq(i).show();

		});
	});

	$(contentElm).not(":first").hide();

	function getResult(i, type, TS_CODE) {
		if(type == "categorySmall"){
			$.post("first_ajax.aspx", { type: type, param: TS_CODE }, function(result) {
				$(contentElm).eq(i).html(result).data("loaded", true);

				//if(type=="categorySmall") alert(result);
			}, "html");
		}else{
			$.post("first_ajax.aspx", { type: type, param: i }, function(result) {
				$(contentElm).eq(i).html(result).data("loaded", true);
				//if(type=="categorySmall") alert(result);
			}, "html");
		}
	}

	//run at once
	if(type=="categorySmall"){
		getResult(0, type, $(titleElm).eq(0).parent().attr("rel"));
	}else{
		getResult(0, type);
	}
}

// 스킨타입 추천제품
var skinTypeRecommand = {
	props: {
		// POST to first_ajax.aspx
		skinType: 100, // 스킨타입 전체 디폴트
		category: 2, 	// 카테고리 바디케어 디폴트
		skinWorry: 100,
		sex: ""
	},

	init: function() {
		skinTypeRecommand.set("skinType"); // 피부타입 클릭 이벤트 및 인덱스 셋팅 후 추천제품 가져옴
		skinTypeRecommand.set("category"); // 카테고리 클릭 이벤트 및 인덱스 셋팅 후 추천제품 가져옴

		// run at once
		skinTypeRecommand.getContent("both");
	},

	set: function(type) {
		var loopElem;

		if (type == "skinType") {
			loopElem = "div.ptype>ul>li";
		} else if (type == "category") {
			loopElem = "div.catego>ul>li";
		}

		$(loopElem).each(function(i) {
			$(this).click(function(e) {
				// skinWorry 즉 피부고민은 roundabout을 이용하므로 이미지 오버/아웃 기능에 해당 없음
				if (type == "skinType" || type == "category") {
					$(loopElem).each(function(i) {
						//console.log(i);
						var imgOn = $(this).children("a").children("img").attr("src");
						//console.log(imgOn);
						imgOn = imgOn.replace(/\_on./gi, "_off.");
						$(this).children("a").children("img").attr("src", imgOn);
					});

					var imgOff = $(this).children("a").children("img").attr("src");
					imgOff = imgOff.replace(/\_off./gi, "_on.");
					$(this).children("a").children("img").attr("src", imgOff);
				}

				var rel = $(this).attr("rel");

				if (type == "skinType") {
					skinTypeRecommand.props.skinType = rel;
					skinTypeRecommand.getContent("one");
				} else if (type == "category") {
					//if (skinTypeRecommand.props.skinType != "100") {
					skinTypeRecommand.props.category = rel;
					skinTypeRecommand.props.skinWorry = 100;
					//}
					skinTypeRecommand.getContent("both");
				}
				//console.log(rel);

			});
		});
		
		$("input[name=skinSex]").click(function(e){
			skinTypeRecommand.props.sex = $(this).val();
			skinTypeRecommand.getContent("one");
		});
	},

	getContent: function(type) {
		// 추천제품
		var p1 = this.props.skinType;
		var p2 = this.props.category;
		var p3 = this.props.skinWorry;
		var p4 = this.props.sex;

		// 카테고리 항목에 변경이 있을 때 피부고민 뿌려 줌
		if (type == "both") {
			$.post("first_ajax.aspx", { type: "skinWorry", p1: p1, p2: p2, p3: p3, p4: p4 }, function(result) {

				$("div.ptruble>ul").html(result).roundabout({
					btnNext: "#btnUp",
					btnPrev: "#btnDown",
					shape: "waterWheel",
					minOpacity: 0,
					duration: 300,
					easing: "easeOutCubic"
					//minScale:1
					//clickToFocus: false,
				});

				$("div.ptruble>ul>li").focus(function(e) {
					imgOff = $(this).children().children().attr("src");
					//$(this).fadeOut("slow");
					$(this).children().children().attr("src", imgOff.replace(/\_off./gi, "_on."));
					var rel = $(this).attr("rel");
					skinTypeRecommand.props.skinWorry = rel;
					skinTypeRecommand.getContent("one");
				}).blur(function(e) {
					imgOn = $(this).children().children().attr("src");
					//$(this).fadeOut("slow");
					$(this).children().children().attr("src", imgOn.replace(/\_on./gi, "_off."));
				});

				var imgOnFirst = $("div.ptruble>ul>li:eq(0)>a>img").attr("src");
				$("div.ptruble>ul>li:eq(0)>a>img").attr("src", imgOnFirst.replace(/\_off./gi, "_on."));
				
				
				
			}, "html");
		}


		// depth에 관계 없이 추천 제품은 무조건 보여줌
		$.post("first_ajax.aspx", { type: "recommandProduct", p1: p1, p2: p2, p3: p3, p4: p4 }, function(result) {
			$("ul.pro-holder").html(result).roundabout({
				btnNext: ".btn-right",
				btnPrev: ".btn-left",
				minOpacity: -2,
				duration: 300,
				easing: "easeOutCubic",
				classHolder: "roundabout-holder2",
				classMoveableItem: "roundabout-moveable-item2",
				classInFocus: "roundabout-in-focus2"
				//debug:true
				//minScale:0
				//bearing:100,
				//tilt:5
				//clickToFocus: false,
			});

			$("ul.pro-holder>li").focus(function() {
				$(this).addClass("item-focus");
				//$(this).animate({border:"5px solid #74BF02"}, 300);
				$(this).children().show();
			}).blur(function() {
				$(this).removeClass("item-focus");
				//$(this).animate({ border: "1px solid #74BF02" }, 300);
				$(this).children().not(".pro-img").hide();
			});

			$("ul.pro-holder>li:eq(0)").addClass("item-focus");
			//console.log($("ul.pro-holder>span:last").text());
			$("ul.pro-holder>li:eq(0)>span").show(0);
			
			var totalCount = parseInt($("ul.pro-holder>span:last").text());
			if(totalCount == 0){
				//alert("검색 결과가 없습니다.");
				$("ul.pro-holder").html("<div style='text-align:center;width:100%;height:100%;'><br /><br /><br /><br /><br /><br /><br /><br /><span style='font-size:12px;font-weight:bold;'>검색 결과가 없습니다.</span></div>");
				//skinTypeRecommand.props.skinWorry = 100;
				//skinTypeRecommand.getContent("both");
				return ;
			}else{
				$("div.recomen>p.total-num>a").text($("ul.pro-holder>span:last").text());
			}
		}, "html");

	}
}

/* 스마트서치 슬라이더 */
function initSlider() {
	var start = 10000;
	var end = 80000;
	var beforeStart = start;
	var beforeEnd = end;

	$("#slider-range").slider({
		range: true,
		min: 10000,
		max: 80000,
		values: [start, end],
		step: 10000,
		slide: function(event, ui) {
			// 슬라이드 이벤트 발생 시 값 셋팅
			currentStart = ui.values[0];
			currentEnd = ui.values[1];
			$("#slider-start>p span").html(commaNum(currentStart) + '<img src="/shop/images/smart/txt_won.gif" alt="원대" />');
			$("#slider-end>p span").html(commaNum(currentEnd) + '<img src="/shop/images/smart/txt_won.gif" alt="원대" />');

			var positionTop = $("#slider-range a:eq(0)").position().top - 5;
			var docWidth = $(document).width();
			var fixed = 470;

			//시작 슬라이더와 끝 슬라이더를 구분하여 해당되는 슬라이더 위에 가격 레이어 배치
			if (start != ui.values[0]) {
				start = ui.values[0];
				//positionLeftStart = (beforeStart >= ui.values[0]) ? positionLeftStart += 2 : positionLeftStart += 16;

				var pageX = event.pageX; // get absolute left 
				pageX = (pageX - docWidth / 2) + fixed; // fix with document width
				pageX = (beforeStart >= ui.values[0]) ? pageX -= 1 : pageX += 4; // 여백 교정

				$("#slider-start").css({
					//left: event.pageX + "px",
					left: pageX + "px",
					//left: (positionLeftStart) + "px",
					top: (positionTop - 2) + "px"
				});
			}

			if (end != ui.values[1]) {
				end = ui.values[1];
				//positionLeftEnd = (beforeEnd >= ui.values[1]) ? positionLeftEnd -= 29 : positionLeftEnd -= 17;

				var pageX = event.pageX;
				pageX = (pageX - docWidth / 2) + fixed;
				pageX = (beforeEnd >= ui.values[1]) ? pageX -= 1 : pageX += 4; // 여백 교정

				$("#slider-end").css({
					//left: (event.pageX) + "px",
					left: pageX + "px",
					//left: (positionLeftEnd + 30) + "px",
					top: (positionTop - 2) + "px"
				});
			}

			beforeStart = ui.values[0];
			beforeEnd = ui.values[1];

			//				alert(event)
			//				console.log("start:" + start + " /\n end:" + end + " /\n ui.values[0]:" + ui.values[0] + " /\n ui.values[1]:" + ui.values[1]);
			//				console.log($("#slider-start").css("top") + " / " + $("#slider-start").css("left"));
			//				console.log
		},
		start: function(event, ui) {

		},
		stop: function(event, ui) {
			//console.log(beforeStart);
			//console.log(beforeEnd);
			$.post("first_ajax.aspx", { type: "giftSet", p1: beforeStart, p2: beforeEnd }, function(result) {
				$("div.mony-gift>ul.pro-list").html(result);
				$("div.smart-search>span.total-pro>a").text($("div.mony-gift>ul.pro-list>span").text());
			}, "html");
		}
	});

	//		$("#slider-start>p span").text($("#slider-range").slider("values", 0));
	//		$("#slider-end>p span").text($("#slider-range").slider("values", 1));

	$("#slider-range a:eq(0)").html('<img src="/shop/images/smart/costscroll_btn.gif" />').focus(function() { this.blur(); });
	$("#slider-range a:eq(1)").html('<img src="/shop/images/smart/costscroll02_btn.gif" />').focus(function() { this.blur(); });

	var posStartLeft, posStartTop, posEndLeft, posEndTop;
	try {
	posStartLeft = Math.round(parseFloat($("#slider-range a:eq(0)").position().left, 2));
	posStartTop = Math.round(parseFloat($("#slider-range a:eq(0)").position().top, 2));

	posEndLeft = Math.round(parseFloat($("#slider-range a:eq(1)").position().left, 2));
	posEndTop = Math.round(parseFloat($("#slider-range a:eq(1)").position().top, 2));

	//console.log(posStartLeft);

	$("#slider-start").css({
		left: (posStartLeft + 8) + "px",
		top: (posEndTop - 7) + "px"
	}).show();
	$("#slider-end").css({
		left: (posEndLeft + 8) + "px",
		top: (posEndTop - 7) + "px"
	}).show();
	} catch(e) {}

	// run at once
	$.post("first_ajax.aspx", { type: "giftSet", p1: beforeStart, p2: beforeEnd }, function(result) {
		$("div.mony-gift>ul.pro-list").html(result);
		$("div.smart-search>span.total-pro>a").text($("div.mony-gift>ul.pro-list>span").text());
	}, "html");
}

