/*
// +----------------------------------------------------------------------+
// | Copyright (c) 2004 Bitflux GmbH					                  |
// +----------------------------------------------------------------------+
// | Licensed under the Apache License, Version 2.0 (the "License");	  |
// | you may not use this file except in compliance with the License.	  |
// | You may obtain a copy of the License at				              |
// | http://www.apache.org/licenses/LICENSE-2.0 			              |
// | Unless required by applicable law or agreed to in writing, software  |
// | distributed under the License is distributed on an "AS IS" BASIS,	  |
// | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or	  |
// | implied. See the License for the specific language governing	      |
// | permissions and limitations under the License.			              |
// +----------------------------------------------------------------------+
// | Author: Bitflux GmbH <devel@bitflux.ch>				              |
// +----------------------------------------------------------------------+
// | In accordance with the Apache Licence, Version 2.0, the following    |
// | modifications have been made to the Javascript source below to allow |
// | this code to work with the ISOxford Heritage WebOPAC Versions 2.3    |
// | and above. Modifications by Chris Sheppard <cpfs@isoxford.com>       |
// +----------------------------------------------------------------------+

*/
var liveSearchReq = false;
var t = null;
var liveSearchLast = "";
var searchbox = new Object();
var resultbox = "";
var shadowbox = "";
var objposn = 0;
var prefixchar = '@';
var currentphrase = '';

var isIE = false;
// on !IE we only have to initialize it once
if (window.XMLHttpRequest) {
	liveSearchReq = new XMLHttpRequest();
}

function liveSearchInit() {
	
	if (navigator.userAgent.indexOf("Safari") > 0) {
		document.getElementById('livesearch').addEventListener("keydown",liveSearchKeyPress,false);
		//		document.getElementById('livesearch').addEventListener("blur",liveSearchHide,false);
		} else if (navigator.product == "Gecko") {
		
		document.getElementById('livesearch').addEventListener("keypress",liveSearchKeyPress,false);
		document.getElementById('livesearch').addEventListener("blur",liveSearchHideDelayed,false);
		} else {
		document.getElementById('livesearch').attachEvent('onkeydown',liveSearchKeyPress);
		//		document.getElementById('livesearch').attachEvent("onblur",liveSearchHide,false);
		isIE = true;
	}
	
	document.getElementById('livesearch').setAttribute("autocomplete","off");

}

function liveSearchHideDelayed() {
	window.setTimeout("liveSearchHide()",400);
}

function liveSearchHide() {
	document.getElementById(resultbox).style.display = "none";
	var highlight = document.getElementById("LSHighlight");
	if (highlight) {
		highlight.removeAttribute("id");
	}
}

function liveSearchKeyPress(event) {
	var currentword = getLastWord(); 
	if (event.keyCode == 40 )
	//KEY DOWN
	{
		highlight = document.getElementById("LSHighlight");
		if (!highlight) {
			highlight = document.getElementById(shadowbox).firstChild.firstChild;
			} else {
			highlight.removeAttribute("id");
			highlight = highlight.nextSibling;
		}
		if (highlight) {
			highlight.setAttribute("id","LSHighlight");
		}
		if (!isIE) { event.preventDefault(); }
		replaceLastWord(highlight.innerHTML);
	}
	//KEY UP
	else if (event.keyCode == 38 ) {
		highlight = document.getElementById("LSHighlight");
		if (!highlight) {
			highlight = document.getElementById(resultbox).firstChild.firstChild.lastChild;
		}
		else {
			highlight.removeAttribute("id");
			highlight = highlight.previousSibling;
		}
		if (highlight) {
			highlight.setAttribute("id","LSHighlight");
		}
		if (!isIE) { event.preventDefault(); }
		replaceLastWord(highlight.innerHTML);
	}
	//ESC
	else if (event.keyCode == 27) {
//		highlight = document.getElementById("LSHighlight");
//		if (highlight) {
//			highlight.removeAttribute("id");
//		}
		document.getElementById(resultbox).style.display = "none";
		searchbox.value = currentphrase;
		
	}
}

function liveSearchStart(newsearchbox, newresult, newshadow, newposition) {
	searchbox = newsearchbox;
	resultbox = newresult;
	shadowbox = newshadow;
	objposn = newposition;
	currentphrase = searchbox.value;
	if (t) {
		window.clearTimeout(t);
	}
	t = window.setTimeout("liveSearchDoSearch()",200);
}

