
/**
 * Inserts a suggestion into the suggestionbox. This is fetched by the current selection.
 */
function StateSuggestions(oTextbox, oSuggestbox, oSelected, selectorOptions) {
	var oThis = this;
	this.textbox = oTextbox;
	this.suggestbox = oSuggestbox;
	this.selectorOptions = new Array(selectorOptions);	// assigned an array
	this.currentDB = selectorOptions[0];
	this.oldDB = selectorOptions[0];

	this.selectImg = oSelected;
	this.selectImg.onmouseup = function() {
		oSuggestbox.innerHTML = "";
		for(var i=0; i < selectorOptions.length; i++) {
				this.suggestions = new Array(selectorOptions);
				this.suggestions[i] = oSuggestbox.appendChild(document.createElement('div'));
				this.suggestions[i].className = 'suggestion';
				this.suggestions[i].innerHTML = selectorOptions[i];
				this.suggestions[i].onmouseover = function() { this.className='suggestion_over'; }
				this.suggestions[i].onmouseout = function() { this.className='suggestion'; }
				this.suggestions[i].onclick = function() {
					oThis.currentDB = this.innerHTML;
					oThis.textbox.style.backgroundImage = "url('pictures/"+this.innerHTML+".jpg')";
					oSuggestbox.style.display = "none";
				}
		}
		oSuggestbox.style.display = "block";
	}
/*
	this.dbSelector.selectedIndex = -1;
	this.dbSelector.onchange = function() {
		this.currentDB = this.options[this.selectedIndex].value;
		this.selectedIndex = -1;
		oTextbox.style.backgroundImage= 'url("pictures/'+this.currentDB+'.jpg")';
		oSelected.value = this.currentDB;
	}
*/
	this.getSuggestions();
}

