 /**
 * Objeto Suggest. *nova* 
 * @author Victor Hugo e Henrique Moreira 
 * Cria a propriedade de um elemento de texto possuir o suggest do letras
 * Tipo 1 : ajax de artistas | tipo 2 : listagem dom + busca por trecho | 3 : listagem DOM | 4: set array
 */

function Suggest(elemento,tipo){
	
	//var HOME = 'http://cifraclub.terra.com.br/';
	var HOME = '/';
	var elemento = elemento;
	var cacheBusca = new Array(); //vetor de caches já realizados
	var cacheArray;
	var strBusca = ""; //busca atual
	var buscaReal = ""; //busca real efetuada (formato do nome do txt)
	var txtMax = 3; //numero máximo de caracteres para a geração do TXT permutado
	var numResultados = 0; //numero de resultados atuais
	var valElemento = ""; //ultimo valor elemento analisado
	var self = this;
	var isinit=false; // flag que verifica se array de dados já foram preenchidos
	var opcaoSel = -1; //item selecionado pelo teclado
	var listagemAtual = null; //array de listagem atual
	this.mouseResultados = false; //estado do mouse em relação à div de resultados
	var classe_padrao="frm";
	var tamanhoLI=21;
	var acao_onclick=''; // variavel com a função da ação se tiver exemplo : acao_onclick='alert(\'vtxt--vdns\');';
	var id=0; var min=0;
	var xmlhttp; var rotinaLag = null; //variaveis p/ ajax
	if(tipo==1){
		var objeto='suggestObjajax';
		novoObjeto();
		id=cria_box('sug_wrap-ajax',267);
	}else if(tipo==2){
		var objeto='suggestObjarray';
		id=cria_box('sug_wrap-array',250,'cor_2');
		var busca_trecho_anterior = new Array();
	}else if(tipo==3){
		var objeto='suggestObjarray';
		id=cria_box('sug_wrap-array',285);
	}else if(tipo==4){
		var objeto='suggestObjarray2';
		id=cria_box('sug_wrap-array2',285);
	}
	
	var resultadosBox=document.getElementById(id);
	resultadosBox.onmouseover = function () { self.mouseResultados = true; } //verifica se mouse esta sobre div de resultados
	resultadosBox.onmouseout = function () { self.mouseResultados = false; }	
	elemento.onkeyup = function(e) { self.buscar(e); }; //dando funcionalidades ao elemento de texto
	elemento.onfocus = function() { self.oFocus(); };
	elemento.onblur = function(){ self.oBlur(); } ;
	elemento.setAttribute("autocomplete", "off");
 

//Seta ação para clique e submit
this.seta_acao = function(acao){
	acao_onclick=acao;
}
//seta arrays no objeto quando lista vem do html
this.setArrays = function(listagem, listagemBusca){
	if(isinit==false){
		cacheArray = new Cache(strBusca,listagem,listagemBusca,tipo);
		isinit=true;
	}
	return false;
}
//seta arrays no objeto quando lista vem do html
this.setDOM = function(classe){
	if(isinit==false){
		var i,j;
		var listagem_array = new Array();
		var listagemBusca_array = new Array();
		var objetos=document.getElementsByTagName('a');
		var pattern = new RegExp('(^|\\s)' + classe+ '(\\s|$)');
		for(i=0;i<objetos.length;i++){
			 if(pattern.test(objetos[i].className)){
			 	listagemBusca_array.push(objetos[i].href);
			 	listagem_array.push(objetos[i].innerHTML.noTag());
			 }
		}
		cacheArray = new Cache(strBusca,listagem_array,listagemBusca_array,tipo);
		isinit=true;
	}
return false;
}

this.enviaForm = function(){// envia form para pagina do artista ou executa acao
	fecharSuggest(id);//desativando resultados
//	document.getElementById('q').value = document.getElementById('q').value + ' -site:forum.cifraclub.terra.com.br -site:guitarbattle.cifraclub.terra.com.br -site:formesuabanda.cifraclub.terra.com.br -site:audioware.cifraclub.terra.com.br';
	if(acao_onclick!=''){
		var txt,dns;
		if(opcaoSel == -1){
			txt=encodeURIComponent(addslashes(elemento.value));
			dns=0;
		}else{
			txt=encodeURIComponent(addslashes(listagemAtual[opcaoSel].txt.noTag()));
			dns=encodeURIComponent(listagemAtual[opcaoSel].dns);
		}
		self.executa_acao(txt,dns);
		return false;
	}else{		
		if(tipo!=2){
			if (opcaoSel != -1 && listagemAtual[opcaoSel].txt.noTag() == elemento.value) {
				if(tipo==1)
					window.location.href = HOME + listagemAtual[opcaoSel].dns;
				else
					window.location.href = listagemAtual[opcaoSel].dns ;
				return false;
			}
		}else{
			if(opcaoSel != -1){
				var i,x;
				x=document.getElementById('lpsug_wrap-array').childNodes;
				for(i=0; i<x.length; i++){
					if(x[i].className=='resultadoSel'){
						window.location.href = x[i].firstChild.href;
						return false;
					}
				}
			}
		}
	}
	return true;
}

//inicia o processo de busca
this.buscar = function(e){	

var listaop = document.getElementById("lp" + id);
var keynum;
try {
	keynum = (window.event) ? event.keyCode : e.which;
} catch(e) {
	keynum = 0;
}

if (keynum != 38 && keynum != 40 && keynum != 13){//caso nao seja uma tecla de setas
	//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";

	var valElementoTemp = elemento.value;
	var novaBusca = valElementoTemp.formatar();//obtendo o formato adequado do texto inserido
	if(tipo==3 && novaBusca.length ==2 )
		cacheArray.getListaFiltrada(strBusca,false);
	
	if (novaBusca.length > min){//verificando se o valor esta vazio
		var cache = null;//procura se a busca ja foi realizada
		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;
				}else if (cache != null && !cache.isInexistente() && cache.isCompleto()) {//testa mostrar um parcial
					mostrarResultado(cache.getListaFiltrada(novaBusca,false));
					if(descTxtMax == -1) 
						fazerAjax = false;
					break;
				}else if (cache == null && descTxtMax == -1){
					descTxtMax = cont;
				} 
			}
			if(fazerAjax){//verificando se ha a nescessidade de realizar o ajax
				strBusca = novaBusca;
				valElemento = valElementoTemp;
				if(tipo==1){
					//apenas fazer ajax com estados completados
					if (ajax.vez==null || ajax.vez=='undefined') {
						if(descTxtMax == -1)
							busca_ajax(txtMax);
						else
							busca_ajax(descTxtMax);
					}
				}else{
					try{
						mostrarResultado(cacheArray.getListaFiltrada(strBusca,false));
					}catch(ex){
						setTimeout("suggestObjarray2.buscar();",1500);
					}
				}
			}
		}else { //se cache existe
			mostrarResultado(cache.getListagem());
		}
						
		if(tipo==2){
			var str_valida=" ";
			var x=2; // numero minimo de resultados da busca normal para buscar por trecho
			str_valida=retorna_palavras_vali(elemento.value,3,3);
			if(str_valida==busca_trecho_anterior['trecho'] && str_valida !=" " && str_valida!=null){
				mostrarResultadoTrecho(busca_trecho_anterior['dns'],busca_trecho_anterior['txt']);
			}else{
				if(numResultados<=x && str_valida!=null && str_valida !=" "){
					busca_trecho(str_valida);
				}
			}
		}
	}else//valor esteja vazio 
		if (novaBusca == "") {
			numResultados = 0;
			//resultadosBox.style.display = "none";
			fecharSuggest(id);
		}
		return true;
	}else if (keynum != 13) {//caso seja uma seta
		if(resultadosBox.style.display == "block") {
			for (var cont = 0; cont < numResultados; cont++) {
				var classe = document.getElementById(tipo+"resultados" + cont).className.split(" ");
				if(classe[0] == "sug_typo")
					document.getElementById(tipo+"resultados" + cont).className = "sug_typo";
				else
					document.getElementById(tipo+"resultados" + cont).className = "";
			}
		//seta para cima
		if(keynum == 38) {
			if (opcaoSel == 0 || opcaoSel == -1) {
				opcaoSel = numResultados - 1;
				listaop.scrollTop = listaop.scrollHeight;
			}else{
				opcaoSel--;
				var mT = listaop.scrollTop;
				if(opcaoSel < Math.abs(mT) / tamanhoLI)
					listaop.scrollTop = opcaoSel * tamanhoLI;
				}
		}else {//seta para baixo
			if (opcaoSel == numResultados - 1 /*|| opcaoSel == -1*/) {
				opcaoSel = 0;
				listaop.scrollTop = 0;
			}else{
				opcaoSel++;
				var mT = listaop.scrollTop;
				if(isNaN(mT)) 
					mT = 0;
				if(opcaoSel >= Math.abs(mT) / tamanhoLI + 2){
					listaop.scrollTop = mT + tamanhoLI + mT;
				}
			}
		}
		
		if(document.getElementById(tipo+"resultados"+opcaoSel)==null)
			opcaoSel=0;
		document.getElementById(tipo+"resultados"+opcaoSel).className += " resultadoSel";
		if(tipo!=2)
			elemento.value = listagemAtual[opcaoSel].txt.noTag();
		}
		
		return false;
	}else{
		//fecharSuggest(id);
		self.enviaForm();
	}
}
//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;
	}
