/*/////////////////////////////////////////////////////////////////////////////////////////////////
	User Guide
		search_result JavaScript
 Modified : 2017-03-03
/////////////////////////////////////////////////////////////////////////////////////////////////*/


/* global textData, opkey_index, _ua */

$(function(){
	
	// 1ページあたりの結果数
	var max = 50;
	// 検索タイプ
	var searchType = 'and';//(and|or)
	
	
	
	
	$('#navi').on('click', 'span', function(){
		var p = $(this).attr('page');
		window.location =  searchAction($('#opkeySearch form').attr('action')) +"?k="+encodeURIComponent(_ua._get['k'])+'&p='+p;
	});
	
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	var start = new Date().getTime();
	var datalist = [];
	var datalistTit = [];
	//var findreg = [];
	var bolderlist = [];
	//var boldreg;
	var releatekey = [];
	var searchTime;
	var st = gid("sCount");
	var re = gid("results");
	var nv = gid("navi");
	//
	var andSearch = searchType==='and';
	
	//----------------------------------------------------------
	
	
	
	var page = _ua._get['p'] || 1 ;
	
	
	
	//フィルタにより検索データ作成
	for(var i=0,len=opkey_index.length; i<len; i++){
		datalist[datalist.length] = ufrm(opkey_index[i].title);
	}
	
	//ユーザーフォント削除
	function ufrm(d){
		return d.replace(/%#symbol-([^#]+?)#%/g, '');
	}
	
	//検索して表示する。
	function do_find(v){//**************************************
		if(this.lastquery == v){return;}
		this.lastquery = v;
		var re = find(v);
		pagenavi(re);
		view(re,page);
	}
	
	//ID取得
	function gid(id){//**************************************
		return document.getElementById(id);
	}
	
	//検索キー作成
	function createfindreg(v){//**************************************
		var findregs = [];
		v = v.replace(/\s|[　]+/g," ");
		v.replace(/[\[\]{}()*+?\\^$|#;\.]/g, "\\$&");
		
		key = v.split(" ");
		for(var i=0,len=key.length; i<len; i++){
			if(key[i]==""){key.splice(i,1);}
		}
		for(var i=0,len=key.length; i<len; i++){
			var findreg = [];
			key[i] = key[i].replace(/\./g,"\\.");
			try{
				findreg[findreg.length]=new RegExp("(" + key[i] + ")", 'i');
			}catch(e){
				
			}
			findregs[findregs.length]=findreg;
		}
		
		return findregs;
	}
	
	
	//findregからor検索Reg作成 （現在は無意味）
	function createboldreg(findreg){//**************************************
		strreg = "";
		for(i=0,len=findreg.length; i<len; i++){
			tmpreg = findreg[i].source;
			tmpreg = tmpreg.substring(1,tmpreg.length-1);
			strreg = strreg + tmpreg + "|";
		}
		strreg = "(" + strreg.substring(0,strreg.length-1) + ")";
		
		boldreg = new RegExp(strreg, 'i');
		return boldreg;
	}

	//検索処理
	function find(v){//**************************************
		//検索結果はkeyをこの配列から削除する。
		query = v;
		if(!v){return [];}
		//start = new Date().getTime();
		
		//検索キー作成 /(aaa)/i,/(bbb)/i
		var findregs = createfindreg(query);
		
		var result = [];
		//重複さけるための配列
		idList= [];
		
		for(h=0,len1=findregs.length; h<len1; h++){
			var findreg = findregs[h];
			boldreg = createboldreg(findreg);
			
			if(andSearch && h>0){
				var result2=[];
				for(var i=0,len2=result.length; i<len2; i++){
					for(j=0,len3=findreg.length; j<len3; j++){
						tHit = result[i][0] || findreg[j].test(datalistTit[result[i][1]]);
						res = findreg[j].test(datalist[result[i][1]]);
						if(!res){break;}
					}
					if(res){
						if(jQuery.inArray(boldreg,bolderlist)==-1) bolderlist[bolderlist.length]=boldreg;
						result2.push([tHit,result[i][1]]);
					}
				}
			}else{
				for(var i=0,len2=datalist.length; i<len2; i++){
					res = false;
					tHit = false;
					s = datalist[i];
					if(jQuery.inArray(i,idList)==-1){
						for(var j=0,len3=findreg.length; j<len3; j++){
							tHit = tHit || findreg[j].test(datalistTit[i]);
							res = findreg[j].test(s);
							if(!res){break;}
						}
						if(res){
							idList[idList.length]=i;
							if(jQuery.inArray(boldreg,bolderlist)==-1) bolderlist[bolderlist.length]=boldreg;
							result.push([tHit,i]);
						}
					}
				}
			}
			result = (result2) ? result2 : result ;
		}
		
		var r1=[],r2=[];
		for(var i=0,len=result.length; i<len; i++){
			if(result[i][0]){
				r1[r1.length]=result[i][1];
			}else{
				r2[r2.length]=result[i][1];
			}
		}
		var result = r1.concat(r2);
		
		//var end = new Date().getTime();
		//searchTime = (end-start) / 1000;
		
		return result;
	}
	
	
	//ユーザーフォントを画像へ変換（opkey search only）
	function ufconvert(v){
		return v.replace(/%#symbol-([^#]+?)#%/g, '<span class="kmsymbol" data-charcode="$1"></span>');
	}
	
	
	//ページナビ作成
	function pagenavi(result){//**************************************
		var len = result.length;
		var ct = Math.ceil(len/max);
		var buf = [];
		for(var i=1; i<=ct; i++){
			buf[buf.length]='<span page="'+i+'">'+i+'</span>';
		}
		nv.innerHTML = buf.join("");
		sw(page);
	}
	
	//ページナビの現表示ページにクラス追加
	function sw(t){//**************************************
		var span = nv.getElementsByTagName("span");
		for(var i=0,len=span.length; i<len; i++){
			span[i].className = (i==t-1)?"selected":"";
		}
	}
	
	//検索結果を表示
	function view(result,page){//**************************************
		offset = page || 1;
		if(!result){
			result = this.last;
		}else{
			this.last = result;
		}
		var r = result;
		var buf = [];
		var count = 0;
		
		
		var fi = (offset-1)*max;
		for(var i=fi,len1=r.length; i<len1; i++){
			count++;
			if(count > max){break}
			var num = r[i];
			var da = opkey_index[num];
			buf.push(
				'<li><a href="', da.file ,'">', ufconvert(da.title) || textData.searchUnknoun ,'<\/a><\/li>'
			);
		}
		
		
		var cost = Math.min(fi+1, result.length);
		var coen = Math.min(fi+max, result.length);
		
		var end = new Date().getTime();
		searchTime = (end-start) / 1000;
		
		var countsArr = [
			result.length,
			cost,
			coen
		];
		var srCount = textData.searchCounts + ' (' + searchTime + ' '+textData.searchCounts3+')';
		srCount = srCount.replace(/#(\d+)#/g, function(hitAll,$1,index,strAll){
			var r = '0';
			if(countsArr[$1]){
				r = countsArr[$1];
			}
			return r;
		});
		
		st.innerHTML = (result.length==1)? srCount.replace('items', 'item') : srCount ;
		re.innerHTML = '<ul>' + buf.join("") + '</ul>';
		$('html,body').scrollTop(0);
	}
	
	
	
	//////////////////////////////
	var getKey = (_ua._get['k']) ? _ua._get['k'].replace(/\s|[　]+/g," ") : '';
	if(getKey){
		$("#op_searchKey").val(getKey).addClass("keyIn");
		do_find(getKey);//検索命令！
	}
	///////////////////////////////
	
	
});
