/* ----------------------------------------------------------------------------
tips - 1o. caracter : 'L' campo com texto livre (default)
                      'T' campo com texto so de caracteres (sem numeros)
                      'E' campo de email
                      'N' campo numerico
                Obs : No caso de ser 'N' e 'E' o 2o. caracter será ignorado
       2o. caracter : 'S' Pode conter espaços (default)
                      'N' Não pode conter espaços
       3o. caracter : 'M' maior que (default)
                      'O' igualdade (do tamanho) entre um dos numeros
                      'C' igualdade entre campos

valors - podem estar separados por '|' no caso do 3o. caracter de tips ser 'O'
         no caso do 3o. caracter ser 'C' no lugar do valor vira um campo
         nos outros casos sempre vem um valor so
---------------------------------------------------------------------------- */
function ValidaCampos(Formul, tips, cmps, valors, nome)
  {
  var i,j,k;
  var cond = "";
  var msg = "";
  var campo = cmps.split(",");
  var nomes = nome.split(",");
  var tipos = tips.split(",");
  var valores = valors.split(",");
  if (campo.length != nomes.length || campo.length != tipos.length || campo.length != valores.length)
    { /*alert("Falta de parametros na função");*/ return false; }

  for (i=0; i < campo.length; i++)
    {
    // Define os default
    if (tipos[i].charAt(0) == ' ') tipos[i] = 'L'+tipos[i].charAt(1)+tipos[i].charAt(2);
    if (tipos[i].charAt(1) == ' ') tipos[i] = tipos[i].charAt(0)+'S'+tipos[i].charAt(2);
    if (tipos[i].charAt(2) == ' ') tipos[i] = tipos[i].charAt(0)+tipos[i].charAt(1)+'M';
    if (tipos[i].charAt(0) == 'E') tipos[i] = tipos[i].charAt(0)+'S'+tipos[i].charAt(2);
    if (tipos[i].charAt(0) == 'N') tipos[i] = tipos[i].charAt(0)+'N'+tipos[i].charAt(2);

    var cmp = eval(Trim(Formul)+'.'+Trim(campo[i]));
    cmp.value = Trim(cmp.value);
    msg = "";

    if (cmp.value.length > 0)
      switch(tipos[i].charAt(0))
        {
        case 'E': if (!VerificaEmail(cmp.value)) msg = "O campo " + Trim(nomes[i]) + " deve ser um e-mail valido";
                  break;
        case 'N': if (!VerificaNumerico(cmp.value)) msg = "O campo " + Trim(nomes[i]) + " deve conter somente números";
                  break;
        case 'T': if (TemNumero(cmp.value)) msg = "O campo " + Trim(nomes[i]) + " não deve conter números";
                  break;
        }

    if (msg != "") { alert(msg); cmp.focus(); return false; }

    if (tipos[i].charAt(1) != 'S' && VerificaEspacos(cmp.value) && cmp.value.length > 0)
      msg = "O campo " + Trim(nomes[i]) + " não deve conter espaços";

    if (msg != "") { alert(msg); cmp.focus(); return false; }

    switch(tipos[i].charAt(2))
      {
      case 'M': if (cmp.value.length < valores[i] || (valores[i] == 0 && cmp.value.length == 0))
                  if (valores[i] == 0) msg = "";
                  else msg = "O campo " + Trim(nomes[i]) + " deve ter mais de " + valores[i] + " caracter(es)";
                break;
      case 'C': var valaux = valores[i].split("|");
                cond = eval(Formul+"."+valaux[0]+".value");
                if (!(cmp.value == cond)) msg = "O campo " + Trim(nomes[i]) + " deve ser igual ao campo " + valaux[1];
                break;
      case 'O': var valaux = valores[i].split("|");
                var msg = "O campo " + Trim(nomes[i]) + " deve ter ";
                k = 0;
                for (j=0; j < valaux.length; j++)
                  {
                  msg += valaux[j];
                  if (cmp.value.length != valaux[j]) k++;
                  if (j+1 < valaux.length) msg += " ou ";
                  }
                msg += " caracteres";
                if (j == k) msg = msg; else msg = "";
                break;
      }

    if (msg != "") { alert(msg); cmp.focus(); return false; }
    }

  return true;
  }

