/* =====================================================================
*
*   common.js | for MAIKO VILLA KOBE
*
* =================================================================== */

if(!window.MVK) window.MVK = {};

/* =====================================================================
*
*	RESERVATION FORM MODULE
*
* =================================================================== */

$.extend(MVK.reserve = {}, {
	
	tplPath : "/tpl/reservation.tpl.html",
	incPath : "/phplib/get_current_date.php",
	date 	: null,
	tpl 	: null,
	mode 	: null,
	isLeapYear : false,
	
	
	/*--------------------------------------------------
	* 初期化
	--------------------------------------------------*/
	init : function(i_mode){
		this.mode = i_mode;
		
		/*--------------------------------------------------
		* サーバーから現在日時を取得
		* エラーを拾った場合はJSで日時を取得し利用
		--------------------------------------------------*/
		try {
			this._getCurrentDate();
		} catch(e) {
			var date = new Date();
			var dateArr = [ date.getFullYear(), date.getMonth() + 1, date.getData() ];
			this.date = dateArr;
			this._getTpl();
		}
	},
	
	/*--------------------------------------------------
	* サーバーから現在日時を取得
	--------------------------------------------------*/
	_getCurrentDate : function() {
		var self = this;
		$.ajax({
			type 	:	"GET",
			url 	: 	self.incPath,
			success : 	function(data){
				self.date = data.split(",");
				self._getTpl();
			},
			error	: function(e) { throw new Error("no response"); }
		});
	},
	
	/*--------------------------------------------------
	* 表示するフォームテンプレートをAJAXで取得
	--------------------------------------------------*/
	_getTpl : function(){	
		var self = this;
		$.ajax({
			type	:	"GET",
			url		: 	self.tplPath,
			dataType:	"html",
			success	:	function(data){
				self.tpl = {
					side : $(data).find("#ReservationTplSide").find("form"),
					body : $(data).find("#ReservationTplBody").find("form")
				}
				
				self._setTpl();
			}
		});
	},
	
	/*--------------------------------------------------
	* 取得したテンプレートを該当の場所に追加
	--------------------------------------------------*/
	_setTpl : function(){
		var self = this;		
		var dateGroup = this._getTodayAndTomorrow();
		var elems = [];
		
		if(this.mode.side != 0){
			this.tpl["side"].insertAfter("#SideReservation h3");
			elems.push(self.tpl["side"].get(0));
		} 
		
		if(this.mode.body != 0){
			this.tpl["body"].insertAfter("#jStayReservationSection h3");
			elems.push(self.tpl["body"].get(0));
		} 
		
		var $tpl = $(elems);
		var opts = [];
		var $yearSelects = $tpl.find("select[name='chkin_yy'], select[name='chkout_yy']");
		var $monthSelects = $tpl.find("select[name='chkin_mm'], select[name='chkout_mm']");
		var $dateSelects = $tpl.find("select[name='chkin_dd'], select[name='chkout_dd']");
		var currentYear = this.date[0];
		var currentMonth = this.date[1];
		var currentDate = this.date[2];
		
		for(var i = 0; i < 2; i++) {	
			var line = '<option value="' + currentYear + '">' + currentYear + '</option>';
			currentYear++;
			opts.push(line);
		}
		
		$yearSelects.empty();
		$yearSelects.append($(opts.join("")));
		
		this._setCurrentDate($yearSelects, dateGroup.tY);
		this._setCurrentDate($monthSelects, dateGroup.tM);
		this._setCurrentDate($dateSelects, dateGroup.tD);
	},
	
	/*--------------------------------------------------
	* 追加したフォームに今日の日付と明日の日付を設定
	--------------------------------------------------*/
	_setCurrentDate : function(i_target, i_dateArr){
		var $target = i_target;
		var dateArr = i_dateArr;
		
		$target.each(function(i, i_this){
			$(this)
				.find('option[value="' + MVK.util.addLeadingZero(dateArr[i % 2]) + '"]')
				.attr("selected", "selected");
		});
	},
	
	/*--------------------------------------------------
	* 今日の日付から明日の年月日を計算し、それぞれをまとめて返す
	--------------------------------------------------*/
	_getTodayAndTomorrow : function(){
		var year = parseInt(this.date[0]);
		var month = parseInt(this.date[1]);
		var day = parseInt(this.date[2]);
		var tomorrow = new Date(year, month -1 , day + 1);
		var ret = {
			tY : [ year, tomorrow.getFullYear() ],
			tM : [ month, tomorrow.getMonth() + 1 ],
			tD : [ day, tomorrow.getDate() ]
		}
		
		return ret;		
	}

});

