
// Envia formulario
function validar(s){
	document.getElementById('a').value=''; 
    if (document.getElementById("s2") != null){
        if (s == "2") document.getElementById("s").value = document.getElementById("s2").value;
	}
    if (document.getElementById("s").value == ""){
        window.location = "http://www.listasa.com.br";
        return false;
    }else{
		n = Math.floor(Math.random()*30);
		document.getElementById("rd").value = n;
		filtra('0');
	}
}

// Filtra formulario para envio
function filtra(s){
    if (s == "0"){
    // vazio
    }
    if (s == "e"){
        document.getElementById("c").value = "";
        document.getElementById("a").value = "";
    }
    if (s == "c"){
        document.getElementById("a").value = "";
    }
    document.getElementById("divResult").style.display = "none";
    document.getElementById("f1").submit();
}

// Validando envio
function enviar(e, s){
    if (document.getElementById("s2") != null)
        if (s == "2") document.getElementById("s").value = document.getElementById("s2").value;
    document.getElementById("g").value = document.getElementById("s").value;
    var keypress = (window.event) ? e.keyCode : e.which;
    if (keypress == 13){
        validar(s);
    }
}

// Abre o mapa de endereco
function abre_mapa(end_cad, fantasia, c){
    if ((end_cad == "")||(end_cad == "NAO")){
        alert("Desculpe, este endereço está incompleto, não é possível mapear este endereço. (veja o endereco)");
        return false;
    }else{
        abre_janela('mapa.php?e='+end_cad+'&f='+fantasia+'&c='+c+'', 'MAPA', 635, 550, 1); //'+end_bai+',
    }
}

// Abrindo Janelas Filho
function abre_janela(wLink, wNome, wW, wH, wS){
    s = ",width="+wW+",height="+wH+",scrollbars="+wS;
    xWindow = window;
    xWindow = window.open( wLink , wNome, "fullscreen=0,toolbar=0,location=0,directories=0,status=1,menubar=0,resizable=1,modal=yes"+s);
    var xLargura = window.screen.width;
    var xAltura = window.screen.height;
    var Esquerda = ((xLargura / 4) - (wW / 4));
    var Topo = ((xAltura / 4) - (wH / 4));
    xWindow.moveTo(Esquerda, Topo);
    xWindow.focus();
    return xWindow;
}

// Abrindo Propagandas
function propaganda(arq, w, idcli){
    // Oculta filtros quando exibe anuncios no IE antigo, senao os Selects ficam por cima
    document.getElementById('ulFiltro').style.display = "none";

    var posTop = document.body.scrollTop + document.documentElement.scrollTop;
    var sizeHeight = document.body.scrollHeight;

    document.getElementById('divFundo').style.display = "block";
    document.getElementById('divFundo').style.height = sizeHeight+'px';

    document.getElementById('divAnuncios').style.display = "block";
    document.getElementById('divAnuncios').style.top = posTop+5+'px';
    //document.getElementById('divAnuncios').align = "center";
    //document.getElementById('divAnuncios').style.left = '5px';

    carregar_anuncios('divAnuncios', 'anuncios/'+arq);
    iconta.location = "url-propag.php?c="+idcli;

//document.getElementById('divAnuncios').style.left = (document.getElementById('body').clientWidth - document.getElementById('divAnuncios').offsetWidth) / 2 +"px";
}

// Abre tela de contato
function contato(idcli){

    // Oculta filtros quando exibe anuncios no IE antigo, senao os Selects ficam por cima
    document.getElementById('ulFiltro').style.display = "none";

    var posTop = document.body.scrollTop + document.documentElement.scrollTop;
    var sizeHeight = document.body.scrollHeight;

    document.getElementById('divFundo').style.display = "block";
    document.getElementById('divFundo').style.height = sizeHeight+'px';

    document.getElementById('divContatos').style.display = "block";
    document.getElementById('divContatos').style.top = posTop+5+'px';
    document.getElementById('divContatos').style.left = (document.getElementById('body').clientWidth - 500) / 2 +"px";

    carregar_get('divContatos', 'contato/contato.php?idcli='+idcli);

}

