//---------------------------------------------------------------------
// Foram retiradas as tags <SCRIPT> abrindo e fechando o arquivo para que o uso deixe de ser por "include" e passa a ser por "script src".
//
// NÃO USAR MAIS:  <!-- # include file="[caminho]/libGlobal.js" -->
// USAR:				 <script type="text/javascript" src="[caminho]/libGlobal.js"></script>
//---------------------------------------------------------------------

var g_URLCallBack = "../WebForms/";

//---------------------------------------------------------------------
//Formatadores
//---------------------------------------------------------------------

function FormatNumberPoint(num,decimalNum,bolLeadingZero,bolParens,bolCommas)
{ 
   num.value = Replace (num.value, ',', '.');

   //if (isNaN(parseInt(num.value))) return "";

   var dec = "";
   var iStartPoint = 0;
	var tmpNum = num.value;
   
   iStartPoint = tmpNum.indexOf(".")

   if (iStartPoint >= 0){
      dec = tmpNum.substring(iStartPoint + 1 ,tmpNum.length)
      tmpNum = tmpNum.substring(0,iStartPoint)
      num.value = tmpNum
   }
   
	var iSign = num.value < 0 ? -1 : 1;		// Get sign of number
	
	// Adjust number so only the specified number of numbers after
	// the decimal point are shown.
	tmpNum *= Math.pow(10,decimalNum);
	tmpNum = Math.round(Math.abs(tmpNum))
	tmpNum /= Math.pow(10,decimalNum);
	tmpNum *= iSign;					// Readjust for sign
	
	
	// Create a string object to do our formatting on
	var tmpNumStr = new String(tmpNum);

	// See if we need to strip out the leading zero or not.
	if (!bolLeadingZero && num.value < 1 && num.value > -1 && num.value != 0)
		if (num.value > 0)
			tmpNumStr = tmpNumStr.substring(1,tmpNumStr.length);
		else
			tmpNumStr = "-" + tmpNumStr.substring(2,tmpNumStr.length);

	var iStart = tmpNumStr.indexOf(".");
	if (iStart >= 0)
		tmpNumStr = tmpNumStr.substring(0,iStart) + "," + tmpNumStr.substring(iStart + 1,tmpNumStr.length);
	// See if we need to put in the commas
	if (bolCommas && (num.value >= 1000 || num.value <= -1000)) {
		//var iStart = tmpNumStr.indexOf(".");
		if (iStart < 0)
			iStart = tmpNumStr.length;

		iStart -= 3;
		while (iStart >= 1) {
			//tmpNumStr = tmpNumStr.substring(0,iStart) + "." + tmpNumStr.substring(iStart,tmpNumStr.length)
			tmpNumStr = tmpNumStr.substring(0,iStart) + "" + tmpNumStr.substring(iStart,tmpNumStr.length)
			iStart -= 3;
		}		
	}

	// See if we need to use parenthesis
	if (bolParens && num.value < 0)
		tmpNumStr = "(" + tmpNumStr.substring(1,tmpNumStr.length) + ")";

//	if (dec == "00")
//		dec=""
	
   if (dec.length > 0)
      dec = "." + dec 
   else
      dec = ".00" 
   num.value = tmpNumStr + dec

	//return tmpNumStr;		// Return our formatted string!
}

//----------------------------

