function isIE() {
	return (window.navigator.appVersion.indexOf("MSIE") != -1);
}

dFeatures = 'dialogHeight: 480px; dialogWidth: 640px; dialogTop: 646px; dialogLeft: 4px; edge: Raised; center: Yes; help: Yes; resizable: Yes; status: Yes;';//default features
modalWin = "";
function xShowModalDialog( sURL, vArguments, sFeatures )
    {
    if (sURL==null||sURL=='')
    {
        alert ("Invalid URL input.");
        return false;
    }
    if (vArguments==null||vArguments=='')
    {
        vArguments='';
    }
    if (sFeatures==null||sFeatures=='')
    {
        sFeatures=dFeatures;
    }
	
    if (window.navigator.appVersion.indexOf("MSIE")!=-1)
    {
        window.showModalDialog ( sURL, vArguments, sFeatures );
        return false;
    }
    sFeatures = sFeatures.replace(/ /gi,'');
    aFeatures = sFeatures.split(";");
    sWinFeat = "directories=0,menubar=0,titlebar=0,toolbar=0,";
	
	if (!isIE())
	sWinFeat += "modal,";
	
	var pHeight, pWidth;
    for ( x in aFeatures )
    {
        aTmp = aFeatures[x].split(":");
        sKey = aTmp[0].toLowerCase();
        sVal = aTmp[1];
        switch (sKey)
        {
            case "dialogheight":
                sWinFeat += "height="+sVal+",";
                pHeight = sVal;
                break;
            case "dialogwidth":
                sWinFeat += "width="+sVal+",";
                pWidth = sVal;
                break;
            case "dialogtop":
                sWinFeat += "screenY="+sVal+",";
                break;
            case "dialogleft":
                sWinFeat += "screenX="+sVal+",";
                break;
            case "resizable":
                sWinFeat += "resizable="+sVal+",";
                break;
            case "status":
                sWinFeat += "status="+sVal+",";
                break;
            case "center":
                if ( sVal.toLowerCase() == "yes" )
                {
                    sWinFeat += "screenY="+((screen.availHeight-parseInt(pHeight))/2)+",";
                    sWinFeat += "screenX="+((screen.availWidth-parseInt(pWidth))/2)+",";
                }
                break;
        }
    }
    modalWin=window.open(String(sURL),vArguments,sWinFeat);

	if (vArguments!=null&&vArguments!='')
    {
        modalWin.dialogArguments=vArguments;
    }
}

function DateAdd(startDate, numDays, numMonths, numYears)
{
	var returnDate = new Date(startDate.getTime());
	var yearsToAdd = numYears;
	
	var month = returnDate.getMonth()	+ numMonths;
	if (month > 11)
	{
		yearsToAdd = Math.floor((month+1)/12);
		month -= 12*yearsToAdd;
		yearsToAdd += numYears;
	}
	returnDate.setMonth(month);
	returnDate.setFullYear(returnDate.getFullYear()	+ yearsToAdd);
	
	returnDate.setTime(returnDate.getTime()+60000*60*24*numDays);
	
	return returnDate;

}


function YearAdd(startDate, numYears)
{
		return DateAdd(startDate,0,0,numYears);
}

function MonthAdd(startDate, numMonths)
{
		return DateAdd(startDate,0,numMonths,0);
}

function DayAdd(startDate, numDays)
{
		return DateAdd(startDate,numDays,0,0);
}

function ispunct(c)
{
 if ((c == '.') || (c == ',') || (c == '-') || (c == '+') || 
     (c == '@') || (c == '_') || (c == '"') ||
	 (c == '$') || (c == '#') || (c == '!') ||
	 (c == '%') || (c == '&') || (c == '*') || (c == '(') ||
	 (c == ')') || (c == '=') || (c == '{') || (c == '}') ||
	 (c == '[') || (c == ']') || (c == '/') || (c == '\\') ||
	 (c == ':') || (c == ';') || (c == '>') || (c == '<') || 
	 (escape(c) == '%20') )
 	 return true;
 else
    return false;
}

function isalpha(c)
{
 if (((c >= 'a') && (c <= 'z')) ||
     ((c >= 'A') && (c <= 'Z')))
 	 return true;
 else  
 	 return false;
}

function isdigit(c)
{
 if ((c >= '0') && (c <= '9'))
 	 return true;
 else  
 	 return false;
}

//Formata Moeda

function FormataMoeda(valor, blnUnidade)
{
   var indPontoDec;                // localizacao do ponto decimal
   var valorLimpo = "";            // valor filtrado (apenas numeros e virgula)
   var cont = 0;                   // contador
   var indPonto = 0;               // localizacao do ?ltimo ponto
   var indVirgula = 0;             // localizacao da ?ltima virgula
   var numero = "0123456789"; // dom?nio de d??gitos v??lidos
   var qtPonto = 0;                // qtde de pontos de milhar
   var qtResto = 0;                // resto de indPontoDec / 3
   var limite = 0;                 // limite da coloca??o do ponto de milhar


     // descobre qual o ?ltimo separador que est? sendo utilizado
     indVirgula = valor.lastIndexOf(',');
     indPonto = valor.lastIndexOf('.');
     if (indVirgula == indPonto)
          indPontoDec = -1;
     else
          if (indVirgula > indPonto)
               indPontoDec = indVirgula;
          else
               indPontoDec = indPonto;

     // limpa d??gitos n??o num?ricos do valor
     for (cont=0; cont < valor.length; cont++)
     {
          if (numero.indexOf(valor.charAt(cont)) != -1)
               valorLimpo += valor.charAt(cont);
          // substitui ponto decimal por v?rgula
          if (cont+1 == indPontoDec)
          {
               cont++;
               valorLimpo += ',';
          }
          else
               if ((cont==0) && (indPontoDec==0))
                    valorLimpo += ',';
     }

     if (valorLimpo.indexOf(",") == -1)
          valorLimpo += ",00";
     if (valorLimpo.indexOf(",") == valorLimpo.length-1)
          valorLimpo += "00";
     if (valorLimpo.indexOf(",") == valorLimpo.length-2)
          valorLimpo += "0";

     // retira zeros ? esquerda
     while (valorLimpo.charAt(0)=='0')
          valorLimpo = valorLimpo.substring(1, valorLimpo.length);
		  
     // transforma ",xx" em "0,xx"
     if (valorLimpo.charAt(0)==',')
          valorLimpo = '0' + valorLimpo;

     // coloca separa??o de milhar
     indPontoDec = valorLimpo.lastIndexOf(',');
     qtPonto = Math.floor(indPontoDec/3);
     qtResto = indPontoDec%3;
     if (qtResto==0)
          limite=1;
     else
          limite=0;
	if(valor != ""){
     for (cont=qtPonto-1; cont >= limite; cont--)
          valorLimpo = valorLimpo.substring(0, qtResto + cont*3) + '.' +valorLimpo.substring(qtResto + cont*3, valorLimpo.length);
	}
     // Deixa s? duas casas depois da v?rgula
	 if((valor != "") && (valorLimpo != "")){
	   while (valorLimpo.indexOf(",") != valorLimpo.length-3) 
	         valorLimpo = valorLimpo.substring(0, valorLimpo.length-1);
	}
	
	// Se o valor for igual 0,00 coloca o campo vazio					   
	if (valorLimpo == "0,00") {
		valorLimpo = "";
	}

     return valorLimpo;
}

function FormataDecimal(valor, blnUnidade)
{

   var indPontoDec;                // localizacao do ponto decimal
   var valorLimpo = "";            // valor filtrado (apenas numeros e virgula)
   var cont = 0;                   // contador
   var indPonto = 0;               // localizacao do ?ltimo ponto
   var indVirgula = 0;             // localizacao da ?ltima virgula
   var numero = "0123456789"; // dom?nio de d??gitos v??lidos
   var qtPonto = 0;                // qtde de pontos de milhar
   var qtResto = 0;                // resto de indPontoDec / 3
   var limite = 0;                 // limite da coloca??o do ponto de milhar
/*

     // descobre qual o ?ltimo separador que est? sendo utilizado

     indPontoDec = valor.lastIndexOf(',');

     // limpa d??gitos n??o num?ricos do valor
     for (cont=0; cont < valor.length; cont++)
     {
          if (numero.indexOf(valor.charAt(cont)) != -1)
               valorLimpo += valor.charAt(cont);
          // substitui ponto decimal por v?rgula
          if (cont+1 == indPontoDec)
          {
               cont++;
               valorLimpo += '.';
          }
          else
               if ((cont==0) && (indPontoDec==0))
                    valorLimpo += '.';
     }

     if (valorLimpo.indexOf(".") == -1)
          valorLimpo += ",00";
     if (valorLimpo.indexOf(".") == valorLimpo.length-1)
          valorLimpo += "00";
     if (valorLimpo.indexOf(".") == valorLimpo.length-2)
          valorLimpo += "0";

     // retira zeros ? esquerda
     while (valorLimpo.charAt(0)=='0')
          valorLimpo = valorLimpo.substring(1, valorLimpo.length);

     // transforma ",xx" em "0,xx"
     if (valorLimpo.charAt(0)=='.')
          valorLimpo = '0' + valorLimpo;

*/
	 valorLimpo = valor;
     return valorLimpo;
}