/* =====================================================================
*
*	DROPDOWN NAV MODULE
*
* =================================================================== */

$.extend(MVK.dropDownNav = {}, {
	
	/*--------------------------------------------------
	* ドロップダウン機能を付加
	--------------------------------------------------*/
	init : function(i_target) {
		var $target = $(i_target);
		var $btns = $target.children();
		$btns.each(function(){
			var tID;
			var $child = $(this).find("ul");
			if($child.length == 0) return true;
			
			$child
				.css("display", "none")
				.css("position", "absolute");
			$(this).hover(function(e){
				clearTimeout(tID);
				$child.filter(':not(:animated)').slideDown(300);
			}, function(e){
				tID = setTimeout(function(){
					$child.slideUp(300);
				}, 300);
			});

		});
		
		//plugin test code
		//$(i_target).ExRollOver();
		//$(i_target).data("RO")["test"]();
	}
	
});


/* =====================================================================
*
*	FONTSIZE CHANGE MODULE
*
* =================================================================== */

$.extend(MVK.fontSize = {}, {
	
	target : null,
	cookieName : "fontsize",
	size : {
		"FontSizeL" : "110%",
		"FontSizeM" : "95%",
		"FontSizeS" : "80%"
	},
	
	/*--------------------------------------------------
	* 初期化
	--------------------------------------------------*/
	init : function(i_target) {
		
		var self = this;
		var $btns = this.target = $(i_target).find("a");
		$btns.each(function(){
			
			$(this).bind("click", function(){
				var size = $(this).attr("id");
			
				self._clearView();
				self._setSize(size);
			});
			
		});
		
		this._check();
	},
	
	/*--------------------------------------------------
	* cookieをチェックして設定すべきサイズを決定
	--------------------------------------------------*/
	_check : function(){
		var current = $.cookie(this.cookieName);
		if(current == null) current = "FontSizeS";
		this._setSize(current);
	},
	
	/*--------------------------------------------------
	* サイズを設定し、cookieに保存
	--------------------------------------------------*/
	_setSize : function(i_sizeStr) {
		var val = i_sizeStr;
		$("body").css("font-size", this.size[val]);
		$("#" + val).addClass("selected");
		$.cookie(this.cookieName, val, { path: '/', expires: null });
	},
	
	/*--------------------------------------------------
	* ナビのselected状態を全て解除
	--------------------------------------------------*/
	_clearView : function() {
		this.target.each(function(){
			if($(this).hasClass("selected")) $(this).removeClass("selected");
		});
	}
	
});



/* =====================================================================
*
*	RECOMMEND MODULE
*
* =================================================================== */
$.extend(MVK.recommendList = {}, {

	/*--------------------------------------------------
	* 初期化
	--------------------------------------------------*/
	init: function( i_controller ){
		var self = this;
		var $controller = $( i_controller );
		
		/*--------------------------------------------------
		* CHANGER
		--------------------------------------------------*/	
		$controller.bind("change", function(){
			var val = "j" + $(this).val();
			self._allClear();
			self._show( val );
		});		
		$controller.change();	
 	},
 	
 	/*--------------------------------------------------
	* 全消し
	--------------------------------------------------*/
 	_allClear: function(){
 		var $children = $( "#jRecommendTargets" ).children();
 		$children.hide();
 	},
 	
 	/*--------------------------------------------------
	* 表示
	--------------------------------------------------*/
 	_show: function(i_target){
 		$( "#" + i_target ).fadeIn();
 	}
});



/* =====================================================================
*
*	REQUEST FORM MODULE
*
* =================================================================== */
$.extend(MVK.requestForm = {},{
	
	/*--------------------------------------------------
	* DATA
	--------------------------------------------------*/
	rules: {
		"宿泊": 			"#jStayForm",
		"レストラン・バー": "#jRestaurantForm",
		"宴会": 			"#jBanquetForm"
	},
	
	/*--------------------------------------------------
	* 初期化
	--------------------------------------------------*/
	init: function( i_controller ){
		
		var self = this;
		var $controller = $( i_controller );
		var $checked = $( i_controller + ":checked" );
		
	
		/*--------------------------------------------------
		* チェックついて要素ははずす
		--------------------------------------------------*/
		$checked.click();
				
		/*--------------------------------------------------
		* 全消し
		--------------------------------------------------*/
		$(this.rules["宿泊"]).hide();
		$(this.rules["レストラン・バー"]).hide();
		$(this.rules["宴会"]).hide();
		
		/*--------------------------------------------------
		* CHANGER
		--------------------------------------------------*/
		$controller.bind("click", function() {
			var val = $(this).val();
			
			/*--------------------------------------------------
			* (':checked')の分岐
			--------------------------------------------------*/
			if ($(this).is(':checked')) self._show( val, this );
			else self._hide( val, this );
		});
	},	
	
	/*--------------------------------------------------
	* 表示
	--------------------------------------------------*/
	_show: function( i_target, i_parent ){
		var $target = $(this.rules[i_target]);
		var $parent = $(i_parent + ":checked");
		$target.show();
	},
	
	/*--------------------------------------------------
	* 非表示
	--------------------------------------------------*/
	_hide: function( i_target, i_parent ){
		var $target = $(this.rules[i_target]);
		var $parent = $(i_parent + ":checked");
		$target.hide();
	}
});




