/*****************************************************************************************************
 *              Biblioteca de Funções Genéricas                                                      *
 *                                                                                                   *
 * Funções neste arquivo:                                                                            *
 *                                                                                                   *
 * FUNÇÂO                                RETORNO   DESCRIÇÂO                                         *
 * ------                                -------   ---------                                         *
 * ToMoney(valor)			             Float	   recebe string e converte no formato monetário     *
 * testaString(str, descricao)           Boolean   checa string nula ou com brancos                  *
 * testaCombo(combo, descricao)          Boolean   checa se existe opção selecinada                  *
 * testaComboValor(combo, descricao)     Boolean   checa se existe opção selecinada testando valor   *
 *                                                 diferente -1                                      *
 * testaCep(campoCep)                    Boolean   Testa se o Cep é valido                           *
 * testaCgc(campoCgc)                    Boolean   Testa se o CGC é valido                           *
 * checa_cpf (numcpf)                    Boolean   Testa se o Cpf é valido                           *
 * mod(ini,fim)                          Number    Calcula o resto de ini/fim                        *
 * emailCheck(emailStr)                  Boolean   Testa se o E-mail é valido                        *
 * trim(str)                             String    comprime espaços da string                        *
 * testaData(dateStr)                    Boolean   Testa se a data é valida                          *
 * formatCurrency(num)                   String    Formata número separando por (.) e (,)            *
 *                                                 Ex: formatCurrency(1000.5) = "1.000,50"           *
 * testaValor(str, descricao)            Boolean   checa se o valor numérico e valido e não nulo     *
 * testaRadioGroup(radioObj, descricao)  Boolean   checa se existeb alguma opção selecionada         *
 * testaAno(str, descricao)              Boolean   Testa ano com 4 algarismo                         *
 * isDigit(c)                            Boolean   Testa se o caracter c é numero (0 a 9)            *
 * isInteger (s)                         Boolean   Testa se a string só contem numeros               *
 * isFloat (s)                           Boolean   Testa se a string só contem float (0 a 9 e .)     *
 * testaFloat(numero, descricao)         Boolean   Testa se a string só contem float (0 a 9 e .)     *
 * testaTelefone(numero, descricao)      Boolean   Testa se a string só contem numeros(0 a 9 e -)    *
 * data(strData)                         Number    Valor Numerico da Data, permitindo comparar datas *
 * dataAtual()                           String    data atual formato dd/mm/yyyy                     *
 * strZero(numero, tam)                  String    numero com zeros a esquerda até preencher o tam   *
 *****************************************************************************************************/

var hoje = new Date();
var AnoCorrente = parseInt(hoje.getFullYear());

function ToMoney(valor) {

var str, virg;
  virg = /,/i;
  str = parseFloat(valor.replace(virg, "."));
  return str;
}


/* function keyPressQty()
{		
	switch (event.keyCode)
	{
		case 48 ://0
		case 49 ://1		
		case 50 ://2
		case 51 ://3
		case 52 ://4
		case 53 ://5
		case 54 ://6
		case 55 ://7
		case 56 ://8
		case 57 ://9
			break;
		default :
			event.keyCode = 0		
	}
} */ 

function keyPressPrice()
{		
	switch (event.keyCode)
	{
		case 48 ://0
		case 49 ://1		
		case 50 ://2
		case 51 ://3
		case 52 ://4
		case 53 ://5
		case 54 ://6
		case 55 ://7
		case 56 ://8
		case 57 ://9
		case 44 ://.				    
			break;
		case 46 ://,
			event.keyCode = 44;
			break;
		
		default :
			event.keyCode = 0;		
	}
	//alert(event.keyCode)
	//alert(event.srcElement.name)
}


function data(strData)
{
  //formato esperado: dd/mm/yyyy
  var ano = strData.substring(6,10);
  var mes = strData.substring(3,5);
  var dia = strData.substring(0,2);
  var dtData = Date.parse(mes + "/" + dia + "/" + ano);

  return dtData;
}

function dataAtual()
{
  var d;
  var s = "";
  d = new Date();
  s += strZero(d.getDate(),2) + "/";
  s += strZero((d.getMonth() + 1),2) + "/";
  s += d.getFullYear();
  return(s);
}

function strZero(numero, tam)
{
  var numero = trim(numero);
  while(numero.length < tam) {
    numero = "0" + numero;
  }
  return numero;
}

