﻿// JScript File
function ValidaFormDoador()
{
    var sucesso = true;
    
    // Define os estilos padrões
    //Pessoa Fisica
    document.getElementById('nome').className = 'txtfield';
    document.getElementById('erronome').style.display = 'none';
    
    document.getElementById('email').className = 'txtfield';
    document.getElementById('erroemail').style.display = 'none';
    
        
    document.getElementById('cpf').className = 'txtfield';
    document.getElementById('errocpf').style.display = 'none';
    
    document.getElementById('endereco').className = 'txtfield';
    document.getElementById('erroendereco').style.display = 'none';
    
    document.getElementById('numero').className = 'txtfield';
    document.getElementById('erronumero').style.display = 'none'; 
    
    document.getElementById('complemento').className = 'txtfield';
    document.getElementById('errocomplento').style.display = 'none';  
   
    document.getElementById('bairro').className = 'txtfield';
    document.getElementById('errobairro').style.display = 'none';
    
    document.getElementById('estado').className = 'txtfield';
    document.getElementById('erroestado').style.display = 'none';
    
    document.getElementById('cidade').className = 'txtfield';
    document.getElementById('errocidade').style.display = 'none';    
    
    document.getElementById('cep').className = 'txtfield';
    document.getElementById('errocep').style.display = 'none';
        
    document.getElementById('fone_residencial').className = 'txtfield';
    document.getElementById('errofone_residencial').style.display = 'none';
    
    document.getElementById('fone_comercial').className = 'txtfield';
    document.getElementById('errofone_comercial').style.display = 'none';
    
    document.getElementById('fone_celular').className = 'txtfield';
    document.getElementById('errofone_celular').style.display = 'none';
    
    document.getElementById('sms').className = 'txtfield';
    document.getElementById('errosms').style.display = 'none';    
    
    document.getElementById('envio_email').className = 'txtfield';
    document.getElementById('erroenvio_email').style.display = 'none';        
                     
    document.getElementById('nascimento').className = 'txtfield';
    document.getElementById('erronascimento').style.display = 'none';
    
    document.getElementById('sexo').className = 'txtfield';
    document.getElementById('errosexo').style.display = 'none';    
    
    document.getElementById('estado_civil').className = 'txtfield';
    document.getElementById('erroestado_civil').style.display = 'none';
    
    //Fim Informações de Contato
    
    if(EmptyField(document.getElementById('nome')))
    {
        sucesso = false;
        document.getElementById('nome').className = 'error';
        document.getElementById('erronome').style.display = '';
        document.getElementById('erronome').innerHTML = 'Por favor, informe seu nome.';  
    }
       
    if(EmptyField(document.getElementById('email')))
    {
        sucesso = false;
        document.getElementById('email').className = 'error';
        document.getElementById('erroemail').style.display = '';
        document.getElementById('erroemail').innerHTML = 'Por favor, informe o seu e-mail.';  
    }
    else
    {
        if(!valida_email(document.getElementById('email')))
        {
            sucesso = false;
            document.getElementById('email').className = 'error';
            document.getElementById('erroemail').style.display = '';
            document.getElementById('erroemail').innerHTML = 'E-mail inválido.';  
        }
    }
    
    if(!EmptyField(document.getElementById('cpf')))
    {
          if(!valida_CPF(document.getElementById('cpf')))
          {
            sucesso = false;
            document.getElementById('cpf').className = 'error';
            document.getElementById('errocpf').style.display = '';
            document.getElementById('errocpf').innerHTML = 'CPF em formato inválido.';  
          }
    }
    else
    {
        sucesso = false;
        document.getElementById('cpf').className = 'error';
        document.getElementById('errocpf').style.display = '';
        document.getElementById('errocpf').innerHTML = 'Por favor, informe o seu CPF.';  
    }
    
    if(!EmptyField(document.getElementById('fone_residencial')))
    {
        if(!valida_telefone(document.getElementById('fone_residencial')))
        {
            sucesso = false;
            document.getElementById('fone_residencial').className = 'error';
            document.getElementById('errofone_residencial').style.display = '';
            document.getElementById('errofone_residencial').innerHTML = 'Telefone em formato inválido.';  
        }
    }
    if(!EmptyField(document.getElementById('fone_comercial')))
    {
        if(!valida_telefone(document.getElementById('fone_comercial')))
        {
            sucesso = false;
            document.getElementById('fone_comercial').className = 'error';
            document.getElementById('errofone_comercial').style.display = '';
            document.getElementById('errofone_comercial').innerHTML = 'Telefone em formato inválido.';  
        }
    }
    if(!EmptyField(document.getElementById('fone_celular')))
    {
        if(!valida_telefone(document.getElementById('fone_celular')))
        {
            sucesso = false;
            document.getElementById('fone_celular').className = 'error';
            document.getElementById('errofone_celular').style.display = '';
            document.getElementById('errofone_celular').innerHTML = 'Telefone em formato inválido.';  
        }
    }
    
    
    if (!sucesso) {
        alert('Alguns campos não foram preenchidos da forma devida. Por favor, verifique os campos marcados em vermelho.'); 
        return false;
    }
    var _nome = document.getElementById('nome').value;
    var _email = document.getElementById('email').value;
    var _cpf = document.getElementById('cpf').value;
    var _endereco = document.getElementById('endereco').value;
    var _numero = document.getElementById('numero').value;
    var _complemento = document.getElementById('complemento').value;
    var _bairro = document.getElementById('bairro').value;
    var _estado = document.getElementById('estado').value;
    var _cidade = document.getElementById('cidade').value;
    var _cep = document.getElementById('cep').value;
    var _telResidencial = document.getElementById('fone_residencial').value;
    var _telComercial = document.getElementById('fone_comercial').value;
    var _telCelular = document.getElementById('fone_celular').value;
    var _sms = document.getElementById('sms').value;
    var _envio_email = document.getElementById('envio_email').value;
    var _envio_email = document.getElementById('envio_email').value;
    var _comunicacao = "1";
    var _preferencia = document.getElementById('preferencia').value;
    var _dtNascimento = document.getElementById('nascimento').value;
    var _sexo = document.getElementById('sexo').value;
    var _estado_civil = document.getElementById('estado_civil').value;
    var alterar_registro  = document.getElementById('hidden_id').value;
    

    //Inserindo registro.
    var cod = news_cadastro.InserirNews(_nome,_email,_cpf,_endereco,_numero,_complemento ,_bairro,_estado,_cidade,_cep,_telResidencial,_telComercial,_telCelular,_sms,_envio_email,_comunicacao,_preferencia,_dtNascimento,_sexo,_estado_civil,alterar_registro).value;
//    if(cod == 1)
//    {
//        document.getElementById('sucesso_cadastro_completo').className= '';
//        document.getElementById('erro_cadastro_completo').style.display = 'none';
//        document.getElementById('form_cadastro').style.display = 'none';
//        document.getElementById('sucesso_alterar_completo').style.display = 'none';
//    }
//    else if(cod == 0)
//    {
//        document.getElementById('sucesso_cadastro_completo').style.display = 'none';
//        document.getElementById('erro_cadastro_completo').className = '';
//        document.getElementById('form_cadastro').style.display = 'none';
//        document.getElementById('sucesso_alterar_completo').style.display = 'none';
//    }
//    else if(cod == 2)
//    {
//        document.getElementById('sucesso_alterar_completo').className= '';
//        document.getElementById('sucesso_cadastro_completo').style.display = 'none';
//        document.getElementById('erro_cadastro_completo').style.display = 'none';
//        document.getElementById('form_cadastro').style.display = 'none';
//    }
    
        switch(cod)
    {
        case 1:
              //document.getElementById('sucesso_alterar_completo').className= '';
              //document.getElementById('form_cadastro').style.display = 'none';
              //document.getElementById('messagem_news').className= '';
              //document.getElementById('messagem_news').innerHTML = '<br /><strong>Este e-mail já se encontra cadastrado na nossa newsletter.</strong>';
              document.getElementById('email').focus();
              alert('Este e-mail já se encontra cadastrado na nossa newsletter.');

            break;
        case 2:
            document.getElementById('sucesso_alterar_completo').className= '';
            document.getElementById('messagem_news').className= '';
            document.getElementById('form_cadastro').style.display = 'none';
            document.getElementById('messagem_news').innerHTML = '<br /><strong>Dados cadastrados com sucesso.Um e-mail de confirmação foi enviado para você.</strong>';
            break;
        case 3:
            document.getElementById('sucesso_alterar_completo').className= '';
            document.getElementById('messagem_news').className= '';
            document.getElementById('form_cadastro').style.display = 'none';
            document.getElementById('messagem_news').innerHTML = '<br /><strong>Aconteceu um erro ao se tentar enviar os seus dados. Por favor, tente novamente. Se o problema persistir por favor entre em contato com o administrador do sistema.</strong>';
            
            break;
    }
}