/* =====================================================================
*
*	REQUEST FORM MODULE
*
* =================================================================== */
$.extend(MVK.banquetTab = {},{
	
	/*--------------------------------------------------
	* DATA
	--------------------------------------------------*/
	isHushAccess : false,
	rules: {
		"西洋料理": "#jWesternStyle",
		"日本料理": "#jJapaneseStyle",
		"中国料理": "#jChineseStyle"
	},
	
	
	/*--------------------------------------------------
	* 初期化
	--------------------------------------------------*/
	init: function( i_controller ){
	
		var url = location.href;
		if(url.indexOf("#") != -1) this.isHushAccess = true;
		
		var self = this;
		var $controller = $(i_controller).find("a");
		/* var $first = i_controller.filter('[name="西洋料理"]'); */
		
		$controller.filter('[title="西洋料理"]').addClass("selected");
		
		
		this._hide();
		this._show($controller.filter('[title="西洋料理"]'));
		
		$controller.each(function(){			
			$(this).hover(function(){
				//over
				if($(this).hasClass("selected")) return;

				var $overSrc = $(this).find("img").attr("src").replace(".gif","-over.gif");
				$(this).find("img").attr("src", $overSrc);
				
				
			},function(){
				//out
				var $outSrc = $(this).find("img").attr("src").replace("-over","");
				$(this).find("img").attr("src", $outSrc);

			});
			
			/* click */
			$(this).bind("click", function(){
				self._removeAllSelected( $controller );
				self._selectNew( this );
				return false;
			});
		});
	},
	
	_removeAllSelected: function( i_controller ){
		
		var self = this;
	
		i_controller.removeClass("selected");	
		i_controller.each(function(){
			var $defaultSrc = $(this).find("img").attr("src").replace("-selected","");
			$(this).find("img").attr("src", $defaultSrc);
			self._hide();
		});
				
		//if(!$(i_newSelect).hasClass("selected")) return;
		
			
	},
	
	_selectNew : function(i_newSelect) {
		
		var replacer;
		if(!this.isHushAccess) replacer = "-over.gif";
		else replacer = ".gif";
		this.isHushAccess = false;
			
		$(i_newSelect).addClass("selected");
		var $selectedSrc = $(i_newSelect).find("img").attr("src").replace(replacer,"-selected.gif");
		$(i_newSelect).find("img").attr("src", $selectedSrc);
		this._show( $(i_newSelect) );
		
	},
	
	
	_hide: function(){
		$(this.rules["西洋料理"]).hide();
		$(this.rules["日本料理"]).hide();
		$(this.rules["中国料理"]).hide();
	},
	
	
	_show: function( i_newSelect ){
		var $key = i_newSelect.attr("title");
		var $target = $(this.rules[$key]);
		$target.fadeIn();
	}
});


