// Biblioteca de validação do formulários e mascaras de campos
// 28/09/2004 por: Elberte Antonio dos Santos Agostinho
// Engenharia de Web
// www.engenhariadeweb.com.br
//
// 	para ativar a validação incluir a biblioteca no html
// 		<script language="Javascript" src="form.js"></script>
//
// 	no onsubmit do formulário colocar a função de validação
// 		<form onsubmit="checkForm(this, "Cor da borda sem erro", "Cor da borda com erro")">
//
// 	como declarar tipo de validação nos campos do formulário
// 		<input type="tipo" alt="tipo de validação" lang="Mensagem de erro">
//
//	tipos de validação:
//		empty 		= checa se campo está vazio
//		isnum		= checa se campo é numérico
//		isdate		= checa se campo é uma data válida
//		isdate2		= checa se campo é uma data válida (mm/aaaa)
//		selected	= checa se campo select foi selecionado algum item
//		checked		= checa se campo radio foi selecionado algum item
//		email		= checa se email é válido
//		cpf			= checa se CPF é válido
//		cnpj		= checa se CNPJ é válido
//		cpf/cnpj	= checa se CPF ou CNPJ válido
//		credicard	= checa se cartão de credito é valido
//		len=x		= checa se o campo possui no minimo a quantidade de caracteres x
//		compara=x=y	= checa se o valor do campo é igual ao do campo x e o comprimento é maior ou igual a y


// Faltando montar
// Validação de CheckBox
// Validação de Radio Box

	
function checkForm(form, OKColor, ErrorColor){
	// Mensagem de erro inicializada
	var ErrorMSG = '';

	for(i=0; i<form.elements.length; i++){
		// Checa campos vazios
		element 	= form.elements[i];
		if(!element.alt)continue;
		//alert(element.name);
		// Volta as cores ao normal
		setFieldColor(element, OKColor);

		//checa campos iguais

		if(element.alt.indexOf("compara") != -1){
			field = element.alt.split("=");
			if(element.value != form.elements[field[1]].value || element.value == "" || element.value.length < field[2]){
				setFieldColor(element, ErrorColor);
				ErrorMSG += element.lang + "\r\n";
			}
		}

		//checa comprimento minimo
		if(element.alt.indexOf("len") != -1){
			len = element.alt.split("=");
			if(element.value.length < len[1]){
				setFieldColor(element, ErrorColor);
				ErrorMSG += element.lang + "\r\n";
			}
		}

		//checa se o campo é fone
		if(element.alt == "fone"){
			if(element.value.length != 13){
				setFieldColor(element, ErrorColor);
				ErrorMSG += element.lang + "\r\n";
			}
		}
		
		//checa se o campo é cep
		if(element.alt == "cep"){
			if(element.value.length != 9){
				setFieldColor(element, ErrorColor);
				ErrorMSG += element.lang + "\r\n";
			}
		}


		//checa se o campo é cep
		if(element.alt == "socio"){
			if(element.value.length != 5){
				setFieldColor(element, ErrorColor);
				ErrorMSG += element.lang + "\r\n";
			}
		}

		if(element.alt == "cei"){
			if(element.value.length != 15){
				setFieldColor(element, ErrorColor);
				ErrorMSG += element.lang + "\r\n";
			}
		}
		//checa se o campo é vazio
		if(element.alt == "empty"){
			if(element.value == ''){
				setFieldColor(element, ErrorColor);
				ErrorMSG += element.lang + "\r\n";
			}
		}

		// Checa se campo é numero
		if(element.alt == "isnum"){
			if(isNUMB(element.value) != 1){
				setFieldColor(element, ErrorColor);
				ErrorMSG += element.lang + "\r\n";
			}
		}

		// Checa se campo é data
		if(element.alt == "isdate"){
			if(checkDate(element.value)){
				setFieldColor(element, ErrorColor);
				ErrorMSG += element.lang + "\r\n";
			}
		}

		// Checa se campo é data (mm/aaaa)
		if(element.alt == "isdate2"){
			if(checkDate2(element.value)){
				setFieldColor(element, ErrorColor);
				ErrorMSG += element.lang + "\r\n";
			}
		}

		// Checa campos Select
		if(element.alt == "selected"){
			if(element.options.selectedIndex == 0){
				setFieldColor(element, ErrorColor);
				ErrorMSG += element.lang + "\r\n";
			}
		}

		// Checa campos Radio
		if(element.alt == "checked"){
			if(element.options.selectedIndex == 0){
				setFieldColor(element, ErrorColor);
				ErrorMSG += element.lang + "\r\n";
			}
		}

		// Checa campos Email
		if(element.alt == "email"){
			if(checkEmail(element)){
				setFieldColor(element, ErrorColor);
				ErrorMSG += element.lang + "\r\n";
			}
		}

		// Checa CPF
		if(element.alt == "cpf"){
			if(checkCPF(element)){
				setFieldColor(element, ErrorColor);
				ErrorMSG += element.lang + "\r\n";
			}
		}

		// Checa CNPJ
		if(element.alt == "cnpj"){
			if(checkCNPJ(element)){
				setFieldColor(element, ErrorColor);
				ErrorMSG += element.lang + "\r\n";
			}
		}

		// Checa CPF ou CNPJ
		if(element.alt == "cpf/cnpj"){
			if(checkCNPJ(element) && checkCPF(element)){
				setFieldColor(element, ErrorColor);
				ErrorMSG += element.lang + "\r\n";
			}
		}

		// Checa cartão de credito
		if(element.alt == "credicard"){
			if(valCC(element)){
				setFieldColor(element, ErrorColor);
				ErrorMSG += element.lang + "\r\n";
			}
  }
	}

	if(ErrorMSG == ''){
		return true;
	} else {
		alert(ErrorMSG);
		return false;
	}
}

