function objXMLHttp(){

	if (window.XMLHttpRequest) { // Mozilla, Safari, ...
		var objetoXMLHttp = new XMLHttpRequest();
		return objetoXMLHttp;
	} else if (window.ActiveXObject) { // IE
		var versoes = [ "MSXML2.XMLHttp.5.0","MSXML2.XMLHttp.4.0","MSXML2.XMLHttp.3.0","MSXML2.XMLHttp","Microsoft.XMLHttp"];
		for (var i = 0; i < versoes.length; i++) {
			try {
				var objetoXMLHttp = new ActiveXObject(versoes[i]);
				return objetoXMLHttp;
			} catch (ex) {
				//nada aqui
			}
		}
	}
	return false;
}

function LetraNumero(campo, event, tipo){
	var LEFT=37, RIGHT=39, DEL=46, BCK=8, ETR=13, TAB=9;
	var key, tecla;
	if (event.which){
		tecla = event.which;
	}else{
		tecla = event.keyCode;
	}
	key=String.fromCharCode(tecla); //traduz o valor ascii para caracter

	if(tecla == ETR){
		return false;
	}
	if (tecla==BCK || tecla==TAB || tecla==DEL || tecla==LEFT || tecla==RIGHT){
		return true;
	}
	switch (tipo) {
	case "numero":
		return (/[0-9]/.test(key)); //testa para ver se key é um carecter de 0-9
	break;
	case "letras":
		return(/[a-zA-Z ._-]/.test(key));
	break;
	}
}//fim da função Valida Campos

function TipoPessoa(tipo){
	//alert(tipo);
	if (tipo=="CPF"){
		document.getElementById('op_pessoa_juridica').checked=0;
		document.getElementById('razao_social').innerHTML="Nome Completo: ";
		document.getElementById('nome_fantasia').innerHTML="Nome Exibição: ";
		document.getElementById('numero_documento').innerHTML="Nº do CPF: ";		
		//document.getElementById('op_pessoa_fisica').checked=1;
	}else{
		document.getElementById('op_pessoa_fisi').checked=0;
		document.getElementById('razao_social').innerHTML="Razão Social: ";
		document.getElementById('nome_fantasia').innerHTML="Nome Fantasia: ";
		document.getElementById('numero_documento').innerHTML="Nº do CNPJ: ";
		//document.getElementById('op_pessoa_juridica').checked=1;
		//pessoa.rows[1].style.display = 'none';
	}
	document.getElementById('tipo').value=tipo;
	document.getElementById('documento').value="";
	MascaraCampos(document.getElementById('documento'), tipo, document.getElementById('txt_nome'))
	document.getElementById('documento').focus();
}

