function exibemensagem(mensagem) {
	alert(mensagem);
	location.href="./";
}

function exibemensagemerro(mensagem) {
	alert(mensagem);
	history.go(-1);
}

function setLength(id, length){
   document.getElementById(id).setAttribute('maxlength', length);
}

function valida_tamanho_cpf_cnpj() {
	d = document.formCadastro;

	if (d.tipo_documento.value == "") {
		d.cpf_cnpj.value = "";
		document.getElementById('cpf_cnpj').disabled = true;
		return false;
	}

	if (d.tipo_documento.value == "CPF") {
		d.cpf_cnpj.value = "";		
		document.getElementById('cpf_cnpj').disabled = false;
		document.getElementById('cpf_cnpj').maxLength = 14;
		d.cpf_cnpj.focus(); 
		return false;
	}
	
	if (d.tipo_documento.value == "CNPJ") {
		d.cpf_cnpj.value = "";
		document.getElementById('cpf_cnpj').disabled = false;
		document.getElementById('cpf_cnpj').maxLength = 19;
		d.cpf_cnpj.focus(); 
		return false;
	}
	
}

function insere_mascaras_cpj_cnpj() {
	d = document.formCadastro;
	if (d.tipo_documento.value == "CPF") {
		txtBoxFormat(d.cpf_cnpj, '999.999.999-99', event);
	}
	if (d.tipo_documento.value == "CNPJ") {
		txtBoxFormat(d.cpf_cnpj, '99.999.999/9999-99', event);
	}
}

/*
function avanca_campo_cpj_cnpj() {
	d = document.formCadastro;
	if (d.tipo_documento.value == "CPF") {
		autoTab(d.cpf_cnpj, 14, event);
	}
	if (d.tipo_documento.value == "CNPJ") {
		autoTab(d.cpf_cnpj, 18, event);
	}
}
*/

function valida_cpf_cnpj() {
	d = document.formCadastro;
	if (d.tipo_documento.value == "CPF") {
		TESTA(d.cpf_cnpj.value, 'CPF');
	}
	if (d.tipo_documento.value == "CNPJ") {
		TESTA(d.cpf_cnpj.value, 'CNPJ');
	}
}

// Máscaras
function txtBoxFormat(objeto, sMask, evtKeyPress) {

var i, nCount, sValue, fldLen, mskLen,bolMask, sCod, nTecla;



if(document.all) { // Internet Explorer

  nTecla = evtKeyPress.keyCode; }
		  //Netscape		   Firefox
else if( (document.layers) || (evtKeyPress) ) {

  nTecla = evtKeyPress.which;

}



sValue = objeto.value;



// Limpa todos os caracteres de formatação que

// já estiverem no campo.

sValue = sValue.toString().replace( "-", "" );

sValue = sValue.toString().replace( "-", "" );

sValue = sValue.toString().replace( ".", "" );

sValue = sValue.toString().replace( ".", "" );

sValue = sValue.toString().replace( "/", "" );

sValue = sValue.toString().replace( "/", "" );

sValue = sValue.toString().replace( ":", "" );

sValue = sValue.toString().replace( ":", "" );

sValue = sValue.toString().replace( "(", "" );

sValue = sValue.toString().replace( "(", "" );

sValue = sValue.toString().replace( ")", "" );

sValue = sValue.toString().replace( ")", "" );

sValue = sValue.toString().replace( " ", "" );

sValue = sValue.toString().replace( " ", "" );

fldLen = sValue.length;

mskLen = sMask.length;



i = 0;

nCount = 0;

sCod = "";

mskLen = fldLen;



while (i <= mskLen) {

  bolMask = ((sMask.charAt(i) == "-") || (sMask.charAt(i) == ".") || (sMask.charAt(i) == "/") || (sMask.charAt(i) == ":"))

  bolMask = bolMask || ((sMask.charAt(i) == "(") || (sMask.charAt(i) == ")") || (sMask.charAt(i) == " "))



  if (bolMask) {

	sCod += sMask.charAt(i);

	mskLen++; }

  else {

	sCod += sValue.charAt(nCount);

	nCount++;

  }



  i++;

}



objeto.value = sCod;



if (nTecla != 8) { // backspace

  if (sMask.charAt(i-1) == "9") { // apenas números...

	return ((nTecla > 47) && (nTecla < 58)); } // números de 0 a 9

  else { // qualquer caracter...

	return true;

  } }

else {

  return true;

}

}

  

var isNN = (navigator.appName.indexOf("Netscape")!=-1);

function autoTab(input,len, e) {

	var keyCode = (isNN) ? e.which : e.keyCode;

	var filter = (isNN) ? [0,8,9] : [0,8,9,16,17,18,37,38,39,40,46];

	if(input.value.length >= len && !containsElement(filter,keyCode)) {

		input.value = input.value.slice(0, len);

		input.form[(getIndex(input)+1) % input.form.length].focus();

	}



function containsElement(arr, ele) {

	var found = false, index = 0;

	while(!found && index < arr.length)

	if(arr[index] == ele)

		found = true;

	else

		index++;

	return found;

}



function getIndex(input) {

	var index = -1, i = 0, found = false;

	while (i < input.form.length && index == -1)

	if (input.form[i] == input)index = i;

	else i++;

	return index;

	}

return true;

}

