// Função replace
function replaceThatWorks(strValue,strSearch,strReplace) {
	var strResult = new String(strValue);
	var strBefore, strAfter;
	while(strResult.indexOf(strSearch)!=-1) {
		strBefore = strResult.substring(0,strResult.indexOf(strSearch));
		strAfter = strResult.substring(strResult.indexOf(strSearch)+1,strResult.length);
		strResult = strBefore + strReplace + strAfter
	}
	return(strResult);
}



function CheckCNPJCPF(cgc)
{
  var cgc = String(cgc);
	cgc = replaceThatWorks(cgc,'.','');
	cgc = replaceThatWorks(cgc,'-','');
	cgc = replaceThatWorks(cgc,'/','');
  
  
  if (cgc.length==11) {
    if (cgc == "00000000000" || cgc == "11111111111" ||
      cgc == "22222222222" ||	cgc == "33333333333" || cgc == "44444444444" ||
		  cgc == "55555555555" || cgc == "66666666666" || cgc == "77777777777" ||
		  cgc == "88888888888" || cgc == "99999999999")
		  return false;

	  soma = 0;

	  for (i=0; i < 9; i ++)
		  soma += parseInt(cgc.charAt(i)) * (10 - i);

	  resto = 11 - (soma % 11);

	  if (resto == 10 || resto == 11)
	  	resto = 0;

	  if (resto != parseInt(cgc.charAt(9)))
		  return false;

	  soma = 0;

	  for (i = 0; i < 10; i ++)
	    soma += parseInt(cgc.charAt(i)) * (11 - i);

	  resto = 11 - (soma % 11);

	  if (resto == 10 || resto == 11)
		  resto = 0;

	  if (resto==parseInt(cgc.charAt(10)))
		  return true;
    else
      return false;
  }
  else
  {
     if (cgc.length==14 && parseInt(cgc)>0) {
      
      var1 = 0;
      i = 0;
      var4 = 0;
      var5 = 0;
      var2 = 5;

      for (i=0; i < 12; i ++)
      {
        var1 += parseInt(cgc.charAt(i)) * var2;

        if (var2>2)
          var2=var2-1;
        else
          var2=9;
      }

      var1=(var1 % 11);

      if (var1 > 1)
        var4 =11 - var1;
      else
        var4=0;

      var1 = 0;
      i = 0;
      var2 = 6;

      for (i=0; i < 13; i ++) {
        var1 += parseInt(cgc.charAt(i)) * var2;
        if (var2>2)
          var2=var2-1;
        else
          var2=9;
      }

      var1 = (var1 % 11);

      if (var1>1)
        var5=11-var1;
      else
        var5=0;

      if (var4==parseInt(cgc.charAt(12)) && var5==parseInt(cgc.charAt(13)))
        return true;
      else
        return false;

    }
    else
     return false;
  }
}


function ValidaEmail (strField, fNull) 
{
  if (strField == "" && fNull == true)
		return (true);
		
  var RegExp = /^[a-zA-Z0-9._-]+@([a-zA-Z0-9.-]+\.)+[a-zA-Z0-9.-]{2,4}$/;
  
  return RegExp.test (strField);
}

function ValidaSoNumero (thisField)
{

	var checkOK = "0123456789";
	var checkStr = thisField.value;
	var allValid = true;
	var decPoints = 0;
	var allNum = "";
	for (i = 0;  i < checkStr.length;  i++)
	{
		ch = checkStr.charAt(i);
		for (j = 0;  j < checkOK.length;  j++)
		if (ch == checkOK.charAt(j))
	        break;
		if (j == checkOK.length)
		{
			allValid = false;
			break;
		}

		allNum += ch;
	}

	if (!allValid)
	{
		alert ('Digite apenas números!');
		thisField.focus ();
		return (false);
	}

	return (true);
}

function ValidaNumero (strField)
{

	var checkOK = "0123456789-";
	var checkStr = strField;
	var allValid = true;
	var decPoints = 0;
	var allNum = "";
	for (i = 0;  i < checkStr.length;  i++)
	{
		ch = checkStr.charAt(i);
		for (j = 0;  j < checkOK.length;  j++)
		if (ch == checkOK.charAt(j))
	        break;
		if (j == checkOK.length)
		{
			allValid = false;
			break;
		}

		allNum += ch;
	}

	if (!allValid)
	{
		return (false);
	}

	return (true);
}


