// Biblioteca de Funções e Validações Gerais do Site

// FUNÇÕES COM VALORES/NÚMEROS

// Função de Validação de Campos tipo Valor
function VerificaValor(Numero)
{
   var i;

   if(Numero.charAt(Numero.length-3) != ",")
      return false;
   else if(Numero.length > 6)
   {
      i = Numero.length - 7;
          while(i >= 0)
          {
             if(Numero.charAt(i) != ".")
                    return (false);
             i = i - 4;
          }
   }
   return true;
}

// Formata Campos tipo Valor para o formato SQL
function FormataValorSQL(pValor)
{
	var i;
	var pNovoValor;

	i = 0
	while(i < pValor.length)
	{
		if ((pValor.charAt(i) != ".") && (pValor.charAt(i) != ","))
		{
			if (i==0)
				pNovoValor = pValor.charAt(i);
			else
				pNovoValor = pNovoValor + pValor.charAt(i);

		}
		i = i + 1
	}
	
	pNovoValor = pNovoValor.substring(0,(pNovoValor.length - 2)) + "." + pNovoValor.substring((pNovoValor.length - 2),pNovoValor.length)
	return pNovoValor
}

// Formata valores em formato SQL para o Brasileiro.
function FormataValorBRA(pValor)
{
	var i
	var j
	var iDecimal
	var iInteiro
	var iNovoValor

	iInteiro = pValor
	iDecimal = '00'

	// Separa a parte Inteira da parte Decimal
	i = 0
	for (i = 0; i < pValor.length; i++)
	{
		if (pValor.charAt(i) == ".")
		{
			iInteiro = pValor.substring(0,i)
			iDecimal = pValor.substring(i + 1,pValor.length)
		}
	}

	// Formata a parte decimal para duas casas no mínimo.
	if (iDecimal.length == 1)
	{
		iDecimal = iDecimal + "0"
	}

	// Formata a parte Inteira.
	iNovoValor = ''
	j = 0
	for (i = iInteiro.length; i > 0; i--)
	{
		j = j + 1
		if (j == 4)
		{
			iNovoValor = iInteiro.substring(i,i-1) + '.' + iNovoValor
			j = 1
		}
		else
		{
			iNovoValor = iInteiro.substring(i,i-1) + iNovoValor
		}
	}

	// Agrega a Parte decimal ao novo valor
	iNovoValor = iNovoValor + "," + iDecimal

	return iNovoValor
}

// Verifica se uma variável só possui números.
function IsNumber(numero)
{
   var i;
   var nPonto = 0;

   for (i = 0; i < numero.length; i++)
   {
      if (numero.charAt(i) < "0" || numero.charAt(i) > "9")
      {
	      return false;
      }
   }
   return true;
}


// FUNÇÕES COM DATAS

//verifica se ano é bissexto; se for, retorna TRUE; se não for, retorna FALSE
function AnoBissexto(Ano)
{
	if (((Ano % 4)==0) && ((Ano % 100)!=0) || ((Ano % 400)==0))
		return true;
	else
		return false;
}

function UltimoDiaDoMes(Mes,Ano)
{
   var DiasDoAno = new Array(13);
   var DiaAux;

	if (AnoBissexto(Ano))
	{
		DiaAux=29;
   }
	else
	{
		DiaAux=28;
   }

	DiasDoAno[1] = 31; DiasDoAno[2] = DiaAux; DiasDoAno[3] = 31; DiasDoAno[4] = 30;
	DiasDoAno[5] = 31; DiasDoAno[6] = 30; DiasDoAno[7] = 31; DiasDoAno[8] = 31;
	DiasDoAno[9] = 30; DiasDoAno[10] = 31; DiasDoAno[11] = 30; DiasDoAno[12] = 31;
	return (DiasDoAno[Mes]);
}


// Verifica se a informação passada é uma data válida.
function IsDate(sData)
{
   var dia
   var mes
   var ano

   if (sData.length != 10)
   {
      return false
   }

   if ( (sData.charAt(2) != "/") || (sData.charAt(5) != "/") )
   {
      return false
   }

   dia = sData.substring(0,2)
   mes = sData.substring(3,5)
   ano = sData.substring(6,10)

   if ( (!IsNumber(dia)) || (!IsNumber(mes)) || (!IsNumber(ano)) )
   {
      return false
   }

   if ( (mes < 1) || (mes > 12) )
   {
      return false
   }

   if ( (dia < 1) || (dia > UltimoDiaDoMes(parseInt(TiraZerosInvalidos(mes)),parseInt(TiraZerosInvalidos(ano)))) )
   {
      return false
   }

   return true
}

