/**
 * @author Henrique Moreira
 */

//dando a propriedade de formatação para as Strings
String.prototype.formatar = function() {
	//passando para minusculo
	var retorno = this.toLowerCase();
	//removendo acentos
	retorno = retorno.replace(/[áàâãäÁÀÂÃÄ]/g,"a").replace(/[éèêëÉÈÊË]/g,"e").replace(/[íìîïÍÌÎÏ]/g,"i").replace(/[óòôõöÓÒÔÕÖ]/g,"o").replace(/[úùûüÚÙÛÜ]/g,"u").replace(/[çÇ]/g,"c").replace(/[ñÑ]/g,"n");
	//retirando caracteres irrelevantes (isto tambem tira espacos e trim)
	retorno = retorno.replace(/[^\w]/g,"");
	
	return retorno;
}
//dada a propriedade de retirar tags da string
String.prototype.noTag = function() {
	return this.replace(/<\/?[a-z]+>/g,"");
}

//function $(id) { return document.getElementById(id); }

/*
 * Objeto Suggest.
 * Cria a propriedade de um elemento de texto possuir o suggest do letras
 */
function Suggest(elemento) {
	//----------------------------------
	//Variaveis globais, privadas ou publicas / Chamada Inicial (Construtor)
	//----------------------------------
	
	//Variaveis PRIVADAS
	
	//elemento HTML de texto onde receberá a entrada
	var elemento = elemento;
	//vetor de caches já realizados
	var cacheBusca = new Array();
	//string de busca atual
	var strBusca = "";
	//busca real efetuada (formato do nome do txt)
	var buscaReal = "";
	//objeto XmlHttpRequest para realizar o AJAX
	var xmlhttp;
	//numero máximo de caracteres para a geração do TXT permutado
	var txtMax = 4;
	//numero de resultados atuais
	var numResultados = 0;
	//ultimo valor elemento analisado
	var valElemento = "";
	//referência ao próprio objeto
	var self = this;
	//item selecionado pelo teclado
	var opcaoSel = -1;
	//retorna o array de listagem atual
	var listagemAtual = null;
	//criando elemento que armazena os resultados
	var resultadosBox = document.createElement("div");
	var rotinaLag = null;
	var mouseInter;
	var tamanhoLI = 0;
	
	var eUL;
	
	//Variaveis PUBLICAS
	//estado do mouse em relação à div de resultados
	this.mouseResultados = false;
	
	//indica se o suggest se encontra habilitado ou não
	this.habilitado = true;
	
	//CONSTRUTOR
	novoObjeto();
	//dando propriedades ao elemento dos resultados
	resultadosBox.className = "sug_wrap";
	resultadosBox.id = "wrap_suggest";
	resultadosBox.onmouseover = function () { self.mouseResultados = true; }
	resultadosBox.onmouseout = function () { self.mouseResultados = false; }
	resultadosBox.style.width = elemento.offsetWidth + "px";

	document.body.appendChild(resultadosBox);
	
	//dando funcionalidades ao elemento de texto
	elemento.onkeyup = function(e) { self.buscar(e); };
	elemento.onfocus = function() { self.oFocus(); };
	elemento.onblur = function(){ self.oBlur(); } ;
	
	//tirando funcionalidades do elemento de texto
	elemento.setAttribute("autocomplete","off");
	
	//----------------------------------
	//Metodos Privados
	//----------------------------------
	
	//criando um objeto xmlhttp de acordo com o browser
	function novoObjeto(){
		try{
			xmlhttp = new XMLHttpRequest();
		}
		catch(ee){
			try{
				xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
			}
			catch(e){
				try{
					xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
				}
				catch(E){
					xmlhttp = false;
				}
			}
		}
	}
	
	//Pega a posicao de um elemento HTML
	function getPos(o) {
	    var bo, x, y, b; x = y = 0;
	    if(document.getBoxObjectFor) { //moz
	        bo = document.getBoxObjectFor(o);
	        x = bo.x; y = bo.y;
	    } else if (o.getBoundingClientRect) { //ie
	        bo = o.getBoundingClientRect();
	        x = bo.left; y = bo.top;
	        x += document.documentElement.scrollLeft;
	        y += document.documentElement.scrollTop;
	    } else {
	        while(o && o.nodeName != 'BODY') {
	            x += o.offsetLeft;
	            y += o.offsetTop;
	            if(window.opera) { //opera
	                x--;
	                y--;
	            } else { //resto
		            x++;
		            y++;
		        }
		        b = parseInt(document.defaultView.getComputedStyle(o,null).getPropertyValue('border-width'));
		        if(b > 0) { x += b; y += b; }
		        o = o.offsetParent;
			}
		}
		return { x:x, y:y }
	}

	//obtendo o timestamp atual da máquina
	//util na manipulação adequada do AJAX
	function UTCTime(){
		var atual = new Date();
 		return Date.UTC(atual.getFullYear(),atual.getMonth(),atual.getDate(),atual.getHours(),atual.getMinutes(),atual.getSeconds(),atual.getMilliseconds());
	}

	//funcao que chama o ajax apartir de parâmetros atuais
	function ajax(max) {
		clearTimeout(rotinaLag);
		rotinaLag = setTimeout( function() { self.abortar(); }, 7000);
		
		buscaReal = strBusca.replace(/\s/g,"").substr(0,max);

		//fazendo uma nova chamada ao ajax
		xmlhttp.open("GET", "http://cifraclub.terra.com.br/tv/proxy.php?p1="+buscaReal.charAt(0)+"&p2="+buscaReal , true);

		//Função para quando alterar o estado
		xmlhttp.onreadystatechange = function(){
			if (xmlhttp.readyState == 4){
				var status = 0;
				//finalizando com a rotina
				clearTimeout(rotinaLag);

				//Circundando BUG de abort do Firefox
				try
				{
					status = xmlhttp.status;
				}
				catch(e)
				{
					novoObjeto();
					return;
				}
				
				//caso seja uma página válida
				if(status == 200)
				{
					var texto = xmlhttp.responseText;
					//verificando se nao esta vazio
					if(texto) {
						//separa as linhas e as informações
						var partes = texto.split("\n");
						var listagem = new Array();
						var listagemBusca = new Array();
						
						for(var cont = 0;cont < partes.length;cont++) {
							var arr = partes[cont].split("||");
							if (arr.length == 2) {
								listagem.push(arr[1].replace(/(^\s+)(\s+$)/g, "").replace(/\s+/," "));
								listagemBusca.push(arr[0].replace(/(^\s+)(\s+$)/g, ""));
							}
						}
						
						//criando cache relativo a busca
						var novoCache = new Cache(buscaReal,listagem,listagemBusca);
					
						if (strBusca.length <= buscaReal.length) 
							mostrarResultado(novoCache.getListagem());
						else
							mostrarResultado(novoCache.getListaFiltrada(strBusca,true));
						
						cacheBusca.push(novoCache);
					}
					
					//verifica se é nescessario realizar novo ajax
					if(valElemento != elemento.value) {
						self.buscar();
					}
				}
				//caso retorne uma pagina inexistente
				else if(status == 404) {
					//criando um cache de pag inexistente
					var novoCache = new Cache(buscaReal,null,null);
					cacheBusca.push(novoCache);
					
					//1 caractere nao existem resultados
					if (buscaReal.length == 1) {
						numResultados = 0;
						resultadosBox.style.display = "none";
						/*try{ document.getElementById("sug_anuncio").style.visibility = "visible"; }
						catch(e) {}*/
					} 
					//caso contrário, tentar realizar uma busca 1 nivel abaixo
					else {
						//procurando por caches antecessores
						var cache, fazerAjax = true;
						var descTxtMax = -1;
						for (var cont = buscaReal.length - 1; cont >= 1; cont--) {
							cache = buscaCache(buscaReal.substr(0, cont));
							
							//verifica se o cache existe
							if (cache != null && !cache.isInexistente() && (!cache.isCompleto() || cont == buscaReal.length - 1)) {
								fazerAjax = false;
								mostrarResultado(cache.getListaFiltrada(strBusca,true));
								break;
							} 
							//resultado parcial
							else if (cache != null && !cache.isInexistente() && cache.isCompleto()) {
								mostrarResultado(cache.getListaFiltrada(strBusca,false));
								if(descTxtMax == -1)
									fazerAjax = false;
								break;
							} else if (cache == null && descTxtMax == -1 ) {
								descTxtMax = cont;
							}
							
						}
			
						if (fazerAjax) {
							if(descTxtMax == -1)
								ajax(buscaReal.length - 1);
							else
								ajax(descTxtMax);
								
						}
					}
				}
				// caso ocora algum erro... Abortar
				else if(status != 0)
				{
					inicialTime = UTCTime();
					setTimeout(function() { self.abortar() },5000);
				}

			}
		};

		try {
			xmlhttp.send(null);
		}
		catch(e) { }
	}
	
	
	//mostra no resultado no elemento de resultados do objeto
	function mostrarResultado(listagem) {
		opcaoSel = -1;
		listagemAtual = listagem;
		
		
		//verifica se existem elementos a serem listados
		if (listagem.length > 0) {
			numResultados = listagem.length;
			
			//posicionando div de resultados
			self.posResultados();
			resultadosBox.style.display = "block";
			/*try{ document.getElementById("sug_anuncio").style.visibility = "hidden"; }
			catch(e) {}*/
			
			//Demonstrando resultados por DOM
			eUL = document.createElement("ul");
			eUL.id = "ul-suggest";
			eUL.className = "sug_list";
			eUL.marginTop = "0px";
			var eLI;
			for (var cont = 0; cont < listagem.length; cont++) {
				contador = cont;
				eLI = document.createElement("li");
				eLI.id = "resultados"+cont;
				eLI.onmouseover = function() { self.oMouseOver(this) };
				eLI.onclick = function () { 
					resultadosBox.style.display = "none";
					
					if(this.firstChild.innerHTML.noTag().substr(0, 8) != 'parecido'){
						elemento.value = this.firstChild.innerHTML.noTag(); 
						document.getElementById('dns_artista').value = this.firstChild.id.noTag();
					}
					else{
						elemento.value = this.firstChild.innerHTML.noTag().substr(8);
						elemento.parentNode.lastChild.value = this.firstChild.id.noTag().substr(8);
						document.getElementById('dns_artista').value = this.firstChild.id.noTag();
					}
						
					return false;
				}
				if (listagem[cont].tipo != 2) 
					eLI.innerHTML = "<a href='#' id='"+ listagem[cont].dns +"'>" + listagem[cont].txt + "</a>";
					
				else {
					eLI.innerHTML = "<a href='#' id='"+ listagem[cont].dns +"'><small>parecido</small>" + listagem[cont].txt + "</a>";
					eLI.className = "sug_typo";
				}
				eUL.appendChild(eLI);
			}
			//adicionando lista de resultados à div
			resultadosBox.innerHTML = "";
			resultadosBox.appendChild(eUL);
			//obtendo o tamanho de visualização de cada linha do resultado
			tamanhoLI = eUL.firstChild.offsetHeight;
			
			if(listagem.length > 10)
				resultadosBox.style.height = (tamanhoLI * 10) + "px";
			else
				resultadosBox.style.height = "";
			
		} else {
			numResultados = 0;
			resultadosBox.style.display = "none";
			/*try{ document.getElementById("sug_anuncio").style.visibility = "visible"; }
			catch(e) {}*/
		}
	}
	
	//procura pela existencia do cache de busca
	function buscaCache(txtBusca) {
		for(var cont = 0;cont < cacheBusca.length;cont++) {
			if(txtBusca == cacheBusca[cont].getBusca()) {
				return cacheBusca[cont];
			}
		}
		return null;
	}
	
	//----------------------------------
	//Metodos Públicos
	//----------------------------------
	this.posResultados = function() {
		//posicionando div de resultados
		var posicaoElem = getPos(elemento);
		resultadosBox.style.top = (posicaoElem.y + elemento.offsetHeight) + "px";
		resultadosBox.style.left = (posicaoElem.x - 1) + "px";
	}
	
	this.enviaForm = function() {
		//desativando resultados
		resultadosBox.style.display = "none";
		/*try{ document.getElementById("sug_anuncio").style.visibility = "visible"; }
		catch(e) {}	*/
		
		if (opcaoSel != -1 && listagemAtual[opcaoSel].txt.noTag() == elemento.value) {
			window.location.href = "http://letras.terra.com.br/" + listagemAtual[opcaoSel].dns + "/";
			return false;
		}
		
		return true;
	}
	
	//inicia o processo de busca
	this.buscar = function(e) {	
		if(!self.habilitado) 
			return;
	
		var keynum;
		///obtendo o codigo da tecla
		try {
			keynum = (window.event) ? event.keyCode : e.which;
		} catch(e) {
			keynum = 0;	
		}
		//caso nao seja uma tela de setas
		if (keynum != 38 && keynum != 40 && keynum != 13) {
			//verificando nescessidade de sumir com caixa de resultados
			if(valElemento.formatar().search(eval("/^"+elemento.value.formatar()+"/")) == -1 &&
			   elemento.value.formatar().search(eval("/^"+valElemento.formatar()+"/")) == -1) {
				resultadosBox.style.display = "none";
				/*try{ document.getElementById("sug_anuncio").style.visibility = "visible"; }
				catch(e) {}*/
			}

			var valElementoTemp = elemento.value;
			
			//obtendo o formato adequado do texto inserido
			var novaBusca = valElementoTemp.formatar();
			
			//verificando se o valor esta vazio
			if (novaBusca.length > 0) {
				//procura se a busca ja foi realizada
				var cache = null;
				if (novaBusca.length <= txtMax) 
					cache = buscaCache(novaBusca);
				
				if (cache == null || cache.isInexistente()) {
					var base = (novaBusca.length > txtMax) ? txtMax : novaBusca.length;
					var fazerAjax = true;
					var descTxtMax = -1;
					var cacheAnt = null;
					
					//procurando por caches antecessores
					for (cont = base; cont >= 1; cont--) {
						cache = buscaCache(novaBusca.substr(0, cont));
						
						//verifica se o cache existe e está incompleto
						//cache pode ser completo se estiver no ultimo nivel
						if (cache != null && !cache.isInexistente() && (!cache.isCompleto() || cont == txtMax)) {
							fazerAjax = false;
							mostrarResultado(cache.getListaFiltrada(novaBusca,true));
							break;
						} 
						//testa mostrar um parcial
						else if (cache != null && !cache.isInexistente() && cache.isCompleto()) {
							mostrarResultado(cache.getListaFiltrada(novaBusca,false));
							if(descTxtMax == -1) 
								fazerAjax = false;
							break;
						}
						else if (cache == null && descTxtMax == -1) {
							descTxtMax = cont;
						} 
						
					}
					
					//verificando se ha a nescessidade de realizar o ajax
					if (fazerAjax) {
						//apenas fazer ajax com estados completados
						if (xmlhttp.readyState == 4 || xmlhttp.readyState == 0) {
							strBusca = novaBusca;
							valElemento = valElementoTemp;
							if(descTxtMax == -1)
								ajax(txtMax);
							else
								ajax(descTxtMax);
						}
					}
				}
				else {
					//pesquisa em cache encontrada, mostrar o cache
					mostrarResultado(cache.getListagem());
				}
			}
			else 
				if (novaBusca == "") {
					numResultados = 0;
					resultadosBox.style.display = "none";
					/*try{ document.getElementById("sug_anuncio").style.visibility = "visible"; }
					catch(e) {}*/
				}
			return true;
		} 
		//caso seja uma seta
		else if (keynum != 13) {
			if(resultadosBox.style.display == "block") {
				
				for (var cont = 0; cont < numResultados; cont++) {
					var classe = document.getElementById("resultados" + cont).className.split(" ");
					if(classe[0] == "sug_typo")
						document.getElementById("resultados" + cont).className = "sug_typo";
					else
						document.getElementById("resultados" + cont).className = "";
				}
				
				//seta para cima
				if(keynum == 38) {
					if (opcaoSel == 0 || opcaoSel == -1) {
						opcaoSel = numResultados - 1;
						resultadosBox.scrollTop = resultadosBox.scrollHeight;
					}
					else {
						opcaoSel--;
						var mT = resultadosBox.scrollTop;
						if(opcaoSel < Math.abs(mT) / tamanhoLI)
							resultadosBox.scrollTop = opcaoSel * tamanhoLI;
					}
				} 
				//seta para baixo
				else {
					if (opcaoSel == numResultados - 1 /*|| opcaoSel == -1*/) {
						opcaoSel = 0;
						resultadosBox.scrollTop = 0;
					}
					else {
						opcaoSel++;
						var mT = resultadosBox.scrollTop;
						if(isNaN(mT)) 
							mT = 0;
						if(opcaoSel >= Math.abs(mT) / tamanhoLI + 10)
							resultadosBox.scrollTop = mT + tamanhoLI;
					}
				}
				document.getElementById("resultados"+opcaoSel).className += " resultadoSel";
				elemento.value = listagemAtual[opcaoSel].txt.noTag();
				document.getElementById('dns_artista').value = listagemAtual[opcaoSel].dns.noTag();
			}
			return false;
		} else {
			resultadosBox.style.display = "none";
			/*try{ document.getElementById("sug_anuncio").style.visibility = "visible"; }
			catch(e) {}*/
		}
	}
	
	//funcao para tratar a seleçao do moude 
	this.oMouseOver = function(elem) {
		for (var cont = 0; cont < numResultados; cont++) {
			var classe = document.getElementById("resultados" + cont).className.split(" ");
			if(classe[0] == "sug_typo")
				document.getElementById("resultados" + cont).className = "sug_typo";
			else
				document.getElementById("resultados" + cont).className = "";
		}
		elem.className += " resultadoSel";
		opcaoSel = elem.id.replace(/[a-z]*/g,"");
	}
	
	//funcao para quando o elemento for ativado
	this.oFocus = function() {
		elemento.className = "input2";
		if (numResultados > 0 && self.habilitado) {
			resultadosBox.style.display = "block";
			/*try{ document.getElementById("sug_anuncio").style.visibility = "hidden"; }
			catch(e) {}*/
		}
	}
	
	//funcao para quando o elemento for desativado
	this.oBlur = function() {
		//só some com a div resultados caso o mouse não esteja encima do mesmo
		//isto evito o erro no click para selecionar um dos resultados
		if (!self.mouseResultados) {
			elemento.className = "input";
			resultadosBox.style.display = "none";
			/*try{ document.getElementById("sug_anuncio").style.visibility = "visible"; }
			catch(e) {}*/
		}
		else 
			elemento.focus();
	}
	
	//aborta chamada ajax
	this.abortar = function(){
		xmlhttp.abort();
		this.buscar();
	}
}

