/*--------------------------------------*
 *   Autocomplete de filtros de salas   *
 *--------------------------------------*/
/** Opcoes
 * 
 * categoryFilter   - Filtro de categorias de sala 		 													  (obrigatorio)
 * nameFilter       - Filtro pelo nome da sala			 													  (obrigatorio)
 * filterPageId     - id da pagina do lumis onde esta localizado o xml com os dados 						  (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) 
 * 
 */

function EnterpriseAutocomplete(options) {
	this.categories = new Array();
	this.names = new Array();
	this.searched = false;
	this.categoryFilter = options.categoryFilter;
	this.nameFilter = options.nameFilter;
	this.filterPageId = options.filterPageId;
	this.threshold = (options.threshold != undefined) ? options.threshold : 3;
	this.loadingIndicator = (options.loadingIndicator != undefined) ? options.loadingIndicator : null;
	
	var ea = this;
	
	// Metodos privados
	function getEnterpriseData() {
		var attrs = {
			pageId : ea.filterPageId
		};
		if(ea.categoryFilter.val() != '')
			attrs["categories"] = ea.categoryFilter.val();
		else if(ea.nameFilter.val() != '')
			attrs["name"] = ea.nameFilter.val();
		
		if((attrs.categories != undefined && $.inArray(ea.categoryFilter.val(), ea.categories) == -1) ||
		   (attrs.name != undefined && $.inArray(ea.nameFilter.val(), ea.names) == -1)) {
			
			if(ea.categoryFilter.val() != '')
				ea.categories.push(ea.categoryFilter.val());
			if(ea.nameFilter.val() != '')
				ea.names.push(ea.nameFilter.val());			
			
			if(ea.loadingIndicator != null)
				ea.loadingIndicator.show();
			$.get("/wkm/xml/interface.jsp", attrs, function(result) {
				var obj = eval('(' + xml2json(result) + ')');
				
				ea.searched = true;
				if(ea.loadingIndicator != null)
					ea.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 nome = item.name;
						
						nome = retirarAcentos(nome);
						searchData.push(nome);
						
						searchData = unique(searchData);
					}
					ea.nameFilter.flushCache();
					ea.nameFilter.autocomplete(searchData, {
						max: 10
					});
					console.log(searchData);
				}
			});
		}
		else
			ea.searched = true;
	}
	
	// bind do evento de keyup do nameFilter
	ea.nameFilter.keyup(function() {
		if($(this).val().length >= ea.threshold && !ea.searched && ea.categoryFilter.val() == '')
			getEnterpriseData();
		
		if(ea.searched && $(this).val().length < ea.threshold) {
			ea.searched = false;
		}
	});
	
	// bind do evento de change do categoryFilter
	ea.categoryFilter.change(function() {
		getEnterpriseData();
	});
}