//funcao que chama o ajax apartir de parâmetros atuais
function busca_ajax(max){
	clearTimeout(rotinaLag);
	rotinaLag = setTimeout( function() { self.abortar(); }, 7000);
	buscaReal = strBusca.replace(/\s/g,"").substr(0,max);
	xmlhttp.open("GET", "/suggest/"+buscaReal.charAt(0)+"/"+buscaReal+".txt" , true);
	xmlhttp.onreadystatechange = function(){
	if (xmlhttp.readyState == 4){
		var status = 0;
		clearTimeout(rotinaLag);
		try	{status = xmlhttp.status;}catch(e){	novoObjeto();return;}	//caso seja uma página válida
				if(status == 200){
					var texto = xmlhttp.responseText;
					if(texto){
						var partes = texto.split("\n");//separa as linhas e as informações
						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, ""));
							}
						}
						var novoCache = new Cache(buscaReal,listagem,listagemBusca,tipo);//criando cache relativo a busca
						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();
					}
				}else if(status == 404){//caso retorne uma pagina inexistente
					var novoCache = new Cache(buscaReal,null,null,tipo);//criando um cache de pag inexistente
					cacheBusca.push(novoCache);
					//1 caractere nao existem resultados
					if (buscaReal.length == 1) {
						numResultados = 0;
						resultadosBox.style.display = "none";
					}else {//caso contrário, tentar realizar uma busca 1 nivel abaixo
						//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));
							if (cache != null && !cache.isInexistente() && (!cache.isCompleto() || cont == buscaReal.length - 1)) {//verifica se o cache existe
								fazerAjax = false;
								mostrarResultado(cache.getListaFiltrada(strBusca,true));
								break;
							}else if (cache != null && !cache.isInexistente() && cache.isCompleto()) {//resultado parcial
								mostrarResultado(cache.getListaFiltrada(strBusca,false));
								if(descTxtMax == -1)
									fazerAjax = false;
								break;
							}else if (cache == null && descTxtMax == -1 )
								descTxtMax = cont;
						}
						if (fazerAjax){
							if(descTxtMax == -1)
								busca_ajax(buscaReal.length - 1);
							else
								busca_ajax(descTxtMax);
						}
					}
				}else if(status != 0){// caso ocora algum erro... Abortar
					inicialTime = UTCTime();
					setTimeout(function() { self.abortar() },5000);
				}
		}
		};

		try {
			xmlhttp.send(null);
		}
		catch(e) { }	
}
/*
function resposta_ajax_txt(data){
	if(ajax.xmlhttp.status==200){
		if(texto){//verificando se nao esta vazio
			var partes = texto.split("\n");//separa as linhas e as informações
			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, ""));
				}
			}
			var novoCache = new Cache(buscaReal,listagem,listagemBusca,tipo);//criando cache relativo a busca
			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();
		}
	}else if(ajax.xmlhttp.status == 404) {//caso retorne uma pagina inexistente
		var novoCache = new Cache(buscaReal,null,null,tipo);//criando um cache de pag inexistente
		cacheBusca.push(novoCache);
		//1 caractere nao existem resultados
		if (buscaReal.length == 1) {
			numResultados = 0;
			resultadosBox.style.display = "none";
		}else {//caso contrário, tentar realizar uma busca 1 nivel abaixo
			//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));
				if (cache != null && !cache.isInexistente() && (!cache.isCompleto() || cont == buscaReal.length - 1)) {//verifica se o cache existe
					fazerAjax = false;
					mostrarResultado(cache.getListaFiltrada(strBusca,true));
					break;
				}else if (cache != null && !cache.isInexistente() && cache.isCompleto()) {//resultado parcial
					mostrarResultado(cache.getListaFiltrada(strBusca,false));
					if(descTxtMax == -1)
						fazerAjax = false;
					break;
				}else if (cache == null && descTxtMax == -1 )
					descTxtMax = cont;
			}
			if (fazerAjax){
				if(descTxtMax == -1)
					busca_ajax(buscaReal.length - 1);
				else
					busca_ajax(descTxtMax);
			}
		}
	}else if(ajax.xmlhttp.status != 0)// caso ocora algum erro... Abortar
		ajax.abortar();
}
*/
 
 this.oMouseOver = function(elem){ //funcao para tratar a seleçao do mouse
 	for(var cont = 0; cont < numResultados; cont++){
 		var classe = document.getElementById(tipo+"resultados" + cont).className.split(" ");
 		if(classe[0] == "sug_typo")
				document.getElementById(tipo+"resultados" + cont).className = "sug_typo";
			else
				document.getElementById(tipo+"resultados" + cont).className = "";
		}
		elem.className += " resultadoSel";
		opcaoSel = elem.id.replace(/[a-z]*/g,"");
		return false;
	}
	
