<!--

  <!-- formata campos DE ACORDO COM A MASCARA INDICADA
  
  // usar desta forma ::: onKeyPress="formatar(this,'AA-000000/A')

function formatar(src, mask) {

		var i = src.value.length;

		var saida = mask.substring(i,i+1);
        
		var ascii = event.keyCode ;

		// testa o valor passado na posição A da mascara

		if (saida == "A") {

	        // testa se o caracter digitado minusculo ele faz -32 para tranformar emm maiusculo		

			if ((ascii >=97) && (ascii <= 122)) { event.keyCode -= 32; }

			  // se o caracter digitado for maiusculo so retorna ele 

			  else if ((ascii >=65) && (ascii <= 90)){ return;}

			  // se o que foi digitado não for letra ele ignora

			  else { event.keyCode = 0; }

		  // testa se o que foi digitado e numero

		} else if (saida == "0") {

			// se for numero retorna ele

			if ((ascii >= 48) && (ascii <= 57)) { return }

			else { event.keyCode = 0 }

		

		// 

		} else if (saida == "#") {
			if(window.event.keyCode == 13){
               window.event.returnValue = false;     
                }

			return;

		//vai formatar os valores com a mascara indicada

		} else {

			src.value += saida;

			i += 1

			saida = mask.substring(i,i+1);

			if (saida == "A") {

				if ((ascii >=97) && (ascii <= 122)) { event.keyCode -= 32; }

				else if ((ascii >=65) && (ascii <= 90)){ return;} 

				else { event.keyCode = 0; }

			} else if (saida == "0") {

				if ((ascii >= 48) && (ascii <= 57)) { return }

				else { event.keyCode = 0 }

			} else { return; }

		}
	}

////////////////////////////////////////////////////////

function FormataLETRA(LETRA)

{

//

   strAux   = LETRA.value;



   if (strAux.length > 0)

     {

     strAux = RetiraMascara(strAux);

     strAux = strAux.toUpperCase();

     LETRA.value = strAux

     }

  

   return (1);

}

function FormataMAIUSCULA(LETRA)

{

//

   strAux   = LETRA.value;



   if (strAux.length > 0)

     {

    

     strAux = strAux.toUpperCase();

     LETRA.value = strAux

     }

  

   return (1);

}

function FormataMINUSCULA(LETRA)

{

//

   strAux   = LETRA.value;



   if (strAux.length > 0)

     {

    

     strAux = strAux.toLowerCase();

     LETRA.value = strAux

     }

  

   return (1);

}


function RetiraMascara(pstrDados)

{

   strValor = '';

   if (pstrDados.length > 0)

   {

//   Retira toda a mascara

     for (var ix = (pstrDados.length); ix > -1; ix--)

     {

       if ((pstrDados.substring(ix,ix+1) != '-') && (pstrDados.substring(ix,ix+1) != '.') && (pstrDados.substring(ix,ix+1) != '/'))

          strValor = pstrDados.substring(ix,ix+1) + strValor;

     }

   }

   return(strValor);

}

//******************************************************
// usar desta forma // onBlur="FormataCRC(this)"

function FormataCRC(CRC)

{

//

   strAux   = CRC.value;



   if (strAux.length > 0)

   {

     strAux = RetiraMascara(strAux);

     strAux = strAux.toUpperCase();

     strValor = '';

     for (var ix = (strAux.length); ix > -1; ix--)

     {

       if ((ix == 6) && (strAux.substring(ix,ix+1) != '/'))

          strValor = '/' + strAux.substring(ix,ix+1) + strValor

       else if ((ix == 3) && (strAux.substring(ix,ix+1) != '-'))

          strValor = '/' + strAux.substring(ix,ix+1) + strValor

//       else if ((ix == 3) && (strAux.substring(ix,ix+1) != '-'))

//          strValor = '.' + strAux.substring(ix,ix+1) + strValor

       else

          strValor = strAux.substring(ix,ix+1) + strValor;

       CRC.value = strValor;

     }

   }

   return (1);

}

/////////////////////////


function FormataDATA(CRC)

{

//

   strAux   = CRC.value;



   if (strAux.length > 0)

   {

     strAux = RetiraMascara(strAux);

     strAux = strAux.toUpperCase();

     strValor = '';

     for (var ix = (strAux.length); ix > -1; ix--)

     {

       if ((ix == 4) && (strAux.substring(ix,ix+1) != '/'))

          strValor = '/' + strAux.substring(ix,ix+1) + strValor

       else if ((ix == 2) && (strAux.substring(ix,ix+1) != '/'))

          strValor = '/' + strAux.substring(ix,ix+1) + strValor

   //    else if ((ix == 2) && (strAux.substring(ix,ix+1) != '/'))

    //     strValor = '/' + strAux.substring(ix,ix+1) + strValor

       else

          strValor = strAux.substring(ix,ix+1) + strValor;

       CRC.value = strValor;

     }

   }

   return (1);

}


