﻿// 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('empresa').className = 'txtfield';
    document.getElementById('erroempresa').style.display = 'none';
    
    document.getElementById('cpf').className = 'txtfield';
    document.getElementById('errocpf').style.display = 'none';
        
    document.getElementById('nascimento').className = 'txtfield';
    document.getElementById('erronascimento').style.display = 'none';
    
    document.getElementById('endereco').className = 'txtfield';
    document.getElementById('erroendereco').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('email').className = 'txtfield';
    document.getElementById('erroemail').style.display = 'none';
    
    document.getElementById('area').className = 'txtfield';
    document.getElementById('erroarea').style.display = 'none';
    
    document.getElementById('funcao').className = 'txtfield';
    document.getElementById('errofuncao').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('empresa')))
    {
        sucesso = false;
        document.getElementById('empresa').className = 'error';
        document.getElementById('erroempresa').style.display = '';
        document.getElementById('erroempresa').innerHTML = 'Por favor, informe a empresa.';  
    }    
    
    if(EmptyField(document.getElementById('cpf')))
        {
            sucesso = false;
            document.getElementById('cpf').className = 'error';
            document.getElementById('errocpf').style.display = '';
            document.getElementById('errocpf').innerHTML = 'Por favor, informe seu CPF.';  
        }
        else
        {
          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.';  
          }
          if(Jornalista.CPFExistente(document.getElementById('cpf').value, document.getElementById('id_user').value).value)
          {
              sucesso = false;
              document.getElementById('cpf').className = 'error';
              document.getElementById('errocpf').style.display = '';
              document.getElementById('errocpf').innerHTML = 'Este CPF já existe em nosso cadastro.';  
          }
    }
    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.';  
        }
    }
    else
    {
        sucesso = false;
        document.getElementById('fone_residencial').className = 'error';
        document.getElementById('errofone_residencial').style.display = '';
        document.getElementById('errofone_residencial').innerHTML = 'Por favor, informe o seu telefone para contato.';  
    }
    
    if (!EmptyField(document.getElementById('nascimento')))
    {
        if(!valida_data(document.getElementById('nascimento')))
        {
            sucesso = false;
            document.getElementById('nascimento').className = 'error';
            document.getElementById('erronascimento').style.display = '';
            document.getElementById('erronascimento').innerHTML = 'Data em formato inválido.';  
        }
    }
    if(EmptyField(document.getElementById('email')))
    {
        sucesso = false;
        document.getElementById('email').className = 'error';
        document.getElementById('erroemail').style.display = '';
        document.getElementById('erroemail').innerHTML = 'Por favor, informe um e-mail para contato.';  
    }
    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('form_login')))
    {
        sucesso = false;
        document.getElementById('form_login').className = 'error';
        document.getElementById('erroform_login').style.display = '';
        document.getElementById('erroform_login').innerHTML = 'Por favor, informe o login de acesso.';  
    }
    else
    {
        if(Jornalista.LoginExistente(document.getElementById('form_login').value, document.getElementById('id_user').value).value)
        {
            sucesso = false;
            document.getElementById('form_login').className = 'error';
            document.getElementById('erroform_login').style.display = '';
            document.getElementById('erroform_login').innerHTML = 'Este login já existe. Por favor, crie outro login.';  
        }
    }
    if(!EmptyField(document.getElementById('id_user')))//Está se alterando um cadastro.
    {   
        if(!EmptyField(document.getElementById('form_senha')) && !validaSenha(document.getElementById('form_senha')))
        {
            sucesso = false;
            document.getElementById('form_senha').className = 'error';
            document.getElementById('erroform_senha').style.display = '';
            document.getElementById('erroform_senha').innerHTML = 'Para sua segurança a senha deve ter no mínimo 6 dígitos, deve conter letras e números (mínimo 3 números), não pode conter os seqüenciais 1234 ou 4321 e não é permitido colocar o ano como senha.  ';      
        }
    }
    else//Está se inserindo um cadastro
    {
        if(EmptyField(document.getElementById('form_senha')))
        {
            sucesso = false;
            document.getElementById('form_senha').className = 'error';
            document.getElementById('erroform_senha').style.display = '';
            document.getElementById('erroform_senha').innerHTML = 'Por favor, informe sua senha de acesso.';  
        }
        else
        {
            if(!validaSenha(document.getElementById('form_senha')))
            {
                sucesso = false;
                document.getElementById('form_senha').className = 'error';
                document.getElementById('erroform_senha').style.display = '';
                document.getElementById('erroform_senha').innerHTML = 'Para sua segurança a senha deve ter no mínimo 6 dígitos, deve conter letras e números (mínimo 3 números), não pode conter os seqüenciais 1234 ou 4321 e não é permitido colocar o ano como senha.  ';      
            }
        }
    }
    //verifica email

    
    
    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 _empresa =  document.getElementById('empresa').value;
    var _cpf = document.getElementById('cpf').value;
    var _dtNascimento = document.getElementById('nascimento').value;
    var _endereco = document.getElementById('endereco').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 _email = document.getElementById('email').value;
    var _veiculo = document.getElementById('veiculo').value;
    var _area = document.getElementById('area').value;
    var _funcao = document.getElementById('funcao').value;
    var _login = document.getElementById('form_login').value;
    var _senha = document.getElementById('form_senha').value;
     var id = document.getElementById('id_user').value;
    
   
    document.body.style.cursor = 'wait';
    
    //Inserindo Pessoa Física.
    var tipo = Jornalista.InserirJornalista(_nome,_empresa,_cpf,_dtNascimento,_endereco,_bairro,_estado,_cidade,_cep,_telResidencial,_telComercial,_telCelular,_email,_area,_funcao,_veiculo,_login, _senha,id).value;
    if(tipo == 1)
    {
        document.getElementById('sucesso_cadastro_jornalista').style.display = '';
        document.getElementById('erro_cadastro_jornalista').style.display = 'none';
        document.getElementById('form_cadastro').style.display = 'none';
        document.body.style.cursor = 'default';
        window.location = 'sala_imprensa.aspx';
    }
    else if(tipo == 2)
    {
         document.getElementById('sucesso_altera_jornalista').style.display = '';
        document.getElementById('erro_cadastro_jornalista').style.display = 'none';
        document.getElementById('form_cadastro').style.display = 'none';
        document.body.style.cursor = 'default';
        window.location = 'sala_imprensa.aspx';
    }
    else if(tipo == 0)
    {
        document.getElementById('sucesso_cadastro_jornalista').style.display = 'none';
        document.getElementById('erro_cadastro_jornalista').style.display = '';
        document.getElementById('form_cadastro').style.display = 'none';
        document.body.style.cursor = 'default';
    }
    document.body.style.cursor = 'default';
}

//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 = "";
    Jornalista.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 EnterCadastroJornalista(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 = Jornalista.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 = Jornalista.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 CPFExistente()
{
alert('vivi');

}