function MascaraCampos(campo, tipodocumento, proximocampo){
var valor = campo.value;
switch (tipodocumento){
case "CNPJ":
	if(valor.length > 1 && valor.length<3){
		campo.value = valor+".";
	}
	if(valor.length > 5 && valor.length<7){
		campo.value = valor+".";
	}
	if(valor.length > 9 && valor.length<12){
		campo.value = valor+"/";
	}
	if(valor.length > 14 && valor.length<16){
		campo.value = valor+"-";
	}	
	if (valor.length > 17){
		proximocampo.focus();
	}
break;	
case "CPF":
if (valor.length >= 14){
	proximocampo.focus();
}else{	
	if(valor.length > 2 && valor.length<4){
		campo.value = valor+".";
	}
	if(valor.length > 6 && valor.length<8){
		campo.value = valor+".";
	}
	if(valor.length > 10 && valor.length<12){
		campo.value = valor+"-";
	}
}
break;
case "FONE":
	if(valor.length >= 4 && valor.length < 5){
		campo.value = valor+"-";
	}
	if (valor.length > 8){
		proximocampo.focus();
	}
break;
case "CEP":
	if(valor.length >= 2 && valor.length < 3){
		campo.value = valor+".";
	}
	if(valor.length >= 6 && valor.length < 7){
		campo.value = valor+"-";
	}
	if (valor.length > 9){
		proximocampo.focus();
	}
break;
case "DDD":
	if (valor.length > 1){
		proximocampo.focus();
	}
break;
case "MOEDA":
	var valor = campo.value;
	valor = valor.replace (".","");
	valor = valor.replace (",","");
	var tamanho = valor.length;
	var iniciodecimais = tamanho - 2;
	
	if(tamanho > 2) { // então deve colocar separador
		var decimais = valor.substr(iniciodecimais,3);
		var inteiros = valor.substr(0,iniciodecimais);
		var stringinvertida = "";
		var tamanhoinverte = tamanho - 2;
		while (tamanhoinverte > 0) {
			tamanhoinverte -= 1;
			stringinvertida += valor.substr(tamanhoinverte,1);
		}
		var j = 0;
		var decimaisformatado = "";
		var stringformatado = "";
		for (i = 0; i <= stringinvertida.length; i++) {
			j = j + 1;
			stringformatado = stringformatado + stringinvertida.substr(i,1);
			if (j == 3 && stringformatado != "") {
				if (decimaisformatado == "") {
					decimaisformatado = stringformatado;
				} else {
					decimaisformatado +=  '.' + stringformatado;
				}
				stringformatado = "";
				j = 0;
			}
		}
		if (j == 1 && tamanho != 5) {
			decimaisformatado += "." + stringformatado
		} else {
			decimaisformatado += stringformatado;
		}
		tamanhoinverte = decimaisformatado.length;
		var stringfinal = "";
		while (tamanhoinverte > 0) {
			tamanhoinverte = tamanhoinverte - 1;
			stringfinal += decimaisformatado.substr(tamanhoinverte,1);
		}
		campo.value = stringfinal + "," + decimais;
	}
break;
case "MAPA":
	if(valor.length >= 2 && valor.length < 3){
		campo.value = valor+".";
	}
	if (valor.length > 18){
		proximocampo.focus();
	}
break;
}
}
function ValidaDocumento(tipo, campo){
if (tipo=="CPF"){
	cpf=campo.value
	erro = new String;
	cpf = cpf.substring(0, 3) + cpf.substring(4, 7) + cpf.substring(8, 11) + cpf.substring(12, 14)
	//alert(cpf)
	if (cpf.length < 11) erro += "Sao necessarios 11 digitos para verificacao do CPF! "; 
	var nonNumbers = /\D/;
	if (nonNumbers.test(cpf)) erro += "A verificacao de CPF suporta apenas numeros! "; 
	if (cpf == "00000000000" || cpf == "11111111111" || cpf == "22222222222" || cpf == "33333333333" || cpf == "44444444444" || cpf == "55555555555" || cpf == "66666666666" || cpf == "77777777777" || cpf == "88888888888" || cpf == "99999999999"){
		erro += "Numero de CPF invalido!"
	}
	var a = [];
	var b = new Number;
	var c = 11;
	for (i=0; i<11; i++){
		a[i] = cpf.charAt(i);
		if (i < 9){
			b += (a[i] * --c);
		}
	}
	if ((x = b % 11) < 2){
		a[9] = 0 
	}else{
		a[9] = 11-x
	}
	b = 0;
	c = 11;
	for (y=0; y<10; y++){
		b += (a[y] * c--);
	}
	if ((x = b % 11) < 2){
		a[10] = 0;
	}else{
		a[10] = 11-x;
	}
	if ((cpf.charAt(9) != a[9]) || (cpf.charAt(10) != a[10])){
		erro +="O CPF Digitado é inválido. Por gentileza digite novamente.";
		campo.value=""
		campo.focus();
	}
	if (erro.length > 0){
		alert(erro);
		return false;
	}
	//alert("CPF válido")
	return true;
}else{
	var CNPJ
	erro = new String;
	CNPJ = campo.value;
	if (CNPJ.length < 18) erro += "O número de dígito do CNPJ é MENOR que o exigido! "; 
	x = CNPJ.substring (0,2);
	x += CNPJ.substring (3,6);
	x += CNPJ.substring (7,10);
	x += CNPJ.substring (11,15);
	x += CNPJ.substring (16,18);
	CNPJ = x; 

	var nonNumbers = /\D/;
	if (nonNumbers.test(CNPJ)) erro += "A verificação de CNPJ suporta apenas números!"
	var a = [];
	var b = new Number;
	var c = [6,5,4,3,2,9,8,7,6,5,4,3,2];

	for (i=0; i<12; i++){
		a[i] = CNPJ.charAt(i);
		b += a[i] * c[i+1];
	}
	if ((x = b % 11) < 2) {
		a[12] = 0
	}else{ 
		a[12] = 11-x
	}
	b = 0;
	for (y=0; y<13; y++){
		b += (a[y] * c[y]); 
	}
	if ((x = b % 11) < 2) {
		 a[13] = 0;
	}else{
		a[13] = 11-x;
	}
	if ((CNPJ.charAt(12) != a[12]) || (CNPJ.charAt(13) != a[13])){
		erro +="O CNPJ digitádo é inválido. Por gentileza digte novamente!";
		campo.value=""
		campo.focus()
	}
	if (erro.length > 0){
		alert(erro);
		return false;
	}else{
		//alert("CNPJ válido")
		return true;
	}
		return true; 
}
}