var vazio = false;
// espaco, tab, enter, recuo
var whitespace = " \t\n\r";

function Trim(str)
  {
  var ret = str;
  var i;

  for(i=0; whitespace.indexOf(ret.charAt(0)) != -1 && ret.length > 0; i++)
    ret = ret.slice(1,ret.length);
  for(i=ret.length-1; whitespace.indexOf(ret.charAt(ret.length-1)) != -1 && ret.length > 0; i++)
    ret = ret.slice(0,ret.length-1);

  return ret;
  }

function VerificaVazio(s)
  {
  return ((s == null) || (s.length == 0))
  }

function VerificaEspacos(s)
  {
  var i,c,j = 0;
  if (VerificaVazio(s)) return true;
  for (i = 0; i < s.length; i++)
    {
    c = s.charAt(i);
    if (whitespace.indexOf(c) == -1) j++;
    }
  if (j == i) return false;
  else return true;
  }

function VerificaEmail (s)
  {
  if (VerificaVazio(s))
    if (VerificaEmail.arguments.length == 1) return vazio;
    else return (VerificaEmail.arguments[1] == true);
  if (VerificaEspacos(s)) return false;
  var i = 1;
  var sLength = s.length;
  while (i < sLength && s.charAt(i) != "@") i++;
  if (i >= sLength || s.charAt(i) != "@") return false;
  else i += 2;
  while (i < sLength && s.charAt(i) != ".") i++;
  if (i >= sLength - 1 || s.charAt(i) != ".") return false;
  else return true;
  }

function VerificaNumerico(s)
  {
  for (cont=0; cont < s.length; cont++)
    {
    Letra = s.charAt(cont);
    if (((Letra < "0") || (Letra > "9")) && (Letra!= ",") && (Letra!= ".")) return false;
    }
  return true;
  }

function TemNumero(s)
  {
  for (cont=0; cont < s.length; cont++)
    {
    Letra = s.charAt(cont);
    if ((Letra > "0") && (Letra < "9")) return true;
    }
  return false;
  }
  
    // Função para habilitar/desabilitar um objeto check_box
function setCheckboxes(the_form, do_check, field)
{
    var elts      = (typeof(document.forms[the_form].elements[field]) != 'undefined')
                  ? document.forms[the_form].elements[field]
                  : (typeof(document.forms[the_form].elements[field]) != 'undefined')
          ? document.forms[the_form].elements[field]
          : document.forms[the_form].elements[field];
    var elts_cnt  = (typeof(elts.length) != 'undefined')
                  ? elts.length
                  : 0;

    if (elts_cnt) {
        for (var i = 0; i < elts_cnt; i++) {
            elts[i].checked = do_check;
        } // end for
    } else {
        elts.checked        = do_check;
    } // end if... else
    

    return true;
} // end of the 'setCheckboxes()' function

function isCNPJ(cgc)
{

	var 
		char_valido = 0, 
		char_invalido = 0, 
		digito1, 
		digito2,
		soma_digito1 = 0,
		soma_digito2 = 0;
		
	cgc = cgc.replace('-','');
	cgc = cgc.replace('/','');
	cgc = cgc.replace('_','');
	cgc = cgc.replace(',','');
	cgc = cgc.replace('#','');
	cgc = cgc.replace('!','');
	cgc = cgc.replace('@','');
	cgc = cgc.replace('#','');
	cgc = cgc.replace('$','');
	cgc = cgc.replace('%','');
	cgc = cgc.replace('*','');
	
	if (cgc == '00000000000000' || cgc == '11111111111111' || cgc == '22222222222222' || cgc == '33333333333333' ||	cgc == '44444444444444' || cgc == '55555555555555' ||	cgc == '66666666666666' || cgc == '77777777777777' ||	cgc == '88888888888888' || cgc == '99999999999999')          
	{
		return false
	}					
	if (cgc.length == 14)
	{
		for (var i = 0; i <= cgc.length - 1; i++)
		{
			if (cgc.charAt(i) >= '0' && cgc.charAt(i) <= '9')
			{
				char_valido = char_valido + 1;
			}
			else
			{
				char_invalido = char_invalido + 1;
			}
		}
		if (char_valido == cgc.length)
		{
			for (i = 0; i < 4; i++)
			{
				soma_digito1 += (5 - i) * (eval(cgc.charAt(i)));
			}
			for (i = 0; i < 8; i++)
			{
				soma_digito1 += (9 - i) * (eval(cgc.charAt(i + 4)));
			}
			digito1 = 11 - (soma_digito1 % 11);
			for (i = 0; i < 5; i++)
			{
				soma_digito2 += (6 - i) * (eval(cgc.charAt(i)));
			}
			for (i = 0; i < 7; i++)
			{
				soma_digito2 += (9 - i) * (eval(cgc.charAt(i + 5)));
			}
			soma_digito2 += 2 * (eval(cgc.charAt(12)));
			digito2 = 11 - (soma_digito2 % 11);	            
			if ((soma_digito1 % 11) < 2)
			{
				digito1 = 0;
			}
			if ((soma_digito2 % 11) < 2)
			{
				digito2 = 0;
			}	            
			if (eval(cgc.charAt(12) != digito1) || eval(cgc.charAt(13) != digito2))
			{
				return false;
			}
		}
		else
		{
				return false;				
		}
	}
	else
	{
		return false;
	}
	return true;
}

