/*
* form.js
* escrito por leandro sa, andre vargas
*
* este js valida formularios automaticamente, para isso basta colocar no tag form o seguinte:
*  onsubmit="return valida(this);"
*
*  e nos campos, colocar as seguintes informacoes:
*  obr - true ou false, indicando se o campo eh obrigatorio ou nao
*  tipo - tipo de critica que deve ser feito no campo,caso haja alguma:
*             cpf,data,email,rg,cnpj,int,float,hora,data-hora,cep,tel,ddd-tel
*  alt - nome completo do campo
*
*
*  Exemplo:
*  <script src="form.js"></script>
*  <form name="formulario" action="script.jsp" method="post" onsubmit="return valida(this);">
*   Nome: <input type="text" name="nome" obr="true" alt="Nome"><br>
*   E-mail: <input type="text" name="email" obr="false" tipo="email" alt="E-mail"><br>
*   <input type="submit" value="Enviar">
*  </form>
*
*
* Nesse exemplo, o campo nome eh obrigatorio e o campo Email nao eh, mas caso seja preenchido
* sera criticado para ver se o email eh valido.
*/
var errorColor = "#CCCCCC";
var defaultColor = "#FFFFFF";
function valida(formulario)
{
	with(formulario)
	{
		var msg = checkCampos(formulario);
		if(msg != "")
		{
			alert("Existe um problema com os seus dados:\n\n"+ msg);
			return false;
		}
		else
		{
			return true;
		}

	}
}

function pegarObjCampo(formulario, campo)
{
    return formulario.elements[campo];
}

function checkCampos(formulario)
{
	var bufferAll = "";
	var tmpRadioCheck = 0;
	var tmpRadioAll = 0;
	var tmpRadioName = "";
	var tmpRadioAlt = "";
	with(formulario)
	{
		var i = 0;
		for(i = 0; i < formulario.elements.length; i++)
		{
			var campo = formulario.elements[i];
			var buffer = "";
			if(tmpRadioAll > 0)
			{
				if(campo.name != tmpRadioName)
				{
					if(tmpRadioCheck == 0)
					{
						buffer = "Selecione uma opção no campo " + tmpRadioAlt + ".";
					}
					tmpRadioCheck = 0; tmpRadioAll = 0;
				}
			}

			if((campo.type == "text") || (campo.type == "password")  || (campo.type == "textarea"))
			{
				if((campo.obr == "true") && (campo.value == ""))
					buffer = "O campo " + campo.alt + " precisa ser preenchido.";
				else if( (campo.value != "") && (campo.maxlength > 0) && (campo.value.length > campo.maxlength))
					buffer = "O campo " + campo.alt + " não pode ter mais que "+ campo.maxlength +" caracteres.";
				else if(campo.value != "")
				{
					if(campo.tipo == "email")
						if(!isValidEmail(campo.value))
							buffer = "O campo " + campo.alt + " não é um email válido.";
					if(campo.tipo == "ncompleto")
						if(!isValidNCompleto(campo.value))
							buffer = "O campo " + campo.alt + " não é válido.";
					if(campo.tipo == "cpf")
						if(!isValidCpf(campo.value))
							buffer = "O campo " + campo.alt + " não é um cpf válido.";
                		}
                    if(campo.tipo == "data6")
                        if(!isValidDate(campo.value))
                            buffer = "O campo " + campo.alt + " não é uma data válida (ddmmaa).";
                    if(campo.tipo == "pontodecimal")
                        if(!isValidPonto(campo.value))
                            buffer = "O campo " + campo.alt + " não é um número decimal válido.";


				if((campo.equal != null) && (campo.equal != ""))
				{
					if(formulario.elements[campo.equal].value != campo.value)
						buffer = "O campo " + campo.alt + " não é igual ao campo "+ formulario.elements[campo.equal].alt +".";
				}

				if((campo.greaterthan != null) && (campo.greaterthan != ""))
				{
				    if(campo.tipo == "data6")
				    {
					   var data1 = campo.value;
					   var data2 = formulario.elements[campo.greaterthan].value;

					   var int1 = data1.substr(4,2) + data1.substr(2,2) + data1.substr(0,2);
					   var int2 = data2.substr(4,2) + data2.substr(2,2) + data2.substr(0,2);

					   if(int2 > int1)
					       buffer = "O campo " + campo.alt + " precisa ser maior que "+ formulario.elements[campo.greaterthan].alt +".";
		            }
				}

			}
			else if(campo.type == "select")
			{
				if((campo.obr == "true") && (campo.selectedIndex <= 0))
					buffer = "Selecione uma opção no campo " + campo.alt + ".";
			}
			else if((campo.type == "checkbox") || (campo.type == "radio"))
			{

				tmpRadioName = campo.name;
				tmpRadioAlt = campo.alt;
				if(campo.obr == "true")
				{
					tmpRadioAll++;
					if(campo.checked)
						tmpRadioCheck++;
				}
			}


			if(buffer != "")
			{
				//campo.style.backgroundColor = errorColor;
				bufferAll += buffer + "\n";
			}
			else
			{
				//campo.style.backgroundColor = defaultColor;
			}
		}
	}
	return bufferAll;
}

