var zyutugohash = {};
var findbox_write="";


// genrelist[内部num] = "表示順:表示項目"
var genrelist = [];
genrelist[0] = "0:-";
genrelist[1] = "1:プログラムのロード・セーブ";
genrelist[2] = "2:入出力ストリームのオープン・クローズ";
genrelist[3] = "3:登録プログラムの出力";
genrelist[4] = "4:項(term)の入出力";
genrelist[5] = "5:一文字入出力";
genrelist[6] = "6:コンソール専用一文字入出力";
genrelist[7] = "7:コンソール画面の制御";
genrelist[8] = "8:ランダムファイル操作述語";
genrelist[9] = "9:その他のファイル操作述語";
genrelist[10] = "10:算術、関数の評価";
genrelist[11] = "11:算術演算子";
genrelist[12] = "12:算術関数";
genrelist[13] = "13:内部状態参照関数";
genrelist[14] = "14:数値比較";
genrelist[15] = "15:項の比較";
genrelist[16] = "16:プログラムの変更・取り出し";
genrelist[17] = "17:メタ述語";
genrelist[18] = "18:型チェック";
genrelist[19] = "19:型変換・項操作";
genrelist[20] = "20:実行制御";
genrelist[21] = "21:処理系動作制御";
genrelist[22] = "22:エラーハンドリング";
genrelist[23] = "23:モード切り替え・宣言";
genrelist[24] = "24:デバッグ関係の述語";
genrelist[25] = "25:OS関連述語・Windows API Call述語";
genrelist[26] = "39:拡張機能述語(9) OLEオートメーション";
genrelist[27] = "40:拡張機能述語(10) 内蔵エディタ(AzEdit) ";
genrelist[28] = "26:アレイ(配列)操作";
genrelist[29] = "27:ニューラルネットワーク述語①（シングルプロセス）";
genrelist[30] = "28:その他の述語";
genrelist[31] = "41:拡張機能述語(11) iso_pred,setof,utility,manual";
genrelist[32] = "32:拡張機能述語(3) CGIユーティリティ";
genrelist[33] = "38:拡張機能述語(8) ODBC";
genrelist[34] = "33:拡張機能述語(4) 鬼車";
genrelist[35] = "34:拡張機能述語(5) Mecab/Cabocha";
genrelist[36] = "";
genrelist[37] = "31:拡張機能述語(2) 並列処理支援機構";
genrelist[38] = "36:拡張機能述語(6) ソケット";
genrelist[39] = "37:拡張機能述語(7) Redisインターフェース";
genrelist[40] = "30:拡張機能述語(1) 制約論理";
genrelist[41] = "29:拡張機能述語";

for (var i in azlist){ if((azlist[i]["used"]== "FALSE")||(azlist[i]["used"]== "false")) azlist.splice(i, 1); }
for (var i in azlist){var genreid=azlist[i]["genre"]; if (genreid) azlist[i]["genre2"]=parseInt(genrelist[genreid].split(":")[0]);}


function init(){
	// テキストボックス autocomplete
	var dataList = $("#searchlist");
	dataList.empty();
	for (var i in azlist){dataList.append($("<option></option>").attr("value", azlist[i]["name"].html2specialword()));}
	for (var i in azlist){
		var arr=azlist[i]["name"].split("<br>");
		for (var j in arr) zyutugohash[arr[j]]=azlist[i]["id"];
	}
	bool = true;
	
	if (location.href.indexOf("_abc.html")!=-1) bool = false;
	var url = location.href;
	if (url.indexOf(".html?")){url=url.replace(".html?",".html#");}
	if (url.indexOf(".html%23")){url=url.replace(".html%23",".html#");}
	if (url.indexOf(".html#")!=-1){
		var str = url.substr(url.indexOf(".html#")+6,100);
		findbox_write=decodeURIComponent(str);
	}

	//$("#title").html((bool)? "AZ-Prolog 機能別述語リファレンス":"AZ-Prolog 述語索引");

	// 2014.11.27 Add by H.O.  ----- [ Start ] -----
	// ジャンルリスト作成
	if(location.href.indexOf("_genre.html") >= 0) {
		var genre_id, genre_name;
		var genre_data = [];
		// ジャンルリストよりIDとジャンル名を取得する
		for(var i in genrelist) {
			genre_id = genrelist[i].split(":")[0];
			genre_name = genrelist[i].split(":")[1];
			if(genre_name == "-") genre_name = "全て";
			if(genre_id != "") genre_data[genre_id] = genre_name;
		}
		// ジャンル名をリスト表示する
		for(var j in genre_data) {
			$("#genre_list").append(new Option(genre_data[j], j));
		}
	}
	// 2014.11.27 Add by H.O.  ----- [ End   ] -----
	
	// 索引一覧
	if (findbox_write){zyutugoonly_write()}
	else {if (bool==false){ sakuin_write();}else{ kinoubetu_write();}}
}

