function validaCnpj(campo) {
    if ( trim( campo.value ) != "" ) {
        var Num = limpa(campo.value);
        var Mult1 = '543298765432';
        var Mult2 = '6543298765432';
        var dig1 = 0;
        var dig2 = 0;
        var X = 0;
        for (var X = 0; X < 13; X++) {
            dig1 += (Num.substr(X, 1) * Mult1.substr(X, 1));
        }
        for (var X = 0; X < 14; X++) {
            dig2 += (Num.substr(X, 1) * Mult2.substr(X, 1));
        }
        dig1 = (dig1 * 10) % 11;
        dig2 = (dig2 * 10) % 11;
    
        if (dig1 == 10) 
            dig1 = 0;
        if (dig2 == 10)
            dig2 = 0;
        if (dig1 != Num.substr(12, 1)) {
            window.alert("CNPJ Inv?lido");
            campo.focus();
            return (false);
        }
        if (dig2 != Num.substr(13, 1)){
            window.alert("CNPJ Inv?lido");
            campo.focus();
            return (false);
        }
   }
    return (true);
}

function validaCpf(campo){
    
    var c = campo.value;
    var i,a1,a2; 
    var repete = true;
    //valida os casos fuleiros repetidos    
    
     for (i=0; i < c.length;i++){
       a1 = c.charAt(0);
       a2 = c.charAt(i);
       if (a2 != a1){
          repete = false;
       }
     }
     
     
     if (repete){
       alert("CPF Inv?lido")
	   v = true; 
	   return false; 
     }
    
	
	s = c;
    var c = s.substr(0,9); 
	var dv = s.substr(9,2); 
	var d1 = 0; 
	var v = false;
	for (i = 0; i < 9; i++) 
	{ 
		d1 += c.charAt(i)*(10-i); 
	} 
	if (d1 == 0){ 
		alert("CPF Inv?lido")
		v = true; 
	 return false; 
	} 
	d1 = 11 - (d1 % 11); 
	if (d1 > 9) d1 = 0; 
	if (dv.charAt(0) != d1) 
	{ 
		alert("CPF Inv?lido") 
		v = true;
		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) 
	{ 
		alert("CPF Inv?lido") 
		v = true;
		return false; 
	} 
	return true;
}

function cpfMask(pForm,pCampo,pTamMax,pPos1,pPos2,pPosTraco,pTeclaPres){
 var wTecla, wVr, wTam;
 wTecla = pTeclaPres.keyCode;
 wVr = pForm[pCampo].value;
 wVr = wVr.toString().replace( "-", "" );
 wVr = wVr.toString().replace( ".", "" );
 wVr = wVr.toString().replace( ".", "" );
 wVr = wVr.toString().replace( "/", "" );
 wTam = wVr.length ;

 if (wTam < pTamMax && wTecla != 8) { 
    wTam = wVr.length + 1 ; 
 }

 if (wTecla == 8 ) { 
    wTam = wTam - 1 ; 
 }
   
 if ( wTecla == 8 || wTecla == 88 || wTecla >= 48 && wTecla <= 57 || wTecla >= 96 && wTecla <= 105 ){
  if ( wTam <= 2 ){
    pForm[pCampo].value = wVr ;
  }
  if (wTam > pPosTraco && wTam <= pTamMax) {
        wVr = wVr.substr(0, wTam - pPosTraco) + '-' + wVr.substr(wTam - pPosTraco, wTam);
  }
  if ( wTam == pTamMax){
        wVr = wVr.substr( 0, wTam - pPos1 ) + '.' + wVr.substr(wTam - pPos1, 3) + '.' + wVr.substr(wTam - pPos2, wTam);
  }
  pForm[pCampo].value = wVr;
 
 }

}

