/********************************************************************************
'--
'-- Arquivo: javafunc.js
'-- Objetivo:	Funções comuns:
'--				1º isEmpty - Se o Campo está vazio;
'--				2º isCNPJ - Se o CNPJ é válido;
'--				3º isCPF - Se o CPF é válido;
'--				4º isDate - Se a Data é válida;
'--				5º isChar - Se o Campo contém caracteres válidos;
'--				6º isEmail - Se o Email é válido; 
'--				7º Compare - Se 2 Campos são iguais; 
'--				8º isNum - Se o Campo é numérico; 
'--				9º Trim - Remove espaços a direita e a esquerda;
'--				10º RTrim - Remove espaços a direita;
'--				11º LTrim - Remove espaços a esquerda;
'--				12º Len - Retorna o comprimento de uma string;
'--				13º Left - Retorna um determinado número de caracteres a esquerda;
'--				14º Right - Retorna um determinado número de caracteres a direita;
'--				15º Mid - Retorna um determinado número de caracteres
'--				16º Find - Retorna true se achar uma string em uma expressão;
'--				17º Replace - Substitui uma string em uma expressão;
'--
'********************************************************************************/

/*--------------------------------------------------------------------------------
--
-- Função: isEmpty
-- Objetivo: Verifica se um elemento está vazio.
-- Entrada: Campo, label (Opcional - Nome descritivo para um elemento)
-- Retorno: true ou false
-- Observação:
--------------------------------------------------------------------------------*/
function isEmpty(Campo) {
	
	if (Trim(Campo) == "") {
		return true;
		}
	return false;
}

/*--------------------------------------------------------------------------------
--
-- Função: isCNPJ
-- Objetivo: Verifica se um CNPJ é válido.
-- Entrada: Campo (elemento CNPJ)
-- Retorno: true ou false
-- Observação:
--------------------------------------------------------------------------------*/
function isCNPJ(Campo) {

//Verifica se o Campo não está vazio.
if(isEmpty(Campo)) {
	return false;
}

var StrCNPJ = Trim(Campo);
var vaCharCNPJ = false;
var DataPat  = /^(\d{2}).(\d{3}).(\d{3})\/(\d{4})-(\d{2})/;
var DataPat2 = /^(\d{14})/;

var matchArray   = StrCNPJ.match(DataPat);
var matchArray2  = StrCNPJ.match(DataPat2);

if (matchArray == null && matchArray2 == null) {
return false;
} 
else if(matchArray != null) {
StrCNPJ = matchArray[1] + matchArray[2] + matchArray[3] + matchArray[4] + matchArray[5] ;
}
else if(matchArray2 != null) {
StrCNPJ = matchArray2[1];
}   

      var Ref_String="1234567890";
      for (Count=0; Count < StrCNPJ.length; Count++)
      {
       TempChar= StrCNPJ.substring (Count, Count+1);
       if (Ref_String.indexOf (TempChar, 0)==-1)
        {
            return false;
         }
      }4

      var varFirstChr = StrCNPJ.charAt(0);
      var vlMult,vlControle,s1, s2 = "";
      var i,j,vlDgito,vlSoma = 0;
      for ( var i=0; i<=13; i++ ) {

        var c = StrCNPJ.charAt(i);
        if( ! (c>="0")&&(c<="9") )
        {
      return false; }
        if( c!=varFirstChr ) { vaCharCNPJ = true; }
      }
      if( ! vaCharCNPJ ) {
      return false ;
      }


      s1 = StrCNPJ.substring(0,12);
      s2 = StrCNPJ.substring(12,15);
      vlMult = "543298765432";
      vlControle = "";
      for ( j=1; j<3; j++ ) {


       vlSoma = 0;
       for ( i=0; i<12; i++ )
        { vlSoma += eval( s1.charAt(i) )* eval( vlMult.charAt(i) );}
         if( j == 2 ){ vlSoma += (2 * vlDgito); }
         vlDgito = ((vlSoma*10) % 11);
         if( vlDgito == 10 ){ vlDgito = 0; }
         vlControle = vlControle + vlDgito;
         vlMult = "654329876543";
      }
      if( vlControle != s2 ) {
      return false; 
      }
      else {
      return true; 
      }      
}
//********************************************************************************

