
//isEmpty(str) : recebe uma string e verifica se está vazia
function isEmpty(str) 
{ 
	if (str==null) return true
	
	for (var intLoop = 0; intLoop < str.length; intLoop++)
		if (" " != str.charAt(intLoop))
			return false;            
	return true; 
}

//msg_vnull: verifica se valor do campo é nulo e retorna mensagem 
//cv = nome do campo
//vv = valor do campo
function msg_vnull(cv,vv)
{	
	if (isEmpty(vv))
		 return "\n" + "O campo '" + cv + "' é obrigatório." 
	return " "
}

//msg_vnum(obrig,campo,valor): valida campo numérico
//obrig: se o campo é obrigatorio ou nao
//nome: nome do campo que aparecerá na mensagem
//valor: valor a ser testado
function msg_vnum(obrig,campo,valor)
{	

  function f_num(cn,vn)
  {
    strVn = vn.toString(10)
    if ((isNaN(vn)) || ((strVn.indexOf(",") != -1) || (strVn.indexOf(".") != -1) || (strVn.indexOf("E") != -1) || (strVn.indexOf("+") != -1) || (strVn.indexOf("-") != -1)))
      {
		return  "\n" + "O campo '" + cn + "' deve ser numérico."
      }
		
    return "  "
    
  }

  if (obrig)
  {	
    m_valid = msg_vnull(campo,valor)
    if (! isEmpty(m_valid)) 
      return m_valid
    return f_num(campo,valor)
  }
  else
	return f_num(campo,valor)
	
}

function  validateNumeric( strValue ) {
/******************************************************************************
DESCRIPTION: Validates that a string contains only valid numbers.

PARAMETERS:
   strValue - String to be tested for validity
   
RETURNS:
   True if valid, otherwise false.
******************************************************************************/
  var objRegExp  =  /(^-?\d\d*\,\d*$)|(^-?\d\d*$)|(^-?\,\d\d*$)/; 
 
  //check for numeric characters 
  return objRegExp.test(strValue);
}


//msg_vfloat(obrig,campo,valor): valida campo numérico
//obrig: se o campo é obrigatorio ou nao
//nome: nome do campo que aparecerá na mensagem
//valor: valor a ser testado
function msg_vfloat(obrig,campo,valor)
{	

  function f_num(cn,vn)
  {
    strVn = vn.toString(10)
    if (!validateNumeric(vn))
      {
		return  "\n" + "O valor de '" + cn + "' deve ser numérico."
      }
		
    return "  "
    
  }

  if (obrig)
  {	
    m_valid = msg_vnull(campo,valor)
    if (! isEmpty(m_valid)) 
      return m_valid
    return f_num(campo,valor)
  }
  else {		
		if (! isEmpty(valor))       
			return f_num(campo,valor)
		return "  "	
	}
	
}

function Verifica_Data(d,m,a)
 {
 if  (((isEmpty(d)) || (isEmpty(m)) || (isEmpty(a))) && ((!isEmpty(d)) && (!isEmpty(m)) && (!isEmpty(a)))) return false; 
 if ( (isNaN(d) && d != '') || (isNaN(m) && m != '') || (isNaN(a) && a != '') ) return false
 if ( (m<1 || m >12) && (m != '') ) return false
 if ( (d<1 || d >31) && (d != '') ) return false
 if ( (a<1900 || a>2078) && (a !='') ) return false
 if (d == 31)
 if( (m == 2) || (m == 4) || (m == 6) || (m == 9) || (m == 11)) return false
 if (m ==2)
 if( (parseInt(a)%4 != 0 && d ==29) || (d == 30) )return false
 return true
 }