//////////////////









// VALIDAÇÃO DE FORMULARIO DO DREAMWEAVER MODIFICADA

function MM_findObj(n, d) { //v4.01

  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {

    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}

  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];

  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);

  if(!x && d.getElementById) x=d.getElementById(n); return x;

}



function MM_validateForm() { //v4.0

  var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;

  for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=MM_findObj(args[i]);

    if (val) { nm=val.name; if ((val=val.value)!="") {

      if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@');

        if (p<1 || p==(val.length-1)) errors+='..::* '+nm+' deverá conter um endereço válido.\n';

      } else if (test!='R') { num = parseFloat(val);

        if (isNaN(val)) errors+='..::* '+nm+' deverá conter números.\n';

        if (test.indexOf('inRange') != -1) { p=test.indexOf(':');

          min=test.substring(8,p); max=test.substring(p+1);

          if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n';

    } } } else if (test.charAt(0) == 'R') errors += '** É necessário digitar '+nm+'.\n'; }

  } if (errors) alert('VEREFIQUE A MENSAGEM ABAIXO PARA IDENTIFICAR O(S) ERRO(S) ENCONTRADO(S):\n\n'+errors);

  document.MM_returnValue = (errors == '');

}


//*********************************************************************
// ao pressionar o enter ele pula campos, comportasse como o tab
 <!--
   function pular(){
     if(window.event.srcElement.type == 'text'){ 
       var ele = window.event.srcElement;
       var index = ele.sourceIndex;
       if(window.event.keyCode == 13){
         document.all.item(index + 2).focus();  
         window.event.returnValue = false;     
       }
     } 
   }
   
   document.onkeypress = pular; 
//-->
//**********************************************************************


// FUNÇÕES QUE VAO FORMATAR E VALIDAR DATA E HORA
// usar deata forma ::: onBlur="verifica_data(this.value)" OnKeyUp="mascara_data(this.value)"
// data nascimento
function mascara_data(dta_nasc){ 
              var mydata = ''; 
              mydata = mydata + dta_nasc; 
		
              if (mydata.length == 2){ 
                  mydata = mydata + '/'; 
                  document.forms[0].dta_nasc.value = mydata; 
              } 
              if (mydata.length == 5){ 
                  mydata = mydata + '/'; 
                  document.forms[0].dta_nasc.value = mydata; 
              } 
              if (mydata.length == 10){ 
                 // verifica_data(); 
              } 
          } 

          function verifica_data() { 
		   if (document.forms[0].dta_nasc.value == "") { 
                situacao = "falsa";	
				alert("É necessário digitar a data e nascimento");
				document.forms[0].dta_nasc.focus(); 
            }  
			else {
				
                  dia = (document.forms[0].dta_nasc.value.substring(0,2)) ; 
                  mes = (document.forms[0].dta_nasc.value.substring(3,5)) ; 
                  ano = (document.forms[0].dta_nasc.value.substring(6,10)); 

                  situacao = ""; 
                 // verifica o dia valido para cada mes 
                 if ((dia < 01)||(dia < 01 || dia > 30) && (  mes == 04 || mes == 06 || mes == 09 || mes == 11 ) || dia > 31) { 
                     situacao = "falsa"; 
					     alert("Data Inválida - Confira o dia digitado"); 
                         document.forms[0].dta_nasc.focus();
                 } 

                 // verifica se o mes e valido 
                 else if (mes < 01 || mes > 12 ) { 
                     situacao = "falsa";
					     alert("Data Inválida - Confira o mês digitado"); 
                         document.forms[0].dta_nasc.focus();
                 } 

                 // verifica se e ano bissexto 
                 else if (mes == 2 && ( dia < 01 || dia > 29 || ( dia > 28 && (parseInt(ano / 4) != ano / 4)))) { 
                     situacao = "falsa"; 
					     alert("Data Inválida - Esta data só é válida para no bissexto"); 
                         document.forms[0].dta_nasc.focus();
                 } 
			
			     // verifica se o ano e valido 
                 else if (ano < 1900 || ano > 1996 ) { 
                     situacao = "falsa";
					     alert("Data Inválida - Confira o ano"); 
                         document.forms[0].dta_nasc.focus();
                 } 
    
           }//fecha else
          } //fecha função

// FIM....FUNÇÕES QUE VAO FORMATAR E VALIDAR DATA E HORA		
/////////////////////////////////////////////////////////////////////////////////////////////////
/**
 *
 * function mask(_mask, val)
 *
 * _mask = Mascara Exemplo: ##/##/#### ou ###.###.###-##
 * val   = Valor a ser formatado.
 *
 * Formata um valor  para a mascara definida.
 *
 * pedro.leao@ig.com.br 2003/08/16
 *******************************************
 * faz parte da função abaixo
 *******************************
 */