function FormatNumber(num,decimalNum,bolLeadingZero,bolParens,bolCommas)
{ 
   //num.value = Replace (num.value, ',', '')
   num.value = Replace (num.value, '.', '');

   //if (isNaN(parseInt(num.value))) return "";

   var dec = "";
   var iStartVirg = 0;
	var tmpNum = num.value;
   
   iStartVirg = tmpNum.indexOf(",")

   if (iStartVirg >= 0){
      dec = tmpNum.substring(iStartVirg + 1 ,tmpNum.length)
      tmpNum = tmpNum.substring(0,iStartVirg)
      num.value = tmpNum
   }
   
	var iSign = num.value < 0 ? -1 : 1;		// Get sign of number
	
	// Adjust number so only the specified number of numbers after
	// the decimal point are shown.
	tmpNum *= Math.pow(10,decimalNum);
	tmpNum = Math.round(Math.abs(tmpNum))
	tmpNum /= Math.pow(10,decimalNum);
	tmpNum *= iSign;					// Readjust for sign
	
	
	// Create a string object to do our formatting on
	var tmpNumStr = new String(tmpNum);

	// See if we need to strip out the leading zero or not.
	if (!bolLeadingZero && num.value < 1 && num.value > -1 && num.value != 0)
		if (num.value > 0)
			tmpNumStr = tmpNumStr.substring(1,tmpNumStr.length);
		else
			tmpNumStr = "-" + tmpNumStr.substring(2,tmpNumStr.length);

	var iStart = tmpNumStr.indexOf(".");
	if (iStart >= 0)
		tmpNumStr = tmpNumStr.substring(0,iStart) + "," + tmpNumStr.substring(iStart + 1,tmpNumStr.length);
	// See if we need to put in the commas
	if (bolCommas && (num.value >= 1000 || num.value <= -1000)) {
		//var iStart = tmpNumStr.indexOf(".");
		if (iStart < 0)
			iStart = tmpNumStr.length;

		iStart -= 3;
		while (iStart >= 1) {
			tmpNumStr = tmpNumStr.substring(0,iStart) + "." + tmpNumStr.substring(iStart,tmpNumStr.length)
			iStart -= 3;
		}		
	}

	// See if we need to use parenthesis
	if (bolParens && num.value < 0)
		tmpNumStr = "(" + tmpNumStr.substring(1,tmpNumStr.length) + ")";

   if (dec.length > 0 )
      dec = "," + dec 
   else
      dec = ",00" 
   num.value = tmpNumStr + dec

	//return tmpNumStr;		// Return our formatted string!
}

//----------------------------

function formataFloat(valor, decimais)
{
var i
var virgula = -1
var valor2 = ''
var valor3 = ''
var zeros = ''

if (valor.length > 0 && parseFloat(valor) >= 0)
{
   for(i=0;i<=valor.length -1;i++)
		if (valor.substring(i,i+1) != '.')
			valor2 = valor2 + valor.substring(i,i+1)
	for(i=0;i<=valor2.length -1;i++)
	{
	   if (virgula >= 0 && decimais >= 0 && i - virgula > decimais)
	      break
	   if (valor2.substring(i,i+1) == ',' && virgula == -1)
	   {
	      virgula = i
	   	if (decimais > 0)
	   	   valor3 = valor3 + '.'
	   }
	   else if (valor2.substring(i,i+1) != ',' && !isNaN(valor2.substring(i,i+1)))
	   	valor3 = valor3 + valor2.substring(i,i+1)
	}
	if (decimais > 0)
	   {
	   if (virgula == -1)
	      {
	      valor3 = valor3 + "."
	      virgula = valor3.length - 1
	      }
	   for(i = valor3.length - virgula; i <= decimais; i++)
	      valor3 = valor3 + "0"
	   }
	if (valor3 == "" || valor3.substring(0,1) == ".")
	   valor3 = "0" + valor3
	
	return valor3
}
else if (decimais == 0)
   return 0
else
   {
   for(i = 1; i <= decimais; i++)
      zeros = zeros + '0'
	return "0." + zeros
	}
}

//----------------------------

function formataFloatBR(valor, decimais)
{
var i
var virgula = -1
var valor3 = ''
var zeros = ""

if (valor.value.length > 0 && parseFloat(valor.value) >= 0)
{
	for(i=0;i<=valor.value.length -1;i++)
	{
	   if (virgula >= 0 && decimais >= 0 && i - virgula > decimais)
	      break
   	if (!isNaN(valor.value.substring(i,i+1)) || (valor.value.substring(i,i+1) == ',' && virgula == -1))
   	   valor3 = valor3 + valor.value.substring(i,i+1)
	   if (valor.value.substring(i,i+1) == ',' && virgula == -1)
	      virgula = i
	}
	if (decimais > 0)
	   {
	   if (virgula == -1)
	      {
	      valor3 = valor3 + ","
	      virgula = valor3.length - 1
	      }
	   for(i = valor3.length - virgula; i <= decimais; i++)
	      valor3 = valor3 + "0"
	   }
	if (valor3 == "" || valor3.substring(0,1) == ",")
	   valor3 = "0" + valor3
   
	valor.value = valor3
}
else if (decimais == 0)
   valor.value = 0
else
   {
   for(i = 1; i <= decimais; i++)
      zeros = zeros + '0'
	valor.value = "0." + zeros
	}
}

