var HPMAIS_autoComplete = new Class({
	initialize: function() {
		this.TAB = 'tab';
		this.ESC = 'esc';
		this.KEYUP = 'up';
		this.KEYDN = 'down';
		this.ENTER = 'enter';
		this.autoCompleteIndex=new Array();
		this.autoCompleteSelected=0;
		this.first=0;
		this.ultbusca='';
		this.autoComplete=new Array();
		var input = $$('input[hpmaisautocomplete]');
		input.each(function(el,i){
			el.index = 'HPMAISauto_completar'+i;
			this.autoComplete[el.index]=new Array();
			el.setAttribute("autocomplete","off");
			// keydown (fix firefox)
			if (window.event)
				el.addEvent('keydown',function (e) { return this.keydown(e); }.bind(this));
			else {
				el.addEvent('keypress',function(e) { return this.keydown(e); }.bind(this));
			}
			//keyup
			el.addEvent('keyup',function(e) { 
				var key = this.getKeyCode(e);
				switch(key)
				{
					case this.TAB:
					case this.ESC:
					case this.KEYUP:
					case this.KEYDN:
						return;
					case this.ENTER:
						if (!window.event) e.preventDefault();
						return false;
						break;
					default:
						this.buscar(el,el.getAttribute('hpmaisautocomplete'));
						return;
				}
			}.bind(this));
			el.addEvent('blur',function(e) { this.removeDiv(el); }.bind(this));
		},this);
	},
	keydown: function(e) {
		var key = this.getKeyCode(e);
		switch(key)
		{
			case this.TAB:
			case this.ENTER:
				if (this.autoCompleteSelected != 0){
					if (!window.event) e.preventDefault();
					this.execute($(this.autoCompleteSelected));
					return false;
				}
			break;
			case this.ESC:
				this.removeDivID(this.autoComplete[this.autoCompleteSelected]['index']);
				if (!window.event) e.preventDefault();
				return false;
			break;

			case this.KEYUP:
				this.highlightKey('up');
				if (!window.event) e.preventDefault();
				return false;
			break;

			case this.KEYDN:
				this.highlightKey('down');
				if (!window.event) e.preventDefault();
				return false;
			break;

		}
	},
	buscar: function(elem,url) {
		var strbusca=elem.value;
		if (this.ultbusca!=strbusca) {
			this.ultbusca=strbusca;
			var id=elem.index;
			if (strbusca.length>3) {
				var file=url+'?'+elem.getProperty('name')+'='+strbusca+'&cod='+(Math.ceil(Math.random()*99999));
				this.ajaxReq=new Request({
					url: file,
					method: 'get',
					initialize: function() { this.carregando('show',elem);  }.bind(this),
					onComplete: function(text,xmldata) { this.carregando('hide',elem); this.complete(xmldata,elem); }.bind(this),
					evalScripts: true,
					autoCancel: true
				}).send();
			} else {
				if ($chk($(id)))
					this.removeDiv(elem);
			}
		}
	},
	complete: function(xml,elem) {

		this.createDiv(elem);
		var id=elem.index;
		if ($chk($(id))) {
			$(id).empty();
			var ul = new Element('ul', {'class':'ul_autocompletar'});
			$(id).appendChild(ul);
			var itens = xml.getElementsByTagName('item');
			var count = itens.length;
			if (count>0) {
				for (var i=0;i<count;i++) {
					var label = unescape(itens[i].getAttribute("label"));
					var action = unescape(itens[i].getAttribute("action"));
					var opt = unescape(itens[i].getAttribute("opt")).toLowerCase();
					var iditem = unescape(itens[i].getAttribute("id"));
					var imgsrc = unescape(itens[i].getAttribute("imgsrc"));
					// configurando LI
					var IDli=id+'li_HPMAISautocompletar'+i;
					this.autoComplete[IDli]=new Array();
					this.autoComplete[IDli]['index']=id;
					this.autoComplete[IDli]['label']=label;
					this.autoComplete[IDli]['action']=action;
					this.autoComplete[IDli]['opt']=opt;
					this.autoComplete[IDli]['id']=iditem;
					this.autoComplete[IDli]['input']=elem;
					this.autoComplete[IDli]['imgsrc']=imgsrc;
					if (i==0) {
						this.first=IDli;
//						var styleClass='li_autocompletar_selected';
//						this.autoCompleteSelected=IDli;
					} else
						var styleClass='li_autocompletar';
					var li=new Element('li', {'class':styleClass});
					li.setAttribute('id',IDli);
					li.addEvent('mouseover',function(e){ this.highlightMouse(e,'over'); }.bind(this));
					li.addEvent('mouseout',function(e){ this.highlightMouse(e,'out'); }.bind(this));
					li.addEvent('mousedown',function(e){ this.selecionar(e); }.bind(this));
					// configurando A
					var a = new Element('a',{'href':'javascript:;'});
					a.addEvent('click',function(e){return false;});
					// acrescentar imagem
					a.set('html',label);
					
					li.appendChild(a);
					ul.appendChild(li);
				}
			} else {
				this.first=0;
				this.autoCompleteSelected=0;
				this.removeDivID(id);
//				var li=new Element('li', {'class':'li_autocompletar'});
//				ul.appendChild(li);
			}
		}
	},
	highlightMouse: function(e,tipo) {
		this.highlight(this.getOBJevent(e),tipo);
	},
	highlightKey: function(tipo) {
		if (this.autoCompleteSelected==0) {
			this.highlight($(this.first),'over');
		} else {
			if ($chk($(this.autoCompleteSelected))) {
				switch(tipo){
					case 'up':
						if($(this.autoCompleteSelected).parentNode.firstChild == $(this.autoCompleteSelected)){
							//this.highlight($(this.autoCompleteSelected).parentNode.lastChild,'over');
							this.highlight($(this.autoCompleteSelected),'out');
//							this.autoCompleteSelected=0;
						}else{
							this.highlight($(this.autoCompleteSelected).previousSibling,'over');
						}
					break;
					case 'down':
						if($(this.autoCompleteSelected).parentNode.lastChild == $(this.autoCompleteSelected)){
							this.highlight($(this.autoCompleteSelected).parentNode.firstChild,'over');
						}else{
							this.highlight($(this.autoCompleteSelected).nextSibling,'over');
						}
					break;
				}
			}
		}
	},
	highlight: function(elem,tipo) {
		if (elem.tagName.toLowerCase()=='li') {
			if (tipo=='over') {
				if ((this.autoCompleteSelected != elem.getAttribute('id')) && (this.autoCompleteSelected!=0)) {
					$(this.autoCompleteSelected).setProperty('class','li_autocompletar');
				}
				this.autoCompleteSelected=elem.getAttribute('id');
				styleClass='li_autocompletar_selected';
			} else if (tipo=='out') {
				styleClass='li_autocompletar';
				this.autoCompleteSelected=0;
			}
			elem.setProperty('class',styleClass);
		}
	},	
	selecionar: function(e) {
		var elem=this.getOBJevent(e);
		this.execute(elem);
	},
	execute: function(elem) {
		var id=elem.getAttribute('id');
		var index=this.autoComplete[id];
		if (index['opt']=='complete') {
			index['input'].value = index['action'];
		} else if (index['opt']=='link') {
			document.location.href=index['action'];
		} else if (index['opt'].substr(0,6)=='submit') {
			var form=index['opt'].split(":")[1];
			$(index['input']).value = index['action'];
			document.getElementById(form).submit();
		}
		this.removeDivID(index['index']);
	},
	createDiv: function(elem) {
		if (!$chk($(elem.index))) {
			var pos=elem.getCoordinates();
			var height=pos.height;
			var width=pos.width;
			var top=pos.top+height;
			var left=pos.left;
			var divbusca=new Element('div', {'id':elem.index,'class':'div_autocompletar','styles':{'width':width,'left':left,'top':top}});
			document.body.appendChild(divbusca);
			this.first=0;
			this.autoCompleteSelected=0;
		}
	},
	carregando: function(opt,elem) {
		if (opt=='show') {
			if ($chk($(elem.index))) {

			}
		} else if (opt=='hide') {
			if ($chk($(elem.index))) {

			}
		}
	},
	removeDiv: function(elem) {
		this.removeDivID($(elem).index);
	},
	removeDivID: function(div) {
		if ($chk($(div)))
			document.body.removeChild($(div));
		this.first=0;
		this.autoCompleteSelected=0;
	},
	getOBJevent: function(e) {
		var e  = (e) ? e : ((event) ? event : null);
		var el = (e.target) ? e.target : ((e.srcElement) ? e.srcElement : null);
		return el.parentNode;
	},
	getKeyCode: function(e) {
//		var e = e || event;
//		var k = e.keyCode || e.which;
		return e.key;
	}
	
});
HPMAIS_autoComplete.implement(new Options);
HPMAIS_autoComplete.implement(new Events);

var hpmais_autocomplete = {};
window.addEvent('load', function(){
	hpmais_autocomplete = new HPMAIS_autoComplete();
});