function ValidaEmail(email){
	if ((email != 0) && ((email.indexOf("@") < 1) || (email.indexOf('.') < 7))){
		alert("O E-mail digitado não é valido!");
		return false;
	}else{
		return true;
	}
}

function GeraCidades(estado, campo, opcao){
	var oXMLHttp = objXMLHttp();
	if (estado){
		oXMLHttp.open("GET", "gerar_cidades.php?estado=" + estado, true);
		oXMLHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

		oXMLHttp.onreadystatechange = function () {
		if (oXMLHttp.readyState == 4) {
			if (oXMLHttp.status == 200) {
				PreencheCidades(oXMLHttp.responseText, campo, opcao);
			} else {
				alert("Ocorreu o erro: "+ oXMLHttp.statusText);
			}
		}
		};
		oXMLHttp.send(null);
		return false;
	}else{
		alert("Escolha um Estado");
	}
}

function PreencheCidades(cidades, campo, opcao){
    campo.length=0;
    results = cidades.split("$");
    if (opcao==1){
        campo.options[0] = new Option("Todas", "");
    }
    for(i = 0+opcao; i < results.length-1+opcao; i++){
	string = results[i-opcao].split("|");
	campo.options[i] = new Option(string[0], string[1]);
    }
    campo.focus();
}

function ExibeZoneamento(campo_cidade, div_zoneamento){
	if (campo_cidade.selectedIndex >= 0){
		if (campo_cidade.options[campo_cidade.selectedIndex].text=="São Paulo"){
			div_zoneamento.style.display = '';
		}else{
			div_zoneamento.style.display = 'none';
		}
	}
	//alert(campo_cidade.options[campo_cidade.selectedIndex].text);
}

function SelecionaCidadeIpUsuario(campo_cidade, ip){
	//seleciona qual a cidade do visitante pelo ip gravado no BD
	var ajax = new myAjax({
	showResponse: false,
	complete: function(){
		var id_cidade=this.getText();
		for(x=0; x < campo_cidade.length; x++){  
			if(campo_cidade[x].value == id_cidade){  
				campo_cidade[x].selected = true;  
			}  
		}
	}
	});
	ajax.load("seleciona_cidade_ip.php?ip=" + ip.value);
	return false;
}

function AbreJanelas(url, largura, altura){
	var nome, end;
	nome="Portal Busque & Encontre - Contatos";
	NewWindow =window.open(url,"nome","width="+largura+",height="+altura+",resizable=no,closable=no");
}

function FechaRedireciona(link) {
  window.opener.location = link;
  self.close();
 }

function Fotos_Avancar(num_fotos, exibida, fotos){
	var foto;
	exibida=eval(exibida);
	if (num_fotos>0){
	if (exibida<num_fotos && exibida>1){
		document.getElementById('exibidas').value=exibida+1;
		foto="fotos/"+fotos[exibida+1];
	}else{
		if (exibida==1){
			document.getElementById('exibidas').value=exibida+1;
			foto="fotos/"+fotos[exibida+1];
		}else{
			foto="fotos/"+fotos[exibida];
		}
	}
	if (foto=="fotos/undefined"){
		foto="fotos/"+fotos[1];
	}
	document.getElementById('janela_fotos').src=foto;
	exibida=eval(exibida);
	if (exibida<num_fotos){
		exibida=exibida+1;
	}else{
		exibida=num_fotos;
	}
	document.getElementById('num_foto').innerHTML = "Foto "+ eval(exibida);
	}
}

function ValidaArquivo(valor){
	if (valor=="" || !valor){
	alert('Você não escolheu nenhuma foto para ser inserida. Por gentileza escolha uma agora!');
	return false;
	document.getElementById('file').focus();
	}
}

function Fotos_Retroceder(num_fotos, exibida, fotos){
	var foto;
	exibida= eval(exibida);
	if (num_fotos>0){
		if (exibida<=1){
			foto="fotos/"+fotos[1];
		}else{
			if (exibida<=num_fotos && exibida>=1){
				foto="fotos/"+fotos[exibida-1];	
				if (exibida==num_fotos){
					foto="fotos/"+fotos[exibida-1];			
				}
				if (exibida<=1){
					foto="fotos/"+fotos[1];			
				}
			document.getElementById('exibidas').value=exibida-1;
			}
		}
	if (foto=="undefined"){
		foto="fotos/"+fotos[1];
	}
	document.getElementById('janela_fotos').src=foto;
	exibida=eval(exibida)-1;
	if (exibida==0){
		exibida=1;
	}
	document.getElementById('num_foto').innerHTML = "Foto "+ eval(exibida);
	}
}