function setFieldColor(element, color){
	if(document.layers){
		element.borderColor = color;
	} else {
		element.style.borderColor = color;
	}
}

// Validações de Cartão de Credito
function valCC(cc){
	if(isVisa(cc.value)){
		return false;
	} else if(isDinersClub(cc.value)) {
		return false;
	} else if(isMasterCard(cc.value)){
		return false;
	} else if(isAmericanExpress(cc.value)){
		return false;
	}
	return true;
}

function isCreditCard(st) {
  if (st.length > 19)
    return (false);

  sum = 0; mul = 1; l = st.length;
  for (i = 0; i < l; i++) {
    digit = st.substring(l-i-1,l-i);
    tproduct = parseInt(digit ,10)*mul;
    if (tproduct >= 10)
      sum += (tproduct % 10) + 1;
    else
      sum += tproduct;
    if (mul == 1)
      mul++;
    else
      mul--;
  }

  if ((sum % 10) == 0)
    return (true);
  else
    return (false);
}

function isVisa(cc) {
  if (((cc.length == 16) || (cc.length == 13)) &&
      (cc.substring(0,1) == 4))
    return isCreditCard(cc);
  return false;
}

function isMasterCard(cc) {
  firstdig = cc.substring(0,1);
  seconddig = cc.substring(1,2);
  if ((cc.length == 16) && (firstdig == 5) &&
      ((seconddig >= 1) && (seconddig <= 5)))
    return isCreditCard(cc);
  return false;
}

function isAmericanExpress(cc) {
  firstdig = cc.substring(0,1);
  seconddig = cc.substring(1,2);
  if ((cc.length == 15) && (firstdig == 3) &&
      ((seconddig == 4) || (seconddig == 7)))
    return isCreditCard(cc);
  return false;
}

function isDinersClub(cc) {
  firstdig = cc.substring(0,1);
  seconddig = cc.substring(1,2);
  if ((cc.length == 14) && (firstdig == 3) &&
      ((seconddig == 0) || (seconddig == 6) || (seconddig == 8)))
    return isCreditCard(cc);
  return false;
}

