﻿$(document).ready(function () {
	// attach input hint handlers
	attachInputHintHandler($(".searchbox input"));
	attachInputHintHandler($("#setting .notice #panelSetting fieldset input"));
	attachLikeHandler();
	attachSnsHandler();

	// main items
	$("#main .product2 div.item").each(function (index) {
		$(this).click(function () {
			selectMainItem(index);
		});
	});

	// sub items
	$("#submain .today .right img").each(function (index) {
		$(this).click(function () {
			var selectedIndex = index;

			$("#submain .today .right img").attr("src", "/images/icon_off.png");
			$(this).attr("src", "/images/icon_on.png");

			$("#submain_content .today .product").hide();
			$("#submain_content .today .product").each(function (index) {
				if (index == selectedIndex) {
					$(this).show();
					today_index = index;
				}
			});
		});
	});

	// style
	$("#submain .style .right img").each(function (index) {
		$(this).click(function () {
			var selectedIndex = index;

			$("#submain .style .right img").attr("src", "/images/icon_off.png");
			$(this).attr("src", "/images/icon_on.png");

			$("#submain_content .style .product").hide();
			$("#submain_content .style .product").each(function (index) {
				if (index == selectedIndex) {
					$(this).show();
					style_index = index;
				}
			});
		});
	});

	$("#submain_content .style .product .thumbnails a").click(function () {
		var href = $(this).attr("href");

		$(this).parent().parent().find(".inner img").attr("src", href);

		return false;
	});

	// login
	var login = $(".login_box .username input");
	login.focus(function () {
		if ($(this).val() == $(this).attr("title")) {
			$(this).val("");
		}
	});
	login.blur(function () {
		if (!$(this).val()) {
			$(this).val($(this).attr("title"));
		}
	});
	if (!login.val()) login.val(login.attr("title"));

	// 지역설정
	$("#btnSetting").click(function () {
		var left = $(this).offset().left - $(this).parent().offset().left - 25;
		$("#panelSetting").css("left", left).toggle();
	});

	$("#panelSetting fieldset input").keydown(function (event) {
		if (event.keyCode == '13') {
			var q = $("#panelSetting fieldset input").val();
			searchRegion(q);
		}
	});

	$("#panelSetting fieldset img").click(function () {
		var q = $("#panelSetting fieldset input").val();
		searchRegion(q);
	});
});

function selectMainItem(selectedIndex) {
	$("#main .product2 div.item").each(function (index) {
		$(this).attr("class", "item deselected");
		if (index < selectedIndex) {
			$(this).find(".content").attr("class", "content top");
		}
		if (selectedIndex < index) {
			$(this).find(".content").attr("class", "content bottom");
		}

		if (selectedIndex == index) {
			$(this).attr("class", "item selected");
			$(this).find(".content").attr("class", "content");
		}
	});

	$("#main .product1").hide();
	$("#main .product1").each(function (index) {
		if (index == selectedIndex) $(this).show();
	});
}

// search
$(document).ready(function () {
	$(".searchbox input").keydown(function(event) {
		if (event.keyCode == '13') {
			$(".searchbox form").submit();
		}
	});
});

// SNS handler
function attachSnsHandler() {
	$(".sns").unbind("click");
	$(".sns").click(function () {
		var href = $(this).attr("href");
		$.get(href, function (data) {
			if (data) {
				if (data.url) {
					location.href = data.url;
				} else {
					alert(data);
				}
			} else {
				alert("전송이 완료되었습니다. :)");
			}
		}, "json");
		return false;
	});

	$("div.category li").unbind("mouseover");
	$("div.category li").mouseover(function () {
		$(this).find(".icon").show();
	});
	$("div.category li").unbind("mouseout");
	$("div.category li").mouseout(function () {
		$(this).find(".icon").hide();
	});
}

// Input hint handler
function attachInputHintHandler(input) {
	input.focus(handleInputHintFocus);
	input.blur(handleInputHintBlur);
	if (!input.val()) input.val(input.attr("title"));
}

function handleInputHintFocus() {
	if ($(this).val() == $(this).attr("title")) {
		$(this).val("");
	}
}

function handleInputHintBlur() {
	if (!$(this).val()) {
		$(this).val($(this).attr("title"));
	}
}

// Like handler
function attachLikeHandler() {
	$(".like").unbind("click");
	$(".like").click(function () {
		var countNode = $(this);
		var url = $(this).attr("href");

		$.get(url, function (data) {
			if (data) {
				alert(data);
			} else {
				var count = countNode.text();
				if (count) {
					countNode.text(parseInt(count) + 1);
				}
				alert("추천해주셔서 감사합니다.");
			}
		}, "json");

		return false;
	});
}

// 서브메인 (오늘의 할인상품 및 스타일 콜렉션)
var today_len = 0;
var today_index = 0;
var today_interval = null;
var style_len = 0;
var style_index = 0;
var style_interval = null;