function mask(_mask, val) {
	var i, mki;
	var aux="";
	
	for(i=mki=0; i<val.length; i++, mki++) {
		if(_mask.charAt(mki)=='' || _mask.charAt(mki)=='#' || _mask.charAt(i)==val.charAt(i)) {
			aux+=val.charAt(i);
		} else {
			aux+=_mask.charAt(mki)+val.charAt(i);
			mki++;
		}
	}
	return aux;
}

/**
 * function maskEvent(field, _mask, event)
 *
 * field = Objeto que esta enviando o evendo onKeyPress()
 * _mask = Mascara Exemplo: ##/##/#### ou ###.###.###-##
 * event = Evento a ser observado.
 *
 * Formata um valor para a mascara definida conforma o valor vai sendo digitado.
 *
 * pedro.leao@ig.com.br 2003;08/16
   ******************************************************
 * usar desta forma /// onKeyPress="return(maskEvent(this, '##/##/##',event))"
 ******************************************************* 
// NAO DEIXAR EXCLUIR NO FIREFOX E NETESCAPE
 */
function maskEvent(field, _mask, event) {
	var key ='';
	var aux='';
	var len=0;
	var i=0;
	var strCheck = '0123456789';//colocara aqui os caracteres que vai aceitar 
	var rcode = (window.Event) ? event.which : event.keyCode;
	
	if(rcode == 13) {
		//Enter
		return true;
	}
	
	//Get key value from key code
	key=String.fromCharCode(rcode);
	
	if(strCheck.indexOf(key)==-1) {
		//window.alert('Caracter inválido');
		return false;
	}
	
	aux=field.value+key;
	//window.alert(aux);
	aux=mask(_mask,aux);
	//window.alert(aux);
	field.value=aux;	
	return false;
}

/**
 *
 * function currencyFormat(fld, milSep, decSep, e)
 *
 * fld    = Objeto a ser verficado.
 * milSep = Separador para milhar.
 * decSep = Separador para decimal.
 * e      = Evento.
 *
 * Formata um valor decimal conforme for digitado no box.
 * Criação: Anonima (coletada em http://http://www.scriptbrasil.com/?class=2&secao=javascript&categoria=Formulários&menu=javascript&ini=1
 * Revisao: pedro.leao@ig.com.br	2003/08/16
 ******************************************************
 * usar desta forma /// onKeyPress="return(currencyFormat(this,'.',',',event))"
 *******************************************************
 */
 // NAO DEIXAR EXCLUIR NO FIREFOX E NETESCAPE
function currencyFormat(fld, milSep, decSep, e) {
	var sep = 0;
	var key = '';
	var i = j = 0;
	var len = len2 = 0;
	var strCheck = '0123456789';
	var aux = aux2 = '';
	var whichCode = (window.Event) ? e.which : e.keyCode;

	if (whichCode == 13) {
		return true;  // Enter
	}
	key = String.fromCharCode(whichCode);  // Get key value from key code
	if (strCheck.indexOf(key) == -1) {
		return false;  // Not a valid key
	}
	len = fld.value.length;
	for(i = 0; i < len; i++) {
		if ((fld.value.charAt(i) != '0') && (fld.value.charAt(i) != decSep)){
			 break;
		}
	}
	
	aux = '';
	for(; i < len; i++) {
		if (strCheck.indexOf(fld.value.charAt(i))!=-1){
			aux += fld.value.charAt(i);
		}
	}
	aux += key;
			
	len = aux.length;
	if (len == 0) {
		fld.value = '';
	} else if (len == 1) {
		fld.value = '0'+ decSep + '0' + aux;
	} else if (len == 2) {
		fld.value = '0'+ decSep + aux;
	} else if (len > 2) {
		aux2 = '';

		for (j = 0, i = len - 3; i >= 0; i--) {
			if (j == 3) {
				aux2 += milSep;
				j = 0;
			}
			aux2 += aux.charAt(i);
			j++;
		}
		fld.value = '';
		len2 = aux2.length;
		for (i = len2 - 1; i >= 0; i--) {
			fld.value += aux2.charAt(i);
		}
		
		fld.value += decSep + aux.substr(len - 2, len);
	}
	return false;
}

// fim função que formata valor moeda
////////////////////////////////////////////////////////////////////////////////////////////




