// SoftwareAG: 
//	- comment out window.onhashchange
//	- add to doSearch
//	- amend findinsiteDbAllLoaded
//	- amend searchDone

//	FindinSite-CD-JS search page example code
//	Copyright (C) 2019 PHD Computer Consultants Ltd
//
//	Version details
//		7.016	29-Apr-2019
//      7.015   18-Jun-2017
//
//	Usage:	findinsite_page.config: idSearch:	id of search input element
//																	idResults: id of results output element
//																	idSearchForm: optional element (eg FORM) to add subsets checkboxes to
//																	baseurl: URL to prepend to all links
//																	startSearch: optional function to call when search started
//																	target: optional window target eg '_blank'
//					findinsite_page.search()
//					findinsite_page.searchKeypress(event)	enter keypresses do search

/*global document, setTimeout, window */
/*global findinsite, fisLogging */
/*jshint bitwise: false*/
/*jslint bitwise: false, white: true */

var findinsite_page = function ($) {
	"use strict";

	var savedresults = false;

	// PRIVATE variables made PUBLIC at end
	var config = {
		idSearch: false,
		idResults: false,
		idSearchForm: false,
		startSearch: false,
		baseurl: '',
		target: false,	// or '_blank' etc
		highlight: false,
	};

	// PRIVATE variables and functions - except as noted

	var userSearch = false;
	var eleSearch = null;
	var eleResults = null;

	var doSearch, showProgress, searchDone;

	/////////////////////////////////////
	function log(msg) {
		if (typeof fisLogging !== 'undefined') {
			if (fisLogging && window.console && window.console.log) {
				window.console.log(msg);
			}
		}
	}

	/////////////////////////////////////
	function fail(msg) {
		if (eleResults) {
			eleResults.innerHTML += "<p><strong>" + msg + "</strong></p>";
		}
		return false;
	}

	/////////////////////////////////////
	function escapeHTML(string) {
		var pre, text;
		pre = document.createElement('pre');
		text = document.createTextNode(string);
		pre.appendChild(text);
		return pre.innerHTML;
	}

	/////////////////////////////////////
	// Made PUBLIC at end
	function search(theSearch) {
		var dbno;
		if (!config.idSearch) { return fail("config.idSearch not given"); }
		eleSearch = document.getElementById(config.idSearch);
		if (!eleSearch) { return fail("Invalid config.idSearch name " + config.idSearch); }

		if (typeof theSearch !== "undefined") {
			eleSearch.value = theSearch;
		}
		userSearch = eleSearch.value;

		if (!config.idResults) { return fail("config.idResults not given"); }
		eleResults = document.getElementById(config.idResults);
		if (!eleResults) { return fail("Invalid config.idResults name " + config.idResults); }

		for (dbno = 0; dbno < findinsite.databases.length; dbno++) {
			findinsite.databases[dbno].selected = true;
		}
		$("[name='subsets']").each(function () {
			var dbno = $(this).val();
			var checked = $(this).is(':checked');
			findinsite.databases[dbno].selected = checked;
		});

		// Show wait message and do search
		eleResults.innerHTML = "Please wait...";
		//findinsite.databases[0].selected = false;
		setTimeout(doSearch, 0);
		return false;
	}

	/////////////////////////////////////
	doSearch = function () {
		var params = { search: userSearch, showProgress: showProgress, searchDone: searchDone };
		$("[name='subsets']").each(function () {	// SoftwareAG
			var dbno = $(this).val();
			$(this).prop('checked', true);
			findinsite.databases[dbno].selected = true;
		});
		if (config.startSearch) {
			config.startSearch();
		}
		findinsite.search(params);
		return false;	// to stop onclick handler
	};

	/////////////////////////////////////
	showProgress = function (info) {
		eleResults.innerHTML = info;
	};

	/////////////////////////////////////
	searchDone = function (results) {	// SoftwareAG
		var output, eno, searchWord, wx, hitix, pagenocount, pageno, page;

		savedresults = results;

		eleResults.innerHTML = "<h2>Results</h2>";

		////// REPORT ANY ERROR
		if (results.error !== false) { fail(results.error); return; }

		location.hash = encodeURIComponent(userSearch);

		////// SHOW SEARCH WITH OPERATORS AND UNFOUND WORDS WITH LINE THROUGH
		// and build up list of words to highlight
		var hi = "";
		output = "<p>Search: ";
		var incontig = false;
		for (eno = 0; eno < results.expression.length; eno++) {
			searchWord = results.expression[eno];
			var op = searchWord.op;
			if (op & findinsite.OP_OR) {
				output += " OR ";
			}
			if (op & findinsite.OP_NOT) {
				output += " NOT ";
			}
			if (!incontig && (op & findinsite.OP_CONTIG)) {
				output += " << ";
				incontig = true;
			}
			if (incontig && ((op & findinsite.OP_CONTIG) === 0)) {
				output += " >> ";
				incontig = false;
			}
			if (!searchWord.anyfound) { output += "<span style='text-decoration:line-through;'>"; }
			output += escapeHTML(searchWord.given);
			if (!searchWord.anyfound) { output += "</span>"; }
			else if (searchWord.given != '*') {
				output += " <span style='color:gray;'>(";
				for (wx = 0; wx < searchWord.wdsfound.length; wx++) {
					output += searchWord.wdsfound[wx] + " ";
					if (!(op & findinsite.OP_NOT)) {
						hi += searchWord.wdsfound[wx] + "+";
					}
				}
				output += ")</span>";
			}
			output += " ";
			//if (!searchWord.anyfound) { continue; }
		}
		if (incontig) {
			output += " >> ";
		}
		output += "</p>";
		//eleResults.innerHTML += output;

		if (config.highlight) {
			hi = config.highlight + hi.substring(0, hi.length - 1);
    } else {    // 7.015
      hi = '';
    }

		////// SHOW RESULTS
		output = "";

		//console.log(results.narrative);
		if (results.narrative && (results.narrative.length > 0)) {
			output += "<ul><li>" + results.narrative.join("</li><li>") + "</li></ul>";
		}

		var shownhits = 0;
		output += "<ol>";
		//log(results.pages.length);
		for (hitix = 0; hitix < results.hits.length; hitix++) {
			pagenocount = results.hits[hitix];
			pageno = pagenocount[0];
			var db = pagenocount[1];
			if (!db.selected) { continue; }
			shownhits++;
			var weight = pagenocount[2];
			var baseurl = db.baseurl;
			if (db.baseurls.length > 0) { baseurl += db.baseurls[0]; }
			if (pageno >= db.pages.length) { eleResults.innerHTML = "<h2>pageno FAIL</h2>"; }
			page = db.pages[pageno - 1];
			//log(page);

			output += "<li><a ";
			if (config.target) {
				output += "target='" + config.target + "' ";
			}
			output += "href='" + config.baseurl + escapeHTML(baseurl + page.path + hi) + "'>" + escapeHTML(page.title) + "</a> <i>" + escapeHTML(page.abst) + "</i></li>";
		}
		output += "</ol>";
		output = "<p>" + shownhits + " results</p>" + output;
		eleResults.innerHTML += output;
	};

	/////////////////////////////////////
	// Basic catch of hash change
	//	could do better with http://benalman.com/projects/jquery-hashchange-plugin/

	window.onhashchange = function () {
		/*if (location.hash.length > 1) {	// SoftwareAG
			var hashsearch = decodeURIComponent(location.hash).substr(1);
			if (hashsearch != userSearch) {
				search(hashsearch);
			}
		}*/
	}

	/////////////////////////////////////
	// Made PUBLIC at end
	function searchKeypress(event) {
		if (event.which === 13 || event.keyCode === 13) {
			return search();
		}
		return true;
	}

	/////////////////////////////////////
	/////////////////////////////////////
	// Handle all databases loaded event
	$(document).on("findinsiteDbAllLoaded", function (e) {	// SoftwareAG

		// Trigger hashchange event so as to re-do search if we've gone back
		window.onhashchange();

		var dbcount = findinsite.databases.length;
		var showSubsets = dbcount > 1;
		if (showSubsets && config.idSearchForm) {
		    var hint = "<h3>Filter</h3><p>Settings will take effect with your next search.</p>";
		    $('#' + config.idSearchForm).append(hint);
		}
		for (var dbno = 0; dbno < dbcount; dbno++) {
			var thisdb = findinsite.databases[dbno];

			// Fill the findinsite-dbs span
			var dbinfo = $('<abbr>', { title: thisdb.description });
			dbinfo.text(thisdb.varname);
			$("#findinsite-dbs").append(dbinfo);
			$("#findinsite-dbs").append($('<span> </span>'));

			// Show list of subsets to search
			if (showSubsets && config.idSearchForm) {
				var chk = "<input type='checkbox' checked name='subsets' value='" + dbno + "' id='subset" + dbno + "'><label for='subset" + dbno + "'>&#xA0;" + thisdb.description + "</label><br>";
				$('#' + config.idSearchForm).append(chk);
			}
		}
		if (showSubsets && config.idSearchForm) {
		  var divider = "<hr>";
		  $('#' + config.idSearchForm).append(divider);
		}

		$("[name='subsets']").change(function () {
			var dbno = $(this).val();
			var checked = $(this).is(':checked');
			findinsite.databases[dbno].selected = checked;
			if (savedresults) {
				searchDone(savedresults);
			}
		});
	});

	/////////////////////////////////////
	// PUBLIC methods
	return {
		config: config,
		search: search,
		searchKeypress: searchKeypress
	};
	/////////////////////////////////////
} (jQuery);