/*-----------------------------*
 *    Autocomplete da busca    *
 *-----------------------------*/
/** Opcoes
 * 
 * searchInput      - Campo input que contem a query da busca												  (obrigatorio)
 * searchPageId     - id da pagina do lumis onde esta localizado o xml com os dados da busca				  (obrigatorio)
 * threshold        - Numero minimo de caracteres buscados no campo de nome que ativa o autocomplete 		  (Default = 3)
 * loadingIndicator - Elemento DOM que possui a imagem de indicador de carregamento dos dados do autocomplete (opcional) 
 * 
 */

// Construtor
function SearchAutocomplete(options) {
	this.searched = false;
	this.queries = new Array();
	this.searchInput = options.searchInput;
	this.searchPageId = options.searchPageId;
	this.threshold = (options.threshold != undefined) ? options.threshold : 3;
	this.loadingIndicator = (options.loadingIndicator != undefined) ? options.loadingIndicator : null;
	
	var sa = this;
	
	// Metodos privados
	function getSearchData() {
		var attrs = {
			pageId : sa.searchPageId,
			query : sa.searchInput.val() + "*"
		};
		
		if($.inArray(sa.searchInput.val(), sa.queries) == -1) {
			sa.queries.push(sa.searchInput.val());
			
			if(sa.loadingIndicator != null)
				sa.loadingIndicator.show();
			$.get("/wkm/xml/interface.jsp", attrs, function(result) {
				var obj = eval('(' + xml2json(result) + ')');
				
				sa.searched = true;
				if(sa.loadingIndicator != null)
					sa.loadingIndicator.hide();
				
				if(obj.data.itens != null) {
					var items = $.isArray(obj.data.itens.item) ? obj.data.itens.item : [obj.data.itens.item];
					var searchData = new Array();
					
					for(var i = 0; i < items.length; i++) {
						var item = items[i];
						var title = item.title;
						
						title = retirarAcentos(title);
						
						if(title.match(new RegExp(sa.searchInput.val(), "i")) != null)
							searchData.push(title);
						
						searchData = unique(searchData);
					}
					sa.searchInput.flushCache();
					sa.searchInput.autocomplete(searchData, {
						max: 10
					});
					//console.log(searchData);
				}
			});
		}
		else
			sa.searched = true;
	}
	
	// bind do evento de keyup do searchInput
	sa.searchInput.keyup(function() {
		if($(this).val().length >= sa.threshold && !sa.searched)
			getSearchData();
		
		if(sa.searched && $(this).val().length < sa.threshold) {
			sa.searched = false;
		}
	});
}



