window.SiteSearch = function() {
	
	this.debug = false;
	this.debugOutput = function(txt) {
		alert(txt);
	};
	
	this.currentResultNum = 1;
	this.currentSearch = null;
	
	this.settings = {
		encoding :	"utf-8",
		fe : "ajax",
		client : "lombard_group",
		host : "search.lombard.com",
		collections : [
			{
				label : "All",
				id	 : "lombard_group"
			}
		]
	};
	
	this.ui = {
		isInternetExplorer : document.all ? true:false,
		queryTextBox : null,
		contentPanel : null,
		heading1 : null,
		heading2 : null,
		createSearchNavigation : false,
		previousButtonText : "<< Previous",
		nextButtonText : "Next >>",
		loadingImageSource : "/img/search/rotation.gif",
		noQueryMessage : "Please enter your search terms above.",
		noResultsMessage : "No results found matching the query \"$a\".",
		spellingSuggestionMessage : "Did you mean : ",
		synonymSuggestionMessage : "You could also try : ",
		heading1Text : "Searching in $a",
		heading2Text : "Results matching $a searching in $b"
	};
	
	this.query = {

		setText : function(txt) {
			this.ui.queryTextBox.value = txt;
		},	
		
		getText : function() {
			var rawText = new String(this.ui.queryTextBox.value);
			return rawText.replace(/[{}"';]*/g, "");
		},
		
		currentCollection : null,
		
		getSearchCollectionName : function() {
			var name = "";
			for(var i = 0; i < this.settings.collections.length; i++) {
				if(this.settings.collections[i].id == this.currentCollection) {
					name = this.settings.collections[i].label;
				}
			}
			return name;
		}	
	};
	
	this.query.ui = this.ui;
	this.query.settings = this.settings;
	
	this.addScript = function(url) {	
		var script = document.createElement("script");
		script.type = "text/javascript";
		script.src = url;
		document.getElementsByTagName("head")[0].appendChild(script);
	};

	this.submit = function() {		
		return this.submit(null);
	};
	
	this.submit = function(start) {
		if(start == null) {start = 0;}
		var url = "http://" + this.settings.host + "/search?access=p&output=xml_no_dtd&getfields=description&client=";		
		url += this.settings.client + "&proxystylesheet=" + this.settings.fe + "&ie=" + this.settings.encoding + "&oe=" + this.settings.encoding;		
		url += "&start=" + start + "&q=" + this.query.getText() + "&site=" + this.query.currentCollection;
		if(this.debug){this.debugOutput("Debug on"); this.debugOutput("Contacting server via " + url);}
	
		this.clearAll();
		this.setHeadings();
		this.setLoadingStatus();
		this.currentResultNum = start;
		this.addScript(url);
		return false;
	};
	
	this.getNextResults = function() {
		var next = this.currentResultNum + 10;
		this.submit(next);		
	};
	
	this.getPreviousResults = function() {
		var previous = (this.currentResultNum >= 11) ?  this.currentResultNum - 10 : 0;
		this.submit(previous);
	};
	
	this.setHeadings = function() {
		
		if(this.debug){this.debugOutput("Setting headings");}
		
		var heading1 = this.ui.heading1;
		var heading2 = this.ui.heading2;
		
		if(heading1 != null) {
			var h1Text = this.ui.heading1Text.replace("\$a", this.query.getSearchCollectionName());		
			this.removeChildNodes(heading1);
			heading1.appendChild(document.createTextNode(h1Text));
		}
		
		if(heading2 != null) {
			this.removeChildNodes(heading2);
			if(this.query.getText() != ""){
				var h2text = this.ui.heading2Text.replace("\$a", this.query.getText());
				var h2text = h2text.replace("\$b", this.query.getSearchCollectionName());
				heading2.appendChild(document.createTextNode(h2text));
				heading2.style.display = "block";
			}
		}
	};
	
	this.setLoadingStatus = function() {
		if(this.debug){this.debugOutput("Setting loading icon");}
		this.loading = this.ui.contentPanel.appendChild(document.createElement("div"));
		this.loading.style.height = "540px";
		this.loading.style.listStyleImage = "none";
		this.loading.style.listStyleType = "none";
		this.loading.style.textAlign = "center";
		this.loading.style.paddingTop = "200px";
		var loadingImg = this.loading.appendChild(document.createElement("img"));
		loadingImg.setAttribute("src", this.ui.loadingImageSource);
	};

	this.removeChildNodes = function (element) {
		if(element.childNodes.length > 0) {
			var currentChild = element.childNodes.item(0);
			var nextChild;
			while(currentChild){
				nextChild = currentChild.nextSibling;
				element.removeChild(currentChild);
				currentChild = nextChild;
			}
		}
	};
	
	this.setStatusText = function(GSP) {
		
		if(this.debug){this.debugOutput("Setting status text");}
		
		this.ui.statusText = this.ui.contentPanel.appendChild(document.createElement("div"));
		this.ui.statusText.className = "statusText";
		
		var message;
		
		if(GSP.queryDetails.estimatedTotal > 0){
			message = "Results " + GSP.queryDetails.startRecordNum + " to " + GSP.queryDetails.endRecordNum;
			if(GSP.queryDetails.estimatedTotal > 10) message += " of about " + GSP.queryDetails.estimatedTotal;
			message += " matching the query \"\$oe" + this.query.getText() + "\$ce\".";
		}
		else {
			if(this.query.getText() == ""){
				message = this.ui.noQueryMessage;
			}
			else {
				message = this.ui.noResultsMessage.replace("\$a", this.query.getText());
			}
		} 
		
		// Modified by NG 300708 - Add italics around the search results
		this.ui.statusText.appendChild(document.createElement("p")).appendChild(document.createTextNode(message));
		var tempStatusText = this.ui.statusText.getElementsByTagName("p")[0].innerHTML;
		tempStatusText = tempStatusText.replace(/\$oe/,"<em>")
		tempStatusText = tempStatusText.replace(/\$ce/,"</em>")
		this.ui.statusText.getElementsByTagName("p")[0].innerHTML = tempStatusText
		this.loadSuggestions(GSP.spelling, this.ui.spellingSuggestionMessage);
		this.loadSuggestions(GSP.synonyms, this.ui.synonymSuggestionMessage);
	};
	
	this.loadSuggestions = function(ar, message) {
		
		if(this.debug){this.debugOutput("Loading " + ar.length + " suggestions");}
		
		if(ar.length > 0){	
			var cur_item;		
			var suggestion = this.ui.statusText.appendChild(document.createElement("p"));
			suggestion.appendChild(document.createTextNode(message));
			suggestion.id = "spelling";			
			for(var i = 0; i < ar.length; i++){
				cur_item = suggestion.appendChild(document.createElement("a"));
				cur_item.href = "#";
				cur_item.onclick = trySuggestion;
				cur_item.appendChild(document.createTextNode(ar[i].q));
			}
		}
	};
	
	this.createNavigation = function(GSP) {
		
		if(this.debug){this.debugOutput("Creating navigation bar");}
		
		var previousButton;
		var nextButton;
		var pageNum = ((GSP.queryDetails.startRecordNum - 1) / 10) + 1;
		var s = (Math.floor((pageNum-1)/10) * 10) + 1;
		var e = s + 9;
		var epc = GSP.queryDetails.estimatedTotal / 10;
		
		var navigator = this.ui.contentPanel.appendChild(document.createElement("div"));
		navigator.className = "searchNavigation";
		
		if(epc > 1) {
			
			if (GSP.queryDetails.hasPrevious) {
				previousButton = navigator.appendChild(document.createElement("button"));
				previousButton.className = "previous";
				previousButton.title = "Previous Page";
				previousButton.onclick = getPreviousResults;
				previousButton.onkeypress = getPreviousResults;
				previousButton.appendChild(document.createTextNode(this.ui.previousButtonText));	
			}
			
			if(this.ui.createSearchNavigation) {
				for(var i = s; i <= e && i <= epc; i++){
					anchor = navigator.appendChild(document.createElement("a"));
					anchor.href = "#" + i;
					anchor.title = "go to results page " + i;
					anchor.onclick = changePage;
					anchor.onkeypress = changePage;
					if(i == pageNum){
						anchor.style.fontWeight = "bold";
						anchor.style.textDecoration = "underline";
					}
					anchor.appendChild(document.createTextNode(i));
				}
			}
			
			if (GSP.queryDetails.hasNext) {
				nextButton = navigator.appendChild(document.createElement("button"));
				nextButton.className = "next";
				nextButton.title = "Next Page";
				nextButton.onclick = getNextResults;
				nextButton.onkeypress = getNextResults;
				nextButton.appendChild(document.createTextNode(this.ui.nextButtonText));
			}
		}
	};
	
	this.trackEvent = function(GSP) {
		try {
			var ev1 = _hbEvent("search");
			ev1.keywords = GSP.queryDetails.queryText;
			ev1.results = GSP.queryDetails.estimatedTotal;
			ev1.attr1 = GSP.queryDetails.site;
		}
		catch(e) {}
	};
	
	this.loadKeyMatches = function(GSP) {
		
		if(this.debug){this.debugOutput("Loading " + GSP.keyMatches.length + " key matches");}
		
		if(GSP.keyMatches.length > 0){
		
			var content;
			var item;
			var anchor;
			
			var keyMatches = this.ui.contentPanel.appendChild(document.createElement("div"));
			var top = keyMatches.appendChild(document.createElement("div"));
			top.className = "keyMatchTop";
			top.appendChild(document.createElement("hr"));
			var centre = keyMatches.appendChild(document.createElement("div"));
			centre.className = "keyMatchContent";
			content = centre.appendChild(document.createElement("ul"));
			content.className = "searchResultsList";
			content.setAttribute("id", "keyMatchResults");
			var base = keyMatches.appendChild(document.createElement("div"));
			base.className = "keyMatchBase";
			base.appendChild(document.createElement("hr"));
			keyMatches.appendChild(document.createElement("br")).className = "cb";
			
			for(var i = 0; i < GSP.keyMatches.length; i++) {
				item = content.appendChild(document.createElement("li"));
				anchor = item.appendChild(document.createElement("a"));
				anchor.setAttribute("href", GSP.keyMatches[i].url);
				anchor.appendChild(document.createTextNode(GSP.keyMatches[i].title));
				item.appendChild(document.createTextNode(" - (Key Match)"));
			}		
		}	
	};
	
	this.clearAll = function() {
		if(this.debug){this.debugOutput("Clearing all content");}
		this.removeChildNodes(this.ui.contentPanel);
	};

	this.loadResults = function(GSP) {
		var result;
		var listItem;
		var anchor;
		var para;
		var summaryText;
		
		if(this.debug){this.debugOutput("Loading results");}
		
		document.title = "Search Results | Lombard";

		this.clearAll();
		this.setStatusText(GSP);
		
		if(GSP.queryDetails.estimatedTotal > 0){
			this.loadKeyMatches(GSP);
			
			if(this.debug){this.debugOutput(GSP.results.length + " results found");}
			
			this.resultsList = this.ui.contentPanel.appendChild(document.createElement("ul"));
			this.resultsList.className = "searchResultsList";
			
			for(var i = 0; i < GSP.results.length; i++) {
				result = GSP.results[i];
				listItem = this.resultsList.appendChild(document.createElement("li"));
				anchor = listItem.appendChild(document.createElement("h4")).appendChild(document.createElement("a"));			
				anchor.href = result.url;
				anchor.title = result.title;
				if(anchor.innerHTML) {
					anchor.innerHTML = result.title;				
				}
				else {
					anchor.appendChild(document.createTextNode(result.title.replace(/(<\/?b>)/g, "").replace(/&amp;/g, "&")));
				}
				para = listItem.appendChild(document.createElement("p"));
				summaryText = (result.description == "") ? result.summary : result.description;
				if(anchor.innerHTML) {para.innerHTML = summaryText;}
				else{para.appendChild(document.createTextNode(summaryText.replace(/(<\/?b>)/g, "").replace(/&amp;/g, "&")));}
			}
			
			this.createNavigation(GSP);
		}
		else {			
			if(this.debug){this.debugOutput("No results returned");}
		}
		
		if(typeof(this.onLoaded) == "function") this.onLoaded.call();
		
		this.currentSearch = GSP;
		this.trackEvent(GSP);
	}
	
	this.onLoaded = null;
}

function changePage() {	
	var a = (ie) ? window.event.srcElement : window.event.target;
	var txt = (a.innerText) ? a.innerText : a.childNodes[0].nodeValue;
	var start = ((parseInt(txt) - 1) * 10);
	search.submit(start);
}

function trySuggestion(e) {
	if(!e) {e = window.event}
	var a = (ie) ? e.srcElement : e.target;
	var txt = (a.innerText) ? a.innerText : a.childNodes[0].nodeValue;
	search.query.setText(txt);
	search.submit();
}

function getNextResults() {
	search.getNextResults();
}

function getPreviousResults() {
	search.getPreviousResults();
}

function loadSearch(GSP) {
	search.loadResults(GSP);
}