var insearch_config = {
	ajax_url: '/insearch/?act=search', 
	s_resulturl: 'https://www.pasona-ns.co.jp/search/result.html', 
	s_bar: 'none', 
	s_limit_result_title: '1', 
	s_limit_result_description: '1', 
	s_limit_result_block: '0', 
	s_limit_result_contents: '0', 
	s_paging: '1', 
	s_paging_unit: '20', 
	letters_search: 'サイト内検索', 
	text_progressing: '<p>検索結果を取得中...</p>', 
	text_summary: '<p>キーワード「$keywords」で $hits件のページが見つかりました。</p>', 
	text_paging: '<p>$start件目から $end件目までの検索結果を表示しています。</p>', 
	msg_errors: {
		server_error: '大変申し訳ありません。サーバ側でエラーが発生しました。', 
		maintaining: 'ただいま検索システムはメンテナンス中です。ご不便おかけしますが、後日またお試し下さい。', 
		frequent_search: '一定時間内の検索回数に制限を設けております。しばらく経ってからまたお試し下さい。', 
		empty_keywords: '検索キーワードに有効な文字がありません。', 
		short_keywords: '検索キーワードが短すぎます。', 
		long_keywords: '検索キーワードが長すぎます。'
	}, 
	msg_suspension: {
		by_processtime: '一定の所要時間を超えたため、検索処理は中断されました。', 
		by_hits: '一定の検索結果数に達したため、検索処理は中断されました。'
	}
}; 