// 2014.11.28 Add by H.O.  ----- [ Start ] -----
function change_genre_list(id) {
	$("#res_body").find("tr").remove();
	var genre_id;
	var genre_first = 0;
	var genre_before = 0;

	genre_id = id;
	//genre_id = genrelist[id].split(":")[0];

	// 全ジャンルが指定された場合
	if(id == 0) {
		zyutugo_tablewrite(azlist,false,true);
		return;
	}

	// 特定ジャンルが指定された場合
	for(var i in azlist) {
		var hash = azlist[i];

		if(hash == null) continue;
		if((hash.used == "false") || (hash.used == false)) continue;
		if(hash["name"] == "") continue;
		var arr = [];

		// 指定されたジャンルIDと同一の述語データを表示する
		//if(hash["genre"] == genre_id) {
		if(genrelist[hash["genre"]].split(":")[0] == genre_id) {
			arr.push('<tr id="zyutugo_' + hash.id + '" style="page-break-before:always;">');
			arr.push('<td bgcolor="#FFFFFF" onclick=' + "'checkExpand("+hash.id+")'" + '><a><img src="../images/arrow.png" width="6" height="10" alt="開く" class="arrow" id="image_'+hash.id+'">' + hash["name"].specialword2html()+'</a></td>');
			if(hash["text"].split("。")[0].replace(/\<br\>/g,"") != "") arr.push('<td bgcolor="#FFFFFF">'+ hash["text"].split("。")[0].specialword2html().replace(/\<br\>/g,"") + '。</td>');
			else arr.push('<td bgcolor="#FFFFFF">' + hash["text"].split("。")[0].specialword2html().replace(/\<br\>/g,"") + '</td>');

			arr.push('<td bgcolor="#FFFFFF">');
			arr.push((hash["common"].match("ISO"))? '<span class="iso">ISO</span>':"");
			arr.push((hash["common"].match("Win"))? ' <span class="win">for Windows</span>':"");
			arr.push((hash["common"].match("Linux"))? ' <span class="linux">for Linux</span>':"");
			arr.push('</td>');
			arr.push('</tr>');
		
			arr.push('<tr id="trzyutugo_' + hash.id + '" style="display:none">');
			arr.push('<td colspan=3>');
			arr.push('<div class="Search">');

			if(genrelist[hash["genre"]] != "") {
				g_name = genrelist[hash["genre"]].split(":")[1];
				arr.push('  <h5>' + '<a href="javascript:void(0)" onclick="genre_window(' + id + ');">' + g_name + '</a></p><br>');
			}
			if(hash["name"] != "") arr.push('  <h5>【述語】 </h5><p> ' + hash["name"].specialword2html() + ' </p><br>');
			if(hash["format"] != "") arr.push('  <h5>【書式】 </h5><p> ' + hash["format"].specialword2html() + ' </p><br>');
			if(hash["argument"] != "") arr.push('  <h5>【引数】 </h5><p>' + hash["argument"].html2specialword() + '</p><br>');

			var line = [];
			var a = hash["incident"].split("<br>");
			for(var j in a) {
				if(a[j] == "") continue;
				var ar = a[j].split("：");
				if(ar.length == 1) {
					if(zyutugohash[ar[0]] != null) line.push('<a href="javascript:incident_write(' + "'incident_" + hash["id"] + "','" + ar[0].replace("\\","\\\\") + "'" + ')">' + ar[0].specialword2html() + '</a>');
					else line.push(a[j].specialword2html());
				}
				else if(ar.length == 2) {
					if(zyutugohash[ar[0]] != null) line.push('<a href="javascript:incident_write('+"'incident_" + hash["id"] + "','" + ar[0].replace("\\","\\\\") + "'" + ')">' + ar[0].specialword2html() + '</a>' + " (" + ar[1].specialword2html() + ")");
					else line.push(a[j].specialword2html());
				}
			}

			if(hash["text"] != "") arr.push('  <h5>【説明】 </h5><p>' + hash["text"].html2specialword() + '<br></p><br>');
			if(hash["incident"] != "") arr.push('  <h5>【関連述語】 </h5><p>' + line.join(" , ") + '</p><br><div id="incident_' + hash.id + '"></div>');
			if(hash["sample"] != "") arr.push('  <h5>【実行例】 </h5><pre class="code">' + hash["sample"].html2specialword() + '</pre>');

			arr.push('</div>');
			arr.push('</td>');
			arr.push('</tr>');
			$("#res_body").append(arr.join(""));
			//checkExpand(hash.id);
		}
	}
}
// 2014.11.28 Add by H.O.  ----- [ End   ] -----

