/*------------------------------------------------------
- Verifica se o campo está vazio
  function chkVazio(palavra)
- Retorna u número de dias conforme o mês e ano
  function getNDias(mes,ano)
- Simula o comando Trim do VBScript
  function getTrim(texto)
- Retorna o tipo de Browser IE = "IE", Outros="Default"
  function getBrowser()
- Valida CPF
  function chkCpf (campo, cpf)
- Valida CNPJ
  function chkCnpj (numero)
- Verifica se a senha e a confirmação são iguais
  function chkSenha (senha1, senha2)
- Limpa os brancos iniciais e finais do campo, retornando 1 se o campo ficou vazio e 0 se não.
  function setLimpaBrancos (campo)
- Seta o maxlength para um objeto TextArea. Ex.: onKeyUp="textarealimite(this.form.'name',300);"
  function setTextAreaLimite(campo, maxlimite)
- Valida Email Ex.: onblur="chkEmail(this)"
  function chkEmail(campo)
- Valida Campo numérico Ex.: onblur="chkNumero(this)"
  function chkNumero(campo)
- Verifica se campos radio e checkbox estão selecionados
  function chkSelecionado(campo)
- Seta a caixa de texto ser digitado somente números
  function setNumero()
- Valida campo CEP
  function chkCep(campo_cep,campo_uf)
- Verifica a idade mínima, verificando o intervalo entre anos
  function chkIdadeMinima(ano_de, ano_ate, campo)
- Verifica se o campo contém somente letras e números
  function chkAlpNum(campo)
- Insere formatação Currency Ex.: onKeyPress="return(setCurrency(this,'.',',',event))"
  function setCurrency(campo, separador_mil, separador_dec, e)
- Limpa espaços em brancos
  functions LTrim,  RTrim, e Trim
- Verifica os caracteres que não são válidos
  function chkCaracter(campo, msg)
------------------------------------------------------

novas funções
*/
// verifica_np
function verifica_np(campo)
{
	if(campo.value== "NP")
	{
		return false;
	}
	else
	{  
		return true;
	}
}

// verifica_vazio
function verifica_vazio(campo)
{ 
  var j = true;
  if(campo.value == "")	j=false; 
  if(j)
  {
	return (j);
  }
  else
  {
	campo.focus();
	return (j);
  }
}

// -----------------------------------------------
//função para verificar se o objeto está vazio
function chkVazio(campo, msg)
{ 
  var j = true; 
  campo.value=Trim(campo.value);
  if(campo.value == "")	j=false; 
  if(j)
  {
	return (j);
  }
  else
  {
	alert(msg);
	campo.focus();
	return (j);
  }
}

//Verifica de um conjunto de dois radios foram checados. Ex.: Sexo ()M ()F 
function chkRadioDuplo(obj, msg)
{
	if(obj[0].checked == false && obj[1].checked == false)
	{
		alert(msg);
		obj[0].focus();
		return false;
	}
	else
	{
		return true;
	}
}


//Retorna u número de dias conforme o mês e ano
function getNDias(mes,ano) 
{
	if (mes==2)
	{
	if((ano % 4) == 0 ) 
		return 29 
	else 
		return 28
	}
	else
	if (mes < 8)
	{
	if ((mes % 2) == 0) 
		return 30 
	else 
		return 31
	}   
	else
	{
	if ((mes % 2) != 0) 
		return 30 
	else 
		return 31
	}      
}

//Simula o comando Trim do VBScript
function getTrim(texto)
{
 while  ( (texto.search(' ') > -1) )
    {
		texto = texto.replace(' ','');    
	}
 return (texto)	
}

//Retorna o tipo de Browser IE = "IE", Outros="Default"
function getBrowser()
{
	var st = document.cookie ;
	var a;
	var i;
	var tipo_browser;

	if( window.navigator.appName == 'Netscape' )
	{
		tipo_browser = "Default"   
	}
	else
	{	
		tipo_browser = "IE"	
	}
	return tipo_browser
}