//Validação de data
function checkDate(d) {
	var reData = /(\d{2})\/(\d{2})\/(\d{4})/;
	var datePart = d.match(reData); // datePartconterá [0]=dia, [1]=mes e [2]=ano

	if(datePart == null){
		return true;
	}

	// passando as partes da data para variáveis mais "amigáveis":
	var dd = datePart[1], mm = datePart[2], yy = datePart[3];
	//alert(dd); // 1o. grupo //alert(mm); // 2o. grupo //alert(yy); // 3o. grupo

	//condições de datas inválidas:
	// dia menor que 1 ou maior que 31
	if (dd<1) { return true;}

	// mes fora dos limites
	if (mm<1 || mm>12) { return true;}

	// meses 4,6,9,11 nao possuem mais de 30 dias
	if ((dd > 30) && (mm == 4)) {return true;}
	if ((dd > 30) && (mm == 6)) {return true;}
	if ((dd > 30) && (mm == 9)) {return true;}
	if ((dd > 30) && (mm == 11)) {return true;}

	if ((dd > 31) && (mm == 1)) {return true;}
	if ((dd > 31) && (mm == 3)) {return true;}
	if ((dd > 31) && (mm == 5)) {return true;}
	if ((dd > 31) && (mm == 7)) {return true;}
	if ((dd > 31) && (mm == 8)) {return true;}
	if ((dd > 31) && (mm == 10)) {return true;}
	if ((dd > 31) && (mm == 12)) {return true;}

	// fevereiro não tem mais de 28 dias, exceto em ano bissexto
	if ((dd > 29) && (mm == 2) && (anobissexto(yy) )) {return true;}
	if ((dd > 28) && (mm == 2) && (!anobissexto(yy) )) {return true;}

// se passou pelos testes acima, então a data é considerada válida.
return false;
}

//Validação de data (mm/aaaa)
function checkDate2(d) {
	mm = d.substring(0,2);
	aaaa = d.substring(3);

	// mes fora dos limites
	if (mm<1 || mm>12) { return true;}

	// mes fora dos limites
	if (aaaa<1900 || aaaa>2100) { return true;}

// se passou pelos testes acima, então a data é considerada válida.
return false;
}

// retorna verdadeiro se for ano bissexto ou falso se não for bissexto
function anobissexto(yy){
	return (yy % 4 == 0 &&(yy % 100 != 0 || yy % 400 == 0));
}

// Checa se campo é email
function checkEmail(element){
  var tmpStr = element.value.replace("'","");
  element.value = tmpStr;

	var emailPat=/^(.+)@(.+)$/
	var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
	var validChars="\[^\\s" + specialChars + "\]"
	var quotedUser="(\"[^\"]*\")"
	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
	var atom=validChars + '+'
	var word="(" + atom + "|" + quotedUser + ")"
	var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")
	var matchArray = tmpStr.match(emailPat)
	if (matchArray == null){
		return true
	}

	var user = matchArray[1]
	var domain = matchArray[2]
	if (user.match(userPat) == null){
		return true
	}

	var IPArray = domain.match(ipDomainPat)
	if (IPArray != null) {
		for (var i=1;i<=4;i++){
			if (IPArray[i]>255){
				return true
			}
		}
		return false
	}

	var domainArray=domain.match(domainPat)
	if (domainArray==null){
    showWarning(errorMessage, tmpEmail);
    tmpEmail.focus();
		return true
	}

	var atomPat = new RegExp(atom,"g")
	var domArr = domain.match(atomPat)
	var len = domArr.length
	if (domArr[domArr.length-1].length<2 || domArr[domArr.length-1].length>3){
		return true
	}

	if (len<2) {
		return true
	}
	return false;
}

// Checa CPF
function checkCPF(element){
  var numcpf = element.value.replace('.','').replace('.','').replace('-','');
  if(numcpf=="1234567890"){return true;};
  x = 0;
  soma = 0;
  dig1 = 0;
  dig2 = 0;
  texto = "";
  numcpf1 = "";
  len = numcpf.length;
  x = len -1;
  for (var i=0; i <= len - 3; i++) {
    y = numcpf.substring(i,i+1);
    soma = soma + ( y * x);
    x = x - 1;
    texto = texto + y;
  }
  dig1 = 11 - (soma % 11);
  if (dig1 == 10) dig1=0 ;
  if (dig1 == 11) dig1=0 ;
    numcpf1 = numcpf.substring(0,len - 2) + dig1 ;
    x = 11; soma=0;
  for (var i=0; i <= len - 2; i++) {
    soma = soma + (numcpf1.substring(i,i+1) * x);
    x = x - 1;
  }
  dig2= 11 - (soma % 11);
  if (dig2 == 10) dig2=0;
  if (dig2 == 11) dig2=0;
  if ((dig1 + "" + dig2) == numcpf.substring(len,len-2)) {
    if(numcpf % 11111111111 == 0){
      return true;
    }
    return false;
  }
  return true;
}

