var AutoCompleter = new Class({

	options: {
	},
	flagAjax: false,
	arrEntries: ['Test 1', 'Test 2'],

	initialize: function(el, options) {
		this.el = $(el);
		this.createListWrapper();
		this.el.addEvent('focus', function(event) { this.loadList(); }.bind(this));
		this.el.addEvent('click', function(event) { this.loadList(); }.bind(this));
		this.el.addEvent('blur', function(event) { if(this.wrapper.hasClass('hidden')) this.hideList()}.bind(this));
		this.el.addEvent('keyup', function(event) { this.handleEvent(event)}.bind(this));
	},

	displayList: function() {
		this.flagAjax = false;
		this.wrapper.removeClass('hidden');
		this.wrapperlist.empty();
		this.el_value = this.el.getValue().trim();
		if(!this.arrEntries.contains(this.el_value) && this.el_value !== '') {
			this.addListItem(this.el_value);
		}
		this.arrEntries.each(function(el) { this.addListItem(el);}.bind(this));
	},
	
	addListItem: function(ajaxtitle) {
		eintrag = new Element('li', {}).setHTML(ajaxtitle).inject(this.wrapperlist);
		eintrag.addEvent('click', function(event) {this.setInput(event);}.bind(this));
	},

	hideList: function() {
		this.wrapper.addClass('hidden');
	},

	loadList: function() {
		this.getList();
	},

	handleEvent: function(event) {
		event = new Event(event);
		if(event.key == 'esc') {
			this.hideList();
			return;
		}
		
		if(this.el_value == this.el.getValue().trim) {
			return;
		}
		
		this.el_value = this.el.getValue().trim();
		
		this.loadList();
	},

	setInput: function(event) {
		event = new Event(event);
		this.hideList();
		this.arrEntries.include(this.el_value);
		this.el.value = event.target.innerHTML;
	},

	getList: function() {
		if(this.flagAjax) {
			return;
		}
		this.flagAjax = true;
		this.displayList();
	},

	createListWrapper: function() {
		coord = this.el.getCoordinates();
		this.wrapper = new Element('div', {'class': 'autocompleter hidden', 'style': 'top: '+ (coord.bottom - 1) + 'px; left: ' + coord.left + 'px; width: ' + coord.width + 'px;'});
		this.wrapper.inject(document.body);
		this.wrapperlist = new Element('ul', {});
		this.wrapperlist.inject(this.wrapper);
	}
});

AutoCompleter.implement(new Options);