// Verifica se o CPF é válido
function chkCpf (campo,valor) {
  
  strcpf = valor;
  str_aux = "";
  
  for (i = 0; i <= strcpf.length - 1; i++)
    if ((strcpf.charAt(i)).match(/\d/)) 
      str_aux += strcpf.charAt(i);
    else if (!(strcpf.charAt(i)).match(/[\.\-]/)) {
      alert ("O campo CPF apresenta caracteres inválidos !!!");
      campo.focus();      return false;
    }
  
  if (str_aux.length != 11) {
    alert ("O campo CPF deve conter 11 dígitos !!!");    campo.focus();
    return false;
  }
  
  soma1 = soma2 = 0;
  for (i = 0; i <= 8; i++) {
    soma1 += str_aux.charAt(i) * (10-i);
    soma2 += str_aux.charAt(i) * (11-i);
  }
  d1 = ((soma1 * 10) % 11) % 10;
  d2 = (((soma2 + (d1 * 2)) * 10) % 11) % 10;
  if ((d1 != str_aux.charAt(9)) || (d2 != str_aux.charAt(10))) {
    alert ("O CPF digitado é inválido !!!");    campo.focus();
    return false;
  }
 
  return true;
}

// Verifica se o CNPJ é válido
function chkCnpj(s)
{
	var i;
 	//s = limpa_string(numero);
 	var c = s.substr(0,12);
 	var dv = s.substr(12,2);
 	var d1 = 0;

 	for (i = 0; i < 12; i++)
 	{
 		d1 += c.charAt(11-i)*(2+(i % 8));
 	}
 	
	if (d1 == 0) return false;

        d1 = 11 - (d1 % 11);

	if (d1 > 9) d1 = 0;

	if (dv.charAt(0) != d1)
	{
		return false;
	}

 	d1 *= 2;

 	for (i = 0; i < 12; i++)
	{
		d1 += c.charAt(11-i)*(2+((i+1) % 8));
	}

	d1 = 11 - (d1 % 11);

	if (d1 > 9) d1 = 0;

	if (dv.charAt(1) != d1)
	{
		return false;
	}
        return true;
}

// Verifica se a senha e a confirmação são iguais
function chkSenha (senha1, senha2){
  strsenha1 = senha1.value;
  strsenha2 = senha2.value;
  
  if ((!strsenha1) || (strsenha1 == strsenha2)) return true;
  if (strsenha2)
    alert ("A senha e a confirmação devem conter o mesmo valor");
  return false;
}

// Limpa os brancos iniciais e finais do campo, retornando 1 se o campo ficou vazio e 0 se não.
function setLimpaBrancos (campo) {
   var strcampo = eval ("document.forms[0]."+campo+".value");
   var inicio = 0;
   var fim = strcampo.length - 1;
 
   while ((strcampo.charAt(fim).match(/\s/)) && (fim != inicio)) fim--;   
   if (inicio != fim) while (strcampo.charAt(inicio).match(/\s/)) inicio++;
   
   str_aux = "";
   if ((fim) || (!(strcampo.charAt(inicio).match(/\s/))))
     for (; inicio <= fim; inicio++) str_aux += strcampo.charAt(inicio);   
     
   eval ("document.forms[0]."+campo+".value = '"+str_aux+"'");
   return (!str_aux.length)
}

//Seta o maxlength para um objeto TextArea. Ex.: onKeyUp="textarealimite(this.form.'name',300);"
function setTextAreaLimite(campo, maxlimite)
{
	if (campo.value.length > maxlimite)
	campo.value = campo.value.substring(0, maxlimite);
}

//valida Email
/*function chkEmail(emailStr)
{
	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 está incorreto (verifique @ e .'s)");
		param_email.value = "";
		return false;
	}
	
	var user=matchArray[1]
	var domain=matchArray[2]

	if (user.match(userPat)==null) {
	    alert("Erro no endereço de E-mail:\nO nome do usuário não está correto.");
		param_email.value = "";
		return false;
	}

	var IPArray=domain.match(ipDomainPat)
	if (IPArray!=null) {
	  for (var i=1;i<=4;i++) {
		    if (IPArray[i]>255) {
		        alert("Erro no endereço de E-mail:\nO endereço IP de destino não é válido.")
		        param_email.value = "";
				return false
			}
		}
		return true
	}

	var domainArray=domain.match(domainPat)
	if (domainArray==null) {
		alert("Erro no endereço de E-mail:\nO domínio não é válido.")
		param_email.value = "";
		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("Erro no endereço de E-mail:\nO endereço precisa terminar com três letras referente ao domínio\nou duas letras referente ao país")
		return false
	}

	if (len<2) {
		var errStr="Erro no endereço de E-mail:\nEstá faltando o nome do provedor."
		param_email.value = "";
		alert(errStr)
		return false
	}
	return true;
}*/


//valida Campo numérico Ex.: onblur="chkNumero(this)"
function chkNumero(campo)
{
	straux = campo.value + '#';
    i = 0;
    while (straux.charAt(i)!='#')
    {
      if (((straux.charAt(i)>='0') && (straux.charAt(i)<='9')) || ((straux.charAt(i)=='.') || (straux.charAt(i)==',')))
        i++;
      else
      {
        alert('Por favor, este campo deve ser numérico. Use somente números.');
        campo.value = '';
        campo.focus();
        return false;
      }
    }
    return true;
}