function ValidaCaracter (thisField)
{
	var checkOK = " ,.()+=:;abcdefghijklmnopqrstuvxywzABCDEFGHIJKLMNOPQRSTUVXYWZ0123456789-?!@%";
	var checkStr = thisField.value;
	var allValid = true;
	var decPoints = 0;
	var allNum = "";
	for (i = 0;  i < checkStr.length;  i++)
	{
		ch = checkStr.charAt(i);
		for (j = 0;  j < checkOK.length;  j++)
		if (ch == checkOK.charAt(j))
	        break;
		if (j == checkOK.length)
		{
			allValid = false;
			break;
		}
		
		allNum += ch;
	}
	
	if (!allValid)
	{
		alert ('Você não inseriu caracteres válidos - Não use acentos ou caracteres especiais.');
		thisField.focus()
		return (false);
	}
	
	return (true);
}

function ValidaInt (thisField, NmInicial, NmFinal, fMsg)
{
	// Versão nova de ValidaInt com mensagem de erro e passando o campo, não mais o valor
	var strVal = thisField.value;
	var prsVal = parseInt(thisField.value, 10);

	// Se for um número
	if (!isNaN (prsVal))
	{
		if (ValidaNumero (strVal) == true)
		{
			// Se NmInicial e NmFinal não foram informados
			if (!NmInicial && !NmFinal)
			{
				// É um int válido
				return (true);
			}
			else
			{
				if (NmInicial && !NmFinal)
				{
					if (!(prsVal >= NmInicial))
					{
						// Não é um Int válido
						if (fMsg)
						{
							alert ('Digite um número maior que ' + NmInicial + '.');
							thisField.select();
							thisField.focus();
						}
						return (false);
					}
					else
						return (true);
				}
				else
				{
					// Se não estiver dentro dos limites passados
					if (!(prsVal >= NmInicial && prsVal <= NmFinal))
					{
						// Não é um Int válido
						if (fMsg)
						{
							alert ('Digite um número entre ' + NmInicial + ' e ' + 
								NmFinal + '.');
							thisField.select();
							thisField.focus();
						}
						return (false);
					}
					else
						return (true);
				}
			}
		}
		else
		{
			if (fMsg)
			{
				alert ('Digite apenas números inteiros.');
				thisField.focus();
				thisField.select();
			}
		}
	}
	else
	{
		if (fMsg)
		{
			alert ('Digite um inteiro válido.');
			thisField.select();
			thisField.focus();
		}
		return (false);
	}	
}

function ValidaFloat (thisField, NmInicial, NmFinal, fMsg)
{
	// Versão nova de ValidaFloat com mensagem de erro e passando o campo, não mais o valor
	var strVal;
	var prsVal;
	
	if (strVal == "")
	{
		
		thisField.focus();
		alert ('O campo não pode ser vazio');
		return (false);
		
	}
	else
	{
	
		strVal = PreparaNumero(thisField.value);
		prsVal = parseFloat(strVal);
//-----------------------------------

// Se NmInicial e NmFinal não foram informados
			if (!NmInicial && !NmFinal)
			{
				// É um int válido
				return (true);
			}
			else
			{
				if (NmInicial && !NmFinal)
				{
					if (!(prsVal >= NmInicial))
					{
						// Não é um Int válido
						if (fMsg)
						{
							alert ('Digite um número maior que ' + NmInicial + '.');
							thisField.select();
							thisField.focus();
						}
						return (false);
					}
					else
						return (true);
				}
				else
				{
					// Se não estiver dentro dos limites passados
					if (!(prsVal >= NmInicial && prsVal <= NmFinal))
					{
						// Não é um Int válido
						if (fMsg)
						{
							alert ('Digite um número entre ' + NmInicial + ' e ' + 
								NmFinal + '.');
							thisField.select();
							thisField.focus();
						}
						return (false);
					}
					else
						return (true);
				}
			}

//-----------------------------------		
		prsVal = String(prsVal);
		prsVal = FormatNumber(prsVal, 2);
		
		if (strVal==prsVal)
		{
			return(true);
		}
		else
		{
			// Não é um Int válido
			if (fMsg)
			{
				alert ('Digite um número fracional correto.');
				thisField.select();
				thisField.focus();
			}
			return(false);
		}
	}	
}

function ValidaFloatTMP (thisField, fSohPositivo)
{
	var regEx = ",";
	var thisFieldValue = thisField.value;
	
	thisFieldValue = thisFieldValue.replace (regEx, ".");
	
	// Se é número
	if (thisFieldValue != "" && !isNaN (thisFieldValue))
	{
		if (fSohPositivo)
		{
			if (thisFieldValue < 0)
			{
				alert ("Digite apenas números positivos.");
				thisField.focus();
				thisField.select();
				return false;
			}
		}
		
		thisField.value = thisFieldValue;
		return true;
	}
	else
	{
		alert ("Digite um número fracional correto.");
		thisField.focus();
		thisField.select();
		return false;
	}
}

