// ウィンドウ幅の判定
function checkDeviceType() {
	var width = window.innerWidth;
	if (width > 768) {
		return 'pc';
	}else if(width > 480){
		return 'tab'
	}else{
		return 'sp';
	}
}

// 現在の画面幅がhtmlで指定したブレイクポイントと一致するか判定
function matchHtmlDataBreakpoint(device, breakpoint){
	if (breakpoint === 'sp') {
		if (device === 'sp') {
			return false;
		}else{
			return true;
		}
	}else if(breakpoint === 'tab'){
		if (device === 'sp' || device === 'tab') {
			return false;
		}else{
			return true;
		}
	}
}

// htmlのData属性からブレイクポイントを取得
function getHtmlDataBreakpoint(num) {
	var breakpoint = $('#js-align-height-breakpoint-tab' + num);
	if (!breakpoint.length) {
		return 'tab';
	}
	return 'sp';
}

// 高さをそろえたい要素のグループを取得
function getClassList() {
	var elements = $('[class*="js-align-height-box"]'),
	classList = [],
	className;
	elements.each(function(index, element) {
		className = element.getAttribute('class').match(/js-align-height-box[0-9]+/);
		if (!className) {
			return;
		}
		if(classList.indexOf('.' + className[0]) >= 0){
			return;
		}else{
			classList.push('.' + className[0]);
		}
	});
	if (classList.length === 0 || classList === undefined || classList === null) {
		console.error('align-height.js:\nページ内に要素「.js-align-height-box(番号)」がありません。\n要素が正しく設置されているか確認してください。');
		return;
	}
	return classList;
}

//取得した中で一番高い高さを付与する
function matchHeight() {
	var elementsGroup =  getClassList(),//高さを揃えたい要素のグループ
	maxHeight = 0,//一番高さのある要素の高さ
	boxHeight = 0,//要素の高さ
	device = checkDeviceType(),//sp or tab
	breakpoint,//htmlで指定した高さを揃える際のブレイクポイント
	needClearMaxHeight;//高さのクリアが必要か

	elementsGroup.forEach(function(elements) {
		$(elements).css('min-height', 'auto');
		if (elements.match(/[0-9]+/) != null) {
			breakpoint = getHtmlDataBreakpoint(elements.match(/[0-9]+/)[0]);
		}else{
			return;
		}
		needClearMaxHeight = matchHtmlDataBreakpoint(device,breakpoint);
		// 高さを揃える必要がない場合、処理を抜ける
		if (!needClearMaxHeight) {
			return;
		}

		// 高さの比較
		$(elements).each(function(index, element) {
			boxHeight = $(element).outerHeight();
			if (index === 0) {
				maxHeight = boxHeight;
			}else if(maxHeight < boxHeight){
				maxHeight = boxHeight;
			}
		});

		// 要素にmaxHeightを指定
		$(elements).css('min-height', maxHeight + 'px');
	});
};

window.addEventListener('load', function () {
	matchHeight();
});

window.addEventListener('resize', function(){
	setTimeout(function(){
		matchHeight();
	//↓ページ読み込んだら 0.5秒後に 高さ取得する（setTimeout）
	},500);
});