///////////////////////////////////////////////////////////////////////////////////////////////
// usa assim :::OnKeyUp="mascara_data2(this)" ou assim onKeyPress=="mascara_data2(this)"
function mascara_data2(field){ 

	          var mydata = ''; 	
			  
              mydata = mydata + field.value; 
		
		
              if (mydata.length == 2){ 
                  mydata = mydata + '/'; 
                  field.value = mydata; 
              } 
              if (mydata.length == 5){ 
                  mydata = mydata + '/'; 
                  field.value = mydata; 
              } 
              if (mydata.length == 10){ 
                 // verifica_data(); 
              } 
          }
//////////////////////////////////////////////////////
// usa assim ::: onBlur="verifica_data2(this)"
/////////////////////////////////////////////////////
function verifica_data2(field) { 
                	
		   if (field.value == "") { 
                situacao = "falsa";	
				alert("É necessário digitar a data e nascimento");
				field.focus(); 
            }  
			else {
				
                  dia = (field.value.substring(0,2)) ; 
                  mes = (field.value.substring(3,5)) ; 
                  ano = (field.value.substring(6,10)); 

                  situacao = ""; 
                 // verifica o dia valido para cada mes 
                 if ((dia < 01)||(dia < 01 || dia > 30) && (  mes == 04 || mes == 06 || mes == 09 || mes == 11 ) || dia > 31) { 
                     situacao = "falsa"; 
					     alert("Data Inválida - Confira o dia digitado"); 
                         field.focus();
                 } 

                 // verifica se o mes e valido 
                 else if (mes < 01 || mes > 12 ) { 
                     situacao = "falsa";
					     alert("Data Inválida - Confira o mês digitado"); 
                         field.focus();
                 } 

                 // verifica se e ano bissexto 
                 else if (mes == 2 && ( dia < 01 || dia > 29 || ( dia > 28 && (parseInt(ano / 4) != ano / 4)))) { 
                     situacao = "falsa"; 
					     alert("Data Inválida - Esta data só é válida para no bissexto"); 
                         field.focus();
                 } 
			
			     // verifica se o ano e valido 
                 else if (ano < 1900 || ano > 2010) { 
                     situacao = "falsa";
					     alert("Data Inválida - Confira o ano"); 
                         field.focus();
                 } 
    
           }//fecha else
		  
          } //fecha função
		  
		  
///////////////////////////////////////////////////////////////////////////////////////////////////////////  
		  

////////////////////////////////////////////////////////////////////////////////////////////
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

// //usar desta forma

 <!-- formata campos DE ACORDO COM A MASCARA INDICADA   - - onKeyPress="formatar(this,'AA-000000/A')"
 
 // problemas no firefox

function formatar(src, mask) {

		var i = src.value.length;

		var saida = mask.substring(i,i+1);

		var ascii = event.keyCode;

		// testa o valor passado na posição A da mascara

		if (saida == "A") {

	        // testa se o caracter digitado minusculo ele faz -32 para tranformar emm maiusculo		

			if ((ascii >=97) && (ascii <= 122)) { event.keyCode -= 32; }

			  // se o caracter digitado for maiusculo so retorna ele 

			  else if ((ascii >=65) && (ascii <= 90)){ return;}

			  // se o que foi digitado não for letra ele ignora

			  else { event.keyCode = 0; }

		  // testa se o que foi digitado e numero

		} else if (saida == "0") {

			// se for numero retorna ele

			if ((ascii >= 48) && (ascii <= 57)) { return }

			else { event.keyCode = 0 }

		

		// 

		} else if (saida == "#") {
			if(window.event.keyCode == 13){
               window.event.returnValue = false;     
                }

			return;

		//vai formatar os valores com a mascara indicada

		} else {

			src.value += saida;

			i += 1

			saida = mask.substring(i,i+1);

			if (saida == "A") {

				if ((ascii >=97) && (ascii <= 122)) { event.keyCode -= 32; }

				else if ((ascii >=65) && (ascii <= 90)){ return;} 

				else { event.keyCode = 0; }

			} else if (saida == "0") {

				if ((ascii >= 48) && (ascii <= 57)) { return }

				else { event.keyCode = 0 }

			} else { return; }

		}
	}

////////////////////////////////////////////////////////

//-->


//************************************************************************************
//***************************INICIO DAS FUNÇÕES PARA CARREGAR OS ESTADO SELECIONADOS
//*****NÃO ESQUECER DO ARQUIVO CIDADES.PHP - ELE GERA O XML COM A LISTA DAS CIDADES E DEVOLVE PARA FUNÇÃO

   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].listCidades.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 = "--Primeiro 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 = "--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", "opcoes");
				//atribui um valor
			    novo.value = codigo;
				//atribui um texto
			    novo.text  = descricao;
				//finalmente adiciona o novo elemento
				document.forms[0].listCidades.options.add(novo);
		 }
	  }
	  else {
	    //caso o XML volte vazio, printa a mensagem abaixo
		idOpcao.innerHTML = "--Primeiro selecione o estado--";
	  }	  
   }