/*--------------------------------------------------------------------------------
--
-- Função: isCPF
-- Objetivo: Verifica se o Campo CPF tem um CIC/CPF válido.
-- Entrada: Campo
-- Retorno: true ou false
-- Observação:
--------------------------------------------------------------------------------*/
function isCPF(Campo) 
{
	//Verifica se o Campo não está vazio.
	if(isEmpty(Campo)) {
		return false;
	}
	
	var CPF = new String(Campo);
	var new_CPF = "";
	var digitsInCIC = 11;
    var digito = new Array(digitsInCIC);
    var dv = new Array(2);
    var aux = 0;
    var i = 0;

    // Retira os caracteres especiais
    for (i=0; i<=(CPF.length-1); i++) {
		if ((CPF.substring(i,i+1) != "-") && (CPF.substring(i,i+1) != ".")) {
        	new_CPF = new_CPF + CPF.substring(i,i+1);
		}
    }
	CPF = new_CPF;
		
    // Se tiver menos de digitsInCIC posicoes, completa com zeros à frente
    if (CPF.length < digitsInCIC-1) 
    {
		CPF = "0000000000" + CPF;
	    CPF = CPF.substring(CPF.length - digitsInCIC, CPF.length);
    }
	    
    // Separa os dígitos (12 dígitos no máximo)
    for (i=0; i<=(CPF.length-1); i++) 
    {
        digito[i]=CPF.substring(i,i+1);
    }
        
    // Calcula o primeiro dígito verificador
    for (i=0; i<=8; i++) 
    {
	    aux += (digito[i] * (10-i));
    }
        
    if (((aux%digitsInCIC)==0) | ((aux%digitsInCIC)==1)) 
    {
        dv[0] = 0;
    } 
    else 
    {
	    dv[0] = digitsInCIC - (aux%digitsInCIC);
    }
        
    // Se o primeiro dígito não valer, pára por aqui
    if (dv[0] != digito[9]) 
    {
		return false;
    }
        
    // Calcula o segundo dígito verificador
    aux = 0;
	for (i=0; i<=8; i++) 
	{
       aux += (digito[i] * (digitsInCIC-i));
    }
    aux += dv[0] * 2;
        
    if (((aux%digitsInCIC)==0) | ((aux%digitsInCIC)==1)) 
    {
       dv[1] = 0;
    } 
    else 
    {
       dv[1] = digitsInCIC - (aux%digitsInCIC);
    }
        
    // Se o segundo dígito não valer, pára por aqui
    if (dv[1] != digito[10]) 
    {
		return false;
    }
        
    // Se chegou até aqui, não há por que não dizer
    // que o CPF não é válido
    return true;
        
}  

/*--------------------------------------------------------------------------------
--
-- Função: isDate
-- Objetivo: Verifica se uma data é válida através dos 3 Campos de uma data (ano, mes e ano).
-- Entrada: ano, mes e ano
-- Retorno: true ou false
-- Observação:
--------------------------------------------------------------------------------*/
function isDate(s)
{
 var i;
 var c;
 var n_barras;
 var data;
 
 n_barras = 0;						  
 if (s.length != 10)
 	 return false; 
 for(i=0; i<s.length; i++) {
   c = s.substring(i,i+1);
   if (c == "/") 
		n_barras++;
   if (n_barras > 2)  
		return false;	 
   if (!isNum(c,false) && (c != "/"))  
		return false; 	  				  
 }
 if (n_barras != 2)  
 	 return false;
 
 if ( (s.indexOf("/") != 2) || (s.lastIndexOf("/") != 5) )  
 	 return false;
	 
 d = s.substring(0, 2)// dia
 m = s.substring(3, 5)// mes
 a = s.substring(6, 11)// ano
 if (m<1 || m>12) 
   return false;
 if (d<1 || d>31) 
 	return false;

 if (a<1900 || a>2050) 
 	return false;
 if (m==4 || m==6 || m==9 || m==11) {
   if (d==31) 
   	  return false;
 }
 if (m==2 && d>29) {
 	return false;
 }
 return true;
}

