var observe_time = null;
var history_show_count = 5;

var getHistory = function(job_ofr_no, company_name, catch_copy, income, location) {
	var url = '/api/job_history';
	try {
		checkLocalStrageTime();
		
		var history = localStorage.getItem('history');
		if(history == null) {
			history = {
				'history' : [] 
			};
		}else{
			history = JSON.parse(history);
		}
		
		var data = [];
		if(job_ofr_no == undefined && company_name == undefined && catch_copy == undefined && income == undefined && location == undefined) {
			data = {'history' : history};
		}else{
			data = {
				'history' : history,
				'job_ofr_no' : job_ofr_no,
				'company_name' : company_name,
				'catch_copy' : catch_copy,
				'income' : income,
				'location' : location,
			};
		}
		
		$.ajax({
			url: url,
			type: 'POST',
			dataType: 'json',
			data: data
		})
		.done(function(data) {
			if(Object.keys(data).length > 0) {
				generateHistory(data);
				localStorage.setItem('history', JSON.stringify(data['history']));
				setLocalStrageTime();
			}
		})
		.fail(function(data) {
			console.log(data);
			alert("求人閲覧履歴の取得に失敗しました。");
		});
	} catch(e) {
		deleteLocalStrageHistory();
	}
}
var getHistoryHeader = function() {
	var url = '/api/job_history';
	try{
		checkLocalStrageTime();
		
		var history = localStorage.getItem('history');
		if(history == null) {
			history = {
				'history' : [] 
			};
		}else{
			history = JSON.parse(history);
		}
		var data = {
				'history' : history,
		};
		
		$.ajax({
			url: url,
			type: 'POST',
			dataType: 'json',
			data: data
		})
		.done(function(data) {
			if(Object.keys(data).length > 0) {
				generateHistoryHeader(data);
				generateHistory(data);
				localStorage.setItem('history', JSON.stringify(data['history']));
				setLocalStrageTime();
			}
		})
		.fail(function(data) {
			console.log(data);
			alert("求人閲覧履歴の取得に失敗しました。");
		});
	} catch(e) {
		deleteLocalStrageHistory();
	}
}


var deleteLocalStrageHistory = function() {
	localStorage.removeItem('history');
}

var generateHistory = function(data) {
	var dom = '';
	if(data.hasOwnProperty('history')) {
		var count = 1;
		var history_size = data['history'].length;
		for(key in data['history']) {
			if((count - 1) % 8 == 0) {
				dom += '<ul  class="history__list">';
			}
			dom +=  '<li class="history__item">'
			     +  '    <a href="/' + jobsearch_path + '/' + data['history'][key]['job_ofr_no'] + '/" class="history__anchor" target="_blank">'
			     +  '        <ul class="history__inList">'
			     +  '            <li class="history__inItem--company">' + truncateHistory(data['history'][key]['company_name'], 45) + '</li>'
			     +  '            <li class="history__inItem--job pc">' + truncateHistory(data['history'][key]['catch_copy'], 45) + '</li>'
			     +  '            <li class="history__inItem--job sp">' + truncateHistory(data['history'][key]['catch_copy'], 90) + '</li>'
			     +  '            <li class="history__inItem--yearlyIncome">' + truncateHistory(data['history'][key]['income'], 44) + '</li>'
			     +  '            <li class="history__inItem--location">' + truncateHistory(data['history'][key]['location'], 49) + '</li>'
			     +  '        </ul>'
			     +  '    </a>'
			     +  '</li>';
			if(count % 8 == 0 && count != history_size) {
				dom += '</ul>';
			}
			count++;
		}
		$(".history__slideItem").html(dom);

		// 求人詳細ページでは自身の閲覧履歴を含むため、閲覧履歴が必ず1件以上存在するが、
		// 企業別求人一覧ページでは1件も存在しない可能性があるため、閲覧履歴エリアの表示制御が必要
		if ($('#historyArea').length) {
			$('#historyArea').show();
		}

		exeHistoryButton(history_show_count, 5);
		setSlick();
		setHistoryClickEvent();
	}
}