function mascaraCNPJ(Campo, teclapres){

   var tecla = teclapres.keyCode;

   var vr = new String(Campo.value);
   vr = vr.replace(".", "");
   vr = vr.replace(".", "");
   vr = vr.replace("/", "");
   vr = vr.replace("-", "");

   tam = vr.length + 1 ;

   
   if (tecla != 9 && tecla != 8){
      if (tam > 2 && tam < 6)
         Campo.value = vr.substr(0, 2) + '.' + vr.substr(2, tam);
      if (tam >= 6 && tam < 9)
         Campo.value = vr.substr(0,2) + '.' + vr.substr(2,3) + '.' + vr.substr(5,tam-5);
      if (tam >= 9 && tam < 13)
         Campo.value = vr.substr(0,2) + '.' + vr.substr(2,3) + '.' + vr.substr(5,3) + '/' + vr.substr(8,tam-8);
      if (tam >= 13 && tam < 15)
         Campo.value = vr.substr(0,2) + '.' + vr.substr(2,3) + '.' + vr.substr(5,3) + '/' + vr.substr(8,4)+ '-' + vr.substr(12,tam-12);
      }
}

function mascaraCpf(campo) {

    var mycpf = new String(campo.value);
    mycpf = mycpf + campo.value;
    if (mycpf.length == 3) {
        mycpf = mycpf + '.';
        document.forms[0].campo.value = mycpf;
    }
    if (mycpf.length == 7) {
        mycpf = mycpf + '.';
        document.forms[0].campo.value = mycpf;
    }
    if (mycpf.length == 11) {
        mycpf = mycpf + '-';
        document.forms[0].campo.value = mycpf;
    }
    if (mycpf.length == 14) {
    }
}



/****************************************
 * Title: Mascara
 * Description: Mascara global
 * Copyright:    Copyright (c) 2003
 * @version 1.0
 ***************************************/
/*
 As seguintes conven??es devem ser utilizadas:

	- Para bloquear a entrada somente para digitos deve-se formatar a mascara utilizando '9'
			Ex: 99/99/9999  formatando datas
	- Para bloquear a entrada somente para letras e digitos deve-se formatar a mascara utilizando '#'
			Ex: ###.###
	- A quantidade de caracteres permitida ser? limitada pela propriedade maxlength e pela mascara especificada
	- Pode-se especificar mais de uma mascara. Neste caso, utiliza-se o operador || para separar as mascaras
	- A fun??o ir? ordenar as mascaras de acordo com o tamanho delas. A primeira mascara a ser utilizada ser? a menor
	  passando para as outras quando a entrada for maior que o tamanho da mascara atual.
	- Deve-se utilizar colchetes para especificar caracteres de repeti??o
			Ex: [###.]###,##    formatando valores

	Segue alguns exemplos das mascaras mais comuns:
      - (###)               --> DDD.  
      - ##                  --> N?mero inteiro, ignora do 3 em diante      
	  - ###-####||####-#### --> Telefone de 7 ou 8 digitos<br>
      - ##/##/####          --> Data com dia, mes e ano
      - ##/##               --> Data com dia, mes
      - ##:##:##            --> Hor?rio com: hora, minuto, segundo
      - ##:##               --> Hor?rio com: hora, minuto
      - ####/##/##          --> Data (invertida) ano, mes, dia
      - ##.###-###          --> Cep
      - ###.###.###-##      --> Cpf
      - ##.###.###/####-##  --> Cgc
      - ###.###.###-##||##.###.###/####-## -->Cpf (pondendo ser cgc tamb?m)           
      - [###.]###           --> N?mero inteiro (que pode variar)
      - [###.]###,##        --> Dinheiro (que pode variar)<br>
*/


//Ponto de partida para as outras functions
function mascara(obj,mascara){		
	var texto = obj.value;
	var max = obj.maxLength;
	
	if(limparEntrada(obj).length > max-1){
		event.keyCode = 0;
		return;
	}
		
	//Default
	if( buscaDigito(mascara,'#') != -1){//Utiliza Lazanha		
		mascaraLazanha(obj,mascara);
	}
	else if( buscaDigito(mascara,'9') != -1){//Utiliza Digito	
		mascaraDigito(obj,substituiPorLazanha(mascara));
	}
	return;
}	

