var emailJaCadastrado = false;
var cpfJaCadastrado = false;
var emailAmigoCadastrado = true;
var dataValida = true;
var senhaAtualCorreta = false;


function alertaAlteracao(campo){
	if(campo.readOnly){
		alert("Para alterar este campo entre em contato com a equipe do pelo e-mail contato@vale1convite.com.br e explique seu motivo.");
		return false;
	}
}

function termo() {
	w = window.open('termo.php','termo','toolbar=no,width=400,height=350,directories=no,scrollbars=yes,status=no,resize=no,menubar=no');
	w.focus();
}
function abreCEP() {
	w = window.open('cep.php','cep','toolbar=no,width=400,height=350,directories=no,scrollbars=yes,status=no,resize=no,menubar=no');
	w.focus();
}

function abreJanelaEsqueceuSenha(){
	var email = document.getElementById('email').value;
	w = window.open('../minhaconta/senha.php?email='+email,'senha','toolbar=no,width=250,height=250,directories=no,scrollbars=no,status=no,resize=no,menubar=no')
	w.focus();
}

function abreJanelaProblemaCPF(){
	var cpf = document.getElementById('cpf').value;
	var email = document.getElementById('email').value;
	var nome = document.getElementById('nome').value+" "+document.getElementById('sobrenome').value;
	w = window.open('problema.php?cpf='+cpf+'&email='+email+'&nome='+nome,'problema','toolbar=no,width=300,height=300,directories=no,scrollbars=no,status=no,resize=no,menubar=no');
	w.focus();
}

function habilitaBotaoSalvar(chkbox){
	var botao = document.getElementById('btnSalvar');
	if(chkbox.checked == true){
		botao.disabled = false;
	} else {
		botao.disabled = true;
	}
}

function ajaxInit() {
	http_request = false;
    if (window.XMLHttpRequest) { // Mozilla, Safari,...
        http_request = new XMLHttpRequest();
        if (http_request.overrideMimeType) {
            http_request.overrideMimeType('text/xml');
            // See note below about this line
        }
    } else if (window.ActiveXObject) { // IE
        try {
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
        }
    }
	return http_request;
}

function buscaEndereco(campo){
	if(campo.value.length == 0){
		return true;
	}
	if(campo.value.length < 9){
		alert("CEP incompleto");
		campo.select();
		return false;
	}
	if(campo.value == ""){
		return false;
	}
	var cep = campo.value;
	ajax = ajaxInit();
	if(!ajax){
		alert("Erro no Ajax");
		return false;
	}
	setTimeout("",100);
	if(ajax) {
		ajax.onreadystatechange = preencheEndereco;
		ajax.open("GET", "buscaCep.php?cep="+cep, true);
		ajax.send(null);
	} else {
		alert("Erro no Ajax");
	}
}

function preencheEndereco(){
	if (ajax.readyState == 4) {
        if (ajax.status == 200) {
            var endereco = "";
			var bairro = "";
			var cidade = "";
			var estado = "";            
            var xmldoc = ajax.responseXML;
			if(xmldoc.getElementsByTagName('endereco').item(0).firstChild != null){
				var endereco = xmldoc.getElementsByTagName('endereco').item(0).firstChild.data;
			}
			if(xmldoc.getElementsByTagName('bairro').item(0).firstChild != null){
				var bairro = xmldoc.getElementsByTagName('bairro').item(0).firstChild.data;
			}
			if(xmldoc.getElementsByTagName('cidade').item(0).firstChild != null){
				var cidade = xmldoc.getElementsByTagName('cidade').item(0).firstChild.data;
			}
			if(xmldoc.getElementsByTagName('estado').item(0).firstChild != null){
				var estado = xmldoc.getElementsByTagName('estado').item(0).firstChild.data;
			}
			var msgCEP = document.getElementById('msgCEP');
			if(endereco == "" && bairro == "" && cidade == "" && estado == ""){
				msgCEP.className = 'alerta';
				msgCEP.innerHTML = 'CEP Inválido!';
				document.getElementById('cep').select();
			} else {
				msgCEP.className = 'alertaVerde';
				msgCEP.innerHTML = 'OK';
				document.getElementById('linhaEstado').style.display='';
				document.getElementById('linhaCidade').style.display='';
				document.getElementById('linhaBairro').style.display='';
				document.getElementById('linhaEndereco').style.display='';
				document.getElementById('linhaComplemento').style.display='';
				if(bairro == ""){
					document.getElementById('bairro').select();
				} else {
					document.getElementById('complemento').select();
				}
			}
			document.getElementById('endereco').value = endereco;
			document.getElementById('bairro').value = bairro;
			document.getElementById('cidade').value = cidade;
			document.getElementById('estado').value = estado;
        } else {
            alert('There was a problem with the request.');
        }
    }
}

