/**
 * エリアを選択するタブの処理
 */
(function($) {

	var AREAS = [
		{ key: "hokkaido",      areaKB: "0" },
		{ key: "east",          areaKB: "1" },
		{ key: "chubu",         areaKB: "2" },
		{ key: "kansai",        areaKB: "4" },
		{ key: "chugokusikoku", areaKB: "5" },
		{ key: "kyusyu",        areaKB: "3" },
		{ key: "okinawa",       areaKB: "6" }
	];

	var COOKIE_NAME = "REXMENUSELECTEDAREACOOKIE";
	var DAYS = 730;

	// デフォルトのエリアは東日本
	var DEFAULT_KEY = AREAS[1].key;
	var currentKey = null;

	var setCookie = function(value) {
		$.cookie(COOKIE_NAME, value, { expires: DAYS, path: "/" });
	};

	var setArea = function(areaKey, selected, notSelected) {
		if (currentKey == areaKey) {
			return;
		}
		currentKey = areaKey;

		$.each(AREAS, function(index, area) {
			var tab = $("#tab-" + area.key);

			if (!tab.length) {
				return;
			}

			if (areaKey == area.key) {
				// クッキーにセット
				setCookie(area.areaKB);

				if ($.isFunction(selected)) {
					selected.call(tab, area);
				}
			} else {
				if ($.isFunction(notSelected)) {
					notSelected.call(tab, area);
				}
			}
		});
	};

	$(function() {
		var cookieArea = $.cookie(COOKIE_NAME);

		if (cookieArea != null) {
			$.each(AREAS, function(index, area) {
				if (cookieArea == area.areaKB) {
					currentKey = area.key;
					return false;
				}
			});
		} else {
			currentKey = DEFAULT_KEY;
		}

		$(".tabHead a").click(function(event) {
			if (!$(this).attr('id').match(/^tab-(.+)$/)) {
				return;
			}

			var areaKey = RegExp.$1;

			if (/^#/.test($(this).attr("href"))) {
				setArea(areaKey,
					// 選択されたタブに対する処理
					function(area) {
						var img = $(this).find("> img");
						img.attr("src", img.attr("src").replace(/(_over)?\.([^.]+)$/, "_crt.$2"));
						img.removeClass("overImg");
						$("#" + area.key).show();
					},
					// それ以外のタブに対する処理
					function(area) {
						var img = $(this).find("> img");
						img.attr("src", img.attr("src").replace(/_crt\.([^.]+)$/, ".$1"));
						img.addClass("overImg");
						$("#" + area.key).hide();
					}
				);

				event.preventDefault();
			} else {
				setArea(areaKey);
			}
		});
	});

})(jQuery);

