// JavaScript Document
function objXMLHttp(){
	if (window.XMLHttpRequest){ //monzila, safari
		var objetoXMLHttp = new XMLHttpRequest();
		return objetoXMLHttp;
	}else if (window.ActiveXObject){ //ie
	//todas as versoes de ie
	var versoes = ["MSXML2.XMLHttp.6.0","MSXML2.XMLHttp.5.0","MSXML2.XMLHttp.4.0","MSXML2.XMLHttp.3.0","MSXML2.XMLHttp.2.0","Microsoft.XMLHttp"];	
		for ( var i=0; i<versoes.length; i++){
			try{
				var objetoXMLHttp = new ActiveXObject(versoes[i]);
				return objetoXMLHttp;
			} catch(ex){
				//nada aqui //kuroleweb design
			}//end try
		}//end for	
	}			
	return false;	
} // end objXMLHttp	
	
		
function retorna_cep_CORREIOS_ADD_IMOVEIS(cep){
		var dados = "cep="+cep;

		var oXMLHttp = objXMLHttp();
			oXMLHttp.open("POST", "ajax_mostra_cep_correios.php", true);
			oXMLHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
			oXMLHttp.onreadystatechange = function(){
				if (oXMLHttp.readyState == 4){
					//alert(oXMLHttp.status);
					if (oXMLHttp.status == 200){
						var results = oXMLHttp.responseText.split("^");		
							
								var string = results[1].split( "|" );

								if (string[0] == "endereco"){
									window.document.cadastra.endereco.value = string[1];
								}else{
									window.document.cadastra.endereco.value = "";
								}						

								
								var string = results[3].split( "|" );
								if (string[0] == "cidade"){
									window.document.cadastra.cidade_estado.value = string[1];
								}else{
									window.document.cadastra.cidade_estado.value = "";
								}
								
								var string = results[2].split( "|" );
								if (string[0] == "bairro"){
									window.document.cadastra.bairro.value = string[1];
								}else{
									window.document.cadastra.bairro.value = "";
								}						
							
								var string = results[4].split( "|" );
								if (string[0] == "estado"){
									window.document.cadastra.estado.value  = string[1]
								}else{
									window.document.cadastra.estado.value = "";
								}
								
								//finaliza o preload
								//window.document.getElementById('carrega_preload').innerHTML='';
								/*								
									var string = results[6].split( "|" );
									if (string[0] == "setor"){
										window.document.forms[0].setor.value = string[1];
									}else{
										window.document.forms[0].setor.value = "";
									}
								*/
					
					}else{
						//window.alert('Erro ao adicionar!');
						//mensagem("Ocorreu um erro: "+oXMLHttp.statusText);
					}
				}
			};//end function onreadystatechange
			oXMLHttp.send(dados);
			return false;
	
	}//end function enviar formulario		
	
	
	
	
	
	
	
	function retorna_cep_CORREIOS_cadastro_site(cep){
		var dados = "cep="+cep;

		var oXMLHttp = objXMLHttp();
			oXMLHttp.open("POST", "ajax_mostra_cep_correios.php", true);
			oXMLHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
			oXMLHttp.onreadystatechange = function(){
				if (oXMLHttp.readyState == 4){
					//alert(oXMLHttp.status);
					if (oXMLHttp.status == 200){
						var results = oXMLHttp.responseText.split("^");		
							
								var string = results[1].split( "|" );

								if (string[0] == "endereco"){
									window.document.cadastra.prop_endereco.value = string[1];
								}else{
									window.document.cadastra.prop_endereco.value = "";
								}						

								
								var string = results[3].split( "|" );
								if (string[0] == "cidade"){
									window.document.cadastra.prop_cidade.value = string[1];
								}else{
									window.document.cadastra.prop_cidade.value = "";
								}
								
								var string = results[2].split( "|" );
								if (string[0] == "bairro"){
									window.document.cadastra.prop_bairro.value = string[1];
								}else{
									window.document.cadastra.prop_bairro.value = "";
								}						
							
								var string = results[4].split( "|" );
								if (string[0] == "estado"){
									window.document.cadastra.prop_estado.value  = string[1]
								}else{
									window.document.cadastra.prop_estado.value = "";
								}
								
								//finaliza o preload
								//window.document.getElementById('carrega_preload').innerHTML='';
								/*								
									var string = results[6].split( "|" );
									if (string[0] == "setor"){
										window.document.forms[0].setor.value = string[1];
									}else{
										window.document.forms[0].setor.value = "";
									}
								*/
					
					}else{
						//window.alert('Erro ao adicionar!');
						//mensagem("Ocorreu um erro: "+oXMLHttp.statusText);
					}
				}
			};//end function onreadystatechange
			oXMLHttp.send(dados);
			return false;
	
	}//end function enviar formulario		