//xxxxxxxxxxx
//xxxxxxxxxxx 222222 xxxxx funções para carregar as cidade de acordo com o estado selecionado
//xxxxxxxxxxx
 function Dados2(valor) {
      //verifica se o browser tem suporte a ajax
	  try {
         ajax2 = new ActiveXObject("Microsoft.XMLHTTP");
      } 
      catch(e) {
         try {
            ajax2 = new ActiveXObject("Msxml2.XMLHTTP");
         }
	     catch(ex) {
            try {
               ajax2 = new XMLHttpRequest();
            }
	        catch(exc) {
               alert("Esse browser não tem recursos para uso do Ajax");
               ajax2 = null;
            }
         }
      }
	  //se tiver suporte ajax
	  if(ajax2) {
	     //deixa apenas o elemento 1 no option, os outros são excluídos
		 document.forms[0].listCidades2.options.length = 1;
	     
		 idOpcao2  = document.getElementById("opcoes2");
		 
	     ajax2.open("POST", "cidades.php", true);
		 ajax2.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		 
		 ajax2.onreadystatechange = function() {
            //enquanto estiver processando...emite a msg de carregando
			if(ajax2.readyState == 1) {
			   idOpcao2.innerHTML = "Carregando...2!";   
	        }
			//após ser processado - chama função processXML que vai varrer os dados
            if(ajax2.readyState == 4 ) {
			   if(ajax2.responseXML) {
			      processXML2(ajax2.responseXML);
			   }
			   else {
			       //caso não seja um arquivo XML emite a mensagem abaixo
				   idOpcao2.innerHTML = "--Primeiro selecione o estado2--";
			   }
            }
         }
		 //passa o código do estado escolhido
	     var params2 = "estado="+valor;
         ajax2.send(params2);
      }
   }
   
   function processXML2(obj){
      //pega a tag cidade
      var dataArray2   = obj.getElementsByTagName("cidade");
      
	  //total de elementos contidos na tag cidade
	  if(dataArray2.length > 0) {
	     //percorre o arquivo XML paara extrair os dados
         for(var i = 0 ; i < dataArray2.length ; i++) {
            var item = dataArray2[i];
			//contéudo dos campos no arquivo XML
			var codigo    =  item.getElementsByTagName("codigo")[0].firstChild.nodeValue;
			var descricao =  item.getElementsByTagName("descricao")[0].firstChild.nodeValue;
			
	        idOpcao2.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", "opcoes2");
				//atribui um valor
			    novo.value = codigo;
				//atribui um texto
			    novo.text  = descricao;
				//finalmente adiciona o novo elemento
				document.forms[0].listCidades2.options.add(novo);
		 }
	  }
	  else {
	    //caso o XML volte vazio, printa a mensagem abaixo
		idOpcao2.innerHTML = "--Primeiro selecione o estado2--";
	  }	  
   }

//xxxxxxxxxxx
//xxxxxxxxxxx 333333 xxxxx funções para carregar as cidade de acordo com o estado selecionado
//xxxxxxxxxxx
 function Dados3(valor) {
      //verifica se o browser tem suporte a ajax
	  try {
         ajax3 = new ActiveXObject("Microsoft.XMLHTTP");
      } 
      catch(e) {
         try {
            ajax3 = new ActiveXObject("Msxml2.XMLHTTP");
         }
	     catch(ex) {
            try {
               ajax3 = new XMLHttpRequest();
            }
	        catch(exc) {
               alert("Esse browser não tem recursos para uso do Ajax");
               ajax3 = null;
            }
         }
      }
	  //se tiver suporte ajax
	  if(ajax3) {
	     //deixa apenas o elemento 1 no option, os outros são excluídos
		 document.forms[0].listCidades3.options.length = 1;
	     
		 idOpcao3  = document.getElementById("opcoes3");
		 
	     ajax3.open("POST", "cidades.php", true);
		 ajax3.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		 
		 ajax3.onreadystatechange = function() {
            //enquanto estiver processando...emite a msg de carregando
			if(ajax3.readyState == 1) {
			   idOpcao3.innerHTML = "Carregando...3!";   
	        }
			//após ser processado - chama função processXML que vai varrer os dados
            if(ajax3.readyState == 4 ) {
			   if(ajax3.responseXML) {
			      processXML3(ajax3.responseXML);
			   }
			   else {
			       //caso não seja um arquivo XML emite a mensagem abaixo
				   idOpcao3.innerHTML = "--Primeiro selecione o estado3--";
			   }
            }
         }
		 //passa o código do estado escolhido
	     var params3 = "estado="+valor;
         ajax3.send(params3);
      }
   }
   
   function processXML3(obj){
      //pega a tag cidade
      var dataArray3   = obj.getElementsByTagName("cidade");
      
	  //total de elementos contidos na tag cidade
	  if(dataArray3.length > 0) {
	     //percorre o arquivo XML paara extrair os dados
         for(var i = 0 ; i < dataArray3.length ; i++) {
            var item = dataArray3[i];
			//contéudo dos campos no arquivo XML
			var codigo    =  item.getElementsByTagName("codigo")[0].firstChild.nodeValue;
			var descricao =  item.getElementsByTagName("descricao")[0].firstChild.nodeValue;
			
	        idOpcao3.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", "opcoes3");
				//atribui um valor
			    novo.value = codigo;
				//atribui um texto
			    novo.text  = descricao;
				//finalmente adiciona o novo elemento
				document.forms[0].listCidades3.options.add(novo);
		 }
	  }
	  else {
	    //caso o XML volte vazio, printa a mensagem abaixo
		idOpcao3.innerHTML = "--Primeiro selecione o estado3--";
	  }	  
   }