function msg_vdata(obrig,campo,d,m,y)
{
//obrig: se o campo é obrigatorio ou nao
//campo: nome do campo que aparecerá na mensagem
//valor: valor a ser testado
function f_data(cvg,vd,vm,vy)
{
	if (! Verifica_Data(vd,vm,vy))	 
		return "\n" + "O campo '" + cvg + "' é inválido." 
	return " "
}
if (obrig)
{	
	m_valid = msg_vnull(campo,d)
	if (! isEmpty(m_valid)) 
		return m_valid
	m_valid = msg_vnull(campo,m)
	if (! isEmpty(m_valid)) 
		return m_valid
	m_valid = msg_vnull(campo,y)
	if (! isEmpty(m_valid)) 
		return m_valid
	return f_data(campo,d,m,y)
}
else
	return f_data(campo,d,m,y)
}

function valida_email_js(str) 
{ 
	var s  = ""
	var s_ = ""
	var Replace = false
	
	if (str==null) return false
	
	if (str=="") return false
	
	s = str.indexOf(" ")
  if (s != -1) return false; // não pode conter espaços
  
  s = str.indexOf(",")
  if (s != -1) return false; // não pode conter vírgulas
  
  s = str.indexOf("@")
  if (s == -1) return false; // verifica se te arroba da esq para a dir
  
  s_ = s
  
  s = str.lastIndexOf("@")
  if (s != s_) return false; // verifica se te arroba da dir para a esq, a posição achada tem que ser a mesma
                             // para ter apenas 1 arroba
  s = str.indexOf(".")
  if (s == -1) return false; // tem que ter pelo menos 1 ponto
  if (str.substr(str.length - 1) == ".") return false // o ponto não pode ser o último caracter
  if (str.substr(str.length - 2,1) == ".") return false // o ponto não pode ser o penúltimo caracter
  
  s = str.indexOf("@.")
  if (s != -1) return false; // não pode ter ponto depois da arroba
    
  if (str.length < 7) return false;   // tem que ter pelo menos tamanho 6    
  
  if ((str.indexOf("à") != -1) || (str.indexOf("á") != -1) || (str.indexOf("ã") != -1) ||
      (str.indexOf("ä") != -1) || (str.indexOf("â") != -1) || (str.indexOf("å") != -1) ||
      (str.indexOf("è") != -1) || (str.indexOf("é") != -1) || (str.indexOf("ê") != -1) ||
      (str.indexOf("ë") != -1) || (str.indexOf("ï") != -1) || (str.indexOf("ì") != -1) ||
      (str.indexOf("î") != -1) || (str.indexOf("ö") != -1) || (str.indexOf("ò") != -1) ||
      (str.indexOf("õ") != -1) || (str.indexOf("ó") != -1) || (str.indexOf("ô") != -1) ||
      (str.indexOf("ù") != -1) || (str.indexOf("ú") != -1) || (str.indexOf("û") != -1) ||
      (str.indexOf("û") != -1) || (str.indexOf("À") != -1) || (str.indexOf("Á") != -1) || 
      (str.indexOf("Ã") != -1) || (str.indexOf("Ä") != -1) || (str.indexOf("Â") != -1) ||
      (str.indexOf("Å") != -1) || (str.indexOf("È") != -1) || (str.indexOf("É") != -1) ||
      (str.indexOf("Ê") != -1) || (str.indexOf("ï") != -1) || (str.indexOf("î") != -1) ||
      (str.indexOf("ì") != -1) || (str.indexOf("Ò") != -1) || (str.indexOf("Õ") != -1) ||
      (str.indexOf("Ó") != -1) || (str.indexOf("Ô") != -1) || (str.indexOf("Ö") != -1) || 
      (str.indexOf("Û") != -1) || (str.indexOf("Ù") != -1) || (str.indexOf("Ú") != -1) ||
      (str.indexOf("Û") != -1) || (str.indexOf("Ü") != -1) || (str.indexOf("ç") != -1) || 
      (str.indexOf("Ç") != -1))
    return false;  
  
  return true; 
}