var generateHistoryHeader = function(data) {
	var dom = '';
	if(data.hasOwnProperty('history')) {
		var history_size = data['history'].length;
		if(history_size != 0) {
			$(".historyFixed__body").mCustomScrollbar('destroy');
			
			dom += '<ul class="historyFixed__list">';
			for(key in data['history']) {
				dom += '<li class="historyFixed__item">'
				     + '    <a href="/' + jobsearch_path + '/' + data['history'][key]['job_ofr_no'] + '/" class="historyFixed__anchor" target="_blank">'
				     + '        <div class="historyFixed__textOuter">'
				     + '            <p class="historyFixed__company">' + data['history'][key]['company_name'] + '</p>'
				     + '            <p class="historyFixed__job">' + data['history'][key]['catch_copy'] + '</p>'
				     + '        </div>'
				     + '    </a>'
				     + '</li>';
			}
			dom += '</ul>';
			$(".historyFixed__body").html(dom);
			$(".historyFixed__head").show();
			// スクロールバー表示
			$(".historyFixed__body").mCustomScrollbar({
				theme: "inset-3-dark"
			});
			setHistoryClickEvent();
		}
	}
}

var truncateHistory = function(word, size) {
	if(word == undefined) {
		return word;
	}
	var word_array = word.split('');
	var count = 0;
	var str = '';
	for( i = 0 ; i < word_array.length ; i++) {
		var n = escape(word_array[i]);
		if(n.length < 4) {
			count++;
		}else{
			count += 2;
		}
		
		if(count > size) {
			return str + '…';
		}
		str += word.charAt(i);
	}
	
	return word;
}

// 幅確認
var checkWindow = function () {
	if ($(window).width() >= 768) {
		var angle = screen && screen.orientation && screen.orientation.angle;
		if (angle !== 0 && navigator.userAgent.match(/iPhone|Android.+Mobile/)) {
			$("meta[name='viewport']").attr("content", "width=749");
			return 'isSP';
		} else if (navigator.userAgent.match(/iPhone|Android.+Mobile/)) {
			return 'isSP';
		} else {
			return 'isPC';
		}
	} else {
		return 'isSP';
	}
}
var exeHistoryButton = function(initNum, moreNum) {
	//履歴をもっとみる
	$("button.history__button").remove();
	if (checkWindow() === 'isSP') {
		var historyItems = $(".history__item").length;
		if (historyItems > initNum) {
			$(".history__slideList").after('<button class="history__button">もっと見る</button>');
			for(var i = 1 ; i <= $(".history__item").length ; i++) {
				if(i <= initNum) {
					$($(".history__item")[i - 1]).removeClass('is-hidden');
				}else {
					$($(".history__item")[i - 1]).addClass('is-hidden');
				}
			}
		}
		$('.history__button').on('click', function () {
			$('.history__list .history__item.is-hidden').slice(0, moreNum).removeClass('is-hidden');
			if ($('.history__list .history__item.is-hidden').length == 0) {
				$('.history__button').remove();
			}
		});
	}
}

var checkLocalStrageTime = function(){
	var history_time = localStorage.getItem('history_time');
	if(history_time != null) {
		var now_time = (new Date()).getTime();
		var diff = now_time - history_time;
		
		if(diff > (60 * 60 * 24 * 365 * 1000)){
			deleteLocalStrageHistory();
		}
	}
}

var setLocalStrageTime = function() {
	var now_time = new Date();
	localStorage.setItem('history_time', now_time.getTime());
}

var setSlick = function() {
	// slick関係
	var slideItems = $(".history__list").length;
	if (checkWindow() === 'isPC') {
		if (slideItems >= 2) {
			if($(".history__slideItem").hasClass("footer_history__slideItem")){
				$(".history__slideItem").slick({
					dots: true,
					infinite: false,
					dotsClass: 'slide-dots',
					prevArrow: '<button class="slick-arrow-prev"><img src="/resource/jobsearch/img/slide-arrow-prev.svg" class="slide-arrow-prev"></button>',
					nextArrow: '<button class="slick-arrow-next"><img src="/resource/jobsearch/img/slide-arrow-next.svg" class="slide-arrow-next"></button>',
				});
			}
		}
	}
}