function valida(form) {
	
cadastro = document.formCadastro;	

if (cadastro.tipo_documento.value == "CPF") {
	TESTA(cadastro.cpf_cnpj.value, 'CPF'); //valida CPF
}
else if (cadastro.tipo_documento.value == "CNPJ") {
	TESTA(cadastro.cpf_cnpj.value, 'CNPJ'); //valida CNPJ
} 

var elementos = form.elements;
	for (var i=0; i < elementos.length; i++) { //faça até existir inputs
		if ((elementos[i].getAttribute("type")=="text") || 
			(elementos[i].getAttribute("type")=="password") || 
			(elementos[i].getAttribute("type")=="textarea") ||
			(elementos[i].getAttribute("name")=="tipo_documento")||
			(elementos[i].getAttribute("name")=="estado")||
			(elementos[i].getAttribute("name")=="cidade")) { //se atributo type==text ou password ou textarea
			if (elementos[i].getAttribute("obrigatorio")=="sim") { //se atributo obrigatorio==sim
				if (elementos[i].value=="") { //se o campo estiver em branco
					alert("O campo "+elementos[i].getAttribute("name")+" é obrigatório.");
					elementos[i].focus();
					return false;
				}
			}
		}
	}
		
	if (cadastro.senha.value != cadastro.confirmaSenha.value) {
		alert('Os campos de senha e de confirmação não conferem.');
		cadastro.senha.focus();
		cadastro.senha.value = "";
		cadastro.confirmaSenha.value = "";
		return false;
	}
if(Verify(CNUMB, CTYPE)) {
	return true;
}
}

function Dados(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.forms[0].cidade.options.length = 1;
	     
		 idOpcao  = document.getElementById("opcoes");
		 
	     ajax.open("POST", "cidades.php", 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);
			   }
			   else {
			       //caso não seja um arquivo XML emite a mensagem abaixo
				   idOpcao.innerHTML = "--Selecione o Estado--";
			   }
            }
         }
		 //passa o código do estado escolhido
	     var params = "estado="+valor;
         ajax.send(params);
      }
   }
   
   function processXML(obj){
      //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 codigo    =  item.getElementsByTagName("codigo")[0].firstChild.nodeValue;
			var descricao =  item.getElementsByTagName("descricao")[0].firstChild.nodeValue;
			
	        idOpcao.innerHTML = "";
			
			//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].cidade.options.add(novo);
		 }
	  }
	  else {
	    //caso o XML volte vazio, printa a mensagem abaixo
		idOpcao.innerHTML = "--Selecione o Estado--";
	  }	  
   }


/* VALIDA CPF E CNPJ */
function TESTA(CNUMB,CTYPE) {
	
	if(Verify(CNUMB, CTYPE)) {
   		return true;
 	} else {
		if (CTYPE=='CPF') {
			alert("CPF inválido, por favor tente novamente!");
		   	document.formCadastro.cpf_cnpj.focus();
			document.formCadastro.cpf_cnpj.select();
			return false;
		}
		
		else if (CTYPE=='CNPJ') {
			alert("CNPJ inválido, por favor tente novamente!");
		   	document.formCadastro.cpf_cnpj.focus();
			document.formCadastro.cpf_cnpj.select();
			return false;
		}

 	}
	
return;
}

function ClearStr(str, char)
{
  while((cx=str.indexOf(char))!=-1)
  {		
    str = str.substring(0,cx)+str.substring(cx+1);
  }
  return(str);
}

function ParseNumb(c)
{
  c=ClearStr(c,'-');
  c=ClearStr(c,'/');
  c=ClearStr(c,',');
  c=ClearStr(c,'.');
  c=ClearStr(c,'(');
  c=ClearStr(c,')');
  c=ClearStr(c,' ');
  if((parseFloat(c) / c != 1))
  {
    if(parseFloat(c) * c == 0)
    {
      return(c);
    }
    else
    {
      return(0);
    }
  }
  else
  {
    return(c);
  }
}

function Verify(CNUMB,CTYPE)
{
  CNUMB=ParseNumb(CNUMB)
  if(CNUMB == 0)
  {
    return(false);
  }
  else
  {
    g=CNUMB.length-2;
    if(TestDigit(CNUMB,CTYPE,g))
    {
      g=CNUMB.length-1;
      if(TestDigit(CNUMB,CTYPE,g))
      {	
        return(true);
      }
      else
      {
        return(false);
      }
    }
    else
    {
      return(false);
    }
  }
}

function TestDigit(CNUMB,CTYPE,g)
{
  var dig=0;
  var ind=2;
  for(f=g;f>0;f--)
  {
    dig+=parseInt(CNUMB.charAt(f-1))*ind;
    if (CTYPE=='CNPJ')
    { if(ind>8) {ind=2} else {ind++} }
    else
    { ind++ }
  }
  dig%=11;
  if(dig<2)
  {
    dig=0;
  }
  else
  {
    dig=11-dig;
  }
  if(dig!=parseInt(CNUMB.charAt(g)))
  {
    return(false);
  }
  else
  {
    return(true);
  }
}
