var GASVars = {
	span_id : 'opt_',
	input_id : 'query'
}

var GAutoSuggester = Class.create();
GAutoSuggester.prototype = {
	initialize : function(options){
		this.opts = Object.extend(Object.clone(GASVars), options || {});
		this.box = null;
		this.input = null;
		this._initEventListener();
	},
	hideBox : function(){
		this._getBox().hide();
	},
	autocomplete : function(i){
		$(this.opts.input_id).value = $(this.opts.span_id + i).innerHTML;
		this.hideBox();
	},
	_getBox : function(){
		if(this.box == null){
			this.box = new DialogBox({id:'gas_select', hasBorder : false, hideOnOut : true});
			this.box.setWidth($(this.opts.input_id).getWidth());
		}
		return this.box;
	},
	_onResponse : function(response){
		var _first = response.indexOf("(");
		var _last = response.lastIndexOf(")");	  
		var _text = response.substring(_first + 1, _last);	  
		var arr = eval(_text); 
		  
		if(arr != null && typeof(arr) != "undefined"){
			var str = new Array;
			var i = 0;
			var len = arr[1].length;
			str.push("<div class=\"gas_options\">");
			for(i=0; i<len; i++){
				str.push("<div style=\"padding-top:2px;\"><a class=\"common_link_blue\" href=\"javascript:void(0);\" onclick=\"gas.autocomplete(");
				str.push(i);
				str.push(")\"><span id=\"opt_");
				str.push(i);
				str.push("\">")
				str.push((arr[1][i])[0]);
				str.push("</span></a></div>");
			}
			str.push("<div align=\"right\"><a href=\"javascript:void(0);\" style=\"font-size:10px;\" onclick=\"gas.hideBox();\">close</a></div>");
		  		
			var _posXY = $(this.opts.input_id).cumulativeOffset();
			this._getBox().setContent(str.join(""));
			this._getBox().show(_posXY.left, _posXY.top + $(this.opts.input_id).getHeight());
		}
	},
	_onKeyup : function(){
		  var _URL = "/ap_autosuggester?q=" + encodeURIComponent($(this.opts.input_id).value);
		  var _this = this;
		  new Ajax.Request(_URL, {
		  		method : 'get',
		  		onSuccess : function(transport){
		  			_this._onResponse(transport.responseText);
		  		},
		  		onFailure : function(){
		  		}
		  });			
	},
	_initEventListener : function(){
		$(this.opts.input_id).observe("keyup", this._onKeyup.bind(this));
	}
}