function zyutugoonly_write(){
	$("#searchbox").val(findbox_write);
	finddata(findbox_write,true,'all');
}



function checkExpand(id) {
	var elm = document.getElementById("trzyutugo_"+id);
	if((elm)&&(elm.style)){
		elm.style.display = (elm.style.display=="none")? "" : "none"
		arrow_change(id,(elm.style.display=="")? true:false);
	}
}

function arrow_change(id,bool){
	var elm = document.getElementById("image_"+id);
	if((elm)&&(elm.style)){
		elm.src = (bool)? "../images/arrow_after.png":"../images/arrow.png"
		elm.width = (bool)? 10:6;
		elm.height = (bool)? 6:10;
	}
}

String.prototype.indexOfCnt = function(word,bool){
	bool = (bool==null)? false:bool;
	var s = this.toString();
	var cnt=0;
	if (bool){word=word.toUpperCase(); s=s.toUpperCase();}
	return s.split(word).length -1;
};


function finddata(word){
	$("#res_body").find("tr").remove();
	if (word == ""){
		if (location.href.indexOf("_abc.html")==-1) kinoubetu_write();
		return;
	}
	var hashs = [];
	word = word.replace(/　/g," ");
	var arr = word.split(" ");
	var res  = [];
	if (word!="printall"){
		azlist.sort(function(a, b) {return a["name"] > b["name"] ? 1 : -1;});
		for (var i in azlist){
			var bool ={};
			var per  = 0;
			for (var j in arr){
				bool[j] = false;
				var cnt = azlist[i]["name"].indexOfCnt(arr[j],true);
				if (cnt>0){ per += 10*cnt/azlist[i]["name"].replace(/\ .+/,"").length; bool[j]=true;}
				cnt = azlist[i]["text"].split("。")[0].indexOfCnt(arr[j],true);
				if (cnt>0){per += 3*cnt/azlist[i]["text"].split("。")[0].length;bool[j]=true;}
				cnt = azlist[i]["text"].indexOfCnt(arr[j],true);
				if (cnt>0){per += cnt/azlist[i]["text"].length;bool[j]=true;}
			}

			var hash = azlist[i];
			hash.percent = per;
			var b = true;
			for (var j in bool){if(!bool[j]) b=false;}
			if (b) hashs.push(hash);
		}

		hashs.sort(function(a, b) {return a["percent"] < b["percent"] ? 1 : -1;});
		zyutugo_tablewrite(hashs,false,false);
		$('#highlight-plugin').removeHighlight();
		for (var j in arr) if(arr[j]!="") $('#highlight-plugin').highlight(arr[j]);
		if (findbox_write.indexOf("/")>-1){
			checkExpand(hashs[0].id);
		}
		findbox_write="";
	} else {
		azlist.sort(function(a, b) {return a["name"] > b["name"] ? 1 : -1;});
		zyutugo_tablewrite(azlist,true,false);
	}
}

function sakuinfind(word){
	$("#searchbox").val("");
	if (word=="記号") word = "\\W";
	else if (word=="全て") word = ".*";

	var re = new RegExp("^"+word,"i");
	azlist.sort(function(a, b) {return a["name"] > b["name"] ? 1 : -1;});
	var arr=[];
	for (var i in azlist){ if (azlist[i]["name"].match(re)) arr.push(azlist[i]);}
	zyutugo_tablewrite(arr,true,false);
}

