/*/////////////////////////////////////////////////////////////////////////////////////////////////
	User Guide
		search_result JavaScript
 Modified : 2013-10-04
/////////////////////////////////////////////////////////////////////////////////////////////////*/


$(function(){
	
	// 1ページあたりの結果数
	var max = 50;
	// 検索タイプ
	var searchType = 'and';//(and|or)
	
	
	$('#ugtitle').text(textData.userGuide);
	$('#search label, #opkeySearch label').text(textData.SearchTxt);
	$('#searchSubmit, #op_searchSubmit').val(textData.SearchTxt);
	$('#crombsNavi span.frist a').text(textData.home);
	$('#crombsNavi span:last-child, h1').text(textData.opkeySearchTitle);
	
	
	
	
	$('#navi span').live('click', function(){
		var p = $(this).attr('page');
		window.location =  searchAction($('#opkeySearch form').attr('action')) +"?k="+encodeURIComponent(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 getdata = document.location.search.replace(/^\?/,'').split('&');
	getdata[0] = decodeURIComponent(getdata[0]);
	var get = [];
	for(var i=0,len=getdata.length; i<len; i++){
		temp = getdata[i].split('=');
		ak = temp[0];
		temp.shift();
		get[ak] = temp.join('=');
	}
	
	var page = get['p'] || 1 ;
	
	
	
	//フィルタにより検索データ作成
	for(var i=0,len=data.length; i<len; i++){
		datalist[datalist.length] = ufrm(data[i].Body + "　" + data[i].Title);
	}
	
	//ユーザーフォント削除
	function ufrm(d){
		return d.replace(/(@@@)((\d@)+)(@@)/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," ");
		var enpat = [
			["\\\\","\\\\"]
			,["\\\(","\\\("]
			,["\\\)","\\\)"]
			,["\\\[","\\\["]
			,["\\\]","\\\]"]
			,["\\\{","\\\{"]
			,["\\\}","\\\}"]
			,["\\\*","\\\*"]
			,["\\\+","\\\+"]
			,["\\\?","\\\?"]
			,["\\\$","\\\$"]
			,["\\\^","\\\^"]
			,["\\\|","\\\|"]
		];
		for(var i=0,len=enpat.length; i<len; i++){
			var re = new RegExp(enpat[i][0], "g");
			v = v.replace(re, enpat[i][1]);
		}
		//v = v.replace(/\\/g,"\\\\").replace(/\(/g,"\\(").replace(/\)/g,"\\)").replace(/\[/g,"\\[").replace(/\]/g,"\\]").replace(/\{/g,"\\{").replace(/\}/g,"\\}").replace(/\*/g,"\\*").replace(/\+/g,"\\+").replace(/\?/g,"\\?").replace(/\$/g,"\\$").replace(/\^/g,"\\^");
		key = v.split(" ");
		//key.sort();//
		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){
		v = v.replace(/(@@@)((\d@)+)(@@)/g, '#####<span class="kmsymbol"><img src="./img/userfonts/$2\.png" alt=""  /></span>#####').split('#####');
		for(vs=0,len2=v.length; vs<len2; vs++){
			if(v[vs].match(/^<span class="kmsymbol"><img [^>]+?><\/span>$/)){
				v[vs] = v[vs].replace(/@/g, '');
			}
		}
		return v.join('');
	}
	
	
	//ページナビ作成
	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 = data[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 srCount = '';
		if(srCountType==1){
			srCount = textData.searchCounts1 +'<span id="counts">' + result.length + '</span> '+ textData.searchCounts1_2 +' [ '+ cost +'-'+ coen +' / '+ result.length + textData.searchCounts2+' ]  (' + searchTime + ' '+textData.searchCounts3+')';
		}else{
			srCount = '<span id="counts">' + result.length + '</span> '+ textData.searchCounts1 +' [ '+ cost +'-'+ coen +' / '+ result.length + textData.searchCounts2+' ]  (' + searchTime + ' '+textData.searchCounts3+')';
		}
		
		st.innerHTML = (result.length==1)? srCount.replace('items', 'item') : srCount ;
		re.innerHTML = '<ul>' + buf.join("") + '</ul>';
		$('html,body').scrollTop(0);
	}
	
	
	
	//////////////////////////////
	var getKey = (get['k']) ? get['k'].replace(/\s|[　]+/g," ") : '';
	if(getKey){
		$("#op_searchKey").val(getKey).addClass("keyIn");
		do_find(getKey);//検索命令！
	}
	///////////////////////////////
	
	
});