/*--------------------------------------------------------------------------------
--
-- Função: isChar
-- Objetivo: Uma string pode conter somente caracteres de A-Z e de 0-9
-- Entrada: Campo
-- Retorno: true ou false
-- Observação:
--------------------------------------------------------------------------------*/
function isChar(Campo) {

	if (isEmpty(Campo)==false) {

		var str = Trim(Campo);
	  
		// Retorna false se os caracteres não forem a-z, A-Z, ou um espaço.
		for (var i = 0; i < str.length; i++) {
			var ch = str.substring(i, i + 1);
			if ((ch < "a" || "z" < ch) && (ch < "A" || "Z" < ch) && (ch < "0" || "9" < ch)) {
				return false;
			}
		}
		return true;
	}
}

/*--------------------------------------------------------------------------------
--
-- Função: isEmail
-- Objetivo:	Verifica se o email é válido
--				1º Se há arroba e ponto
--				2º Se começa com arroba ou com ponto
--				3º Se termina com ponto ou com arroba
--				3º Se há mais de uma arroba
-- Entrada: Campo
-- Retorno: true ou false
-- Observação:
--------------------------------------------------------------------------------*/
function isEmail(Campo) {

	if(isEmpty(Campo)==false) {
		var email = Trim(Campo)
		
		//Verfica se há arroba e ponto
		if ((email.indexOf('@',0) == -1) || (email.indexOf('.',0) == -1)) {
			return false;
		}

		//Verifica se começa com arroba ou com ponto
		if ((email.indexOf('@',0) == 0) || (email.indexOf('.',0) == 0)) {
			return false;
		}
			
		//Verifica se termina com ponto ou com arroba
		if ((email.indexOf('@',0) == email.length - 1) || (email.indexOf('.',0) == email.length - 1)) {
			return false;
		}

		//Verifica se há mais de uma arroba
		if (email.indexOf('@') != email.lastIndexOf('@')) {
			return false;
		}
		
		return true;
	}
}

/*--------------------------------------------------------------------------------
--
-- Função: isNum
-- Objetivo: Valida se um Campo contém um valor é numérico, seja ele inteiro ou real.
-- Entrada: Campo,bNotDecimal (se true o valor terá de ser inteiro, caso contrário, o valor pode ser real)
-- Retorno: true ou false
-- Observação:
--------------------------------------------------------------------------------*/
function isNum(Campo,bNotDecimal) {
	if (isEmpty(Campo)) {
		return false;
	}

	if (bNotDecimal) {
		// Valor deve ser númerico e inteiro
		if (isNaN(Campo) || (parseFloat(Campo)!=parseInt(Campo))) {
			return false;
		}
	}
	else
	{
		// Valor deve ser númerico e pode ser real
		if (isNaN(parseFloat(Campo))) {
			return false;
		}
	}
	return true;
}
					
/*--------------------------------------------------------------------------------
--
-- Função: Trim
-- Objetivo: Verifica se a string está vazia ou tem espaços a direita ou a esquerda
-- Entrada: str (uma string)
-- Retorno: true ou false
-- Observação:
--------------------------------------------------------------------------------*/
function Trim(str) {
	return RTrim(LTrim(str));
}

/*--------------------------------------------------------------------------------
--
-- Função: RTrim
-- Objetivo: Verifica se a string está vazia ou tem espaços a direita
-- Entrada: str (uma string)
-- Retorno: true ou false
-- Observação:
--------------------------------------------------------------------------------*/
function RTrim(str) {
var whitespace = new String(" \t\n\r");
var s = new String(str);
	if (whitespace.indexOf(s.charAt(s.length-1)) != -1) {
		var i = s.length - 1;
        while (i >= 0 && whitespace.indexOf(s.charAt(i)) != -1) {
			i--;
            s = s.substring(0, i+1);
		}
    }
    return s;
}

/*--------------------------------------------------------------------------------
--
-- Função: LTrim
-- Objetivo: Verifica se a string está vazia ou tem espaços a esquerda
-- Entrada: str (uma string)
-- Retorno: true ou false
-- Observação:
--------------------------------------------------------------------------------*/
function LTrim(str) {
var whitespace = new String(" \t\n\r");
var s = new String(str);
	if (whitespace.indexOf(s.charAt(0)) != -1) {
		var j=0, i = s.length;
		while (j < i && whitespace.indexOf(s.charAt(j)) != -1) {
			j++;
            s = s.substring(j, i);
		}
	}
    return s;
}