// Checa CNPJ
function checkCNPJ(element){
  var CNPJ = element.value.replace('.','').replace('.','').replace('-','').replace('/','');;

  if(CNPJ=="1234567890"){return true;};
  CNPJ = LIMP(CNPJ);
  if(isNUMB(CNPJ) != 1){
    return true;
  }
  else{
    if(CNPJ == 0){
      return true;
    }
    else{
      g = CNPJ.length - 2;
      if (RealTestaCNPJ(CNPJ,g) == 1){
        g = CNPJ.length - 1;
        if(RealTestaCNPJ(CNPJ,g) == 1){
          return false;
        }
        else{
          return false;
        }
      }
      else{
        return true;
      }
    }
  }
}

function RealTestaCNPJ(CNPJ,g){
  var VerCNPJ=0;
  var ind=2;
  var tam;
  for(f = g; f > 0; f--){
    VerCNPJ+=parseInt(CNPJ.charAt(f-1))*ind;
    if(ind>8){
      ind=2;
    }
    else{
      ind++;
    }
  }
  VerCNPJ%=11;
  if(VerCNPJ==0 || VerCNPJ==1){
    VerCNPJ=0;
  }
  else{
    VerCNPJ=11-VerCNPJ;
  }
  if(VerCNPJ!=parseInt(CNPJ.charAt(g))){
    return false;
  }
  else{
    return true;
  }
}

function LIMP(c){
  while((cx=c.indexOf("-"))!=-1){
    c = c.substring(0,cx)+c.substring(cx+1);
  }
  while((cx=c.indexOf("/"))!=-1){
    c = c.substring(0,cx)+c.substring(cx+1);
  }
  while((cx=c.indexOf(","))!=-1){
    c = c.substring(0,cx)+c.substring(cx+1);
  }
  while((cx=c.indexOf("."))!=-1){
    c = c.substring(0,cx)+c.substring(cx+1);
  }
  while((cx=c.indexOf("("))!=-1){
    c = c.substring(0,cx)+c.substring(cx+1);
  }
  while((cx=c.indexOf(")"))!=-1){
    c = c.substring(0,cx)+c.substring(cx+1);
  }
  while((cx=c.indexOf(" "))!=-1){
    c = c.substring(0,cx)+c.substring(cx+1);
  }
  return(c);
}

function isNUMB(c){
  if((cx=c.indexOf(","))!=-1){
    c = c.substring(0,cx)+"."+c.substring(cx+1);
  }
  if((parseFloat(c) / c != 1)){
    if(parseFloat(c) * c == 0){
      return(1);
    }
    else{
      return(0);
    }
  }
  else{
    return(1);
  }
}

function linkConfirm(element){
	if(confirm(element.title)){
		return true;
	}
	return false;
}

function linkPopup(element, w, h){
	window.open(element.href, '', 'width=' + w + ',height=' + h +',top=' + (((screen.height - h) / 2) - 30) + ',left=' + ((screen.width - w) / 2));
	return false;
}


// Checa Campos Radio
function checkRadio(whatForm, whatRadio, errorMessage){
  var tmpRadio = whatForm.elements[whatRadio];
  var ok = 0;

  for(var i = 0; i < tmpRadio.length; i++){
    if(tmpRadio[i].checked){
      ok = 1;
    }
  }
  if(!ok){
    showWarning(errorMessage);
    tmpRadio[0].focus();
    return false;
  }
  return true;
}

// Checa igualdade
function checkFields(whatForm, whatInput, whatInputCopy, errorMessage){
  var tmpInput = whatForm.elements[whatInput];
  var tmpInputCopy = whatForm.elements[whatInputCopy];

		// || tmpInput.value != ''
  if(tmpInput.value != tmpInputCopy.value){
    showWarning(errorMessage, tmpInputCopy);
    tmpInputCopy.focus();
    return false;
  }
  else{
    return true;
  }
}

