
function ColoreObrigatorio(obrigatorio, form, classe) {

	for (var i = 0; i < obrigatorio.length; i++) {
		form.elements[obrigatorio[i]].className = classe;
	}

}


////////////////////////////////////////////////////////////////////////////////////
// Seta a classe de estilo 'obrigatorio' para os campos de preenchimento obrigatório
//
// @param obrigatorio (array) -> array com o nome dos campos obrigatórios
// @param form (form) -> o formulário onde estão os campos
//
// @return (bool) -> retorna false se algum campo estiver em branco
//
////////////////////////////////////////////////////////////////////////////////////
function checaObrigatorio2(obrigatorio, form) {
	var erro = new Array();

	ColoreObrigatorio(obrigatorio, form, 'obrigatorio');

	for (var i = 0; i < obrigatorio.length; i++) {
		if (form.elements[obrigatorio[i]].value == "") {
			 erro.push(obrigatorio[i]);
		}
	}
	if (erro.length > 0) {
		ColoreObrigatorio(erro, form, 'erro');
		alert('Os campos em destaque precisam ser preenchidos');
		return false;
	}
	else {
		return true;
	}
}
	

	function MostraDiv(div){
		var nomeDiv = div;
		document.getElementById(nomeDiv).style.display = 'block';
	}
	
	function EscondeDiv(div){
		var nomeDiv = div;
		document.getElementById(nomeDiv).style.display = 'none';
	}

//Função de Máscara para o Telefone 
function mascara_tel2(campo){	
	if(document.getElementById(campo).value.length == 2){
        document.getElementById(campo).value = '(' + document.getElementById(campo).value + ')';
        return false;
    }
    if(document.getElementById(campo).value.length == 8){
        document.getElementById(campo).value = document.getElementById(campo).value + '-';
        return false;
    }
}

//Função de Máscara para a Data
function mascara_data(campo){
    if(document.getElementById(campo).value.length == 2 || document.getElementById(campo).value.length == 5){
        document.getElementById(campo).value = document.getElementById(campo).value + '/';
        return false;
    }
}

// Função de somente números podem ser digitados
function SomenteNumero(e){
    var tecla=(window.event)?event.keyCode:e.which;
    if((tecla > 47 && tecla < 58)) return true;
    else{
    if (tecla != 8) return false;
    else return true;
    }
}

//Função Máscara do CEP
function MM_formtCep(e,src,mask) {
    if(window.event) { _TXT = e.keyCode; } 
    else if(e.which) { _TXT = e.which; }
    if(_TXT > 47 && _TXT < 58) { 
 var i = src.value.length; var saida = mask.substring(0,1); var texto = mask.substring(i)
 if (texto.substring(0,1) != saida) { src.value += texto.substring(0,1); } 
    return true; } else { if (_TXT != 8) { return false; } 
 else { return true; }
    }
}

function valida_email(campo){
	var invalid, s;
	invalid = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/;

	var s;
	// verifica se o email é válido
	if (document.getElementById(campo).value.length == 0)	{
		alert("Digite corretamente seu E-mail por favor!");
		document.getElementById(campo).value = "";
		document.getElementById(campo).focus();
		return false;	
	}

	if (invalid.test(document.getElementById(campo).value) == false) {
		// caso o teste falhe, para mudar a cor do texto na caixa, mude na linha abaixo
		alert("Endereço de E-mail inválido !");
		document.getElementById(campo).style.color = "red";		
		document.getElementById(campo).value = "";
		document.getElementById(campo).focus();
		return (false); 
	}

	document.getElementById(campo).style.color = "black";
     return true;
}

//MASCARA PARA CPF EXTENSÍVEL PARA TODOS OS FORMULÁRIO.
//O CAMPO QUE CHAMA ESTA FUNÇÃO DEVE TER UM ID, ALÉM DO NOME.
function mascara_cpf(campo){

    if(document.getElementById(campo).value.length == 3){
        document.getElementById(campo).value = document.getElementById(campo).value + '.';
        return false;
    }
    if(document.getElementById(campo).value.length == 7){
        document.getElementById(campo).value = document.getElementById(campo).value + '.';
        return false;
    }
    if(document.getElementById(campo).value.length == 11){
        document.getElementById(campo).value = document.getElementById(campo).value + '-';
        return false;
	}

}