this.oFocus = function() {//funcao para quando o elemento for ativado
	elemento.className = classe_padrao;
	self.posResultados(); 
	if (numResultados > 0) {
		resultadosBox.style.display = "block";
	}
	return false;
}
	
//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 = classe_padrao;
	fecharSuggest(resultadosBox.id);
}else
	elemento.focus();
}

//aborta chamada ajax
this.abortar = function(){
	ajax.abortar();
	this.buscar();
}

this.muda_class = function(classe){ //muda classe padrão do elemento
	classe_padrao=classe; return false;
}

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";
	return false;
}

//mostra no resultado no elemento de resultados do objeto
function mostrarResultado(listagem){
	opcaoSel = -1;
	listagemAtual = listagem;
	numResultados = listagem.length;
	if (numResultados > 0) {		
		self.posResultados();
		var eUL,eLI;
		var cabecalho = '<h3>Sugestões</h3> <a href="#" class="fechar" onclick="fecharSuggest(\''+id+'\'); return false;">x</a>';
		eUL = document.createElement("ul");
		eUL.className = "sug_list";
		eUL.id='lp'+id;
		eUL.marginTop = "0px";
		var i=1;
		for (var cont = 0; cont < numResultados; cont++){
			eLI = document.createElement("li");
			eLI.id = tipo+"resultados"+cont;
			eLI.onmouseover = function() { self.oMouseOver(this) };
			if(acao_onclick!='')
				eLI.onclick = new Function(objeto+".executa_acao(\'"+addslashes(encodeURIComponent(listagem[cont].txt.noTag()))+"\',\'"+encodeURIComponent(listagem[cont].dns)+"\'); return false;");
			else
				eLI.onclick = function () {fecharSuggest(id);} 
			if (listagem[cont].tipo != 2){
				if(tipo==1)
					eLI.innerHTML = "<a href='"+HOME + listagem[cont].dns + "'>" + listagem[cont].txt + "</a>";
				else
					eLI.innerHTML = "<a href='"+listagem[cont].dns + "'>" + listagem[cont].txt + "</a>";
			}else{
				eLI.innerHTML = "<a href='" + listagem[cont].dns + "'><small>parecido</small>" + listagem[cont].txt + "</a>";
				eLI.className = "sug_typo";
			}
			eUL.appendChild(eLI);
		}
		/*if(tipo==1){
			var rodape=document.createElement('center');
			rodape.className="sug_ver_mais";
			rodape.innerHTML=numResultados+' resultados encontrados (<a href="#" onclick="'+objeto+'.ver_mais(); return false;">ver mais</a>)<div class="sug_fim">'+numResultados+' resultados</div>';
		}else{
			var rodape=document.createElement('div');
			rodape.className="sug_fim";
			rodape.innerHTML=numResultados+" resultados";
		}*/
		//resultadosBox.innerHTML = cabecalho;
		resultadosBox.innerHTML = "";
		resultadosBox.appendChild(eUL);
		//resultadosBox.appendChild(rodape);
		
		tamanhoLI=21;
		if(numResultados > 10)
			eUL.style.height = (tamanhoLI * 10) + "px";
		else
			eUL.style.height = "";
		//exibirSuggest(id);
		resultadosBox.style.display='block';
	}else{
		fecharSuggest(id);
	}
}
this.executa_acao = function(vtxt,vdns){//executa acao passada pelo usuario, passando nome e txt do artista ou musica para a funçao
	fecharSuggest(id);
	var temp=acao_onclick;
	acao_onclick=acao_onclick.replace('vtxt',addslashes(vtxt)).replace('vdns',vdns);
	eval(acao_onclick);
	acao_onclick=temp;
	return false;
}
this.ver_mais = function(){//executa acao passada pelo usuario, passando nome e txt do artista ou musica para a funçao
	window.location = '/?q='+elemento.value;
	return false;
}
function mostrarResultadoTrecho(listagem,listagemBusca) {
var numResultadosTrecho;
var eLI,eUL,x,i;
var append=false;
var cont2=0;
if(numResultados==0)
	append = true;
opcaoSel = -1;
var num=listagem.length;
var texto_busca;
if(document.getElementById('lpsug_wrap-array')==null)
	x=null;
else
	x=document.getElementById('lpsug_wrap-array').childNodes;
		
if(x!=null && numResultados!=0){
	for (var cont1 = 0; cont1 < listagem.length; cont1++){
		for(i=0; i<x.length; i++){
			str=x[i].firstChild.innerHTML;
			texto_busca=html_entity_decode(listagemBusca[cont1]);				
			if(str.noTagSuggest().noTag()==texto_busca){
				listagemBusca.splice(cont1,1);
				listagem.splice(cont1,1);
			}
		}
	}
}
numResultadosTrecho = listagem.length;
if(append){
	eUL = document.createElement("ul");
	eUL.className = "sug_list";
	eUL.id='lp'+id;
	eUL.marginTop = "0px";
	eUL.style.height="210px";
}
for (var cont = 0; cont < listagem.length; cont++){
	eLI = document.createElement("li");
	eLI.id = tipo+"resultados"+(numResultados+cont);
	eLI.onmouseover = function() { self.oMouseOver(this) };
	eLI.onclick = function () {	resultadosBox.style.display = "none"; }
	eLI.innerHTML = '<a href="'+ HOME + dns +'/'+ listagem[cont] + '"><small>trecho</small>' + listagemBusca[cont] + '</a>';
	if(append)
		eUL.appendChild(eLI);
	else
		$id('lp'+id).appendChild(eLI);
}
resultadosBox=document.getElementById(id);
if(append){
    var rodape=document.createElement('div');
	rodape.className="sug_fim";
	rodape.innerHTML=numResultadosTrecho+numResultados+" resultados";
	var cabecalho = '<h3>Sugestões</h3> <a href="#" class="fechar" onclick="fecharSuggest(\''+id+'\'); return false;">x</a>';
	resultadosBox.innerHTML = "";
	//resultadosBox.innerHTML = cabecalho;
	resultadosBox.appendChild(eUL);
	resultadosBox.appendChild(rodape);
	numResultados=numResultadosTrecho;
}else{
	numResultados=numResultadosTrecho+numResultados;
	document.getElementById('sug_wrap-array').lastChild.innerHTML=numResultados+" resultados";	
}
tamanhoLI=21;
			if(numResultados > 10)
				eUL.style.height = (tamanhoLI * 10) + "px";
			else
				eUL.style.height = "";
exibirSuggest(id);
}
function html_entity_decode( string ){
  	var ret, tarea = document.createElement('textarea');
   	tarea.innerHTML = string;
   	ret = tarea.value;
return ret;
}