function verificaEmailCadastrado(campo, email){
	var msgEmail = document.getElementById('msgEmail');
	if(campo.value == "" || (campo.value == email)){
		msgEmail.innerHTML = "";
		return true;
		emailJaCadastrado = false;
	}
	if(validaEmail(campo)){
		ajax = ajaxInit();
		if(!ajax){
			alert("Erro no Ajax");
			return false;
		}
		setTimeout("",100);
		if(ajax) {
			ajax.onreadystatechange = preencheMsgEmail;
			ajax.open("GET", "buscaEmailCadastrado.php?email="+campo.value, true);
			ajax.send(null);
		} else {
			alert("Erro no Ajax");
		}
	} else {		
		msgEmail.className = 'alerta';
		msgEmail.innerHTML = 'E-Mail Incorreto!';
		campo.select();
	}
}

function preencheMsgEmail(){
	if (ajax.readyState == 4) {
        if (ajax.status == 200) {
            var msgEmail = document.getElementById('msgEmail');
            var xmldoc = ajax.responseXML;
			if(xmldoc.getElementsByTagName('usuarioCadastrado').item(0).firstChild != null){
				msgEmail.className = 'alerta';
				msgEmail.innerHTML = "E-Mail já cadastrado!<br>Dúvidas <a href='#' onclick='abreJanelaEsqueceuSenha()' class='alerta'>clique aqui!</a>";
				document.getElementById('email').select();
				emailJaCadastrado = true;
			} else {
				msgEmail.className = 'alertaVerde';
				msgEmail.innerHTML = 'OK';
				emailJaCadastrado = false;
				document.getElementById('nome').select();
			}
        } else {
            alert('There was a problem with the request.');
        }
    }
}

function verificaCPFCadastrado(campo){
	var msgCPF = document.getElementById('msgCPF');
	if(campo.value == ""){
		msgCPF.innerHTML = "";
		return true;
	}
	if(validaCPF(campo)){
		ajax = ajaxInit();
		if(!ajax){
			alert("Erro no Ajax");
			return false;
		}
		setTimeout("",100);
		if(ajax) {
			ajax.onreadystatechange = preencheMsgCPF;
			ajax.open("GET", "buscaCPFCadastrado.php?cpf="+campo.value, true);
			ajax.send(null);
		} else {
			alert("Erro no Ajax");
		}
	} else {		
		msgCPF.className = 'alerta';
		msgCPF.innerHTML = 'CPF Incorreto!';
		campo.select();
	}
}

function preencheMsgCPF(){
	if (ajax.readyState == 4) {
        if (ajax.status == 200) {
            var msgCPF = document.getElementById('msgCPF');
            var xmldoc = ajax.responseXML;
			if(xmldoc.getElementsByTagName('usuarioCadastrado').item(0).firstChild != null){
				msgCPF.className = 'alerta';
				msgCPF.innerHTML = "CPF já cadastrado!<br>Dúvidas <a href='#' onclick='abreJanelaProblemaCPF()' class='alerta'>clique aqui!</a>";
				cpfJaCadastrado = true;
				document.getElementById('cpf').select();
			} else {
				msgCPF.className = 'alertaVerde';
				msgCPF.innerHTML = 'OK';
				cpfJaCadastrado = false;
				document.getElementById('sexo').select();
			}
        } else {
            alert('There was a problem with the request.');
        }
    }
}

function verificaEmailAmigo(campo){
	var msgEmail = document.getElementById('msgEmailAmigo');
	if(campo.value == ""){
		msgEmail.innerHTML = "";
		return true;
	}
	if(validaEmail(campo)){
		ajax = ajaxInit();
		if(!ajax){
			alert("Erro no Ajax");
			return false;
		}
		setTimeout("",100);
		if(ajax) {
			ajax.onreadystatechange = preencheMsgEmailAmigo;
			ajax.open("GET", "buscaEmailCadastrado.php?email="+campo.value, true);
			ajax.send(null);
		} else {
			alert("Erro no Ajax");
		}
	} else {		
		msgEmail.className = 'alerta';
		msgEmail.innerHTML = 'E-Mail Incorreto!';
		campo.select();
	}
}

