/********************************************************************
*                                                                   *
*       Titulo:     Utilidade.JS                                    *
*                                                                   *
*       Criacao:    2000/08/02                                      *
*       Autor:      Marcelo Sequeiros                               *
*                                                                   *
*       Assunto:    Arquivo de Rotinas utilizadas para validacao    *
*                   de formularios.                                 *
*                                                                   *
*   HEADER (Funcoes que estam dentro deste arquivo                  *
*       -> validaTexto(textField) as boolean                        *
*       -> validaTextoComTamanho(strVal, strLen) as boolean         *
*       -> validaCampoNumerico(numField) as boolean                 *
*       -> possuiCaracterAlfa(strVar) as boolean                    *
*       -> validaMail(mailField) as boolean                         *
*       -> validaRadio(radioField) as variant                       *
*       -> formataValor(num) as string                              *
*       -> validaData(dateField) as variant                         *
*       -> criaDgVerificadorCPF(strCPF) as integer                  *
*       -> validaCPF(cgcField) as boolean                           *
*       -> criaDgVerificadorCGC(strCGC) as integer                  *
*       -> validaCGC(cgcField) as boolean                           *
*       -> validaDataNascimento(dateField) as boolean               *
*                                                                   *
********************************************************************/

// *******************
// *** validaTexto ***
// *******************
//
// Esta rotina verifica se a String passada por parametro
// possui tamanho superior a zero (0)
// Se ok, retorna true
// Se ñ ok, retorna false
//
// Parametros -> Campo a ser verificado
// Retorno    -> true/false
// 
// DataCriacao: 2000/08/02
// Autor:       Marcelo Sequeiros
//
function validaTexto(textField)
{
    var strVal = textField.value;
	
	if(strVal.length > 0)
	{
	    return true;
	} else {
	    return false;
	}
}

// *****************************
// *** validaTextoComTamanho ***
// *****************************
//
// Esta rotina verifica se a String strVal passada
// por parametro possui tamanho igual a strLen
// Se ok, retorna true
// Se ñ ok, retorna false
//
// Parametros -> Campo a ser verificado
// Retorno    -> true/false
// 
// DataCriacao: 2000/08/02
// Autor:       Marcelo Sequeiros
//
function validaTextoComTamanho(strVal, strLen)
{
	if(strVal.length == (strLen * 1))
	{
	    return true;
	} else {
	    return false;
	}
}

// ***************************
// *** validaCampoNumerico ***
// ***************************
//
// Esta rotina verifica se a String passada por parametro
// possui algum caracter naum numerico
// Se possuir valor 100% numerico, retorna true
// Se possuir algum caracter alfa, retorna false
//
// Parametros -> Campo a ser verificado
// Retorno    -> true/false
// 
// DataCriacao: 2000/08/02
// Autor:       Marcelo Sequeiros
//
function validaCampoNumerico(numField)
{
    var strVar = numField.value;
	
	for (var i = 0; i < strVar.length; i++)
	{
	    if (strVar.substring(i,i+1) < "0" || strVar.substring(i,i+1) > "9")
		{
	        return false;
		}
	}
	return true;
}

// ***************************
// *** possuiCaracterAlfa ***
// ***************************
//
// Esta rotina verifica se a String passada por parametro
// possui algum caracter alfa
// Se possuir algum abc..., retorna true
// Se possuir somente numeros, retorna false
//
// Parametros -> string a ser verificada
// Retorno    -> true/false
// 
// DataCriacao: 2000/08/03
// Autor:       Marcelo Sequeiros
//
function possuiCaracterAlfa(strVar)
{
	var retval = false;
	for (var i = 0; i < strVar.length; i++)
	{
	    if (strVar.substring(i,i+1) < "0" || strVar.substring(i,i+1) > "9")
		{
	        retval = true;
	    	break;
		}
	}
	return retval;
}	