//Fun??o que coloca as mascaras
function mascarar(obj,mascara){
		var valor_duplicar = "";
		var valor_completar = "";
		var colchete_abre = abriuColchete(mascara);
		var colchete_fecha = fechouColchete(mascara)
		var retorno = "";
		var tam_lazanha = contaLazanha(mascara);		
		var texto = obj.value+retornaValor(event);
		event.keyCode = 0;
		if(colchete_abre ==-1 && texto.length > tam_lazanha){			
			texto = obj.value;			
		}

		mascara = limpaMascara(mascara);
				
		//aumenta a mascara quando existem colchetes
		if(colchete_abre < colchete_fecha  && colchete_abre!=-1 && colchete_fecha!=-1){
			var tamanhoDoTexto = 1+obj.value.length;			
			valor_duplicar = mascara.substring(colchete_abre+1,colchete_fecha);
			valor_completar = mascara.substring(colchete_fecha+1);

			//valor_completar = valor_duplicar + valor_completar;
			while(contaLazanha(valor_completar) < tamanhoDoTexto){
				valor_completar = valor_duplicar + valor_completar;				
			}			
			mascara = valor_completar;

			var j = texto.length-1;											
			for (i = mascara.length-1; i>-1 && j>-1; i--) {		
				if (mascara.substring(i,i+1)=="#") {								
					retorno = texto.substring(j,j+1) + retorno;
					j--;							
				}
				else{
					retorno = mascara.substring(i,i+1) + retorno;
				}				
			}
		}//Caso n?o tem colchetes e n?o tem ||
		else if(mascara.split('||').length == 1){
			var j = 0;											
			for(i = 0 ; i<mascara.length && j<texto.length; i++) {		
				if (mascara.substring(i,i+1)=="#") {								
					retorno = retorno + texto.substring(j,j+1);
					j++;							
				}
				else{
					retorno = retorno + mascara.substring(i,i+1) ;
				}				
			}
			var f = mascara.length;
			while(mascara.substring(f-1,f)!="#"){
				retorno = retorno + mascara.substring(f-1,f);
				f--;
			}

		}//N?o tem Colchetes e Tem ||
		else if(mascara.split('||').length != 1){

			///////////Trecho de c?digo que quebra a mascara para pegar a mascara adequada////
			var array = mascara.split('||');			
			array = tamanho(array);		
			var i = 0;
			mascara = array[i];			
			while(contaLazanha(mascara) < texto.length  && i+1 < array.length){
				i=i+1;
				mascara = array[i];		
			}
			/////////////////////////////////////////////////////////////////////////////////

			var tam_lazanha = contaLazanha(mascara);
			if(texto.length > tam_lazanha){			
				texto = obj.value;			
			}	
		
			//mascarando			
			var j = 0;											
			for(i = 0 ; i<mascara.length && j<texto.length; i++) {		
				if (mascara.substring(i,i+1)=="#") {								
					retorno = retorno + texto.substring(j,j+1);
					j++;							
				}
				else{
					retorno = retorno + mascara.substring(i,i+1) ;
				}				
			}
			var f = mascara.length;
			while(mascara.substring(f-1,f)!="#"){
				retorno = retorno + mascara.substring(f-1,f);
				f--;
			}			
		}
				
		obj.value = retorno;
		return obj;
}

//Funcao que retira os espacos em branco antes e depois da mascara
function limpaMascara(mascara){
	var masc = "";

    for (i = 0; i < mascara.length; i++) {
		var sub = mascara.substring(i,i+1);
		if (sub != " "){
            masc=masc+sub;
        }
    }
	return masc;
}

//Fun??o que ordena um array, de acordo com o tamanho dos seus elementos. Ordena??o Ascendente.
function tamanho(array){
	var temp1;
	var temp2;
	for(i=0; i<array.length-1; i++){
		temp1 = array[i];
		for(j=i+1; j<array.length; j++){
			temp2 = array[j];
			if(temp2.length < temp1.length){				
				array[i] = temp2;
				array[j] = temp1;
				temp1= temp2;
				temp2= array[j]; 
			}
		}
	}	
	return array;
}

//funcao que conta quantas lazanhas tem na palavra
function contaLazanha(mascara){
	var cont_lazanha = 0;
	for (i = 0; i < mascara.length; i++){
		if (mascara.substring(i,i+1) == "#"){
			cont_lazanha++;
        }
	}
	return cont_lazanha;
}