function retorna_palavras_vali(string_busca,minPalavras,minLetras) {//Retorna palavras validas em uma string
	var partes_string = new Array();
	var num_palavras=0;
	var num_palavras_validas=0;
	var string_retorno="";
	var i;
	partes_string=string_busca.split(" ");
	num_palavras=partes_string.length;
	for(i=0;i<num_palavras;i++){
		if(partes_string[i].length>=minLetras){
			string_retorno=string_retorno.concat(partes_string[i]+" ");
			num_palavras_validas=num_palavras_validas+1;
		}
	}
	if(num_palavras_validas>=minPalavras)
		return string_retorno;
	else
		return null;
}

function cria_box(id,width,cor){//cria box de resultado
  	var resultadosBox = document.createElement("div");
 	resultadosBox.className = "sug_wrap trans";
 	resultadosBox.id=id;
 	resultadosBox.display='block';
 	resultadosBox.style.height = "220px";
 	resultadosBox.style.width = width+"px";
 	if(cor=="cor_2"){
 		var divCor2=document.createElement("div");
 		divCor2.className="cor_2";
 		document.body.appendChild(divCor2);
 		divCor2.appendChild(resultadosBox);
 	}else
 		document.body.appendChild(resultadosBox);
 		
 	return id;
 }
 
function getPos(o){ //Pega a posicao de um elemento HTML
 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 }
}