StateSuggestions.prototype.getSuggestions = function () {
		var transport = (typeof XMLHttpRequest != 'undefined' ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP'));
		transport.open('GET', 'suggestions/'+this.currentDB, false);
		transport.send('');
		if (transport.status != 200) throw('Error ' + transport.status + ' (' + transport.statusText + ') trying to get ' + this.currentDB);

		this.suggestions = transport.responseText.split(", ");
}

StateSuggestions.prototype.requestSuggestions = function (oAutoSuggestControl) {
    var aSuggestions = [];
    var sTextboxValue = oAutoSuggestControl.textbox.value.toLowerCase();

		if (this.currentDB!=this.oldDB) {
			if (this.getSuggestions())
				this.oldDB = this.currentDB;
		}

    if (sTextboxValue.length > 0){
        for (var i=0; i < this.suggestions.length; i++) { 
            if (this.suggestions[i].toLowerCase().indexOf(sTextboxValue) == 0) {
                aSuggestions.push(this.suggestions[i]);
            } 
        }
    }

    oAutoSuggestControl.autosuggest(aSuggestions);
};



/**
 * An autosuggest textbox control.
 */
function AutoSuggestControl(oTextbox, oSuggestbox, oSelected, selectorOptions) {
    this.provider = new StateSuggestions(oTextbox, oSuggestbox, oSelected, selectorOptions);
    this.textbox = oTextbox;
    this.suggestbox = oSuggestbox;
    this.fucusing = false;
    this.cur = -1;

    this.init();
}

AutoSuggestControl.prototype.suggest = function (suggestion) {
	this.textbox.value = suggestion;
	this.suggestbox.style.display = 'none';
}

/**
 * Autosuggests one or more suggestions for what the user has typed.
 * If no suggestions are passed in, then no autosuggest occurs.
 */
AutoSuggestControl.prototype.autosuggest = function (aSuggestions) {
    if (aSuggestions.length == 1) {
        this.typeAhead(aSuggestions[0]);
    } else if (aSuggestions.length > 0) {
			this.suggestions = [];
			this.suggestbox.innerHTML = '';
			for(var i=0; i < aSuggestions.length; i++) {
				this.suggestions[i] = this.suggestbox.appendChild(document.createElement('div'));
				this.suggestions[i].className = 'suggestion';
				this.suggestions[i].id = i;
				this.suggestions[i].innerHTML = aSuggestions[i];
				this.suggestions[i].onclick = function() { oTextbox.suggest(this.innerHTML); }
				this.suggestions[i].onmouseover = function() {
					var iKeyCode = 39+parseInt(this.id)-parseInt(oTextbox.cur);
					oTextbox.highlightSuggestion(iKeyCode); 
				}
				this.suggestions[i].onmouseout = function() { this.className='suggestion'; }
				if (i==20) break;
	   }
		 this.suggestbox.style.display = 'block';
	}
};

/**
 * Handles Highlighting of suggestions.
 */
AutoSuggestControl.prototype.highlightSuggestion = function (iKeyCode) {
			if (this.cur>=0) this.suggestions[this.cur].className='suggestion';
			this.cur = parseInt(this.cur)+parseInt(iKeyCode)-39;
			if (this.cur>=this.suggestions.length)
				this.cur = this.suggestions.length-1;
			else if (this.cur < 0)
				this.cur = 0;
			this.suggestions[this.cur].className='suggestion_over';
}


/**
 * Initializes the textbox with event handlers for
 * auto suggest functionality.
 * @scope private
 */
AutoSuggestControl.prototype.init = function () {
    var oThis = this;
    this.textbox.onkeyup = function (oEvent) {
        if (!oEvent) oEvent = window.event;
        oThis.handleKeyUp(oEvent);
    };

    this.textbox.onkeydown = function (oEvent) {
        if (!oEvent) oEvent = window.event;
        if (this.focusing)
		oThis.handleKeyDown(oEvent);
    };

	onmousedown = function (oEvent) {
//		alert(oThis.suggestbox);
	};
};


/**
 * Handles keyup events.
 * @scope private
 * @param oEvent The event object for the keyup event.
 */
AutoSuggestControl.prototype.handleKeyUp = function (oEvent) {
    var iKeyCode = oEvent.keyCode;
    if (iKeyCode < 32 || (iKeyCode >= 33 && iKeyCode <= 46) || (iKeyCode >= 112 && iKeyCode <= 123)) {
		if ((this.suggestbox.style.display=='block') && (iKeyCode==40 || iKeyCode==38)) {
			this.highlightSuggestion(iKeyCode);	// up or down arrow
		} else if (iKeyCode==13) {
			this.suggest(this.suggestions[this.cur].innerHTML);		// return
		}
    } else {
        this.provider.requestSuggestions(this);
    }
};

AutoSuggestControl.prototype.handleKeyDown = function (oEvent) {
    var iKeyCode = oEvent.keyCode;
	var iLen = this.textbox.value.length;
	if (iKeyCode == 13) {
        this.selectRange(iLen, iLen);
		this.focusing = false;
	}
};


/**
 * Selects a range of text in the textbox.
 * @scope public
 * @param iStart The start index (base 0) of the selection.
 * @param iLength The number of characters to select.
 */
AutoSuggestControl.prototype.selectRange = function (iStart, iLength) {
    if (this.textbox.createTextRange) {
        var oRange = this.textbox.createTextRange(); 
        oRange.moveStart("character", iStart); 
        oRange.moveEnd("character", iLength - this.textbox.value.length);      
        oRange.select();
    } else if (this.textbox.setSelectionRange) {
        this.textbox.setSelectionRange(iStart, iLength);
    }
    this.textbox.focus();
    this.focusing = true;
}; 

/**
 * Inserts a suggestion into the textbox, highlighting the 
 * suggested part of the text.
 * @scope private
 * @param sSuggestion The suggestion for the textbox.
 */
AutoSuggestControl.prototype.typeAhead = function (sSuggestion) {
    if (this.textbox.createTextRange || this.textbox.setSelectionRange){
        var iLen = this.textbox.value.length; 
        this.textbox.value = sSuggestion; 
        this.selectRange(iLen, sSuggestion.length);
    }
	this.suggestbox.style.display = 'none';
};

