// 複数検索ワード区切り文字
var MatchWordDlm = '`';

$(function(){
	var urlparams = document.location.search.substring(1);

	if (urlparams) {
		var searchvalues = '';
		var params = urlparams.split('&');

		for (var i = 0; i < params.length; i++) {
			var keyval = params[i].split('=');
			if (keyval[0] == 'search') {
				searchvalues = decodeURIComponent(keyval[1]);
				break;
			}
		}

		if (searchvalues) {
			var swords = searchvalues.split(MatchWordDlm);

			for (var i = 0; i < swords.length; i++) {
				if (swords[i].length > 0) {
					highlight($('.content').get(0), swords[i]);
				}
			}
		}
	}
});

function highlight(element, word) {
	var escape = word;
	escape = escape.replace('\\', '\\\\');
	escape = escape.replace('*', '\\*');
	escape = escape.replace('+', '\\+');
	escape = escape.replace('.', '\\.');
	escape = escape.replace('?', '\\?');
	escape = escape.replace('{', '\\{');
	escape = escape.replace('}', '\\}');
	escape = escape.replace('(', '\\(');
	escape = escape.replace(')', '\\)');
	escape = escape.replace('[', '\\[');
	escape = escape.replace(']', '\\]');
	escape = escape.replace('^', '\\^');
	escape = escape.replace('$', '\\$');
	escape = escape.replace('-', '\\-');
	escape = escape.replace('|', '\\|');
	escape = escape.replace('/', '\\/');

	for (var child = element.firstChild; child != null; child = next) {
		var next = child.nextSibling;

		if (child.nodeType == 3) {
			var value = child.nodeValue;

			while (value.includes(word)) {
				var parts = value.match(new RegExp("(.*?)(" + escape + ")(.*)"));

				if (parts[1] != '') {
					var text = document.createTextNode(parts[1]);
					element.insertBefore(text, child);
				}

				var font = document.createElement('font');
				font.setAttribute('color', '#FF0000');
				element.insertBefore(font, child);

				var b = document.createElement('b');
				b.textContent = parts[2];
				font.appendChild(b);

				value = parts[3];
			}

			if (value == "") {
				element.removeChild(child);
			} else {
				child.textContent = value;
			}
		} else if (child.nodeType == 1) {
			highlight(child, word);
		}
	}
}