/* =====================================================================
*
*	FAILITIES MODULE
*
* =================================================================== */
$.extend(MVK.floorView = {},{
	
	/*--------------------------------------------------
	* DATA
	--------------------------------------------------*/
	rules: {
		"mc_h1": "#ExternalHonkan1",
		"mc_h2": "#ExternalHonkan2",
		"mc_h3": "#ExternalHonkan3",
		"mc_h4": "#ExternalHonkan4",
		"mc_h5": "#ExternalHonkan5",
		"mc_h14": "#ExternalHonkan14",
		"mc_a0": "#ExternalAnnex0",
		"mc_a1": "#ExternalAnnex1",
		"mc_a2": "#ExternalAnnex2",
		"mc_a3": "#ExternalAnnex3",
		"mc_a4": "#ExternalAnnex4",
		"mc_a8": "#ExternalAnnex8",
		"mc_wedding": "/wedding/"
		/*, "mc_parking": "#ParkingInfoSection" */
	},
	
	init: function(){	
		/* 消す */
		this._allHide();
		$("#ExternalHonkan1").fadeIn();
	},
	
	
	/*--------------------------------------------------
	* Flashから切り替え用
	--------------------------------------------------*/
	_floorMapChanger: function( i_target ){
		
		var $target = $(this.rules[i_target]); 
		
		/*
		if( i_target == "mc_parking" ){
			this._toParking();
			
			var dest = $(this.rules[i_target]).offset().top;
			$("html,body").stop().animate( {scrollTop:dest}, 600 );
			
			return;
		}
		*/
		
		this._allHide();
		$target.stop().show().css( { opacity:0 } ).animate( { opacity:1 }, 500);
	},
	
	
	/*--------------------------------------------------
	* 全消し
	--------------------------------------------------*/
	_allHide: function(){
		$("#ExternalHonkan1").stop().hide();
		$("#ExternalHonkan2").stop().hide();
		$("#ExternalHonkan3").stop().hide();
		$("#ExternalHonkan4").stop().hide();
		$("#ExternalHonkan5").stop().hide();
		$("#ExternalHonkan14").stop().hide();
		$("#ExternalAnnex0").stop().hide();
		$("#ExternalAnnex1").stop().hide();
		$("#ExternalAnnex2").stop().hide();
		$("#ExternalAnnex3").stop().hide();
		$("#ExternalAnnex4").stop().hide();
		$("#ExternalAnnex8").stop().hide();
	}
});




/* =====================================================================
*
*	UTILITY MODULE
*
* =================================================================== */

$.extend(MVK.util = {}, {
	
	/*--------------------------------------------------
	* 渡された値が1桁なら先頭に"0"をつけて返す
	--------------------------------------------------*/
	addLeadingZero : function(i_num) {
		if(isNaN(i_num)) return;
		var numStr = String(i_num);
		if(numStr.length < 2) numStr = "0" + numStr;
		return numStr;
	},
	
	/*--------------------------------------------------
	* 渡された年が閏年かどうかを判定
	--------------------------------------------------*/
	isLeapYear : function(i_currentY){
		var currentY = i_currentY;
		var leapCond1 = currentY % 4;	
		var leapCond2 = currentY % 100; 
		var leapCond3 = currentY % 400; 
		
		if(leapCond1 == 0) {
			if(leapCond2 != 0) {
				return true;
			} else {
				if(leapCond3 == 0) return true;
				else return false;
			}
		} else {
			return false;
		}
	}
	
});

/* =====================================================================
*
*	PLUGIN DIFINES
*
* =================================================================== */