function ValidaNumInt (thisField)
{
	if (ValidaNumero (thisField.value) && ValidaInt (thisField, 0, 32000, false))
		return (true);
	else
		return (false);
}

function ValidaNull (thisField, strFriendlyName, fMsg)
{
	if (fMsg != false)
		fMsg = true;
	
	if (thisField.value == "")
	{
		if (fMsg == true)
		{
			thisField.focus();
			alert ('O campo ' + strFriendlyName + ' não pode ser vazio');
		}
		return (false);
	}
	else
		return (true);
}

function ValidaDia (thisField, fNull)
{
	if (fNull && thisField.value == "")
		return (true);
	else
	{
		if (ValidaNumero (thisField.value) && ValidaInt (thisField, 1, 31, false))
			return (true);
		else
			return (false);
	}
}

function ValidaMes (thisField, fNull)
{
	if (fNull && thisField.value == "")
		return (true);
	else
	{
		if (ValidaNumero (thisField.value) && ValidaInt (thisField, 1, 12, false))
			return (true);
		else
			return (false);
	}
}

function ValidaAno (thisField, fNull)
{
	if (fNull && thisField.value == "")
		return (true);
	else
	{
		if (ValidaNumero (thisField.value) && ValidaInt (thisField, 1900, 9999, false) && thisField.value.length == 4)
			return (true);
		else
			return (false);
	}
}

function ValidaData (thisField, strTipoData, fNull)
{
	var thisFieldValue = thisField.value;

	switch (strTipoData)
	{
		case "dia":
			// Se o valor estiver OK (Inteiro válido)
			if (!ValidaDia (thisField, fNull))
			{
				alert ('Preencha um dia válido (de 1 a 31)');
				thisField.focus();
				thisField.select();
				return (false);
			}
			break;
		
		case "mes":
			if (!ValidaMes (thisField, fNull))
			{
				alert ('Preencha um mês válido (de 1 a 12)');
				thisField.focus();
				thisField.select();
				return (false);
			}
			break;
		
		case "ano":
			// Se o valor estiver OK (data válida)
			if (!ValidaAno (thisField, fNull))
			{
				alert ('Preencha com o ano maior que 1900');
				thisField.focus();
				thisField.select();
				return (false);
			}
			break;
	}
	
	return (true);
}

function ValidaFullDate (varDia, varMes, varAno, var1, var2) 
{
	
	data = varDia.value + '/' + varMes.value + '/' + varAno.value;
	if(data.length < 6 || data.length > 10)
	{ 
		alert ('Preencha a data corretamente, nenhum campo pode ficar em branco (dd/mm/aaaa)');
		varDia.focus();
		return (false);
	} 
	
	pos0 = data.indexOf("/");
	if(pos0 == -1)
	{
		alert ('Preencha a data corretamente (dd/mm/aaaa)');
		varDia.focus();
		return (false);
	}
	
	pos1 = data.indexOf("/", pos0 + 1);
	if(pos1 == -1)
	{
		alert ('Preencha a data corretamente (dd/mm/aaaa)');
		varDia.focus();
		return (false);
	}
	
	if(data.indexOf("/", pos1 + 1) != -1)
	{
		alert ('Preencha a data corretamente (dd/mm/aaaa)');
		varDia.focus();
		return (false);
	}
	
	dia = data.substring(0,pos0);
	dia = (dia.charAt(0) == "0")?dia.charAt(dia.length - 1):dia
	mes = data.substring(pos0 + 1, pos1);
	mes = (mes.charAt(0) == "0")?mes.charAt(mes.length - 1):mes
	ano = data.substring(pos1 + 1, data.length);
	ano = (ano.charAt(0) == "0")?ano.charAt(ano.length - 1):ano
	
	if(varDia.value=='')
	{
		alert ('Dia em Branco, nenhum campo pode ficar em branco, favor preencha a data corretamente (DD/mm/aaaa)');
		varDia.focus();
		return (false);
	}
	if(varMes.value=='')
	{
		alert ('Mês em Branco, nenhum campo pode ficar em branco, favor preencha a data corretamente (dd/MM/aaaa)');
		varMes.focus();
		return (false);
	}
	if(varAno.value=='')
	{
		alert ('Ano em Branco, nenhum campo pode ficar em branco, favor preencha a data corretamente (dd/mm/AAAA)');
		varAno.focus();
		return (false);
	}
	
	if(parseInt(ano) >= 0 && parseInt(ano) < 1900)
	{
		alert ('Ano incorreto, favor preencha a data corretamente (dd/mm/AAAA)');
		varAno.select();
		varAno.focus();
		return (false);
	}
	
	if(parseInt(ano) > 2100 || parseInt(ano) < 0)
	{
		alert ('Ano incorreto, favor preencha a data corretamente (dd/mm/AAAA)');
		varAno.select();
		varAno.focus();
		return (false);
	}
	
	if(parseInt(mes) > 12 || parseInt(mes) < 1)
	{
		alert ('Mês incorreto, favor preencha a data corretamente (dd/MM/aaaa)');
		varMes.select();
		varMes.focus();
		return (false);
	}
	
	numero = ((parseInt(ano) - 1884) / 4)
	if(numero == Math.floor(numero)) 
	{
		dias = "312931303130313130313031";
	}
	else
	{
		dias = "312831303130313130313031";
	}
	
	diamax = parseInt(dias.substring((mes-1)*2,((mes-1)*2)+2));
	if(parseInt(dia) < 1 || parseInt(dia) > diamax)
	{
		alert ('Dia incorreto, favor preencha a data corretamente (DD/mm/aaaa)');
		varDia.select();
		varDia.focus();
		return (false);
	} 
	
	return (true);
}

