// FUNÇÃO PARA FORMATAR DATA
function FormataData(objeto,teclapress) 
{ 
    var tecla = teclapress.keyCode; 

    //Testa se o campo está selecionado, se estiver, limpa o conteúdo para nova digitação. 
    var selecionado = document.selection.createRange();  
    var selecao        = selecionado.text;  
    if((selecao != "") && (tecla != 8) && (tecla != 9) && (tecla != 13) && (tecla != 35) && (tecla != 36) && (tecla != 46) && (tecla != 16) && (tecla != 17) && (tecla != 18) && (tecla != 20) && (tecla != 27) && (tecla != 37) && (tecla != 38) && (tecla != 39) && (tecla != 40)) {objeto.value = "";} 



    if(((window.event.keyCode == 13) || (window.event.keyCode == 9))&&objeto.value != "") 
    { 
        if(!(ValidaData(objeto))) 
            { 
                window.event.cancelBubble = true; 
                window.event.returnValue = false; 
                alert("Data Inválida"); 
                objeto.value = ""; 
                objeto.focus(); 
            } 
    } 

    if (( tecla == 8 || tecla == 88 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105 )&& objeto.value.length < (10)) 
    { 
        vr = objeto.value; 
        vr = vr.replace( "/", "" ); 
        vr = vr.replace( "/", "" ); 
        tam = vr.length; 

        if (tam < 8) 
            { 
                if (tecla != 8) {tam = vr.length + 1 ;} 
            } 
        else 
            { 
                window.event.cancelBubble = true; 
                window.event.returnValue = false; 
            } 
         
        if ((tecla == 8) && (tam > 1)) 
            { 
                tam = tam - 1 ; 
                objeto.value = vr.substr(0,tam); 
                window.event.cancelBubble = true; 
                window.event.returnValue = false; 
            } 
                if ( tam <= 4 && tecla != 8){  
                     objeto.value = vr ; } 

                if ( (tam >= 4) && (tam <= 6) ){ 
                     objeto.value = vr.substr(0, tam - 4) + '/' + vr.substr( tam - 4, 4 ); } 

                if ( (tam >= 6) && (tam <= 8) ){ 
                    objeto.value = vr.substr(0, tam - 6 ) + '/' + vr.substr( tam - 6, 2 ) + '/' + vr.substr( tam - 4, 4 ); } 

                if ((tam == (8)) && tecla != 8) 
                    { 
                        if(tecla >=96 && tecla <=105) 
                            { 
                                tecla = tecla - 48; 
                            } 

                        objeto.value = objeto.value + (String.fromCharCode(tecla)); 
                        window.event.cancelBubble = true; 
                        window.event.returnValue = false; 

                        if (!(ValidaData(objeto))) 
                            { 
                                alert("Data Inválida"); 
                                objeto.value = ""; 
                                objeto.focus(); 
                            } 
                    } 
    } 
    else if((window.event.keyCode != 8) && (window.event.keyCode != 9) && (window.event.keyCode != 13) && (window.event.keyCode != 35) && (window.event.keyCode != 36) && (window.event.keyCode != 46)) 
        { 
            event.returnValue = false; 
        } 
}