function preencheMsgEmailAmigo(){
	if (ajax.readyState == 4) {
        if (ajax.status == 200) {
            var msgEmail = document.getElementById('msgEmailAmigo');
            var nomeAmigo = document.getElementById('nome_amigo');
            var xmldoc = ajax.responseXML;
			if(xmldoc.getElementsByTagName('usuarioCadastrado').item(0).firstChild != null){
				msgEmail.className = 'alertaVerde';
				msgEmail.innerHTML = xmldoc.getElementsByTagName('usuarioCadastrado').item(0).firstChild.data;
				nomeAmigo.value = xmldoc.getElementsByTagName('usuarioCadastrado').item(0).firstChild.data;
				emailAmigoCadastrado = true;
				document.getElementById('senha').select();
			} else {
				msgEmail.className = 'alerta';
				msgEmail.innerHTML = 'E-Mail não cadastrado!';
				nomeAmigo.value = "";
				emailAmigoCadastrado = false;
				document.getElementById('email_amigo').select();		
			}
        } else {
            alert('There was a problem with the request.');
        }
    }
}

function verificaSenhaAtual(campo){
	var msgEmail = document.getElementById('msgSenhaAtual');
	if(campo.value == ""){
		msgEmail.innerHTML = "";
		return true;
	}
	ajax = ajaxInit();
	if(!ajax){
		alert("Erro no Ajax");
		return false;
	}
	setTimeout("",100);
	if(ajax) {
		ajax.onreadystatechange = preencheMsgSenhaAtual;
		ajax.open("GET", "buscaSenhaAtual.php?senha="+campo.value, true);
		ajax.send(null);
	} else {
		alert("Erro no Ajax");
	}
}

function preencheMsgSenhaAtual(){
	if (ajax.readyState == 4) {
        if (ajax.status == 200) {
            var msgSenhaAtual = document.getElementById('msgSenhaAtual');
            var xmldoc = ajax.responseXML;
			if(xmldoc.getElementsByTagName('idUsuario').item(0).firstChild != null){
				msgSenhaAtual.className = 'alertaVerde';
				msgSenhaAtual.innerHTML = 'OK';
				senhaAtualCorreta = true;
				document.getElementById('senha').select();
			} else {
				msgSenhaAtual.className = 'alerta';
				msgSenhaAtual.innerHTML = 'Senha Atual Incorreta!';
				senhaAtualCorreta = false;
				document.getElementById('senhaAtual').select();
			}
        } else {
            alert('There was a problem with the request.');
        }
    }
}

function verificaDigitacaoCPF(campo, e){
	if (e.keyCode) code = e.keyCode;
	else if (e.which) code = e.which;
	if(code == 0 || code == 8 || code == 9 || code == 13 || code == 27){
		return true;
	}
	if(code >= 48 && code <= 57){
		if(campo.value.length == 9){
			campo.value = campo.value+"-";
		}
		return true;
	}
	return false;
}

function verificaDigitacaoCEP(campo, e){
	if (e.keyCode) code = e.keyCode;
	else if (e.which) code = e.which;
	if(code == 0 || code == 8 || code == 9 || code == 13 || code == 27){
		return true;
	}
	if(code >= 48 && code <= 57){
		if(campo.value.length == 5){
			campo.value = campo.value+"-";
		}
		return true;
	}
	return false;
}

function verificaDigitacaoData(campo, e){
	if (e.keyCode) code = e.keyCode;
	else if (e.which) code = e.which;
	if(code == 0 || code == 8 || code == 9 || code == 13 || code == 27){
		return true;
	}
	if(code >= 48 && code <= 57){
		if(campo.value.length == 2 || campo.value.length == 5){
			campo.value = campo.value+"/";
		}
		return true;
	}
	return false;
}

function verificaDigitacaoDDD(campo, e){
	if (e.keyCode) code = e.keyCode;
	else if (e.which) code = e.which;
	if(code == 0 || code == 8 || code == 9 || code == 13 || code == 27){
		return true;
	}
	// 0 (zero) não é válido
	if(code >= 49 && code <= 57){
		campo.value = campo.value + String.fromCharCode(code);
		if(campo.value.length == 2){
			var proxCampo = "";
			if(campo.name == 'ddd'){
				proxCampo = 'telefone';
			} else {
				proxCampo = 'telefone2';
			}
			document.getElementById(proxCampo).focus();
		}
	}
	return false;
}