function msgLimitaTextArea_onKeyDown (objField, iLimite)
{
	var strFieldValue = objField.value;

	if (strFieldValue.length >= iLimite)
	{
		alert ("O limite desta caixa de texto é de " + iLimite + " caracteres.");
	}	
}

function msgLimitaTextArea_onBlur (objField, iLimite)
{
	var strFieldValue = objField.value;

	if (strFieldValue.length >= iLimite)
	{
		objField.focus();
	}	
}

function LimitaTextArea_onKeyPress (objField, iLimite)
{
	var strFieldValue = objField.value;
	var strLimitedText = "";

	if (strFieldValue.length >= iLimite)
	{
		event.returnValue = false;
	}	
}

function LimitaTextArea_onBlur (objField, iLimite)
{
	var strFieldValue = objField.value;
	var strLimitedText = "";

	if (strFieldValue.length >= iLimite)
	{
		for (i=0; i<iLimite; i++)
			strLimitedText = strLimitedText + strFieldValue.charAt(i);
		objField.value = strLimitedText;
	}	
}

function CommaToPoint (StringToChange)
{
	var regEx = ",";
	
	return StringToChange.replace (regEx, ".");
}

function ValidaDataMenor(Dt, DtFinal)
{;
}

// Usada para validar e-mails
function ValidaEmail_Old (thisField, fNull)
{
	if (fNull == true)
		return true;
	if (!isEmail (thisField.value, false))
		return false;
	else
		return true;
}

function isLetterOrDigit (c)
{
	return isLetter(c) || isDigit(c);
}

function isLetter (c)
{
	return ((c >= "a") && (c <= "z")) || ((c >= "A") && (c <= "Z"));
}

function isDigit (c)
{
	return (c >= "0") && (c <= "9");
}

function isEmail (s)
{   
	var ct = 1;
	var ctArroba = 0;
	var sLength = s.length;
	
	// procura ç, ', ^, á, é, í, ó, ú, â, ê, î, ô, û
	while ((ct < sLength) && (s.charAt(ct) != "ç") && (s.charAt(ct) != "^") && (s.charAt(ct) != "'") && (s.charAt(ct) != "á") && (s.charAt(ct) != "é") && (s.charAt(ct) != "í") && (s.charAt(ct) != "ó") && (s.charAt(ct) != "ú") && (s.charAt(ct) != "â") && (s.charAt(ct) != "ê") && (s.charAt(ct) != "î") && (s.charAt(ct) != "ô") && (s.charAt(ct) != "û")) 
	{
		++ct;
	}

	if (ct < sLength)
		return false;
	else
		ct = 1;

	// verifica se existe mais de um @
	while (ct < sLength) 
	{
		if (s.charAt(ct) == "@")
			++ctArroba;
		
		++ct;
	}

	if (ctArroba > 1)
		return false;
	else
		ct=1;
	
	// procura @
	while ((ct < sLength) && (s.charAt(ct) != "@")) 
	{
		++ct;
	}

	if ((ct >= sLength) || (s.charAt(ct) != "@"))
		return false;
	else
		ct+=2;

	// procura .
	while ((ct < sLength) && (s.charAt(ct) != "."))
	{
		++ct;
	}

	// deve existir no mínimo um caractere depois do ponto	
	if ((ct >= sLength - 1) || (s.charAt(ct) != "."))
		return false;
	else
		return true;
}