function testaString(str, descricao)
{
  if (trim(str) == "") {
    alert(descricao + " é Campo Obrigatório !");
    return false;
  }
  return true;
}


function testaCombo(combo, descricao)
{
  if (combo.selectedIndex == -1 || combo.selectedIndex == 0) {
        if (trim(descricao) != "" && trim(descricao) != " "){
            alert(descricao + " deve ter uma Opção Selecionada");
        }
    return false;
    }
  else
    return true;
}

function testaComboValor(combo, descricao)
{
  if (combo.options[combo.selectedIndex].value == -1) {
        if (trim(descricao) != "" && trim(descricao) != " "){
            alert(descricao + " deve ter uma Opção Selecionada");
        }
    return false;
    }
  else
    return true;
}

function testaValor_(str)
{
  var inp = "";
  var decimal = -1;
  var milhar = -1;
  var chr;
  var negativo = false;
  var texto = trim(str);
  if (texto == "") return 0;
  for (i = 1; i <= texto.length; i++) {
    chr = texto.charAt(texto.length - i);
    if (negativo) return 0;
    else if (chr == '-') {
      inp = '-' + inp;
      negativo = true;
    }
    else if (",.".indexOf(chr) >= 0) {
      if (chr == decimal) return 0;
      if (i <= 3) {
        if (decimal != -1) return 0;
        decimal = chr;
        inp = '.' + inp;
      }
      else if (milhar == -1) milhar = chr;
      if (chr != milhar && chr != decimal) return 0;
    }
    else if ("0123456789".indexOf(chr) >= 0) inp = chr + inp;
    else return 0;
  }
  return parseFloat(inp);
}

function testaValor(str, descricao)
{
    if (str.length > 13) {
        alert(descricao + " deve ter no máximo 13 posições");
        return false;
    }
    if (testaValor_(str) == 0 && trim(descricao) != "" && trim(descricao) != " ") {
        alert(descricao + " Deve ser Preenchido Corretamente");
        return false;
    }
    return true;
}

function testaRadioGroup(radioObj, descricao)
{
  for(i = 0; i < radioObj.length; i++) {
    if (radioObj[i].checked)
      return true;
  }
        if (trim(descricao) != "" && trim(descricao) != " "){
                  alert("Deve ser selecionada uma opção de " + descricao);
                  return false;
        }
}

function isDigit (c)
{   return ((c >= "0") && (c <= "9"))
}

function isInteger (s)
{   var i;
    for (i = 0; i < s.length; i++)
    {
        // Check that current character is number.
        var c = s.charAt(i);

        if (!isDigit(c)) return false;
    }
    // All characters are numbers.
    return true;
}

function isFloat (s)

{   var i;
    var decimalPointDelimiter = ".";

    if (s == decimalPointDelimiter) return false;

    for (i = 0; i < s.length; i++)
    {
        // Check that current character is number.
        var c = s.charAt(i);

        if (!((c == decimalPointDelimiter) || (isDigit(c))))
          return false;
    }

    return true;
}

function testaFloat(numero, descricao)
{
  if (!isFloat(numero)) {
    alert(descricao + " Deve ser Preenchido Corretamente");
    return false;
  }
  return true;
}

function testaTelefone (numero, descricao)

{   var i;
    var traco = "-";
    var branco = " ";
    s = trim(numero);
    if (s == traco) {
      alert(descricao + " não é um numero de telefone válido");
      return false;
    }
    for (i = 0; i < s.length; i++)
    {
        // Check that current character is number.
        var c = s.charAt(i);

        if (!((c == traco) || (c == branco) || (isDigit(c)))) {
          alert(descricao + " não é um numero de telefone válido");
          return false;
        }
    }

    return true;
}


function testaAno(ano, descricao, tipoVeiculo)
{
  var tam = ano.length;
  var maxAnos = ((arguments.length < 3) ? 10 : ((tipoVeiculo == 'CA') ? 10 : 10)) - 1;

  if (tam < 4) {
    alert(descricao + " Deve ter 4 (quatro) posições");
    return false;
  }
  if (!isInteger(ano)) {
    alert(descricao + " Deve ser Numero Inteiro");
        return false;
  }
  if (parseInt(ano) < parseInt(AnoCorrente - maxAnos)) {
    alert(descricao + " deve ser maior ou igual a " + parseInt(AnoCorrente - maxAnos));
    return false;
  }
  return true;
}