// PAGINANDO RESULTADOS
function paginas(i){
    document.getElementById("i").value = i;
    filtra('');
}

// Funcao para contar letras em um input
function conta_letras(Obj){
    var ObjTexto = Obj.value;
    if (ObjTexto.length >= 500){
        Obj.value = ObjTexto.substring(0, 500);
    }
    ObjTexto = ObjTexto.substring(0, 500);
    document.getElementById("contador").value = ObjTexto.length + '/500';
}

// Funcao de mascaras
function fMaskText(ObjMask, StrMask){
    /* determinha o numero maximo de caracteres aceitos no input */
    ObjMask.maxLength = StrMask.length;

    var i = ObjMask.value.length;
    var saida1 = "#";
    var saida2 = " ";
    var texto = StrMask.substring(i);
    var t = texto.substring(0,1);

    if ((t != saida1)&&(t != saida2)) {
        if(t == ")") {
            ObjMask.value += ") ";
        } else {
            if(t == "_") {
                ObjMask.value += " ";
            } else {
                ObjMask.value += t;
            }
        }
    }
}

// Recarrega imagem de codigo
function fCaptcha(){
    new_img  = new Image;
    n = Math.floor(Math.random()*10000000);
    new_img.src = "imagens/img-sec.php?n="+n;
    document.getElementById("img_seg").src = new_img.src;
    new_img = null;
}

// Validar formulario de Contato
function valida_contato(){
    if (document.getElementById("nome").value == ""){
        alert("O Campo [Nome] deve ser preenchido.");
        document.getElementById("nome").focus();
        return false;
    }
    if (document.getElementById("email").value == ""){
        alert("O Campo [Email] deve ser preenchido.");
        document.getElementById("email").focus();
        return false;
    }
    if (document.getElementById("assunto").value == ""){
        alert("Coloque o assunto");
        document.getElementById("assunto").focus();
        return false;
    }
    if (document.getElementById("obs").value == ""){
        alert("Coloque um breve comentário sobre o assunto");
        document.getElementById("obs").focus();
        return false;
    }
    if (document.getElementById("codigo").value == ""){
        alert("Coloque o codigo da figura ao lado");
        document.getElementById("codigo").focus();
        return false;
    }
    if (!confirm("Atenção:\n\n Os dados foram conferidos, deseja enviar ?")){
        return false;
    }else{
        var codcli 	= document.getElementById("codcli").value;
        var nome 	= document.getElementById("nome").value;
        var email 	= document.getElementById("email").value;
        var fone 	= document.getElementById("fone").value;
        var assunto = document.getElementById("assunto").value;
        var obs 	= document.getElementById("obs").value;
        var codigo 	= document.getElementById("codigo").value;
        carregar_get('divContatos', 'contato/contato.php?codcli='+codcli+"&nome="+nome+"&email="+email+"&fone="
            +fone+"&assunto="+assunto+"&obs="+obs+"&codigo="+codigo);
    }
    return false;
}

// Abrir mapa google
function abre_mapa(cod_cad){
    if (cod_cad == ""){
        alert("Desculpe, este endereço está incompleto, não é possível mapear este endereço. (veja o endereco)");
        return false;
    }else{
        //abre_janela('mapa.php?cod_cad='+cod_cad+'', 'MAPA', 635, 550, 1); //'+end_bai+',
        // Oculta filtros quando exibe anuncios no IE antigo, senao os Selects ficam por cima
        document.getElementById('ulFiltro').style.display = "none";

        var posTop = document.body.scrollTop + document.documentElement.scrollTop;
        var sizeHeight = document.body.scrollHeight;

        document.getElementById('divFundo').style.display = "block";
        document.getElementById('divFundo').style.height = sizeHeight+'px';

        document.getElementById('divMapa').style.display = "block";
        document.getElementById('divMapa').style.top = posTop+5+'px';
        document.getElementById('divMapa').style.left = (document.getElementById('body').clientWidth - 635) / 2 +"px";

        carregar_get('divMapa', 'mapa.php?cod_cad='+cod_cad);
    }
}