function kinoubetu_write(){
	for (var i in azlist){if(!azlist[i]["genre2"]) azlist[i]["genre2"] = genrelist.length;}
	azlist.sort(function(a, b) {
		if (parseInt(a["genre2"]) < parseInt(b["genre2"]) ) return -1;
		if (parseInt(a["genre2"]) > parseInt(b["genre2"]) ) return 1;
		if (a["name"] < b["name"]) return -1;
		if (a["name"] > b["name"]) return 1;
		return 0;
	});
	zyutugo_tablewrite(azlist,false,true);
}

function zyutugo_tablewrite(hashs,expand,bool){
	$("#res_body").find("tr").remove();
	var genre_before = 0;
	for (var i in hashs){
		var hash = hashs[i];
		if (hash==null) continue;
		if ((hash.used=="false")||(hash.used==false)) continue;
		if (hash["name"]=="") continue;
		var arr = [];
		
		if (bool){
			if (genre_before != hash["genre"]){
				arr.push('<tr><th colspan="3" class="header"><strong>'+genrelist[hash["genre"]].split(":")[1]+'</strong></th></tr>');
				genre_before = hash["genre"];
			}
		}
		arr.push('<tr id="zyutugo_'+hash.id+'" style="page-break-before:always;">');
		arr.push('<td bgcolor="#FFFFFF" onclick='+"'checkExpand("+hash.id+")'"+'><a><img src="../images/arrow.png" width="6" height="10" alt="開く" class="arrow" id="image_'+hash.id+'">'+hash["name"].specialword2html()+'</a></td>');
		if (hash["text"].split("。")[0].replace(/\<br\>/g,"")!="") arr.push('<td bgcolor="#FFFFFF">'+hash["text"].split("。")[0].specialword2html().replace(/\<br\>/g,"")+'。</td>');
		else arr.push('<td bgcolor="#FFFFFF">'+hash["text"].split("。")[0].specialword2html().replace(/\<br\>/g,"")+'</td>');
		arr.push('<td bgcolor="#FFFFFF">');
		arr.push((hash["common"].match("ISO"))? '<span class="iso">ISO</span>':"");
		arr.push((hash["common"].match("Win"))? ' <span class="win">for Windows</span>':"");
		arr.push((hash["common"].match("Linux"))? ' <span class="linux">for Linux</span>':"");
		arr.push('</td>');
		arr.push('</tr>');
		
		arr.push('<tr id="trzyutugo_'+hash.id+'" style="display:none">');
		arr.push('<td colspan=3>');
		arr.push('<div class="Search">');

		// 2014.11.25 Add by H.O.  ----- [ Start ] -----
		if(genrelist[hash["genre"]] != "") {
			g_id   = genrelist[hash["genre"]].split(":")[0];
			g_name = genrelist[hash["genre"]].split(":")[1];
			arr.push('  <h5>' + '<a href="javascript:void(0)" onclick="genre_window(' + g_id + ');">' + g_name + '</a></p><br>');

		}
		// 2014.11.25 Add by H.O.  ----- [ End   ] -----
		if (hash["name"]!="")		arr.push('  <h5>【述語】 </h5><p> '+hash["name"].specialword2html()+' </p><br>');
		if (hash["format"]!="")		arr.push('  <h5>【書式】 </h5><p> '+hash["format"].specialword2html()+' </p><br>');
		if (hash["argument"]!="")	arr.push('  <h5>【引数】 </h5><p>'+hash["argument"].html2specialword()+'</p><br>');

		var line = [];
		var a = hash["incident"].split("<br>");
		for (var i in a){
			if (a[i]=="") continue;
			var ar = a[i].split("：");
			if (ar.length==1){
				if(zyutugohash[ar[0]]!=null) line.push('<a href="javascript:incident_write('+"'incident_"+hash["id"]+"','"+ar[0].replace("\\","\\\\")+"'"+')">' + ar[0].specialword2html() + '</a>');
				else line.push(a[i].specialword2html());
			} else if (ar.length==2){
				if(zyutugohash[ar[0]]!=null) line.push('<a href="javascript:incident_write('+"'incident_"+hash["id"]+"','"+ar[0].replace("\\","\\\\")+"'"+')">' + ar[0].specialword2html() + '</a>' + " (" + ar[1].specialword2html() + ")");
				else line.push(a[i].specialword2html());
			}
		}
		if (hash["text"]!="") 		arr.push('  <h5>【説明】 </h5><p>'+hash["text"].html2specialword()+'<br></p><br>');
		if (hash["incident"]!="")	arr.push('  <h5>【関連述語】 </h5><p>'+line.join(" , ")+'</p><br><div id="incident_'+hash.id+'"></div>');
		if (hash["sample"]!="")		arr.push('  <h5>【実行例】 </h5><pre class="code">'+hash["sample"].html2specialword()+'</pre>');

		arr.push('</div>');
		arr.push('</td>');
		arr.push('</tr>');
		$("#res_body").append(arr.join(""));
		//$("#restable").find('tbody').append(arr.join(""));
		if (expand) checkExpand(hash.id);
	}
}
function incident_close(id){$("#"+id).html("");}
function incident_write(id,name){
	var hash = {};
	for (var i in azlist){
		var arr = azlist[i]["name"].split("<br>");
		for(var j in arr) if (arr[j]==name) hash=azlist[i];
	}
	
	var list = [];
	list.push('<table class="table">');
	list.push('<tr>');
	list.push('<th width="19%" onclick='+"'"+'incident_close("'+id+'")'+"'"+'>'+hash["name"].specialword2html()+'</th>');
	list.push('<td width="45%"><PRE>'+hash["text"].split("。")[0].specialword2html().replace(/\<br\>/g,"")+'</PRE></td>');
	list.push('<td width="33%">');
	list.push((hash["common"].match("ISO"))? '<span class="iso">ISO</span>':"");
	list.push((hash["common"].match("Win"))? ' <span class="win">for Windows</span>':"");
	list.push((hash["common"].match("Linux"))? ' <span class="linux">for Linux</span>':"");
	list.push('</td>');
	list.push('<td width="3%" class="close"><a href="javascript:incident_close('+"'"+id+"'"+')"><img src="../images/close.png" width="24" height="24" alt="閉じる" class="close"></a></td>');
	list.push('</tr>');

	var line = [];
	var a = hash["incident"].split("<br>");
	for (var i in a){
		if (a[i]=="") continue;
		var ar = a[i].split("：");
		if (ar.length==1){
			if(zyutugohash[ar[0]]!=null) line.push(ar[0].specialword2html());
			else line.push(a[i].specialword2html());
		} else if (ar.length==2){
			if(zyutugohash[ar[0]]!=null) line.push(ar[0].specialword2html() + " (" + ar[1].specialword2html() + ")");
			else line.push(a[i].specialword2html());
		}
	}

	list.push('<tr><td colspan="4"><div class="Search">');
	// 2014.11.25 Add by H.O.  ----- [ Start ] -----
	if (genrelist[hash["genre"]] != "") {
			g_id   = genrelist[hash["genre"]].split(":")[0];
			g_name = genrelist[hash["genre"]].split(":")[1];
			list.push('  <h5>' + '<a href="javascript:void(0)" onclick="genre_window(' + g_id + ');">' + g_name + '</a></p><br>');
	}
	// 2014.11.25 Add by H.O.  ----- [ End   ] -----
	if (hash["name"]!="") list.push(' <h5>【述語】</h5><p>'+hash["name"].specialword2html()+'</p><br>');
	if (hash["format"]!="") list.push(' <h5>【書式】</h5><p>'+hash["format"].specialword2html()+'</p><br>');
	if (hash["argument"]!="") list.push(' <h5>【引数】</h5><p>'+hash["argument"].html2specialword()+'</p><br>');
	if (hash["text"]!="") list.push(' <h5>【説明】</h5><p>'+hash["text"].html2specialword()+'</p><br>');
	list.push(' <h5>【関連述語】</h5><p>'+line.join(" , ")+'</p><br>');
	if (hash["sample"]!="") list.push(' <h5>【実行例】</h5><pre class="code">'+hash["sample"].html2specialword()+'</pre>');
	list.push('</div></tr></table>');
	$("#"+id).html(list.join("\n"));

}