//msg_email: verifica se valor do campo é nulo e retorna mensagem 
//cv = nome do campo
//vv = valor do campo
function msg_vemail(cv,vv)
{	
	if (isEmpty(vv))
		 return "\n" + "O campo '" + cv + "' é obrigatório." 
	
	if (!valida_email_js(vv))
		 return "\n" + "O campo '" + cv + "' está preenchido incorretamente." 	 
	return " "
}

function verifica_cpf (CPF) {

	if (CPF.length != 11 || CPF == "00000000000" || CPF == "11111111111" ||
		CPF == "22222222222" ||	CPF == "33333333333" || CPF == "44444444444" ||
		CPF == "55555555555" || CPF == "66666666666" || CPF == "77777777777" ||
		CPF == "88888888888" || CPF == "99999999999")
		return false;

	soma = 0;
	for (i=0; i < 9; i ++)
		soma += parseInt(CPF.charAt(i)) * (10 - i);
	resto = 11 - (soma % 11);
	if (resto == 10 || resto == 11)
		resto = 0;
	if (resto != parseInt(CPF.charAt(9)))
		return false;
	soma = 0;
	for (i = 0; i < 10; i ++)
		soma += parseInt(CPF.charAt(i)) * (11 - i);
	resto = 11 - (soma % 11);
	if (resto == 10 || resto == 11)
		resto = 0;
	if (resto != parseInt(CPF.charAt(10)))
		return false;
	return true;
 }
 
function msg_vcpf(obrig,campo,valor)
{	

//obrig: se o campo é obrigatorio ou nao
//campo: nome do campo que aparecerá na mensagem
//valor: valor a ser testado
//ATENCAO: as funcoes msg_vnull(), isEmpty() e verifica_cpf() estão em arquivos externos

function f_cpf(cvg,vcg)
{
	if (! verifica_cpf(vcg))	 
		return  "\n" + "O campo '" + cvg + "' é inválido." 
	return " "
}

if (obrig)
{	
	m_valid = msg_vnull(campo,valor)
	if (! isEmpty(m_valid)) 
		return m_valid
	return f_cpf(campo,valor)
}
else
	return f_cpf(campo,valor)
}


function verifica_cgc(valor)
{
	if ((isNaN(valor)) && (valor.length != 14))
		return false
		
	Mult1 = "543298765432"
	Mult2 = "6543298765432"
	dig1=0
	dig2=0
		
	for(var i=0;i<=11;i++)   
	{
		ind=valor.charAt(i)
		M=Mult1.charAt(i)
		dig1 += ((parseFloat(ind)) *  (parseFloat(M)))
	}
	
	for( var i=0;i<=12;i++)   
	{
		ind=valor.charAt(i)
		M=Mult2.charAt(i)
		dig2 += ((parseFloat(ind)) *  (parseFloat(M)))
	}
		
	dig1 = (dig1 * 10) % 11
	dig2 = (dig2 * 10) % 11
	
	if (dig1 == 10)
		dig1 = 0
		
	if (dig2 == 10) 
		dig2 = 0

	if (dig1 != (parseFloat(valor.charAt(12))))
		return false
	
	if (dig2 != (parseFloat(valor.charAt(13))))
		return false
		
	return true
}

function msg_vcgc(obrig,campo,valor)
{	
//obrig: se o campo é obrigatorio ou nao
//campo: nome do campo que aparecerá na mensagem
//valor: valor a ser testado
//ATENCAO: as funcoes msg_vnull(), isEmpty() e verifica_cgc() estão em arquivos externos

function f_cgc(cvg,vcg)
{
	if (! verifica_cgc(vcg))	 
		return "\n" + "O campo '" + cvg + "' é inválido." 
	return " "
}

if (obrig)
{	
	m_valid = msg_vnull(campo,valor)
	if (! isEmpty(m_valid)) 
		return m_valid
	return f_cgc(campo,valor)
}
else
	return f_cgc(campo,valor)

}


