// JavaScript Document
var er = new RegExp(/^[A-Za-z0-9_\-\.]+@[A-Za-z0-9_\-\.]{2,}\.[A-Za-z0-9]{2,}(\.[A-Za-z0-9])?/);
function mostrarDivs(id){
	if (id == 1) {
		func.style.display='block';
		adv.style.display='none';
	} else if (id == 2) {
		func.style.display='none';
		adv.style.display='block';
	} else if (id == 3) {		
		func.style.display='block';
		adv.style.display='block';
	} else {
		func.style.display='none';
		adv.style.display='none';
	}
}

function mascaraInteiro(){
    if (event.keyCode < 48 || event.keyCode > 57){
        event.returnValue = false;
        return false;
    }
    return true;
}

//formata de forma generica os campos
function formataCampo(campo, Mascara, evento) { 
    var boleanoMascara; 

    var Digitato = evento.keyCode;
    exp = /\-|\.|\/|\(|\)| /g
    campoSoNumeros = campo.value.toString().replace( exp, "" ); 
   
    var posicaoCampo = 0;     
    var NovoValorCampo="";
    var TamanhoMascara = campoSoNumeros.length;; 

    if (Digitato != 8) { // backspace 
        for(i=0; i<= TamanhoMascara; i++) { 
            boleanoMascara  = ((Mascara.charAt(i) == "-") || (Mascara.charAt(i) == ".")
                                || (Mascara.charAt(i) == "/")) 
            boleanoMascara  = boleanoMascara || ((Mascara.charAt(i) == "(") 
                                || (Mascara.charAt(i) == ")") || (Mascara.charAt(i) == " ")) 
            if (boleanoMascara) { 
                NovoValorCampo += Mascara.charAt(i); 
                  TamanhoMascara++;
            }else { 
                NovoValorCampo += campoSoNumeros.charAt(posicaoCampo); 
                posicaoCampo++; 
              }            
          }     
        campo.value = NovoValorCampo;
          return true; 
    }else { 
        return true; 
    }
}

//adiciona mascara de data
function MascaraData(data){
    if(mascaraInteiro(data)==false){
        event.returnValue = false;
    }    
    return formataCampo(data, '00/00/0000', event);
}


//valida o CPF digitado
function ValidarCPF(Objcpf){
    var cpf = Objcpf.value;
    exp = /\.|\-/g
    cpf = cpf.toString().replace( exp, "" ); 
    var digitoDigitado = eval(cpf.charAt(9)+cpf.charAt(10));
    var soma1=0, soma2=0;
    var vlr =11;
    
    for(i=0;i<9;i++){
        soma1+=eval(cpf.charAt(i)*(vlr-1));
        soma2+=eval(cpf.charAt(i)*vlr);
        vlr--;
    }    
    soma1 = (((soma1*10)%11)==10 ? 0:((soma1*10)%11));
    soma2=(((soma2+(2*soma1))*10)%11);
    
    var digitoGerado=(soma1*10)+soma2;
    if(digitoGerado!=digitoDigitado)   
        alert('Atenção: CPF Inválido!');
}

function MascaraCPF(cpf){
    if(mascaraInteiro(cpf)==false){
        event.returnValue = false;
    }    
    return formataCampo(cpf, '000.000.000-00', event);
}


function MascaraCep(cep){
        if(mascaraInteiro(cep)==false){
        event.returnValue = false;
    }    
    return formataCampo(cep, '00.000-000', event);
}


//preenxe o campo 'campo' com o valor 'valor'
function preenche(campo,valor) {
	document.cadassociado.elements[campo].value = valor;
}
///////////////////////////////////////////////////////////
///////// AJAX DE CARREGAMENTO DE ESTADO -> CIDADES
//////////////////////////////////////////////////////////