function sakuin_write(){
	$("#searchbox").val("");
	arr = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","記号","全て"];
	var list=[];
	for (var i in arr){
		var bool = false;
		var word ="";
		if (arr[i]=="記号") word = "^\W";
		else if (arr[i]=="全て") word = ".*";
		else word = '^'+arr[i];
		re = new RegExp(word,"i");
		for (var j in azlist){if (azlist[j]["name"].match(re)) { bool = true; break; }}
		if (bool) list.push("[<a href='javascript:sakuinfind("+'"'+arr[i]+'"'+")'>"+arr[i]+"</a>] ");
		else list.push("["+arr[i]+"] ");
	}
	re = null;
	$("#sakuin").html(list.join("\n"));
}

// 2014.11.10 Add by H.O.  ----- [ Start ] -----
var subwin = null;
var jyutsugo_name;
var jyutsugo_id;

// 述語詳細表示ウィンドウを開設する
function jyutsugo_window(name,id) {
	jyutsugo_name = name;
	jyutsugo_id = id;
	subwin = null;
	jyutsugo_win_open();
}

// 述語詳細表示ウィンドウを新規に開設し、
// 該当述語の詳細説明表示を行う。
function jyutsugo_win_open() {
	if(!subwin) subwin = window.open("../reference/jutugo_abc.html");
	if(!subwin.dummy_function) {
		setTimeout(jyutsugo_win_open, 500);
		return;
 	}
	subwin.jyutsugo_name = jyutsugo_name;
	subwin.jyutsugo_id   = jyutsugo_id;
	subwin.$("#searchbox").val(jyutsugo_name);
	subwin.finddata(jyutsugo_name,true,'all');
	subwin.checkExpand(jyutsugo_id);
}