//Formatar Moeda.
//Autor : Claudio Braga Leite.
//Fun??o de formata??o r?pida de valores tipo moeda.
//Essa fun??o n??o precisa trabalhar em conjunto com a fun??o FormataDecimal().
//Exemplos de entrada : "qwe1234.56".
//                      "1234.56".
//                      "1234,56".
//                      "1a2n3n4.,.56".
//Exemplo do retorno  : "1.234,56".
function formatarMoeda(m)
{
    var valorLimpo = "";
	
	valorLimpo = FormataMoeda(FormataDecimal(m, false), false);

	if (valorLimpo == "")
	{
		valorLimpo = "0,00";
	}

    return valorLimpo;
}

//On Blur Moeda.
//Autor : Claudio Braga Leite.
function onBlurMoeda(obj) {
	with (document.forms[0]) {
		obj.value = formatarMoeda(obj.value);
	}
}

//Confirma Excluir.
//Autor : Claudio Braga Leite.
//Fun??o para padronizar as mensagens de exclus?o.
function confirmaExcluir()
{
	return !confirm("Deseja realmente excluir?");
}

//Confirma Excluir.
//Autor : Claudio Braga Leite.
//Fun??o para padronizar as mensagens de exclus?o.
function confirmaExcluir(msg)
{
	return !confirm(msg);
}

function ValidaCPF(s)
{
 var i;
 var c;
 var achou; 
 x = 0;
 soma = 0;
 dig1 = 0;
 dig2 = 0;
 texto = "";
 numcpf1="";
 numcpf = "";

 for (i = 0; i < s.length; i++) {
 	 c = s.substring(i,i+1);
	 if (isdigit(c))
	 	numcpf = numcpf + c;
 }
	 	
 if (numcpf.length != 11) {
 	return false;
 }
 
 /*if (s.indexOf("-")!=9) 
 	 return false; 	 
*/	
 len = numcpf.length; x = len -1;
 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;
  if ((dig1 + "" + dig2) == numcpf.substring(len,len-2)) {
  return true;
 }
 return false;
}


function ValidaCGC(s)
{
 var i;
 var c;
 x = 2;
 soma = 0;
 dig1 = 0;
 dig2 = 0;
 numcgc1="";
 numcgc = "";


 for (i = 0; i < s.length; i++) {
 	 c = s.substring(i,i+1);
	 if (isdigit(c))
	 	numcgc = numcgc + c;
 }
	 	
 if (numcgc.length != 14) {
 	return false;
 }

 /*if (s.indexOf("-")!=9) 
 	 return false; 	 
*/	
 len = numcgc.length;
 for (var i = len - 3; i >= 0; i--) {
  y = numcgc.substring(i,i+1);
  soma = soma + ( y * x);
	if (x == 9) 
		x = 2;
	else
	  x = x + 1;
 }
 dig1 = 11 - (soma % 11);
 if (dig1 == 10) dig1=0 ;
 if (dig1 == 11) dig1=0 ;
 numcgc1 = numcgc.substring(0,len - 2) + dig1 ;
 x = 2; soma=0;
 for (var i=len - 2; i >= 0; i--) {
  soma = soma + (numcgc1.substring(i,i+1) * x);
  	if (x == 9) 
		x = 2;
	else
	  x = x + 1;
 }
 dig2= 11 - (soma % 11);
 if (dig2 == 10) dig2=0;
 if (dig2 == 11) dig2=0;
  if ((dig1 + "" + dig2) == numcgc.substring(len,len-2)) {
  return true;
 }
 return false;
}


function SoNumeros(s)
{
 for (var i=0;i<s.length;i++) { 
 	  c = s.substring(i,i+1); 
	  if (!isdigit(c)) 
	  	  return false;	  
 }
 return true;
}

function SoNumerosLetras(s)
{
 for (var i=0;i<s.length;i++) { 
 	  c = s.substring(i,i+1); 
	  if (!isdigit(c) && !isalpha(c)) 
	  	  return false;	  
 }
 return true;
}

function SoLetras(s)
{
 for (var i=0;i<s.length;i++) { 
 	  c = s.substring(i,i+1); 
	  if (!isalpha(c) && c != ' ') 
	  	  return false;	  
 }
 return true;
}

function ValidaValor(s, prec)
{
 if (s.length - s.lastIndexOf(",") != (prec + 1)) 
 	 return false;
 return true;
}