function verificaDigitacaoTelefone(campo, e){
	if (e.keyCode) code = e.keyCode;
	else if (e.which) code = e.which;
	if(code == 0 || code == 8 || code == 9 || code == 13 || code == 27){
		return true;
	}
	if(code >= 48 && code <= 57){
		return true;
	}
	return false;
}

function verificaDigitacaoSenha(campo, e){
	if (e.keyCode) code = e.keyCode;
	else if (e.which) code = e.which;
	if(code == 0 || code == 8 || code == 9 || code == 13 || code == 27){
		return true;
	}
	if((code >= 48 && code <= 57) || (code >= 65 && code <= 90) || (code >= 97 && code <= 122)){
		return true;
	} else {
		alert ('Só podem haver caracteres alfanumérios (\'0\' a \'1\' e \'a\' a \'z\')');
		return false;
	}
}

function validaData(campo){
	var msgData = document.getElementById('msgData');
	if(campo.value == ""){
		return true;
	}
	var erro = true;
	if(campo.value.length == 10){
		var t = campo.value.split("/");
		if(t[0].length == 2 && t[1].length == 2 && t[2].length == 4){
			var d = new Date();
			if(t[2].valueOf() > d.getFullYear() - 100 && t[2].valueOf() < d.getFullYear()){
				if(t[0].valueOf() > 0 && t[0].valueOf() < 32 && t[1].valueOf() > 0 && t[1].valueOf() < 13){
					erro = false;
				}
			}
		}
	}
	if(erro){
		msgData.className = 'alerta';
		msgData.innerHTML = "Data Inválida!";
		dataValida = false;
		campo.select();
	} else {
		msgData.className = 'alertaVerde';
		msgData.innerHTML = "OK";
		dataValida = true;
	}
}

function validaCPF(campo){
	var i;
	var retorno = true;
	s = campo.value;
	if(s == ""){
		return true;
	}
	if(s.length != 12){
		return false;
	}
	if(s.charAt(9) != "-"){
		return false;
	}
	s = s.replace(/\-/g,"");
	s = s.replace(/\./g,"");
	var c = s.substr(0,9);
	var dv = s.substr(9,2);
	var d1 = 0;
	for (i = 0; i < 9; i++){
		d1 += c.charAt(i)*(10-i);
	}
	if (d1 == 0){
		return false;
	}
	d1 = 11 - (d1 % 11);
	if (d1 > 9) d1 = 0;
	if (dv.charAt(0) != d1){
		return false;
	}
	d1 *= 2;
	for (i = 0; i < 9; i++){
		d1 += c.charAt(i)*(11-i);
	}
	d1 = 11 - (d1 % 11);
	if (d1 > 9) d1 = 0;
	if (dv.charAt(1) != d1){
		return false;
	}
	return true;
}

function validaEmail(campo){
	prim = campo.value.indexOf("@")
	if(prim < 2) {
		campo.select();
		return false;
	}
	if(campo.value.indexOf("@",prim + 1) != -1) {
		campo.select();
		return false;
	}
	if(campo.value.indexOf(".") < 1) {
		campo.select();
		return false;
	}
	if(campo.value.charAt(campo.value.length-1) == ".") {
		campo.select();
		return false;
	}
	if(campo.value.indexOf(" ") != -1) {
		campo.select();
		return false;
	}
	if(campo.value.indexOf("zipmeil.com") > 0) {
		campo.select();
		return false;
	}
	if(campo.value.indexOf("hotmeil.com") > 0) {
		campo.select();
		return false;
	}
	if(campo.value.indexOf(".@") > 0) {
		campo.select();
		return false;
	}
	if(campo.value.indexOf("@.") > 0) {
		campo.select();
		return false;
	}
	if(campo.value.indexOf(".com.br.") > 0) {
		campo.select();
		return false;
	}
	if(campo.value.indexOf("/") > 0) {
		campo.select();
		return false;
	}
	if(campo.value.indexOf("[") > 0) {
		campo.select();
		return false;
	}
	if(campo.value.indexOf("]") > 0) {
		campo.select();
		return false;
	}
	if(campo.value.indexOf("(") > 0) {
		campo.select();
		return false;
	}
	if(campo.value.indexOf(")") > 0) {
		campo.select();
		return false;
	}
	if(campo.value.indexOf("..") > 0) {
		campo.select();
		return false;
	}
	if(campo.value.indexOf(",") > 0) {
		campo.select();
		return false;
	}
	
	return true;
}

function validaSexo(){
	var s = document.getElementsByName('sexo');
	if(s[0].checked == true || s[1].checked == true){
		return true;
	}
	return false;
}