// ******************
// *** validaMail ***
// ******************
//
// Esta rotina verifica o formato do mail fornecido
// ela naum verifica se o email estah correto,
// mas evita que valores absurdos sejam passados
// false significa que naum eh valido, true que eh valido
//
// Parametros -> Campo a ser verificado
// Retorno    -> true/false
//
// DataCriacao: 2000/08/02
// Autor:       Marcelo Sequeiros
//
function validaMail(mailField)
{
    var strMail = mailField.value;
	var Parte;
	var Partes;
	var Contador;
	var Temp;
	
	if(strMail.indexOf(" ") >= 0)
	{
		return false;
	} else {
		Contador = 0;
		Partes = strMail.split("@");
		for(var i=0; i<Partes.length; i++)
		{
			if(Partes[i] == "")
			{
			    return false;
			} else {
				Contador++;
			}
		}
		if (Contador != 2)
		{
			return false;
		}

		Contador = 0;
		Temp = Partes[1];
		if((Temp.charAt(0) == ".") || (Temp.charAt(Temp.length) == "."))
		{
			return false;
	    } else {
			Partes = Temp.split(".");
			for(var j=0; j<Partes.length; j++)
			{
				if(Partes[j] == "")
				{
					return false;
				} else {
					Contador++;
				}
			}
			if (Contador < 2)
			{
				return false;
			}
			return true;
		}
	}
}

// *******************
// *** validaRadio ***
// *******************
//
// Esta rotina verifica se ao menos um dos radios
// do grupo esta selecionado. Caso sim, ela
// retorna o valor do radio selecionado, caso 
// nao, retorna false
//
// Parametros -> Grupo de Radios a ser verificado
// Retorno    -> value/false
//
// DataCriacao: 2000/08/02
// Autor:       Marcelo Sequeiros
//
function validaRadio(radioField) 
{
    var varRadio = radioField;
    var checkedButton = false;
    for (i=0; i < varRadio.length; i++)
    {
        if (varRadio[i].checked == "1")
        {
            checkedButton = varRadio[i].value;
        }
    }
    return checkedButton;
}

// ********************
// *** formataValor ***
// ********************
//
// Esta rotina recebe um numero por parametro
// e retorna ele formatado como 999.999.999,99
//
// Parametros -> float
// Retorno    -> string
//
// DataCriacao: 2000/08/02
// Autor:       Marcelo Sequeiros
//
function formataValor(num)
{
    //Multiplica o numero por 100 e transforma em uma String
    num          = num * 100;
    var strValor = num.toString();
    
    //Retira toda a pontuacao
    myRE1     = /\./g;
    myRE2     = /\,/g;
    strValor  = strValor.replace(myRE1, "");
    strValor  = strValor.replace(myRE2, "");
    
    //Adiciona a pontuacao brasileira
    var j     = 1;
    var Valor = "";
    for (var i = (strValor.length-1); i >= 0; i--)
    {
        if((((j - 3) % 3) == 0) && ((j - 3) != 0)) Valor = '.' + Valor;
        
        Valor = strValor.charAt(i) + Valor;
        if(j == 2)      Valor = ',' + Valor;
        j++;
    }
    
    return Valor
}

// ******************
// *** validaData ***
// ******************
//
// Esta rotina recebe uma string representando uma data
// e retorna true caso a data esteja formatada corretamente
// (dd/mm/aaaa) e false caso a data seja inválida.
//
// Parametros -> data
// Retorno    -> true/msg de erro
//
// DataCriacao: 2000/08/02
// Autor:       Marcelo Sequeiros
//
function validaData(dateField)
{
    var strData = dateField.value;
	var mes, dia, ano, bissexto;
	var retval = false;
	var msg;
	if (strData != "")
	{
		if (strData.length != 10 || strData.substring(2,3)!="/" || strData.substring(5,6)!="/")
		{
			msg = "  Formato incorreto. Corrija para dd/mm/aaaa";
		} else {
			//guarda o mes em uma variavel
			mes = strData.substring(3,5);
			if ((!possuiCaracterAlfa(mes)) && parseInt(mes,10) > 0 && parseInt(mes,10) <= 12)
			{
				mes = parseInt(mes,10);
				ano=strData.substring(6,10);
				if ((!possuiCaracterAlfa(ano)) && parseInt(ano,10) >= 0000) 
				{
					if ((parseInt(ano,10) % 4) == 0) 
					{
						bissexto = 1;
					} else {
		            	bissexto = 0;
					}
					dia = strData.substring(0,2);
					if (!possuiCaracterAlfa(dia))
					{
		            	dia = parseInt(dia,10);
		            	if (((mes==1 || mes==3 || mes==5 || mes==7 || mes==8 || mes==10 || mes==12) && (dia >= 1 && dia <= 31)) ||
				               ((mes==4 || mes==6 || mes==9 || mes==11) && (dia >= 1 && dia <= 30)) ||
				               (mes==2 && dia >= 1 && dia <= (28 + bissexto))) 
						{
			               	retval = true;
		            	} else {
							msg = "  O dia fornecido para este mês e ano não é válido.";
						}
					} else {
						msg = "  O dia fornecido não é válido. Ele não pode conter valores não numéricos.";
					}
				} else {
					msg = "  O ano fornecido não é válido. Ele não pode conter valores alfa não numéricos.";
				}
			} else {
				msg = "  O mês fornecido não é válido. Ele deve estar entre 1 e 12.";
			}
		}
	} else {
		retval = true;
	}
    return msg;
}

