/** 
  * Função que valida campos requeridos em um form.
  * Para utilizá-la, apenas chame-a no evento onSubmit de um form e coloque o atributo required="yes" nos campos obritatórios
  */
function validateForm( objForm ){
	for(i=0; i<objForm.elements.length; i++) {
        if((objForm.elements[i].attributes['required'] && objForm.elements[i].attributes['required'].value.toLowerCase()=="yes" && !objForm.elements[i].value)){
            fieldLabel = objForm.elements[i].name;
            if( objForm.elements[i].attributes['fieldLabel'] && objForm.elements[i].attributes['fieldLabel'].value){
                fieldLabel=objForm.elements[i].attributes['fieldLabel'].value
            }
            
            alert('Erro: O campo "'+fieldLabel+'" é de preenchimento obrigatório.');
            return false;
        }
    }
    
    return true;
}

// Classe de tipo de entrada, para validação de formulários
function entryFormat(){
    var pattern;
    var autoIntesert;
}

// Alguns tipos comuns, pré-definidos para facilitar o uso
ipMask = new entryFormat();
ipMask.pattern = /^((25[0-5]|2[0-4][0-9]|[0-9]|[1-9][0-9]?|1[0-9][0-9]?)\.){0,3}(25[0-5]|2[0-4][0-9]|[0-9]|[1-9][0-9]?|1[0-9][0-9]?)?$/;
ipMask.autoInsert = ".";

cpfMask = new entryFormat();
cpfMask.pattern = /^([0-9]{0,3}\.){0,2}[0-9]{0,3}(\-[0-9]{0,2})?$/;
cpfMask.autoInsert = ".-";

cnpjMask = new entryFormat();
cnpjMask.pattern = /^[0-9]{0,2}(\.[0-9]{0,3}(\.[0-9]{0,3}(\/[0-9]{0,4}(-[0-9]{0,2})?)?)?)?$/;
cnpjMask.autoInsert = "./-";

cepMask = new entryFormat();
cepMask.pattern = /^[0-9]{0,5}(-[0-9]{0,3})?$/;
cepMask.autoInsert = "-";

timeMask = new entryFormat();
timeMask.pattern = /^([0-1][0-9]?|2[0-3]?)(:[0-5][0-9]?)?$/;
timeMask.autoInsert = ":";

dataMask = new entryFormat();
dataMask.pattern = /^(0[1-9]?|[1-9]|[12][0-9]|3[01])(\/((0[1-9]?|[1-9]|1[0-2])(\/[0-9]{0,4})?)?)?$/;
dataMask.autoInsert = "/";

dataTimeMask = new entryFormat();
dataTimeMask.pattern = /^(0[1-9]?|[1-9]|[12][0-9]|3[01])(\/((0[1-9]?|[1-9]|1[0-2])(\/[0-9]{0,4}( [0-9]{0,2}(:[0-9]{0,2})?)?)?)?)?$/;
dataTimeMask.autoInsert = "/: ";

intMask = new entryFormat();
intMask.pattern = /^[0-9]*$/;

floatMask = new entryFormat();
floatMask.pattern = /^[0-9]+(,[0-9]*)?$/;

bigIntMask = new entryFormat();
bigIntMask.pattern = /^[0-9]{1,3}(\.[0-9]{0,3})*?$/;
bigIntMask.autoInsert = ".";


// Função que avalia a validade da entrada no campo e faz a máscara automática.
function testEntry(e, patternTest, autoInsert){
    if (window.event){
        e = window.event;
        fieldValue = event.srcElement.value;
        fieldElement = event.srcElement;
        lastEntry = String.fromCharCode(e.keyCode);
    }else{
        fieldValue = e.target.value;
        fieldElement = e.target;
        lastEntry = String.fromCharCode(e.charCode);
    }
    
    resultValue = fieldValue + lastEntry;
    //alert(e.keyCode);
    switch( e.keyCode ){
		case 9: //Tab
		case 13: //Enter
        case 8: //Backspace
        case 45: //Delete
        case 37: //Left
        case 39: //Right
        case 36: //Home
        case 35: //End
		case 116: //F5
            return;
    }
    
    if( !autoInsert ) autoInsert="";
    
    if( resultValue.match( patternTest ) ) return;
    for(var i=0; i<autoInsert.length; i++){
        if( (resultValue+autoInsert.charAt(i)).match( patternTest ) ) return;
        
        if( (fieldValue+autoInsert.charAt(i)+lastEntry).match( patternTest ) ){
            fieldElement.value += autoInsert.charAt(i);
            return;
        }
    }
    
    
    if (window.event){
        window.event.returnValue = null;
    }else{
        e.preventDefault(); 
    }
}

function validateCPF( strCpf ){
	//var CPF = document.form2.CPF.value; // Recebe o valor digitado no campo
	var CPF = strCpf; // Recebe o valor digitado no campo
	var posicao, i, soma, dv, dv_informado;
	var digito = new Array(10); //Cria uma array de 11 posições para armazenar o CPF
	dv_informado = CPF.substr(9, 2); // Armazena os dois últimos dígito do CPF
	for (i=0; i<=8; i++) { // Desmembra o número do CPF na array digito
		digito[i] = CPF.substr( i, 1);
	}
	// Calcula o valor do 10° dígito da verificação
	posicao = 10;
	soma = 0;
	for (i=0; i<=8; i++) {
		soma = soma + digito[i] * posicao;
		posicao = posicao - 1;
	}
	digito[9] = soma % 11;
	if (digito[9] < 2) {
		digito[9] = 0;
	}else{
		digito[9] = 11 - digito[9];
	}
	// Calcula o valor do 11° dígito da verificação
	posicao = 11;
	soma = 0;
	for (i=0; i<=9; i++) {
		soma = soma + digito[i] * posicao;
		posicao = posicao - 1;
	}
	digito[10] = soma % 11;
	if (digito[10] < 2) {
		digito[10] = 0;
	}else {
		digito[10] = 11 - digito[10];
	}
	//Verifica se os dígitos verificadores conferem
	dv = digito[9] * 10 + digito[10];
	if (dv != dv_informado || document.form2.CPF.value == 00000000000 ||
							  document.form2.CPF.value == 11111111111 || 
							  document.form2.CPF.value == 22222222222 || 
							  document.form2.CPF.value == 33333333333 || 
							  document.form2.CPF.value == 44444444444 || 
							  document.form2.CPF.value == 55555555555 || 
							  document.form2.CPF.value == 66666666666 || 
							  document.form2.CPF.value == 77777777777 || 
							  document.form2.CPF.value == 88888888888 || 
							  document.form2.CPF.value == 99999999999) {
		alert("CPF inválido");
		document.form2.CPF.value = "";
		return false;
	}else{
		alert("CPF válido");
		return false;
	}
	return false;
}

function validateCNPJ( strCnpj ) {
	//CNPJ = document.validacao.CNPJID.value;
	CNPJ = strCnpj;
	erro = new String;
	if (CNPJ.length < 18) erro += "É necessario preencher corretamente o número do CNPJ! \n\n";
	if ((CNPJ.charAt(2) != ".") || (CNPJ.charAt(6) != ".") || (CNPJ.charAt(10) != "/") || (CNPJ.charAt(15) != "-")){
		if (erro.length == 0) erro += "É necessário preencher corretamente o número do CNPJ! \n\n";
	}
    //substituir os caracteres que não são números
	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 verificação de CNPJ suporta apenas números! \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 +="Dígito verificador com problema!";
	}
	if (erro.length > 0){		
		return false;
	} else {
		return true;	
	}
}