/*--------------------------------------------------------------------------------
--
-- Função: Len
-- Objetivo: retorna o tamanho de uma string
-- Entrada: str (uma string)
-- Retorno: true ou false
-- Observação:
--------------------------------------------------------------------------------*/
function Len(str) {
	return String(str).length;
}

/*--------------------------------------------------------------------------------
--
-- Função: Left
-- Objetivo: Retorna um determinado número de caracteres do lado esquerdo de uma string.
-- Entrada: str (uma string), n (nº de caracteres)
-- Retorno: true ou false
-- Observação:
--------------------------------------------------------------------------------*/
function Left(str, n) {
    if (n <= 0)     // Invalid bound, return blank string
		return "";
    else if (n > String(str).length)   // Invalid bound, return
        return str;                // entire string
    else // Valid bound, return appropriate substring
        return String(str).substring(0,n);
}

/*--------------------------------------------------------------------------------
--
-- Função: Right
-- Objetivo: Retorna um determinado número de caracteres do lado direito de uma string.
-- Entrada: str (uma string), n (nº de caracteres)
-- Retorno: true ou false
-- Observação:
--------------------------------------------------------------------------------*/
function Right(str, n) {
    if (n <= 0)     // Invalid bound, return blank string
       return "";
    else if (n > String(str).length)   // Invalid bound, return
       return str;                     // entire string
    else { // Valid bound, return appropriate substring
       var iLen = String(str).length;
       return String(str).substring(iLen, iLen - n);
    }
}

/*--------------------------------------------------------------------------------
--
-- Função: Mid
-- Objetivo: Retorna um determinado número de caracteres de uma string.
-- Entrada: str (uma string), start (posição inicial),len (nº de caracteres)
-- Retorno: true ou false
-- Observação:
--------------------------------------------------------------------------------*/
function Mid(str, start, len) {
    // Make sure start and len are within proper bounds
    if (start < 0 || len < 0) return "";

    var iEnd, iLen = String(str).length;
    if (start + len > iLen) {
            iEnd = iLen;
	}
    else
    {
            iEnd = start + len;
	}
    return String(str).substring(start,iEnd);
}

/*--------------------------------------------------------------------------------
--
-- Função: Find
-- Objetivo: Procura um valor em uma expressão.
-- Entrada: expr (expressão a ser pesquisada), achar(valor da procura)
-- Retorno: Se o valor for encontrado, então retorna true, senão false.
-- Observação:
--------------------------------------------------------------------------------*/
function Find(expr, achar) {
var tmpNumStr = new String(expr); //Converte expr em string.
var iStart = tmpNumStr.indexOf(achar); //Retorna a posição da 1º ocorrencia de achar em expr.
	if (iStart > -1) { 
		return true; //O valor foi encontrado na experssão.
	}
	return false;
}

/*--------------------------------------------------------------------------------
--
-- Função: Replace
-- Objetivo: Procura um valor em uma expressão.
-- Entrada: expr (expressão a ser pesquisada), achar(valor da procura), subst(valor de substituição)
-- Retorno: Retorna a expressão com os caracteres substituídos.
-- Observação:
--------------------------------------------------------------------------------*/
function Replace(expr, achar, subst) {
var tmpNumStr = new String(expr); //Converte expr em string.
var iLen = achar.length; //Comprimento do valor a ser substituído.
var iStop = tmpNumStr.length; //Comprimento da expressão.
var iPos1 = tmpNumStr.indexOf(achar); //Posição da 1º ocorrencia de achar em expr.
var iPos2 = 0;
	while (iPos1 > -1) { //Processa enquanto tiver ocorrência de achar em expr.
		iPos2 = iPos1 + iLen; 
		// Concatena nova expressão.
		tmpNumStr = tmpNumStr.substring(0, iPos1) + subst + tmpNumStr.substring(iPos2, iStop);		
		iPos1 = tmpNumStr.indexOf(achar, iPos1+1); //Faz nova busca.
	}
	return tmpNumStr;
}