function Dadosb(campo,arquivo,valor) {
//verifica se o browser tem suporte a ajax
	try {
    	ajax = new ActiveXObject("Microsoft.XMLHTTP");
	} catch(e) {
		try {
			ajax = new ActiveXObject("Msxml2.XMLHTTP");
		} catch(ex) {
			try {
				ajax = new XMLHttpRequest();
			} catch(exc) {
				alert("Esse browser não tem recursos para uso do Ajax");
				ajax = null;
			}
		}
	}
//se tiver suporte ajax
	if(ajax) {
//deixa apenas o elemento 1 no option, os outros são excluídos
		document.cadassociado.elements[campo].options.length = 1;
		idOpcao  = document.getElementById("opcoes");
		ajax.open("POST", ""+arquivo+"", true);
		ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		ajax.onreadystatechange = function() {
			
//enquanto estiver processando...emite a msg de carregando
		if(ajax.readyState == 1) {
			idOpcao.innerHTML = "Carregando...!";   
		}
//após ser processado - chama função processXML que vai varrer os dados
		if(ajax.readyState == 4 ) {
			if(ajax.responseXML) {
				processXMLb(campo,ajax.responseXML);
			} else {
//caso não seja um arquivo XML emite a mensagem abaixo
				idOpcao.innerHTML = "Selecione o Item Acima.";
			}
		}
	}
//passa o código do estado escolhido
	var params = "consulta="+valor;
//	alert(params);
	ajax.send(params);
	}
}
  
function processXMLb(campo,obj){
      //pega a tag cidade

      var dataArray   = obj.getElementsByTagName("opc");

	  //total de elementos contidos na tag cidade
	  if(dataArray.length > 0) {
	     //percorre o arquivo XML paara extrair os dados
         for(var i = 0 ; i < dataArray.length ; i++) {
            var item = dataArray[i];
			//contéudo dos campos no arquivo XML
			var codigo    =  item.getElementsByTagName("codigo")[0].firstChild.nodeValue;
			var descricao =  item.getElementsByTagName("descricao")[0].firstChild.nodeValue;
			
	        idOpcao.innerHTML = "Selecione uma Opção";
			
			//cria um novo option dinamicamente  
			var novo = document.createElement("option");
			    //atribui um ID a esse elemento
			    novo.setAttribute("id", "opcoes");
				//atribui um valor
			    novo.value = codigo;
				//atribui um texto
			    novo.text  = descricao;
				//finalmente adiciona o novo elemento
//				document.forms[0].listBairros.options.add(novo);
				document.cadassociado.elements[campo].options.add(novo);
		 }
	  }
	  else {
	    //caso o XML volte vazio, printa a mensagem abaixo
		idOpcao.innerHTML = "Seleciona uma Opção Abaixo";
	}	  
}

function foco(){
	document.cadassociado.rg.focus();
}

function foco_cadastro(){
	document.cadassociado.cpf.focus();
}

function checkForm() {
	nome		= document.getElementById('nome').value;
	email		= document.getElementById('email').value;
	matricula	= document.getElementById('matricula').value;	
	
	if (nome == "") {
		alert("O nome é obrigatorio!");
		document.getElementById('nome').focus();
		return false;
	}
	
	if (email.value == ""){
		alert("O e-mail deve ser preenchido!");
		document.getElementById('email').focus();
		return false;
	}

	if (!(er.test(email))) { 
		alert("O campo e-mail deve ser conter um endereço eletronico valido!");
		document.getElementById('email').focus();
		return false;
	}

	if (matricula == "") {
		alert("A matricula é obrigatorio!");
		document.getElementById('matricula').focus();
		return false;
	}

	return true;
}

function checkForm_cadastro() {
	cpf			= document.getElementById('cpf').value;	
	nome		= document.getElementById('nome').value;
	email		= document.getElementById('email').value;
	senha		= document.getElementById('senha').value;
	c_senha		= document.getElementById('c_senha').value;	
	matricula	= document.getElementById('matricula').value;	
	
	if (ValidarCPF(cadassociado.cpf)) {
		alert("O cpf é invalido!");
		document.getElementById('cpf').focus();
		return false;
	}
	
	if (nome == "") {
		alert("O nome é obrigatorio!");
		document.getElementById('nome').focus();
		return false;
	}

	if (email.value == ""){
		alert("O e-mail deve ser preenchido!");
		document.getElementById('email').focus();
		return false;
	}

	if (!(er.test(email))) { 
		alert("O campo e-mail deve ser conter um endereço eletronico valido!");
		document.getElementById('email').focus();
		return false;
	}

	if (matricula == "") {
		alert("A matricula é obrigatorio!");
		document.getElementById('matricula').focus();
		return false;
	}

	if (senha == "") {
		alert("A senha é obrigatorio!");
		document.getElementById('senha').focus();
		return false;
	}
	
	if (senha != c_senha) {
		alert("A confirmação da senha é inválida!");
		document.getElementById('senha').focus();
		return false;
	}
	

	return true;
}

function contrato(id) {
	window.open('contrato.php?idcadastro='+id,'Extorno', 'left=50,top=50,width=640,height=480,toolbar=0,resizable=0,scrollbars=2,statusbar=1');		
}