//***** GOOGLE MAPS INICIO ******************************************************//

var mapaobj;
var geocoder;
var nivelZoom = [];
nivelZoom[0] = 2;
nivelZoom[1] = 8;
nivelZoom[2] = 9;
nivelZoom[3] = 10;
nivelZoom[4] = 12;
nivelZoom[5] = 13;
nivelZoom[6] = 14;
nivelZoom[7] = 15;
nivelZoom[8] = 16;

function inicializa() {
    mapaobj = new GMap2(document.getElementById("map_canvas"));
    //mapaobj.setCenter(new GLatLng(34, 0), 8);
    geocoder = new GClientGeocoder();
}

var endereco = "";
var tipo_mapa = "";

function realizaConsulta(end, tmap) {
    endereco = end;
    tipo_mapa = tmap;
    geocoder.getLocations(endereco, resolverEnderecos);
}

function resolverEnderecos(resposta) {

    mapaobj.clearOverlays();

    if (!resposta || resposta.Status.code != G_GEO_SUCCESS) {
        alert("Não foi possivel localizar o endereco solicitado");
        alert("Código de erro: " +  resposta.Status.code);
    } else {

        var num_resultados = resposta.Placemark.length;
        var alvo = document.getElementById("locais");

        listarLocais(alvo, resposta.Placemark);

        if (num_resultados > 1) {
            alert('A sua consulta retornou resultados ambíguos.' +
                '\nEscolha a localidade mais adequada a consulta.');
        } else {
            var local = resposta.Placemark[0];
            var ponto = local.Point.coordinates;
            var acc = resposta.Placemark[0].AddressDetails.Accuracy;

            if ((tipo_mapa == "cad")
                || (tipo_mapa == "end")
                || (tipo_mapa == "cod")) {

                centralizaMapa(ponto[1],ponto[0],resposta.Placemark[0].address, acc);
            } else {
                centralizaMapa(endereco, resposta.Placemark[0].address, acc);
            }

        }
    }
}

function listarLocais(alvo, placemark) {

    alvo.innerHTML = "A pesquisa retornou " +
    placemark.length + " resultado(s):<br>";

    for (var i=0; i<placemark.length; ++i) {

        var uf = placemark[i].AddressDetails.Country.AdministrativeArea.AdministrativeAreaName;
        var acc = placemark[i].AddressDetails.Accuracy;
        var p = placemark[i].Point.coordinates;
        var info = placemark[i].address;

        alvo.innerHTML +="<a href='javascript:centralizaMapa(" + p[1] +
        "," + p[0] + ",\"" + info + "\", " + acc +
        ")'>" + placemark[i].address +"</a><br />";
    }
}

function centralizaMapa(x, y, info, acc) {

    document.getElementById("map_canvas").style.display = 'block';

    var p = new GLatLng(x, y);
    var zoom = nivelZoom[acc];

    mapaobj.setCenter(p,16);

    marcador = new GMarker(p);
    mapaobj.addOverlay(marcador);
    mapaobj.addControl(new GSmallMapControl());
    mapaobj.addControl(new GMapTypeControl());

    marcador.openInfoWindowHtml("<b>" + info + "</b>");
}

// ***** GOOGLE MAPS FIM *******************************************//

// Funcao para enviar pesquisa quando clica nas sugestoes
function sugere(s){
    document.getElementById("s").value = s;
    if (document.getElementById("s2") != null)
        document.getElementById("s2").value = s;
    validar();
}