// ダミー関数
function dummy_function() {
	return;
}
// 2014.11.10 Add by H.O.  ----- [ End   ] -----

// 2014.11.28 Add by H.O.  ----- [ Start ] -----
var subwin2 = null;
var select_genre;
var select_genre_id;
var select_genre_name;

// ジャンル別熟語リファレンス表示ウィンドウを開設する
function genre_window(id) {
	select_genre = id;
	//select_genre_id = genrelist[id].split(":")[0];
	select_genre_id = id;
	//select_genre_name = genrelist[id].split(":")[1];
	// ジャンル名をリスト表示する
	for(var i in genrelist) {
		gid = genrelist[i].split(":")[0];
		if(gid == id) {
			select_genre_name = genrelist[i].split(":")[1];
			break;
		}
	}
	subwin2 = null;
	genre_win_open(id);
}

// ジャンル別熟語リファレンス表示ウィンドウを新規に開設し、
// 該当ジャンルの述語一覧表示を行う。
function genre_win_open() {
	if(!subwin2) subwin2 = window.open("../reference/jutugo_genre.html");
	if(!subwin2.dummy_function) {
		setTimeout(genre_win_open, 500);
		return;
 	}
	subwin2.select_genre_id = select_genre_id;
	subwin2.select_genre_name = select_genre_name;
	subwin2.$("#genre_list").val(select_genre_id);
	subwin2.$("#genre_list").filter(function(index){return $(this).text() === select_genre_name;}).prop('selected', true);
	subwin2.change_genre_list(select_genre);
	//subwin2.checkExpand(jyutsugo_id);
}

// 2014.11.28 Add by H.O.  ----- [ End   ] -----

String.prototype.specialword2html = function(){
	return this.toString().replace(/\<br\>/g, "\n").replace(/\\/g, '&yen;').replace(/\ /g, '&nbsp;').replace(/\"/g, '&quot;').replace(/\`/g, '&lsquo;').replace(/\'/g, '&rsquo;').replace(/\>/g, '&gt;').replace(/\</g, '&lt;').replace(/\n/g, '<br>').replace(/￥/g, '\\');
};
String.prototype.html2specialword = function(){
	return this.toString().replace(/\&yen\;/g, "\\").replace(/\&nbsp;/g," ").replace(/\&quot\;/g, "\"").replace(/\&lsquo\;/g, "\`").replace(/\&rsquo\;/g, "\'").replace(/\&gt\;/g, "\>").replace(/\&lt\;/g, "\<");
};

