$(function(){

	$("#search_tab").change(function(){
		$("#keyword").focus();
	});

	$("#btn_search").click(function() {
		search();
		return false;
	});

	$("#keyword").keydown(function(e){
		if(e.which == 13){
			search();
		}
	});

	function search() {

		var keywordString = $("#keyword").val();
		keywordString = $.trim(keywordString);
		if (keywordString == "") {
			// noop
			return;
		}

		initSearchResluts();

		try {
			var resultObjects = execSearch(keywordString);
			if (resultObjects.length == 0) {
				$("#search .result_count .count").text(0);
				$("#search .search_results").html("");
				return;
			}
		
			// create search results structure.
			var resultsTags = createResultsTags(resultObjects);

			// insert search results tags
			$("#search .result_count .count").text(resultObjects.length);
			$("#search .search_results").html(resultsTags.clone().children());
		} catch(e) {
		}
	};

	function initSearchResluts() {
		$("#result_count>.count").text(0);
		$("#search_results").empty();
	}

	// The following 2 searches are executed.
	// [1] Search for title.
	// [2] Search for text.
	function execSearch(keywordString) {

		var resultObjects = [];

		// Search condition : [AND]
		var searchKeywordAnd = createRegexpAndString(keywordString);
		var regexpForSearch = new RegExp(searchKeywordAnd, 'g' + 'i');	// i: ignore case
		var searchKeywordOr = createRegexpOrString(keywordString);
		var regexpForHighlight = new RegExp(searchKeywordOr, 'g' + 'i');	// i: ignore case

		// [1] Search for title.
		// searchIndex: data/searchIndex.js
		$.each(searchIndex, function(index, indexItem) {

			// Search title.
			var result = indexItem.title.match(regexpForSearch);
			if (result == null) {
				// Not match
				return;
			}

			// Highlight title
			var searchResultTitle = createHighlightedTitle(indexItem.title, regexpForHighlight);
			if (searchResultTitle != "") {
				var resultObject = {};
				resultObject["id"] = indexItem.id;
				resultObject["title"] = searchResultTitle;
				// No body
				resultObject["detail"] = "";

				resultObjects.push(resultObject);
			}
		});

		// [2] Search for text.
		// searchIndex: data/searchIndex.js
		$.each(searchIndex, function(index, indexItem) {

			// Search text.
			var result = indexItem.text.match(regexpForSearch);
			if (result == null) {
				// Not match
				return;
			}

			// Highlight detail text
			var searchResultDetails = createHighlightedDetailList(indexItem.text, regexpForHighlight);
			if (searchResultDetails.length > 0) {
				var resultObject = {};
				resultObject["id"] = indexItem.id;
				resultObject["title"] = indexItem.title;
				// Use first item.
				resultObject["detail"] = searchResultDetails[0];

				resultObjects.push(resultObject);
			}
		});

		return resultObjects;
	}

	// Create search results structure.
	// <div class="search_results">
	function createResultsTags(resultObjects) {
		var resultsTags = $("<div>").addClass("search_results");

		$.each(resultObjects, function(index, result) {
			var resultTagItem = createResultItem(result.title, result.id + ".htm", result.detail);
			resultTagItem.appendTo(resultsTags);
		});

		return resultsTags;
	}

	// Create Highlighted title.
	// (Highlight 1st keyword.)
	//     xxxxxxxxxxx<span class="reslut_highlight">#keyword#</span>xxxxxxxxx
	function createHighlightedTitle(title, regexp) {

		var highlightedTitle = title;

		regexp.lastIndex = 0;
		var SearchResultMaxCount = 1;

		// Get 1st item (matchKeywords[0]).
		var matchKeywords = regexp.exec(title);
		if (regexp.lastIndex <= 0) {
			// not exits
			return highlightedTitle;
		}
		var matchKeyword = matchKeywords[0];

		var startIndex = 0;
		var titleBefore = title.substring(startIndex, regexp.lastIndex - matchKeyword.length);
		titleBefore = htmlEscape(titleBefore);

		// Create #aftertext#
		var lastIndex = title.length;
		var titleAfter = title.substring(regexp.lastIndex, lastIndex);
		titleAfter = htmlEscape(titleAfter);

		// Create Highlight
		matchKeyword = htmlEscape(matchKeyword);
		matchKeyword = "<span class=\"reslut_highlight\">" + matchKeyword + "</span>";

		highlightedTitle = titleBefore + matchKeyword + titleAfter ;

		return highlightedTitle;
	}

	// Create search result detail.
	// (Highlight 1st keyword.)
	//     ...#beforetext#<span class="reslut_highlight">#keyword#</span>#aftertext#...
	// (exsample)
	//     ...XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX<span class="reslut_highlight">AAA</span>XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX...
	function createHighlightedDetailList(targetText, regexp) {

		var detailList = [];
		regexp.lastIndex = 0;
		var SearchResultDetailMaxCount = 1;

		for (var count = 0; count < SearchResultDetailMaxCount; count++) {

			// Get 1st item (matchKeywords[0]).
			var matchKeywords = regexp.exec(targetText);
			if (regexp.lastIndex <= 0) {
				// not exits
				break;
			}
			var matchKeyword = matchKeywords[0];

			// Create #beforetext#
			var elipsisBefore = "...";
			var elipsisAfter = "...";
			var displayTextLength = 20;	// Length for #beforetext# / #aftertext#
			var startIndex = regexp.lastIndex - matchKeyword.length - displayTextLength;
			if (startIndex < 0) {
				startIndex = 0;
				elipsisBefore = "";
			}
			var detailBefore = targetText.substring(startIndex, regexp.lastIndex - matchKeyword.length);
			detailBefore = htmlEscape(detailBefore);

			// Create #aftertext#
			var lastIndex = regexp.lastIndex + displayTextLength;
			if (lastIndex > targetText.length) {
				lastIndex = targetText.length;
				elipsisAfter = "";
			}
			var detailAfter = targetText.substring(regexp.lastIndex, lastIndex);
			detailAfter = htmlEscape(detailAfter);

			// Create Highlight
			matchKeyword = htmlEscape(matchKeyword);
			matchKeyword = "<span class=\"reslut_highlight\">" + matchKeyword + "</span>";

			var detailText = elipsisBefore + detailBefore + matchKeyword + detailAfter + elipsisAfter;
			detailList.push(detailText);
		}

		return detailList;
	}

	// Create search_result tag structure.
	// <div class="search_result">
	//     <a class="search_result_title" href="#fileName#">#title#</a>
	//     <div class="search_result_detail">...#beforetext#<span class="reslut_highlight">#keyword#</span>#aftertext#...</div>
	// </div>
	// (exsample)
	// <div class="search_result">
	//     <a class="search_result_title" href="AAA.htm">TitleAAA</a>
	//     <div class="search_result_detail">...XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX<span class="reslut_highlight">AAA</span>XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX...</div>
	// </div>
	function createResultItem(title, fileName, detail) {
		var resultItem = $("<div>").addClass("search_result");
		var resultLink = $("<a>").addClass("search_result_title").attr("href", fileName).html(title);
		var detail = $("<div>").addClass("search_result_detail").html(detail);
		resultLink.appendTo(resultItem);
		detail.appendTo(resultItem);

		return resultItem;
	}

	// Create regexpression for [OR]
	// (exsample)： AAA|BBB|CCC
	function createRegexpOrString(keywords) {

		keywords = regexpEscape(keywords);

		// Split by space(\s)
		var separator = /\s+/;
		var arrayKeyword = keywords.split(separator);  
		var regexpString = "";
		for (var index = 0; index < arrayKeyword.length; index++) {
			var keyword = arrayKeyword[index];
			if (keyword != undefined && keyword != "") {
				// separater : "|"
				if (regexpString != "") {
					regexpString += "|";
				}
				regexpString += keyword;
			}
		}

		return regexpString;
	}

	// Create regexpression for [AND]
	// (exsample)：  ^(?=.*AAA)(?=.*BBB)(?=.*CCC)
	function createRegexpAndString(keywords) {

		keywords = regexpEscape(keywords);

		// Split by space(\s)
		var separator = /\s+/;
		var arrayKeyword = keywords.split(separator);  
		var regexpString = "";
		for (var index = 0; index < arrayKeyword.length; index++) {
			var keyword = arrayKeyword[index];
			if (keyword != undefined && keyword != "") {
				if (regexpString == "") {
					// For 1st item
					regexpString += "^";
				}
				regexpString += "(?=.*" + keyword + ")";
			}
		}

		return regexpString;
	}

	function regexpEscape(str) {
		return str.replace(/[-\/\\^$*+?.()|\[\]{}]/g, '\\$&');
	}

	function htmlEscape(str) {
		return str
			.replace(/&/g, '&amp;')
			.replace(/>/g, '&gt;')
			.replace(/</g, '&lt;')
			.replace(/"/g, '&quot;')
			.replace(/'/g, '&apos;');
	}

});