﻿arrPermitidos = new Array(".jpg",".jpeg");
var corAlerta = "#509a10";

function validaForm(form) {
	var elementos = form.elements;
	var nome = '';
	for (var i=0; i< elementos.length; i++){
		//if (elementos[i].getAttribute("type")=="text") {
			elementos[i].style.backgroundColor = "#74bc28";
			if (elementos[i].getAttribute("obrigatorio")=="1") {
				nome = (!elementos[i].getAttribute("exibe")) ? elementos[i].getAttribute("name") : elementos[i].getAttribute("exibe");
				if (elementos[i].value=="" || elementos[i].value==0) {
					alert("O campo "+nome+" é obrigatorio.");
					elementos[i].style.backgroundColor = corAlerta;
					return false;
				}	
				if(elementos[i].getAttribute("name")=="imagem" && elementos[i].getAttribute("value")!=null){
					if(!limitaAnexo(elementos[i].value)){
						alert("Por favor selecione apenas arquivos dos tipos:  " + (arrPermitidos.join("  ")) + "\nPor favor selecione novamente!");
						return false;
					}
				}
				
			}
			
			if (elementos[i].getAttribute("cnpj")=="1") {
				if(!validaCNPJ(elementos[i].value)){
					elementos[i].style.backgroundColor = corAlerta;
					return false;
				}
			}
			
			if (elementos[i].getAttribute("email")=="1") {
				if(!validaEmail(elementos[i].value)){
					elementos[i].style.backgroundColor = corAlerta;
					return false;
				}
			}
				
			if (elementos[i].getAttribute("data")=="1") {
				if(!validaData(elementos[i].value)){
					elementos[i].style.backgroundColor = corAlerta;
					return false;
				}
			}
			
			if (elementos[i].getAttribute("data")=="2") {
				if(!validaSoData(elementos[i].value)){
					elementos[i].style.backgroundColor = corAlerta;
					return false;
				}
			}
			
			if (elementos[i].getAttribute("hora")=="1") {
				if(!validaHora(elementos[i].value)){
					elementos[i].style.backgroundColor = corAlerta;
					return false;
				}
			}
			
		//}
	}
	
	
	
	return true;
}

function limitaAnexo(arquivo) {
	enviar = false;
	
	if (!arquivo) 
		return;
	
	while (arquivo.indexOf("\\") != -1)
		arquivo = arquivo.slice(arquivo.indexOf("\\") + 1);
	
	ext = arquivo.slice(arquivo.indexOf(".")).toLowerCase();
	
	for (var i = 0; i < arrPermitidos.length; i++) {
		if (arrPermitidos[i] == ext) {
			enviar = true; break; 
		}
	}
	if (enviar) 
		return true;
	else
		return false;
}



function validaCNPJ(CNPJ) {
	//CNPJ = document.validacao.CNPJID.value;
	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 ("/","");
		   }
		   if(CNPJ == "00000000000000"){
				return true;
		   }
		   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 +="CNPJ inválido!";
		   }
		   if (erro.length > 0){
				   alert(erro);
				   return false;
		   } 
		   return true;
}



//validar email
function validaEmail(email){
	var email = email;
	if(email.value == "" || email.value == "E-mail"){
		alert("Preencha o campo E-MAIL.")
		return false;
	}
	//Checar Espaço do email
	checks=email.indexOf(" ")
	if(checks>=1) {
		alert("Preencha o campo E-MAIL corretamente.");
		return false;
	}
	//checar email
	check1=email.indexOf("@");
	check2=email.indexOf(".");
	check3=email.length;
	if(!(check1 >= 2 && check2 >= 4 && check3 >= 7)) {
		alert("Preencha o campo email corretamente. Ex.: algum@email.com.br");
		return false;
	}
	return true;
}

function validaData(dt){
	
	var dia1=dt.substring(0,2);
	//alert(dia1);
    var mes1=dt.substring(3,5);
	//alert(mes1);
    var ano1=dt.substring(6,10);
	//alert(ano1);

    var mydate= new Date()
    var mili=mydate.getTime();
	
	var datadigitada= new Date(ano1,(mes1-1),dia1);
	datadigitada.setHours(mydate.getHours(), mydate.getMinutes(), mydate.getSeconds(), mydate.getMilliseconds());
    var miliqq=datadigitada.getTime();
    
    var diaqq=parseInt(datadigitada.getDate());
    var mesqq=parseInt(datadigitada.getMonth())+1;
	
	
	
    if((dia1!=diaqq) || (mes1!=mesqq)){
        alert("Data inválida");
        return false;
    }
	
    else if(miliqq < mili){
      alert("Data digitada menor que data atual!");
       return false;
   }
   return true;
}

function validaSoData(dt){
	
	var dia1=dt.substring(0,2);
	//alert(dia1);
    var mes1=dt.substring(3,5);
	//alert(mes1);
    var ano1=dt.substring(6,10);
	//alert(ano1);

    var mydate= new Date()
    var mili=mydate.getTime();
	
	var datadigitada= new Date(ano1,(mes1-1),dia1);
	datadigitada.setHours(mydate.getHours(), mydate.getMinutes(), mydate.getSeconds(), mydate.getMilliseconds());
    var miliqq=datadigitada.getTime();
    
    var diaqq=parseInt(datadigitada.getDate());
    var mesqq=parseInt(datadigitada.getMonth())+1;
	
	
	
    if((dia1!=diaqq) || (mes1!=mesqq)){
        alert("Data inválida");
        return false;
    }
	
   return true;
}


function validaHora(hr){
	
	var hora=hr.substring(0,2);
	var minu=hr.substring(3,5);
	

    if((hora > 23) || (minu > 59)){
        alert("Hora inválida");
        return false;
    }
   
   return true;
}