//Pega data no formato 'Fri Dec 11 14:26:08 UTC-0200 1998' e transforma em 'DD/MM/AAAA'
//                     'Tue Dec 1 14:28:17 UTC-0200 1998'
function FormataData(Data)
{
   var dia = new String()
   var mes = new String()
   var ano = new String()
   var dat = new String()

   if (Data.length == 33)     // se o dia tiver dois caracteres
   {
      dia = Data.substring(8, 10)
      ano = Data.substring(29, 33)
   }
   else if(Data.length == 32)    // se o dia tiver um caracter
   {
      dia = "0" + Data.substring(8, 9)
      ano = Data.substring(29, 33)
   }

   mes = Data.substring(4, 7)

   if (mes == "Jan")
      mes = "01"
   else if (mes == "Feb")
      mes = "02"
   else if (mes == "Mar")
      mes = "03"
   else if (mes == "Apr")
      mes = "04"
   else if (mes == "May")
      mes = "05"
   else if (mes == "Jun")
      mes = "06"
   else if (mes == "Jul")
      mes = "07"
   else if (mes == "Aug")
      mes = "08"
   else if (mes == "Sep")
      mes = "09"
   else if (mes == "Oct")
      mes = "10"
   else if (mes == "Nov")
      mes = "11"
   else if (mes == "Dec")
      mes = "12"

   dat = dia + "/" + mes + "/" + ano
   return (dat)
}

/* Pega Datas no formato dd/mm/aaaa e fala qual a data mais recente
   -1 - Uma das datas é inválida ou com formato inválido
   0  - As duas datas são iguais
   1  - A 1ª data é a mais recente
   2  - A 2ª data é a mais recente*/
function ComparaDatas(sData1, sData2)
{
   if ( (!IsDate(sData1)) || (!IsDate(sData2)) )
   {
      return (-1)
   }
   else if (sData1 == sData2)
   {
      return (0)
   }
   else
   {
      if ( sData1.substring(6, 10) != sData2.substring(6, 10) )
      {
         if ( parseFloat(sData1.substring(6, 10)) > parseFloat(sData2.substring(6, 10)) )
         {
            return (1)
         }
         else if ( parseFloat(sData1.substring(6, 10)) < parseFloat(sData2.substring(6, 10)) )
         {
            return (2)
         }
      }
      else
      {
         if ( sData1.substring(3, 5) != sData2.substring(3, 5) )
         {
            if ( parseFloat(sData1.substring(3, 5)) > parseFloat(sData2.substring(3, 5)) )
            {
               return (1)
            }
            else if ( parseFloat(sData1.substring(3, 5)) < parseFloat(sData2.substring(3, 5)) )
            {
               return (2)
            }
         }
         else
         {
            if ( sData1.substring(0, 2) != sData2.substring(0, 2) )
            {
               if ( parseFloat(sData1.substring(0, 2)) > parseFloat(sData2.substring(0, 2)) )
               {
                  return (1)
               }
               else if ( parseFloat(sData1.substring(0, 2)) < parseFloat(sData2.substring(0, 2)) )
               {
                  return (2)
               }
            }
            else
            {
               return (0)
            }
         }
      }
   }
}

// DEMAIS FUNÇÕES

//Função que retorna a quantidade de vezes que determinada expressão aprerece em uma string
function ContaOcorrencias(strValor, strExpressao)
{
	//cria o vetor
	arrAux = strValor.split(strExpressao)
	
	//retorna o tamanho do vetor - 1, para indicar a quantidade de vezes que a expressão aparece na string
	return arrAux.length - 1
}

