/* JAVASCRIPT */

// FUNCAO PARA CRIAR UM OBJETO ACTIVEX PARA CADA REQUISICAO
function CriaObjAjax(objAjax){
    try {
        objAjax = new ActiveXObject("Microsoft.XMLHTTP");
    }
    catch(e) {
        try {
            objAjax = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch(ex) {
            try {
                objAjax = new XMLHttpRequest();
            }
            catch(exc) {
                alert("Esse browser não tem recursos para uso do Ajax");
                objAjax = null;
            }
        }
    }
    return objAjax;
}

// FUNCAO PARA CARREGAR A PESQUISA
function fPesquisa(div, url) {
    var Ajax = CriaObjAjax('objAjax');
    if(Ajax){
        // pega o objeto DIV
        var objDiv = document.getElementById(div);
        // VAMOS USAR O METODO POST PARA NAO LIMITAR OS DADOS
        Ajax.open("POST", url, true);
        //Ajax.setRequestHeader("encoding", "ISO-8859-1");
        //Ajax.setRequestHeader("Content-Type", "text/html; charset=ISO-8859-1");
        Ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; text/html; charset=ISO-8859-1");
        // Ajax.setRequestHeader("content", "text/html; charset=ISO-8859-1");

        Ajax.onreadystatechange = function() {
            //enquanto estiver processando...emite a msg de carregando
            if(Ajax.readyState == 1) {
            //window.location = "#topo";
            //objDiv.style.display = "none";
            //objDiv.innerHTML = ' Carregando...';
            //objDiv.style.display = "block";
            }
            //após ser processado - chama função que vai varrer os dados
            if(Ajax.readyState == 4 ) {
                if(Ajax.responseText.length > 1) {
                    texto = (Ajax.responseText.replace(/\+/g," "));
                    objDiv.innerHTML = texto;
                    fScript(texto);
                    objDiv.style.overflow = 'auto';
                    objDiv.style.display = "block";
                //fScript(texto);
                }else{
                    //caso o arquivo esteja vazio emite a mensagem abaixo
                    objDiv.innerHTML = "";
                //objDiv.style.display = "none";
                }
            }
        }

        // somente para executar o ajax, nao precisa de parametros pois ja passei pela URL no Ajax.open
        Ajax.send(url);
    }
}

function fPegaDados(Texto){
    if (Texto.length >= 1){
        fPesquisa('divResult', 'search-preview.php?p='+Texto);
    }else{
        document.getElementById("divResult").style.display = "none";
    }
}

var POS = -1;
var nITEM = 15;
var dica = '';
var AuxTexto = '';

function setUpDown(Texto, event, q, objLinha) {
    if (q == 0){
        // Pegando o valor da Tecla
        var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
        //alert(POS);
        // Declarando a Variavel Anterior
        var ANT;

        // Se a tecla pressionada for down arrow (Seta para baixo)
        if(keyCode == 40) {

            if(POS >= (nITEM-1)) {
                POS = (nITEM-1);
            } else {
                POS++;
            }

            if (document.getElementById("div_"+POS)){
                // Seleciona a DIV
                document.getElementById("div_"+POS).style.backgroundColor = "#000066";
                document.getElementById("div_"+POS).style.color = "#FFFFFF";
                // Armazena a posição da DIV que será deselecionada
                ANT = eval(POS-1);
                // Se posição da DIV selecionada for diferente de -1 (Posição Inicial)
                if(ANT != -1) {
                    // Deseleciona a DIV
                    document.getElementById("div_"+ANT).style.backgroundColor = "";
                    document.getElementById("div_"+ANT).style.color = "#666666";
                }

                // Armazena o conteudo dela na variavel TEMP
                var TEMP = eval("TextoLiteral_"+POS);// document.getElementById("div_"+POS).innerHTML;
                // Atribui o valor da TEMP ao campo REFERENCIA
                document.getElementById("s").value = TEMP;

            }
        // Se a tecla pressionada for up arrow (Seta para cima)
        } else if(keyCode == 38) {


            if(POS <= 0) {
                POS = 0;
            } else {
                POS--;
            }

            if (document.getElementById("div_"+POS)){
                // Seleciona a DIV
                document.getElementById("div_"+POS).style.backgroundColor = "#000066";
                document.getElementById("div_"+POS).style.color = "#FFFFFF";
                // Armazena a posição da DIV que será deselecionada
                ANT = eval(POS+1);

                // Deseleciona a DIV
                document.getElementById("div_"+ANT).style.backgroundColor = "";
                document.getElementById("div_"+ANT).style.color = "#666666";
                // Armazena o conteudo dela na variavel TEMP
                var TEMP = eval("TextoLiteral_"+POS); //document.getElementById("div_"+POS).innerHTML;
                // Atribie o valor da TEMP ao campo REFERENCIA
                document.getElementById("s").value = TEMP;

            }
        } else {
            if(keyCode == 13) {

            }else{
                // Executa a BUSCA
                POS = -1;
                fPegaDados(Texto);
            }
        }
    }else{
        //alert('passou');
        if ((dica != '')&&(q == 4)){
            document.getElementById("s").value = Texto;
            document.getElementById("f1").submit();
            //document.getElementById("divResult").style.display = "none";
        }else{
            if (q == 1) {
                //alert(Texto);
                document.getElementById("s").value = Texto;
                document.getElementById("f1").submit();
                //document.getElementById("divResult").style.display = "none";
            }else{

                if (q == 3){

                    if (dica != ''){
                        //alert(AuxTexto);
                        document.getElementById("s").value = Texto;
                        document.getElementById("f1").submit();
                    }else{
                        document.getElementById("divResult").style.display = "none";
                    }

                }else{
            //document.getElementById(objLinha.id).style.backgroundColor = "#99FFFF";
            }
            }

        }

    }
}

// Pega JavaScript dentor do Ajax
function fScript(texto){
    // inicializa o inicio ><
    var ini = 0;
    // loop enquanto achar um script
    while (ini!=-1){
        // procura uma tag de script
        ini = texto.indexOf('<script', ini);
        // se encontrar
        if (ini >=0){
            // define o inicio para depois do fechamento dessa tag
            ini = texto.indexOf('>', ini) + 1;
            // procura o final do script
            var fim = texto.indexOf('</script>', ini);
            // extrai apenas o script
            codigo = texto.substring(ini,fim);
            // executa o script
            eval(codigo);
        }
    }
}

// FUNCAO PARA CARREGAR OS DADOS NO DIV
function carregar_anuncios(div, url) {
  var Ajax = CriaObjAjax('objAjax');
  if(Ajax){
	 // pega o objeto DIV
	 var objDiv = document.getElementById(div);
	 // VAMOS USAR O METODO POST PARA NAO LIMITAR OS DADOS
	 Ajax.open("POST", url, true);
	 //Ajax.setRequestHeader("encoding", "ISO-8859-1");
	 //Ajax.setRequestHeader("Content-Type", "text/html; charset=ISO-8859-1");
	 Ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; text/html; charset=ISO-8859-1");
	// Ajax.setRequestHeader("content", "text/html; charset=ISO-8859-1");

	 Ajax.onreadystatechange = function() {
		//enquanto estiver processando...emite a msg de carregando
		if(Ajax.readyState == 1) {
			//window.location = "#topo";
			objDiv.style.display = "none";
			objDiv.innerHTML = '<img src="imagens/ajax-loader.gif" align="absmiddle" /> Carregando...';
            objDiv.style.left = (document.getElementById('body').clientWidth - objDiv.offsetWidth) / 2 +"px";
			objDiv.style.display = "block";
		}
		//após ser processado - chama função que vai varrer os dados
		if(Ajax.readyState == 4 ) {
		   if(Ajax.responseText) {
				objDiv.innerHTML = Ajax.responseText;
				objDiv.style.overflow='visible';
                objDiv.style.left = (document.getElementById('body').clientWidth - objDiv.offsetWidth) / 2 +"px";
		   }
		   else {
			   //caso o arquivo esteja vazio emite a mensagem abaixo
			   objDiv.innerHTML = "-- Arquivo de conteudo vazio --";
		   }
		}
	 }
	 // somente para executar o ajax, nao precisa de parametros pois ja passei pela URL no Ajax.open
	 Ajax.send(url);
  }
}

// CARREGA COM METODO GET
function carregar_get(div, url) {
  var Ajax = CriaObjAjax('objAjax');
  if(Ajax){
	 // pega o objeto DIV
	 var objDiv = document.getElementById(div);
	 // VAMOS USAR O METODO GET
	 Ajax.open("GET", url, true);
	 //Ajax.setRequestHeader("encoding", "ISO-8859-1");
	 //Ajax.setRequestHeader("Content-Type", "text/html; charset=ISO-8859-1");
	 Ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; text/html; charset=ISO-8859-1");
	// Ajax.setRequestHeader("content", "text/html; charset=ISO-8859-1");

	 Ajax.onreadystatechange = function() {
		//enquanto estiver processando...emite a msg de carregando
		if(Ajax.readyState == 1) {
			//window.location = "#topo";
			objDiv.style.display = "none";
			objDiv.innerHTML = 'Carregando...';
			objDiv.style.display = "block";
		}
		//após ser processado - chama função que vai varrer os dados
		if(Ajax.readyState == 4) {
           Texto = Ajax.responseText;
		   if(Texto) {
			  objDiv.innerHTML = Texto;
			  objDiv.style.overflow = 'auto';
              fScript(Texto);
		   }
		   else {
			   //caso o arquivo esteja vazio emite a mensagem abaixo
               objDiv.style.display = "none";
			   objDiv.innerHTML = "-- Arquivo de conteudo vazio --";
		   }
		}
	 }
	 // somente para executar o ajax, nao precisa de parametros pois ja passei pela URL no Ajax.open
	 Ajax.send(url);
  }
}

function fechar(){

    document.getElementById('divAnuncios').innerHTML = "";
    document.getElementById('divAnuncios').style.display = 'none';

    document.getElementById('divContatos').style.display = 'none';
    document.getElementById('divContatos').innerHTML = "";

    document.getElementById('divMapa').style.display = 'none';
    document.getElementById('divMapa').innerHTML = "";
	
	document.getElementById('divCadastro').style.display = 'none';
	document.getElementById('divCadastro').innerHTML = "";

    document.getElementById('divFundo').style.display = 'none';

	if (document.getElementById('ulFiltro')) {
    	document.getElementById('ulFiltro').style.display = "block";
	}
	
	if (document.getElementById('divSimilares')) {
    	document.getElementById('divSimilares').style.display = "block";
	}

}