function msg_vcartao(campo,num)
{
	var i=0;
	var total=0;
	
	if  ( num != "") {
		for(i=num.length; i>=2; i=i-2){
			  total = total + parseInt(num.substring(i-1,i));
			  TempMultiplier= num.substring(i-2,i-1)*2;
			  temp = "" + TempMultiplier + "";
			  if (TempMultiplier >= 10 ){
				   total = total + parseInt(temp.substring(0,1));
			  }
			  else {
				   total = total + TempMultiplier;
			  }
			  if (temp.length > 1){
				   total = total + parseInt(temp.substring(1,2));
			  }
		}
		if ( num.length % 2 == 1 ){
			total = total + parseInt(num.substring(0,1));
		}
		if ( total % 10 != 0 ) {
		  return  "\n" + "O campo '" + campo + "' é inválido." 
			
		}
	}
	else {
		return  "\n" + "O campo '" + campo + "' é obrigatório." 
	}
	return " ";
}

function data_posterior(dia, mes, ano){	
	
	var hoje = new Date();  	
	var hora = hoje.getHours()
	hoje.setHours(23)
	hoje.setMinutes(59)
	hoje.setSeconds(59)
			
	var dataInicio = new Date(ano,mes-1,dia)
	dataInicio.setHours(23)
	dataInicio.setMinutes(59)
	dataInicio.setSeconds(59)
			
	//verifica se a data de início já passou
	if (hoje > dataInicio) {
		return false;
	}else{
		return true;
	}	
}	

function CheckLen (target, quant) 
{
  // variável que mostrará o erro na tela
  var strerror = "" 
  // variável que guarda o texto do índice "0" até "quant"
	// caso o usuário ultrapasse o limite de caracteres 
  var Texto = ""    
  
  StrLen = target.value.length;
  if (StrLen == 1 && target.value.substring(0,1) == " ")
  { 
    target.value = ""
    StrLen = 0
  }
  if (StrLen > quant) 
  {
    //target.value = target.value.substring(0,target.value.length - 1)
   // CharsLeft = 0  
		strerror += "Texto limitado a " + quant + " caracteres."
		alert(strerror)
		texto = target.value.substring(0, quant)
		target.value = texto
	}
}

function pula(txt){			
	var tk;
  var c;
	// Recebe a tela pressionada
	tk = ( (QualNavegador()=="IE") ? event.keyCode : event.which);  
  c=String.fromCharCode(tk);
	c=c.toUpperCase();		
	var vr = txt.value;
	var tam = txt.maxLength	
	
	if( tk == 109 || tk == 188 || tk == 110 || tk == 111 || tk == 223 || tk == 108 ){
		//alert(tk);
		txt.value = vr.substr( 0, vr.length - 1 ); }
	else{		
			if (tk!=8 && tk!=46 && tk!=13){
				//alert(tk);
				if (vr.length == tam){						
					if (txt.form[txt.tabIndex]){
					  if (txt.form[txt.tabIndex].type != "hidden"){
							txt.form[txt.tabIndex].focus();	
							//alert(txt.sourceIndex);
						}												
					}else{
						//alert(txt.tabIndex);
					}						
				}else{
					//alert(txt.maxLength);
					//alert(txt.value.length + "=" + txt.maxLength)
				}	
			}
	}	
}

// Verificar qual navegador
function QualNavegador() 
{
	var s = navigator.appName;
	if ( s == "Microsoft Internet Explorer" )
		return "IE";
	else if ( s == "Netscape" )
		return "NE";
	else
		return "";
}

// Verificar qual a versão do navegador
function QualVersao()
{
	var s = navigator.appVersion;
	if ( QualNavegador() == "IE" )
	{
		var i = s.search("MSIE");
		s=s.substring(i+5);
		i=s.search(".");
		return parseInt(s.substring(0,i+1));
	}
	else if ( QualNavegador() == "NE" )
		return parseInt(s.substring(0,1));
	else
		return 0;
}