// Abre tela de cadastro gratis e edicao
function fCadastro(State){

    // Oculta filtros quando exibe anuncios no IE antigo, senao os Selects ficam por cima
    if (document.getElementById('ulFiltro')){
        document.getElementById('ulFiltro').style.display = "none";
    }

    var posTop = document.body.scrollTop + document.documentElement.scrollTop;
    var sizeHeight = document.body.scrollHeight;
    var sizeWidth = document.getElementById('body').clientWidth;

    document.getElementById('divFundo').style.display = "block";
    document.getElementById('divFundo').style.height = sizeHeight+'px';

    document.getElementById('divCadastro').style.display = "block";
    document.getElementById('divCadastro').style.top = posTop+5+'px';
	
	if (State == "dsInsert") {
		document.getElementById('divCadastro').style.width = "650px";
		document.getElementById('divCadastro').style.left = (sizeWidth - 650) / 2 +"px";
	
		carregar_get('divCadastro', 'cadastro-gratuito.php?dsState='+State);
	}else{
		if (State == "dsLogin") {
			document.getElementById('divCadastro').style.width = "400px";
			document.getElementById('divCadastro').style.left = (sizeWidth - 400) / 2 +"px";
	
			carregar_get('divCadastro', 'cadastro-gratuito-login.php');	
		} else {
			if (State == "dsEdit") {
				document.getElementById('divCadastro').style.width = "650px";
				document.getElementById('divCadastro').style.left = (sizeWidth - 650) / 2 +"px";
	
				carregar_get('divCadastro', 'cadastro-gratuito-editar.php');	
			} else {
				if (State == "dsEmail") {
					var w = 550;
					document.getElementById('divCadastro').style.width = w+"px";
					document.getElementById('divCadastro').style.left = (sizeWidth - w) / 2 +"px";
	
					carregar_get('divCadastro', 'contato-com-a-listasa.php');	
				} else {
					if (State == "dsAnuncia") {
						var w = 550;
						document.getElementById('divCadastro').style.width = w+"px";
						document.getElementById('divCadastro').style.left = (sizeWidth - w) / 2 +"px";
		
						carregar_get('divCadastro', 'anuncie-na-listasa.php');	
					} else {
						if (State == "dsSobre") {
							var w = 450;
							document.getElementById('divCadastro').style.width = w+"px";
							document.getElementById('divCadastro').style.left = (sizeWidth - w) / 2 +"px";
			
							carregar_get('divCadastro', 'sobre-a-listasa.php');	
						} else {
							if (State == "dsTrabalhe") {
								var w = 600;
								document.getElementById('divCadastro').style.width = w+"px";
								document.getElementById('divCadastro').style.left = (sizeWidth - w) / 2 +"px";
				
								carregar_get('divCadastro', 'trabalhe-com-a-gente.php');	
							}	
						}
					}
				}
			}
		}
	}

}