function busca_trecho(trecho){ //Busca trecho valido via ajax
	if(id_artista!=null && id_artista!=undefined){
	if(xmlhttp==undefined)
		novoObjeto();
	else 
		xmlhttp.abort();
	
	xmlhttp.open("GET", "/suggest/ajax_busca_suggest_trecho.php?trecho="+trecho+"&id_artista="+id_artista , true);
	xmlhttp.onreadystatechange = function(){
	if (xmlhttp.readyState == 4){
		var status = 0;
		clearTimeout(rotinaLag);//finalizando com a rotina
		try{
			status = xmlhttp.status;//Circundando BUG de abort do Firefox
		}catch(e){
			novoObjeto();
			return;
		}
		if(status == 200){
			var data = xmlhttp.responseText;
			data = eval('(' + data + ')');
			if(data.status=='OK'){
				var listagem_trecho = new Array(); var listagemBusca_trecho = new Array();//arrays p/ resultados
				for(var i=0;i < data.musicas.length;i++){
					//listagem_trecho.push(data.musicas.id_musica[i].replace(/(^\s+)(\s+$)/g, "").replace(/\s+/," "));
					listagemBusca_trecho.push(data.musicas.nome[i].replace(/(^\s+)(\s+$)/g, ""));
				}
				busca_trecho_anterior = { trecho:data.trecho,txt:listagemBusca_trecho,dns:listagem_trecho };
				mostrarResultadoTrecho(listagem_trecho,listagemBusca_trecho);
			}
			return false;
			}
		}
	};
		try { xmlhttp.send(null); }catch(e) { }
	}
	return false;
}

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;}}}}
function UTCTime(){//obtendo o timestamp atual da máquina
	var atual = new Date();return Date.UTC(atual.getFullYear(),atual.getMonth(),atual.getDate(),atual.getHours(),atual.getMinutes(),atual.getSeconds(),atual.getMilliseconds());
}

}