if(typeof jQuery == "undefined")
{
	console.log("Please load jQuery beforehand"); 
	// return; // seems like it can't without a function 
}
let $ = jQuery; 
var insearch = {
	//-- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- 
	conf: null, 
	data: null, 
	$form: null, 
	$result: null, 

	//-- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- 
	init: function(config)
	{
		this.conf = config; 
		this.$form = $("#insearch-form").first(); 
		this.$result = $("#insearch-result").first(); 
		let params = this.getparam(); 

		if(
			this.$form.length == 0 && 
			this.conf.s_bar != "" &&
			this.conf.s_bar != "none")
		{
			let action = this.conf.s_resulturl; 
			let letters = this.conf.letters_search; 
			let position = this.conf.s_bar; 
			let keywords = "", state = "inactive"; 
			if('keywords' in params)
			{
				keywords = params['keywords']; 
				state = "active"; 
			}
			$(document.body).append(`
<div id="insearch-form" class="${position} ${state}">
	<form action="${action}" method="get">
		<nobr>
			<input type="text" name="keywords" value="${keywords}" /><button class="insearch-form-button"><i class="icon-search"/>${letters}</button>
		</nobr>
	</form>
</div>
`); 
			this.$form = $("#insearch-form").first(); 
			this.$form.on("submit", function(){
				if($(this).hasClass("active"))
					return true; 
				$(this).addClass("active").removeClass("inactive"); 
				$(this).find("input").focus(); 
				return false; 
			}); 
		}

		if('keywords' in params)
		{
			let path = location.protocol + "//" + location.host + location.pathname; 
			if(path == this.conf.s_resulturl)
			{
				if(this.$result.length == 0)
				{
					$(document.body).append('<div id="insearch-result"></div>'); 
					this.$result = $("#insearch-result").first(); 
				}
				this.$result.append(this.template(this.conf.text_progressing, params)); 
				let self = this; 
				this.ajax(
					this.conf.ajax_url, 
					{keywords: params['keywords']}, 
					function(data){self.data = data; self.show_result(data,0)}); 
			}
		}
	},

	//-- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- 
	show_result: function(data, page)
	{
		let self = insearch; 
		if(data == null)
			data = self.data; 
		let conf = self.conf; 
		let $result = self.$result; 
		if(typeof data.status == "undefined")
		{
			console.log("Ajax search request went wrong."); 
			return; 
		}
		$result.empty(); 
		if(data.status != "success")
		{
			console.log("Search request failed."); 
			let msg = "Sorry, unknown errors has occured."; 
			if(data.status in conf.msg_errors)
				msg = conf.msg_errors[data.status]; 
			$result.append(`<p>${msg}</p>`); 
			return; 
		}
		$result.append(self.template(self.conf.text_summary, data)); 
		if(data.suspension != null)
		{
			let msg = "Searching process has been suspended for some reason."; 
			if(data.suspension in conf.msg_suspension)
				msg = conf.msg_suspension[data.suspension]; 
			$result.append(`<p>${msg}</p>`); 
		}
		let result_items = data.result; 
		if(conf.s_paging == 1)
		{
			if(typeof page != "number")
				page = 1; 
			page = page < 1 ? 1 : page; 
			let unit = conf.s_paging_unit; 
			let paging = self.paging_index({
				items: result_items, 
				unit: unit, 
				page: page, 
				click: "insearch.show_result(null, $(this).data('value'));", 
				add_style: false}); 
			//console.log(paging); 
			if(typeof paging == "object")
			{
				result_items = paging.items; 
				$result.append(paging.source); 
				let vars = {
					start: unit*(page-1)+1, 
					end: unit*(page-1)+result_items.length}; 
				$result.append(self.template(self.conf.text_paging, vars)); 
			}
		}
		let $ul = $("<ul/>"); 
		for(var n in result_items){
			let page = result_items[n]; 
			let $a = $(`<a href="${page.link}"/>`); 
			if(conf.s_limit_result_title == 1)
				$a.append(`<h3>${page.title}</a></h3>`); 
			//if(conf.s_limit_result_path == 1)
			//	$a.append(`<p class="path">${page.path}</p>`); 
			if(conf.s_limit_result_description == 1)
				$a.append(`<p class="description">${page.description}</p>`); 
			if(conf.s_limit_result_block == 1)
				$a.append(`<p class="block">${page.block}</p>`); 
			if(conf.s_limit_result_contents == 1)
				$a.append(`<p class="contents">${page.contents}</p>`); 
			let $li = $("<li/>"); 
			$li.append($a); 
			$ul.append($li); 
		}
		$result.append($ul); 
	}, 

	//-- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- 
	dynamic_load: function(tag, prop)
	{
		var d = document; 
		if(typeof prop != "object")
			return; 
		if(typeof prop.id != "undefined")
			if(d.getElementById(prop.id))
				return;
		var elem = d.createElement(tag); 
		elem.async = true;
		for(var n in prop)
			elem[n] = prop[n]; 
		d.body.appendChild(elem); 
	}, 

	//-- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- 
	ajax: function(ajax_url, params, done)
	{
		jQuery.ajax({
			type: "POST",
			url: ajax_url,
			dataType: 'json', 
			data: params, 
			async: true
		})
		.done(done)
		.fail(function(data, text, thrown){
			console.log('Ajax transaction went wrong: '+text); 
		}); 
	}, 

	//-- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- 
	getparam: function(qs)
	{
		var param = new Array(); 
		if(! qs)
			qs = window.location.search; 
		if(! qs)
			return param; 
		if(qs.indexOf('?', 0) > -1)
			qs = qs.split('?', 2).pop(); 
		qs = qs.split('&'); 
		var pair; 
		while(pair = qs.shift())
		{
			pair = pair.split('=', 2); 
			if(pair[0] == "")
				continue; 
			pair[0] = decodeURIComponent(pair[0]); 
			pair[1] = typeof(pair[1]) == "undefined" ? true : decodeURIComponent(pair[1]); 
			param[pair[0]] = pair[1]; 
		}
		return param; 
	}, 

	//-- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- 
	template: function(target, data)
	{
		var type = typeof target; 
		var html = ""; 
		if(type == "object") 
			html = target.innerHTML; 
		else if(type == "string")
			if(target.match(/^[_a-z][-_a-z0-9]+$/)) // supposed to be an ID
				html = (target = document.getElementById(target)).innerHTML; 
			else
				html = target; 

		// to prevent browsers from loading a dummy $tplvar image 
		html = html.replace(/data-(src|href)=/g, "$1="); 
		//html = html.replace("javascript:void(0);//", ""); 

		var loop = 0; 
		while(html.match(/\$([_a-z0-9]+(\.[_a-z0-9]+)*)/))
		{
			var path = RegExp.$1; 
			var keys = path.split('.'); 
			var val = data; 
			for(var i in keys)
			{
				var key = keys[i]; 
				if(typeof val[key] == "undefined")
				{
					val = ""; 
					break; 
				}
				val = val[key]; 
			}
			html = html.replace('$'+path, val); 
			if(loop++ > 512) // just in case 
				break; 
		}

		if(typeof target == "object") 
		{
			target.innerHTML = html; 
			return target; 
		}
		return html; 
	}, 

	//-- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- 
	paging_index: function(args)
	{
		let log = false, ope = 'generating-paging-index'; 
		if(log) console.log(`[${ope}] has begun`); 

		let default_style = `
<style type="text/css">
ul.paging-index{ clear: both; margin: 1em auto; padding: 0.5em; list-style: none; text-align: left; }
ul.paging-index li{ display: inline-block; margin: 0; margin-right: 4pt; } 
ul.paging-index li a{ display: inline-block; min-width: 2em; padding: 2pt 4pt; border: solid 1px #333; border-radius: 2pt; cursor: pointer; font: bold 100%; font-family: "Meiryo UI", monospace; text-align: center; }
li.paging-index-current a{ color: white; background-color: #33f; }
li.paging-index-outbound a{ opacity: 0.3; }
</style>
`; 
		if(typeof args != 'object')
			return; 

		let key, keys = 'items total unit index_unit page href click add_style'.split(' '); 
		for(let i=0; i<keys.length; i++)
		{
			key = keys[i]; 
			if(typeof args[key] == 'undefined')
				args[key] = ""; 
		}
		keys = 'total unit index_unit page'.split(' '); 
		for(let i=0; i<keys.length; i++)
		{
			key = keys[i]; 
			if(args[key] == '')
				args[key] = 0; 
		}
//		while(key = keys.shift())
//			if(typeof args[key] == 'undefined')
//				args[key] = ''; 
//		while(key = keys.shift())
//			if(args[key] == '')
//				args[key] = 0; 

		let items = args.items; 
		let total = parseInt(args.total); 
		let unit = parseInt(args.unit); 
		let index_unit = parseInt(args.index_unit); 
		let page = parseInt(args.page); 
		let pages = null; 
		let href = args.href; 
		let click = args.click; 

		unit = unit <= 0 ? 10 : unit; 
		index_unit = index_unit <= 0 ? 6 : index_unit; 

		if(total == 0)
			if(Array.isArray(items))
				total = items.length; 
		if(total <= unit)
			return; 
		pages = Math.ceil(total / unit); 
		page = page == 0 ? 1 : (page > pages ? pages : page); 
		if(args.total == 0)
		{
			if(! Array.isArray(items))
				return; 
			if(items.length == 0)
				return; 
			let shown = unit*(page-1); 
			let rest = total-shown; 
			let len = rest < unit ? rest : unit; 
			items = items.slice(shown, shown+len); 
			//console.log({shown: shown, rest: rest, len: len, itemlen: items.length}); 
		}

		let left = 1; 
		for(; left <= page; left += index_unit)
			if(page >= left && page < left+index_unit)
				break; 
		if(log) console.log(`[${ope}] the left: ${left}`); 

		let ret = ''; 
		if(args.add_style)
			ret += default_style; 

		// make the li-generation as easy as possible 
		let li = function(v, text){
			let cls = 
				v == page ? ' class="paging-index-current"' : 
				v == 0 || v > pages ? ' class="paging-index-outbound"' : ""; 
			let ref = href; 
			if(ref != '')
			{
				ref = ref.replace('${page}', v); 
				ref = ` href="${ref}"`; 
			}
			let onclick = click != '' ? ` onclick="${click}"` : ''; 
			if(v == 0 || v > pages)
				onclick = ""; 
			text = !text ? v : text; 
			return `<li data-value="${v}"${onclick}${cls}><a${ref}>${text}</a></li>`; 
		}; 

		ret += '<ul class="paging-index">'; 
		ret += li(page-1, '&lt;'); 
		if(left > 1){
			ret += li(left-1); 
			ret += li(left, '...'); 
		}
		let i; 
		for(i=left; i<left+index_unit; i++){ 
			if(i > pages) 
				break;
			ret += li(i); 
		}
		if(i < pages){
			ret += li(left+index_unit, '...'); 
			ret += li(pages); 
		}
		ret += li(page+1, '&gt;'); 
		ret += '</ul>'; 
		return {source: ret, items: items}; 
	}
}; 
jQuery(function(){
	if(typeof insearch_config != "undefined")
		insearch.init(insearch_config);
}); 