/*--------------------------------------------------------------------------------
--
-- Função: isChecked
-- Objetivo: Verifica se há pelo menos um item selecionado em um elemento checkbox ou radio.
-- Entrada: Campo, label
-- Retorno: true ou false
-- Observação:
--------------------------------------------------------------------------------*/
function isChecked(Campo, label) {
	for (var i = 0; i < Campo.length; i++) {
		if (Campo(i).checked) {
			return true;
		}
	}
	if (label==null) {
		if (i==0) {
			label = Campo.name;
		} else {
			label = Campo(0).name;
		}
	}

	alert("\nO Campo " + label + " não está selecionado!\n\nPor favor selecione um item no Campo " + label + ".")
	return false;
}

/*--------------------------------------------------------------------------------
--
-- Função: isSelected
-- Objetivo: Verifica se há pelo menos um item selecionado em um elemento menu/list.
-- Entrada: Campo, label
-- Retorno: true ou false
-- Observação:
--------------------------------------------------------------------------------*/
function isSelected(Campo, label) {
	if (Campo.selectedIndex >= 0) {
		return true;
	}
	if (label==null) {
		label = Campo.name;
	}

	alert("\nO Campo " + label + " não está selecionado!\n\nPor favor selecione um item no Campo " + label + ".")
	return false;
}


// [dFilter] - A Numerical Input Mask for JavaScript
// Written By Dwayne Forehand - March 27th, 2003
// Please reuse & redistribute while keeping this notice.

var dFilterStep

function dFilterStrip (dFilterTemp, dFilterMask)
{
    dFilterMask = replace(dFilterMask,'#','');
    for (dFilterStep = 0; dFilterStep < dFilterMask.length++; dFilterStep++)
		{
		    dFilterTemp = replace(dFilterTemp,dFilterMask.substring(dFilterStep,dFilterStep+1),'');
		}
		return dFilterTemp;
}

function dFilterMax (dFilterMask)
{
 		dFilterTemp = dFilterMask;
    for (dFilterStep = 0; dFilterStep < (dFilterMask.length+1); dFilterStep++)
		{
		 		if (dFilterMask.charAt(dFilterStep)!='#')
				{
		        dFilterTemp = replace(dFilterTemp,dFilterMask.charAt(dFilterStep),'');
				}
		}
		return dFilterTemp.length;
}

function dFilter (key, textbox, dFilterMask)
{
		dFilterNum = dFilterStrip(textbox.value, dFilterMask);
		if (key>=96&&key<=105) {
			key -= 48;
		}
		
		if (key==9)
		{
		    return true;
		}
		else if (key==8&&dFilterNum.length!=0)
		{
		 	 	dFilterNum = dFilterNum.substring(0,dFilterNum.length-1);
		}
 	  else if ( ((key>47&&key<58)||(key>95&&key<106)) && dFilterNum.length<dFilterMax(dFilterMask) )
		{
        dFilterNum=dFilterNum+String.fromCharCode(key);
		}

		var dFilterFinal='';
    for (dFilterStep = 0; dFilterStep < dFilterMask.length; dFilterStep++)
		{
        if (dFilterMask.charAt(dFilterStep)=='#')
				{
					  if (dFilterNum.length!=0)
					  {
				        dFilterFinal = dFilterFinal + dFilterNum.charAt(0);
					      dFilterNum = dFilterNum.substring(1,dFilterNum.length);
					  }
				    else
				    {
				        dFilterFinal = dFilterFinal + "";
				    }
				}
		 		else if (dFilterMask.charAt(dFilterStep)!='#')
				{
				    dFilterFinal = dFilterFinal + dFilterMask.charAt(dFilterStep); 			
				}
//		    dFilterTemp = replace(dFilterTemp,dFilterMask.substring(dFilterStep,dFilterStep+1),'');
		}


		textbox.value = dFilterFinal;
    return false;
}

function replace(fullString,text,by) {
// Replaces text with by in string
    var strLength = fullString.length, txtLength = text.length;
    if ((strLength == 0) || (txtLength == 0)) return fullString;

    var i = fullString.indexOf(text);
    if ((!i) && (text != fullString.substring(0,txtLength))) return fullString;
    if (i == -1) return fullString;

    var newstr = fullString.substring(0,i) + by;

    if (i+txtLength < strLength)
        newstr += replace(fullString.substring(i+txtLength,strLength),text,by);

    return newstr;
}