//---------------------------------------------------------------------

function SeVazioNull(objValor)
{
if (EhVazioNull(objValor))
	return null
else
	return objValor
}

//-------------------------------------------------------------

function SeNullVazio(objValor)
{
if (objValor == null)
	return ""
else
	return Trim(objValor)
}



//---------------------------------------------------------------------
//String
//---------------------------------------------------------------------

function Trim(texto)
{
var i, achou, texto_novo

if (texto == null || texto == undefined)
   texto = ""
else
   {
   achou = false
   for (i = 0; i <= texto.length - 1; i++)
      if (texto.charAt(i) != " ")
         {
         achou = true
         break
         }
   if (!achou)
      texto = ""
   else
      {
      texto = texto.substr(i, texto.length - i)
      achou = false
      for (i = texto.length - 1; 0 <= i; i--)
         if (texto.charAt(i) != " ")
            {
            achou = true
            break
            }
      if (!achou)
         texto = ""
      else
         texto = texto.substr(0, i + 1)
      }
   }
return texto
}

//---------------------------------------------------------------------

function Replace(Expression, Find, Replace)
{
	var temp = Expression;
	var a = 0;

	for (var i = 0; i < Expression.length; i++) 
	{
		a = temp.indexOf(Find);
		if (a == -1)
			break
		else
			temp = temp.substring(0, a) + Replace + temp.substring((a + Find.length));
	}
	return temp;
}

//---------------------------------------------------------------------

function strRetEnter()
{
return String.fromCharCode(13) + String.fromCharCode(10);
}

//---------------------------------------------------------------------

function strRetTab(intNumVezes)
{
var strTab;

if (intNumVezes == null) intNumVezes = 1
strTab = "";
for (var intTab = 1; intTab <= intNumVezes; intTab++)
	strTab = strTab + String.fromCharCode(9);

return strTab;
}



//---------------------------------------------------------------------
//Pausa
//---------------------------------------------------------------------

function Pausa(intTentativa)
{
var CONST_DELAY = 1000	//Em milisegundos
var dtmDtAtual, dtmDtPausa

if (intTentativa > 1)
	{
   dtmDtAtual = Date.parse(Date());
   dtmDtPausa = dtmDtAtual + CONST_DELAY;
   while (dtmDtAtual < dtmDtPausa)
		{
      dtmDtAtual = Date.parse(Date());
		}
	}
}



//---------------------------------------------------------------------
//File System
//---------------------------------------------------------------------