function retorna_cpf_cnpj(valor){
	if(valor == 'digite seu CPF/CNPJ'){
		var dados = "cpf_cnpj=";
	}else{
		var dados = "cpf_cnpj="+valor;
	}
	var loader = "<div align='center'>aguarde... <img src='http://www.carregando.com.br/preloader/carregando.gif' border=0></div>";
	var oXMLHttp = objXMLHttp();
		oXMLHttp.open("POST", "painel/usuario_senha.php", true);
		oXMLHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
		oXMLHttp.onreadystatechange = function(){
			if (oXMLHttp.readyState == 1){	
				document.getElementById('status_cpf_cnpj').innerHTML=loader;
			}
			if (oXMLHttp.readyState == 4){
				if (oXMLHttp.status == 200){
					if (oXMLHttp.responseText.indexOf("logado:")>-1){
						window.location='index.php?imobiliaria=painel';
					}else{
						window.document.getElementById('status_cpf_cnpj').innerHTML= oXMLHttp.responseText;
					}
				}else{
					window.alert('Ocorreu um erro: '+oXMLHttp.statusText);
				}
			}else{
				document.getElementById('status_cpf_cnpj').innerHTML=loader;
			}
		};//end function onreadystatechange
		oXMLHttp.send(dados);
		return false;
}
		
		
function Formata_Telefone(objeto,tammax,teclapres)
{
	var tecla = teclapres.keyCode;
	vr = objeto.value;
	vr = vr.replace( "(", "" );
	vr = vr.replace( ")", "" );
	vr = vr.replace( " ", "" );
	vr = vr.replace( "-", "" );
	tam = vr.length;
	if (tam < tammax && tecla != 8) {
		tam = vr.length + 1 ;
	}
	if (tecla == 8 ) {
		tam = tam - 1 ;
	}
	if ( tecla == 8 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105 ) {
		if ( tam <= 4 ) { 
			objeto.value = vr ;
		}
		if ( (tam > 4) && (tam <= 8) ) {
			objeto.value = vr.substr(0,tam-4) + '-' + vr.substr( tam - 4, tam ) ;
		}
		if ( (tam >= 9) && (tam <= 10) ) {
			objeto.value = '(' + vr.substr(0,2) + ') ' + vr.substr(2,tam-6) + '-' + vr.substr(tam-4,tam) ;			
		}
	}		
}



//modelo 2 de fromatar valor
//chamada da funcao
//onKeyDown="Formata_VALOR(this,11,event,2)"
//kurolewebdesign kurole@kurole.com.br

function Limpar(valor, validos) {
	// retira caracteres invalidos da string
	var result = "";
	var aux;
	for (var i=0; i < valor.length; i++) {
	aux = validos.indexOf(valor.substring(i, i+1));
	if (aux>=0) {
	result += aux;
	}
	}
	return result;
}


function Formata_VALOR(campo,tammax,teclapres,decimal) {
	
	var tecla = teclapres.keyCode;

	var vr = Limpar(campo.value,"0123456789");
	var tam = vr.length;
	var dec=decimal
	
	if (tam < tammax && tecla != 8){ tam = vr.length + 1 ; }
	
	if (tecla == 8 )
	{ tam = tam - 1 ; }
	
	if ( tecla == 8 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105 )
	{
	
	if ( tam <= dec )
	{ campo.value = vr ; }

	if ( (tam > dec) && (tam <= 5) ){
	campo.value = vr.substr( 0, tam - 2 ) + "," + vr.substr( tam - dec, tam ) ; }
	if ( (tam >= 6) && (tam <= 8) ){
	campo.value = vr.substr( 0, tam - 5 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - dec, tam ) ; 
	}
	
	if ( (tam >= 9) && (tam <= 11) ){
		campo.value = vr.substr( 0, tam - 8 ) + "." + vr.substr( tam - 8, 3 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - dec, tam ) ; }
	if ( (tam >= 12) && (tam <= 14) ){
		campo.value = vr.substr( 0, tam - 11 ) + "." + vr.substr( tam - 11, 3 ) + "." + vr.substr( tam - 8, 3 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - dec, tam ) ; }
	if ( (tam >= 15) && (tam <= 17) ){
		campo.value = vr.substr( 0, tam - 14 ) + "." + vr.substr( tam - 14, 3 ) + "." + vr.substr( tam - 11, 3 ) + "." + vr.substr( tam - 8, 3 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - 2, tam ) ;}
	}	

}	


 function formata_data(x,tecla){ 
        
        separador="/"; // Você pode definir o separador. Ex: "/" ou "-" ou "."
        
        tecla=tecla.keyCode; // Identifica a tecla, caso seja backspace
        
        valor=x.value.split(''); // Pega o valor do campo e transforma cada caractere em uma string
        formatado=""; // Variável para carregar formatação temporariamente
        
        i=0; // variável de controle
        
        while(i<valor.length){ // Loop para cada caractere do campo
            caractere=valor[i]; // Seleciona um caractere para ser formatado
            numeros=/^\d+$/; // Variavel contendo números positivos
                // Verifica se é número ou "barra"
            if(numeros.test(caractere) || caractere==separador){ formatado+=String(caractere);}
                // Verifica se precisa de barra, se a tecla for backspace, então a barra não é adicionada
                // Se for para adicionar barra, aumenta ++ variável de controle "i" para pular a barra adicionada
            if((formatado.length==2 || formatado.length==5) && tecla!=8){formatado+=separador; i++;}
                
            i++; // Se houver, passa para o próximo caractere
        }
        
        x.value=formatado; // Atribui o valor formatado ao campo
		if (formatado.length == 10){
		x.focus();
		}	
    }
	
	