function isValidEmail(email)
{
	if((email.indexOf("@") < 0) || (email.indexOf(".") < 0) || (email.indexOf(" ") >= 0))
		return false;
	return true;
}

function isValidDate(data)
{
	if( data.length != 6 )
		return false;
    var dia = data.substr(0,2);
    var mes = data.substr(2,2);
    var ano = 2000 + parseInt(data.substr(4,2));
     //alert(data + "::" + dia + "::" + mes + "::" + ano);
    var dataObj = new Date(ano, (mes-1), dia);

    //alert("dia: " + dia + "::" + dataObj.getDate() + "\n" + "mes: " + mes + "::" + (dataObj.getMonth()+1) + "\n"+ "ano: " + ano + "::" + dataObj.getYear() + "\n");

    if( dia != dataObj.getDate())
        return false;

    if( mes != (dataObj.getMonth()+1))
        return false;

    if( ano != dataObj.getYear())
        return false;


	return true;
}

function isValidPonto(numero)
{
    var temPonto = false;
    for(var i = 0; i < numero.length; i++)
    {
        var ch = numero.charAt(i);
        if(ch == "." && !temPonto)
            temPonto = true;
        else if(ch == "." && temPonto)
            return false;
    }
    return true;

}

function isValidNCompleto(nome)
{
	if((nome.indexOf(" ") <= 0) || (nome.length < 5) )
		return false;
	return true;
}


function isValidCpf(CPF) {

// Verifica se o campo é nulo
if (CPF == '') {
  return false;
}

// Aqui começa a checagem do CPF
var POSICAO, I, SOMA, DV, DV_INFORMADO;
var DIGITO = new Array(10);
DV_INFORMADO = CPF.substr(9, 2); // Retira os dois últimos dígitos do número informado

// Desemembra o número do CPF na array DIGITO
for (I=0; I<=8; I++) {
  DIGITO[I] = CPF.substr( I, 1);
}

// Calcula o valor do 10º dígito da verificação
POSICAO = 10;
SOMA = 0;
   for (I=0; I<=8; I++) {
      SOMA = SOMA + DIGITO[I] * POSICAO;
      POSICAO = POSICAO - 1;
   }
DIGITO[9] = SOMA % 11;
   if (DIGITO[9] < 2) {
        DIGITO[9] = 0;
}
   else{
       DIGITO[9] = 11 - DIGITO[9];
}

// Calcula o valor do 11º dígito da verificação
POSICAO = 11;
SOMA = 0;
   for (I=0; I<=9; I++) {
      SOMA = SOMA + DIGITO[I] * POSICAO;
      POSICAO = POSICAO - 1;
   }
DIGITO[10] = SOMA % 11;
   if (DIGITO[10] < 2) {
        DIGITO[10] = 0;
   }
   else {
        DIGITO[10] = 11 - DIGITO[10];
   }

// Verifica se os valores dos dígitos verificadores conferem
DV = DIGITO[9] * 10 + DIGITO[10];
   if (DV != DV_INFORMADO) {
      return false;
   }
   return true;
}