/*--------------------------------------------------
* MVK用カスタムImgSwapプラグイン
--------------------------------------------------*/
(function($){
	
	$.fn.exImgSwap = function(i_option){
		
		var options = $.extend({ trigger:"click", attribute:"href" }, i_option);
		var isAnimate = false;
		
		$(this).each(function(){
			var href = String($(this).attr(options.attribute));
			var rs = href.match(/#(.+)$/);
			if ( rs ) {
			
				$('<img>').attr('src',href);
				$(this).bind( options.trigger, function(){
				
					var $display = $("#"+rs[1]);
					var $parent = $display.parent();
					$parent.css("position", "relative");
					$display.css({
						"position" : "absolute"
					});
					
					//ここの実装が微妙。
					if(isAnimate) {
						var $childs = $parent.children();
						var $overlayAlias = $childs.filter(":not(#MainDisplay)");
						$childs.filter(":animated").stop().clearQueue();
						$display.remove();
						$display = $overlayAlias;
					}
					
					//for IEBug 暫定回避
					var h = $display.height();
	

					$parent.height(h);
					var $overlay = $("<img>").attr("src", href);
					$parent.prepend($overlay);
					$overlay.css({
						"display" : "none",
						"position": "absolute",
						"left" : 0
					});
					
					/*
					$parent.animate({
						"height" : $overlay.height()	
					}, 700);
					*/
					
					isAnimate = true;
					$display.fadeOut(600);
					$overlay.fadeIn(700, function(){
						$display.remove();
						$display = $overlay;
						$display.attr("id", "MainDisplay");
						isAnimate = false;
					});
						
					return false;
				});
			}
		});
		
	}
	
})(jQuery);


/*--------------------------------------------------
* MVK用カスタムAPI内蔵ロールオーバー
--------------------------------------------------*/
(function($){

	var Constants = {
		OVER	: "RO_OVER",
		OUT		: "RO_OUT",
		SELECTED: "RO_SELECTED"
	}
	
	var $elems;
	
	$.ExRollOver = function(i_elem, i_option) {	
		//INIT
		var self = this;
		
		this.elem = $target = $(i_elem);
		this.options = $.extend({ postfix:"-over" }, i_option);
		
		this.selected = false;
		this.up = null;
		this.select = null;
		this.img = null;
		
		$target.each(function(){
			var $a = $(this);
			var $i = $a.children('img');
			if(!$i.length && $a.attr("src")) $i = $a;
			if(!$i.length) return;
			
			var up = $i.attr("src");
			var over = up.replace(/\.([a-zA-Z0-9]+)$/,self.options.postfix+".$1");
			var select = up.replace(/\.([a-zA-Z0-9]+)$/,"-selected"+".$1");
			
			self.up = up;
			self.select = select;
			self.img = $i;
			
			$("<img />").attr("src",over);
			$("<img />").attr("src",select);
		
			$a.hover(
				function(){ 
					if(!self.selected) {
						$(this).trigger(Constants.OVER);
						$i.attr("src",over); 
					}
				}, function(){ 
					if(!self.selected) {
						$(this).trigger(Constants.OUT);
						$i.attr("src",up); 
					}
				}
			);
			
			$a.bind("click", function(){
				if(self.selected) return; 
				self.selected = true;
				$(this).trigger(Constants.SELECTED);
			});
		});
	}
	
	$.extend($.ExRollOver.prototype, {
		
		////API this equals $.ExRollOver instance////
		restartAll : function() {
			$elems.each(function(){
				var instance = $(this).data("RO");
				var $img = instance.img;
				
				$img.attr("src", instance.up);
				instance.selected = false;
			});
		},
		
		stop : function() {
			var self = this;
			this.selected = true;
			this.img.attr("src", self.select);
		}
	});
	
	$.fn.ExRollOver = function(i_option){
		$elems = this;
		return this.each(function(){
			$(this).data("RO", new $.ExRollOver(this, i_option));
		});
	}
	
})(jQuery);

/* =====================================================================
*
*	ENTRY POINT
*
* =================================================================== */

$(function(){
	
	//余裕があればinqにpathnameの実装する
/* 	var domain = String(location.href).match(/(^https?:\/\/.*?\/)/)[0]; */

	/* 宿泊予約フォームショートカット */
	var reservation = {
		side : $("#SideReservation").length,
		body : $("#jStayReservationSection").length
	}
	if(reservation.side != 0 || reservation.body != 0) MVK.reserve.init(reservation);
	
	/* ドロップダウンナビ */
	if($("#RestaurantTopTabNav").length != 0) MVK.dropDownNav.init("#RestaurantTopTabNav");
	
	/* フォントサイズ */
	MVK.fontSize.init("#FontSize");
	$(".imgSwap").exImgSwap();
	
	/* タブ用カスタムロールオーバー */
	var $exRollOvers = $(".exRollover");
	if($exRollOvers.length != 0) {
		
		$exRollOvers.ExRollOver();	
		$exRollOvers.each(function(){
			$(this).bind("RO_SELECTED", function(){	
				var inst = $(this).data("RO");
				inst["restartAll"]();
				inst["stop"]();
			});
			
		});
	}
	
	/* 宿泊・宴会 > RECOMMEND MODULE #267 */
	if( $("#jConditionSelect").length != 0 ) MVK.recommendList.init("#jConditionSelect select");
	if( $("#jBanquetSelect").length != 0 ) MVK.recommendList.init("#jBanquetSelect select");
	
	/* 資料請求 > REQUEST FORM MODULE #310 */
	if( $("#jRequestChecks").length != 0 ) MVK.requestForm.init("#jRequestChecks label input");

	/* お問い合わせタブへのハッシュアクセス */
	if($("#InqSection").length != 0) {
		
		var hash = location.hash;
		var $current;
		if(hash != "") {
			$current = $('#ContactTabNav a[href="' + hash + '"]');
			//SimpleLibのTabとのバッティングを避ける
			//余裕があればSimpleLib側を変更したほうがよい
			var f = $($('#ContactTabNav a')[0]);
			var tId = setInterval(function(){
				if(f.hasClass("selected")) {
					clearInterval(tId);
					$current.click();

				}
			}, 100);
		} 
		
	}
	
	/* 宴会料理メニュー #384 */
	if( $("#BanquetTabNav li").length != 0 ) MVK.banquetTab.init("#BanquetTabNav li");
	
	/* 宴会メニュータブへのハッシュアクセス */
	if($("#BanquetTabNav").length != 0) {
		
		var hash = location.hash;
		var $current;
		
		if(hash != "") {
			$current = $('#BanquetTabNav a[href="' + hash + '"]');
			$current.click(); 
		}
		
	}


	/* FAILITIES MODULE #474 */
	if( $("#FacilitiesAndFloorSction") ) MVK.floorView.init("#ExternalHonkan1");

});