// ****************************
// *** criaDgVerificadorCPF ***
// ****************************
//
// Esta rotina recebe um CPF sem dg 
// calcula o dg e retorna
// Se o numero passado naum atender aos
// requisitos retorna false
//
// Parametros -> Campo a ser verificado
// Retorno    -> dg (99)/false
// 
// DataCriacao: 2000/08/02
// Autor:       Marcelo Sequeiros
//
function criaDgVerificadorCPF(strCPF)
{
    var dig_1 = 0;
    var dig_2 = 0;
    
    var controle_1  = 10;
    var controle_2  = 11;
    var lsucesso    = 1;
    
    var numero = strCPF;
    
    if(numero.length != 9)
    {
        return false;
    } else {
        for ( i=0 ; i < 9 ; i++) 
        {
            dig_1 = dig_1 + parseInt(numero.substring(i, i+1) * controle_1);
            controle_1 = controle_1 - 1;
        }

        resto = dig_1 % 11;
        dig_1 = 11 - resto;
        if ((resto == 0) || (resto == 1)) 
        {
            dig_1 = 0;
        }
        for ( i=0 ; i < 9 ; i++) 
        {
            dig_2 = dig_2 + parseInt(numero.substring(i, i + 1) * controle_2);
            controle_2 = controle_2 - 1;
        }
        dig_2 = dig_2 + 2 * dig_1;
        resto = dig_2 % 11;
        dig_2 = 11 - resto;
        if ((resto == 0) || (resto == 1)) 
        {
            dig_2 = 0;
        }
        dig_ver = dig_1 + "" + dig_2;
        
        return dig_ver;
    }
}

// *****************
// *** validaCPF ***
// *****************
//
// Esta rotina recebe um CPF
// e verifica atraves do dg 
// se ele eh valido.
// O CPF deve estar no formato 
// 999.999.999-99
//
// Parametros -> Campo a ser verificado
// Retorno    -> true/false
// 
// DataCriacao: 2000/08/02
// Autor:       Marcelo Sequeiros
//
function validaCPF(cpfField)
{
    var strCPF = cpfField.value;
    
    if (strCPF.length < 14)
    {
        //Naum estah corretamente pontuado, ou esta incompleto
        return false;
    }

    //Retira os pontos
    myRE   = /\./g;
    strCPF = strCPF.replace(myRE, "");
    
    if (strCPF.charAt(9) != '-')
    {
        //Naum estah corretamente pontuado, ou esta incompleto
        return false;
    }
    
    if (strCPF.length != 12)
    {
        //Naum estah completo
        return false;
    }
    
    if ((criaDgVerificadorCPF(strCPF.substring(0,9)) == false) || 
        (criaDgVerificadorCPF(strCPF.substring(0,9)) != strCPF.substring(10,12)))
    {
        return false;
    } else {
        return true;
    }
}

// ****************************
// *** criaDgVerificadorCGC ***
// ****************************
//
// Esta rotina recebe um CGC sem dg 
// calcula o dg e retorna
// Se o numero passado naum atender aos
// requisitos retorna false
//
// Parametros -> Campo a ser verificado
// Retorno    -> dg (99)/false
// 
// DataCriacao: 2000/08/04
// Autor:       Marcelo Sequeiros
//
function criaDgVerificadorCGC(strCGC) 
{
    numero = strCGC;
    dig_1  = 0;
    dig_2  = 0;
    controle_1 = 5;
    controle_2 = 6;

    if (numero.length != 12)
    {
        return false;
    } else {
        for ( i=0 ; i < 12 ; i++) 
        {
            dig_1       = dig_1 + parseFloat(numero.substring(i, i+1) * controle_1);
	        controle_1  = controle_1 - 1;
            if (i == 3) 
            {
                controle_1 = 9;
            }
        }
        resto = dig_1 % 11;
        dig_1 = 11 - resto;

        if ((resto == 0) || (resto == 1))
        {
 	        dig_1 = 0;
        }
        
        for ( i=0 ; i < 12 ; i++) 
        {
            dig_2 = dig_2 + parseInt(numero.substring(i, i+1) * controle_2);
	        controle_2 = controle_2 - 1;
            if (i == 4) 
            {
                controle_2 = 9;
            }
        }
        dig_2 = dig_2 + (2 * dig_1);
        resto = dig_2 %11;
        dig_2 = 11 - resto;
        
        if ((resto == 0) || (resto == 1))
        {
 	        dig_2 = 0;
        }
        
        dig_ver = dig_1 + "" + dig_2;
        
        return dig_ver;
    }
}

