/**
 * 共通JS
 *
 * @author Tsue Shogo
 * @version
 *	1.0.0	2018/06/30(土) 20:49	新規作成
 *	1.0.1	2018/06/30(土) 22:18	jqueryのエラー回避で#にダブルクォーテーション追加
 *	1.1.0	2018/07/18(水) 14:47	日付関数追加
 *	2.0.0	2018/10/16(火) 11:44	リファクタリング
 *	2.1.0	2018/10/16(火) 13:21	スクロール中はSPフッタを非表示にする
 *	2.2.0	2018/10/16(火) 13:53	SP時のパンくずか被るのを阻止
 *	2.2.1	2018/10/23(火) 11:19	上へ戻るボタンもスクロール中は非表示にする
 *	2.2.2	2018/10/24(水) 09:03	上へ戻るボタンはPC時は強制表示
 *	2.3.0	2018/11/21(水) 11:50	画像トリミング追加
 *	3.0.0	2019/02/05(火) 23:09	メガメニュー対応
 */
(function(){
	/**
	 * コントローラ
	 *
	 * @var Object
	 */
	var Controller = {
		/**
		 * パラメータ
		 *
		 * @var Object
		 */
		params: {
			scrollTimer: null
		},
		/**
		 * イベント
		 *
		 * @var Object
		 */
		events: {
			'window': {
				'scroll resize': 'scrollResizeWindow',
				'scroll': 'scrollWindow',
				'resize': 'resizeWindow'
			},
			'a': {
				'click': 'clickA'
			},
			'.tab li': {
				'click': 'clickTabLi'
			},
			'.more-btn': {
				'click': 'clickMoreBtn'
			},
			'#pageTop, #totopbtn': {
				'click': 'clickPageTop'
			},
			'.offcanvas .dropdown a': {
				'click': 'clickOffcanvasDropdownA'
			},
			'.accordion .accordion-title': {
				'click touchstart': 'clickAccordionTitle'
			},
			'#chatbot_opener': {
				'click': 'clickChatbotOpener'
			},
			'#chatbot_opener_footer': {
				'click': 'clickChatbotOpener'
			},
			'#chatbot_opener_footer2': {
				'click': 'clickChatbotOpener'
			},
			'.chatbot_header .close_icon': {
				'click': 'clickChatbotCloser'
			},
			'.chatbot_bg': {
				'click': 'clickChatbotCloser'
			}
		},
		/**
		 * 初期実行
		 *
		 * @return void
		 */
		init: function(){
			var _this = this;
			// スクロールタイマー設置
			this.params.scrollTimer = new Timer();
			
			// メガメニュー準備
			this.readhMegaMenu();
			
			// matchHeigtht処理
			$('.js-matchHeigtht').matchHeight();
			
			// hiraku処理
			$(".offcanvas").hiraku({
				btn: "#offcanvas-btn-right",
				fixedHeader: "#sp-menu",
				direction: "right"
			});
			
			// ページ内リンクの処理
			this.moveInnerLink();
			
			// TOPへ戻るボタンの表示更新
			$('#pageTop, #totopbtn').hide(); // はじめ隠しておく
			this.updatePageTop();
			setInterval(function(){
				_this.updatePageTop();
			}, 100);
			
			// SPフッターの表示更新
			$('#footer-fixed').hide();	// はじめ隠しておく
			this.updateFotterFixed();
			setInterval(function(){
				_this.updateFotterFixed();
			}, 100);
			
			// グロナビの表示を更新する
			this.updateNaviPos();
			
			// SP用スリックの更新
			this.updateSlickSp();
			
			// パンくずの高さを更新する
			this.updateBreadCrumbsSpace();
			
			// imgのトリミングを行う
			this.trimmingImg();
			
			// .vetical .description の高さを揃える
			this.upateSameHeight();
			setInterval(function(){
				_this.upateSameHeight();
			}, 1000);
			
			// チャットボット設定値取得
			this.getChatbotConfigs();

			// stickyを更新する
			this.updateSticky();
		},
		/**
		 * [event] scrollResizeWindow
		 *
		 * @param object	event
		 * @param object	target
		 */
		scrollResizeWindow: function(event, target) {
			// TOPへ戻るボタンの表示を更新する
			this.updatePageTop();
			
			// SPフッターの表示を更新する
			this.updateFotterFixed();
			
			// グロナビの表示を更新する
			this.updateNaviPos();

			// stickyを更新する
			this.updateSticky();
		},
		/**
		 * [event] scrollWindow
		 *
		 * @param object	event
		 * @param object	target
		 */
		scrollWindow: function(event, target) {
			// スクロールタイマーリセット
			this.params.scrollTimer.set('scrollStart');
		},
		/**
		 * [event] resizeWindow
		 *
		 * @param object	event
		 * @param object	target
		 */
		resizeWindow: function(event, target) {
			// SP用スリックの更新
			this.updateSlickSp();
			
			// パンくずの高さを更新する
			this.updateBreadCrumbsSpace();
			
			// imgのトリミングを行う
			this.trimmingImg();
			
			// .vetical .description の高さを揃える
			this.upateSameHeight();
		},
		/**
		 * [event] clickA
		 *
		 * @param object	event
		 * @param object	target
		 */
		clickA: function(event, target) {
			return !this.moveInnerLink($(target).attr('href'), 400);
		},
		/**
		 * [event] clickTabLi
		 *
		 * @param object	event
		 * @param object	target
		 */
		clickTabLi: function(event, target) {
			//.index()を使いクリックされたタブが何番目かを調べ、
			//indexという変数に代入します。
			var index = $('.tab li').index(target);

			//コンテンツを一度すべて非表示にし、
			$('.content div').css('display','none');

			//クリックされたタブと同じ順番のコンテンツを表示します。
			$('.content div').eq(index).css('display','block');

			//一度タブについているクラスselectを消し、
			$('.tab li').removeClass('select');

			//クリックされたタブのみにクラスselectをつけます。
			$(target).addClass('select')
		},
		/**
		 * [event] clickMoreBtn
		 *
		 * @param object	event
		 * @param object	target
		 */
		clickMoreBtn: function(event, target) {
			$(target).next('.more').slideToggle();
			$(target).addClass('open');
		},
		/**
		 * [event] clickPageTop
		 *
		 * @param object	event
		 * @param object	target
		 */
		clickPageTop: function(event, target) {
			$('body,html').animate({
				scrollTop: 0
			}, 800);
			return false;
		},
		/**
		 * [event] clickOffcanvasDropdownA
		 *
		 * @param object	event
		 * @param object	target
		 */
		clickOffcanvasDropdownA: function(event, target) {
			$(target).next('ul').slideToggle();
			$(target).parent('li').toggleClass('is-open');
		},
		/**
		 * [event] clickAccordionTitle
		 *
		 * @param object	event
		 * @param object	target
		 */
		clickAccordionTitle: function(event, target) {
			$(target).next().slideToggle();
			$(target).parent('.accordion').toggleClass('is-open');
		},
		/**
		 * [event] clickChatbotOpener
		 *
		 * @param object	event
		 * @param object	target
		 */
		clickChatbotOpener: function(event, target) {
			// イベントキャンセル
			event.preventDefault();
			
			if (!$('#chatbot')[0]) {
				// iframe生成
				var html = '';
				html += '<div id="chatbot" class="hide">';
				html += 	'<div class="chatbot_header">';
				html += 		'<p class="title"><span class="icon"></span><strong>株式会社クラシアン</strong></p>';
				html += 		'<p class="scrollHide">こちらは、水まわりに関するお問い合わせ用の<br>メールフォームです。お気軽にご利用ください。</p>';
				html += 		'<span class="close_icon"><i class="fa fa-times"></i></span>';
				html += 	'</div>';
				html += 	'<iframe src="' + $(target).data('chatboturl') + '" id="iframe_chatbot"></iframe>';
				html += '</div>';
				html += '<div class="chatbot_bg PCnone hide"></div>';
				var $chatbot = $(html);
				$('body').append($chatbot);
				
				// iframeイベント登録
				$('#iframe_chatbot').on('load', function(){
					var iframeDoc = $('#iframe_chatbot')[0].contentWindow.document;
					$('#for_chat', iframeDoc).on('scroll', function(){
						if ($(this).scrollTop() > 0) {
							$('.chatbot_header .scrollHide').slideUp();
						} else {
							$('.chatbot_header .scrollHide').slideDown();
						}
					});
				});
			}
			
			// アニメーション
			$('#chatbot_opener').fadeOut();
			setTimeout(function(){
				$('#chatbot').removeClass('hide');
				$('.chatbot_bg').removeClass('hide');
				$('html').addClass('fixed');
			}, 600);
		},
		/**
		 * [event] clickChatbotCloser
		 *
		 * @param object	event
		 * @param object	target
		 */
		clickChatbotCloser: function(event, target) {
			// イベントキャンセル
			event.preventDefault();
			
			// アニメーション
			$('#chatbot').addClass('hide');
			$('.chatbot_bg').addClass('hide');
			$('html').removeClass('fixed');
			setTimeout(function(){
				$('#chatbot_opener').fadeIn();
				
				// 終了時はiframe削除
				if (sessionStorage.getItem('chatbot') === null) {
					$('#chatbot').remove();
					$('.chatbot_bg').remove();
				}
			}, 600);
		},
		///////////////////////////////////////////////////////////
		/**
		 * メガメニューを準備する
		 *
		 * @return void
		 */
		readhMegaMenu: function() {
			// 黒背景挿入
			var $megamenuBg = $('<div class="megamenu_bg"></div>');
			$('#wrapper > .main').prepend($megamenuBg);
			
			// イベント登録
			var $navLi = $('#nav .navInner > ul > li');
			$navLi.hover(function(){
				// hoverクラス
				$(this).addClass('hover');
				
				// メガメニューアニメーション
				if ($('.megamenu', this)[0]) {
					$('.megamenu', this).stop(true, true).fadeIn(200);
					$megamenuBg.stop(true, true).fadeIn(200);
				}
			}, function(){
				// hoverクラス
				$(this).removeClass('hover');
				
				// メガメニューアニメーション
				if ($('.megamenu', this)[0]) {
					$('.megamenu', this).stop(true, true).fadeOut(200);
					$megamenuBg.stop(true, true).fadeOut(200);
				}
			});
			/*
			var $li = $('#nav .navInner > ul > li:eq(5)');
			$('.megamenu', $li).stop(true, true).fadeIn();
			$megamenuBg.stop(true, true).fadeIn();
			*/
		},
		/**
		 * TOPへ戻るボタンの表示を更新する
		 *
		 * @return void
		 */
		updatePageTop: function() {
			if (window.matchMedia('screen and (max-width:767px)').matches) {
				// SPメニュー表示中は強制的に非表示
				if ($('#js-hiraku-offcanvas-0').is(':visible')) {
					$('#pageTop, #totopbtn').hide();
					return;
				}
				// スクロールに合わせて表示切替
				var scrollStart = this.params.scrollTimer.get('scrollStart');
				var scrollTimerFlag = scrollStart < 600;
				if (($(window).scrollTop() <= 100) || scrollTimerFlag) {
					$('#pageTop, #totopbtn').fadeOut();
				} else {
					$('#pageTop, #totopbtn').fadeIn();
				}
			} else {
				$('#pageTop, #totopbtn').show();
			}
		},
		/**
		 * SPフッターの表示を更新する
		 *
		 * @return void
		 */
		updateFotterFixed: function() {
			var $footerFixedSp = $('#footer-fixed');
				var footerHeight = $footerFixedSp.outerHeight();
				var fixedClass = 'is-fixed';
				if (($(window).scrollTop() <= footerHeight)) {
					$footerFixedSp.fadeOut().removeClass(fixedClass);
				} else {
					$footerFixedSp.fadeIn().addClass(fixedClass);
				}
		},
		/**
		 * SP用スリックの更新
		 *
		 * @return void
		 */
		updateSlickSp: function() {
			if ($('.slickSp')[0]) {
				var isSp = window.matchMedia('(max-width: 767px)');
				var isPc = window.matchMedia('(min-width: 768px)');
				if(isSp.matches) {
					$('.slickSp').not('.slick-initialized').slick({
						arrows: true,
						infinite: true
					});
				} else {
					$('.slickSp.slick-initialized').slick('unslick');
				}
				$('.slickSp').each(function(){
					var $image = $(window).find('.image');
					if ($image[0]) {
						var imgH = $image.height();
						var imgW = $image.width();
						var scrW = $(window).width();
						var arrowH = $(window).find('.slick-arrow').height();
						var dtH = $image[0].tagName.match(/dd/i) ? $('dt', $image.parent()).outerHeight() : 0;
						var pos = (scrW / imgW * imgH - arrowH) / 2 + dtH;
						$(window).find('.slick-arrow').css('top', pos);
					}
				});
			}
		},
		/**
		 * グロナビの表示を更新する
		 *
		 * @return void
		 */
		updateNaviPos: function() {
			var $morisue = $('#morisue');
			var $nav = $('#nav');
			var morisueHeight = 34;
			var navTopDefault = 119;
			var $loggedIn = $('.logged-in');
			if (true) {
				// プランA
				var winTop = $(window).scrollTop();
				$morisue.hide();
				if (winTop > navTopDefault) {
					var navTop = $loggedIn[0] ? 32 : 0;
					$nav.css({top: navTop, position: 'fixed'});
				} else {
					var navTop = navTopDefault;
					$nav.css({top: navTopDefault, position: 'absolute'});
				}
			} else {
				// プランB
				var winTop = $(window).scrollTop();
				var k = 0.5;
				var morisueTop = (winTop > navTopDefault - morisueHeight) ? 0 : k * (winTop - navTopDefault + morisueHeight);
				var navTop = (winTop > navTopDefault - morisueHeight) ? winTop + morisueHeight : navTopDefault;
				$morisue.css({top: morisueTop});
				$nav.css({top: navTop});
			}
		},
		/**
		 * ページ内リンクの処理
		 *
		 * @param int	href
		 * @param int	duration
		 * @return bool
		 */
		moveInnerLink: function (href, duration) {
			// パラメータデフォルト
			if (typeof(href) === 'undefined') {
				href = location.href;
			}
			if (typeof(duration) === 'undefined') {
				duration = 0;
			}
			// ページ内リンク検索
			var match;
			if (match = href.match(/(#[^\?]+)/)) {
				var $target = $(match[1]);
				if ($target[0]) {
					// 移動
					var top = $target.offset().top - 60;
					$('body,html').animate({scrollTop: top}, duration, 'swing');
					return true;
				}
			}
			return false;
		},
		/**
		 * パンくずの高さを更新する
		 *
		 * @return void
		 */
		updateBreadCrumbsSpace: function() {
			if (window.matchMedia('screen and (max-width:767px)').matches) {
				// 応募はパンくず非表示
				if (!(
					$('body.isbody-elected')[0]
				)) {
					var breadcrumbsHeight = $('#breadcrumbs').outerHeight() + 15;
					$('#wrapper > .main').css({'padding-bottom': breadcrumbsHeight + 'px'});
				}
			} else {
				$('#wrapper > .main').removeAttr('style');
			}
		},
		/**
		 * imgのトリミングを行う
		 *
		 * @return void
		 */
		trimmingImg: function() {
			var _this = this;
			var isSp = window.matchMedia('screen and (max-width:767px)').matches;
			var retryFlag = false;
			$('.imgtrimwrap').each(function(){
				var cls = $(this).attr('class');
				var pcMatch = cls.match(/ratio-(\d+)-(\d+)/);
				var spMatch = cls.match(/spratio-(\d+)-(\d+)/);
				var pcIgnore = cls.match(/pc-ignore/) ? true : false;
				var spIgnore = cls.match(/sp-ignore/) ? true : false;
				var fullWidth = cls.match(/full-width/) ? true : false;
				if (pcMatch || spMatch) {
					var $img = $('img', $(this));
					if ($img[0]) {
						// 情報リセット
						$(this).removeAttr('style');
						$img.removeAttr('style');
						var w;
						var h;
						if (isSp) {
							if (spMatch) {
								w = spMatch[1] * 1;
								h = spMatch[2] * 1;
							} else {
								w = pcMatch[1] * 1;
								h = pcMatch[2] * 1;
							}
							if (spIgnore) {
								return true;
							}
						} else {
							w = pcMatch[1] * 1;
							h = pcMatch[2] * 1;
							if (pcIgnore) {
								return true;
							}
						}
						
						// 情報取得
						if (fullWidth) {
							$(this).css('width', '100%');
						}
						var imgW = $img.width() * 1;
						var imgH= $img.height() * 1;
						if (imgW && imgH) {
							var ratioW = w;
							var ratioH = h;
							var wrapW = $(this).width() * 1;
							var wrapH = ratioH * wrapW / ratioW;
							var imgMarginLeft = 0;
							var imgMarginTop = 0;
							// 調整
							imgH = imgH * wrapW / imgW;
							imgW = wrapW; // この時点で左右が空くことは無い
							if (imgH > wrapH) { // この時点で上下が空くことも無い
								imgMarginTop = (wrapH - imgH) / 2;
							} else { // この条件だと上下が空く
								var scale = wrapH / imgH; // > 1
								imgH = wrapH; // = wrapH
								imgW = imgW * scale; // > wrapW
								imgMarginLeft = (wrapW - imgW) / 2;
							}
							// セット
							$(this).width(wrapW);
							$(this).height(wrapH);
							$img.width(imgW);
							$img.height(imgH);
							$img.css({'margin-left': imgMarginLeft, 'margin-top': imgMarginTop, 'max-width': 'none',  'max-height': 'none'});
						} else {
							// 画像読み込んでないかもなのでもっかい実行
							retryFlag = true;
						}
					}
				}
			});
		},
		/**
		 * 高さを揃える
		 *
		 * class="sameheight grp-XXXX pc-XXX sp-XXX"
		 *
		 * @return void
		 */
		upateSameHeight: function() {
			// グループを検索する
			var groups = {};
			$('.sameheight').each(function(){
				var classStr = $(this).attr('class');
				var matchGrp = classStr.match(/grp-(\S+)/);
				var matchPc = classStr.match(/pc-(\S+)/);
				var matchSp = classStr.match(/sp-(\S+)/);
				if (matchGrp && matchPc && matchSp && typeof(groups[matchGrp[1]]) === 'undefined') {
					groups[matchGrp[1]] = {
						'pc': matchPc[1],
						'sp': matchSp[1]
					};
				}
			});
			
			// メディア分岐
			var media = window.matchMedia('screen and (max-width:767px)').matches ? 'sp' : 'pc';
			
			$.each(groups, function(grp, info){
				// リセット
				var target = '.sameheight.grp-' + grp;
				$(target).removeAttr('style');
				// col確認
				var col = info[media];
				if (col === 'none') {
					return true;
				}
				col = col * 1;
				if (!(col > 0)) {
					return true;
				}
				// 高さ取得
				var heights = [];
				$(target).each(function(){
					var height = $(this).height();
					heights.push(height);
				});
				// 更新値計算
				var sameHeights = [];
				var max = null;
				$.each(heights, function(index, height){
					// 最大値更新
					if (max === null || max < height) {
						max = height;
					}
					// 配列更新
					var m = index % col;
					var p = index - m;
					for (var i = p; i <= index; i++) {
						sameHeights[i] = max;
					}
					// maxリセット
					if (m === col - 1) {
						max = null;
					}
				});
				// 高さ更新
				$.each(sameHeights, function(index, height){
					$(target).eq(index).height(height);
				});
			});
		},
		/**
		 * チャットボット設定値取得
		 *
		 * @return Promise
		 */
		getChatbotConfigs: function() {
			var _this = this;
			var deferred = new $.Deferred();
			$.ajax({
				url: '/form-control/chatbot/get_configs/style.json',
				type: 'get',
				dataType: 'json',
				success: function(data) {
					// styleタグを作ってhead内に入れる
					var html = '';
					html += '<style type="text/css" id="style_chatbot">';
					html += '#chatbot {height: ' + data.sizeChatbotPcHeight + ';}';
					html += '@media screen and (max-width: 767px) {';
					html += '#chatbot.hide {bottom: calc(-' + data.sizeChatbotPcHeight + ' - 2px);}';
					html += '}';
					html += '</style>';
					$('#style_chatbot').remove();
					$('head').append(html);
					deferred.resolve();
				},
				error: function(e) {
					deferred.fail();
				}
			});
			return deferred.promise();
		},
		/**
		 * stickyを更新する
		 *
		 * @return void
		 */
		updateSticky: function() {
			var isSp = window.matchMedia('(max-width: 767px)').matches;
			if (isSp) {
				// SP
				$('#side').removeClass('activate activate_b');
			} else {
				// PC
				var wst = $(window).scrollTop();
				var headerH = $('#header').outerHeight(true);
				var sideH = $('#side').outerHeight(true);
				var mainH = $('#main').outerHeight(true);

					if (wst < headerH) {
						$('#side').removeClass('fixed');
						$('#side').removeClass('bottom');
						$('#side').addClass('top');
					} else if (wst + headerH < mainH - 500) {
						$('#side').removeClass('top');
						$('#side').removeClass('bottom');
						$('#side').addClass('fixed');
					} else {
						$('#side').removeClass('top');
						$('#side').removeClass('fixed');
						$('#side').addClass('bottom');
					}
			}
		}
	};
	/**
	 * タイマー
	 *
	 * @return Object
	 */
	var Timer = function() {
		return {
			/**
			 * 現在の時刻ミリ秒
			 *
			 * @return int
			 */
			now: function() {
				if (false && typeof performance !== "undefined" && typeof performance.now !== "undefined") {
					return performance.now();
				} else {
					var d = new Date();
					return d.getTime();
				}
			},
			/**
			 * セッター
			 *
			 * @param string tag
			 * @return int
			 */
			set: function(tag) {
				return (this._memory[tag] = this.now());
			},
			/**
			 * ゲッター
			 *
			 * @param string fromTag
			 * @param string toTag
			 * @return int
			 */
			get: function(fromTag, toTag) {
				var to = typeof toTag === "undefined" || typeof this._memory[toTag] === "undefined" ? this.now() : this._memory[toTag];
				var from = typeof fromTag === "undefined" || typeof this._memory[fromTag] === "undefined" ? this.now() : this._memory[fromTag];
				return to - from;
			},
			/**
			 * メモリ
			 *
			 * @var Object
			 */
			_memory: {},
			/**
			 * アニメーションフレーム
			 *
			 * @param function func
			 * @return void
			 */
			frame: function(func) {
				if (typeof window.requestAnimationFrame !== "undefined") {
					window.requestAnimationFrame(func);
				} else {
					window.setTimeout(func, this.delay);
				}
			},
			/**
			 * setTimeout遅延
			 *
			 * @var number
			 */
			delay: 1000 / 60
		};
	};
	/**
	 * UserAgentによるブラウザ・OSの判別
	 *
	 */
	var UserAgent = (function() {
		var ua = navigator.userAgent.toLowerCase();
		var ver = navigator.appVersion.toLowerCase();

		// [1] ブラウザ
		var isMSIE = ua.indexOf("msie") > -1 && ua.indexOf("opera") == -1; // ※IE11以外
		var isIE6 = isMSIE && ver.indexOf("msie 6.") > -1;
		var isIE7 = isMSIE && ver.indexOf("msie 7.") > -1;
		var isIE8 = isMSIE && ver.indexOf("msie 8.") > -1;
		var isIE9 = isMSIE && ver.indexOf("msie 9.") > -1;
		var isIE10 = isMSIE && ver.indexOf("msie 10.") > -1;
		var isIE11 = ua.indexOf("trident/7") > -1;
		var isIE = isMSIE || isIE11;
		var isEdge = ua.indexOf("edge") > -1;
		var isChrome = ua.indexOf("chrome") > -1 && ua.indexOf("edge") == -1;
		var isFirefox = ua.indexOf("firefox") > -1;
		var isSafari = ua.indexOf("safari") > -1 && ua.indexOf("chrome") == -1;
		var isOpera = ua.indexOf("opera") > -1;

		// [2] スマホ
		var isiPhone = ua.indexOf("iphone") > -1;
		var isiPad = ua.indexOf("ipad") > -1;
		var isAndroid = ua.indexOf("android") > -1 && ua.indexOf("mobile") > -1;
		var isAndroidTablet = ua.indexOf("android") > -1 && ua.indexOf("mobile") == -1;

		return {
			isMSIE: isMSIE,
			isIE6: isIE6,
			isIE7: isIE7,
			isIE8: isIE8,
			isIE9: isIE9,
			isIE10: isIE10,
			isIE11: isIE11,
			isIE: isIE,
			isEdge: isEdge,
			isChrome: isChrome,
			isFirefox: isFirefox,
			isSafari: isSafari,
			isOpera: isOpera,
			isiPhone: isiPhone,
			isiPad: isiPad,
			isAndroid: isAndroid,
			isAndroidTablet: isAndroidTablet
		};
	})();
	/**
	 * チェッカー
	 *
	 * @var object
	 */
	var Checker = {
		/**
		 * 必須チェック
		 *
		 * @param mixed		val
		 * @param object	rule
		 * @return bool
		 */
		notEmpty: function(val, rule) {
			if (val === null || typeof val === "undefined") {
				val = "";
			}
			return val !== "";
		},
		/**
		 * 長さチェック
		 *
		 * @param mixed		val
		 * @param object	rule
		 * @return bool
		 */
		length: function(val, rule) {
			var ret = true;
			if (val === "") {
				return ret;
			}
			var len = val.length;
			if (typeof rule.min !== "undefined") {
				// 最小長さチェック
				if (len < rule.min) {
					ret = false;
				}
			}
			if (typeof rule.max !== "undefined") {
				// 最大長さチェック
				if (len > rule.max) {
					ret = false;
				}
			}
			return ret;
		},
		/**
		 * 数値チェック
		 *
		 * @param mixed		val
		 * @param object	rule
		 * @return bool
		 */
		between: function(val, rule) {
			var ret = true;
			if (val === "") {
				return ret;
			}
			val = val * 1;
			if (typeof rule.min !== "undefined") {
				// 最小長さチェック
				if (val < rule.min) {
					ret = false;
				}
			}
			if (typeof rule.max !== "undefined") {
				// 最大長さチェック
				if (val > rule.max) {
					ret = false;
				}
			}
			return ret;
		},
		/**
		 * 全角ひらがなチェック
		 *
		 * @param mixed		val
		 * @param object	rule
		 * @return bool
		 */
		zenHiragana: function(val, rule) {
			if (typeof rule !== "undefined" && typeof rule.allowSpace !== "undefined" && rule.allowSpace) {
				return val.match(/^([ぁ-ん]|ー|\s)*$/) ? true : false;
			} else {
				return val.match(/^([ぁ-ん]|ー)*$/) ? true : false;
			}
		},
		/**
		 * 全角カタカナチェック
		 *
		 * @param mixed		val
		 * @param object	rule
		 * @return bool
		 */
		zenKatakana: function(val, rule) {
			if (typeof rule !== "undefined" && typeof rule.allowSpace !== "undefined" && rule.allowSpace) {
				return val.match(/^([ァ-ン]|ー|－|\s)*$/) ? true : false;
			} else {
				return val.match(/^([ァ-ン]|ー|－)*$/) ? true : false;
			}
		},
		/**
		 * 全角チェック
		 *
		 * @param mixed		val
		 * @param object	rule
		 * @return bool
		 */
		zenkaku: function(val, rule) {
			var ret = val.match(/^([０-９ぁ-んァ-ン－一-龥ー。、？＋　\n])*$/) ? true : false;
			return ret;
		},
		/**
		 * 半角チェック
		 *
		 * @param mixed		val
		 * @param object	rule
		 * @return bool
		 */
		hankaku: function(val, rule) {
			var ret = val.match(/^([0-9a-zA-Zｧ-ﾝﾞﾟ\-.\x20\n])*$/) ? true : false;
			return ret;
		},
		/**
		 * 半角英数チェック
		 *
		 * @param mixed		val
		 * @param object	rule
		 * @return bool
		 */
		hanEisu: function(val, rule) {
			var ret = val.match(/^([0-9a-zA-Z])*$/) ? true : false;
			return ret;
		},
		/**
		 * 半角数チェック
		 *
		 * @param mixed		val
		 * @param object	rule
		 * @return bool
		 */
		hanSu: function(val, rule) {
			var ret = val.match(/^([0-9])*$/) ? true : false;
			return ret;
		},
		/**
		 * メールアドレスチェック
		 *
		 * @param mixed		val
		 * @param object	rule
		 * @return bool
		 */
		email: function(val, rule) {
			if (val === "") {
				return true;
			}
			var ret = val.match(/^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/) ? true : false;
			return ret;
		},
		/**
		 * 電話番号チェック
		 *
		 * @param mixed		val
		 * @param object	rule
		 * @return bool
		 */
		tel: function(val, rule) {
			if (val === "") {
				return true;
			}

			if (val.match(/^0\d{1,3}-?\d{1,4}-?\d{1,4}$/)) {
				// 固定
				return true;
			} else if (val.match(/^\(0\d{1,3}\)\d{1,4}-?\d{1,4}$/)) {
				// 固定
				return true;
			} else if (val.match(/^(070|080|090)-?\d{1,4}-?\d{1,4}$/)) {
				// 携帯
				return true;
			} else if (val.match(/^050-?\d{1,4}-?\d{1,4}$/)) {
				// IP
				return true;
			} else if (val.match(/^0120-?\d{1,3}-?\d{1,3}$/)) {
				// フリーダイアル
				return true;
			}

			return false;
		},
		/**
		 * URLチェック
		 *
		 * @param mixed		val
		 * @param object	rule
		 * @return bool
		 */
		url: function(val, rule) {
			if (val === "") {
				return true;
			}
			var ret = val.match(/(https?:\/\/[\w\-\.\/\?\,\#\:\u3000-\u30FE\u4E00-\u9FA0\uFF01-\uFFE3]+)/) ? true : false;
			return ret;
		},
		/**
		 * 日付チェック
		 *
		 * @param mixed		val
		 * @param object	rule
		 * @return bool
		 */
		date: function(val, rule) {
			if (val === "") {
				return true;
			}

			var match;
			if ((match = val.match(/^(?:西暦)?(\d{4})[-/年]?(\d{1,2})[-/月]?(\d{1,2})[日]?$/))) {
				var numbers = Calibrator.date(val, { format: "Y-n-j" }).split("-");
				if (numbers.length !== 3) {
					return false;
				}
				var ret = true;
				for (var i = 0; i < 3; i++) {
					ret = ret && match[i + 1] * 1 === numbers[i] * 1;
				}
				return ret;
			} else if ((match = val.match(/^((?:明治|大正|昭和|平成|令和)(?:元|[0-9]+))年([0-9]+)月([0-9]+)日$/))) {
				var numbers = Calibrator.date(val, { format: "和-n-j" }).split("-");
				if (numbers.length !== 3) {
					return false;
				}
				var ret = true;
				for (var i = 0; i < 3; i++) {
					var v = match[i + 1].split("元").join("1");
					var w = numbers[i].split("元").join("1");
					if (i === 0) {
						ret = ret && v === w;
					} else {
						ret = ret && v * 1 === w * 1;
					}
				}
				return ret;
			}
			return false;
		},
		/**
		 * 年齢チェック
		 *
		 * @param mixed		val
		 * @param object	rule
		 * @return bool
		 */
		age: function(val, rule) {
			if (val === "") {
				return true;
			}
			rule = $.extend(true, { min: 0, max: 120 }, rule);
			var thisYmd = val.match(rule.format);
			if (!thisYmd) {
				return false;
			}
			var age = Calibrator.date(val, { format: "齢" });
			var ret = age >= rule.min && age <= rule.max;
			return ret;
		},
		/**
		 * 配列存在チェック
		 *
		 * @param mixed		val
		 * @param object	rule
		 * @return bool
		 */
		inList: function(val, rule) {
			if (typeof rule.list === "undefined" || typeof Map[rule.list] === "undefined" || typeof Map[rule.list][val] === "undefind") {
				return false;
			}
			return true;
		}
	};
	/**
	 * 校正
	 *
	 * @var Object
	 */
	var Calibrator = {
		/**
		 * 半角に変換する
		 *
		 * @param string	str
		 * @param object	option
		 * @return string
		 */
		toHankaku: function(str, option) {
			str = str.replace(/[Ａ-Ｚａ-ｚ０-９]/g, function(s) {
				return String.fromCharCode(s.charCodeAt(0) - 0xfee0);
			});
			str = this.toKatakana(str);
			Object.keys(Map.kana).forEach(function(zenkana) {
				var hankana = Map.kana[zenkana];
				str = str.split(zenkana).join(hankana);
			});
			return str;
		},
		/**
		 * 半角数字に変換する
		 *
		 * @param string	str
		 * @param object	option
		 * @return string
		 */
		toHansu: function(str, option) {
			str = this.toHankaku(str, option);
			str = str.replace(/[^0-9]/g, function(s) {
				return "";
			});
			return str;
		},
		/**
		 * 全角に変換する
		 *
		 * @param string	str
		 * @param object	option
		 * @return string
		 */
		toZenkaku: function(str, option) {
			str = str.replace(/[A-Za-z0-9]/g, function(s) {
				return String.fromCharCode(s.charCodeAt(0) + 0xfee0);
			});
			Object.keys(Map.kana).forEach(function(zenkana) {
				var hankana = Map.kana[zenkana];
				str = str.split(hankana).join(zenkana);
			});
			return str;
		},
		/**
		 * ひらがなに変換する
		 *
		 * @param string	str
		 * @param object	option
		 * @return string
		 */
		toHiragana: function(str, option) {
			Object.keys(Map.kana).forEach(function(zenkana) {
				var hankana = Map.kana[zenkana];
				str = str.split(hankana).join(zenkana);
			});
			str = str.replace(/[\u30a1-\u30f6]/g, function(match) {
				var chr = match.charCodeAt(0) - 0x60;
				return String.fromCharCode(chr);
			});
			return str;
		},
		/**
		 * カタカナに変換する
		 *
		 * @param string	str
		 * @param object	option
		 * @return string
		 */
		toKatakana: function(str, option) {
			Object.keys(Map.kana).forEach(function(zenkana) {
				var hankana = Map.kana[zenkana];
				str = str.split(hankana).join(zenkana);
			});
			str = str.replace(/[\u3041-\u3096]/g, function(match) {
				var chr = match.charCodeAt(0) + 0x60;
				return String.fromCharCode(chr);
			});
			return str;
		},
		/**
		 * 補助単位を付ける
		 *
		 * @param int	num
		 * @param string	unit
		 * @return string
		 */
		addSubUnit: function(num, unit) {
			var subUnits = ["", "K", "M", "G", "T"];
			subUnits.forEach(function(subUnit, index) {
				if (num < 1000 || index === subUnits.length - 1) {
					return Math.round(num * 100) / 100 + subUnit + unit;
				}
				num = num / 1000;
			});
		},
		/**
		 * 数字を3桁区切りでカンマを付ける
		 *
		 * @param string	str
		 * @param object	option
		 * @return string
		 */
		numberFormat: function(str, option) {
			return str.toString().replace(/(\d+?)(?=(?:\d{3})+$)/g, function(x) {
				return x + ",";
			});
		},
		/**
		 * 左右のスペースを削除する
		 *
		 * @param string	str
		 * @param object	option
		 * @return string
		 */
		trim: function(str, option) {
			return str.trim();
		},
		/**
		 * 日付
		 *
		 * @param string	str
		 * @param object	option
		 * @return string
		 */
		date: function(str, option) {
			// 全角 → 半角
			str = Calibrator.toHankaku(str);
			// 和暦変換
			str = str.split("元").join("1");
			str = str.split("明治").join("M");
			str = str.split("大正").join("T");
			str = str.split("昭和").join("S");
			str = str.split("平成").join("H");
			str = str.split("令和").join("R");
			str = str.replace(/M([0-9]+)/g, function(s, y) {
				return String(y * 1 + 1867);
			});
			str = str.replace(/T([0-9]+)/g, function(s, y) {
				return String(y * 1 + 1911);
			});
			str = str.replace(/S([0-9]+)/g, function(s, y) {
				return String(y * 1 + 1925);
			});
			str = str.replace(/H([0-9]+)/g, function(s, y) {
				return String(y * 1 + 1988);
			});
			str = str.replace(/R([0-9]+)/g, function(s, y) {
				return String(y * 1 + 2018);
			});
			// 半角数字以外 → 半角ハイフン
			str = str.replace(/[^0-9]/g, function(s) {
				return "-";
			});
			// 2重ハイフン → ハイフン
			while (str.match("--")) {
				str = str.split("--").join("-");
			}
			// 最初と最後のハイフン除去
			str = str.replace(/^-?(.*?)-?$/, function(s, a) {
				return a;
			});
			// yyyy-mm-dd に変換
			var numbers = str.split("-");
			if (numbers.length === 1 && str.length === 8) {
				numbers = [str.substr(0, 4), str.substr(4, 2), str.substr(6, 2)];
			}
			if (numbers.length === 1 && str.length === 6) {
				numbers = [str.substr(0, 2), str.substr(2, 2), str.substr(4, 2)];
			}
			var newNumbers = [];
			for (var i = 0; i < 3; i++) {
				var number = typeof numbers[i] !== "undefined" ? numbers[i] : 1;
				newNumbers[i] = number * 1;
			}

			// フォーマット
			if (typeof option === "undefined" || typeof option.format === "undefined") {
				option = {
					format: "Y-m-d"
				};
			}
			var obj = new Date(newNumbers[0], newNumbers[1] - 1, newNumbers[2]);
			newNumbers = [obj.getFullYear(), obj.getMonth() + 1, obj.getDate()];
			var replaces = {
				// 西暦4桁
				Y: ("0000" + newNumbers[0]).slice(-4),
				// 西暦2桁
				y: ("00" + newNumbers[0]).slice(-2),
				// 月2桁
				m: ("00" + newNumbers[1]).slice(-2),
				// 日2桁
				d: ("00" + newNumbers[2]).slice(-2),
				// 月
				n: String(newNumbers[1] * 1),
				// 日
				j: String(newNumbers[2] * 1),
				// 和暦
				和: (function() {
					var ymd = newNumbers[0] * 10000 + newNumbers[1] * 100 + newNumbers[2] * 1;
					if (ymd < 18680125) {
						// 明治以降なので西暦を返す
						return newNumbers[0];
					} else if (ymd < 19120730) {
						var y = newNumbers[0] - 1867;
						return "明治" + (y === 1 ? "元" : y);
					} else if (ymd < 19261225) {
						var y = newNumbers[0] - 1911;
						return "大正" + (y === 1 ? "元" : y);
					} else if (ymd < 19890108) {
						var y = newNumbers[0] - 1925;
						return "昭和" + (y === 1 ? "元" : y);
					} else if (ymd < 20190501) {
						var y = newNumbers[0] - 1988;
						return "平成" + (y === 1 ? "元" : y);
					} else {
						var y = newNumbers[0] - 2018;
						return "令和" + (y === 1 ? "元" : y);
					}
				})(),
				// 曜日(数値)
				w: (function() {
					return obj.getDay();
				})(),
				曜: (function() {
					var w = obj.getDay();
					return ["日", "月", "火", "水", "木", "金", "土"][w];
				})(),
				// 年齢(大文字のオー)
				齢: (function() {
					var now = new Date();
					var nowY = now.getFullYear();
					var nowMd = (now.getMonth() + 1) * 100 + now.getDate();
					var y = newNumbers[0] * 1;
					var md = newNumbers[1] * 100 + newNumbers[2] * 1;
					var old = nowY - y + (nowMd >= md ? 0 : -1);
					return old;
				})(),
				// 星座
				星: (function() {
					var md = newNumbers[1] * 100 + newNumbers[2] * 1;
					if (md < 120 || 1222 <= md) {
						return "山羊";
					} else if (md < 219) {
						return "水瓶";
					} else if (md < 321) {
						return "魚";
					} else if (md < 420) {
						return "牡羊";
					} else if (md < 521) {
						return "牡牛";
					} else if (md < 622) {
						return "双子";
					} else if (md < 723) {
						return "蟹";
					} else if (md < 823) {
						return "獅子";
					} else if (md < 923) {
						return "乙女";
					} else if (md < 1024) {
						return "天秤";
					} else if (md < 1123) {
						return "蠍";
					} else {
						return "射手";
					}
				})()
			};
			str = option.format;
			$.each(replaces, function(key, val) {
				str = str.split(key).join(val);
			});

			return str;
		},
		/**
		 * サニタイズ
		 *
		 * @param string	str
		 * @param object	option
		 * @return string
		 */
		sanitize: function(str, option) {
			if (typeof option === "undefined") {
				option = {
					encode: 1,
					decode: 0
				};
			}
			if (typeof option.encode === "undefined") {
				option.encode = 1;
			}
			if (typeof option.decode === "undefined") {
				option.decode = 0;
			}
			var replaces = {
				"&": "&amp;",
				"<": "&lt;",
				">": "&gt;",
				'"': "&quot;",
				"'": "&#39;"
			};
			if (option.decode) {
				Object.keys(replaces).forEach(function(key) {
					var need = replaces[key];
					var replace = key;
					str = str.split(need).join(replace);
				});
			} else {
				Object.keys(replaces).forEach(function(key) {
					var need = key;
					var replace = replaces[key];
					str = str.split(need).join(replace);
				});
			}
			return str;
		}
	};
	/**
	 * 簡易マップ
	 *
	 * @var Object
	 */
	var Map = {
		// 半角カナ
		"kana": {
			"ア": "ｱ",  "イ": "ｲ",  "ウ": "ｳ",  "エ": "ｴ",  "オ": "ｵ",
			"カ": "ｶ",  "キ": "ｷ",  "ク": "ｸ",  "ケ": "ｹ",  "コ": "ｺ",
			"サ": "ｻ",  "シ": "ｼ",  "ス": "ｽ",  "セ": "ｾ",  "ソ": "ｿ",
			"タ": "ﾀ",  "チ": "ﾁ",  "ツ": "ﾂ",  "テ": "ﾃ",  "ト": "ﾄ",
			"ナ": "ﾅ",  "ニ": "ﾆ",  "ヌ": "ﾇ",  "ネ": "ﾈ",  "ノ": "ﾉ",
			"ハ": "ﾊ",  "ヒ": "ﾋ",  "フ": "ﾌ",  "ヘ": "ﾍ",  "ホ": "ﾎ",
			"マ": "ﾏ",  "ミ": "ﾐ",  "ム": "ﾑ",  "メ": "ﾒ",  "モ": "ﾓ",
			"ヤ": "ﾔ",  "ユ": "ﾕ",  "ヨ": "ﾖ",
			"ラ": "ﾗ",  "リ": "ﾘ",  "ル": "ﾙ",  "レ": "ﾚ",  "ロ": "ﾛ",
			"ワ": "ﾜ",  "ヲ": "ｦ",  "ン": "ﾝ",  "ー": "ｰ",
			"ヴ": "ｳﾞ",
			"ガ": "ｶﾞ", "ギ": "ｷﾞ", "グ": "ｸﾞ", "ゲ": "ｹﾞ", "ゴ": "ｺﾞ",
			"ザ": "ｻﾞ", "ジ": "ｼﾞ", "ズ": "ｽﾞ", "ゼ": "ｾﾞ", "ゾ": "ｿﾞ",
			"ダ": "ﾀﾞ", "ヂ": "ﾁﾞ", "ヅ": "ﾂﾞ", "デ": "ﾃﾞ", "ド": "ﾄﾞ",
			"バ": "ﾊﾞ", "ビ": "ﾋﾞ", "ブ": "ﾌﾞ", "ベ": "ﾍﾞ", "ボ": "ﾎﾞ",
			"パ": "ﾊﾟ", "ピ": "ﾋﾟ", "プ": "ﾌﾟ", "ペ": "ﾍﾟ", "ポ": "ﾎﾟ",
			"ァ": "ｧ",  "ィ": "ｨ",  "ゥ": "ｩ",  "ェ": "ｪ",  "ォ": "ｫ",
			"ャ": "ｬ",  "ュ": "ｭ",  "ョ": "ｮ",  "ッ": "ｯ",  "ヮ": "ﾜ",
			"－": "-",  "‐": "-",  "―": "-",
			"！": "!",  "”": "\"",  "＃": "#",  "＄": "$",  "％": "%", "＆": "&",
			"’": "'",  "（": "(",  "）": ")",  "＝": "=",  "～": "~", "｜": "|",
			"＠": "@",  "‘": "`",  "｛": "{",  "｝": "}",  "＋": "+", "＊": "*",
			"；": ";",  "：": ":",  "＜": "<",  "＞": ">",  "、": ",", "。": ".",
			"？": "?",  "／": "/",  "＿": "_",  "￥": "\\", "．": "."
		},
		// 都道府県
		"pref": {
			 "1": "北海道",   "2": "青森県",   "3": "岩手県",   "4": "宮城県",   "5": "秋田県",
			 "6": "山形県",   "7": "福島県",   "8": "茨城県",   "9": "栃木県",  "10": "群馬県",
			"11": "埼玉県",  "12": "千葉県",  "13": "東京都",  "14": "神奈川県","15": "新潟県",
			"16": "富山県",  "17": "石川県",  "18": "福井県",  "19": "山梨県",  "20": "長野県",
			"21": "岐阜県",  "22": "静岡県",  "23": "愛知県",  "24": "三重県",  "25": "滋賀県",
			"26": "京都府",  "27": "大阪府",  "28": "兵庫県",  "29": "奈良県",  "30": "和歌山県",
			"31": "鳥取県",  "32": "島根県",  "33": "岡山県",  "34": "広島県",  "35": "山口県",
			"36": "徳島県",  "37": "香川県",  "38": "愛媛県",  "39": "高知県",  "40": "福岡県",
			"41": "佐賀県",  "42": "長崎県",  "43": "熊本県",  "44": "大分県",  "45": "宮崎県",
			"46": "鹿児島県","47": "沖縄県"
		}
	};
	jQuery(function($){
		// 初期実行
		Controller.init();
		// イベント登録
		Object.keys(Controller.events).forEach(function(selector) {
			var events = Controller.events[selector];
			Object.keys(events).forEach(function(event) {
				var func = events[event];
				if (selector === "document") {
					$(document).on(event, function(eve) {
						Controller[func](eve, this);
					});
				} else if (selector === "window") {
					$(window).on(event, function(eve) {
						Controller[func](eve, this);
					});
				} else {
					if (event !== "scroll") {
						$(document).on(event, selector, function(eve) {
							Controller[func](eve, this);
						});
					} else {
						$(selector).on(event, function(eve) {
							Controller[func](eve, this);
						});
					}
				}
			});
		});
	});
})();

/**
 * 日付関数
 *
 * @param string	format
 * @param Date		dateobj
 * @return string
 */
function date(format, dateobj) {
	switch (typeof(dateobj)) {
		case 'number':
			if (dateobj <= 24 * 60 * 60 * 1000) {
				dateobj += strtotime(date('Y-m-d 00:00:00'));
			}
		case 'string':
			dateobj = new Date(dateobj);
			break;
		case 'undefined':
			dateobj = new Date();
		default:
	}
	var ret = format;
	var replaces = {
		'Y': dateobj.getFullYear(),
		'm': ('0' + (dateobj.getMonth() + 1)).slice(-2),
		'n': dateobj.getMonth() + 1,
		'd': ('0' + dateobj.getDate()).slice(-2),
		'j': dateobj.getDate(),
		'H': ('0' + dateobj.getHours()).slice(-2),
		'i': ('0' + dateobj.getMinutes()).slice(-2),
		's': ('0' + dateobj.getSeconds()).slice(-2),
		'w': dateobj.getDay(),
		't': (new Date(dateobj.getFullYear(), dateobj.getMonth() + 1, 0)).getDate(),
		'曜': ['日', '月', '火', '水', '木', '金', '土'][dateobj.getDay()]
	};
	Object.keys(replaces).forEach(function(replaceKey){
		ret = ret.split(replaceKey).join(replaces[replaceKey]);
	});
	return ret;
}
/**
 * 日付文字列からUT取得
 *
 * @param string datestr
 * @return int
 */
function strtotime(datestr) {
	datestr = datestr.split('-').join('/');
	if (datestr.indexOf('/') >= 0) {
		// 日付
		var date = new Date(datestr);
		var time = date.getTime();
		return time;
	} else {
		// 時刻
		var sp = datestr.split(':');
		var time = 0;
		sp.forEach(function(str, index){
			time += str * Math.pow(60, 2 - index) * 1000;
		});
		return time;
	}
}

/**
 * FAQ項の開閉メニュー
 */

$(function(){
  var hideanswer = $(".service-faq .faqDetail .top-answer_sp");
  hideanswer.hide();
  $(".service-faq .faqDetail .q-text_sp").on('click',function(){
    if($(this).hasClass("close_sp")){
      $(this).next().slideDown();
      $(this).removeClass("close_sp").addClass("open_sp");
    }else{
      $(this).next().slideUp();
      $(this).removeClass("open_sp").addClass("close_sp");
    }  
  });
});

/**
 * フッター固定メニューの高さを取得して、その高さ分のmargin-bottomを確保
 */

$(document).ready(function(){
  var footerfixedheight=$("#footer-fixed").innerHeight();
  $(".footer_mb").css("margin-bottom", footerfixedheight);
});
$(window).resize(function(){
  var footerfixedheight=$("#footer-fixed").innerHeight();
  $(".footer_mb").css("margin-bottom", footerfixedheight);
});

/**
 * 新トイレつまりLP
 */

const FUNCTION = {};

FUNCTION.SAMPLE = {
    init: function() {
      this.bindEvents();
    },
    bindEvents: function () {
        $(".c-faqBox-a").hide();
        let $item = $('.c-faqBox').find('dl');
        $item.each(function () {
            let $trigger = $(this).find(".c-faqBox-q");
            let $target = $(this).find(".c-faqBox-a");
            $trigger.on('click', function () {
                if ($(this).hasClass("is-open")) {
                    $target.slideUp(200)
                    $(this).removeClass("is-open")
                } else {
                    $(this).addClass("is-open")
                    $target.slideDown(200)
                }
            });
        });

        $fadeTrigger = $('.jsc-fadetrigger');
        $fadeTrigger.on('click', function (e) {
            e.preventDefault();
            let $target = $($(this).attr("href"));
            if ($(this).hasClass("is-open")) {
                $target.slideUp(200)
                $(this).removeClass("is-open")
                $(this).find(".is-action").text("のお得なプランを見る")
            } else {
                $(this).addClass("is-open")
                $target.slideDown(200)
                $(this).find(".is-action").text("のお得なプランを閉じる")
            }
        });

        $reformTrigger = $('.jsc-reformtrigger');
        $reformTrigger.on('click', function (e) {
            e.preventDefault();
            let $target = $($(this).attr("href"));
            if ($(this).hasClass("is-open")) {
                $target.slideUp(200)
                $(this).removeClass("is-open")
                $(this).text("もっと見る")
            } else {
                $(this).addClass("is-open")
                $target.slideDown(200)
                $(this).text("閉じる")
            }
        });

        $caseTrigger = $('.jsc-casetrigger');
        $caseTrigger.on('click', function (e) {
            e.preventDefault();
            let $target = $($(this).attr("href"));
            if ($(this).hasClass("is-open")) {
                $target.slideUp(200)
                $(this).removeClass("is-open")
                $(this).text("お客様の施工事例をもっと見る")
            } else {
                $(this).addClass("is-open")
                $target.slideDown(200)
                $(this).text("お客様の施工事例を閉じる")
            }
        });

        // windowHeight = $(window).outerHeight();
        // $(window).scroll(function(){
        //     let count = $(window).scrollTop()
        //     if (count >= windowHeight) {
        //         $(".jsc-fix").addClass("is-fix")
        //     } else {
        //         $(".jsc-fix").removeClass("is-fix")
        //     }
        //  })


    }
};
FUNCTION.SAMPLE.init();

    $(function(){
        $('.jsc-voiceSlide').slick({
            infinite: true,
            slidesToShow: 2,
            slidesToScroll: 1,
            responsive: [{
                breakpoint: 768,
                settings: {
                    slidesToShow: 1,
                    slidesToScroll: 1,
                    infinite: true,
                    dots: false,
                    adaptiveHeight: true
                }
            }, ]
        });
    });

    $(function(){
        var heightArray = []
        $(".c-voiceBox").each(function() {
            heightArray.push($(this).outerHeight());
        })
        var maxheight = Math.max.apply(null, heightArray);
        $(".c-voiceBox").each(function() {
            $(this).css("height", maxheight)
        })

        $(".c-covid-trigger").on('click', function() {
            if ($(this).hasClass("is-open")) {
                $(this).removeClass("is-open")
                $(".c-covid-body").fadeOut(200)
            } else {
                $(this).addClass("is-open")
                $(".c-covid-body").fadeIn(200)
            }
        })
    });

/**
 * 新キッチンつまりLP
 */

//=============================================
//画像レスポンシブ
//=============================================
$(function() {
  var $elem = $('img');
  var sp = '-sp.';
  var pc = '-pc.';
  var replaceWidth = 768;
  function imageSwitch() {
    var windowWidth = parseInt(window.innerWidth);
    $elem.each(function() {
      var $this = $(this);
      if(windowWidth >= replaceWidth) {
        $this.attr('src', $this.attr('src').replace(sp, pc));
      } else {
        $this.attr('src', $this.attr('src').replace(pc, sp));
      }
    });
  }
  imageSwitch();
  var resizeTimer;
  $(window).on('resize', function() {
    clearTimeout(resizeTimer);
    resizeTimer = setTimeout(function() {
      imageSwitch();
    }, 100);
  });
});

//=============================================
//アコーディオン コロナ
//=============================================
$(function() {
	$('.toggle-box .toggle').click(function(){
        $(this).next().slideToggle('fast');
		$(this).toggleClass("open");
	});
});

//=============================================
//アコーディオン FAQ
//=============================================
$(function() {
	var dt = $('.faq-box dt:not(.closed)');
	$(".faq-box").find("dt:not(.closed)").addClass('selected');
	dt.click(function(){
		
		var next = $(this).next();
		
		if(next.is(':visible')){
			$(this).removeClass('selected');
			$(this).addClass('closed');
			next.slideToggle('fast')
		}else{
			$(this).addClass('selected');
			$(this).removeClass('closed');
			next.slideToggle('fast')
		}
	});
	
	var dt02 = $('.faq-box dt.closed');
	var dd02 = $('.faq-box dt.closed + dd');
	dd02.css("display","none");
	
	dt02.click(function(){
		var next = $(this).next();
		if(next.is(':visible')){
			$(this).removeClass('selected');
			$(this).addClass('closed');
			next.slideToggle('fast')
		}else{
			$(this).addClass('selected');
			$(this).removeClass('closed');
			next.slideToggle('fast')
		}
	});
});

//=============================================
//カルーセル
//=============================================
$(function() {
    $('.slick-box').slick({
        infinite: true,
        slidesToShow: 2,
        slidesToScroll: 1,
        prevArrow: '<img src="/wp-content/themes/qracian/images/kitchen/slide-arrow-l-pc.png" class="slick-prev">',
        nextArrow: '<img src="/wp-content/themes/qracian/images/kitchen/slide-arrow-r-pc.png" class="slick-next">',
        responsive: [
            {
              breakpoint: 768,
              settings: {
                    slidesToShow: 1,
                    adaptiveHeight: true,
                    prevArrow: '<img src="/wp-content/themes/qracian/images/kitchen/slide-arrow-l-sp.png" class="slick-prev">',
                    nextArrow: '<img src="/wp-content/themes/qracian/images/kitchen/slide-arrow-r-sp.png" class="slick-next">',
              }
            }
          ]
    });
});

//=============================================
//アコーディオン お支払い方法
//=============================================
$(function() {
	$('.payment .payment_toggle').click(function(){
        $(this).next().slideToggle('fast');
		$(this).toggleClass("open");
	});
});

//=============================================
//サービス料金アコーディオン
//=============================================
$(function() {
	$('.service .toggle02').click(function(){
        $(this).next().slideToggle('fast');
		$(this).toggleClass("open");
	});
    $('.service .toggle02-close').click(function(){
        var headerHeight = $('#header').outerHeight();
        var position = $(this).parent().parent().parent().offset().top;
        $(this).parent().prev().toggleClass('open');
        $(this).parent().slideToggle();
        $("html,body").animate({
            scrollTop : position - headerHeight
        }, {
            queue : false
        });
        
	});
});

//=============================================
//カルーセル_30周年特設ページ
//=============================================
$(function() {
    $('.contest-slick-box').slick({
        infinite: true,
        slidesToShow: 1,
        slidesToScroll: 1,
        prevArrow: '<img src="/wp-content/themes/qracian/images/kitchen/slide-arrow-l-pc.png" class="slick-prev">',
        nextArrow: '<img src="/wp-content/themes/qracian/images/kitchen/slide-arrow-r-pc.png" class="slick-next">',
        responsive: [
            {
              breakpoint: 768,
              settings: {
                    slidesToShow: 1,
              }
            }
          ]
    });
});

//=============================================
//アコーディオン 30周年特設ページ
//=============================================
$(function() {
	$('.contest_toggle_box .contest_toggle').click(function(){
        if ($(this).hasClass("open")) {
                $(this).prev().slideUp(200)
                $(this).removeClass("open")
                $(this).text("続きを見る")
        } else {
                $(this).prev().slideDown(200)
                $(this).addClass("open")
                $(this).text("閉じる")
                $('.contest-slick-box').slick('setPosition');
        }
	});
});

/**
 * 新トイレつまり駆けつけサービスLP
 */

//=============================================
//トイレ駆けつけサービス対応エリアの詳細
//=============================================
$(function() {
	$('.service_area .item-in .typesquare_option').click(function(){
        $(this).next().slideToggle('fast');
		$(this).toggleClass("is-open");
	});

});

//=============================================
//お客様の声
//=============================================
    $(function(){
        $('.jsc_voiceSlide').slick({
            infinite: true,
            slidesToShow: 2,
            slidesToScroll: 1,
            responsive: [{
                breakpoint: 768,
                settings: {
                    slidesToShow: 1,
                    slidesToScroll: 1,
                    infinite: true,
                    dots: false,
                    adaptiveHeight: true
                }
            }, ]
        });
    });

//=============================================
//よくあるご質問アコーディオン
//=============================================
$(function() {
	$('.sec_faq .c-faqBox-q').click(function(){
        $(this).next().slideToggle('fast');
		$(this).toggleClass("is-open");
	});
});

//=============================================
//指定給水装置・給水設備工事事業者アコーディオン
//=============================================
$(function() {
	$('.merchantNoArea dt').click(function(){
        $(this).next().slideToggle('fast');
		$(this).toggleClass("is-open");
	});

});


/**
 * 新トップページ
 */

//=============================================
//サービス料金アコーディオン
//=============================================
$(function(){
	$(".accordion li a").on("click", function() {
		$(this).next().slideToggle();	
		// activeが存在する場合
		if ($(this).children(".accordion_icon").hasClass('active')) {			
			// activeを削除
			$(this).children(".accordion_icon").removeClass('active');				
		}
		else {
			// activeを追加
			$(this).children(".accordion_icon").addClass('active');			
		}			
	});
});

//=============================================
//お客様の声カルーセル
//=============================================
$(function() {
    $('.slick-box').slick({
        infinite: true,
        slidesToShow: 2,
        slidesToScroll: 1,
        prevArrow: '<img src="/wp-content/themes/qracian/images/top/slide-arrow-l-pc.png" class="slick-prev">',
        nextArrow: '<img src="/wp-content/themes/qracian/images/top/slide-arrow-r-pc.png" class="slick-next">',
        responsive: [
            {
              breakpoint: 768,
              settings: {
                    slidesToShow: 1,
                    adaptiveHeight: true,
                    prevArrow: '<img src="/wp-content/themes/qracian/images/top/slide-arrow-l-sp.png" class="slick-prev">',
                    nextArrow: '<img src="/wp-content/themes/qracian/images/top/slide-arrow-r-sp.png" class="slick-next">',
              }
            }
          ]
    });
});


//=============================================
//ポップアップアコーディオン
//=============================================

$(function() {
	$('header .window ul li.dropdown a').click(function(){
        $(this).next().slideToggle('fast');
		$(this).toggleClass("is-open");
	});
});



//=============================================
//メインスライダー
//=============================================

$(function() {
  $('.main_slider').slick({
    autoplay:true,
    autoplaySpeed:2500,
    dots:false,
	fade:true,
	prevArrow:'<img src="/wp-content/themes/qracian/images/top/arrow01.png" class="slide-arrow prev-arrow">',
    nextArrow:'<img src="/wp-content/themes/qracian/images/top/arrow02.png" class="slide-arrow next-arrow">',
});
});



$(document).click(function(event) { // (1)
    if (!$.contains($("#pop-up")[0], event.target)) { // (2)
        $("#pop-up").hide();
    }
});

//=============================================
//PC/SP選ばれる理由モーダルウインドウ
//=============================================
$(function(){
   
  // 「.modal_open」をクリックしたらモーダルと黒い背景を表示する
  $('.modal_open').click(function(){
 
    // 黒い背景をbody内に追加
    $('body').append('<div class="modal_bg"></div>');
    $('.modal_bg').fadeIn();
 
    // data-targetの内容をIDにしてmodalに代入
    var modal = '#' + $(this).attr('data-target');
 
    // モーダルをウィンドウの中央に配置する
    function modalResize(){
        var w = $(window).width();
        var h = $(window).height();
 
        var x = (w - $(modal).outerWidth(true)) / 2;
        var y = (h - $(modal).outerHeight(true)) / 2;
 
        $(modal).css({'left': x + 'px','top': y + 'px'});
    }
 
    // modalResizeを実行
    modalResize();
 
    // modalをフェードインで表示
    $(modal).fadeIn();
 
    // .modal_bgか.modal_closeをクリックしたらモーダルと背景をフェードアウトさせる
    $('.modal_bg, .modal_close').off().click(function(){
        $('.modal_box').fadeOut();
        $('.modal_bg').fadeOut('slow',function(){
            $('.modal_bg').remove();
        });
    });
 
    // ウィンドウがリサイズされたらモーダルの位置を再計算する
    $(window).on('resize', function(){
        modalResize();
    });
 
    // .modal_switchを押すとモーダルを切り替える
    $('.modal_switch').click(function(){
 
      // 押された.modal_switchの親要素の.modal_boxをフェードアウトさせる
      $(this).parents('.modal_box').fadeOut();
 
      // 押された.modal_switchのdata-targetの内容をIDにしてmodalに代入
      var modal = '#' + $(this).attr('data-target');
 
      // モーダルをウィンドウの中央に配置する
      function modalResize(){
          var w = $(window).width();
          var h = $(window).height();
 
          var x = (w - $(modal).outerWidth(true)) / 2;
          var y = (h - $(modal).outerHeight(true)) / 2;
 
          $(modal).css({'left': x + 'px','top': y + 'px'});
      }
 
      // modalResizeを実行
      modalResize();
 
      $(modal).fadeIn();
 
      // ウィンドウがリサイズされたらモーダルの位置を再計算する
      $(window).on('resize', function(){
          modalResize();
      });
    });
  });
});



//=============================================
//SP対応エリア
//=============================================
// ウィンドウを開く
$( '.js-modal-open' ).each( function() {
     $( this ).on( 'click', function() {
          var target = $( this ).data( 'target' );
          var modal = document.getElementById( target );
          $( modal ).fadeIn( 300 );
          return false;
     });
});

// ウィンドウを閉じる
$( '.js-modal-close' ).on( 'click', function() {
    $( '.js-modal' ).fadeOut( 300 );
    return false;
});



//=============================================
//SP 固定ヘッダースクロール時非表示
//=============================================


$(function () {
	var menuHeight = $("#header").height();
	var startPos = 0;
	$(window).scroll(function () {
		var currentPos = $(this).scrollTop();
		if (currentPos > startPos) {
			if ($(window).scrollTop() >= 200) {
				$("#header").css("top", "-" + menuHeight + "50px");
			}
		} else if (startPos > currentPos) {
			$("#header").css("top", 0 + "px");
		}
		startPos = currentPos;
	});
});


//=============================================
//PC メインビジュアルフェード
//=============================================
$(function(){
    var setImg = '.viewer';
    var fadeSpeed = 800;
    var switchDelay = 5000;
  
    $(setImg).children('img').css({opacity:'0'});
    $(setImg + ' img:first').stop().animate({opacity:'1',zIndex:'20'},fadeSpeed);
  
    setInterval(function(){
        $(setImg + ' :first-child').animate({opacity:'0'},fadeSpeed).next('img').animate({opacity:'1'},fadeSpeed).end().appendTo(setImg);
    },switchDelay);
});