//Objeto para manipular caches e subcaches
function Cache(busca, listagem, listagemBusca,tipo){
	var subCaches = new Array();//filtros já realizados acima do nivel atual do cache
	if(tipo==1){//Limites
		var maxCache = 60;
		var maxListagem = 30;
	}else if(tipo==2 || tipo==4){
		var resultado=listagem.length;
		var maxCache = resultado;
		var maxListagem = resultado;
	}else if(tipo==3){
		var maxListagem = 30;
		var resultado=listagem.length;
		var maxCache = resultado;
	}
	var sugestoes = true;
	//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];
	}
	
	function marcarTexto(texto,marcacao,dns){	
		var correspondente = texto.formatar();
		var parte;
		if(texto.length < marcacao.length)//a marcação deve ser sempre menor
			return null;
		var posicao = correspondente.search(eval("/" + marcacao + "/"));//verificando se o texto a marcar é um subtring do texte procurado
		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;
	}
	
	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
			for (var cont2 = 0; cont2 < subCaches.length; cont2++){//procurando sub-cache
				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++;
			}
			listagemSC=null;
			listagemBuscaSC=null;
			//verificando se o subcache jah existe, para poder ser criado
			if (!mesmoNivel && listagem.length > 0)
				subCaches.push(new Cache(filtro,listagemFil,listagemBuscaFil));//adicionando na lista

			//caso hajam retornos...
			if (retorno.length > 0)
				return retorno;
			else if(sCache != null && !sCache.getSugestoes())
				return [];
			else if (sugerir){//sem resultados, tentar sugerir algo
				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;
	}
}
function iniciar_sug(input,tipo){
if(typeof(suggestObjajax)=='undefined' || typeof(suggestObjarray)=='undefined' || typeof(suggestObjarray2)=='undefined'){// Se o objeto já foi criado não entra no if
	var elemento=document.getElementById(input);
	elemento.value='';
	if(tipo==1){
		suggestObjajax = new Suggest(elemento,tipo);
		suggestObjajax.buscar();
		window.onresize = function(){ suggestObjajax.posResultados();};
	}else if(tipo==2 || tipo==3){
		suggestObjarray = new Suggest(elemento,tipo);
		suggestObjarray.buscar();
		window.onresize = function(){ suggestObjarray.posResultados();};	
	}else if(tipo==4){
		suggestObjarray2 = new Suggest(elemento,tipo);
		suggestObjarray2.buscar();
		 window.onresize = function(){ suggestObjarray2.posResultados();};
	}
}
return false;
}

