var AutoComplete = new Class ({
	options: {
		// the controller currently only supports single options, no lists
		types: '',
		targetType:'TEL',
		limit: 15,
		maxNumbers:0,
		insertName: true,
		allowSelect: true,
		referenceElement: null,
		freeInput: true,
		selectMessage:null,
		faqtitles:null,
		resultFunction:Class.empty,
		resultArea:null,
		resultCount:0,
		selectedRow:-1,
		currentResults: []
	},

	initialize: function(element, options) {
		element=$(element);

		// should be compatible with input[type=text] and textarea
		var type=element.getTag();
		if (type!="input" && type!="textarea") return false;

		this.setOptions(options);

		// prevent the field from doing it's own autocomplete
		this.options.currentResults = new Array();
		this.options.referenceElement=this.element=element;
		this.element.setAttribute('autocomplete','off');
		// prepare the div to speed up display
		this.resultArea=new Element('div');
		this.resultArea.addClass('numberList');
		this.selectedRow = -1;

		var resultpos=(this.options.referenceElement ? this.options.referenceElement.getCoordinates() : element.getCoordinates());
		leftpos=resultpos.left;

		this.resultArea.setStyles({
			position : "absolute",
			top    : (resultpos.bottom),
			left   : leftpos,
			'z-index' : 2,	
			width	: '305px'
		});

		new Element('p').setHTML('').injectInside(this.resultArea);
		this.resultArea.injectInside($(document.body));
		this.resultArea.setStyles({'display':'inline', 'visibility':'visible'});

		this.loadData();

		element.addEvent('keydown', function(evnt) {
			if(evnt.keyCode==13 && this.selectedRow!= -1) {
					evnt.preventDefault();
			}
		}.bindAsEventListener(this));
		element.addEvent('keyup', this.updateList.bindWithEvent(this));
//		element.addEvent('click', this.updateList.bindWithEvent(this));
//		element.addEvent('blur', this.killResult.bindWithEvent(this));

	},

	loadData : function() {
		var url = '/ajax/faq/gettitles/';
		new Ajax(url, {
			method: 'post',
			sgjson:true,
			windowSpinner: false,
			onComplete: function(data) {
				this.faqtitles = data;
				
				 
			}.bind(this)
		}).request();
	},

	updateList : function(evnt) {

		evnt.stop();
		this.options.currentResults = new Array();
		this.resultArea.setStyles({'display':'none', 'visibility':'hidden'});
		this.resultArea.empty();
		var body = new Element('ul', {'class':'unformatedList autocompleteList'}).injectInside(this.resultArea);
		var textToFind = this.element.getValue();
		if(textToFind.length<3) return;
		this.options.resultCount = 0;
		this.faqtitles.each(function(entry){
			var title = entry.title.toUpperCase();
			if(title.match(textToFind.toUpperCase()) && this.options.resultCount<10) {
				var currentLi = new Element('li',{'id':'completeLine_'+this.options.resultCount}).injectInside(body);
				new Element('div', {'class':'autoCompleteArticleName'}).setHTML(entry.title).injectInside(currentLi);
				new Element('div', {'class':'autoCompleteCategoryName'}).setHTML(entry.categoryname).injectInside(currentLi);
				new Element('input', {'type':'hidden', 'value':'/faq/article/'+entry.article_category_id+'/'+entry.linktitle+'/'}).injectInside(currentLi);
				
				currentLi.addEvent('click', function(evnt){ location.href = ( this.getElement('input').getValue()  ); });
				currentLi.addEvent('mouseenter', function(evnt){
					var target = evnt.target;
					if(evnt.target.nodeName=='DIV') target = evnt.target.up('li');
					this.selectRow(target.id.replace('completeLine_',''),true);
				}.bindAsEventListener(this));
				this.options.resultCount++;
				this.options.currentResults.push(entry);
			}
			 
		}.bind(this));
		this.resultCount = body.getElements('li').length;
		
		if(this.options.resultCount>0) this.resultArea.setStyles({'display':'inline', 'visibility':'visible'});

		
		if (evnt) {
			evnt.stop();
			if (this.reactToKey(evnt.key)) {
				evnt.preventDefault();
				return;
			}
		}
	},

	reactToKey: function(key) {
		
		switch(key) {
			case 'esc':
				this.killResult();
				return true;
				break;
			case 'up':
				this.selectRow(-1);
				return true;
				break;
			case 'down':
				this.selectRow(1);
				return true;
				break;
			case 'enter':
				if(this.selectedRow!=-1) this.passSelection();
				this.killResult();
				return true;
				break;
			default:
				return false;
		}
	},

	// change row selection (0=none, >0=up, <0=down)
	selectRow: function(direction, absolute) {

		var oldSelection=this.selectedRow;
		
		if (direction==0) {
			this.selectedRow=-1;
		} else {

			this.selectedRow += direction;

			if (this.selectedRow<0) this.selectedRow=this.resultCount-1;
			if ((this.selectedRow)>(this.resultCount-1)) this.selectedRow=0;
		}

		if (absolute) { this.selectedRow=direction; }

		var rows=this.resultArea.getElements("li");

		if (typeof oldSelection!='undefined' && oldSelection!=-1 && rows[oldSelection]) rows[oldSelection].removeClass('selectedRow');
		if (this.selectedRow!=-1 && $type(rows[this.selectedRow])) rows[this.selectedRow].addClass('selectedRow');
//		console.log(this.selectedRow);
	},

	// puts the selected contact into the text field
	passSelection: function() {
		var currentArticle = ((this.options.currentResults[this.selectedRow]));
		location.href = '/faq/article/'+currentArticle.article_category_id+'/'+currentArticle.linktitle+'/';

		this.element.focus();
	},

	// close the list
	killResult: function() {
		this.resultArea.setStyles({'display':'none', 'visibility':'hidden'});
//		this.listVisible=false;
		this.selectRow(0);
	}
});
AutoComplete.implement(new Options());