/*
 * Objeto para manipular caches e subcaches
 */
function Cache(p_busca, p_listagem, p_listagemBusca) {
	//------------------------------
	//Variaveis globais
	//------------------------------
	//filtros já realizados acima do nivel atual do cache
	var subCaches = new Array();
	
	//Limites
	var maxCache = 60;
	var maxListagem = 30;
	
	//Dados
	var busca = p_busca;
	var listagem = p_listagem;
	var listagemBusca = p_listagemBusca;
	
	var sugestoes = true;
	
	//------------------------------
	//Métodos
	//------------------------------
	//Algoritimo de aproximação de Strings de Levenshtein
	function levenshtein( str1, str2 ) {
	    var s, l = (s = str1.split("")).length, t = (str2 = str2.split("")).length, i, j, m, n;
	    if(!(l || t)) return Math.max(l, t);
	    for(var a = [], i = l + 1; i; a[--i] = [i]);
	    for(i = t + 1; a[0][--i] = i;);
	    for(i = -1, m = s.length; ++i < m;){
	        for(j = -1, n = str2.length; ++j < n;){
	            a[(i *= 1) + 1][(j *= 1) + 1] = Math.min(a[i][j + 1] + 1, a[i + 1][j] + 1, a[i][j] + (s[i] != str2[j]));
	        }
	    }
	    return a[l][t];
	}
	
	//funcao para marcar o texto
	function marcarTexto(texto,marcacao,dns) {
		//criando uma formatação do texto original	
		var correspondente = texto.formatar();
		var parte;
		
		//a marcação deve ser sempre menor
		if(texto.length < marcacao.length)
			return null;
		
		//verificando se o texto a marcar é um subtring do texte procurado
		var posicao = correspondente.search(eval("/" + marcacao + "/"));
		if(posicao != -1) {
			parte = texto.substr(0,posicao);
			var deslocamentoInicial = 0;
			while(parte.search(/[^\wÀ-ü]/) != -1) {
				parte = parte.replace(/[^\wÀ-ü]/,"a");
				parte += texto.charAt(++posicao);
			}
			while(texto.charAt(posicao).search(/[^\wÀ-ü]/) != -1)
				posicao++;
			
			var tamMarcacao = marcacao.length;
			parte = texto.substr(posicao, tamMarcacao);
			while(parte.search(/[^\wÀ-ü]/) != -1) {
				parte = parte.replace(/[^\wÀ-ü]/,"a");
				parte += texto.charAt(posicao + (++tamMarcacao) - 1);
			}
			while(texto.charAt(posicao+tamMarcacao).search(/[^\wÀ-ü]/) != -1)
				tamMarcacao++;
			
			var retorno = texto.substr(0,posicao) + "<b>" + texto.substr(posicao, tamMarcacao) + "</b>" + texto.substr(tamMarcacao + posicao);
			return { txt:retorno, dns:dns };
		}	
		return null;
	}
	
	//funcoes de retorno
	this.getBusca = function () {
		return busca;
	}
	this.getVListagem = function () {
		return listagem;
	}
	this.getVListagemBusca = function () {
		return listagemBusca;
	}
	this.getSugestoes = function () {
		return sugestoes;
	}
	
	//obtem listagem apartir da busca da classe
	this.getListagem = function () {
		var retorno = new Array();
		var tamRetorno = busca.length;
		var cont = 0;
		var strL, strB, stringBase;
		while (cont < listagem.length && retorno.length < maxListagem) {
			marcacao = marcarTexto(listagem[cont],busca,listagemBusca[cont]);
			if(marcacao != null)
				retorno.push(marcacao);
				
			cont++;
		}
		
		return retorno;
	}
	
	//filtra resultados armazenados em um cache
	this.getListaFiltrada = function(filtro,sugerir) {
		if (filtro.length > busca.length) {
			var listagem2 = null, listagemBusca2 = null;
			var mesmoNivel = false;
			var sCache = null;
			//subcaches só serão uteis se estiverem acima do nivel do cache
			//procurando sub-cache
			for (var cont2 = 0; cont2 < subCaches.length; cont2++) {
				if (subCaches[cont2] != null && subCaches[cont2].getBusca() == filtro.substr(0, subCaches[cont2].getBusca().length)) {
					sCache = subCaches[cont2];
					listagem2 = subCaches[cont2].getVListagem();
					listagemBusca2 = subCaches[cont2].getVListagemBusca();
					mesmoNivel = (subCaches[cont2].getBusca() == filtro);
				}
			}
		
			//verificando qual listagem sera considerada
			//a do Cache ou a do SubCache referente
			var listagemSC = (listagem2 == null) ? listagem : listagem2;
			var listagemBuscaSC = (listagemBusca2 == null) ? listagemBusca : listagemBusca2;
			
			var listagemFil = new Array();
			var listagemBuscaFil = new Array();
			var retorno = new Array();
			var cont = 0;
			var marcacao;
			
			while (cont < listagemBuscaSC.length) {		
				marcacao = marcarTexto(listagemSC[cont],filtro,listagemBuscaSC[cont]);
				if (marcacao != null) {
					listagemFil.push(listagemSC[cont]);
					listagemBuscaFil.push(listagemBuscaSC[cont]);
					if(retorno.length < maxListagem) retorno.push(marcacao);
				}
				
				cont++;
			} 
			
			//verificando se o subcache jah existe, para poder ser criado
			if (!mesmoNivel && listagem.length > 0) {
				//adicionando na lista
				subCaches.push(new Cache(filtro,listagemFil,listagemBuscaFil));
			}
			
			//caso hajam retornos...
			if (retorno.length > 0)
				return retorno;
			else if(sCache != null && !sCache.getSugestoes()) {
				return [];
			}
			//sem resultados, tentar sugerir algo
			else if (sugerir) {
				var retorno = new Array();
				var listagemForm;
				var maximoSug = (listagem.length > 200) ? 200 : listagem.length;
				
				for (cont = 0; cont < maximoSug; cont++) {
					listagemForm = listagem[cont].formatar();
					//não considerar resultados com muito menos caracteres
					if (listagemForm.length - filtro.length >= -2 && 
						levenshtein(listagemForm, filtro) / listagemForm.length < 0.30) {
						retorno.push({
							txt: listagem[cont],
							dns: listagemBusca[cont],
							tipo: 2
						});
						if (retorno.length == maxListagem) 
							break;
					}
				}
				if (sCache != null && retorno.length == 0) 
					sCache.setSugestoes(false);
					
				return retorno;
			}
		} 
		return [];
	}
	
	//verifica se o cache se encontra completo, ou não conseguiu retornar o max
	this.isCompleto = function() {
		return (listagem.length >= maxCache);
	}
	this.isInexistente = function() {
		return (listagem == null);
	}
	
	this.setSugestoes = function(sug) {
		sugestoes = sug;
	}
}

//Variavel de instancia do objeto do suggest
var suggestObj = null;

//Instanciação do objeto
function iniciar_sug() {
	if (suggestObj == null) {
		suggestObj = new Suggest(document.getElementById("q"));
		suggestObj.buscar();
		window.onresize = function(){
			suggestObj.posResultados();
		};
	}
}