//Função igual ao TRIM
function TiraEspacos(Texto)
{
   if (Texto.length > 0)
   {
      //Tira espaços da esquerda
      while (Texto.charAt(0) == " ")
      {
         Texto = Texto.substring(1, Texto.length)
      }

      if (Texto.length > 0)
      {
         //Tira espaços da direita
         while (Texto.charAt(Texto.length - 1) == " ")
         {
            Texto = Texto.substring(0, Texto.length - 1)
         }
      }
   }
   return Texto
}


// Função igual ao REPLACE (do VBScript)
function Troca(Texto, Car1, Car2)
{
   var pos
   var tam

   tam = Texto.length

   for (pos = 0; pos < tam; pos++)
   {
      if (Texto.charAt(pos) == Car1)
      {
         Texto = Texto.substring(0, pos) + Car2 + Texto.substring(pos + 1, tam)
      }

      tam = Texto.length
   }

   return(Texto)
}

function TiraZerosInvalidos(ValorString)
{
   var bFlag

   bFlag = true

   while (bFlag)
   {
      if (ValorString.charAt(0) == "0")
      {
         ValorString = ValorString.substring(1)
      }
      else
      {
         bFlag = false
      }
   }

   return (ValorString)
}

function AbrePopUp(strURL, strNome, Width, Height)
{
		jWidth  = Width;
		jHeight = Height;
		jTop    = (screen.height - jHeight) / 2;
		jLeft   = (screen.width - jWidth) / 2;
		jTamPos = 'width=' + jWidth + ',height=' + jHeight + ',left=' + jLeft + ',top=' + jTop + ';';
	    var windowprops = "location=no,scrollbars=yes,menubars=no,toolbars=no,resizable=no," + jTamPos;
	    popup = window.open(strURL,strNome,windowprops); 
}

// Função que monta os combos de data (dia, mês e ano) automaticamente
// Autor: Humberto Ploennes Junior
// Parâmetros:
// strComplemento ----> Complemento do nome dos campos no formulário
// strStyle ----> Style utilizado pelos combos
// intDiaSelecionado ----> Dia que virá selecionado no combo de dia
// intMesSelecionado ----> Mês que virá selecionado no combo de mês
// intAnoSelecionado ----> Ano que virá selecionado no combo de ano
// intComplementoAno ----> Quantidade de anos, após o atual, que virá no combo de ano
function MontaComboData(strComplemento, strStyle, intDiaSelecionado, intMesSelecionado, intAnoSelecionado, intComplementoAno){

	var objData = new Date()
	
	document.write("<TABLE BORDER='0' CELLPADDING='0' CELLSPACING='0'>")
	document.write("<TR>")
	document.write("<TD>")
	document.write("<SELECT NAME='intDia" + strComplemento + "' CLASS='" + strStyle + "'>")
	for(x = 1; x <= 31; x++){
		if(x == intDiaSelecionado){
			if(x < 10){
				x = "0" + x
			}
			document.write("<OPTION VALUE='" + x + "' SELECTED>" + x)
		}
		else
		{
			if(x < 10){
				x = "0" + x
			}
			document.write("<OPTION VALUE='" + x + "'>" + x)
		}
	}
	document.write("</SELECT>")
	document.write("</TD>")
	document.write("<TD>")
	document.write("<SELECT NAME='intMes" + strComplemento + "' CLASS='" + strStyle + "'>")
	for(x = 1; x <= 12; x++){
		if(x == intMesSelecionado){
			if(x < 10){
				x = "0" + x
			}
			document.write("<OPTION VALUE='" + x + "' SELECTED>" + x)
		}
		else
		{
			if(x < 10){
				x = "0" + x
			}
			document.write("<OPTION VALUE='" + x + "'>" + x)
		}
	}
	document.write("</SELECT>")
	document.write("</TD>")
	document.write("<TD>")
	document.write("<SELECT NAME='intAno" + strComplemento + "' CLASS='" + strStyle + "'>")
	// Verifica o navegador que está sendo utilizado, para definir o ano atual
	if(navigator.appName.toUpperCase() == "NETSCAPE"){
		intAno = objData.getYear() + 1900
	}
	else
	{
		intAno = objData.getYear()
	}
	for(x = intAno - 100; x <= intAno + intComplementoAno; x++){
		if(x == intAnoSelecionado){
			document.write("<OPTION VALUE='" + x + "' SELECTED>" + x)
		}
		else
		{
			document.write("<OPTION VALUE='" + x + "'>" + x)
		}
	}
	document.write("</SELECT>")
	document.write("</TD>")
	document.write("</TR>")
	document.write("</TABLE>")
	
}