var setHistoryClickEvent = function(){
	// 設定済イベントの削除
	$(".history__anchor").off('click');
	$(".historyFixed__anchor").off('click');
	$(".history__anchor").off('mouseup');
	$(".historyFixed__anchor").off('mouseup');
	
	// イベントの設定
	$(".history__anchor").on('click', function() {
		var parent_li = $(this).parents('li.history__item');
		
		var history_list = (document.querySelectorAll("ul.history__list"))[0];
		history_list.insertBefore(parent_li[0], history_list.firstChild);
		if (checkWindow() === 'isPC') {
			// 各ul内のli数を確認し、9以上の場合は最後のliを次ulの最初へ移動
			organizeHistoryListPC();
		}else {
			organizeHistoryListSP();
		}
		setHistoryClickEvent();
	});
	
	$(".historyFixed__anchor").on('click', function(){
		if (checkWindow() === 'isPC') {
			var parent_li = $(this).parents('li.historyFixed__item');
			var parent_ul = $(this).parents('ul.historyFixed__list');
			var historyFixed__list = (document.querySelectorAll("ul.historyFixed__list"))[0];
			historyFixed__list.insertBefore(parent_li[0], historyFixed__list.firstChild);
			setHistoryClickEvent();
		}
	});
	
	// ホイールクリックイベントによってクリックイベントを発火させる
	$(".history__anchor").on('mouseup',function(){
		if(event.button == 1){
			$(this).trigger('click');
			window.open($(this).attr('href'), '_blank');
		}
	});
	$(".historyFixed__anchor").on('mouseup',function(){
		if(event.button == 1){
			$(this).trigger('click');
			window.open($(this).attr('href'), '_blank');
		}
	});
}

organizeHistoryListPC = function(){
	// 各ul内のli数を確認し、9以上の場合は最後のliを次ulの最初へ移動
	var i = 0;
	while(true) {
		var tmp_ul = $("ul.history__list[data-slick-index=" + i + "]")
		if(tmp_ul.length == 0) {
			break;
		}
		if(tmp_ul.children('li.history__item').length > 8) {
			var last_child_li = tmp_ul.children('li.history__item').last();
			var next_ul = $("ul.history__list[data-slick-index=" + (i + 1)  + "]");
			
			last_child_li.clone().prependTo(next_ul);
			last_child_li.remove();
		}
		i++;
	}
}

organizeHistoryListSP = function() {
	var show_count = $(".history__item:not(.is-hidden)").length;
	if(show_count == 0) {
		show_count = 1;
	}
	var max_show_count = Math.ceil(show_count / 5) * 5 ;
	for(var i = 1 ; i <= $(".history__item").length ; i++) {
		if(i <= max_show_count) {
			$($(".history__item")[i - 1]).removeClass('is-hidden');
		}else {
			$($(".history__item")[i - 1]).addClass('is-hidden');
		}
	}
}

observeHistory = function() {
	observe_time = localStorage.getItem('history_time');
	var max_count = 100;
	var now_count = 0;
	// ※IEで別タブのlocalStorage変更を検知するため、イベントリスナーを空実装
	window.onstorage = function(e) {}
	
	var timer = setInterval(function(){
		var history_time = localStorage.getItem('history_time');
		if(observe_time != history_time) {
			var show_count = $(".history__item:not(.is-hidden)").length;
			if(show_count == 0) {
				show_count = 1;
			}
			history_show_count = Math.ceil(show_count / 5) * 5 ;
			getHistoryHeader();
			clearInterval(timer);
		}
		now_count++;
		if(now_count >= max_count) {
			clearInterval(timer);
		}
	},100)
}

$(function(){
	$(document).on("click", ".jobOffer__anchor", function() {
		observeHistory();
	});

	$(document).on("mouseup", ".jobOffer__anchor", function() {
		if(event.button == 1){
			$(this).trigger("click");
		}
	});
});