// MÁSCARA CNPJ
/********************************************************************************/
function mascara_cnpj(){
	var doc = document.forms[0];
	var mycnpj = '';
    mycnpj = mycnpj + doc.cnpj.value;
    if (mycnpj.length == 2) {
    mycnpj = mycnpj + '.';
    doc.cnpj.value = mycnpj;
	}
    if (mycnpj.length == 6) {
    mycnpj = mycnpj + '.';
    doc.cnpj.value = mycnpj;
	}
    if (mycnpj.length == 10) {
    mycnpj = mycnpj + '/';
    doc.cnpj.value = mycnpj;
	}
    if (mycnpj.length == 15) {
    mycnpj = mycnpj + '-';
    doc.cnpj.value = mycnpj;
    }
	if (mycnpj.length == 18){
	validaCNPJ();
	}
}
	function validaCNPJ() {
		CNPJ = document.forms[0].cnpj.value;
		erro = new String;
		if (CNPJ.length < 18) erro += "E' necessarios preencher corretamente o numero do CNPJ! \n\n";
		if ((CNPJ.charAt(2) != ".") || (CNPJ.charAt(6) != ".") || (CNPJ.charAt(10) != "/") || (CNPJ.charAt(15) != "-")){
			if (erro.length == 0) erro += "E' necessarios preencher corretamente o numero do CNPJ! \n\n";
		}
		//substituir os caracteres que nao sao numeros
		if(document.layers && parseInt(navigator.appVersion) == 4){
			x = CNPJ.substring(0,2);
			x += CNPJ.substring(3,6);
			x += CNPJ.substring(7,10);
			x += CNPJ.substring(11,15);
			x += CNPJ.substring(16,18);
			CNPJ = x;	
		} else {
			CNPJ = CNPJ.replace(".","");
			CNPJ = CNPJ.replace(".","");
			CNPJ = CNPJ.replace("-","");
			CNPJ = CNPJ.replace("/","");
		}
		var nonNumbers = /\D/;
		if (nonNumbers.test(CNPJ)) erro += "A verificacao de CNPJ suporta apenas numeros! \n\n";	
		var a = [];
		var b = new Number;
		var c = [6,5,4,3,2,9,8,7,6,5,4,3,2];
		for (i=0; i<12; i++){
			a[i] = CNPJ.charAt(i);
			b += a[i] * c[i+1];
		}
		if ((x = b % 11) < 2) { a[12] = 0 } else { a[12] = 11-x }
		b = 0;
		for (y=0; y<13; y++) {
			b += (a[y] * c[y]); 
		}
		if ((x = b % 11) < 2) { a[13] = 0; } else { a[13] = 11-x; }
		if ((CNPJ.charAt(12) != a[12]) || (CNPJ.charAt(13) != a[13])){
			erro +="CNPJ inválido";
		}
		if (erro.length > 0){
			alert(erro);
			return false;
		} 
		return true;
	}
/********************************************************************************/
// MÁSCARA E-MAIL
/********************************************************************************/

function FormatarMail(mail){
    var er = new RegExp(/^[A-Za-z0-9_\-\.]+@[A-Za-z0-9_\-\.]{2,}\.[A-Za-z0-9]{2,}(\.[A-Za-z0-9])?/);
    if(typeof(mail) == "string"){
        if(er.test(mail)){ return true; }
    }else if(typeof(mail) == "object"){
        if(er.test(mail.value)){ 
                    return true; 
                }
    }else{
        return false;
        }
}

/********************************************************************************/
// FUNCÇÃO PARA DEIXAR TODAS AS LETRAS MAIUSCULAS
/********************************************************************************/

   function TextBoxCaixaAlta_OnKeyUp(fsValor, foForm, foNome) { 
	if (window.event.keyCode >= 65 && window.event.keyCode <= 90){
		x = new String(document.forms[foForm].elements[foNome].value);
		document.forms[foForm].elements[foNome].value = x.toUpperCase();
	}
   }

   function TextBoxCaixaAlta_OnBlur(fsValor, foForm, foNome){ 	
	var tam=0;
	x = new String(document.forms[foForm].elements[foNome].value);
	while (tam != x.length){
		tam = x.length;
		x = x.replace('\'', '');
	}
	document.forms[foForm].elements[foNome].value = x.toUpperCase();
   }


// Somente Número
/********************************************************************************/
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;
    }
}

// JavaScript Document
/********************************************************************************/
/* Variáveis globais                                                            */
/*------------------------------------------------------------------------------*/
/*                                                                              */
if (document.layers){
	document.captureEvents(Event.KEYDOWN | Event.KEYUP);
	document.onkeydown = PTATMascaraNumeroTecla;
	document.onkeyup   = PTATMascaraNumeroExibe;
}
/*                                                                              */
/*------------------------------------------------------------------------------*/
/********************************************************************************/