function liveSearchDoSearch() {
	
	var slashposn = window.location.href.lastIndexOf('/')+1;
	var urlroot = window.location.href.substring(0,slashposn);
	var actualword = getLastWord();
	if (typeof liveSearchRoot == "undefined") {
		liveSearchRoot = "";
	}
	if (typeof liveSearchRootSubDir == "undefined") {
		liveSearchRootSubDir = "";
	}
	if (typeof liveSearchParams == "undefined") {
		liveSearchParams = "";
	}
	if (liveSearchLast != actualword) {
		if (liveSearchReq && liveSearchReq.readyState < 4) {
			liveSearchReq.abort();
		}
		if ( getLastWord() == "") {
			liveSearchHide();
			return false;
		}
		if (window.XMLHttpRequest) {
			// branch for IE/Windows ActiveX version
			} else if (window.ActiveXObject) {
			liveSearchReq = new ActiveXObject("Microsoft.XMLHTTP");
		}
		liveSearchReq.onreadystatechange= liveSearchProcessReqChange;
//		liveSearchReq.open("GET", liveSearchRoot + "/HeritageScripts24/Hapi.dll/getwordlist?window=20&delim=%3C/A%3E%3C/div%3E%3Cdiv%20name=word%20class=LSRow%3E%3CA%20HREF%3d%22javascript:loadwd()%22%3E&word=@" + actualword.toUpperCase());
		liveSearchReq.open("GET", urlroot + "getwordlist?window=20&delim=%3C/div%3E%3Cdiv%20name=%22word%22%20class=%22LSRow%22%3E&word="+prefixchar+actualword.toUpperCase());
		liveSearchLast = actualword;
		liveSearchReq.send(null);
	}
}

function liveSearchProcessReqChange() {
	
	/*
	uninitialized				Object is not initialized with data.
	loading				      Object is loading its data.
	loaded				      Object has finished loading its data.
	interactive				  User can interact with the object even though it is not fully loaded.
	complete			      Object is completely initialized.
	*/
	
	if (liveSearchReq.readyState == 4) {
		var currentword = getLastWord();
		var  res = document.getElementById(resultbox);
		res.style.display = "block";
		var  sh = document.getElementById(shadowbox);
		var wordlst = liveSearchReq.responseText; 
		var wordterm = new RegExp("LSRow\">" + currentword.toUpperCase());
		if (wordlst.search(wordterm) != -1) {
			//		  wordlst = wordlst.replace(wordterm, "LSRhi> " + currentword.toUpperCase());
			searchbox.className = "Boxwhite";
			} else {
			searchbox.className = "Boxpink";
		}
		sh.innerHTML = wordlst.toLowerCase();
		var  wordlst1 = document.getElementsByTagName('div');
		if (wordlst1[objposn] != null) {
			wordlst1[objposn].setAttribute("id","LSHighlight");
		}
	}
}


function liveSearchSubmit() {
	var highlight = document.getElementById("LSHighlight");
	if (highlight && highlight.firstChild) {
		window.location = liveSearchRoot + liveSearchRootSubDir + highlight.firstChild.nextSibling.getAttribute("href");
		return false;
	}
	else {
		return true;
	}
}

function getLastWord() {
	var LastWord = searchbox.value;
	LastWord = LastWord.replace(/^(\s+)?(.*\S)(\s+)?$/, '$2'); // trim function
	
	while (LastWord.search(/ /) != -1) {
		var wordpos = LastWord.indexOf(' ');
		LastWord = LastWord.substr(wordpos+1);
	}
	return LastWord;
}

function replaceLastWord(rword)  {
	var rLastWord = searchbox.value;
//	var rLastWord = rLastWord.replace(/^(\s+)?(.*\S)(\s+)?$/, '$2'); // trim function
	rword = rword.replace(/^(\s+)?(.*\S)(\s+)?$/, '$2'); // trim this as well
	var rwordpos = rLastWord.lastIndexOf(' ');
	if (rwordpos == -1) {
		searchbox.value =  rword;
		} else {
		var firstbit = rLastWord.substr(0,rwordpos+1);
		searchbox.value =  firstbit + rword;
	}
}

function loadwd() {
   alert('No idea what we\'ve clicked on');
}

function removefirstchar() {
}