var Suggestion = new Class({

	Implements: [Events, Options],
	
	options: {
		onShow: function(){
			this.container.setStyle('display', '');	
			this.position();
		},
		onHide: function(){
			this.container.setStyle('display', 'none');	
		},
		duration: Fx.Durations.long,
		wait: false,
		define: '_ajax/',
		form: '',
		url: '',
		parent: [],
		value: ''
	},
	
	initialize: function(element, options){
		this.setOptions(options);
		this.element = $(element);
		this.Err = new LightBox(this.element, { closeBx:true });
		this.build();
		this.setup(true);
	},
	
	build: function(){
		if( !$('sgContainer') )
			this.container = new Element("ul", {'id': "sgContainer", 'class': "sgContainer"}).setStyle('display', 'none').inject(document.body);
		else
			this.container = $('sgContainer');
			
		this.element.addEvent('keyup', function(){this.makeList();}.bind(this));
	},
	
	show: function(){
		this.fireEvent('onShow');
	},
	
	hide: function(){
		this.fireEvent('onHide');
	},
	
	makeList: function(){
		var parent = this.element;
		var hide = this.hide.bind(this);
		var dimension = this.dimension.bind(this);
		var position = this.position.bind(this);
		var url = this.options.define + this.options.url;
		var Err = this.Err;
		var container = this.container;
		this.Request = new Request({
			url: url,
			onSuccess: function(txt) {
				var arr = txt.split("::");
				container.empty();
				if( arr != '' ){
					arr.forEach(function(txt){
						var row = new Element("li", {}).set('text', txt).inject(container);
						row.addEvents({
							'mouseenter': function(){ this.addClass('hover'); },
							'mouseleave': function(){ this.removeClass('hover'); },
							'click': function(){
								parent.value = this.get('text');	
								hide();
							}
						});
					});
					position();
					dimension();
				}
			},
			onFailure: function() {
				Err.receive('Sorry!! Connecting error please try again.');
			}
		});
		
		if(this.element.get('value').length > 0){
			var arr = this.Request.send( getValue($(this.options.form)) );
			this.show();
		}else{
			this.container.empty();
			this.hide();
		}
	},
	
	dimension: function() {
		var Coor = this.container.getCoordinates();
		var Parent = this.element.getCoordinates();
		var win_height = window.getHeight();
		var cur_height = win_height - Parent.bottom;
		if (Coor.height >= cur_height) {
			this.container.setStyle('height', cur_height - 10);
		} else {
			this.container.setStyle('height', 'auto');	
		}
	},
	
	setup: function(open) {
		var fn = open ? "addEvent" : "removeEvent";
		var position = this.position.bind(this);
		window[fn]("scroll", position)[fn]("resize", position);
	},
	
	position: function(){
		this.container.setStyles({
			'left': this.element.getCoordinates().left,
			'top': this.element.getCoordinates().bottom - 1,
			'width': this.element.getCoordinates().width - 2
		});
	}
	
});