function isCPF(cpf)
{
	var numeros, digitos, soma, i, resultado, digitos_iguais;
	digitos_iguais = 1;
	if (cpf.length < 11)
	    return false;
	for (i = 0; i < cpf.length - 1; i++)
	    if (cpf.charAt(i) != cpf.charAt(i + 1))
	          {
	          digitos_iguais = 0;
	          break;
	          }
	if (!digitos_iguais){
	    numeros = cpf.substring(0,9);
	    digitos = cpf.substring(9);
	    soma = 0;
	    for (i = 10; i > 1; i--)
	          soma += numeros.charAt(10 - i) * i;
	    resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
	    if (resultado != digitos.charAt(0))
	          return false;
	    numeros = cpf.substring(0,10);
	    soma = 0;
	    for (i = 11; i > 1; i--)
	          soma += numeros.charAt(11 - i) * i;
	    resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
	    if (resultado != digitos.charAt(1))
	          return false;
	    return true;
	} else {
	    return false;
	}
}


// Verifica data
function isData(data, campo) {
	if(data != "") {
		if(data.length == 8) {
			var ano = "20" + data.substring(6,8);
		} else {
			var ano = data.substring(6,10);
		}
		var mes = data.substring(3,5);
		var dia = data.substring(0,2);
	    if((mes==4 || mes==6 || mes==9 || mes==11) && dia > 30){
			alert("Dia incorreto !!! O mês especificado contém no máximo 30 dias.");
			document.getElementById(campo).focus();
		return false;
		} else{
			if(ano%4!=0 && mes==2 && dia>28){
				alert("Data incorreta!! O mês especificado contém no máximo 28 dias.");
				document.getElementById(campo).focus();
				return false;
			} else{
				if(ano%4==0 && mes==2 && dia>29){
					alert("Data incorreta!! O mês especificado contém no máximo 29 dias.");
					document.getElementById(campo).focus();
					return false;
				} else{ 
					if(mes > 12){
						alert("Data incorreta!! Mês não existe.");
						document.getElementById(campo).focus();
						return false;
					} else{ 
						if(dia > 31){
							alert("Data incorreta!! Dia não existe.");
							document.getElementById(campo).focus();
							return false;
						} else{ 
							document.getElementById(campo).value = valorFinal = dia + "/" + mes + "/" + ano;
							return true;
						}
					}
				}
			}
		}
	}
}


/*
   Descrição: Data2 maior que Data1
*/
function F_MaiorData(data1, data2) {
	if ( parseInt( data2.split( "/" )[2].toString() + data2.split( "/" )[1].toString() + data2.split( "/" )[0].toString() ) > parseInt( data1.split( "/" )[2].toString() + data1.split( "/" )[1].toString() + data1.split( "/" )[0].toString() ) ){  
		return true;
	}else{  
		return false;
	}
}

	
// Verifica data
function forcaCasaDecimal(valor, campo) {
	if(valor != ""){
		var xfound = false;
		for (i=0; i < valor.length; i++){
	      var Caractere = valor.charAt(i);
	      if(Caractere == ","){
	      	xfound = true;
	      } 
		}
		
		if(xfound == false){
	      	document.getElementById(campo).value = valor + ',00';
	   	}
	}
}