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

$(function(){
	
	// 1ページあたりの結果数
	var max = 10;
	// ヒットキーワードの前何文字表示
	var snippetStart = 30;
	// 説明の表示文字数
	var snippetLength = 80;
	// 検索タイプ
	var searchType = 'and';//(and|or)
	
	
	$('#ugtitle').text(textData.userGuide);
	$('#search label, #search2 label').text(textData.SearchTxt);
	$('#searchSubmit, #searchSubmit2').val(textData.SearchTxt);
	$('#NarrowDownBlock h4:first').text(textData.refine);
	$('#searchTi label').text(textData.titleOnry);
	$('#alluncheck').text(textData.cancelAll);
	$('#narrowSubmit').text(textData.confirmed);
	$('#crombsNavi span.frist a').text(textData.home);
	$('#crombsNavi span:last-child').text(textData.searchResult);
	
	var ct = [];
	for(var i=0,len=data.length; i<len; i++){
		var testid = data[i].File.replace(/(-|_).+$/,'');
		var tidre = new RegExp(testid);
		var testct = data[i].Path.replace(/>?[ ]*([^>]+) ?>[ ]*([^>]+).*$/,'$2');
		if(!tidre.test(ct)){
			ct.push([testid, testct]);
		}
	}
	
	for(var i=0,len=ct.length; i<len; i++){
		if(ct[i]){
			$('#searchCt').append('<span><input type="checkbox" id="scid'+i+'" value="'+ct[i][0]+'"/><label for="scid'+i+'">'+ct[i][1]+'</label></span>');
		}
	}
	
	
	$('#NarrowDown input:checkbox').change(function(){
		if(!$(this).is(':checked')){
			$(this).parent('span').removeClass('checked');
		}else{
			$(this).parent('span').addClass('checked');
		}
	});
	
	$('#alluncheck').hover(
		function(){ $(this).addClass('hover'); },
		function(){ $(this).removeClass('hover'); }
	).click(function(){
		$('#NarrowDown input').removeAttr('checked');
		$('#NarrowDown span').removeClass('checked');
		return false;
	});
	
	
	$('#searchSubmit2').after('<span id="searchBtn2"></span>');
	$('#searchBtn2, #narrowSubmit').hover(
		function(){ $(this).addClass('hover'); },
		function(){ $(this).removeClass('hover'); }
	).click(function(){ $('#search2 form').submit(); });
	$('#search2 form').submit(function(){
		var str = $('#searchKey2').val();
		if((str==textData.searchDefTxt)||str==""){
			return false;
		}else{
			var fil = [];
			if($('#t').is(':checked')){
				fil = '&t=1';
			}
			var sid = [];
			$('#searchCt input:checked').each(function(){
				sid[sid.length]=$(this).val();
			});
			if(sid){
				fil += '&scid=' + sid.join(',');
			}
			window.location =  searchAction($('#search2 form').attr('action')) +"?k="+encodeURIComponent(str) + fil;
			return false;
		}
	});
	$('#navi span').live('click', function(){
		var p = $(this).attr('page');
		window.location =  searchAction($('#search2 form').attr('action')) + "?k="+encodeURIComponent(get['k'])+'&t='+get['t']+'&scid='+get['scid']+'&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('=');
	}
	
	if(!!get['t']){
		$('#t').attr('checked','checked').parent('span').addClass('checked');
	}else{
		get['t'] = '';
	}
	if(!!get['scid']){
		for(var i=0,len=ct.length; i<len; i++){
			if(ct[i]){
				if(get['scid'].match(ct[i][0])){
					$('#scid'+i).attr('checked','checked').parent('span').addClass('checked');
				}
			}
		}
	}else{
		get['scid'] = '';
	}
	var page = get['p'] || 1 ;
	
	
	
	//フィルタにより検索データ作成
	for(var i=0,len=data.length; i<len; i++){
		var temp = data[i].File.replace(/(-|_).+$/,'');
		var reid = new RegExp(temp);
		if(!!get['t']){
			if(!!get['scid']){//----タイトルのみでカテゴリ指定
				if(reid.test(get['scid']+"")){
					datalist[datalist.length] = ufrm(data[i].Title);
				}else{
					datalist[datalist.length] = '';
				}
			}else{//----------------タイトルのみ
				datalist[datalist.length] = ufrm(data[i].Title);
			}
		}else if(!!get['scid']){//--本文含めカテゴリ指定
			if(reid.test(get['scid']+"")){
				datalist[datalist.length] = ufrm(data[i].Body + "　" + data[i].Title);
			}else{
				datalist[datalist.length] = '';
			}
		}else{//--------------------全内容
			datalist[datalist.length] = ufrm(data[i].Body + "　" + data[i].Title);
		}
		datalistTit[datalistTit.length] = ufrm(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){
				
			}
			//findreg.sort(regSort)
			findregs[findregs.length]=findreg;
		}
		
		//関連キーワード作成
		releateQuery(key);
		
		return findregs;
	}
	
	//ソート
	function regSort(a, b){//**************************************
		return (a.source.length < b.source.length) ? 1 : -1;
	}
	
	//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 releateQuery(keys){//**************************************
		for(var i in keys){
			/*var kv = keys[i];
			if(keyword_data[kv]){
				releatekey = releatekey.concat(keyword_data[kv]);
			}*/
			
			var a = keys[i].toLowerCase();
			for(var j in keyword_data){
				var b = j.toLowerCase();
				if(a == b){
					releatekey = releatekey.concat(keyword_data[j]);
				}
			}
		}
	}
	
	//検索処理
	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(var 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]){//tHit true
				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;
		//alert(result);
		return result;
	}
	
	//説明トリミング
	function snippet(body, boldreg){//**************************************
		var sniPoint = 0;
		//isMatch = body.match(boldreg);
		for(i=0,len=boldreg.length; i<len; i++){
			isMatch = boldreg[i].exec(body);
			if(isMatch) break;
		}
		if(isMatch){
			newPoint = isMatch.index;
			sniPoint = Math.max(sniPoint, newPoint);
		}
		var sb = sniPoint - snippetStart;
		var eb = sniPoint + snippetStart + snippetLength;
		var rb = body.substring(sb, eb);
		//rb = rb.replace(/^([\d@]+@@|@[\d@]+@@|@@[\d@]+@@|@@|@)/,'').replace(/(@@@\d[\d@]*@@|@@@\d[\d@]+@|@@@\d|@+)$/,'');
		//rb = "@@@@@@8@2@@@j";
		//console.log('----- ');
		if(rb.match(/(@@@)((\d@)+)(@@)/)){
			ufini = rb.match(/(@@@)((\d@)+)(@@)/gm).join('');
			var ufsb = Math.max((sb - Math.floor(ufini.length/2)), 0);
			var ufeb = eb + Math.floor(ufini.length/2);
			rb = body.substring(ufsb, ufeb);
			//console.log('before: '+rb);
			rb = rb.replace(/@@@@@@/gm,'@@@#####@@@');
			rb = rb.replace(/^([\d@]+@@|@[\d@]+@@|@@[\d@]+@@|@@|@)/,'').replace(/(@@@(\d@)+@|@@@(\d@)+|@@@(\d@)+\d|@+)$/,'');
			rb = rb.replace(/@@@#####@@@/gm,'@@@@@@');
			//console.log('after: '+rb);
		}else{
			//console.log('before: '+rb);
			rb = rb.replace(/^(@{0,2}(\d@)+@@|@{1,3})/,'').replace(/(@@@(\d@)+@|@@@(\d@)+|@@@(\d@)+\d|@+)$/,'');
			//console.log('after: '+rb);
		}
		if(sb > 0) rb = '<span class="conm">&#8230;</span>' + rb;
		if(body.length > eb) rb = rb + '<span class="conm">&#8230;</span>';
		return rb;
	}
	
	//ページナビ作成
	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];
			
			var v = boldkeyword(snippet(da.Body, bolderlist), bolderlist);
			v = v.replace(/(@@@)((\d@)+)(@@)/gm, '#####<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(/@/gm, '');
				}
			}
			v=v.join('');
			hrefURI = da.File.replace(/\.html/, '$&'+"?k="+encodeURIComponent(getKey));
			buf.push(
				'<div class="item">'
				,'<h3><a href="', hrefURI ,'">', boldkeyword(da.Title, bolderlist) || textData.searchUnknoun ,'</a></h3>'
				,'<div>', v ,'</div>'
				,'<div class="path">', da.Path ,'</div></div>'
			);
		}
		
		if(releatekey.length){
			var rurl = location.href;
			$('#relatedWords').remove();
			$('#sCount').after('<div id="relatedWords"><h4>'+ textData.searchRelatedHeader +'</h4></div>');
			for(var i=0,len=releatekey.length; i<len; i++){
				relatedUrl = location.href.replace(/(k\=)([^&]+)(\&|$)/, '$1' + releatekey[i] + '$3').replace(/(\&p=)([0-9]+)(\&|$)/,'');
				$('#relatedWords').append('<span class="relatedKey"><a href="' + relatedUrl + '">' + releatekey[i] + '</a></span>');
			}
		}
		
		
		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 = buf.join("");
		$('html,body').scrollTop(0);
	}
	
	//キーワードの強調処理
	function boldkeyword(body, boldregs){//**************************************
		var result = body, ststr="", enstr="";
		if(result.match(/^<span class="conm">&#8230;<\/span>/)){
			ststr = result.match(/^<span class="conm">&#8230;<\/span>/);
			result = result.replace(/^<span class="conm">&#8230;<\/span>/, '');
		}
		if(result.match(/<span class="conm">&#8230;<\/span>$/)){
			enstr = result.match(/<span class="conm">&#8230;<\/span>$/);
			result = result.replace(/<span class="conm">&#8230;<\/span>$/, '');
		}
		
		var inUF=false;
		if(uf = result.match(/(@@@)((\d@)+)(@@)/g)){
			inUF=true;
			result = result.split('@@@');
		}else{
			result=[result];
		}
		
		strreg = "";
		for(i=0,len=boldregs.length; i<len; i++){
			tmpreg = boldregs[i].source;
			tmpreg = tmpreg.substring(1,tmpreg.length-1);
			strreg = strreg + tmpreg + "|";
		}
		strreg = "(" + strreg.substring(0,strreg.length-1) + ")";
		strreg = strreg.replace(/</g, '&lt;').replace(/>/g, '&gt;');
		boldreg = new RegExp(strreg, 'igm');
		for(var i=0,len=result.length; i<len; i++){
			if(!/^(\d|\d(@\d)+)$/.test(result[i])){
				result[i] = result[i].replace(/</g, '&lt;').replace(/>/g, '&gt;');
				result[i] = result[i].replace(boldreg, '<span class="hitkey">$1</span>');
			}
		}
		result = (inUF)? result.join('@@@') : result[0] ;
		result = ststr + result + enstr;
		return result;
	}
	
	
	
	//////////////////////////////
	var getKey = (get['k']) ? get['k'].replace(/\s|[　]+/g," ") : '';
	if(getKey){
		$("#searchKey2").val(getKey).addClass("keyIn");
		$("#searchKey").val(getKey).addClass("keyIn");
		do_find(getKey);//検索命令！
	}
	///////////////////////////////

});

