// ----------- UTILITY FUNCTIONS BEGIN ----------- //

function ltrim(string) {
	return string.replace(/^\s*/, ''); }

function rtrim(string) {
	return string.replace(/\s*$/, ''); }

function trim(string) {
	return ltrim(rtrim(string)); }

function normalise(string) {
	return string.replace(/\s+/, ' '); }

function GetKey(e) {
	if(document.layers)
		return e.which;
	else if (document.all)
		return event.keyCode;
	else if (document.getElementById)
		return e.keyCode;
	return 0; }

function Hide(el) {
	Debug('Hide(' + el.id + ')');
	oldIdx = -1;
	oldIdx2 = -1;
	if(el) el.style.display = 'none'; }

function Show(el) {
	Debug('Show(' + el.id + ')');
	if(el) el.style.display = 'block'; }

function IsHidden(el) {
	Debug('IsHidden(' + el.id + ')');
	return el.style.display == 'none'; }

function UpdateInnerHtml(el, contents) {
	Debug('UpdateInnerHtml(' + el.id + ', ' + contents + ')');
	theContent = contents;
	eval(contents);
	theOutput = '';
	theOutput = theOutput + '<div style="cursor: default; font-size: small; background: #eee; color: green; font-weight: bold; font-family: Arial, sans-serif; border-bottom: 1px solid black; text-align: center;">Do you mean...</div>';
	if(el == theSuggestions2)
		suffix = '2';
	else
		suffix = '';
	for(loopA = 0; loopA < 10; loopA++)
	{
		theOutput = theOutput + '<div class="frmAecSuggestion"  onmouseover="suggestionMouseover' + suffix + '()" onmouseout="suggestionMouseout' + suffix + '()"  onclick="suggestionMouseclick' + suffix + '(\'' + theResults[loopA] + '\')">' + theResults[loopA] + '</div>';
	}
	if(el) el.innerHTML = theOutput; }

function UpdateSuggestions(el, idx) {
	if(idx == oldIdx)
		return 0;
	oldIdx = idx;
	Debug('UpdateSuggestions(' + el.id + ', ' + idx+ ')');
	contents = theContent;
	eval(contents);
	theOutput = '';
	theOutput = theOutput + '<div style="cursor: default; font-size: small; background: #eee; color: green; font-weight: bold; font-family: Arial, sans-serif; border-bottom: 1px solid black; text-align: center;">Do you mean...</div>';
	if(el == theSuggestions2)
		suffix = '2';
	else
		suffix = '';
	for(loopA = 0; loopA < 10; loopA++)
	{
		if(loopA == idx)
			theOutput = theOutput + '<div class="frmAecSuggestionSelected"  onmouseover="suggestionMouseover' + suffix + '(' + loopA + ')" onmouseout="suggestionMouseout' + suffix + '()"  onclick="suggestionMouseclick' + suffix + '(\'' + theResults[loopA] + '\')">' + theResults[loopA] + '</div>';
		else
			theOutput = theOutput + '<div class="frmAecSuggestion"  onmouseover="suggestionMouseover' + suffix + '(' + loopA + ')" onmouseout="suggestionMouseout' + suffix + '()"  onclick="suggestionMouseclick' + suffix + '(\'' + theResults[loopA] + '\')">' + theResults[loopA] + '</div>';
	}
	if(el) el.innerHTML = theOutput;
	if(idx == -1) {
		if(el == theSuggestions)
			return originalInput;
		else if(el == theSuggestions2)
			return originalInput2;
		}
	return theResults[idx]; }

function Scheduler(code, ms) {
	this.code = code;
	this.ms = ms;
	this.timer = false; }

Scheduler.prototype.start = function() {
	Debug('Scheduler.start() --> ' + this.code + ' : ' + this.ms);
	if(this.timer) this.reset();
	this.timer = window.setTimeout(this.code, this.ms); }

Scheduler.prototype.reset = function() {
	Debug('Scheduler.reset() --> ' + this.code + ' : ' + this.ms);
	if(this.timer) window.clearTimeout(this.timer);
	this.timer = false; }