//xxxxxxxxxxx
//xxxxxxxxxxx 444444 xxxxx funções para carregar as cidade de acordo com o estado selecionado
//xxxxxxxxxxx
 function Dados4(valor) {
      //verifica se o browser tem suporte a ajax
	  try {
         ajax4 = new ActiveXObject("Microsoft.XMLHTTP");
      } 
      catch(e) {
         try {
            ajax4 = new ActiveXObject("Msxml2.XMLHTTP");
         }
	     catch(ex) {
            try {
               ajax4 = new XMLHttpRequest();
            }
	        catch(exc) {
               alert("Esse browser não tem recursos para uso do Ajax");
               ajax4 = null;
            }
         }
      }
	  //se tiver suporte ajax
	  if(ajax4) {
	     //deixa apenas o elemento 1 no option, os outros são excluídos
		 document.forms[0].listCidades4.options.length = 1;
	     
		 idOpcao4  = document.getElementById("opcoes4");
		 
	     ajax4.open("POST", "cidades.php", true);
		 ajax4.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		 
		 ajax4.onreadystatechange = function() {
            //enquanto estiver processando...emite a msg de carregando
			if(ajax4.readyState == 1) {
			   idOpcao4.innerHTML = "Carregando...4!";   
	        }
			//após ser processado - chama função processXML que vai varrer os dados
            if(ajax4.readyState == 4 ) {
			   if(ajax4.responseXML) {
			      processXML4(ajax4.responseXML);
			   }
			   else {
			       //caso não seja um arquivo XML emite a mensagem abaixo
				   idOpcao4.innerHTML = "--Primeiro selecione o estado4--";
			   }
            }
         }
		 //passa o código do estado escolhido
	     var params4 = "estado="+valor;
         ajax4.send(params4);
      }
   }
   
   function processXML4(obj){
      //pega a tag cidade
      var dataArray4   = obj.getElementsByTagName("cidade");
      
	  //total de elementos contidos na tag cidade
	  if(dataArray4.length > 0) {
	     //percorre o arquivo XML paara extrair os dados
         for(var i = 0 ; i < dataArray4.length ; i++) {
            var item = dataArray4[i];
			//contéudo dos campos no arquivo XML
			var codigo    =  item.getElementsByTagName("codigo")[0].firstChild.nodeValue;
			var descricao =  item.getElementsByTagName("descricao")[0].firstChild.nodeValue;
			
	        idOpcao4.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", "opcoes4");
				//atribui um valor
			    novo.value = codigo;
				//atribui um texto
			    novo.text  = descricao;
				//finalmente adiciona o novo elemento
				document.forms[0].listCidades4.options.add(novo);
		 }
	  }
	  else {
	    //caso o XML volte vazio, printa a mensagem abaixo
		idOpcao4.innerHTML = "--Primeiro selecione o estado4--";
	  }	  
   }
 //************FIM DA FUNÇÃO DE LISTAR AS CIDADES DE ACORDO COM O ESTADO SELECIONADO
//***************************************************************************************

//////////////////////////////////////////////////////////////////////////////////////////
//Uso:
// onkeypress="return MaskCPF(this, event)" 
// onkeypress="return MaskTelefone(this, event)"