/********************************************************************************/
/* Função: PTATMascaraNumero                                                    */
/*------------------------------------------------------------------------------*/
/* Autor:                                                                       */
/*   Nome: Frank Gindri Brandolff                                               */
/*   Email: frank@pta.com.br                                                    */
/*   Data: 01/10/2001                                                           */
/*------------------------------------------------------------------------------*/
/* Descrição: Classe responsável por criar o objeto MascaraNumero. Conta a quan-*/
/*            tidade de numeros que farão parte da máscara através da própria   */
/*            máscara passada como parâmetro.                                   */
/*------------------------------------------------------------------------------*/
/* Parâmetros: Nome: o nome da variável que receberá o objeto do tipo           */
/*                   PTATMascaraNumero deverá obrigatiramente ser passado como	*/
/*                   uma string neste parâmetro.                                */
/*             Mascara: máscara de entrada que delimita a quantidade de números */
/*                   a serem entrados. Delimita também o tamanho do TextBox.    */
/*                   A máscara é do tipo ___*__*__, ou seja, reconhece o carac- */
/*                   tere sublinhado (_) como sendo posição de número e qualquer*/
/*                   outro caractere com osendo pertencenta à máscara.          */
/*------------------------------------------------------------------------------*/
/* Retorno: Objeto PTATMascaraNumero.                                           */
/*------------------------------------------------------------------------------*/
/* Dependências: Nenhum.                                                        */
/*------------------------------------------------------------------------------*/
/*                                                                              */
function PTATMascaraNumero(Nome, Mascara, SaidaComMascara, ValorEntrada, autoTab){

	//propriedades
	this.ComMascara  = SaidaComMascara;
	this.Mascara     = Mascara;
	this.autoTab     = autoTab;
	this.Valor       = '';
	this.Nome        = Nome;
	this.Qtde        = 0;
	this.Objeto      = null;
	this.Form        = '';
	this.lastKey     = 0;

	var Auxiliar     = '';

	//contar quantos numeros terá a mascara
	for (i=0; i<Mascara.length; i++){
		if (Mascara.charAt(i)=='_') this.Qtde++;
	}

	for (i = 0; i < ValorEntrada.length; i++){
		if ((ValorEntrada.charCodeAt(i)>=48) && (ValorEntrada.charCodeAt(i)<=57)) Auxiliar += ValorEntrada.charAt(i);
	}
	this.Valor = Auxiliar;

	//métodos
	this.Exibe     = PTATMascaraNumeroExibe;
	this.Tecla     = PTATMascaraNumeroTecla;
	this.Blur      = PTATMascaraNumeroBlur;
	this.NextField = PTATMascaraNumeroNext;
	
	return this;
}
/*                                                                              */
/*------------------------------------------------------------------------------*/
/********************************************************************************/


function PTATMascaraNumeroBlur(){
	this.Objeto = (this.Objeto == null) ? document.getElementById(this.Nome) : this.Objeto;
	if (this.Valor=='')
		this.Objeto.value = '';
}

/********************************************************************************/
/* Função: PTATMascaraNumeroExibe                                               */
/*------------------------------------------------------------------------------*/
/* Autor:                                                                       */
/*   Nome: Frank Gindri Brandolff                                               */
/*   Email: frank@pta.com.br                                                    */
/*   Data: 01/10/2001                                                           */
/*------------------------------------------------------------------------------*/
/* Descrição: Método destinado a exibir os valores digitados juntamente com sua */
/*            máscara.                                                          */
/*------------------------------------------------------------------------------*/
/* Parâmetros: Nenhum.                                                          */
/*------------------------------------------------------------------------------*/
/* Retorno: Nenhum.                                                             */
/*------------------------------------------------------------------------------*/
/* Dependências: Nenhum.                                                        */
/*------------------------------------------------------------------------------*/
/*                                                                              */
function PTATMascaraNumeroExibe(){
	var conteudo, qtdvalor;
	conteudo = '';
	qtdvalor = 0;
	var ValorEntrada;
	this.Objeto = (this.Objeto == null) ? document.getElementById(this.Nome) : this.Objeto;

	for (i = 0; i < this.Mascara.length; i++){
		if (qtdvalor<this.Valor.length){
			if (this.Mascara.charAt(i)!='_'){
				conteudo += this.Mascara.charAt(i);
			}
			else{
				conteudo += this.Valor.charAt(qtdvalor);
				qtdvalor++;
			}
		}
		else{
			conteudo += this.Mascara.charAt(i);
		}
	}

	this.Objeto.value = conteudo;

	if (PTATMascaraNumeroExibe.arguments.length > 0){
    if (((this.lastKey >= 48) && (this.lastKey <= 57)) || ((this.lastKey >= 96) && (this.lastKey <= 105))){
      if (this.autoTab && this.Valor.length == this.Qtde) this.NextField();
    }
	}
	this.lastKey = 0;
}
/*                                                                              */
/*------------------------------------------------------------------------------*/
/********************************************************************************/



