/**	Adam Wentz 4/16/07 
	Requires MooTools w/ ajax + event **/

// CONSTANTS!
var USER_TYPING = 1;
var USER_ARROW_SELECT = 2;
var testRpcData = '<a href="/search/floop">Beads</a><a href="/search/garbage">Garbage</a><a href="/search/testing">Testing</a><a href="/search/other">Debris</a>';

var rpcSearchBar = new Class({
	initialize: function(formId, termsId, suggestId, maxSuggestions) {
		this.timeLastRequest = 0;
		this.requestWaitTime = 500; // milliseconds
		this.suggestionCache = {};
		this.formElem = $(formId);  // can i get this from the text input?
		this.termsElem = $(termsId); // text input 
		this.suggestElem = $(suggestId); // div to contain suggestions
		this.active = false;
		this.userState = USER_TYPING;
		this.selectedNode = null;
		this.selectedIndex = -1;
		this.nSuggestions = 0;
		this.nMaxSuggestions = maxSuggestions;
		this.termsElem.onkeyup = this.handleKeyUp.bindWithEvent(this);
		this.termsElem.setProperty('autocomplete', 'off');
	},

	activate: function() {
		this.selectedIndex = -1;
		this.active = true;
		///this.suggestElem.setStyle('visibility', 'visible');
		this.suggestElem.effects().start({'opacity':[0,1], 'width':[0, 250]});
		window.addEvent('click', this.deactivate.bindWithEvent(this));
	},	

	deactivate: function() {
		this.active = false;
		this.styleSelected(false);
		this.suggestElem.effects().start({'opacity':[1,0], 'width':[250,0]});
		//this.suggestElem.setStyle('visibility', 'hidden');
		window.removeEvent('click');
	},
	
	handleKeyUp: function(event) {
		if(true || this.active) {
			if(event.key == 'up' || event.key == 'down') {
				if(this.nSuggestions <= 0) {
					return;
				}
				this.userState = USER_ARROW_SELECT;
				if(this.selectedIndex != -1) {
					this.styleSelected(false);
				}
				if(event.key == 'up') {
					this.selectedIndex--;
					if(this.selectedIndex < 0) {
						this.selectedIndex = this.nSuggestions - 1;
					}
				} else {
					this.selectedIndex++;
					if(this.selectedIndex >= this.nSuggestions) {
						this.selectedIndex = 0;
					}
				}
				this.selectedNode = this.suggestElem.getChildren()[this.selectedIndex]
				this.styleSelected(true);	
				event.stop();
			}
			else if(event.key == 'enter') {
				if(this.userState == USER_ARROW_SELECT) {
					//TODO: submit form with hi-lit suggestion
					document.location = this.suggestElem.getChildren()[this.selectedIndex];
				}
			}
			else if(event.key == 'esc') {
				this.deactivate();
			} 
			else {
				this.userState == USER_TYPING;
				currentTime = new Date().getTime();
				if(this.timeLastRequest + this.requestWaitTime < currentTime) {
					this.requestSuggest(); 
					this.timeLastRequest = currentTime;
				}
			}
		} /* else {
			this.activate();
		} */
	},

	styleSelected: function(bSelected) {
		if(this.selectedNode != null) {
			if(bSelected) {	
				this.selectedNode.setStyle('background', '#F2EEB4');
			} else {
				this.selectedNode.setStyle('background', 'transparent');
			}
		}
	},
	
	requestSuggest: function() {
		// checkCache
		var key = this.termsElem.value;
		var cacheSuggest = this.getSuggestionFromCache(key);
		if(cacheSuggest == undefined) {	// send RPC request
			var query = 'action=searchSuggest&q=' + key;
			var req = new Ajax('/rpc?'+query, {	method : 'get',
							update: this.suggestElem,
							onComplete: function() { 
								this.setSuggestionCache(key);
								this.suggestionsUpdated(); }.bind(this)
							});
			req.request();
			
		} else {
			this.setSuggestions(cacheSuggest);
		}
	},

	suggestionsUpdated : function(key) {
		this.styleSelected(false);
		this.selectedIndex = -1;
		this.selectedNode = null;
		this.nSuggestions = this.suggestElem.getChildren().length;
		if(this.nSuggestions <= 0) { 
			if(this.active) {
				this.deactivate();
			}
		} else {
			if(!this.active) {
				this.activate();
			}
		}
	},

	setSuggestions: function(data) {
		// put zee data into zee suggestion div
		this.suggestElem.setHTML(data);
		this.suggestionsUpdated();
	},

	getSuggestionFromCache: function(key) {
		return this.suggestionCache[key];
	},

	setSuggestionCache: function(key) {
		//this.suggestionCache[key] = 'Not cachin yet';
	}
});