function Mascara(objeto, evt, mask) {
 
var LetrasU = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
var LetrasL = 'abcdefghijklmnopqrstuvwxyz';
var Letras  = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
var Numeros = '0123456789';
var Fixos  = '().-:/ '; 
var Charset = " !\"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_/`abcdefghijklmnopqrstuvwxyz{|}~";

evt = (evt) ? evt : (window.event) ? window.event : "";
var value = objeto.value;
if (evt) {
 var ntecla = (evt.which) ? evt.which : evt.keyCode;
 tecla = Charset.substr(ntecla - 32, 1);
 if (ntecla < 32) return true;

 var tamanho = value.length;
 if (tamanho >= mask.length) return false;

 var pos = mask.substr(tamanho,1); 
 while (Fixos.indexOf(pos) != -1) {
  value += pos;
  tamanho = value.length;
  if (tamanho >= mask.length) return false;
  pos = mask.substr(tamanho,1);
 }

 switch (pos) {
   case '#' : if (Numeros.indexOf(tecla) == -1) return false; break;
   case 'A' : if (LetrasU.indexOf(tecla) == -1) return false; break;
   case 'a' : if (LetrasL.indexOf(tecla) == -1) return false; break;
   case 'Z' : if (Letras.indexOf(tecla) == -1) return false; break;
   case '*' : objeto.value = value; return true; break;
   default : return false; break;
 }
}
objeto.value = value; 
return true;
}

function MaskCEP(objeto, evt) { 
return Mascara(objeto, evt, '##.###-###');
}

function MaskTelefone(objeto, evt) { 
return Mascara(objeto, evt, '(##) ####-####');
}

function MaskCPF(objeto, evt) { 
return Mascara(objeto, evt, '###.###.###-##');
}

function MaskPlacaCarro(objeto, evt) { 
return Mascara(objeto, evt, 'AAA-####');
}

function MaskData(objeto, evt) { 
return Mascara(objeto, evt, '##/##/####');
}

function MaskNumeros(objeto, evt) { 
return Mascara(objeto, evt, '###########');
}

function MaskCRC(objeto, evt) { 
return Mascara(objeto, evt, 'ZZ-######/Z');
}

/////////////////////////////////////////////////////////////////////////////
/*
Para usar é bem simples
carrege esse arquivo em seu html e no onload do body execute 
Mascaras.carregar();
<body onload="Mascaras.carregar();">

pontro o codigo vai percorrer todoseu html procurando as marcacoes abaixo em seus inputs e aplicando a mascara

insira os seguintes atributos nos seus input 

tipo = pode ser numerico ou decimal
mascara = é a mascara a ser usada coloque # nas posições dos caracteres ex : "##:##"
casasdecimais = para o caso do tiposer decimal aqui eh dito quantas casas decimais vaum ser usadas 
negativo = isso define um sinal de negativo no inicio do valor 

pronto é so isso 
exemplos:
<input type="text" tipo="numerico"> aqui so da para digitar numeros
<input type="text" tipo="numerico" negativo=true> aqui so da para digitar numeros e no caso de precionar "-" umsinal de negativo vai aparecer
<input type="text" tipo="decimal" negativo=true casasdecimais=3>
<input type="text" tipo="numerico" mascara="##/##/####"> data
<input type="text" tipo="numerico" mascara="###.###.###-##"> cpf
*/