// Checa comprimento minimo
function checkMinLength(whatForm, whatInput, iMinLength, errorMessage){
  var tmpInput = whatForm.elements[whatInput];

  if(tmpInput.value.length < iMinLength){
    showWarning(errorMessage, tmpInput);
    tmpInput.focus();
    return false;
  }
  else{
    return true;
  }
}

// Checa Comprimento Máximo
function checkMaxLength(whatForm, whatInput, iMaxLength, errorMessage){
  var tmpInput = whatForm.elements[whatInput];

  if(tmpInput.value.length > iMaxLength){
    showWarning(errorMessage, tmpInput);
    tmpInput.focus();
    return false;
  }
  else{
    return true;
  }
}

// Funções de Formatação

//Função para que o campo aceite somente números inteiros
function maskInteger(evt) {
	evt = (evt) ? evt : window.event
	var charCode = (evt.which) ? evt.which : evt.keyCode
	if (charCode > 31 && (charCode < 48 || charCode > 57)) {
		status = "Este campo aceita somente número."
		return false
	}
	status = ""
	return true
}

//Função para que o campo aceite somente números inteiros e vírgula
function maskNum(){
	if ((event.keyCode < 48) || (event.keyCode > 57)) {
		if ((event.keyCode != 44) && (event.keyCode != 45)) {
		return false;
		}
	}
return true;
}

// Função que faz uma máscara para telefone
function maskFone(campo) {
	var valor
	valor = campo.value.replace('(','').replace('-','').replace(')','');
	if(valor.length == 1){
		campo.value = "(" + valor;
	}else if(valor.length > 6){
		campo.value = "(" + valor.substr(0,2) + ")" + valor.substr(2,4) + "-" + valor.substr(6,4) ;
	}else if(valor.length == 6){
		campo.value = "(" + valor.substr(0,2) + ")" + valor.substr(2,4) ;
	}else if(valor.length > 2 ){
		campo.value = "(" + valor.substr(0,2) + ")" + valor.substr(2,valor.length-2);
	}
}
function maskFone7(campo) {
	var valor

	valor = campo.value.replace('(','').replace('-','').replace(')','');
	if(valor.length == 9){
		campo.value = "(" + valor.substr(0,2) + ")" + valor.substr(2,3) + "-" + valor.substr(5,valor.length-5) ;
	}
}


//Função que faz uma máscara para data
function maskDate(campo) {
	var valor
	valor = campo.value.replace('/','').replace('/','');
	if(valor.length > 4){
		campo.value = valor.substr(0,2) + "/" + valor.substr(2,2) + "/" + valor.substr(4,4) ;
	}else if(valor.length > 2 ){
		campo.value = valor.substr(0,2) + "/" + valor.substr(2,2);
	}
}


//Função que faz uma máscara para cep
function maskCEP(campo) {
	var valor
	valor = campo.value.replace('-','');
	 if(valor.length >= 5){
		campo.value = valor.substr(0,5) + "-" + valor.substr(5,3);
	}else{
		campo.value = valor;
	}
}

//Função de Validação dos Campos de períodos de inscrições

// dateCompare
// verifica qual data eh maior
// recebe:
//	- data inicial
//	- data final
// retorna:
//	- maior ou menor (segunda data em relacao a primeira)
function dateCompare(vDtInicial,vDtFinal) {

	if (vDtInicial.length > 0) {
		if (vDtInicial.charAt(2) != '/' || vDtInicial.charAt(5) != '/') {
			return false;
		}
		var vDiaInicial = vDtInicial.substring(0,2);
		var vMesInicial = vDtInicial.substring(3,5);
		var vAnoInicial = vDtInicial.substring(6,10);
	}
	if (vDtFinal.length > 0) {
		if (vDtFinal.charAt(2) != '/' || vDtFinal.charAt(5) != '/') {
			return false;
		}
		vDiaFinal = vDtFinal.substring(0,2);
		vMesFinal = vDtFinal.substring(3,5);
		vAnoFinal = vDtFinal.substring(6,10);
		if (vAnoFinal < vAnoInicial) {
			return("menor");
		}
		else if (vAnoFinal == vAnoInicial) {
			if (vMesFinal < vMesInicial) {
				return("menor");
			}
			else if (vMesFinal == vMesInicial && vDiaFinal < vDiaInicial) {
				return("menor");
			}
		}
	}
	return("maior");
}