$(document).ready(function () {
	today_len = $("#submain .today .right img").length;
	style_len = $("#submain .style .right img").length;

	var today_interval = setInterval(todayRollingHandler, 3000);
	$("#submain_content .today .product").mouseover(function () {
		clearInterval(today_interval);
	});
	$("#submain_content .today .product").mouseout(function () {
		today_interval = setInterval(todayRollingHandler, 3000);
	});
	var style_interval = setInterval(styleRollingHandler, 3000);
	$("#submain_content .style .product").mouseover(function () {
		clearInterval(style_interval);
	});
	$("#submain_content .style .product").mouseout(function () {
		style_interval = setInterval(styleRollingHandler, 3000);
	});
});

function todayRollingHandler() {
	today_index = (today_index + 1) % today_len;
	selectTodaySubItem(today_index);
}

function styleRollingHandler() {
	style_index = (style_index + 1) % style_len;
	selectStyleSubItem(style_index);
}

function selectTodaySubItem(selectedIndex) {
	var today_bullets = $("#submain .today .right img");
	var today_contents = $("#submain_content .today .product");

	today_bullets.attr("src", "/images/icon_off.png");
	today_contents.hide();

	today_index = selectedIndex;

	today_contents.each(function (index) {
		if (index == selectedIndex) {
			$(this).show();
		}
	});
	today_bullets.each(function (index) {
		if (index == selectedIndex) {
			$(this).attr("src", "/images/icon_on.png");
		}
	});
}

function selectStyleSubItem(selectedIndex) {
	var style_bullets = $("#submain .style .right img");
	var style_contents = $("#submain_content .style .product");

	style_bullets.attr("src", "/images/icon_off.png");
	style_contents.hide();

	style_index = selectedIndex;

	style_contents.each(function (index) {
		if (index == selectedIndex) {
			$(this).show();
		}
	});
	style_bullets.each(function (index) {
		if (index == selectedIndex) {
			$(this).attr("src", "/images/icon_on.png");
		}
	});
}

// 스프링타운
var st_p = 1;
var st_url = "/springtown/items";

function loadSpringTown(lat, lng) {
	$("#springtown_list").load("/springtown", function () {
		$("#btnSpringTownWrite").click(function () {
			$("#panelSpringTownWrite").toggle();
		});
		$(".lay-type-01 span.close").click(function () {
			$("#panelSpringTownWrite").hide();
		});
		$(".lay-type-01 span.btn").click(function () {
			var title = $("#panelSpringTownWrite input").val();
			var content = $("#panelSpringTownWrite textarea").val();

			$.post("/springtown/add", { title: title, content: content }, function (data) {
				loadSpringTown();
				$("#panelSpringTownWrite").hide();
			});
		});
		$("#panelSpringTownWrite textarea").keyup(function () {
			var remain = 140 - $(this).val().length;
			if (remain >= 0) {
				$("#txtRemain").text(remain + "자 남았습니다.");
			} else {
				$("#txtRemain").text((-remain) + "자 초과되었습니다.");
			}
		});
		// 목록, 더보기
		$(".fr-ad span.more").click(function () {
			var more = $(this);
			more.html("<img src='/images/loading.gif' />");
			$.get(st_url, { p: ++st_p }, function (data) {
				if (data) {
					$("#springtown_items").append(data);
					more.text("더보기");
				}
			});
		});

		loadSpringTownItems(lat, lng);
	});
}

function loadSpringTownItems(lat, lng) {
	$("#springtown_items").load("/springtown/items", { p: 1, lat: lat, lng: lng });
	st_p = 1;
}

// 하단 카테고리별 상품 조회
$(document).ready(function () {
	$("#prod-content .category li").click(function () {
		$("#prod-content .category li").attr("class", "");
		$(this).attr("class", "on");
		loadCategory($(this).attr("title"));
	});

	loadCategory("all");
});

function loadCategory(category) {
	$("#meta_category").load("/meta/subcategory/" + category, function () {
		$("#meta_category_items").load("/meta/subitems/" + category, function () {
			attachLikeHandler();
			attachSnsHandler();
		});
		$("#prod-content .category li").each(function () {
			if ($(this).attr("title") == category) {
				$(this).attr("class", "on");
			}
		});
	});
}

function loadMap(targetId, map_width, map_height, roadview_width, roadview_height, lat, lng) {
	var mapview_id = "mapview-" + targetId;
	var roadview_id = "roadview-" + targetId;
	var point = new DLatLng(lat, lng);

	$("#" + mapview_id).empty();
	var mapview = new DMap(mapview_id, { level: 2, point: point, width: map_width, height: map_height });
	mapview.addOverlay(new DMark(point));

	$("#" + roadview_id).empty();
	var roadview = new DRoadView(roadview_id, { point: point, width: roadview_width, height: roadview_height });

	$("#map-" + targetId).toggle();
}

// 지역 설정
function searchRegion(q) {
	$.getJSON("/api/regions", { q: q }, function (data) {
		var result = $("#panelSetting .search-list ul");
		result.empty();

		if (data && data.length > 0) {
			$.each(data, function (index, item) {
				var a = $("<a><img src=\"/images/btn_select.gif\" alt=\"선택\" /></a>").click(function () {
					$.cookie("_region", item.region_code);
					window.location.reload();
				});

				var li = $("<li />");
				li.text(item.address);
				li.append(a).click(function () {
					$.cookie("_region", item.region_code);
					window.location.reload();
				});

				result.append(li);
			});
		} else {
			result.append($("<li class=\"none\">검색 결과가 없습니다.</li>"));
		}
	});
}