// *****BOA MAS APRESENTA PROBLEMAS COM NETSCAPE... repete numeros digitados....
Mascaras = {
IsIE: navigator.appName.toLowerCase().indexOf('microsoft')!=-1,
AZ: /[A-Z]/i,
Acentos: /[À-ÿ]/i,
Num: /[0-9]/,
carregar: function(parte){
 var Tags = ['input','textarea'];
 if (typeof parte == "undefined") parte = document;
 for(var z=0;z<Tags.length;z++){
  Inputs=parte.getElementsByTagName(Tags[z]);
  for(var i=0;i<Inputs.length;i++)
   if(('button,image,hidden,submit,reset').indexOf(Inputs[i].type.toLowerCase())==-1)
    this.aplicar(Inputs[i]);
 }
},
aplicar: function(campo){
 tipo = campo.getAttribute('tipo');
 if (!tipo || campo.type == "select-one") return;
 orientacao = campo.getAttribute('orientacao');
 mascara = campo.getAttribute('mascara');
 if (tipo.toLowerCase() == "decimal"){
  orientacao = "esquerda";
  casasdecimais = campo.getAttribute('casasdecimais');
  tamanho = campo.getAttribute('maxLength');
  if (!tamanho || tamanho > 50)
   tamanho = 10;
  if (!casasdecimais)
   casasdecimais = 2;
  campo.setAttribute("mascara", this.geraMascaraDecimal(tamanho, casasdecimais));
  campo.setAttribute("tipo", "numerico");
  campo.setAttribute("orientacao", orientacao);
 }
 if (orientacao && orientacao.toLowerCase() == "esquerda") campo.style.textAlign = "right";
 if (mascara) campo.setAttribute("maxLength", mascara.length);
 if (tipo){
  campo.onkeypress = function(e){ return Mascaras.onkeypress(e?e:event); };
  campo.onkeyup = function(e){ Mascaras.onkeyup(e?e:event, campo) };
 }
 campo.setAttribute("snegativo", ((campo.value).substr(0,1) == "-" ? "s" : "n"));
},
onkeypress: function(e){
 KeyCode = this.IsIE ? event.keyCode : e.which;
 campo =  this.IsIE ? event.srcElement : e.target;
 readonly = campo.getAttribute('readonly');
 if (readonly) return;
 maxlength = campo.getAttribute('maxlength');
 pt = campo.getAttribute('pt');
 selecao = this.selecao(campo);
 if (selecao.length > 0 && KeyCode != 0){
  campo.value = ""; return true;
 }
 if (KeyCode == 0) return true;
 Char = String.fromCharCode(KeyCode);
 valor = campo.value;
 mascara = campo.getAttribute('mascara');
 if (KeyCode != 8){
  tipo = campo.getAttribute('tipo').toLowerCase();
  negativo = campo.getAttribute('negativo');
  if(negativo && KeyCode == 45){
   snegativo = campo.getAttribute('snegativo');
   snegativo = (snegativo == "s" ? "n" : "s");
   campo.setAttribute("snegativo", snegativo);
  }else{
   valor += Char
   if (tipo == "numerico" && Char.search(this.Num) == -1) return false;
   if (KeyCode != 32 && tipo == "caracter" && Char.search(this.AZ) == -1 && Char.search(this.Acentos) == -1) return false;
  }
 }
 if (mascara){
  this.aplicarMascara(campo, valor);
  return false;
 }
 return true;
},
onkeyup: function(e, campo){
 KeyCode = this.IsIE ? event.keyCode : e.which;
 if (KeyCode != 9 && KeyCode != 16 && KeyCode != 109){
  valor = campo.value;
  if (KeyCode == 8 && !this.IsIE) valor = valor.substr(0,valor.length-1);
  this.aplicarMascara(campo, valor);
 }
},
aplicarMascara: function(campo, valor){
 mascara = campo.getAttribute('mascara');
 if (!mascara) return;
 negativo = campo.getAttribute('negativo');
 snegativo = campo.getAttribute('snegativo');
 if (negativo && valor.substr(0,1) == "-") 
  valor = valor.substr(1,valor.length-1);
 orientacao = campo.getAttribute('orientacao');
 var i = 0;
 for(i=0;i<mascara.length;i++){
  caracter = mascara.substr(i,1);
  if (caracter != "#") valor = valor.replace(caracter, "");
 }
 retorno = "";
 if (orientacao != "esquerda"){
  contador = 0;
  for(i=0;i<mascara.length;i++){
   caracter = mascara.substr(i,1);
   if (caracter == "#"){
    retorno += valor.substr(contador,1);
    contador++;
   }else
    retorno += caracter;
   if(contador >= valor.length) break;
  }
 }else{
  contador = valor.length-1;
  for(i=mascara.length-1;i>=0;i--){
   if(contador < 0) break;
   caracter = mascara.substr(i,1);
   if (caracter == "#"){
    retorno = valor.substr(contador,1) + retorno;
    contador--;
   }else
    retorno = caracter + retorno;
  }
 }
 if (negativo && snegativo == "s")
  retorno = "-" + retorno;
 campo.value = retorno;
},
geraMascaraDecimal: function(tam, decimais){
 var retorno = ""; var contador = 0; var i = 0;
 decimais = parseInt(decimais);
 for (i=0;i<(tam-(decimais+1));i++){
  retorno = "#" + retorno;
  contador++;
  if (contador == 3){
   retorno = "." + retorno;
   contador=0;
  }
 }
 retorno = retorno + ",";
 for (i=0;i<decimais;i++) retorno += "#";
 return retorno;
},
selecao: function(campo){
 if (this.IsIE)
  return document.selection.createRange().text;
 else
  return (campo.value).substr(campo.selectionStart, (campo.selectionEnd - campo.selectionStart));
},
formataValor: function (valor, decimais){
 valor = valor.split('.');
 if (valor.length == 1) valor[1] = "";
 for(var i=valor[1].length;i<decimais;i++)
  valor[1] += "0"; 
 valor[1] = valor[1].substr(0,2);
 return (valor[0] + "." + valor[1]);
}
};

////////////////////////////////////////////


////////////////////////////////////////////////////////////////////
//                VALIDAR E-MAIL
//////////////////////////////////////////////////////////////////

// USAR DESTA FORMA onBlur="validarEmail(this.form.email.value);" OU DESTA onBlur="validarEmail(this.form.email.value);"
 function validarEmail(valor) {
         
if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(valor)){
   //alert("E-mail " + valor    + " está correto."); 
   
   return (true);
  } else {
   alert("E-mail incorreto.");
   return (false);
  }
 }