//fun??o que deixa apenas os digitos e as letras
function limparEntrada(obj){
	var texto = "";
	
    for (i = 0; i < obj.value.length; i++) {
		var temp = obj.value.substring(i,i+1);
		if( validar(temp)  ){
			texto= texto+obj.value.substring(i,i+1);
        }	
    }

	return texto;
}

//retorna true quando o parametro ? um digito ou uma letra
function validar(temp){
	if( !isNaN(temp) || temp=='a' || temp=='A' || temp=='b' || temp=='B' || temp=='c' || temp=='C' || temp=='d' || temp=='D' || temp=='e' || temp=='E'
			 || temp=='f' || temp=='F' || temp=='g' || temp=='G' || temp=='h' || temp=='H' || temp=='i' || temp=='I' || temp=='j' || temp=='J'
			 || temp=='k' || temp=='K' || temp=='l' || temp=='L' || temp=='m' || temp=='M' || temp=='n' || temp=='N' || temp=='o' || temp=='O'
			 || temp=='p' || temp=='P' || temp=='q' || temp=='Q' || temp=='r' || temp=='R' || temp=='s'|| temp=='S' || temp=='t' || temp=='T'
			 || temp=='u' || temp=='U' || temp=='v' || temp=='V' || temp=='x' || temp=='X' || temp=='y' || temp=='Y' || temp=='z' || temp=='Z' ){
		return true;
	}
	else{
		return false;
	}
}

//fun??o que retorna -1 caso naum encotre o digito desejado, se encontrar retorna o indice onde ele foi encontrado
function buscaDigito(valor,digito){
		indice= valor.indexOf(digito);
		return indice;
}

//Fun??o que bloqueia a entrada apenas para digito
function mascaraDigito(obj,mascara){
	if (event.keyCode <= 47 || event.keyCode >57){
		event.keyCode = 0;
		return false;
	}
	else{
		obj.value = limparEntrada(obj);
		mascarar(obj,mascara);
	}
}

//Fun??o que bloqueia a entrada apenas para digito e letras
function mascaraLazanha(obj,mascara){
	if ( !(event.keyCode > 47 && event.keyCode <58) && !(event.keyCode > 64  && event.keyCode < 91) && !(event.keyCode > 96  && event.keyCode < 123)  ){
		event.keyCode = 0;
		return false;
	}
	else{
		obj.value = limparEntrada(obj);
		mascarar(obj,mascara);
	}
	return;
}

//Funcao que retorna o indice onde foi encontrado um ]
function fechouColchete(mascara){
	var posicao = -1;

	//verificar se existe colchete abrindo e fechando
    for (i = 0; i < mascara.length; i++) {
		var sub = mascara.substring(i,i+1);
		if (sub == ']' ){
            posicao = i;
        }
    }
	return posicao;
}

//Funcao que retorna o indice onde foi encontrado um [
function abriuColchete(mascara){
	var posicao  = -1;

	//verificar se existe colchete abrindo e fechando
    for (i = 0; i < mascara.length; i++) {
		var sub = mascara.substring(i,i+1);
		if( sub == '[' ){
			posicao = i;
        }
    }
	return posicao;
}

function substituiPorLazanha(mascara){
	var masc = "";

	//verificar se existe colchete abrindo e fechando
    for (i = 0; i < mascara.length; i++) {
		var sub = mascara.substring(i,i+1);
		if( sub == '9' ){
			masc = masc+'#';
        }
		else{
			masc = masc+sub;
		}
    }
	return masc;
}


//Retorna  o valor de um evento
function retornaValor(ev){	
	return String.fromCharCode(event.keyCode);
}