//Função assincrona do populaCidade.
function retorno_populaCidade(ret){
    var dt = ret.value;
    var cidade = document.getElementById('cidade');
    cidade.options.length = 0;
	cidade.options[cidade.options.length] = new Option("Selecione uma cidade","0");            
    for(var i = 0; i < dt.length; i++)
    {                
        cidade.options[cidade.options.length] = new Option(dt[i].Nome, dt[i].Codigo_Cidade);
    }
    document.getElementById('img_cidade').style.display = "none";
    
}

//Metodo responsável por popular as cidades de acordo com o estado selecionado.
function populaCidade(value)
{
    document.getElementById('img_cidade').style.display = "";
    news_cadastro.PopulaCidade(value,retorno_populaCidade);   
}

//Função para ao se dá um Enter cair sobre o evento de submit da pagina de contato
//param:evt = Evento do keyPress
//param:botao = Id do botão que dá o submit na página
function EnterCadastroCompleto(evt,botao)
{
    //Verificando se o que é digitado é somente campos numéricos
    var charCode = (evt.which) ? evt.which : evt.keyCode;
  
    if(charCode==13)
    {
         document.getElementById(botao).onclick();		
         return false;
    }
    return true;
}

var resultadoCEP = null;

function makeRequestCEP(url,callback_function) {
	var http_request = false;
	if (window.XMLHttpRequest) { // Mozilla, Safari,...
		http_request = new XMLHttpRequest();
		if (http_request.overrideMimeType) {
			http_request.overrideMimeType('text/xml');
		}
	} else if (window.ActiveXObject) { // IE
		try {
			http_request = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				http_request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}
	
	if (!http_request) {
		alert('Unfortunatelly you browser doesn\'t support this feature.');
		return false;
	}
	http_request.onreadystatechange = function() {
		if (http_request.readyState == 4) {
			if (http_request.status == 200) {
				eval('retornoXMLCep(http_request.responseXML, callback_function)');
			} else {
				alert('There was a problem with the request.(Code: ' + http_request.status + ')');
			}
		}
	}
	var Data = new Date();
	http_request.open('GET', url, true);
	http_request.setRequestHeader( "If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT" );
	http_request.send(null);
}


function retornoXMLCep(xml, retorno){
	var result = new Object();
	var endereco="", bairro="", cidade="", estado="", cep = "";
	if (document.all){
		var nodes = xml.documentElement.childNodes;
		    endereco = result.endereco = nodes.item(0).text;
		    bairro   = result.bairro = nodes.item(1).text;
		    cidade   = result.cidade = nodes.item(2).text;
		    estado   = result.estado = nodes.item(3).text;
		    cep      = result.cep = nodes.item(4).text;
	}else{
		endereco = result.endereco = xml.getElementsByTagName("endereco")[0].childNodes[0].nodeValue;
		if(endereco != "")
		{
		    bairro   = result.bairro = xml.getElementsByTagName("bairro")[0].childNodes[0].nodeValue;
		    cidade   = result.cidade = xml.getElementsByTagName("cidade")[0].childNodes[0].nodeValue;
		    estado   = result.estado = xml.getElementsByTagName("estado")[0].childNodes[0].nodeValue;
		    cep      = result.cep = xml.getElementsByTagName("cep")[0].childNodes[0].nodeValue;
		}
	}
	
	if (estado== "" || cidade == "")
	{
	    DisabledElementos(false);
	    sucesso = false;
        document.getElementById('cep').className = 'error';
        document.getElementById('errocep').style.display = '';
        document.getElementById('errocep').innerHTML = 'Este CEP não foi encontrado no sistema dos Correios. Confira novamente os dados digitados. Caso esteja correto insira manualmente as informações sobre o seu endereço.';  
	}
	else
	{
	    //Limpando o campo caso seja necessário.
	    document.getElementById('cep').className = 'txtfield';
        document.getElementById('errocep').style.display = 'none';
	
	    resultadoCEP = result;
	    eval(retorno +'(resultadoCEP)');
	 }
}

function buscaCEPCorreios(controle){
    if(valida_CEP(document.getElementById('cep')))
    {
        DisabledElementos(true);
    
        if (resultadoCEP==null || resultadoCEP.cep!=document.getElementById('cep').value){
		    makeRequestCEP('_CEP.aspx?cep='+controle.value.replace('.','').replace('-',''),'getCEPUsuario');
	    }else{
		    getCEPUsuario(resultadoCEP);
	    }
	}
}

function DisabledElementos(controle)
{
    document.getElementById('cep').disabled = controle;
    document.getElementById('endereco').disabled = controle;
    document.getElementById('estado').disabled = controle;
    document.getElementById('cidade').disabled = controle;
    document.getElementById('bairro').disabled = controle;
    if(!controle)
        document.getElementById('img_cep').style.display = 'none';
    else
        document.getElementById('img_cep').style.display = '';
    
}


function getCEPUsuario(resultadoCEP)
{
    DisabledElementos(false);
    
    document.getElementById('bairro').value = CharSet(resultadoCEP.bairro);
    document.getElementById('endereco').value = CharSet(resultadoCEP.endereco);
    
    var estadoAtual = news_cadastro.DevolveCodigoEstado(CharSet(resultadoCEP.estado)).value
    if(estadoAtual!= 0)
    {
    
        //Percorrendo os estado para se selecionar o estado correto.
        for(var i = 0; i < document.getElementById('estado').length; i++)
        {
            var x=document.getElementById("estado")
            if(x.options[i].value == estadoAtual)
            {
                document.getElementById('estado').selectedIndex = i;
                break;
            }
        }

        //Carregando as cidades...
        document.getElementById('img_cidade').style.display = "";
        var dt = news_cadastro.PopulaCidade(estadoAtual).value;   
        var cidade = document.getElementById('cidade');
        cidade.options.length = 0;
        cidade.options[cidade.options.length] = new Option("Selecione uma cidade","0");            
        for(var i = 0; i < dt.length; i++)
        {                
           cidade.options[cidade.options.length] = new Option(dt[i].Nome, dt[i].Codigo_Cidade);
        }
        document.getElementById('img_cidade').style.display = "none";
        //Fim carregando as cidades...


        //Percorrendo as cidades para se selecionar a cidade correta.
        for(var i = 0; i < document.getElementById('cidade').length; i++)
        {
            var x=document.getElementById("cidade")
            if(x.options[i].text == CharSet(resultadoCEP.cidade))
            {
                document.getElementById('cidade').selectedIndex = i;
                break;
            }
        }
    }
}

function AlterarCadastro()
{
   var sucesso = true; 
   
//    document.getElementById('cpf').className = 'txtfield';
//    document.getElementById('errocpf').style.display = 'none';
    
    document.getElementById('alt_email').className = 'txtfield';
    document.getElementById('erroalt_email').style.display = 'none';
    
    document.getElementById('nao_encontrado_descadastrar').style.display = "none";
    

    
//    if(!EmptyField(document.getElementById('cpf')))
//    {
//          if(!valida_CPF(document.getElementById('cpf')))
//          {
//            document.getElementById('cpf').className = 'error';
//            document.getElementById('errocpf').style.display = '';
//            document.getElementById('errocpf').innerHTML = 'CPF em formato inválido.';  
//            sucesso = false;
//          }
//    }
//    else
//    {
//        document.getElementById('cpf').className = 'error';
//        document.getElementById('errocpf').style.display = '';
//        document.getElementById('errocpf').innerHTML = 'Por favor, informe o seu CPF.';  
//        sucesso = false;
//    }
    
     if(EmptyField(document.getElementById('alt_email')))
    {
        document.getElementById('alt_email').className = 'error';
        document.getElementById('erroalt_email').style.display = '';
        document.getElementById('erroalt_email').innerHTML = 'Por favor, informe o seu e-mail.';  
        sucesso = false;
    }
    
   if (!sucesso) {
        alert('Alguns campos não foram preenchidos da forma devida. Por favor, verifique os campos marcados em vermelho.'); 
        return false;
    }
    
    
    var id = news_alterar_cadastro.VerificaAlterar(document.getElementById('alt_email').value).value;
    
    if( id != "")
    {
        window.location = "news_cadastro.aspx?alt=true&id="+ id;
    }
    else
    {
//        document.getElementById('cpf').className = 'error';
        document.getElementById('alt_email').className = 'error';
        document.getElementById('nao_encontrado_descadastrar').style.display = "";
        
        //document.getElementById('nao_encontrado_descadastrar').style.display = "";
        //document.getElementById('form_alterar').style.display = "none";
    }
   
}