// Função utilizada para completar zeros a esquerda em um valor informado
// Autor: Humberto Ploennes Junior
// Parâmetros:
// strValor ----> Valor que será completado
// intCasasDecimais ----> Total de casas decimais que o valor deverá ter
function CompletaZeros(strValor, intCasasDecimais){

	if(strValor.length < parseInt(intCasasDecimais)){
		// Armazena a quantidade de zeros que deverá completar o valor
		intQtdZeros = intCasasDecimais - strValor.length
		// Inicializa a variável
		strZeros = ""
		// Loop que gera a string de zeros que irá completar o valor
		for(x = 1; x <= intQtdZeros; x++){
			strZeros = strZeros + "0"
		}
		// String de retorno
		strRetorno = strZeros + strValor
	}
	else
	{
		// String de retorno
		strRetorno = strValor
	}
	
	// Retorna o valor
	return strRetorno
	
}

// Função que obriga a utilização de números no campo informado
// Autor: Humberto Ploennes Junior
// Parâmetros:
// intParam ----> Valor
function SomenteNumeros(intParam){
	if((intParam/intParam != 1) && intParam != 0){
		return false
	}
	else
	{
		return true
	}
}

// Função que verifica se o e-mail informado é válido
// Autor: Humberto Ploennes Junior
// Parâmetros:
// strValor ----> E-mail que será validado
function VerificaEmail(strValor){
	strEmail = strValor
	strArroba = strEmail.indexOf("@")
	strPonto = strEmail.indexOf(".")
	strUltimoCaracter = strEmail.substring(strEmail.length, strEmail.length - 1)
	strMaisPontos = strEmail.indexOf("..")
	if(
		// Se o "@" for o primeiro caracter
		(strArroba == 0) ||
		// Se o "@" não existir
		(strArroba == -1) ||
		// Se existir o "@."
		(strEmail.indexOf("@.") != -1) ||
		// Se não existirem pontos
		(strPonto == -1) ||
		// Se o "." for o último caracter
		(strUltimoCaracter == ".") ||
		// Se existirem "..", "..." e etc...
		(strMaisPontos != -1)
	){
		return false
	}
	else
	{
		return true
	}
}

// Função se o CEP informado é válido
// Autor: Humberto Ploennes Junior
// Parâmetros:
// strNomeCampo ----> Nome do campo que contém o CEP
// strCaracter ----> Contém um caracter não numérico que poderá ser aceito
function ValidaNumericos(strValor, strCaracter){

	intQtdCaracteres = strValor.length
	intASCIICaracter = strCaracter.charCodeAt(0)
	for (i = 0; i < intQtdCaracteres; i++){
		// charCodeAt(i) -> Retorna o código Unicode do caracter que se encontra na posição "i" da string
		// Verifica se é o caracter tolerável
		if(strValor.charCodeAt(i) != intASCIICaracter){
			if((strValor.charCodeAt(i) < 48) || (strValor.charCodeAt(i) > 57)){
				return false
			}
		}
	}
	
	return true
	
}

// Função Replace
// Autor: Humberto Ploennes Junior
// Parâmetros:
// strValor ----> Valor que terá seus caracteres substituídos
// strAntigo ----> Caracter que será substituído
// strNovo ----> Novo caracter
function Substitui(strValor, strAntigo, strNovo){
	strNovoValor = ""
	if(strValor.indexOf(strAntigo) != "-1"){
		// Percorre todos os caracteres da string
		for(x = 0; x < strValor.length; x++){
			strCaractere = strValor.substring(x, x + 1)
			// Substitui o valor antigo pelo novo
			if(strCaractere == strAntigo){
				strNovoValor = strNovoValor + strNovo
			}
			else
			{
				strNovoValor = strNovoValor + strCaractere
			}
		}
		return strNovoValor
	}
	else
		return strValor
}

// Retorna o index do campo no formulário
function GetIndex(strCampo){
    for(var i=0; i < document.form.elements.length; i++)
        if(strCampo == document.form.elements[i])
            return i;
    return -1;
}