function mostraCamposSenha(mostrar){
	var senhaAtual = document.getElementById('linhaSenhaAtual');
	var senha = document.getElementById('linhaSenha');
	var senha2 = document.getElementById('linhaSenha2');
	if(mostrar){
		senhaAtual.style.display = "";
		senha.style.display = "";
		senha2.style.display = "";
	} else {
		senhaAtual.style.display = "none";
		senha.style.display = "none";
		senha2.style.display = "none";
	}
}

function validaCampos(tipoCadastro){
	
	if(document.getElementById('email').value == ""){
		alert("Informe seu e-mail!");
		return false;
	} else {
		if(!validaEmail(document.getElementById('email'))){
			alert('E-Mail incorreto!');
			return false;
		}
		if(emailJaCadastrado){
			alert("O E-Mail que você está tentando cadastrar já está cadastrado no Vale1Convite.")
			return false;
		}
	}
	if(document.getElementById('nome').value == ""){
		alert("Informe seu nome!");
		return false;
	}
	if(document.getElementById('sobrenome').value == ""){
		alert("Informe seu sobrenome!");
		return false;
	}
	if(document.getElementById('cpf').value == ""){
		alert("Informe CPF!");
		return false;
	} else if(cpfJaCadastrado){
		alert("O CPF que você está tentando cadastrar já está cadastrado no Vale1Convite!")
		return false;
	} else if(!validaCPF(document.getElementById('cpf'))){
		alert("CPF Inválido!");
		return false;
	}
	if(!validaSexo()){
		alert("Selecione seu sexo!");
		return false;
	}
	if(document.getElementById('ddd').value == ""){
		alert("Informe o DDD do seu telefone!");
		return false;
	}
	if(document.getElementById('telefone').value == ""){
		alert("Informe seu telefone!");
		return false;
	}
	if(document.getElementById('ddd2').value == ""){
		alert("Informe o DDD do seu celular!");
		return false;
	}
	if(document.getElementById('telefone2').value == ""){
		alert("Informe seu celular!");
		return false;
	}
	if(tipoCadastro == 'completo'){
		if(document.getElementById('nascimento').value == ""){
			alert("Informe sua Data de Nascimento!");
			return false;
		} else {
			if(!dataValida){
				alert("Data de Nascimento incorreta!");
				return false;
			}
		}
		if(document.getElementById('cep').value == ""){
			alert("cep!");
			return false;
		}
		if(document.getElementById('complemento').value == ""){
			alert("Informe o complemento do seu endereço!");
			return false;
		}
		if(document.getElementById('indicadoSim').checked == true){
			if(document.getElementById('email_amigo').value == ""){
				alert("Você precisa informar seu amigo que indicou o Vale1Convite!");
				return false;
			}
			if(!emailAmigoCadastrado){
				alert("O E-Mail do amigo que o indicou não está cadastrado no Vale1Convite!")
				return false;
			}
			
		}
		if(document.getElementById('radioCadastroAdicionalSim').checked == true){
			var estadoCivil = document.getElementById('estadocivil').selectedIndex;
			var escolaridade = document.getElementById('escolaridade').selectedIndex;
			var ocupacao = document.getElementById('ocupacao').selectedIndex;
			var renda = document.getElementById('renda').selectedIndex;
			var casa = document.getElementById('casa').selectedIndex;
			var op_cel = document.getElementById('op_cel').selectedIndex;
			if(estadoCivil == 0 || escolaridade == 0 || ocupacao == 0 || renda == 0 || casa == 0 || op_cel == 0){
				alert("Para ganhar mais 300 pontos, você precisa preencher todos os campos do cadastro adicional!");
				return false;
			}
		}
	}
	var alteraSenhaSim = document.getElementById('alteraSenhaSim');
	if(typeof alteraSenhaSim == 'undefined' || alteraSenhaSim == null){
		if(document.getElementById('senha').value == ""){
			alert("Informe sua senha!");
			return false;
		}
		if(document.getElementById('senha').value != document.getElementById('senha2').value){
			alert("Senhas não conferem!");
			return false;
		}
	} else {
		if(alteraSenhaSim.checked){
			if(!senhaAtualCorreta){
				alert("Senha atual não confere.");
				return false;
			} else {
				if(document.getElementById('senha').value == ""){
					alert("Informe sua nova senha!");
					return false;
				}
				if(document.getElementById('senha').value != document.getElementById('senha2').value){
					alert("Senhas não conferem!");
					return false;
				}	
			}
		}
	}
	return true;
}