// *****************
// *** validaCGC ***
// *****************
//
// Esta rotina recebe um CGC
// e verifica atraves do dg 
// se ele eh valido.
// O CPF deve estar no formato 
// 99.999.999/9999-99
//
// Parametros -> Campo a ser verificado
// Retorno    -> true/false
// 
// DataCriacao: 2000/08/04
// Autor:       Marcelo Sequeiros
//
function validaCGC(cgcField)
{
    var strCGC = cgcField.value;
    
    if (strCGC.length < 18)
    {
        //Naum estah corretamente pontuado, ou esta incompleto
        return false;
    }

    //Retira os pontos
    myRE1   = /\./g;
    myRE2   = /\//g;
    strCGC  = strCGC.replace(myRE1, "");
    strCGC  = strCGC.replace(myRE2, "");
    
    if (strCGC.charAt(12) != '-')
    {
        //Naum estah corretamente pontuado, ou esta incompleto
        return false;
    }
    
    if (strCGC.length != 15)
    {
        //Naum estah completo
        return false;
    }
    
    if ((criaDgVerificadorCGC(strCGC.substring(0,12)) == false) || 
        (criaDgVerificadorCGC(strCGC.substring(0,12)) != strCGC.substring(13,15)))
    {
        return false;
    } else {
        return true;
    }
}

// ****************************
// *** validaDataNascimento ***
// ****************************
//
// Esta rotina recebe uma data de nascimento
// e compara com a data de hoje. 
// Se a data de nascimento for anterior a de hoje
// retorna true, caso contrario retorna false.
//
// Parametros -> Campo a ser verificado
// Retorno    -> true/false
// 
// DataCriacao: 2000/08/07
// Autor:       Marcelo Sequeiros
//
function validaDataNascimento(dateField)
{
    if(validaDate(dateField) == true)
    {
        //transforma para o formato JP sem formatacao
        var dataNasc    = new Date();
        var today       = new Date();
        
        dataNasc.setYear(dateField.value.substring(6,10));
        dataNasc.setMonth(dateField.value.substring(3,5));
        dataNasc.setDate(dateField.value.substring(0,2));
        
        if(dataNasc >= today)
        {
            return false;
        } else {
            return true;
        }            
    } else {
        return false;
    }
}

// *******************
// *** validaMoney ***
// *******************
//
// Esta rotina recebe um campo 
// numerico e verificasua formatacao. 
//  a) 999.999.999,99   retorna 1
//  b) 99999999999,99   retorna 2
//  c) 999,999,999.99   retorna 3
//  d) 99999999999.99   retorna 4
//  e) 99999999999999   retorna 5
//  f) 9..9999,99,9.9   retorna 0
//  g) asdfa3432rasff   retorna 0
//
// Parametros -> Campo a ser verificado
// Retorno    -> integer
// 
// DataCriacao: 2000/08/07
// Autor:       Marcelo Sequeiros
//
function validaMoney(moneyField)
{
    var strMoney = moneyField.value;
    //identifica formatacao
    if(strMoney.lastIndexOf(",") == (strMoney.length - 3))
    {
        if(strMoney.indexOf(".") >= 0)
        {
            //valida caso a)
            for(var i = (strMoney.length - 1); i >= 0; i--)
            {
                if((((((strMoney.length-1) - i) - 6) % 4) == 0) && ((((strMoney.length-1) - i) - 6) >= 0))
                {
                    if(strMoney.charAt(i) != '.')
                        return 0;
                }
            }
            return 1;
        } else {
            //caso b)
            return 2;
        }
    } else if (strMoney.lastIndexOf(".") == (strMoney.length - 3)) {
        if(strMoney.indexOf(",") >= 0)
        {
            //valida caso c)
            for(var i = (strMoney.length - 1); i >= 0; i--)
            {
                if((((((strMoney.length-1) - i) - 6) % 4) == 0) && ((((strMoney.length-1) - i) - 6) >= 0))
                {
                    if(strMoney.charAt(i) != ',')
                        return 0;
                }
            }
            return 3;
        } else {
            //caso d)
            return 4;
        }
    } else {
        return 0;
    }
}

function formataFloat(strNum, cod)
{
    
}