function FormataDado(campo,tammax,pos,teclapres){
	var tecla = String.fromCharCode(event.keyCode);
	var re = /[0-9]/;
	
	if ((campo.value.length > tammax)){
		event.keyCode = 0;
		return;
	}
	
	var tecla = teclapres.keyCode;
	vr = campo.value;
	vr = vr.replace( "-", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( "/", "" );
	tam = vr.length ;

	if (tam < tammax && tecla != 8){ tam = vr.length + 1 ; }

	if (tecla == 8 ){ tam = tam - 1 ; }
			
	if ( tam <= 2 ){
 		campo.value = vr ;
 	}
 	
	if ( tam > pos && tam <= tammax ){
		campo.value = vr.substr( 0, tam - pos ) + '-' + vr.substr( tam - pos, tam );
	}
}

//Coloca a máscara no campo CNPJ. Usado no evento 'onblur'.
function mascararCampoCNPJ(Campo){

   var vr = new String(Campo.value);
   vr = vr.replace(".", "");
   vr = vr.replace(".", "");
   vr = vr.replace("/", "");
   vr = vr.replace("-", "");

   Campo.value = vr;
   mascarar(Campo, '##.###.###/####-##');
}

//Coloca a máscara no campo CPF. Usado no evento 'onblur'.
function mascararCampoCPF(Campo){

   var vr = new String(Campo.value);
   vr = vr.replace(".", "");
   vr = vr.replace(".", "");
   vr = vr.replace("/", "");
   vr = vr.replace("-", "");

   Campo.value = vr;
   mascarar(Campo, '###.###.###-##');
}



if (document.layers)
    window.captureEvents(Event.KEYDOWN | Event.KEYUP);
// Funcoes para mascara de cpf usando regex
// Exemplo para campos numericos: onkeypress="mascara(this,Integer)"
// onmouseover="mascara(this,Integer)"
function mascara(o,f){
    v_obj=o;
    v_fun=f;
    setTimeout("execmascara()",1);
}

/**
 * Coloca mascara no campo e apos a digitao faz o auto-tab Usar o
 * caracter '#' como coringa. O campos maxLength nao e obrigatorio Ex se fosse
 * para CPF: onkeypress="return mask(true, event, this, '###.###.###-##');" -
 * Obs: Para CPF ja existe funcao propria Para mascara dinamica, inicie a
 * marcara com '[' e depois a mascara que sera dinamica, finalizando com ']',
 * depois pode continuar com a marcara normal Ex de utilizacao dinamica, para
 * separar de 2 em 2 caracteres com um '-' e finalizar com '.' e outro caracter:
 * onkeypress="return mask(false, event, this, '[-##].#');" Para colocar somente
 * um '-' no penultimo caracter, como nos casos de dv: onkeypress="return
 * mask(false, event, this, '[#].#', 10);"
 */
function mask(somenteNumeros, event, campo, mask, maxLength) {
    var keyCode;
	 
    if (event.srcElement)
        keyCode = event.keyCode;
    else if (event.target)
        keyCode = event.which;
    else
        return true;
	
    var maskStack = new Array();
	
    var isDynMask = false;
	
    if (mask.indexOf('[') != -1)
        isDynMask = true;
	
    var length = mask.length;
	
    for (var i = 0; i < length; i++)
        maskStack.push(mask.charAt(i));
	
    var value = campo.value;
    i = value.length;
	 
    if (keyCode == 0 || keyCode == 8 || event.ctrlKey)
        return true;
	
    if (somenteNumeros && (keyCode < 48 || keyCode > 57))
        return false;
	
    if (maxLength != undefined && value.length > maxLength) {
        return false;
    }
	
    if (!isDynMask && i < length) {
	
        if (maskStack.toString().indexOf(String.fromCharCode(keyCode)) != -1 && keyCode != 8) {
            return false;
        } else {
            if (keyCode != 8) {
                if (maskStack[i] != '#') {
                    var old = campo.value;
                    campo.value = old + maskStack[i];
                }
            }
		
            if (autoTab(campo, keyCode, length)) {
                if (!document.layers) {
                    return true;
                } else if (keyCode != 8) {
                    campo.value += String.fromCharCode(keyCode);
                    return false;
                } else {
                    return true;
                }
            } else {
                return false;
            }
        }
	
    } else if (isDynMask) {
	
        var maskChars = "";
        for (var j = 0; j < maskStack.length; j++)
            if (maskStack[j] != '#' && maskStack[j] != '[' && maskStack[j] != ']')
                maskChars += maskStack[j];
	
        var tempValue = "";
        for (j = 0; j < value.length; j++) {
            if (maskChars.indexOf(value.charAt(j)) == -1)
                tempValue += value.charAt(j);
        }
	
        value = tempValue + String.fromCharCode(keyCode);
	
        if (maskChars.indexOf(String.fromCharCode(keyCode)) != -1) {
            return false;
        } else {
	
            var staticMask = mask.substring(mask.indexOf(']') + 1);
            var dynMask = mask.substring(mask.indexOf('[') + 1, mask.indexOf(']'));
	
            var realMask = new Array;
	
            if (mask.indexOf('[') == 0) {
	 
                var countStaticMask = staticMask.length - 1;
                var countDynMask = dynMask.length - 1;

                for (j = value.length - 1; j >= 0; j--) {
                    if (countStaticMask >= 0) {
                        realMask.push(staticMask.charAt(countStaticMask));
                        countStaticMask--;
                    }
                    if (countStaticMask < 0) {
                        if (countDynMask >= 0) {
                            if (dynMask.charAt(countDynMask) != '#') {
                                realMask.push(dynMask.charAt(countDynMask));
                                countDynMask--;
                            }
                        }
				 
                        if (countDynMask == -1) {
                            countDynMask = dynMask.length - 1;
                        }
				
                        realMask.push(dynMask.charAt(countDynMask));
                        countDynMask--;
                    }
                }
            }
	
            var result = "";
	
            var countValue = 0;
            while (realMask.length > 0) {
                var c = realMask.pop();
                if (c == '#') {
                    result += value.charAt(countValue);
                    countValue++;
                } else {
                    result += c;
                }
            }
	
            campo.value = result;

            if (maxLength != undefined && value.length == maxLength) {
                var form = campo.form;
                for (i = 0; i < form.elements.length; i++) {
                    if (form.elements[i] == campo) {
                        campo.blur();
                        if ((form.elements[i + 1] != null) && (form.elements[i + 1].name != "METHOD"))
                            form.elements[i + 1].focus();
                        break;
                    }
                }
            }
            return false;
        }
    } else {
        return false;
    }

}
	

/*
 * Auto tab que insere um caracter passado
 */
function autoTab(campo, keyCode, length) {
    var i = campo.value.length;
    if (i == length - 1) {
        campo.value += String.fromCharCode(keyCode);
        var form = campo.form;
        for (var i = 0; i < form.elements.length; i++) {
            if (form.elements[i] == campo) {
                campo.blur();
                // procura no formulario o proximo campo que esta visivel
                while((form.elements[i + 1] != null) && form.elements[i + 1].attributes.getNamedItem("type")!=null && form.elements[i + 1].attributes.getNamedItem("type").value == "hidden") {
                    i++;
                }
                if ((form.elements[i + 1] != null) && (form.elements[i + 1].name != "METHOD")) {
                    form.elements[i + 1].focus();
                }
                break;
            }
        }
        return false;
    } else {
        return true;
    }
}	


function formataTransferido(event, el, noPaste, fn) {
    var paste = (noPaste === true ? false : true);

    if (event.ctrlKey) {
        var keyCode;
        var V = 0x56;
        var v = 0x76;

        if (event.srcElement)
            keyCode = event.keyCode;
        else if (event.target)
            keyCode = event.which;
        else
            keyCode = 0;

        if (keyCode == v || keyCode == V) {
            if (paste) {
                fn(el);
            } else {
                el.value = "";
            }
        }
    }
}

/*
 * Formata CPF transferido por CTRL+V. Se o conteudo nao puder ser formatado
 * como CPF, entao apaga o conteudo.
 * 
 * Exemplo de utilizao: onkeyup="formataCPFTransferido(event, this);"
 * 
 * 
 * Exemplo: onpaste="this.blur();" onchange="formataCPFEstatico(this);"
 */
function formataCPFTransferido(event, el, noPaste) {
    formataTransferido(event, el, noPaste, formataCPFEstatico);
}


/*
 * Formata CPF estaticamente.
 * 
 * Exemplo de uti: onmouseover="formataCPFEstatico(this);"
 */
function formataCPFEstatico(el) {
    if (el.value) {
        var value = el.value;
		var retorno = "";
		var tamanho;
        
        value = value.replace(/\D/g,"");

        if (value.length <= 11){
			tamanho = value.length;
        }else{
        	tamanho = 11;
        }
        
       	for(var j = 0; j < tamanho; j++){
			if(j == 3 || j == 6){
				retorno += ".";
			}
			if(j == 9){
				retorno += "-";
			}
			retorno += value.charAt(j);
		}

        el.value = retorno;
    }
}


function mascaraData(el) {
    
	if (el.value) {
        var value = el.value;

        value = value.replace(/\D/g,"");

        if (value.length != 6 &&
                value.length != 8) {
            value = "";
        } else if (value.length == 6) {
            value = value.replace(/^(\d{2})(\d{2})(\d{2})$/,
                function(s, g1, g2, g3) {
                    return g1 + "/" + g2 + "/" +
                          (g3 < 50  ? "20" : "19") +
                           g3;
                }
            );
        } else {
            value = value.replace(/^(\d{2})(\d{2})(\d{4})$/,
                function(s, g1, g2, g3) {
                    return g1 + "/" + g2 + "/" + g3;
                }
            );
        }

        el.value = value;
    }
}


/*
 * Formata o CPF enquanto os ditos so informados e ao informar todos os
 * ditos o foco  automaticamente transferido para o proximo elemento do
 * formulario atual.
 * 
 * Exemplo de utiliza: onkeypress="return formataCPF(event, this);"
 */
function formataCPF(event, campo) {
    return mask(true, event, campo, '###.###.###-##');
}
 
function formataData(event, campo){
	return mask(true,event,campo, '##/##/####');
}

function formataCEP(event, campo){
	return mask(true,event,campo, '#####-###');
}
function formataTelefone(event, campo){
	return mask(true,event,campo, "####-####")
}
function formataCNPJ(event,campo){
	return mask(true,event,campo, "##.###.###/####-##");
}
function formataHora(event,campo){
	return mask(true,event,campo, "##:##");
}

/*
 * Formata CPF transferido por CTRL+V. Se o conteudo nao puder ser formatado
 * como CPF, entao apaga o conteudo.
 * 
 * Exemplo de utilizao: onkeyup="formataCPFTransferido(event, this);"
 * 
 * 
 * Exemplo: onpaste="this.blur();" onchange="formataCPFEstatico(this);"
 */
function formataCNPJTransferido(event, el, noPaste) {
    formataTransferido(event, el, noPaste, formataCNPJEstatico);
}


/*
 * Formata CPF estaticamente.
 * 
 * Exemplo de uti: onmouseover="formataCPFEstatico(this);"
 */
function formataCNPJEstatico(el) {
    if (el.value) {
        var value = el.value;
		var retorno = "";
		var tamanho;
        
        value = value.replace(/\D/g,"");

        if (value.length <= 14){
			tamanho = value.length;
        }else{
        	tamanho = 14;
        }
        
       	for(var j = 0; j < tamanho; j++){
			if(j == 2 || j == 5){
				retorno += ".";
			}
			if(j == 8){
				retorno += "/";
			}
			if(j == 12){
				retorno += "-";
			}
			retorno += value.charAt(j);
		}

        el.value = retorno;
    }
}

function mascaraHorarioVariavel(campo){
	var textoCampo = campo.value.replace(":","");
	var tamanhoCampo = textoCampo.length;
	if(tamanhoCampo > 5){
		textoCampo = textoCampo.substring(0,5);
		tamanhoCampo = textoCampo.length;
	}
	if(tamanhoCampo  == 4 || tamanhoCampo == 5){
		var temp = textoCampo.substring(0,tamanhoCampo-2);
		var temp2 = textoCampo.substring(tamanhoCampo-2,tamanhoCampo);
		var textoResul = temp + ':' + temp2;
		campo.value = textoResul;
	}
}