function mascara(o,f){
    v_obj=o
    v_fun=f
    setTimeout("execmascara()",1)
}

function execmascara(){
    v_obj.value=v_fun(v_obj.value)
}

function leech(v){
    v=v.replace(/o/gi,"0")
    v=v.replace(/i/gi,"1")
    v=v.replace(/z/gi,"2")
    v=v.replace(/e/gi,"3")
    v=v.replace(/a/gi,"4")
    v=v.replace(/s/gi,"5")
    v=v.replace(/t/gi,"7")
    return v
}

function soNumeros(v){
    return v.replace(/\D/g,"")
}

function telefone(v){
    v=v.replace(/\D/g,"")                 //Remove tudo o que não é dígito
    v=v.replace(/^(\d\d)(\d)/g,"($1) $2") //Coloca parênteses em volta dos dois primeiros dígitos
    v=v.replace(/(\d{4})(\d)/,"$1-$2")    //Coloca hífen entre o quarto e o quinto dígitos
    return v
}

function cpf(v){
    v=v.replace(/\D/g,"")                    //Remove tudo o que não é dígito
    v=v.replace(/(\d{3})(\d)/,"$1.$2")       //Coloca um ponto entre o terceiro e o quarto dígitos
    v=v.replace(/(\d{3})(\d)/,"$1.$2")       //Coloca um ponto entre o terceiro e o quarto dígitos
                                             //de novo (para o segundo bloco de números)
    v=v.replace(/(\d{3})(\d{1,2})$/,"$1-$2") //Coloca um hífen entre o terceiro e o quarto dígitos
    return v
}

function cep(v){
    v=v.replace(/D/g,"")                //Remove tudo o que não é dígito
    v=v.replace(/^(\d{5})(\d)/,"$1-$2") //Esse é tão fácil que não merece explicações
    return v
}

function cnpj(v){
    v=v.replace(/\D/g,"")                           //Remove tudo o que não é dígito
    v=v.replace(/^(\d{2})(\d)/,"$1.$2")             //Coloca ponto entre o segundo e o terceiro dígitos
    v=v.replace(/^(\d{2})\.(\d{3})(\d)/,"$1.$2.$3") //Coloca ponto entre o quinto e o sexto dígitos
    v=v.replace(/\.(\d{3})(\d)/,".$1/$2")           //Coloca uma barra entre o oitavo e o nono dígitos
    v=v.replace(/(\d{4})(\d)/,"$1-$2")              //Coloca um hífen depois do bloco de quatro dígitos
    return v
}

function romanos(v){
    v=v.toUpperCase()             //Maiúsculas
    v=v.replace(/[^IVXLCDM]/g,"") //Remove tudo o que não for I, V, X, L, C, D ou M
    //Essa é complicada! Copiei daqui: http://www.diveintopython.org/refactoring/refactoring.html
    while(v.replace(/^M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$/,"")!="")
        v=v.replace(/.$/,"")
    return v
}

function site(v){
    //Esse sem comentarios para que você entenda sozinho ;-)
    v=v.replace(/^http:\/\/?/,"")
    dominio=v
    caminho=""
    if(v.indexOf("/")>-1)
        dominio=v.split("/")[0]
        caminho=v.replace(/[^\/]*/,"")
    dominio=dominio.replace(/[^\w\.\+-:@]/g,"")
    caminho=caminho.replace(/[^\w\d\+-@:\?&=%\(\)\.]/g,"")
    caminho=caminho.replace(/([\?&])=/,"$1")
    if(caminho!="")dominio=dominio.replace(/\.+$/,"")
    v="http://"+dominio+caminho
    return v
}	