String.prototype.formatar = function(){//dando a propriedade de formatação para as Strings - minusculo, sem acento e carac irrelevantes
	var retorno = this.toLowerCase(); retorno = retorno.replace(/[áàâãäÁÀÂÃÄ]/g,"a").replace(/[éèêëÉÈÊË]/g,"e").replace(/[íìîïÍÌÎÏ]/g,"i").replace(/[óòôõöÓÒÔÕÖ]/g,"o").replace(/[úùûüÚÙÛÜ]/g,"u").replace(/[çÇ]/g,"c").replace(/[ñÑ]/g,"n"); retorno = retorno.replace(/[^\w]/g,"");
	return retorno;
}
String.prototype.noTag = function(){//dada a propriedade de retirar tags da string
	return this.replace(/<\/?[a-z]+>/g,"");
}
String.prototype.noTagSuggest = function() {//dada a propriedade de retirar tags do suggest (<parecido> <trecho>)
	return this.replace(/<[a-z]+>(parecido|trecho)<\/[a-z]+>/g,"");
}
function fecharSuggest(div){
	//$id('#'+div).animate({ opacity: 'hide' }, "fast"); return false;
	document.getElementById(div).style.display = "none";
}
function exibirSuggest(div){
	//$id('#'+div).css({"opacity": 0,"display": "block"}).fadeTo("fast", 1);
	document.getElementById(div).style.display = "block";
}