// Funcao para verificar formulario de cadastro gratuito
	function fConfirma(){
	
		if (document.getElementById("cod_ati").value == ""){
			alert('Por favor, escolha uma atividade.');
			document.getElementById("cod_ati").focus();
			return false;
		}
	
		if ((!document.getElementsByName("pessoa")[0].checked)&&(!document.getElementsByName("pessoa")[1].checked)){
			alert("Escolha o tipo pessoa física ou jurídica.");
			document.getElementsByName("pessoa")[0].focus();
			return false;
		}
	
		if (document.getElementById("cpf_cnpj").value == ""){
			if (document.getElementsByName("pessoa")[0].checked){
				document.getElementById("cpf_cnpj").value = "000.000.000-00";
			}else document.getElementById("cpf_cnpj").value = "00.000.000/0000-00";
		}
	
		if (document.getElementById("nome").value == ""){
			alert("O Campo [Nome] deve ser preenchido.");
			document.getElementById("nome").focus();
			return false;
		}
	
		if (document.getElementById("fantasia").value == ""){
			alert("O Campo [Fantasia] deve ser preenchido.");
			document.getElementById("fantasia").focus();
			return false;
		}
	
		if (document.getElementById("contato").value == ""){
			document.getElementById("contato").value = "SEM CONTATO";
		}
		
		if (document.getElementById("end_cad").value == ""){
			alert("Coloque o endereço!");
			document.getElementById("end_cad").focus();
			return false;
		}
		
		if (document.getElementById("end_bai").value == ""){
			alert("Coloque o bairro!");
			document.getElementById("end_bai").focus();
			return false;
		}
	
		if (document.getElementById("end_est").value == ""){
			alert('Selecione um estado!');
			document.getElementById("end_est").focus();
			return false;
		}
	
		if (document.getElementById("end_cid").value == ""){
			alert('Selecione uma cidade!');
			document.getElementById("end_cid").focus();
			return false;
		}		
	
		
	
		if (document.getElementById("end_cep").value == ""){
			document.getElementById("end_cep").value = "00000-000";
		}
	
		if (document.getElementById("senha").value == ""){
			document.getElementById("senha").value = "SEMSENHA";
		}
	
		if (!document.getElementById("contrato").checked){
			alert("Para continuar você deve aceitar os termos de cadastro");
			document.getElementById("contrato").focus();
			return false;
		}
	
		if (!confirm("Atenção:\n\n Os dados foram conferidos, deseja confirmar este cadastro ?")){
			return false;
		}
	}
	
	function f_auto(){
		if (document.getElementById("auto_fan").checked){
			document.getElementById("fantasia").value = document.getElementById("nome").value;
		}else{
			document.getElementById("fantasia").value = "";
		}
	}
	
	function fCidades(e) {
		iconta.location = "cadastro-gratuito-cidades.php?e="+e.value;
	}
	
	function fLimpa(obj){
		if (document.getElementById(obj.id).id == "nome"){
			document.getElementById(obj.id).value = "";
		}
		if (document.getElementById(obj.id).id == "fantasia"){
			document.getElementById(obj.id).value = "";
		}
		if (document.getElementById(obj.id).id == "email"){
			document.getElementById(obj.id).value = "";
		}
		if (document.getElementById(obj.id).id == "end_cad"){
			document.getElementById(obj.id).value = "";
		}
		if (document.getElementById(obj.id).id == "fone_res"){
			document.getElementById(obj.id).value = "";
		}
	}
	
	// Validar login de cadastro gratuito
	function fLogin(){
		if (document.getElementById('email').value == ""){
			alert("Coloque o email");
			document.getElementById('email').focus();
			return false;
		}
	}

// Fim do cadastro gratuito

// Contato com a listasa
	function fContatoEmail(){
		if (document.getElementById("nome").value == ""){
			alert("O Campo [Nome] deve ser preenchido.");
			document.getElementById("nome").focus();
			return false;
		}
		if (document.getElementById("end_cad").value == ""){
			alert("Coloque o endereço.");
			document.getElementById("end_cad").focus();
			return false;
		}
		if (document.getElementById("end_bai").value == ""){
			alert("Coloque o bairro");
			document.getElementById("end_bai").focus();
			return false;
		}
		if (document.getElementById("end_cid").value == ""){
			alert("Coloque a cidade.");
			document.getElementById("end_cid").focus();
			return false;
		}
		if (document.getElementById("end_est").value == ""){
			alert("Escolha o Estado.");
			document.getElementById("end_est").focus();
			return false;
		}
		if (document.getElementById("fone_con").value == ""){
			alert("Coloque um telefone para contato");
			document.getElementById("fone_con").focus();
			return false;
		}
		if (document.getElementById("assunto").value == ""){
			alert("Coloque o assunto");
			document.getElementById("assunto").focus();
			return false;
		}
		if (document.getElementById("mensagem").value == ""){
			alert("Coloque um breve comentário sobre o assunto");
			document.getElementById("mensagem").focus();
			return false;
		}
		if (!confirm("Atenção:\n\n Os dados foram conferidos, deseja confirmar este cadastro ?")){
			return false;
		}
	}
	
	// VERIFICA SE É SÓ NUMEROS
	function fNumeros(ObjNumero){
		var nAux = '';
		nAux = nAux + ObjNumero.value;
		if ((nAux != '')&&(isNaN(nAux.substr(nAux.length-1,1)))){
			alert('Digite somente números neste campo !');
			ObjNumero.value = '';
			ObjNumero.focus();
			return false;
		}
	}		

// Fim do contato com a listasa

	function fHomeListasa(){
		top.location = "http://www.listasa.com.br";	
	}