function CalculateOffsetLeft(el){
  return CalculateOffset(el,"offsetLeft")
}

function CalculateOffsetTop(el){
  return CalculateOffset(el,"offsetTop")
}

function CalculateOffset(el, type) {
	var offset = 0;
	while(el) {
		offset += el[type];
		el = el.offsetParent; }
	return offset; }

// ----------- UTILITY FUNCTIONS CEASE ----------- //

var theInput = false;
var theInput2 = false;
var theSuggestions = false;
var theSuggestions2 = false;
var classPrimary = false;
var classSecondary = false;
var mainTimer = new Scheduler('UpdateAdvisor()', 30);
var mainTimer2 = new Scheduler('UpdateAdvisor2()', 30);
var suggestionsBlurTimer = new Scheduler('Hide(theSuggestions)', 3000);
var suggestionsBlurTimer2 = new Scheduler('Hide(theSuggestions2)', 3000);
var getUrl = "get.php?s="; // The server-side script
var getUrl2 = "get.php?i=2&s="; // The server-side script
var suggestionsQuickBlurTimer = new Scheduler('Hide(theSuggestions)', 500);
var suggestionsQuickBlurTimer2 = new Scheduler('Hide(theSuggestions2)', 500);
var theContent = false;
var oldIdx = -1;
var originalInput = false;
var originalInput2 = false;

// ID for <input> and suggestions <div>
// class selector for primary and secondary fields
function InitialiseAdvisor(elidInput, elidInput2, elidSuggestions, elidSuggestions2, elclPrimary, elclSecondary) {
		//ShowDebug();
		Debug('InitialiseAdvisor(...)');
		theInput = document.getElementById(elidInput);
		theSuggestions = document.getElementById(elidSuggestions);
		theInput2 = document.getElementById(elidInput2);
		theSuggestions2 = document.getElementById(elidSuggestions2);
		classPrimary = elclPrimary;
		classSecondary = elclSecondary;

		theInput.onkeyup = function(e) {
			key = GetKey(e);
			switch (key) {
				case 27: // escape
					Hide(theSuggestions);
					return false;
					break;
				case 38: // up arrow
					//gsc_handleup(__results, __query);
					if(IsHidden(theSuggestions)) {
						return false; }
					if(oldIdx > -1) {
						theInput.value = UpdateSuggestions(theSuggestions, oldIdx-1);
						suggestionsBlurTimer.reset(); }
					if(oldIdx == -1)
						suggestionsBlurTimer.start();
					return false;
					break;
				case 40: // down arrow
					//gsc_handledown(__results, __query);
					if(IsHidden(theSuggestions)) {
						return false; }
					if(oldIdx < 9) {
						theInput.value = UpdateSuggestions(theSuggestions, oldIdx+1);
						suggestionsBlurTimer.reset(); }
					return false;
					break;
				default:
					originalInput = theInput.value;
					mainTimer.start(); }
			return true; }

		theInput2.onkeyup = function(e) {
			key = GetKey(e);
			switch (key) {
				case 27: // escape
					Hide(theSuggestions2);
					return false;
					break;
				case 38: // up arrow
					//gsc_handleup(__results, __query);
					if(IsHidden(theSuggestions2)) {
						return false;}
					if(oldIdx > -1) {
						theInput2.value = UpdateSuggestions(theSuggestions2, oldIdx-1);
						suggestionsBlurTimer2.reset(); }
					if(oldIdx == -1)
						suggestionsBlurTimer2.start();
					return false;
					break;
				case 40: // down arrow
					//gsc_handledown(__results, __query);
					if(IsHidden(theSuggestions2)) {
						return false;}
					if(oldIdx < 9) {
						theInput2.value = UpdateSuggestions(theSuggestions2, oldIdx+1);
						suggestionsBlurTimer2.reset(); }
					return false;
					break;
				default:
					originalInput2 = theInput2.value;
					mainTimer2.start(); }
			return true; }
		
		resizeHandler();
		window.onresize = resizeHandler;
		
		if(theInput && theSuggestions && theInput2 && theSuggestions2 && classPrimary && classSecondary)
			return 0;
		else
			return 1;
	}
	