function testaInteiro(numero, descricao)
{
  if (trim(numero) == "") {
    alert(descricao + " é Campo Obrigatório");
    return false;
  }
  var numero = trim(numero);
  var tam = numero.length;
  if (tam > 8) {
    alert(descricao + " deve ter no máximo 8 (oito) posições");
    return false;
  }
  if (!isInteger(numero)) {
    alert(descricao + " deve ser Numero Inteiro");
        return false;
  }
  return true;
}

function testaCep(campoCep)
{
        /* Critica de CEP - função principal */
        var dblNum;
        var num1 = new initArrayCep(8);
        if((campoCep == null) || (campoCep == "00000000")) {
              alert("CEP nulo");
            return false; }
        if(campoCep.length != 8) {
            alert("Campo 'CEP' diferente de 8 posições!");
            return false; }
        if((campoCep.substr(5,1) < "0") || (campoCep.substr(5,1) > "9")
                 || (campoCep.substr(6,1) < "0") || (campoCep.substr(6,1) > "9")
                 || (campoCep.substr(7,1) < "0") || (campoCep.substr(7,1) > "9"))
         {
            alert("O campo 'CEP' deve conter apenas números!");
            return false;
         }

        dblNum = 0.1;
        if(!isNaN(campoCep))
        {
                dblNum = campoCep;
                return true;
        }
        else
        {
                alert("O campo 'CEP' deve conter apenas números!");
                return false;
        }
}

function initArrayCep()
{
        /* Critica de Cep - Sub-funcao */
        this.length = initArrayCep.arguments.length;
      for (var i = 0 ; i < 8 ; i++)
        {
        this[i] = " ";
      }
}

function testaCgc(campoCgc)
{
      var num1 = new initArray(14);
      if(campoCgc == null)
        {     alert("CNPJ nulo");
            return false;
        }
        if(campoCgc.length != 14)
        {
            alert("CNPJ diferente de 14 posições");
            return false;
        }
            for (var i = 0 ; i < 14 ; i++)
                {
               num1[i] = campoCgc.substring(i, i+1);
                }

        digito13 = calculaDigito(13, num1);
        digito14 = calculaDigito(14, num1);
        if (num1[12]==(digito13) && num1[13]==(digito14)){
            return true;  }
      else {
            alert("CNPJ incorreto");
            return false;  }

}

function initArray()
{
        this.length = initArray.arguments.length;
      for (var i = 0 ; i < 14 ; i++)
        {
        this[i] = " ";
      }
}

function calculaDigito( cgc_limite,  num)
{
     cgc_soma = 0;
     cgc_ind = 1;
     cgc_peso = cgc_limite - 7 - cgc_ind;
     while(cgc_ind < cgc_limite)
     {
         cgc_soma += num[cgc_ind - 1] * cgc_peso;
         cgc_ind++;
         if(cgc_peso == 2)
              cgc_peso = 9;
         else
              cgc_peso--;
     }
     cgc_resto = mod(cgc_soma, 11);
     if(cgc_resto == 0 || cgc_resto == 1)
           {cgc_digito = 0;}
     else
           {cgc_digito = 11 - cgc_resto;}
     return cgc_digito;
}

function mod(ini, fim)
{
     t = ini % fim;
     return t;
}

function checa_cpf (numcpf)
{
        x = 0;
        soma = 0;
        dig1 = 0;
        dig2 = 0;
        texto = "";
        numcpf1="";
        len = numcpf.length; x = len -1;
        // var numcpf = "12345678909";
        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;
        //alert ("Digito Verificador : " + dig1 + "" + dig2);
        if ((dig1 + "" + dig2) == numcpf.substring(len,len-2)) {
                return true;
        }
        alert ("Número do CPF inválido !!!");
        falso = "F";
        return false;
}

function testa_CPF(numcpf)
{
        if(checa_cpf(numcpf)) {
                return true;
        }
        else {
                return false;
        }
}