//Verifica se campos radio e checkbox estão selecionados
function chkSelecionado(campo,msg)
{
	var checado = "";
	for (var i = 0;i < campo.length; i++)
	{
	    if(campo[i].checked)
		{
			checado = "1";
			return true;
		}
	}
	if(checado == "")
	{
		alert(msg);
		campo[0].focus();
		return false;
	}
}

function chkSelecionado_np(campo,msg)
{
	if(campo.value== "NP")
	{
		alert(msg);
		campo.focus();
		return false;
	}
	else
	{  
		return true;
	}
}

//Seta a caixa de texto ser digitado somente números
function setNumero()
{
	if (event.keyCode < 45 || event.keyCode > 57) event.returnValue = false;
}

//Valida o campo CEP
function chkCep(campo_cep,campo_uf)
{
  if (!chkNumero(campo_cep)) {
    campo_cep.value = "";
    return false;
  }

  if(campo_cep.value.length < 8)
  {
	alert('Por favor digite o cep com 8 dígitos.');
	campo_cep.value = "";
	return false;
  }
  
  var valor_inicial = campo_cep.value;
  valor_inicial = valor_inicial.substring(0,5);
  var valor = parseInt(valor_inicial);
  var est = campo_uf.options[campo_uf.selectedIndex].value;
  var erro = true;
  
 if (valor >= 0 && valor <= 19999) {
	if (est == "SP") {
      erro = false;
    }
  }
  else if (valor >= 20000 && valor <= 29999) {
    if (est == "RJ" || est == "ES") {
      erro = false;
    }
  }
  else if (valor >= 30000 && valor <= 39999) {
    if (est == "MG") {
      erro = false;
    }
  }
  else if (valor >= 40000 && valor <= 49999) {
    if (est == "BA" || est == "SE") {
      erro = false;
    }
  }
  else if (valor >= 50000 && valor <= 59999) {
    if (est == "PE" || est == "AL" || est == "PB" || est == "RN") {
      erro = false;
    }
  }
  else if (valor >= 60000 && valor <= 69999) {
    if (est == "CE" || est == "PI" || est == "MA" || est == "PA" || est == "AP" || est == "AM" || est == "RR" || est == "AC") {
      erro = false;
    }
  }
  else if (valor >= 70000 && valor <= 79999) {
    if (est == "DF" || est == "GO" || est == "TO" || est == "MT" || est == "RO" || est == "MS") {
      erro = false;
    }
  }
  else if (valor >= 80000 && valor <= 89999) {
    if (est == "PR" || est == "SC") {
      erro = false;
    }
  }
  else if (valor >= 90000 && valor <= 99999) {
    if (est == "RS") {
      erro = false;
    }
  }
  if (erro) {
	campo_cep.value = "";
	alert ("O CEP não corresponde ao estado selecionado.");
    return false;

  }
  else
  {
	return true;
  }
  return true;
}

//Verifica a idade mínima, verificando o intervalo entre anos
function chkIdadeMinima(ano_de, ano_ate, campo)
{
	var data = new String();
	var data_num = new Number();
	data = campo.value;
	data = data.substr(6,4);
	data_num = data;
	if((data_num < parseInt(ano_de))||(data_num > parseInt(ano_ate)))
	{
		alert("Idade mínima excedida\nou data inválida!");
		campo.focus();
		return false;
	}
	else
	{
		return true;
	}
}

//Verifica se o campo contém somente letras e números
function chkAlpNum(campo)
{
	var valid = "abcdefghijklmnopqrstuvwxyz0123456789"
	var ok = "yes";
	var temp;
	for (var i=0; i < campo.value.length; i++)
	{
		temp = "" + campo.value.substring(i, i+1);
		if (valid.indexOf(temp) == "-1") ok = "no";
	}
	if (ok == "no")
	{
		alert("Esse campo só aceita caracteres e números.");
		campo.focus();
		campo.select();
		return false;
	}
	else
	{
		return true;
	}
}