function GetSearchString() {
	Debug('GetSearchString -> "' + trim(normalise(theInput.value)) + '"');
	return (trim(normalise(theInput.value))); }

function GetSearchString2() {
	Debug('GetSearchString2 -> "' + trim(normalise(theInput2.value)) + '"');
	return (trim(normalise(theInput2.value))); }

function UpdateAdvisor() {

	Debug('UpdateAdvisor()');
	if(GetSearchString() == '') {
		Hide(theSuggestions);
		return 0; }
	
	if(AjaxRequest.isActive())
		AjaxRequest.abort();
	
	AjaxRequest.get(
	{
			'url' : 'get.php?s=' + GetSearchString(),
			'onSuccess' : function(req)
			{
				UpdateInnerHtml(theSuggestions, req.responseText);
				if(theInput.hasFocus)
					Show(theSuggestions);
				suggestionsBlurTimer.start();
			}
	} ); 
	
	}

function UpdateAdvisor2() {
	Debug('UpdateAdvisor2()');
	if(GetSearchString2() == '') {
		Hide(theSuggestions2);
		return 0; }
	
	if(AjaxRequest.isActive())
		AjaxRequest.abort();
	
	AjaxRequest.get(
	{
			'url' : 'get.php?s=' + GetSearchString2(),
			'onSuccess' : function(req)
			{
				UpdateInnerHtml(theSuggestions2, req.responseText);
				if(theInput2.hasFocus)
					Show(theSuggestions2);
				suggestionsBlurTimer2.start();
			}
	} ); 
	
	}

function suggestionMouseover(idx) {
	Debug('suggestionMouseover()');
	UpdateSuggestions(theSuggestions, idx);
	suggestionsBlurTimer.reset(); }

function suggestionMouseout() {
	Debug('suggestionMouseout()');
//	UpdateSuggestions(theSuggestions, -1);
	suggestionsBlurTimer.start(); }

function suggestionMouseclick(string) {
	Debug('suggestionMouseclick()');
	theInput.value = string;
	theInput.focus();
	Hide(theSuggestions); }

function suggestionMouseover2(idx) {
	Debug('suggestionMouseover2()');
	UpdateSuggestions(theSuggestions2, idx);
	suggestionsBlurTimer2.reset(); }

function suggestionMouseout2() {
	Debug('suggestionMouseout2()');
//	UpdateSuggestions(theSuggestions2, -1);
	suggestionsBlurTimer2.start(); }

function suggestionMouseclick2(string) {
	Debug('suggestionMouseclick2()');
	theInput2.value = string;
	theInput2.focus();
	Hide(theSuggestions2); }

function CalculateWidth(el){
  if(navigator && navigator.userAgent.toLowerCase().indexOf("msie") == -1){
    return el.offsetWidth - 1 * 2
  }else{
    return el.offsetWidth
  }
}

function resizeHandler(){
    theSuggestions.style.left = CalculateOffsetLeft(theInput) + "px";
    theSuggestions.style.top = CalculateOffsetTop(theInput) + theInput.offsetHeight - 1 + "px";
    theSuggestions.style.width = CalculateWidth(theInput) + "px";
    theSuggestions2.style.left = CalculateOffsetLeft(theInput2) + "px";
    theSuggestions2.style.top = CalculateOffsetTop(theInput2) + theInput2.offsetHeight - 1 + "px";
    theSuggestions2.style.width = CalculateWidth(theInput2) + "px";
}

// Show the debug window
function ShowDebug() {
  window.top.debugWindow =
      window.open("",
                  "Debug",
                  "left=0,top=0,width=300,height=700,scrollbars=yes,"
                  +"status=yes,resizable=yes");
  window.top.debugWindow.opener = self;
  // open the document for writing
  window.top.debugWindow.document.open();
  window.top.debugWindow.document.write(
      "<HTML><HEAD><TITLE>Debug Window</TITLE></HEAD><BODY><PRE>\n");
}

// If the debug window exists, then write to it
function Debug(text) {
  if (window.top.debugWindow && ! window.top.debugWindow.closed) {
    window.top.debugWindow.document.write(text+"\n");
  }
}