/********************************************************************************/
/* Função: PTATMascaraNumeroTecla                                               */
/*------------------------------------------------------------------------------*/
/* Autor:                                                                       */
/*   Nome: Frank Gindri Brandolff                                               */
/*   Email: frank@pta.com.br                                                    */
/*   Data: 01/10/2001                                                           */
/*------------------------------------------------------------------------------*/
/* Descrição: Função que trata a entrada de dados, filtra as teclas pressiona-  */
/*            das para aceitar apenas números. Verifica se a tecla backspace    */
/*            foi pressionada para excluir o último número digitado na proprie- */
/*            dade Valor. Verifica se a tecla delete foi pressionada para esva- */
/*            ziar a propriedade Valor.                                         */
/*------------------------------------------------------------------------------*/
/* Parâmetros: e: o evento realizado no input text da máscara.                  */
/*------------------------------------------------------------------------------*/
/* Retorno: Nenhum.                                                             */
/*------------------------------------------------------------------------------*/
/* Dependências: Nenhum.                                                        */
/*------------------------------------------------------------------------------*/
/*                                                                              */
function PTATMascaraNumeroTecla (e){
	var whichCode;
	this.Objeto = (this.Objeto == null) ? document.getElementById(this.Nome) : this.Objeto;

	if (document.layers){
		whichCode = e.which;
	}
	else{
		whichCode = (window.Event) ? e.which : e.keyCode;
	}
  this.lastKey = whichCode;
	var key;

	if (((whichCode >= 48) && (whichCode <= 57)) || ((whichCode >= 96) && (whichCode <= 105))){
		//a tecla pressionada é um número
		if (this.Valor.length < this.Qtde){
			if (whichCode > 95){
				key = String.fromCharCode(whichCode-48);
			}
			else{
				key = String.fromCharCode(whichCode);
			}
			this.Valor += key;
		}
	}
	else{
		//se a tecla pressionada não for um numero
		switch (whichCode){
			case 8://Tecla backspace
				//apagar o último caracter;
				this.Valor = this.Valor.substring(0,this.Valor.length-1);
			break;
			case 46://tecla delete
				//apaga todo o conteúdo da máscara;
				this.Valor = '';
			break;
		}
	}
	return 0;
}



/********************************************************************************/
/* Função: PTATMascaraNumeroNext                                                */
/*------------------------------------------------------------------------------*/
/* Autor:                                                                       */
/*   Nome: Frank Gindri Brandolff                                               */
/*   Email: frank@pta.com.br                                                    */
/*   Data: 01/10/2001                                                           */
/*------------------------------------------------------------------------------*/
/* Descrição: Função que trata de mudar o foco da mascara para o proximo campo  */
/*            do Form.                                                          */
/*------------------------------------------------------------------------------*/
/* Parâmetros: Nenhum.                                                          */
/*------------------------------------------------------------------------------*/
/* Retorno: Nenhum.                                                             */
/*------------------------------------------------------------------------------*/
/* Dependências: Nenhum.                                                        */
/*------------------------------------------------------------------------------*/
/*                                                                              */
function PTATMascaraNumeroNext(){
  this.Objeto = (this.Objeto == null) ? document.getElementById(this.Nome) : this.Objeto;
  var theIndex = this.Objeto.tabIndex;
  var theForm = this.Objeto.form;
  for (var i = 0; i<theForm.elements.length; i++){
    if (theForm.elements[i].tabIndex == (theIndex+1)){
      theForm.elements[i].focus();
      break;
    }
  }
}
/*                                                                              */
/*------------------------------------------------------------------------------*/
/********************************************************************************/