function ExibirImagem(foto, fotoatual, descricao){
	//alert(foto);
	document.getElementById('janela_fotos').src="fotos/"+foto; 
	//document.getElementById('exibidas').value=fotoatual;
	//document.getElementById('num_foto').innerHTML = "Foto "+ fotoatual;
	//document.getElementById('descricao_fotos').innerHTML = descricao;
}

function ExcluirImagem(foto, num_fotos){
	var url;
	url="retirar_foto_ins.php?foto="+foto+"&num_fotos="+num_fotos;
	window.location=url;
}
function GeraSubcategoria(valor, campo){
    if (valor){
    oXMLHttp.open("GET", "gerar_subcategoria.php?categoria=" + valor, true);
    oXMLHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

    oXMLHttp.onreadystatechange = function () {
        if (oXMLHttp.readyState == 4) {
            if (oXMLHttp.status == 200) {
                PreencheSubcategorias(oXMLHttp.responseText, campo);
            } else {
               alert("Ocorreu o erro: "+ oXMLHttp.statusText);
            }
        }
    };
    oXMLHttp.send(null);
	return false;
    }else{
        alert("Escolha uma Categoria");
    }
}

function PreencheSubcategorias(cidades, campo){
    campo.length=0;
    results = cidades.split("$");
    for(i = 0; i < results.length-1; i++){
        string = results[i].split("|");
        campo.options[i] = new Option(string[0], string[1]);
    }
}

function GeraTreeview(busca){
	trv = new treeview('menuPrincipal');
	trv.limpaNodes('menuPrincipal');
	
	oXMLHttp.open("GET", "gerar_treeview.php?busca=" + busca, true);
	oXMLHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

	oXMLHttp.onreadystatechange = function () {
        if (oXMLHttp.readyState == 4) {
		if (oXMLHttp.status == 200) {
			PreencheTreeview(oXMLHttp.responseText, busca);
		} else {
			alert("Ocorreu o erro: "+ oXMLHttp.statusText);
		}
        }
	};
	oXMLHttp.send(null);
	return false;
}

function PreencheTreeview(conteudo, busca){
    var campo;
    var categoria="";
    results = conteudo.split("$");
    for(i = 0; i < results.length-1; i++){
        string = results[i].split("|");
	if (categoria != string[0]){
		a = trv.add(string[0],"javascript:void(null);",'_self', null);
		categoria=string[0];
	}
	b = trv.add(string[2],'search_anuncio.php?busca=' + busca + '&categoria=' + string[1] + "&subcategoria=" + string[3],'_self', a);
    }
}
function GeraCategoria(campo){
    oXMLHttp.open("GET", "gerar_categoria.php", true);
    oXMLHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

    oXMLHttp.onreadystatechange = function () {
        if (oXMLHttp.readyState == 4) {
            if (oXMLHttp.status == 200) {
                PreencheCategorias(oXMLHttp.responseText, campo);
            } else {
               alert("Ocorreu o erro: "+ oXMLHttp.statusText);
            }
        }
    };
	oXMLHttp.send(null);
	return false;
}
function PreencheCategorias(categorias, campo){
    campo.length=0;
    results = categorias.split("$");
    for(i = 0; i < results.length-1; i++){
        string = results[i].split("|");
        campo.options[i] = new Option(string[0], string[1]);
    }
}

function GeraAnuncios(valor, campo){
    if (valor){
    oXMLHttp.open("GET", "gerar_anuncios.php?cliente=" + valor, true);
    oXMLHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

    oXMLHttp.onreadystatechange = function () {
        if (oXMLHttp.readyState == 4) {
            if (oXMLHttp.status == 200) {
                PreencheAnuncios(oXMLHttp.responseText, campo);
            } else {
               alert("Ocorreu o erro: "+ oXMLHttp.statusText);
            }
        }
    };
    oXMLHttp.send(null);
	return false;
    }else{
        alert("Escolha uma Categoria");
    }
}

