/**
 * common.js
 */

;(function($) {
	//===================================== init var
	var $window;

	//===================================== document ready
	$(function() {
		$window = $(window);

		var browser = getBrowser();
		var device = getDevice();
		var breakPoint = 640;

		//window load resize action
		$window.on('load resize', function(e){
			if ( e.type === 'load' ) {
				//uniform selectbox
				//required jquery.uniform.js
				if( $('select.uniform')[0] && browser !== 'ie7' && browser !== 'ie8' ){
					$('select.uniform').uniform({
						selectAutoWidth: false
					});
				}
			}
			alignHeight();
		});

		//local scroll --------------------------------------
		$('.smoothScroll').find('[href^="#"]').click(function(e){
			var $trigger = $(this);
			var targetId = $trigger.attr('href').replace('#', '');
			var targetBlock = $('#' + targetId);
			if ($(targetBlock).length > 0) {
				var speed = 0;
				var strHeaderHeight = $('header').outerHeight() ;
				var position = $(targetBlock).offset().top - strHeaderHeight ;
				$("html, body").animate({ scrollTop: position }, speed, "swing");
			}else{
				$('html, body').stop().animate({ scrollTop: 0 }, 500);
			}
			e.preventDefault();
			return false;
		});

		/**
		 * initialize accordion for small screen
		 */
		function initSmallScreenAccordion() {
			var $smallAccordionTitles = $('.smallAccordionTitle');
			var $smallAccordionContents = $('.smallAccordionContent');

			var smallScreenAccordionOpenClassName = 'open';

			if( $smallAccordionTitles[0] === undefined ){
				return;
			}

			$smallAccordionTitles.each(function(index){
				var $this = $(this);
				$this.data('titleIndex', index);

				$this.click(function(e){
					var $clickedObj =  $(this);
					var index = $clickedObj.data('titleIndex');
					var $content = $smallAccordionContents.eq(index);

					if( !$content.hasClass(smallScreenAccordionOpenClassName) ){
						$this.addClass(smallScreenAccordionOpenClassName);
					}

					$content.not(':animated').slideToggle(200, function(e){
						var $this = $(this);

						$this.toggleClass(smallScreenAccordionOpenClassName);

						if( $this.css('display') === 'block' ){
							scrollToWithjQueryObject($clickedObj);
							$this.data('opened', true);
							alignHeight();
						}else{
							$clickedObj.removeClass(smallScreenAccordionOpenClassName);
							$this.data('opened', false);
						}
						$this.removeAttr('style');
					});

					e.preventDefault();
					return false;
				});
			});

			$window.on('resize', function(){
				if( getViewport().width > breakPoint ){
					$smallAccordionContents.addClass(smallScreenAccordionOpenClassName);
				}else{
					$smallAccordionContents.removeClass(smallScreenAccordionOpenClassName);
					$smallAccordionContents.each(function(index){
						var $this = $(this);

						if( $this.data('opened') ){
							$smallAccordionTitles.eq(index).addClass(smallScreenAccordionOpenClassName);
							$this.addClass(smallScreenAccordionOpenClassName);
						}
					});
				}
			});
		}

		initSmallScreenAccordion();
		// accordion for small screen ------------------------------

		/**
		 * initialize bx slider
		 * required jquery.bxslider.min.js
		 */
		function initBxslider() {
			var $slider = $('#slider');

			if( $slider[0] === undefined ){
				return;
			}
			
			var sliderElmChild =  $slider.find('li').length;
			if(sliderElmChild < 2){
				return;
			}
			
			var obj = $slider.bxSlider({
				auto: true,
				pause: 5000,
				speed: 800,
				pager: true,
				controls: true,
				touchEnabled: true,
				autoControlsCombine: true,
				autoControls: true,
				onSliderLoad: function () {
					var $slidecntrlPager = $('.bxsld_pager').css('display', 'inline-block');
					var $slidecntrlAuto = $('.bxsld_controls-auto').css('display', 'inline-block');
					var $slidecntrlCntrlset = $('<div class="bxsld_controls-pager-auto" />');
					$slidecntrlCntrlset.append($slidecntrlAuto).append($slidecntrlPager);
					$slidecntrlCntrlset.prependTo($('.bxsld_controls'));
					var $slidecntrlDirBgPrev = $('<div class="bxsld_controls_dirction_bg_prev" />');
					var $slidecntrlDirBgNext = $('<div class="bxsld_controls_dirction_bg_next" />');
					$('.bxsld_controls-direction').append($slidecntrlDirBgPrev).append($slidecntrlDirBgNext);
					
					var getHash = location.hash;
					if(getHash){
						var $html = $('html, body');
						var getIdPos = $(getHash).position();
						$html.scrollTop(getIdPos.top);
					}
					
					_heightAdjust();

				},
				onSliderResize: function(){
					_heightAdjust();
				},
				onSlideBefore: function () {
					if( device === 'android' || device === 'iphone' || device === 'ipad' ){
						var $pagerItemAnchor = $('.bxsld_pager-item a');
						$pagerItemAnchor.addClass('smartphone');
					}					
				},
				onSlideAfter: function () {
				}
			});
			
			function _heightAdjust() {
				var $mainViDevice = $slider.find('.main_vi_device');					
				if($mainViDevice.length > 0){
					$mainViDevice.css({'height' : 'auto'});
					var largeHeight = 0;
					$mainViDevice.each(function(){
						var getHeight = $(this).height();						
						if(getHeight > largeHeight){
							largeHeight = getHeight;					
						}
					});						
					$mainViDevice.css({'height' : largeHeight + 'px'});
				}
			}
			
		}

		initBxslider();
		//bx slider ------------------------------

		/**
		 * align height
		 * required jquery.tile.js
		 */
		function alignHeight() {
			var $tileSameRoots = $('.tileSame');

			if( $tileSameRoots[0] === undefined ){
				return;
			}

			for( var i = 0, l = $tileSameRoots.length; i < l; i++ ){
				var $tileSameRoot = $tileSameRoots.eq(i);
				var $cells = $tileSameRoot.find('[class*="tlSame"]');

				if( $cells[0] === undefined || $tileSameRoot.css('height').replace('px', '') <= 0 || $tileSameRoot.css('display') === 'none' ){
					continue;
				}

				var tiledClassNameArray = [];
				for( var j = 0, jl = $cells.length; j < jl; j++ ){
					if( $cells.eq(j).css('height').replace('px', '') <= 0 || $cells.eq(j).css('display') === 'none' ){
						continue;
					}

					var className = $cells.eq(j).attr('class');
					var startIndex = className.indexOf('tlSame');

					var noPrefixHl = className.substring(startIndex, className.length);

					var endIndex = noPrefixHl.search(/ /);

					var hlClassName;
					if( endIndex !== -1 ){
						hlClassName = noPrefixHl.substring(0, endIndex);
					}else{
						hlClassName = noPrefixHl;
					}

					if( $.inArray(hlClassName, tiledClassNameArray) === -1 ){
						var $groupCells = $tileSameRoot.find('.' + hlClassName);
						var firstOffset = $groupCells.eq(0).offset().top;
						var numberOfColumn = 0;
						for( var k = 0, kl = $groupCells.length; k < kl; k++  ){
							if( firstOffset !== $groupCells.eq(k).offset().top ){
								numberOfColumn = k;
								break;
							}
						}

						$groupCells.tile(numberOfColumn);
						tiledClassNameArray[tiledClassNameArray.length] = hlClassName;
					}
				}
			}
		}
		//align height ------------------------------

		/**
		 *  initialize responsiveTabs
		 *  required jquery.responsiveTabs.js
		 */
		function initTabAccordion(){
			var $accordionTab = $('.tabAccordion');

			if( $accordionTab[0] ){
				$accordionTab.responsiveTabs();
			}
		}
		initTabAccordion();
		//initialize responsiveTabs ------------------------------

		/**
		 *  initialize normalTab
		 */
		function initNormalTab(){
			var $tabWrapper = $('div.tabNormal');

			if( $tabWrapper[0] === undefined ){
				return;
			}

			var tabActiveClassName = 'act';

			$tabWrapper.each(function() {
				var $tabWrap = $(this);
				var $tabUl = $tabWrap.find('.tabNormalTitle');
				var $tabTriggerLi = $tabUl.find('li');
				var $tabContent = $tabWrap.find('.tabNormalDetail');
				var tabOpenClassName = 'open';

				$tabUl.css('display', 'block');

				$tabTriggerLi.eq(0).addClass(tabActiveClassName);
				$tabContent.eq(0).addClass(tabActiveClassName);

				$tabTriggerLi.each(function(index) {
					var $li = $(this);
					var $a = $li.children('a');

					$a.data('tabIndex', index);

					$a.click(function (e) {
						var $trigger = $(this);
						var thisIndex = $trigger.data('tabIndex');

						$tabTriggerLi.removeClass(tabActiveClassName);
						$tabContent.removeClass(tabActiveClassName);
						$trigger.parent('li').addClass(tabActiveClassName);
						$tabContent.eq(thisIndex).addClass(tabActiveClassName);

						if ($tabContent.eq(thisIndex).find('.tileSame').size() > 0) {
							alignHeight();
						}

						e.preventDefault();
						return false;
					});
				});
			});
		}
		initNormalTab();
		// initialize normalTab --------------------------

		/**
		 * initialize smallTable
		 */
		function initSmallTable(){
			$('.smallTableTrigger > a > img').attr('src', 'asset/image/logo/small_table_btn.png');
			var smallTableClassName = 'smallTable';
			var $originSmallTables = $('.' + smallTableClassName);
			var hiddenOriginTableClassName = 'smallTable-hidden';

			if( $originSmallTables[0] === undefined ){
				return;
			}

			var $triggers = $('.smallTableTrigger');

			var $contentsWrapper = $('div.largeContentsWrapper');
			if( $contentsWrapper[0] === undefined ){
				$contentsWrapper = $('body').wrapInner('<div class="largeContentsWrapper"></div>').find('div.largeContentsWrapper');
			}
			//var $contentsWrapper = $('body').wrapInner('<div class="largeContentsWrapper"></div>').find('div.largeContentsWrapper');
			var $smallTableWrapper = $('<div class="tbl_wrapper smallTableWrapper" />').append('<p class="tbl_btn backBtn"><a class="ico_nml_lf left_lf" href="javascript:void(0)">Back</a></p>');
			var $backBtn = $smallTableWrapper.find('.backBtn');
			var originScrollTop = 0;

			$contentsWrapper.before($smallTableWrapper);
			changeLayout();

			$triggers.each(function(index){
				var $trigger = $(this);

				$trigger.data('triggerIndex', index);

				$trigger.click(function(e){
					var index = $trigger.data('triggerIndex');
					var $originSmallTable = $originSmallTables.eq(index);
					var $smallTable = $originSmallTable.clone(true).css('display', 'block');

					originScrollTop = $window.scrollTop();

					$smallTableWrapper.append($smallTable);
					$contentsWrapper.css('display', 'none');
					$smallTableWrapper.css('display', 'block');

					$('body, html').scrollTop(0);
				});
			});

			$backBtn.find('a').click(function(e){
				hideSmallTable();
				$smallTableWrapper.find('.' + smallTableClassName).remove();

				e.preventDefault();
				return false;
			});

			$window.resize(function(e){
				changeLayout();
			});

			$window.scroll(function(e){
				var offsetLeft = $(this).scrollLeft();

				$backBtn.css('margin-left', offsetLeft);
			});

			/**
			 * show small Table
			*/
			function showSmallTable(){
				$contentsWrapper.css('display', 'none');
				$smallTableWrapper.css('display', 'block');
			}

			/**
			 * hide small Table
			*/
			function hideSmallTable(){
				$contentsWrapper.css('display', 'block');
				$('body, html').scrollTop(originScrollTop);
				$smallTableWrapper.css('display', 'none');
			}

			/**
			 *  change layout
			 */
			function changeLayout() {
				if( getViewport().width > breakPoint ){
					$originSmallTables.removeClass(hiddenOriginTableClassName);

					if( $smallTableWrapper.find('.' + smallTableClassName)[0] ){
						hideSmallTable();
					}
				}else{
					$originSmallTables.addClass(hiddenOriginTableClassName);

					if( $smallTableWrapper.find('.' + smallTableClassName)[0] ){
						showSmallTable();
					}
				}
			}
		}
		initSmallTable();
		// initialize smallTable --------------------------

		/**
		 * initialize accordion
		 */
		function initAccordionSct(){
			var $acoDtl = $('.accordionDetail');

			var acoTtlClassName = ('.accordionTitle');

			var $singleLink_acd_ttl = $('.accordionSingleLink .accordionTitle');
			var activeClassName = ('open');

			$acoDtl.hide();
			$acoDtl.removeClass(activeClassName);

			$singleLink_acd_ttl.click(function () {
				var $clickedObj = $(this);
				var $content = $clickedObj.parent().find('.accordionDetail');

				if( !$content.hasClass(activeClassName) ){
					$clickedObj.addClass(activeClassName);
				}

				$content.not(':animated').slideToggle(200, function(e){
					var $this = $(this);

					$this.toggleClass(activeClassName);

					if( $this.css('display') === 'block' ){
						scrollToWithjQueryObject($clickedObj);
						alignHeight();
					}else{
						$clickedObj.removeClass(activeClassName);
					}
				});
			});
		}

		initAccordionSct();

		function defaultOpenAccordion(){
			var activeClassName = ('open');

			var $defaultOpen = $('.defaultOpen');

			$defaultOpen.children('.accordionSingleLink .accordionTitle, .accordionSingleLink .accordionDetail').addClass(activeClassName);
			$defaultOpen.children('.accordionDetail').show();

		}

		defaultOpenAccordion();
		// initialize accordion --------------------------

		/**
		 * initialize smallImage
		 */
		function initSmallImage(){
			$('p > img').addClass('smallImage');
			$('img').parent('p').not('.smallTableTrigger').addClass("smallImageTrigger");
			var smallImageClassName = 'smallImage'; //class 名の指定
			var $originsmallImages = $('.' + smallImageClassName);
			var hiddenOriginImageClassName = 'hidden';

			if( $originsmallImages[0] === undefined ){
				return;
			}

			var $triggers = $('.smallImageTrigger');

			var $contentsWrapper = $('div.largeContentsWrapper');
			if( $contentsWrapper[0] === undefined ){
				$contentsWrapper = $('body').wrapInner('<div class="largeContentsWrapper"></div>').find('div.largeContentsWrapper');
			}
			//var $contentsWrapper = $('body').wrapInner('<div class="largeContentsWrapper"></div>').find('div.largeContentsWrapper');
			var $smallImageWrapper = $('<div class="img_wrapper smallImageWrapper" />').append('<p class="img_btn backBtn"><a class="ico_nml_lf left_lf" href="javascript:void(0)">Back</a></p>');
			var $backBtn = $smallImageWrapper.find('.backBtn');
			var originScrollTop = 0;

			$contentsWrapper.before($smallImageWrapper);

			$triggers.each(function(index){
				var $trigger = $(this);

				$trigger.data('triggerIndex', index);

				$trigger.click(function(e){
					var index = $trigger.data('triggerIndex');
					var $originsmallImage = $originsmallImages.eq(index);
					var $smallImage = $originsmallImage.clone(true).css({'display':'block', 'width':''});

					originScrollTop = $window.scrollTop();

					$smallImageWrapper.append($smallImage);
					$contentsWrapper.css('display', 'none');
					$smallImageWrapper.css('display', 'block');

					$("meta[name='viewport']").attr('content', 'width=1200, initial-scale=1.0, maximum-scale=2.0, user-scalable=yes');


					$('body, html').scrollTop(0);
				});
			});

			$backBtn.find('a').click(function(e){
				hidesmallImage();
				$smallImageWrapper.find('.' + smallImageClassName).remove();

				$("meta[name='viewport']").attr('content', 'width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no');


				e.preventDefault();
				return false;
			});

			$window.scroll(function(e){
				var offsetLeft = $(this).scrollLeft();

				$backBtn.css('margin-left', offsetLeft);
			});

			/**
			 * show small Image
			*/
			function showsmallImage(){
				$contentsWrapper.css('display', 'none');
				$smallImageWrapper.css('display', 'block');
			}

			/**
			 * hide small Image
			*/
			function hidesmallImage(){
				$contentsWrapper.css('display', 'block');
				$('body, html').scrollTop(originScrollTop);
				$smallImageWrapper.css('display', 'none');
			}

		}
		//initSmallImage();
		// initialize smallImage --------------------------

		/**
		 *  scroll with animation when accordion opened.
		 *
		 *  @param {$} $obj jQuery Object
		 *  when accordion open, scroll to $obj
		 */
		function scrollToWithjQueryObject( $obj ){
			var offsetTop = $obj.offset().top;
			var slideDurationSP = 400;
      /* 20220719 add 247 No.221 不具合対応 ここから*/
      var headerHeight = $("header#page-header").outerHeight(true) ; //headerの位置を取得"
			$('body, html').animate(
				{ 'scrollTop':  offsetTop - headerHeight}, slideDurationSP);
      /* 20220719 add 247 No.221 不具合対応 ここまで*/
		}
		// scrollToWithjQueryObject ---------------------


		/**
		 *  get viewport
		 */
		function getViewport() {
			var e = window, a = 'inner';
			if (!('innerWidth' in window )) {
				a = 'client';
				e = document.documentElement || document.body;
			}
			return { width : e[ a+'Width' ] , height : e[ a+'Height' ] };
		}

		//check browser
		/**
		 *  get browser name
		 *
		 *  @return     browser name(ie6, ie7, ie8, ie9, ie10, ie11, chrome, safari, opera, firefox, unknown)
		 *
		 */
		function getBrowser() {
			var userAgent = window.navigator.userAgent.toLowerCase();
			var appVersion = window.navigator.appVersion.toLowerCase();
			var browserName = 'unknown';

			if (userAgent.indexOf('msie') !== -1){
				if (appVersion.indexOf('msie 6.') !== -1){
					browserName = 'ie6';
				}else if (appVersion.indexOf('msie 7.') !== -1){
					browserName = 'ie7';
				}else if (appVersion.indexOf('msie 8.') !== -1){
					browserName = 'ie8';
				}else if (appVersion.indexOf('msie 9.') !== -1){
					browserName = 'ie9';
				}else if (appVersion.indexOf('msie 10.') !== -1){
					browserName = 'ie10';
				}else{
					browserName = 'ie';
				}
			}else if(userAgent.indexOf('trident/7') !== -1){
				browserName = 'ie11';
			}else if (userAgent.indexOf('chrome') !== -1){
				browserName = 'chrome';
			}else if (userAgent.indexOf('safari') !== -1){
				browserName = 'safari';
			}else if (userAgent.indexOf('opera') !== -1){
				browserName = 'opera';
			}else if (userAgent.indexOf('firefox') !== -1){
				browserName = 'firefox';
			}
			return browserName;
		}
		// getBrowser ------------------------------

		/**
		 *  get device
		 *
		 *  @return     device name(iphone, ipad, android, other)
		 *
		 */
		function getDevice() {
			var userAgent = window.navigator.userAgent.toLowerCase();
			var deviceName = 'other';

			if ( userAgent.indexOf('iphone') !== -1 ){
				deviceName = 'iphone';
			}else if ( userAgent.indexOf('ipad') !== -1 ){
				deviceName = 'ipad';
			}else if ( userAgent.indexOf('android') !== -1 ){
				deviceName = 'android';
			}
			return deviceName;
		}
		// getDevice ------------------------------
	});
})(jQuery);