function strRetCaminhoFormatado(strCaminho, EhWindows)
{
var strCaminhoFormatado

if (EhWindows)
	{
	strCaminhoFormatado = strCaminho.replace(/\//g, "\\")
	strCaminhoFormatado = strCaminhoFormatado.replace(/\\/g, "\\\\")
	if (strCaminhoFormatado.slice(-1) != "\\")
		strCaminhoFormatado += "\\\\"
	}
else
	{
	strCaminhoFormatado = strCaminho.replace(/\\/g, "/")
	if (strCaminhoFormatado.slice(-1) != "/")
		strCaminhoFormatado += "/"
	}
return strCaminhoFormatado
}

//---------------------------------------------------------------------

function strRetCaminhoNomeArquivo(strCaminho, strArquivoOrigem)
{
try
	{
   var strArquivoOrigemBase,strArquivoOrigemExtensao;
   var fso, f, fc, strNomeArquivo;
		
   if(strArquivoOrigem.lastIndexOf('.') != -1)
		{
		strArquivoOrigemBase			= (strArquivoOrigem.slice(0,strArquivoOrigem.lastIndexOf('.'))).toLowerCase();
		strArquivoOrigemExtensao	= (strArquivoOrigem.slice(strArquivoOrigem.lastIndexOf('.'))).toLowerCase();
		}
	else
		{
		strArquivoOrigemBase			= strArquivoOrigem.toLowerCase();
		strArquivoOrigemExtensao	= "";
		}
   fso = new ActiveXObject("Scripting.FileSystemObject");
   f = fso.GetFolder(strCaminho);
   fc = new Enumerator(f.Files);
   
   for (; !fc.atEnd(); fc.moveNext())
		{
		strNomeArquivo = (fc.item()+"").toLowerCase();
		if(strNomeArquivo.indexOf(strArquivoOrigemBase) != -1 && strNomeArquivo.indexOf(strArquivoOrigemExtensao) != -1)
			{
			return fc.item() +"";
			}
		}
   return  null;	
	}
catch(err)
	{
	Response.Write("strRetCaminhoNomeArquivo: " + err.number + '-' + err.Description)
	}
}

//----------------------------

function RetornaNomeArquivo(arquivo)
{
var i, achou

arquivo = Trim(arquivo)
achou = false
for (i = arquivo.length - 1; 0 <= i; i--)
   if (arquivo.charAt(i) == "\\" || arquivo.charAt(i) == ":")
      {
      achou = true
      break
      }
if (achou)
   return arquivo.substr(i + 1, arquivo.length - i)
else
   return arquivo
}



//---------------------------------------------------------------------
//Data
//---------------------------------------------------------------------

function strRetDtFormatada(strData)
{
var dtmData, strDtFormatada;

if (strData != null)
	dtmData = new Date(strData)
else
	dtmData = new Date();
strDtFormatada = dtmData.getFullYear();
strDtFormatada += ("0" + (dtmData.getMonth() + 1)).slice(-2);
strDtFormatada += ("0" + dtmData.getDate()).slice(-2);
strDtFormatada += ("0" + dtmData.getHours()).slice(-2);
strDtFormatada += ("0" + dtmData.getMinutes()).slice(-2);
strDtFormatada += ("0" + dtmData.getSeconds()).slice(-2);

return strDtFormatada;
}

//---------------------------------------------------------------------

function strRetDtFormatadaDMA(strDataLonga)
{
var dtmData, strDtFormatada;

if (EhVazioNull(strDataLonga))
	strDtFormatada = null
else
	{
	dtmData = new Date(strDataLonga)
	strDtFormatada  = ("0" + dtmData.getDate()).slice(-2) + "/";
	strDtFormatada += ("0" + (dtmData.getMonth() + 1)).slice(-2) + "/";
	strDtFormatada += dtmData.getFullYear() + " ";
	strDtFormatada += ("0" + dtmData.getHours()).slice(-2) + ":";
	strDtFormatada += ("0" + dtmData.getMinutes()).slice(-2) + ":";
	strDtFormatada += ("0" + dtmData.getSeconds()).slice(-2);
	}
return strDtFormatada;
}

//---------------------------------------------------------------------

function strRetDtFormatadaBD(strDataDMA)
{
// strDataDMA deve estar no formato DMY
var intIndexPrimeiraBarra, intIndexSegundaBarra
var strDia, strMes, strAno

ok = false
intIndexPrimeiraBarra = strDataDMA.indexOf("/")
intIndexSegundaBarra = strDataDMA.indexOf("/", intIndexPrimeiraBarra + 1)
if (intIndexPrimeiraBarra < 0 || intIndexSegundaBarra < 0)
	return "NULL"
else
	{
	strDia = Trim(strDataDMA.substr(0, intIndexPrimeiraBarra))
	strMes = Trim(strDataDMA.substr(intIndexPrimeiraBarra + 1, intIndexSegundaBarra - intIndexPrimeiraBarra - 1))
	strAno = Trim(strDataDMA.substr(intIndexSegundaBarra + 1))
	if (strAno.length == 1)
		strAno = "200" + strAno
	else if (strAno.length == 2)
		if (parseInt(strAno) > 50)
			strAno = "19" + strAno
		else
			strAno = "20" + strAno
	else
		strAno = Trim(strAno)
	return "'" + strAno + "/" + strMes + "/" + strDia + "'"
	}
}

//-------------------------------------------------------------

function dtmRetDtAtual()
{
var strDtAtual, dtmDtAtual;

dtmDtAtual = new Date();
strDtAtual = dtmDtAtual.getFullYear();
strDtAtual += '/' + ('0' + (dtmDtAtual.getMonth() + 1)).slice(-2);
strDtAtual += '/' + ('0' + dtmDtAtual.getDate()).slice(-2);
strDtAtual += ' ' + ('0' + dtmDtAtual.getHours()).slice(-2);
strDtAtual += ':' + ('0' + dtmDtAtual.getMinutes()).slice(-2);
strDtAtual += ':' + ('0' + dtmDtAtual.getSeconds()).slice(-2);

return strDtAtual;
}

//---------------------------------------------------------------------

function ValidouData(strData)
{
var ok = false;
var strCaracter = " 0123456789/:"
var intAno, intMes, intDia
var intHora,intMinutos
if(strData == null)
	ok = true;
else if (strData.length == 16)
	{
	for(var count; count < strData.length;count++)
		{
			if(strCaracter.indexOf(strData.charAt(count)) < 0) 
				return ok;
		}
	intMinutos	= strData.slice(-2);
	intHora		= strData.slice(-5,-3);
	intDia		= strData.slice(-8,-5);
	intMes		= strData.slice(-11,-9);
	intAno		= strData.slice(-16,-12);
		
	if ((intMinutos.indexOf('/') == -1  || intMinutos.indexOf(':') == -1 ) && 
		(intHora.indexOf('/')== -1  || intHora.indexOf(':') == -1 ) &&
		(intDia.indexOf('/') == -1  || intDia.indexOf(':') == -1 ) &&
		(intMes.indexOf('/') == -1  || intMes.indexOf(':') == -1 ) &&
		(intAno.indexOf('/') == -1  || intAno.indexOf(':') == -1 ))
			ok = true;
	}
return ok;
}

//---------------------------------------------------------------------

function ValidouHora(txt, nome)
{
var ok = true

txt.value = Trim(txt.value)
if (txt.value != "")
   {
   ok = EhHora(txt.value)
   if (!ok)
      {
      alert(nome + " inválido(a).")
      txt.focus()
      }
   }
return ok
}

//----------------------------

function strRetDtFormatadaYYYYMMDD(strDataDMA)
{
// strDataDMA deve estar no formato DMY
var intIndexPrimeiraBarra, intIndexSegundaBarra
var strDia, strMes, strAno

strDataDMA = Trim (strDataDMA)
ok = false
intIndexPrimeiraBarra = strDataDMA.indexOf("/")
intIndexSegundaBarra = strDataDMA.indexOf("/", intIndexPrimeiraBarra + 1)
if (intIndexPrimeiraBarra < 0 || intIndexSegundaBarra < 0)
	return "NULL"
else
	{
	strDia = strDataDMA.substr(0, intIndexPrimeiraBarra)
	strMes = strDataDMA.substr(intIndexPrimeiraBarra + 1, intIndexSegundaBarra - intIndexPrimeiraBarra - 1)
	strAno = strDataDMA.substr(intIndexSegundaBarra + 1)
	if (strAno.length == 1)
		strAno = "200" + strAno
	else if (strAno.length == 2)
		if (parseInt(strAno) > 50)
			strAno = "19" + strAno
		else
			strAno = "20" + strAno
	else
		strAno = strAno

	strDia = new String (100 + parseInt(strDia, 10))
	strDia = strDia.substr(strDia.length -2, strDia.length -1)

	strMes = new String (100 + parseInt(strMes, 10))
	strMes = strMes.substr(strMes.length -2, strMes.length -1)

	return strAno + strMes + strDia
	}
}



//---------------------------------------------------------------------
//Validadores
//---------------------------------------------------------------------

function EhVazioNull(texto)
{
if (Trim(texto) == "" || texto == null || texto == "undefined")
	return true
else
	return false
}

//-------------------------------------------------------------

function EhInteiro(s) {
var num = "0123456789";
var erro = false;

for (var i = 0; i < s.length; i++) {
if (num.indexOf(s.charAt(i)) == -1) {
	erro = true; break;				
}
}
return !erro;
}

//----------------------------

function EhDecimal(s) {
var num = "0123456789,";
var erro = false;

for (var i = 0, p = 0; i < s.length; i++) {
if (num.indexOf(s.charAt(i)) == -1) {
	erro = true; break;				
}
else {
	if (s.charAt(i) == ",") p = p + 1;
	if (p > 1) {
		erro = true; break;
	}
}
}
return !erro;
}

//----------------------------

function EhHora(s) {
var num = "0123456789:";
var erro = false;
var hora;
var h, m;

for (var i = 0, p = 0; i < s.length; i++) {
if (num.indexOf(s.charAt(i)) == -1) {
	erro = true; break;				
}
else {
	if (s.charAt(i) == ":") p = p + 1;
	if (p > 1) {
		erro = true; break;
	}
}
}
if (p != 1) erro = true;
if (!erro) {
hora = s.split(":");
h = hora[0] - 0;
m = hora[1] - 0;
if (h > 23 || m > 59) erro = true;
}
return !erro;
}

//----------------------------

function isEmail(str) {
  // are regular expressions supported?
  var supported = 0;
  if (window.RegExp) {
    var tempStr = "a";
    var tempReg = new RegExp(tempStr);
    if (tempReg.test(tempStr)) supported = 1;
  }
  if (!supported) 
    return (str.indexOf(".") > 2) && (str.indexOf("@") > 0);
  var r1 = new RegExp("(@.*@)|(\\.\\.)|(@\\.)|(^\\.)");
  var r2 = new RegExp("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$");
  return (!r1.test(str) && r2.test(str));
}

//----------------------------

function ValidouCPF(CPF)
{
// Aqui começa a checagem do CPF
var posicao, i, soma, dv, dv_informado;
var digito = new Array(10);

switch(CPF)
{
	case "00000000000":
	case "00000000000":
	case "11111111111":
	case "22222222222":
	case "33333333333":
	case "44444444444":
	case "55555555555":
	case "66666666666":
	case "77777777777":
	case "88888888888":
	case "99999999999":
		alert('CPF inválido.');
		return false;	
}

dv_informado = CPF.substr(9, 2); // Retira os dois últimos dígitos do número informado

// Desemembra o número do CPF na array DIGITO
for (i=0; i<=8; i++)
	{
	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 valores dos dígitos verificadores conferem
dv = digito[9] * 10 + digito[10];
if (dv != dv_informado)
	{
  	alert('CPF inválido.')
  	return false;
	}
else
	return true;
}

//----------------------------

function ValidouCGC(CGC)
{

/*var CGCNumerico = CGC;

CGCNumerico = CGCNumerico.replace( "-", "" );
CGCNumerico = CGCNumerico.replace( "/", "" );
CGCNumerico = CGCNumerico.replace( ".", "" );
CGCNumerico = CGCNumerico.replace( ".", "" );

var multiplicador = 2;
var soma = 0;
var num = 0;
var digito = parseInt(CGCNumerico.charAt(CGCNumerico.length - 1));
var i;

switch(CGCNumerico)
{
	case "00000000000000":
	case "11111111111111":
	case "22222222222222":
	case "33333333333333":
	case "44444444444444":
	case "55555555555555":
	case "66666666666666":
	case "77777777777777":
	case "88888888888888":
	case "99999999999999":
		alert('CNPJ inválido.');
		return false;	
}

if ((CGCNumerico.length !== 14) || (!EhInteiro(CGCNumerico)))
	{
	alert('CNPJ inválido.')
	return false
	}
else
	{
	for (var i = CGCNumerico.length - 1; i >= 1; i--) 
		{
		num = parseInt(CGCNumerico.charAt(i-1));
		soma = soma + num * multiplicador;
		if (multiplicador == 9)
			multiplicador = 2
		else
			multiplicador++
		}
	num = soma / 11;
	if (num == parseInt(num)) 
		num = 0
	else
		num = soma - (11 * parseInt(num))
   if (num < 2)
		num = 0
   else
		num = 11 - num
	if (num == digito)
		return true
   else
		{
		alert('CNPJ inválido.')
		return false
		}   
   }*/
   
//Declaração as variáveis
var numeros, digitos, soma, i, resultado, pos, tamanho, digitos_iguais, cnpj;
cnpj = CGC;

//Verificando se o campo é nulo
if (cnpj.length == 0) {
	alert("CNPJ inválido.");
	return false;
}

//Filtrar o campo para verificar se está com máscara
var filtro = /\d{2,3}.\d{3}.\d{3}\/\d{4}-\d{2}/;
if(filtro.test(cnpj)){
	window.alert("CNPJ inválido.");
	return false;
}
//Ultilização expressão regular para retirar o que não for número
cnpj = cnpj.replace(/\D+/g, '');
digitos_iguais = 1;

for (i = 0; i < cnpj.length - 1; i++)
	if (cnpj.charAt(i) != cnpj.charAt(i + 1)){
		digitos_iguais = 0;
		break;
	}
	if (!digitos_iguais){
		tamanho = cnpj.length - 2
		numeros = cnpj.substring(0,tamanho);
		digitos = cnpj.substring(tamanho);
		soma = 0;
		pos = tamanho - 7;
		for (i = tamanho; i >= 1; i--){
			soma += numeros.charAt(tamanho - i) * pos--;
			if (pos < 2)
				pos = 9;
		}
		resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
		if (resultado != digitos.charAt(0)){
			alert('CNPJ inválido');
			return false;
		}
		tamanho = tamanho + 1;
		numeros = cnpj.substring(0,tamanho);
		soma = 0;
		pos = tamanho - 7;
		for (i = tamanho; i >= 1; i--){
			soma += numeros.charAt(tamanho - i) * pos--;
			if (pos < 2)
				pos = 9;
		}

		resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
		if (resultado != digitos.charAt(1)){
			alert('CNPJ inválido');
			return false;
		}
		return true;
	}
	else
		alert('CNPJ inválido');
		return false;
}

//----------------------------

function ValidouValor(txt, decimais, nome, minimo, maximo)
{
var ok = false

txt.value = Trim(txt.value)
if (txt.value == "")
   ok = true
else
   if (decimais == 0)
      if (!EhInteiro(txt.value))
         {
         alert(nome + " inválido(a).")
         txt.value = ""
         txt.focus()
         }
      else if (parseFloat(txt.value) < minimo)
         {
         alert(nome + " deve ser maior ou igual a " + minimo + ".")
         txt.value = ""
         txt.focus()
         }
      else if (parseFloat(txt.value) > maximo)
         {
         alert(nome + " deve ser menor ou igual a " + maximo + ".")
         txt.value = ""
         txt.focus()
         }
      else
         ok = true
   else
      if (!EhDecimal(txt.value))
         {
         alert(nome + " inválido(a).")
         txt.value = ""
         txt.focus()
         }
      else if (parseFloat(formataFloat(txt.value, decimais)) > maximo)
         {
         alert(nome + " deve ser menor ou igual a " + maximo + ".")
         txt.value = ""
         txt.focus()
         }
      else if (parseFloat(formataFloat(txt.value, decimais)) < minimo)
         {
         alert(nome + " deve ser maior ou igual a " + minimo + ".")
         txt.value = ""
         txt.focus()
         }
      else
         {
         //formataFloatBR(txt, decimais)
         ok = true
         }
return ok
}

//-----------------------------------

function ValidaValorPonto(txt, decimais, nome)
{
var ok = false

txt.value = Trim(txt.value)
if (txt.value == "")
   ok = true
else
   if (decimais == 0)
      if (!EhInteiro(txt.value))
         {
         alert(nome + " inválido(a).")
         txt.value = ""
         txt.focus()
         }
      else
         ok = true
   else
      if (!EhDecimal(Replace (txt.value, ".", ",")))
         {
         alert(nome + " inválido(a).")
         txt.value = ""
         txt.focus()
         }
      else
         {
         ok = true
         }
return ok
}

//----------------------------

function ValidouDDD(txt)
{
var ok

ok = ValidouValor(txt, 0, 'DDD')
if (ok && txt.value != "")
   if (txt.value.length != 2)
      {
      ok = false
      alert("DDD deve ser composto por dois dígitos.")
      txt.value = ""
      txt.focus()
      }
return ok
}

//----------------------------

function ValidouTelefone(txt)
{
var ok

ok = ValidouValor(txt, 0, 'Telefone')
if (ok && txt.value != "")
   if (txt.value.length != 7 && txt.value.length != 8)
      {
      ok = false
      alert("Telefone deve ser composto por oito dígitos.")
      txt.value = ""
      txt.focus()
      }
return ok
}

//----------------------------

function ValidouTarifa(txt, nome)
{
var ok

ok = ValidouValor(txt, 5, nome)
if (ok && txt.value != "")
   if (formataFloat(txt.value, 5) >= 10000)
      {
      ok = false
      alert(nome + " deve ser maior que zero e menor que 10,000.")
      txt.value = ""
      txt.focus()
      }
return ok
}

//----------------------------

function ValidouDinheiro(txt, nome)
{
var ok

ok = ValidouValor(txt, 2, nome)
if (ok && txt.value != "")
   if (formataFloat(txt.value, 2) >= 10000000)
      {
      ok = false
      alert(nome + " deve ser maior que zero e menor que 10,000,000.")
      txt.value = ""
      txt.focus()
      }
return ok
}

//----------------------------

function ValidouEmail(txt, nome)
{
var ok = true

txt.value = Trim(txt.value)
if (txt.value != "")
   {
   ok = isEmail(txt.value)
   if (!ok)
      {
      alert(nome + " inválido.")
      txt.value = ""
      txt.focus()
      }
   }
return ok
}

//----------------------------

function ValidouCEP(txt)
{
var ok

ok = ValidouValor(txt, 0, 'CEP')
if (ok && txt.value != "")
   if (txt.value.length != 8)
      {
      ok = false
      alert("CEP deve ser composto por oito dígitos.")
      txt.value = ""
      txt.focus()
      }
return ok
}

//-------------------------------------------------------------








//---------------------------------------------------------------------
//Navegação
//---------------------------------------------------------------------

function AbrePopSimples(url, parametros, nome, largura, altura, menubar)
{
var propriedades

if (largura == 0)
	largura = screen.width
if (altura == 0)
	altura = 400
if (menubar == 'nothing')
	menubar = 0
propriedades  = "directories=0, location=0, menubar=" + menubar + ", resizable=1, scrollbars=1, status=1, toolbar=0, "
propriedades += "width=" + largura + ", height=" + altura + ", "
propriedades += "left=" + (screen.width - largura) / 2 + ", top=" + (screen.height - altura) / 2
window.open(url + '?EhPop=1&' + parametros, nome, propriedades)
}

//----------------------------

function AbrePop(url, parametros, nome, largura, altura, tipopop, retornopop1, retornopop2, menubar)
{
var propriedades

if (largura == 0)
	largura = screen.width
if (altura == 0)
	altura = 400
if (menubar == 'nothing')
	menubar = 0
propriedades  = "directories=0, location=0, menubar=" + menubar + ", resizable=1, scrollbars=1, status=1, toolbar=0, "
propriedades += "width=" + largura + ", height=" + altura + ", "
propriedades += "left=" + (screen.width - largura) / 2 + ", top=" + (screen.height - altura) / 2
window.open(url + '?EhPop=1&TipoPop=' + tipopop + '&RetornoPop1=' + retornopop1 + '&RetornoPop2=' + retornopop2 + '&' + parametros, nome, propriedades)
}

//----------------------------

function FechaPop(eh_edicao)
{
if (eh_edicao)
	{
	window.opener.document.forms[0].submit()
	//window.opener.location = window.opener.location;
	}
window.close()
}

//----------------------------

function RetornaPop(campo, valor)
{
eval('window.opener.document.forms[0].' + campo).value = valor
FechaPop(true)
}

//----------------------------

function RetornaPop2(campo1, valor1, campo2, valor2)
{
eval('window.opener.document.forms[0].' + campo1).value = valor1
eval('window.opener.document.forms[0].' + campo2).value = valor2
FechaPop(true)
}

//----------------------------

function imP(btnImprimir) {
	if (confirm('Você deseja imprimir essa página?')) { 
		document.all.btnImprimir.style.display = "none";
		window.print();
		document.all.btnImprimir.style.display = "";
	}
}

//----------------------------

//Controle do 'Return'

function KeyDownHandler(nextfield)
{
if (event.keyCode == 13)
	{
	if (nextfield == 'done')
		{
		return false;
		}
	else
		{
		eval('document.all.' + nextfield + '.click()');
		event.returnValue=false;
		event.cancel = true;
		}
	}
}

//----------------------------

function AbrePopArquivoUpload(tamanhoMaximoPropostaModularCSS_, extensaoLista_, urlVirtual_, nomeNovoArquivo_, 
										objNomeFormOpener_, objNomeArquivoOpener_, target_, atributos_)
{
var _url, _parametro;

_url = g_URLCallBack + "wfrArquivoUpload.aspx";
_parametro  = "?TamanhoMaximo=" + tamanhoMaximoPropostaModularCSS_;
_parametro += "&ExtensaoLista=" + extensaoLista_;
_parametro += "&URLVirtual=" + urlVirtual_;
_parametro += "&NomeNovoArquivo=" + nomeNovoArquivo_;
_parametro += "&ObjNomeFormOpener=" + objNomeFormOpener_;
_parametro += "&ObjNomeArquivoOpener=" + objNomeArquivoOpener_;
window.open(_url + _parametro, (target_ ? target_ : "wfrArquivoUpload"), (atributos_ ? atributos_ : "width=600, height=180, scrollbars=no, titlebar=no, menubar=no, toolbar=no, location=no, status=no, resizable=no"));
}