function PreencheAnuncios(resultado, campo){
    campo.length=0;
    results = resultado.split("$");
    for(i = 0; i < results.length-1; i++){
        string = results[i].split("|");
        campo.options[i] = new Option(string[1], string[0]);
    }
}
function RodapePrincipal(destino){
document.write('<table width="779" height="60" border="0" cellpadding="0" cellspacing="0" class="tabela" id="rodape">');
document.write('<tr><td><div class="tabela" id="logomarca"></div></td><td align="center" valign="top"><div class="tabela" id="fundo_menu"><div class="textos" id="copyrigth"> todos os direitos reservados &copy; 2007 </div>');
document.write('<div class="textos" id="menu_rodape"> <a href="'+destino+'index.php">HOME</a>');
document.write(' | QUEM SOMOS | <a href="'+destino+'search.php">EMPRESAS</a> | <a href="'+destino+'eventos/index.php">EVENTOS</a> | AJUDA | <a href="'+destino+'contatos.php">CONTATOS</a> | POL&Iacute;TICAS</div></div></td>');
document.write('<td valign="top"><div class="tabela" id="baladas_fundo_princ"><div class="textos" id="desenvolvimento"><div align="right">desenvolvimento</div>');
document.write('</div></div></td><td width="70" bgcolor="#1F1A17"><a href="http://www.jmsolucoes.com.br" target="_blank"><img src="imagens/logomarca_jmsolucoes.png" width="70" height="60" border="0"></a></td></tr></table>');
}

function Rodape(destino){
document.write('<table width="779" height="60" border="0" cellpadding="0" cellspacing="0" class="tabela" id="rodape">');
document.write('<tr><td><div class="tabela" id="logomarca"></div></td><td align="center" valign="top"><div class="tabela" id="fundo_menu"><div class="textos" id="copyrigth"> todos os direitos reservados &copy; 2007 </div>');
document.write('<div class="textos" id="menu_rodape"> <a href="'+destino+'index.php">HOME</a>');
document.write(' | QUEM SOMOS | <a href="'+destino+'search.php">EMPRESAS</a> | <a href="'+destino+'eventos/index.php">EVENTOS</a> | AJUDA | <a href="'+destino+'contatos.php">CONTATOS</a> | POL&Iacute;TICAS</div></div></td>');
document.write('<td valign="top"><div class="tabela" id="baladas_fundo"><div class="textos" id="desenvolvimento"><div align="right">desenvolvimento</div>');
document.write('</div></div></td><td width="70"><a href="http://www.jmsolucoes.com.br" target="_blank"><img src="'+destino+'imagens/logomarca_jmsolucoes.png" width="70" height="60" border="0"></a></td></tr></table>');
}

function MouseOver(celula){
	celula.className = "selecionada";
}
function MouseFora(celula){
	celula.className = "nao_selecionada";
}

function AtivaAba(celula){
	celula.className = "selecionada";
}
function DesativaAba(celula){
	celula.className = "complemento";
}

function AtivaVideo(celula){
	celula.className = "selecionada2";
}
function DesativaVideo(celula){
	celula.className = "nao_selecionada";
}

function AlteraCidade(opcao){
	if (opcao==1){
		document.getElementById('cidade').style.display = '';
		document.getElementById('cidade_existente').style.display = 'none';
		GeraCidades(document.getElementById('estados2').value, document.getElementById('cidades2'));
	}else{
		document.getElementById('cidade_existente').style.display = '';
		document.getElementById('cidade').style.display = 'none';
	}
}

function ValidaContato(){
	if (document.getElementById('nome').value==""){
		alert("Você não informou seu Nome. Por gentileza escreva-o agora!");
		return false;
		document.getElementById('nome').focus();
	}
	if (document.getElementById('email').value==""){
		alert("Você forneceu seu email para a resposta. Por gentileza digite agora!");
		return false;
		document.getElementById('email').focus();
	}
	if (document.getElementById('assunto').value==""){
		alert("Você deve informar o assunto de sua mensagem!");
		return false;
		document.getElementById('assunto').focus();
	}
	if (document.getElementById('mensagem').value==""){
		alert("Você não escreveu sua mensagem. Por favor escreva agora!");
		return false;
		document.getElementById('mensagem').focus();
	}
	return true;
}

function DirecionaCategoria(categoria){
	url="search.php?c=" + categoria;
	window.location=url;
}

function DirecionaSubCategoria(categoria, subcategoria){
	url="search.php?c=" + categoria + "&s=" + subcategoria;
	window.location=url;
}

function addBookmark(title, url) {
if (window.sidebar) { 
	window.sidebar.addPanel(title, url,"");
} else if( document.all ) { 
	window.external.AddFavorite( url, title);
	} else if( window.opera && window.print ) { 
		return true; 
	}
}