//Insere formatação Currency Ex.: onKeyPress="return(setCurrency(this,'.',',',event))"
function setCurrency(campo, separador_mil, separador_dec, e)
{
	var sep = 0;
	var key = '';
	var i = j = 0;
	var len = len2 = 0;
	var strCheck = '0123456789';
	var aux = aux2 = '';
	var whichCode = (window.Event) ? e.which : e.keyCode;
	
	if (whichCode == 13) return true;  // Enter
	key = String.fromCharCode(whichCode);  // Get key value from key code
	if (strCheck.indexOf(key) == -1) return false;  // Not a valid key
	len = campo.value.length;
	for(i = 0; i < len; i++)
		if ((campo.value.charAt(i) != '0') && (campo.value.charAt(i) != separador_dec)) break;
	aux = '';
	for(; i < len; i++)
		if (strCheck.indexOf(campo.value.charAt(i))!=-1) aux += campo.value.charAt(i);
	aux += key;
	len = aux.length;
	if (len == 0) campo.value = '';
	if (len == 1) campo.value = '0'+ separador_dec + '0' + aux;
	if (len == 2) campo.value = '0'+ separador_dec + aux;
	if (len > 2)
	{
		aux2 = '';
		for (j = 0, i = len - 3; i >= 0; i--)
		{
			if (j == 3)
			{
				aux2 += separador_mil;
				j = 0;
			}
			aux2 += aux.charAt(i);
			j++;
		}
		campo.value = '';
		len2 = aux2.length;
		for (i = len2 - 1; i >= 0; i--)
			campo.value += aux2.charAt(i);
			campo.value += separador_dec + aux.substr(len - 2, len);
	}
	return false;
}

function chkEmail(emailStr)
{
	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 está incorreto (veirfque @ e .'s)")
		return false
	}
	
	var user=matchArray[1]
	var domain=matchArray[2]

	if (user.match(userPat)==null) {
	    alert("Erro no endereço de E-mail:\nO nome do usuário não está correto.")
		return false
	}

	var IPArray=domain.match(ipDomainPat)
	if (IPArray!=null) {
	  for (var i=1;i<=4;i++) {
		    if (IPArray[i]>255) {
		        alert("Erro no endereço de E-mail:\nO endereço IP de destino não é válido.")
				return false
			}
		}
		return true
	}

	var domainArray=domain.match(domainPat)
	if (domainArray==null) {
		alert("Erro no endereço de E-mail:\nO domínio não é 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("Erro no endereço de E-mail:\nO endereço precisa terminar com três letras referente ao domínio\nou duas letras referente ao país")
		return false
	}

	if (len<2) {
		var errStr="Erro no endereço de E-mail:\nEstá faltando o nome do provedor."
		alert(errStr)
		return false
	}
	return true;
}


//Fuctions to mimmick LTrim,  RTrim, and Trim...
function LTrim(str)
/*
        PURPOSE: Remove leading blanks from our string.
        IN: str - the string we want to LTrim
*/
{
        var whitespace = new String(" \t\n\r");

        var s = new String(str);

        if (whitespace.indexOf(s.charAt(0)) != -1) {
            // We have a string with leading blank(s)...

            var j=0, i = s.length;

            // Iterate from the far left of string until we
            // don't have any more whitespace...
            while (j < i && whitespace.indexOf(s.charAt(j)) != -1)
                j++;


            // Get the substring from the first non-whitespace
            // character to the end of the string...
            s = s.substring(j, i);
        }

        return s;
}

function RTrim(str)
/*
        PURPOSE: Remove trailing blanks from our string.
        IN: str - the string we want to RTrim

*/
{
        // We don't want to trip JUST spaces, but also tabs,
        // line feeds, etc.  Add anything else you want to
        // "trim" here in Whitespace
        var whitespace = new String(" \t\n\r");

        var s = new String(str);

        if (whitespace.indexOf(s.charAt(s.length-1)) != -1) {
            // We have a string with trailing blank(s)...

            var i = s.length - 1;       // Get length of string

            // Iterate from the far right of string until we
            // don't have any more whitespace...
            while (i >= 0 && whitespace.indexOf(s.charAt(i)) != -1)
                i--;


            // Get the substring from the front of the string to
            // where the last non-whitespace character is...
            s = s.substring(0, i+1);
        }

        return s;
}


function Trim(str)
/*
                PURPOSE: Remove trailing and leading blanks from our string.
                IN: str - the string we want to Trim

                RETVAL: A Trimmed string!
*/
{
     return RTrim(LTrim(str));
}


/*Valida caracter*/
function chkCaracter(campo, msg)
{
  var checkOK = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzƒŠŒŽšœžŸÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþ0123456789-.@ \t\r\n\f";
  var checkStr = campo.value;
  var allValid = true;

  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;
    }
  }
  if (!allValid)
  {
    alert(msg);
    campo.focus();
    return (false);
  }
  return (true);
}