function DataNasc(s)
{
 var i;
 var c;
 var n_barras;
 var data;
 
hoje = new Date()
teste_ano = hoje.getYear()
teste_dia = hoje.getDay()
teste_mes = hoje.getMonth()
teste_mes = teste_mes + 1
if (teste_dia < 10)
        teste_dia = "0" + teste_dia

if (teste_mes < 10)
        teste_mes = "0" + teste_mes

if (navigator.appName=='Netscape')
	teste_ano= 1900 + teste_ano;
 
 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 (!isdigit(c) && (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 + m + d > teste_ano + teste_mes + teste_dia)
 	return false;

 if (a<1900 || a>2050) 
 	return false;
 if (m==4 || m==6 || m==9 || m==11) {
   if (d==31) 
   	  return false;
 }
// Bissexto
 if (m==2){
	var g=parseInt(a/4)
	if (isNaN(g)) {
		return false;
	}
	if (d > 29){
		return false;
	}
	if (d==29 && ((a/4)!=parseInt(a/4))){
		return false;
	}
 }
 return true;
}

//Verifica se a primeira data ? maior que a segunda data
function verificaTamDatas(d1, d2)
{
  if (!ValidaData(d1) || !ValidaData(d2))
    return false;

  d1_dia	= d1.substring(0,2);
  d1_mes	= d1.substring(3,5);
  d1_ano	= d1.substring(6,10);

  dt_ini = new Date();
  dt_ini.setFullYear(parseInt(d1_ano));
  dt_ini.setMonth(parseInt(d1_mes));
  dt_ini.setDate(parseInt(d1_dia));
  
  d2_dia	= d2.substring(0,2);
  d2_mes	= d2.substring(3,5);
  d2_ano	= d2.substring(6,10);

  dt_fim = new Date();
  dt_fim.setFullYear(parseInt(d2_ano));
  dt_fim.setMonth(parseInt(d2_mes));
  dt_fim.setDate(parseInt(d2_dia));

  return ((dt_ini.getTime() - dt_fim.getTime() < 0) || (dt_ini.getTime() - dt_fim.getTime() == 0));

}

//Comparar duas datas, onde o retorno ?:
// -1 -> Erro caso as datas passadas como parametro estejam no formato errado
//  0 -> d1 < d2
//  1 -> d1 = d2
//  2 -> d1 > d2
function comparaDatas(d1, d2)
{
    if (!ValidaData(d1) || !ValidaData(d2))
    {
        return -1;
    }

    d1_aux = d1.substring(6,10) + d1.substring(3,5) + d1.substring(0,2);
    d2_aux = d2.substring(6,10) + d2.substring(3,5) + d2.substring(0,2);

    if (parseFloat(d1_aux) < parseFloat(d2_aux))
    {
        return 0;
    }
    else if (parseFloat(d1_aux) > parseFloat(d2_aux))
    {
        return 2;
    }
    else
    {
        return 1;
    }
}

// Verifica se a data esta no formato DD/MM/YYYY
function ValidaData(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 (!isdigit(c) && (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>3000) 
 	return false;
 if (m==4 || m==6 || m==9 || m==11) {
   if (d==31) 
   	  return false;
 }
// Bissexto
 if (m==2){
	var g=parseInt(a/4)
	if (isNaN(g)) {
		return false;
	}
	if (d > 29){
		return false;
	}
	if (d==29 && ((a/4)!=parseInt(a/4))){
		return false;
	}
 }
 return true;
}

function ValidaCEP(s)
{
 var i;
 var c;
 var achou;
 
 if (s.length != 9) 
 	 return false;
 achou = false;
 for (i=0; i<s.length; i++) {
 	 c = s.substring(i,i+1); 
     if ( !isdigit(c) && (c != '-') ) 					
	  	  return false;
     if (c == '-') {
	   if (!achou) achou = true;
	   else 
			  return false;
	 }  	 	
 }
 if (s.indexOf("-")!=5) 
 	 return false;
 return true;
}

function ValidaFone(s)
{
 var i;
 var c;
 var achou;
 
 achou = false;
 for (i=0; i<s.length; i++) {
 	 c = s.substring(i,i+1); 
     if ( !isdigit(c) && (c != '-') ) 
	  	  return false;
     if (c == '-') {
	   if (!achou) 
			achou = true;
	   else 
			  return false;
	 }  	 	
 }
 return true;
}

function ValidaTexto(s) // Critica se ha caracteres estranhos
{
 var i;   									  
 var c;
 
 for (i=0;i<s.length;i++) {	
	c = s.substring(i,i+1); 
	if (!( isalpha(c) ||	
	       isdigit(c) ||
		   ispunct(c) ) )  
		return false;
 }						
 return true;
}

function SoTexto(s) // Critica so texto
{
 var i;   									  
 var c;
 
 for (i=0;i<s.length;i++) {	
	c = s.substring(i,i+1); 
	if (isdigit(c)) 
		return false;
 }						
 return true;
}

function ValidaEmail(email) {
        var achou_ponto=false;
        var achou_arroba=false;
        var achou_caracter=false;
        for (var i=0; i<email.length; i++) {
                if (email.charAt(i)=="@") achou_arroba=true;
                else if (email.charAt(i)==".") achou_ponto=true;
                else if (email.charAt(i)!=" ") achou_caracter=true;
        }
        return (achou_ponto & achou_arroba & achou_caracter);
}

// Obtem valor de um grupo de radio buttons de mesmo nome
function ValorRadio(radio)
{
 for (i = 0; i < radio.length; i++)
   if (radio[i].checked) {
   return radio[i].value;
  }
 return "";
}

// Obtem descricao do item selecionado
function GetSelectText(sel)
{
  if(sel.selectedIndex >= 0)
    if (GetSelectValue(sel) == ''){
      return "";
    }
    else{
  	  return sel.options[sel.selectedIndex].text;
  	}
  else
    return "";
}

// Obtem valor do item selecionado
function GetSelectValue(sel)
{
  if(sel.selectedIndex >= 0)    
  	return sel.options[sel.selectedIndex].value;
  else
    return "";
}

// Posiciona o select no item cujo valor eh value
function PosicionaSelect(select, value)
{
	for (var i=0; i <select.length; i++)
		if (select.options[i].value == value) {
			select.selectedIndex = i;
			return;
		}
}

// Seta o radiobutton cujo valor eh value
function SetaRadio(radio, value)
{
 for (i = 0; i < radio.length; i++)
   if (radio[i].value == value) 
   	radio[i].checked = true;
	else
   	radio[i].checked = false;
}

// Seta a checkbox cujo valor eh value
function SetaCheckBox(checkbox, value)
{
 for (i = 0; i < checkbox.length; i++)
   if (checkbox[i].value == value) 
   	checkbox[i].checked = true;
	else
   	checkbox[i].checked = false;
}

// Seta a checkbox cujo checkbox s?o diferentes
function SetaCheckBox2(checkbox, value)
{
   if (checkbox.value == value) 
   	checkbox.checked = true;
	else
   	checkbox.checked = false;
}

function formatavalor(valor) {
//formata valor de 100.000,00 p/ 100000.00
	temp = ""
	tamanho = valor.length
	cont = 1

	for (i=0;i<tamanho;i++) {
		if (valor.substring(i,cont) == ",") {
		}
		else if (valor.substring(i,cont) == ".") {
		}		
		else {
		temp = temp + valor.substring(i,cont)
		}
		cont = cont + 1
	}
	tamanho = temp.length
	temp = temp.substring(0,tamanho-2) + "." + temp.substring(tamanho-2)
	valor =  temp	
	return valor;
}

//Soma a esquerda qualquer car?ter quando necess?rio 
//sWord 	- STRING
//iLength 	- Tamanho desejado
//sChar 	- Caracter a ser preenchido
function addLeftChar(sWord, iLength, sChar) {
	result = sWord;
	if ((sWord.length > iLength)||(iLength<=0)||(sChar.length==0)) {
				result = sWord;
	}
	while (result.length < iLength){ 
		result = sChar + result
	}
	return result;				
}

// Valida??o de hora no formato HH:MM:SS (24 horas)
// Os segundos s?o opcionais.
// Retorna 0 se for tudo ok!
// Retorna 1 se a hora for inv?lida.
// Retorna 2 se os minutos forem invalidos.
// Retorna 3 se os segundos forem inv??lidos.
// Retorna 4 se a hora estiver no formato inv??lido
// Na valida??o do form, deve ser usado o Switch()
function ValidaHora(timeStr) {
var timePat = /^(\d{1,2}):(\d{2})(:(\d{2}))?(\s?(AM|am|PM|pm))?$/;

var matchArray = timeStr.match(timePat);
if (matchArray == null) {
return 4;
}
hour = matchArray[1];
minute = matchArray[2];
second = matchArray[4];
ampm = matchArray[6];

if (second=="") { second = null; }
if (ampm=="") { ampm = null }

if (hour < 0  || hour > 23) {
//alert("Hour must be between 1 and 12. (or 0 and 23 for military time)");
return 1;
}

/*
if (hour <= 12 && ampm == null) {
	if (confirm("Please indicate which time format you are using.  OK = Standard Time, CANCEL = Military Time")) {
		alert("You must specify AM or PM.");
		return 2;
   }
} 

if  (hour > 12 && ampm != null) {
alert("You can't specify AM or PM for military time.");
return false;
}
*/

if (minute<0 || minute > 59) {
//alert ("Minute must be between 0 and 59.");
return 2;
}
if (second != null && (second < 0 || second > 59)) {
//alert ("Second must be between 0 and 59.");
return 3;
}
return 0;
}

// Valida hora.
// Autor : Ivan Magalh?es.
// Fun??o de valida??o de hora.
// Valida??o de hora no formato HH:MM:SS (24 horas)
// Os segundos s?o opcionais.
function validaCampoHora(hora) {

	if (ValidaHora(hora.value) != 0){
		alert('O campo '+hora.title+ ' está com formato inválido.');
		hora.focus();
		hora.select();
		return true;
	}
	return false;
}

// Valida a igualdade das horas.
// Autor : Ivan Magalh?es.
function validaHorasIguais(hora1, hora2) {

	if (comparaHoras(hora1.value, hora2.value) == 0){
		alert('O campo '+hora1.title+ ' não pode ser igual ao campo '+ hora2.title +'.');
		hora2.focus();
		hora2.select();
		return true;
	}
	return false;
}

// Valida a superioridade das horas.
// Autor : Ivan Magalh?es.
function validaHoraMaior(hora1, hora2) {

	if (comparaHoras(hora1.value, hora2.value) == 1){
		alert('O campo '+hora1.title+ ' não pode ser maior que o campo '+ hora2.title +'.');
		hora1.focus();
		hora1.select();
		return true;
	}
	return false;
}

// Valida a superioridade das horas.
// Autor : Ivan Magalh?es.
function validaHoraMenor(hora1, hora2) {

	if (comparaHoras(hora1.value, hora2.value) == 2){
		alert('O campo '+hora1.title+ ' não pode ser menor que o campo '+ hora2.title +'.');
		hora1.focus();
		hora1.select();
		return true;
	}
	return false;
}

// Compara horas.
// Autor : Ivan Magalh?es.
// Fun??o de compara??o de 2 par?metros horas de mesmo formato .
// Valida??o de cada hora no formato HH:MM:SS (24 horas)
// Os segundos s?o opcionais para ambas as horas simultaneamente.
// Retorna 0 se primeira hora for igual a segunda.
// Retorna 1 se a primeira hora for maior que a segunda.
// Retorna 2 se a primeira hora for menor que a segunda.
// Retorna 3 se a primeira hora estiver no formato inv??lido
// Retorna 4 se a segunda hora estiver no formato inv??lido
// Na valida??o do form, deve ser usado o Switch()
function comparaHoras(timeStr1, timeStr2) {
var timePat = /^(\d{1,2}):(\d{2})(:(\d{2}))?(\s?(AM|am|PM|pm))?$/;

var matchArray1 = timeStr1.match(timePat);
var matchArray2 = timeStr2.match(timePat);
if (ValidaHora(timeStr1) == 4) {
return 3;
}
if (ValidaHora(timeStr2) == 4) {
return 4;
}

hour1 = matchArray1[1];
minute1 = matchArray1[2];
second1 = matchArray1[4];
ampm1 = matchArray1[6];
hour2 = matchArray2[1];
minute2 = matchArray2[2];
second2 = matchArray2[4];
ampm2 = matchArray2[6];


if (second1=="") { second1 = null; }
if (ampm1=="") { ampm1 = null; }
if (second2=="") { second2 = null; }
if (ampm2=="") { ampm2 = null; }


if (hour1 > hour2) {
	return 1;
}else if(hour1 < hour2) {
	return 2;
}else{ 
	// As horas(HH) s?o iguais
	if (minute1 > minute2) {
		return 1;
	}else if (minute1 < minute2) {
		return 2;	
	}else{
		// Os minutos s?o iguais
		if (second1 != null && second2 != null && (second1  > second2)) {
			return 1;
		}else if (second1 != null && second2 != null && (second1  < second2)) {
			return 2; 
		}else{
		// timeStr1 = timeStr2 
			return 0;
		}
	}

}

}


// verifica o preenchimento do campo
function validaCampo(campo, valida) {
  
  if (campo.type == 'text'){
    if (campo.value == ''){
      alert('O campo '+campo.title+ ' deve ser preenchido.'); 
	   erros = erros + '- O campo '+campo.title+ ' deve ser preenchido.\n';
      campo.focus();
      campo.select();      
      return true;
    }
  }
  else if (campo.type == 'password'){
    if (campo.value == ''){
      alert('O campo '+campo.title+ ' deve ser preenchido.'); 
	   erros = erros + '- O campo '+campo.title+ ' deve ser preenchido.\n';
      campo.focus();
      campo.select();      
      return true;
    }
  }
  else if (campo.type == 'textarea'){
    if (campo.value == ''){
      alert('O campo '+campo.title+ ' deve ser preenchido.'); 
      campo.focus();
      campo.select();      
      return true;
    }
  }
  else if (campo.type == 'select-one'){
    if (campo.options.length > 1) {
      if (campo.value == '' || campo.value == '-1'){
        alert('O campo '+campo.title+ ' deve ser selecionado.');
        campo.focus();
        return true;
      }
    }
    else{
      if (valida == 'S'){
        if (campo.value == '' || campo.value == '-1'){
          alert('O campo '+campo.title+ ' deve ser selecionado.');
          campo.focus();
          return true;
        }
      }
    }
  }
  
  return false;
}

// verifica o preenchimento do campo tipo radio
function validaCampoRadio(campo) {
  
  marcou = false;
  for (i=0; i<campo.length; i++){
    if (campo[i].checked){
      return false;
    }
  }
  
  if (campo.length>0){
    alert('O campo '+campo[0].title+ ' deve ser escolhido.');
    return true;
  }
  else{
    if (!campo.checked){
      alert('O campo '+campo.title+ ' deve ser escolhido.');
      return true;
    }
  }
  
  
  return false;
}

// retorna true no caso de alguma op??o ter sido checkada
// falso caso nenhuma op??o tenha sido escolhida
function isCampoCheckboxChecked(campo) {
  
  marcou = false;
  for (i=0; i<campo.length; i++){    
    if (campo[i].checked){
     marcou = true;
    }
  }
    
  if (!marcou){
    if (campo.length>0){            
      return false;
    }
    else{
      if (!campo.checked){
        return false;
      }
    }
  }
  
  return true;
}

function validaCampoChave(campo) {
	if (campo.type != 'select-one'){
		if (campo.defaultValue == '') {
			alert("O campo " + campo.title + " precisa ser consultado.");
			campo.focus();
			return true;
		}
		else {
			if (campo.value != campo.defaultValue) {
				alert("O campo " + campo.title + " pesquisado '" + campo.defaultValue + "' não pode ser diferente do campo " + campo.title + " digitado '" + campo.value + "'.");
				campo.focus();
				return true;
			}
		}
	}
	else {
		if (campo[0].defaultSelected == true) {
			alert("O campo " + campo.title + " precisa ser selecionado e consultado.");
			campo.focus();
			return true;
		}
		else {
			if (campo[campo.selectedIndex].defaultSelected != true) {
				for (i=0; i<campo.length; i++) {
					if (campo[i].defaultSelected == true) {
						alert("O campo " + campo.title + " pesquisado '" + campo[i].text + "' não pode ser diferente do campo " + campo.title + " selecionado '" + campo[campo.selectedIndex].text + "'.");
						campo.selectedIndex = i;
						campo.focus();
						return true;
					}
				}
			}
		}
	}
	return false;
}

function validaCampoChave2(campo1, campo2) {
	if (campo1.value != campo2.value) {
		alert("O " + campo1.title + " pesquisado '" + campo2.value + "' não pode ser diferente do " + campo1.title + " digitado '" + campo1.value + "'.");
		campo1.focus();
		return true;
	}
	return false;
}

function validaMinimoCaracteres(campo, tamMin) {
	if (campo.value.length < tamMin) {
		alert("O campo " + campo.title + " deve ser preenchido com no mínimo " + tamMin + " caracteres.");
		campo.focus();
		return true;
	}
	return false;
}

function validaCampoCompleto(campo) {
	if (campo.value.length != campo.maxLength) {
		alert("O campo " + campo.title + " deve ser completamente preenchido.");
		campo.focus();
		return true;
	}
	return false;
}

// verifica o preenchimento do campo tipo checkbox
function validaCampoCheckbox(campo) {
  
  marcou = false;
  for (i=0; i<campo.length; i++){    
    if (campo[i].checked){
     marcou = true;
    }
  }
    
  if (!marcou){
    if (campo.length>0){
      alert('O campo '+campo[0].title+ ' deve ser escolhido.');
      return true;
    }
    else{
      if (!campo.checked){
        alert('O campo '+campo.title+ ' deve ser escolhido.');
        return true;
      }
    }
  }
  
  return false;
}

// verifica se todos  os checkbox foram preenchidos
function validaTodosCamposCheckbox(campo) {

  marcados = 0;  
  entrou = false;
  
  for (i=0; i<campo.length; i++){
    entrou = true;
    if (campo[i].checked){
     marcados++;
    }
  }
  
  if (!entrou){
    if (!campo.checked){
      alert('Todos as opções do campo '+campo.title+ ' devem ser selecionadas.');
      return true;
    }  
  }

  if (campo.length > marcados){
    alert('Todos as opções do campo '+campo[0].title+ ' devem ser selecionadas.');
    return true;
  }
  
  return false;
}

// seleciona todas as op??es de um checkbox
function selecionaTodosCheckbox(campo) {

  entrou = false;
  for (i=0; i<campo.length; i++){
    entrou = true;
    campo[i].checked = true;
  }

  if (!entrou){
    campo.checked = true;
  }

  return;
}

// Alterna todas as op??es de um checkbox do form
function alternaAllCheckboxForm(campo) {
	var flag = campo.checked;

    	for (i=0; i < document.forms[0].elements.length; i++) {
	      	if (document.forms[0].elements[i].type == 'checkbox'){
	      			document.forms[0].elements[i].checked = flag;
	      	}
    	} 
}

// verifica o CPF caso o campo tenha sido preenchido
function validaCampoCpf(campo) {
  if (campo.value != ''){
    if (!ValidaCPF(campo.value)){
	  var msg = campo.title == '' ? 'Campo' : campo.title;
      alert(msg + ' inválido.'); 
      campo.focus();
      campo.select();
      return true;
    }
  }
  return false;
}

//Verifica o CPF com Mascara caso o campo tenha sido preenchido.
function validaCampoCpfComMascara(campo) {
  if (campo.value != '') {
	var cpf = campo.value;
	cpf = cpf.replace(".", "");
	cpf = cpf.replace(".", "");
	cpf = cpf.replace("-", "");
  
    if (!ValidaCPF(cpf)){
	  var msg = 'O campo ' + campo.title;
      alert(msg + ' deve ser válido.'); 
      campo.focus();
      campo.select();
      return true;
    }
  }
  return false;
}

// verifica o CNPJ caso o campo tenha sido preenchido
function validaCampoCnpj(campo) {
  
  if (campo.value != ''){
    if (!ValidaCGC(campo.value)){
	  var msg = 'O campo ' + campo.title;
      alert(msg + ' deve ser válido.');
      campo.focus();
      campo.select();
      return true;
    }
  }

  return false;
}

// verifica o Per?odo(mm/aaaa) caso o campo tenha sido preenchido
function validaCampoPeriodo(campo) {
  
  if (campo.value != ''){
    if (!ValidaData("01/" + campo.value)){
      alert('O campo '+campo.title+ ' não foi preenchido corretamente.');
      campo.focus();
      campo.select();
      return true;
    }
  }

  return false;
}
// verifica os campos Periodo caso tenham sido preenchidos
function comparaCampoPeriodoMenor(campo1, campo2) {
  
  if (campo1.value != '' && campo2.value != ''){
    if (comparaDatas("01/"+campo1.value, "01/"+campo2.value) == 2){  
      alert('O campo '+campo2.title+ ' não pode ser anterior a '+campo1.title+'.');
      campo2.focus();
      return true;
    }    
  }

  return false;
}


// verifica o DATA caso o campo tenha sido preenchido
function validaCampoData(campo) {
  
  if (campo.value != ''){
    if (!ValidaData(campo.value)){
      alert('O campo '+campo.title+ ' não foi preenchido corretamente.');
      campo.focus();
      campo.select();
      return true;
    }
  }

  return false;
}

// verifica o DATA caso o campo tenha sido preenchido
function comparaCampoData(data1, data2) {
  
  if (data1.value != '' && data2.value != ''){
    if (comparaDatas(data1.value, data2.value) == 2){
      alert('O campo '+data1.title+ ' não pode ser posterior a '+data2.title+'.');
      data1.focus();
      return true;
    }
  }

  return false;
}

// verifica o DATA caso o campo tenha sido preenchido
function comparaCampoDataMenor(data1, data2) {
  
  if (data1.value != '' && data2.value != ''){
    if (comparaDatas(data1.value, data2.value) == 2){  
      alert('O campo '+data2.title+ ' não pode ser anterior a '+data1.title+'.');
      data2.focus();
      return true;
    }    
  }

  return false;
}


// verifica se ? n??mero o campo preenchido
function validaCampoNumero(campo) {
  
  if (campo.value != ''){
    if (!SoNumeros(campo.value)){
      alert('O campo '+campo.title+ ' deve ser preenchido apenas com números.');
      campo.focus();
      campo.select();      
      return true;
    }
  }

  return false;
}

function comparaCampoValorMenor(valor1, valor2) {
  
  if (valor1.value != '' && valor2.value != ''){
    
    if (parseFloat(formataNumero(vazio(valor1.value), "2", false, ".")) > parseFloat(formataNumero(vazio(valor2.value), "2", false, "."))){
      alert('O campo '+valor2.title+ ' não pode ser menor que o campo '+ valor1.title +'.');
      valor2.focus();
      return true;
    }    
  }

  return false;
}


// verifica se ? um ANO v??lido
function validaCampoAno(campo) {
  
  if (campo.value != ''){
    if (campo.value.length < parseInt(4)){
      alert('O campo '+campo.title+ ' deve ser preenchido com no minimo 4 caracter(es).');
      campo.focus();
      campo.select();      
      return true;
    }
    
    if (campo.value < 1900 || campo.value > 2100){
      alert('O campo '+campo.title+ ' deve ser um ano de 1900 a 2100.');
      campo.focus();
      campo.select();
      return true;        
    }
  }

  return false;
}

// verifica se ? n??mero o campo preenchido
function validaTamanhoCampo(campo, tam) {
  
  if (campo.value != ''){
    if (campo.value.length < parseInt(tam)){
      alert('O campo '+campo.title+ ' deve ser preenchido com no minimo '+tam+' caracter(es).');
      campo.focus();
      campo.select();
      return true;
    }
  }

  return false;
}

// valida um tamanho m??ximo de um campo - muito usado no caso de um textarea, pois este n??o possui maxlength
function validaTamanhoMaxCampo(campo, tam) {
  
  if (tam=='')
    tam = 255;
  
  if (campo.value != ''){
    if (campo.value.length > parseInt(tam)){
      alert('O campo '+campo.title+ ' deve ser preenchido com no máximo '+tam+' caracter(es).');
      campo.focus();
      campo.select();
      return true;
    }
  }

  return false;
}

// habilita todos os campos existentes no formul?rio recebido
function habilitaCamposForm(formName) {
  for (i=0; i < formName.elements.length; i++) {
    if (formName.elements[i].type != 'hidden') {
	  formName.elements[i].disabled = false;
    }
  }
}

// limpa todos os campos existentes no formul?rio recebido
function limpaCamposForm(formName) {
  for (i=0; i < formName.elements.length; i++){
    if (formName.elements[i].type != 'hidden') {
      if (formName.elements[i].type != 'button'){
        if (formName.elements[i].type != 'submit'){
	      formName.elements[i].value = '';
	    }
	  }
    }
  }
}

// limpa todos os campos existentes no formul?rio recebido
// inclusive os campos "hidden"
function limpaCamposForm2(formName) {
  for (i=0; i < formName.elements.length; i++) {
    if (formName.elements[i].type != 'button') {
      if (formName.elements[i].type != 'submit') {
        formName.elements[i].value = '';
      }
    }
  }
}

// imprime o frame corrente
function imprimeTelaCorrente(){
  if(confirm("O documento que ser? impresso corresponde as informa??es contidas na p?gina corrente. Deseja prosseguir?") == false) {
    return;
  }
  else {
    for (i=0; i < document.forms[0].elements.length; i++) {
      if (document.forms[0].elements[i].type == 'button' || document.forms[0].elements[i].type == 'submit'){
        document.forms[0].elements[i].style.visibility = 'hidden';
      }
    }

    window.print();

    for (i=0; i < document.forms[0].elements.length; i++) {
      if (document.forms[0].elements[i].type == 'button' || document.forms[0].elements[i].type == 'submit'){
        document.forms[0].elements[i].style.visibility = 'visible';
      }
    }    
  }
}

//Bloqueia os bot?es na hora do submit
function lockButtons(formName) {
  for (i=0; i < formName.elements.length; i++) {
    if (formName.elements[i].type == 'button' || formName.elements[i].type == 'submit'){
      formName.elements[i].disabled = true;
    }
  }
}
//Desbloqueia os bot?es
function unlockButtons(formName) {
  for (i=0; i < formName.elements.length; i++) {
    if (formName.elements[i].type == 'button' || formName.elements[i].type == 'submit'){
      formName.elements[i].disabled = false;
    }
  }
}

// FUN??O QUE DEVE SER UTILIZADA NO EVENTO ONKEYPRESS DE UM OBJETO TEXTO
// EXEMPLO DE USO: onKeyPress="return validaNumero(this, event)"
// @autor: Arthur Bellieny
function validaNumero(obj,evt) {
	if (isIE()) {
		var charCode = evt.keyCode;
		if (charCode == 32) return false;
		if (isNaN(String.fromCharCode(charCode))) return false;
		return true;
	}
}

//Fun??o Digita Nada.
function digitaNada(obj, evt) {
	return false;
}

// FUN??O QUE DEVE SER UTILIZADA NO EVENTO ONKEYPRESS DE UM OBJETO TEXTO
// EXEMPLO DE USO: onkeypress="return(currencyFormat(this,'.',',',event))";
// fls: objeto texto
// milSep: separador de milhar
// decSep: separador de casas decimais
// e: evento
// @autor: Arthur Bellieny
function currencyFormat(fld, milSep, decSep, e) {
	var MAXIMO_VALOR = 18;
	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 = fld.value.length;
	
	if (len >= MAXIMO_VALOR) return false;
	
	for(i = 0; i < len; i++)
		  if ((fld.value.charAt(i) != '0') && (fld.value.charAt(i) != decSep)) break;
    aux = '';
	for(; i < len; i++)
		  if (strCheck.indexOf(fld.value.charAt(i))!=-1) aux += fld.value.charAt(i);
	aux += key;
	len = aux.length;
	if (len == 0) fld.value = '';
	if (len == 1) fld.value = '0'+ decSep + '0' + aux;
	if (len == 2) fld.value = '0'+ decSep + aux;
	if (len > 2) {
	   aux2 = '';
	   for (j = 0, i = len - 3; i >= 0; i--) {
	   	   if (j == 3) {
		   	  aux2 += milSep;
			  j = 0;
		   }
		   aux2 += aux.charAt(i);
		   j++;
	   }
       fld.value = '';
	   len2 = aux2.length;
	   for (i = len2 - 1; i >= 0; i--)
		   fld.value += aux2.charAt(i);
	   fld.value += decSep + aux.substr(len - 2, len);
	}
	return false;
}

// FUN??O QUE DEVE SER UTILIZADA NO EVENTO ONKEYPRESS DE UM OBJETO TEXTO
// EXEMPLO DE USO: onkeypress="return(currencyFormatGeneric(this,'.',',','7',3,event))";
// fls: objeto texto
// milSep: separador de milhar
// decSep: separador de casas decimais
// MaxDigitos: quantidade m?xima de d??gitos, incluindo os separadores de milhar e de casas decimais.
// nCasasDec: quantidade de casas decimais
// e: evento
// @autor: Ivan Magalh?es
function currencyFormatGeneric(fld, milSep, decSep,MaxDigitos, nCasasDec, 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 = fld.value.length;
	
	if (len >= MaxDigitos) return false;
	
	for(i = 0; i < len; i++)
		  if ((fld.value.charAt(i) != '0') && (fld.value.charAt(i) != decSep)) break;
    aux = '';
	for(; i < len; i++)
		  if (strCheck.indexOf(fld.value.charAt(i))!=-1) aux += fld.value.charAt(i);
	aux += key;
	
	len = aux.length;

	for(d = 0; d <= (nCasasDec - len); d++){
		if (d == 0) fld.value = '0'+ decSep;
		if (d > 0) fld.value = fld.value + '0';
		if (d == (nCasasDec - len)) fld.value = fld.value + aux;
	}
	if (len > nCasasDec) {
	   aux2 = '';
	   for (j = 0, i = (len - (nCasasDec+1)); i >= 0; i--) {
	   	   if (j == 3) {
		   	  aux2 += milSep;
			  j = 0;
		   }
		   aux2 += aux.charAt(i);
		   j++;
	   }
       fld.value = '';
	   len2 = aux2.length;
	   for (i = len2 - 1; i >= 0; i--)
		   fld.value += aux2.charAt(i);
	   fld.value += decSep + aux.substr(len - nCasasDec, len);
	}
	return false;
}

//---------------
// RECURSO: VALIDA??O E FORMATA??O DE n??meroS
// PAR?METROS: 
// 	1) pStr: CONTE?DO A SER VALIDADO / FORMATADO (obs.: possivelmente proveniente de um element 'text' do html)
//	2) formata: INDICA SE O RETORNO SER? FORMATADO '9.999.999,99'(true) OU n??o (false)
// 	   -> obs.: Para 'formata==true', o separador obrigatoriamente dever? ser ',' (v?rgula)
//	3) separador: INDICA QUAL O SEPARADOR FAR? PARTE DO n??mero FRACION?RIO (caso seja fracion?rio)
//	   -> obs.: Ao enviar o valor do textField para o servlet, utilizar os seguintes par?metros (valor, numCasasDec, false, '.')
// formataNumero(pStr: string, numCasasDec: inteiro, formata: booleano, separador: string)
// @autor: Arthur Bellieny
function formataNumero(pStr, numCasasDec, formata, separador) {

  // Valida o n??mero de casas decimais
  if (isNaN(numCasasDec)) {
	alert("Número de casas decimais inválida na função!"); return "erro";
  }
  // Valida o separador
  if (separador != "." && separador != ",") {
  	 alert("Separador inválido na função!"); return "erro";
  }

  // retira os espa?os vazios antes do n??mero
  var ind = 0;
  tirouZeros = false;
  while (pStr.charAt(ind) == ' ') {
	pStr = (ind+1 > pStr.length) ? "" : pStr.substring(ind+1);
	tirouZeros = true;
  }

  if (tirouZeros && pStr.length == 0) return "erro";

  // verifica se o n??mero ? negativo
  negativo = false;
  if (pStr.length > 0 && pStr.charAt(0) == "-") {
	pStr = pStr.substr(1,pStr.length); // tira o sinal
	negativo = true;
  }
  // valida todos os caracteres, com exce??o dos poss?veis separadores ('.' ou ',')
  for (var i=0; i<pStr.length; i++) {
  	  if (isNaN(pStr.charAt(i)) && pStr.charAt(i) != "." && pStr.charAt(i) != ",") {
	  	 alert("Número inválido!"); return "erro";
	  }
  }
  // recupera o ?ndice do separador natural, se houver
  var inte = "", frac = "";
  var temSep = false;  
  for (var j=pStr.length-1; j>=0; j--) {
  	  if (isNaN(pStr.charAt(j)) && (pStr.charAt(j) == "." || pStr.charAt(j) == ",")) {
	  	 temSep = true;
	  	 break;
	  }
	  else
	  	  frac = pStr.charAt(j) + frac;
  }

  if (!temSep) {
     inte = pStr;
  	 frac = "";	 
  }
  else {
	inte = pStr.substr(0,j);
	if (j == 0) inte = "0";
	else inte = pStr.substr(0,j);
  }

  // retira uma poss?vel formata??o (99.999.999)
  var novoInte = "";
  for (var k=0; k<inte.length; k++)
  	  if (inte.charAt(k) != ".") novoInte += inte.charAt(k);
  if (novoInte != "") inte = novoInte;

  if (isNaN(inte)) {
  	 alert("Número inválido!"); return "erro";
  }
  // parte fracion?ria
  if (isNaN(frac)) {
  	 alert("Número inválido!"); return "erro";
  }

  // forma??o da parte inteira  
  if (formata) {
  	 if (separador != ",") { // separador obrigat?rio para n??meros formatados
	 	alert("Separador inválido para formatação numérica!");return "erro";
	 }
	 var cont = 0; var aux = "";
	 for (var i = inte.length-1; i >= 0; i--) {
	 	 cont++; aux = inte.charAt(i) + aux;
		 if (cont == 3 && i > 0) {
		 	aux = "." + aux;  cont = 0;
		 }
	 }
	 inte = aux;
  }

  // formata??o da parte fracion?ria
  if (numCasasDec > 0) {
     var max = 0;
	 if (numCasasDec > frac.length)
  	 	max = numCasasDec - frac.length;
	 if (inte.length > 0) {
	 	if (frac.length < numCasasDec) {
	 	   for (ind=0; ind < max; ind++)
		   	   frac += "0";
	 	}
		else
			frac = frac.substr(0,numCasasDec);
  	 }
  }
  else {
  	   frac = "";
  	   separador = "";
  }

/*  inteiroZero = true;
  for (var i=0; i<inte.length; i++) {
     if (inte.charAt(i) != '0') { inteiroZero = false; break; }
  }
  fracZero = true;
  for (var i=0; i<frac.length; i++) {
     if (frac.charAt(i) != '0') { fracZero = false; break; }
  }*/
//  if ((inte.length == 0 && frac.length == 0) || (inteiroZero && fracZero)) {
  
  if ((inte.length == 0 && frac.length == 0)) {
	 inte = ""; frac = "";
  	 separador = "";
  }

  if (inte.length > 0 && negativo) inte = "-" + inte;  

  return inte + separador + frac;
}

// retorna um objeto
// campo - nome do objeto
// frame - nome do frame onde esta o objeto
// @autor: Arthur Bellieny
function getElement(campo, frame){
    if (frame != null) {
       if (frame != "[object]") frame = getFrame(frame);  
       return frame.document.all.item(campo);
    } else {
       return document.all.item(campo);
    }
}

// faz o arredondamento de um numero
// num - numero para ser arredondado
// X   - numero de casas
// @autor: Arthur Bellieny
function round(num,X) {
	 X = (!X ? 2 : X);
	 return Math.round(num * Math.pow(10, X )) / Math.pow(10,X);
}

// fun??o para ser usada no metodo de soma
// retorna um valor 0,00 quando o valor for vazio
// val - valor a ser validado
// @autor: Arthur Bellieny
function vazio(val) {
	if (val == "") {
	   return "0,00";
	}
	return val;
}

// fun??o para somar um array de objetos texto
// valores - array de objetos texto
// @autor: Arthur Bellieny
function somaValores(valores) {
	if (valores.length == null){
	   return valores.value;
	}
	var t = 0;
	for (var i = 0; i < valores.length; i++) {
		t += parseFloat(formataNumero(vazio(valores[i].value), "2", false, "."));
	}
	return round(t, 2);
}

// fun??o para ser usada em uma janela modal
// seta o campo de origem com o valor passado como parametro
// codigo - valor a ser setado
// @autor: Arthur Bellieny
function enviarServidor(codigo){
    with (document.forms[0]){	 
	   var handler = window.dialogArguments;
	   var obj = handler.getElement(campoOrigem.value);
	   obj.value = codigo;
	
	   window.close();
	}
}
// valida se um PT esta no formato padr?o
function validaPt(objText){
	return validaCampoMask(objText, MASK_PT);
}

// valida se uma Natureza de Receita esta no formato padr?o
function validaNaturezaReceita(objText){
	return validaCampoMask(objText, MASK_NATUREZA_RECEITA);
}

// valida se uma Natureza de Despesa esta no formato padr?o
function validaNaturezaDespesa(objText){
	return validaCampoMask(objText, MASK_NATUREZA_DESPESA);
}

// fun??o para validar um campo texto
// de acordo com uma mascara
// Arthur Bellieny
function validaCampoMask(objText, mascara){
	var tamMask = mascara.length;
	if (objText.value.length != tamMask){
	   var msg = objText.title == "" ? "Campo" : objText.title;
	   alert(msg + " não esta no formato padrão.\nEx.: " + mascara);
	   objText.focus();
	   return true;
	}
	return false;
}

function replaceSubstring(inputString, fromString, toString) {
   var temp = inputString;
   if (fromString == "") {
      return inputString;
   }
   if (toString.indexOf(fromString) == -1) {
      while (temp.indexOf(fromString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(fromString));
         var toTheRight = temp.substring(temp.indexOf(fromString)+fromString.length, temp.length);
         temp = toTheLeft + toString + toTheRight;
      }
   } else {
      var midStrings = new Array("~", "`", "_", "^", "#");
      var midStringLen = 1;
      var midString = "";
      while (midString == "") {
         for (var i=0; i < midStrings.length; i++) {
            var tempMidString = "";
            for (var j=0; j < midStringLen; j++) { tempMidString += midStrings[i]; }
            if (fromString.indexOf(tempMidString) == -1) {
               midString = tempMidString;
               i = midStrings.length + 1;
            }
         }
      }
      while (temp.indexOf(fromString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(fromString));
         var toTheRight = temp.substring(temp.indexOf(fromString)+fromString.length, temp.length);
         temp = toTheLeft + midString + toTheRight;
      }
      while (temp.indexOf(midString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(midString));
         var toTheRight = temp.substring(temp.indexOf(midString)+midString.length, temp.length);
         temp = toTheLeft + toString + toTheRight;
      }
   }
   return temp; 
}

// retorna a data atual no formato dd/mm/yyyy
function getDataAtual(){
   var d, s;
   d = new Date();
   s =  (d.getDate() < 10 ? "0" : "")+ d.getDate() + "/";
   mes = d.getMonth() + 1;
   s += ( mes < 10 ? "0" : "")+ mes + "/";
   s += d.getFullYear();
   return(s);
}

function tirarMascara(campo) {

 var c, ret;
 ret = "";
 for (i = 0; i < campo.value.length; i++) {
 	 c = campo.value.substring(i,i+1);
	 if (isdigit(c))
	 	ret = ret + c;
 }
 
 return ret;
  
}
// Init padr?o
function init(){
}
function calculaTotalDias(ano,mes,dia){
	ano = ano == "" ? 0 : parseInt(ano);
	mes = mes == "" ? 0 : parseInt(mes);
	dia = dia == "" ? 0 : parseInt(dia);
	return (ano * 360) + (mes * 30) + dia;
} 
// dias = total de dias
function calculaAnoMesDia(dias){
        var ano = parseInt(dias / 360);
        var dia = dias - (ano * 360);
        var mes = 0;
        if (dia > 30) {
            mes = parseInt(dia / 30);
			
            dia = dia - (mes * 30);
        }
        return new Array(ano, mes, dia);
}

// Cria din?micamente uma m?scara espec?fica 
// Autor: Franklin
function fnMascDinam(peStrCampo, peStrMask)
{
	var locObj		 = peStrCampo;
	
	var locStr		 = locObj.value;
	var locCharPos   = locStr.length;
	var locCharInput = String.fromCharCode(event.keyCode);

	var locCharMask  = peStrMask.substring(locCharPos, locCharPos + 1);
	var locCharProx	 = peStrMask.substring(locCharPos + 1, locCharPos + 2);
	var locStrNumeros= '0123456789';
	var locStrLetras = 'abcdefghijklmnopqrstuvxzABCDEFGHIJKLMNOPQRSTUVXZ??????????????????????????????????????';

	// A - Alfanum?rico (Letras, espa?o e n??meros)
	// # - n??meros apenas.

	if (locStr.length >= peStrMask.length)
	{
		locObj.value = locStr.substring(0,peStrMask.length);
		return false;
	}
	
	switch (locCharMask)
	{
		case "#":
		{
			if (locStrNumeros.indexOf(locCharInput) == -1)
			{
				return false;
			}
			break;
		}
		case "A":
		{
			if (locStrLetras.indexOf(locCharInput) == -1)
			{
				return false;
			}
			break;
		}
		default:
		{		
			switch (locCharProx)
			{
				case "#":
				{
					if (locStrNumeros.indexOf(locCharInput) == -1)
					{
						return false;
					}
					break;
				}
				case "A":
				{
					if (locStrLetras.indexOf(locCharInput) == -1)
					{
						return false;
					}
					break;
				}
			}
		}
		locObj.value += locCharMask;
	}
}

//===================================================================================
// Funcoes modificadas por Romulo, evitando varios alets de erro, 
// Acumulando erros em uma unica variavel e apresentando apenas 
// uma vez o Resumo de Erros a cada Evento

var erros = ""; // Variavel que agrega mensagens de Erro

// verifica o preenchimento do campo
function validaCampo2(campo, valida) {
  
  if (campo.type == 'text'){
    if (campo.value == ''){
		if (erros == '') {
            campo.focus();
		}
	   erros = erros + '- O campo '+campo.title+ ' deve ser preenchido.\n';
      return true;
    }
  }
  else if (campo.type == 'textarea'){
    if (campo.value == ''){
		if (erros == '') {
            campo.focus();
		}
      erros = erros + '- O campo '+campo.title+ ' deve ser preenchido.\n';
      return true;
    }
  }
  else if (campo.type == 'select-one'){
    if (campo.options.length > 1) {
      if (campo.value == '' || campo.value == '-1'){
		if (erros == '') {
            campo.focus();
		}
  	    erros = erros + '- O campo '+campo.title+ ' deve ser selecionado.\n';        
        return true;
      }
    }
    else{
      if (valida == 'S'){
        if (campo.value == '' || campo.value == '-1'){
    		if (erros == '') {
                campo.focus();
    		}
           erros = erros + '- O campo '+campo.title+ ' deve ser selecionado.\n';
          return true;
        }
      }
    }
  }
  
  return false;
}

function validaCampoCompleto2(campo) {
	if (campo.value.length != campo.maxLength) {
		if (erros == '') {
            campo.focus();
		}
		erros = erros + '- O campo ' + campo.title + ' deve ser completamente preenchido.\n';
		return true;
	}
	return false;
}

//Verifica o CPF com Mascara caso o campo tenha sido preenchido.
function validaCampoCpfComMascara2(campo) {
  if (campo.value != '') {
	var cpf = campo.value;
	cpf = cpf.replace(".", "");
	cpf = cpf.replace(".", "");
	cpf = cpf.replace("-", "");
  
    if (!ValidaCPF(cpf)){
	  var msg = campo.title == '' ? 'Campo' : campo.title;
      //alert(msg + ' inválido.'); 
		if (erros == '') {
            campo.focus();
		}
      erros = erros + msg + ' inválido.\n';
      return true;
    }
  }
  return false;
}


// verifica o DATA caso o campo tenha sido preenchido
function validaCampoData2(campo) {
  
  if (campo.value != ''){
    if (!ValidaData(campo.value)){
      //alert('O campo '+campo.title+ ' n??o foi preenchido corretamente.');
		if (erros == '') {
            campo.focus();
		}
      erros = erros + '- O campo '+campo.title+ ' não foi preenchido corretamente.\n';
      return true;
    }
  }

  return false;
}
function validaMinimoCaracteres2(campo, tamMin) {
	if (campo.value.length < tamMin) {
		if (erros == '') {
            campo.focus();
		}
		erros = erros + "- O campo " + campo.title + " deve ser preenchido com no mínimo " + tamMin + " caracteres.\n";
		return true;
	}
	return false;
}

function SoLetras2(campo) {
 for (var i=0;i<campo.value.length;i++) { 
 	  c = campo.value.substring(i,i+1); 
	  if (!isalpha(c) && c != ' ') {
    		if (erros == '') {
                campo.focus();
		    }
	  	    erros = erros + "- O campo " + campo.title + " cont?m caracteres diferentes de letras \n";
	  	  return false;	  
	  }
 }
 return true;
}

// verifica o DATA caso o campo tenha sido preenchido
function comparaCampoDataMenor2(data1, data2) {
  
  if (data1.value != '' && data2.value != ''){
    if (comparaDatas(data1.value, data2.value) == 2) {  
		if (erros == '') {
            data2.focus();
		}
      erros = erros + "- O campo " + data2.title + " não pode ser anterior a "+data1.title+".\n";
      return true;
    }    
  }

  return false;
}

function validaCampoChave3(campo) {
	if (campo.type != 'select-one'){
		if (campo.defaultValue == '') {
    		if (erros == '') {
                campo.focus();
    		}
			erros = erros + "- O campo " + campo.title + " precisa ser consultado.\n";
			return true;
		}
		else {
			if (campo.value != campo.defaultValue) {
    		    if (erros == '') {
                    campo.focus();
    		    }
			    erros = erros + "- O campo " + campo.title + " pesquisado " + campo.defaultValue + " não pode ser diferente do campo " + campo.title + " digitado " + campo.value + ".\n";
				return true;
			}
		}
	}
	else {
		if (campo[0].defaultSelected == true) {
    		if (erros == '') {
                campo.focus();
    		}
			erros = erros + "O campo " + campo.title + " precisa ser selecionado e consultado.\n";
			return true;
		}
		else {
			if (campo[campo.selectedIndex].defaultSelected != true) {
				for (i=0; i<campo.length; i++) {
					if (campo[i].defaultSelected == true) {
    		            if (erros == '') {
                            campo.focus();
    		            }
						erros = erros + "O campo " + campo.title + " pesquisado " + campo[i].text + " não pode ser diferente do campo " + campo.title + " selecionado " + campo[campo.selectedIndex].text + ".\n";
						campo.selectedIndex = i;
						return true;
					}
				}
			}
		}
	}
	return false;
}


// Controla a entrada de dados para campos do tipo "NOME".
function fnEvnEntradaAlfa()
{
	var peCharEntrada = String.fromCharCode(event.keyCode);
	
	var locStrExpression	= /[^A-Za-z????????????????????\ ]/i;
	var locRetorno			= peCharEntrada.match(locStrExpression);

	if (locRetorno == null)
	{
		return true;
	}
	else
	{
		event.keyCode = 0;
		return false;
	}
}

// verifica o CNPJ caso o campo tenha sido preenchido
function validaCampoCnpj2(campo) {
  
  if (campo.value != ''){
    if (!ValidaCGC(campo.value)){
	  var msg = campo.title == '' ? '- O campo' : campo.title;
      //alert(msg + ' inválido.'); 
		if (erros == '') {
            campo.focus();
		}
      erros = erros + msg + ' inválido.\n'
      return true;
    }
  }

  return false;
}


// valida um tamanho m??ximo de um campo - muito usado no caso de um textarea, pois este n??o possui maxlength
function validaTamanhoMaxCampo2(campo, tam) {
  
  if (tam=='')
    tam = 255;
  
  if (campo.value != ''){
    if (campo.value.length > parseInt(tam)){
      //alert('O campo '+campo.title+ ' deve ser preenchido com no máximo '+tam+' caracter(es).');
		if (erros == '') {
            campo.focus();
		}
	    erros = erros + '- O campo '+campo.title+ ' deve ser preenchido com no máximo '+tam+' caracter(es).\n';
      return true;
    }
  }

  return false;
}

// verifica se ? um ANO v??lido
function validaCampoAno2(campo) {
  
  if (campo.value != ''){
    if (campo.value.length < parseInt(4)) {
		if (erros == '') {
            campo.focus();
		}
        erros = erros + '- O campo '+campo.title+ ' deve ser preenchido com no minimo 4 caracter(es).\n';
        return true;
    }
    
    if (campo.value < 1900 || campo.value > 2100){
		if (erros == '') {
            campo.focus();
		}
	    erros = erros + '- O campo '+campo.title+ ' deve ser um ano de 1900 a 2100.\n';
        return true;        
    }
  }
}

function reSelecionaCombo(campo) {
	if (campo.type == 'select-one'){
		if (campo[campo.selectedIndex].defaultSelected != true) {
			for (i=0; i<campo.length; i++) {
				if (campo[i].defaultSelected == true) {
					campo.selectedIndex = i;
					break;
				}
			}
		}
	}
}

function validaCampoEmail(campo) {

	if (campo.value.indexOf("@") < 2) {
		alert('O campo ' + campo.title + ' deve ser preenchido corretamente.'); 
		campo.focus();
		campo.select();      
		return true;
	}

	if (campo.value.indexOf(".", campo.value.indexOf("@")) < campo.value.indexOf("@") + 3) {
		alert('O campo ' + campo.title + ' deve ser preenchido corretamente.'); 
		campo.focus();
		campo.select();      
		return true;
	}

	if (campo.value.lastIndexOf(".") > campo.value.length - 3) {
		alert('O campo ' + campo.title + ' deve ser preenchido corretamente.'); 
		campo.focus();
		campo.select();      
		return true;
	}
	
	campo.value = campo.value.toLowerCase();

	return false;
}

function dateDiff(d1, d2) {

	data1Array = d1.split("/");
	data1Dia = data1Array[0];
	data1Mes = data1Array[1] - 1; //Month is 0-11 in JavaScript.
	data1Ano = data1Array[2];
	var data1Date = new Date(data1Ano, data1Mes, data1Dia);

	data2Array = d2.split("/");
	data2Dia = data2Array[0];
	data2Mes = data2Array[1] - 1; //Month is 0-11 in JavaScript.
	data2Ano = data2Array[2];
	var data2Date = new Date(data2Ano, data2Mes, data2Dia);

	var diff = data2Date.getTime() - data1Date.getTime();
	var daysDiff = Math.floor(diff / (1000 * 60 * 60 * 24));

	return daysDiff;
}

function dateInterval(d1, d2) {

	data1Array = d1.split("/");
	data1Dia = data1Array[0];
	data1Mes = data1Array[1] - 1; //Month is 0-11 in JavaScript.
	data1Ano = data1Array[2];
	var data1Date = new Date(data1Ano, data1Mes, data1Dia);

	data2Array = d2.split("/");
	data2Dia = data2Array[0];
	data2Mes = data2Array[1] - 1; //Month is 0-11 in JavaScript.
	data2Ano = data2Array[2];
	var data2Date = new Date(data2Ano, data2Mes, data2Dia);

	var diff = data2Date.getTime() - data1Date.getTime();
	var daysDiff = Math.floor(diff / (1000 * 60 * 60 * 24));

	return daysDiff + 1;
}
//  End -->