function emailCheck (emailStr) {
        //remove espaços antes da verificação
        var emailStr = trim(emailStr)
        /* Critica de e-mail */
        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=emailStr.match(emailPat)
        if (matchArray==null) {
                alert("O endereço de e-mail parece incorreto (verifique @ e .'s)")
                return false
        }
        var user=matchArray[1]
        var domain=matchArray[2]

        if (user.match(userPat)==null) {
            alert("O nome de usuário do e-mail não parece ser válido.")
            return false
        }

        var IPArray=domain.match(ipDomainPat)
        if (IPArray!=null) {
                  for (var i=1;i<=4;i++) {
                    if (IPArray[i]>255) {
                        alert("O endereço IP de destino do e-mail é inválido!")
                        return false
                    }
            }
            return true
        }

        var domainArray=domain.match(domainPat)
        if (domainArray==null) {
                alert("O nome do domínio do e-mail não parece ser válido.")
            return false
        }

        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) {
           alert("O endereço de e-mail deve terminar com um domínio de 3 letras ou um país com 2 letras.")
           return false
        }

        if (len<2) {
           var errStr="Este endereço de e-mail não possui um nome de Host!"
           alert(errStr)
           return false
        }

        return true;
}


function trim(str) {
  str = str.toString().replace(/\$|\ /g,'');
  return str;
}

function testaData(dateStr) {

  // testa data em branco -> usa função trim
  if (trim(dateStr) == "") {
    alert("Data é Campo Obrigatório");
    return false;
  }
// Checks for the following valid date formats:
// DD/MM/YY   DD/MM/YYYY   DD-MM-YY   DD-MM-YYYY
// Also separates date into month, day, and year variables

// To require a 2 digit year entry, use this line instead:
var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{2}|\d{4})$/;

// To require a 4 digit year entry, use this line instead:
   var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{4})$/;

var matchArray = dateStr.match(datePat); // is the format ok?
if (matchArray == null) {
alert("Data deve estar no formato DD/MM/AAAA")
return false;
}

day = matchArray[1];
month = matchArray[3]; // parse date into variables
year = matchArray[4];
if (month < 1 || month > 12) { // check month range
alert("Mês deve ser entre 1 e 12.");
return false;
}
if (day < 1 || day > 31) {
alert("Dia deve ser entre 1 e 31.");
return false;
}
if ((month==4 || month==6 || month==9 || month==11) && day==31) {
alert("Mês "+month+" não tem 31 dias!")
return false
}
if (month == 2)
{ // check for february 29th
	var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
	if (day>29 || (day==29 && !isleap))
	{
		alert("Fevereiro " + year + " não tem " + day + " dias!");
		return false;
	}
}

//determinando intervalo de data
/*
if (year < 1900 || year > AnoCorrente)
{
	alert("O ano de estar entre 1900 e "+ AnoCorrente + "!")
	return false;
}*/

return true;  // date is valid
}

function testaHora(horaStr)
{

  // testa hora em branco -> usa função trim
  if (trim(horaStr) == "")
  {
    alert("Hora é Campo Obrigatório");
    return false;
  }
	// Checks for the following valid date formats:
	// HH/MM
	// Also separates date into month, day, and year variables

	// To require a 2 digit use this line instead:
	var horaPat = /^(\d{2})(\:)(\d{2})$/;


	var matchArray = horaStr.match(horaPat); // is the format ok?
	if (matchArray == null)
	{
		alert("Hora deve estar no formato HH:MM")
		return false;
	}

	hora = matchArray[1];
	minuto = matchArray[3]; 
	
	if (hora < 0 || hora > 23) { // check hora range
	alert("Hora deve ser entre 00 e 23.");
	return false;
	}
	
	if (minuto < 0 || minuto > 59) { // check hora range
	alert("Minuto deve ser entre 00 e 59.");
	return false;
	}
return true;  // hora is valid
}



function formatCurrency(num) {
num = num.toString().replace(/\$|\./g,'');
num = num.toString().replace(/\$|\,/g,'.');
if(isNaN(num)) num = "0";
cents = Math.floor((num*100+0.5)%100);
num = Math.floor(num).toString();
if(cents < 10) cents = "0" + cents;
for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
num = num.substring(0,num.length-(4*i+3))+'.'+num.substring(num.length-(4*i+3));
return (num + ',' + cents);
}

function valorCurrency(num)
{
  num = num.toString().replace(/\$|\./g,'');
  num = num.toString().replace(/\$|\,/g,'.');
  valor = parseFloat(num);
  return valor;
}

function roundOff(value, precision)
{
        value = "" + value //convert value to string
        precision = parseInt(precision);

        var whole = "" + Math.round(value * Math.pow(10, precision));

        var decPoint = whole.length - precision;

        if(decPoint != 0)
        {
                result = whole.substring(0, decPoint);
                result += ".";
                result += whole.substring(decPoint, whole.length);
        }
        else
        {
                result = whole;
        }
        return result;
}