function isValidCnpj(RecebeCNPJ)
{

	digitos = new Array(14);
	digitos[0] = RecebeCNPJ.charAt(0);
	digitos[1] = RecebeCNPJ.charAt(1);
	digitos[2] = RecebeCNPJ.charAt(2);
	digitos[3] = RecebeCNPJ.charAt(3);
	digitos[4] = RecebeCNPJ.charAt(4);
	digitos[5] = RecebeCNPJ.charAt(5);
	digitos[6] = RecebeCNPJ.charAt(6);
	digitos[7] = RecebeCNPJ.charAt(7);
	digitos[8] = RecebeCNPJ.charAt(8);
	digitos[9] = RecebeCNPJ.charAt(9);
	digitos[10] = RecebeCNPJ.charAt(10);
	digitos[11] = RecebeCNPJ.charAt(11);
	digitos[12] = RecebeCNPJ.charAt(12);
	digitos[13] = RecebeCNPJ.charAt(13);

	var soma = digitos[0] * 5 + digitos[1] * 4 + digitos[2] * 3 + digitos[3] * 2 + digitos[4] * 9 + digitos[5] * 8 + digitos[6] * 7 + digitos[7] * 6 + digitos[8] * 5 + digitos[9] * 4 + digitos[10] * 3 + digitos[11] * 2;
	soma = soma - (11 * parseInt(soma / 11));
        var resultado1 = 0;
	if((soma == 0) || (soma == 1))
	{
		resultado1 = 0;
	}
	else
	{
		resultado1 = 11 - soma;
	}
	if(resultado1 == digitos[12])
	{
		soma = digitos[0] * 6 + digitos[1] * 5 + digitos[2] * 4 + digitos[3] * 3 + digitos[4] * 2 + digitos[5] * 9 + digitos[6] * 8 + digitos[7] * 7 + digitos[8] * 6 + digitos[9] * 5 + digitos[10] * 4 + digitos[11] * 3 + digitos[12] * 2;
		soma = soma - (11 * parseInt(soma/11));
		var resultado2 = 0;
		if((soma == 0) || (soma == 1))
		{
			resultado2 = 0;
		}
		else
		{
			resultado2 = 11 - soma;
		}

		if(resultado2 == digitos[13])
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	else
	{
		return false;
	}


}

function isValidInt(inteiro)
{
	return true;
}

function pularcampo(campo1,campo2, tamanho)
{
	if (campo1.value.length == tamanho)
			campo2.focus();
}

function onlyNumber(event)
{

	if (event.keyCode > 47 && event.keyCode < 58)
	{
		event.returnValue = true;
		return true;
	}
	else
	{
		event.returnValue = false;
		return false;
	}

}

function onlyNumberPoint(event)
{

	if ((event.keyCode > 47 && event.keyCode < 58) || (event.keyCode == 46))
	{
		event.returnValue = true;
		return true;
	}
	else
	{
		event.returnValue = false;
		return false;
	}

}

function putSlash(event, objeto)
{
	if(event.keyCode == 8)
	{
		event.returnValue = false;
		return false;
	}
	else
	{

		if (objeto.value.length == 2)
		{
			if(objeto.value > 31)
			{
				alert('Dia do mês inválido! Digite um número menor ou igual a 31.');
			}
			else
			{
				objeto.value = objeto.value + "/";
			}
		}
		if (objeto.value.length == 5)
		{
			if(objeto.value.substr(3,2) > 12)
			{
				alert('Mês inválido! Digite um número menor ou igual a 12.');
			}
			else
			{
				objeto.value = objeto.value + "/";
			}

		}
		if ((objeto.value.length == 10) && (objeto.tipo == "datetime"))
		{
			if((objeto.value.substr(6,4) < 2002) || (objeto.value.substr(6,4) > 2020))
			{
				alert('Ano inválido! Digite um número entre 2002 e 2020.');
			}
			else
			{
				objeto.value = objeto.value + " ";
			}
		}
		if (objeto.value.length == 13)
		{
			if(objeto.value.substr(11,2) > 23)
			{
				alert('Hora inválida! Digite um número menor ou igual a 23.');
			}
			else
			{
				objeto.value = objeto.value + ":";
			}
		}
		if (objeto.value.length == 16)
		{
			if(objeto.value.substr(14,2) > 59)
			{
				alert('Minuto inválido! Digite um número menor ou igual a 59.');
			}
			else
			{
				objeto.value = objeto.value + ":";
			}
		}

		return true;
	}
}

function putCep(event, objeto)
{
	if(event.keyCode == 8)
	{
		event.returnValue = false;
		return false;
	}
	else
	{

		if (objeto.value.length == 5)
		{
			/*if(objeto.value.substr(3,2) > 12)
			{
				alert('Mês inválido! Digite um número menor ou igual a 12.');
			}
			else
			{*/
				objeto.value = objeto.value + "-";
			//}

		}
		return true;
	}
}

function checkData(objeto)
{


		if (objeto.value.length < 10)
		{
			alert('Digite corretamente a data!');
			return false;
		}
		return true;
}