//MASCARA PARA RG EXTENSÍVEL PARA TODOS OS FORMULÁRIO.
//O CAMPO QUE CHAMA ESTA FUNÇÃO DEVE TER UM ID, ALÉM DO NOME.
function mascara_rg(campo){

    if(document.getElementById(campo).value.length == 2){
        document.getElementById(campo).value = document.getElementById(campo).value + '-';
        return false;
    }
    if(document.getElementById(campo).value.length == 5){
        document.getElementById(campo).value = document.getElementById(campo).value + '.';
        return false;
    }
    if(document.getElementById(campo).value.length == 9){
        document.getElementById(campo).value = document.getElementById(campo).value + '.';
        return false;
	}
	if(document.getElementById(campo).value.length == 13){
        document.getElementById(campo).value = document.getElementById(campo).value + '-';
        return false;
	}

}

function limpa_string(S){
	// Deixa so' os digitos no numero
	var Digitos = "0123456789";
	var temp = "";
	var digito = "";

	for (var i=0; i<S.length; i++)	{
		digito = S.charAt(i);
		if (Digitos.indexOf(digito)>=0)	{
			temp=temp+digito	}
	} //for

	return temp
}
// fim da funcao

//Verifica se o CPF é válido
function valida_cnpjcpf(campo){
	if (document.getElementById(campo).value == '') {
		alert("O CPF é um campo obrigatório !");
		document.getElementById(campo).value = "";
		document.getElementById(campo).focus();
		return false;	}
		
	s = limpa_string(document.getElementById(campo).value);
	
	
	// checa se é cpf	
	if (s.length == 11) {
		if (valida_CPF(document.getElementById(campo).value) == false ) {
			document.getElementById(campo).style.color = "red";
			alert("O CPF não é válido !");
			document.getElementById(campo).value = "";
			document.getElementById(campo).focus();
			return false;	
		}
	}
	document.getElementById(campo).style.color = "black";
		
}
function valida_CPF(s)	{
	var i;
	s = limpa_string(s);
	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;
}

//---------------------------AJAX CIDADE-----------------------------//

function Dados(valor, id_option, id_select) {
      //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.getElementById(id_select).options.length = 1;
	     
		 idOpcao  = document.getElementById(id_option);
		 
	   ajax.open("GET", "http://www.sobrac.org.br/cidade.php?estado="+valor, 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) {
			      processXML(ajax.responseXML, id_option, id_select);
				  
			   }
			   else {
			       //caso não seja um arquivo XML emite a mensagem abaixo
				   idOpcao.innerHTML = "--Primeiro selecione o Estado--";
			   }
            }
         }
		 //passa o código do estado escolhido
	     var params = "estado="+valor;
         ajax.send(params);
      }
   }
   
   function processXML(obj, id_option, id_select){
      //pega a tag cidade
      var dataArray   = obj.getElementsByTagName("cidade");
      
	  //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 codigoestado    =  item.getElementsByTagName("codigoestado")[0].firstChild.nodeValue;
			var nome =  item.getElementsByTagName("nome")[0].firstChild.nodeValue;
			var codigo =  item.getElementsByTagName("codigo")[0].firstChild.nodeValue;
			
	        idOpcao.innerHTML = "--Selecione uma das opções abaixo--";
			
			//cria um novo option dinamicamente  
			var novo = document.createElement("option");
			    //atribui um ID a esse elemento
			    novo.setAttribute("id", id_option);
				//atribui um valor
			    novo.value = codigo;
				//atribui um texto
			    novo.text  = nome;
				//finalmente adiciona o novo elemento
				document.getElementById(id_select).options.add(novo);
		 }
	  }
	  else {
	    //caso o XML volte vazio, printa a mensagem abaixo
		idOpcao.innerHTML = "--Primeiro selecione o Estado--";
	  }	  
   }

//------------------FIM AJAX--------------------//








