//Descrição: Funções reduzidas de verificação
//Pacote: tw Framework
//Copyright: 1996 - 2009 (c) tw Latin America - www.tw.com.br
//Versão: 1.0.0.0

//Verifica se o numero de caracteres de um campo é menor que um número especifico.
//    Se for menor, retorna (false) e exibe um alerta com uma mensagem.
//    Se for maior ou igual, apenas retorna (true).
function twFctCampoCheckMin(ccmCampo, ccmQuantidadeMinima, ccmMensagem, ccmFoco){
	if (ccmCampo.value.length < ccmQuantidadeMinima){ alert(ccmMensagem); if(ccmFoco!=false){ ccmCampo.focus(); } return (false); }
	else { return (true); }
}

//Verifica se o numero de caracteres de um campo exede um número especifico.
//    Se for maior, retorna (false) e exibe um alerta com uma mensagem.
//    Se for menor ou igual, apenas retorna (true).
function twFctCampoCheckMax(ccmCampo, ccmQuantidadeMaxima, ccmMensagem){
	if (ccmCampo.value.length > ccmQuantidadeMaxima){ alert(ccmMensagem); ccmCampo.focus(); return (false); }
	else { return (true); }
}

//Verifica se um valor é um email.
//    Se não for um email, retorna (false).
//    Se for um email, retorna (true).
function twFctIsEmail(ieValor) {
	var ieRegExpEmail = /^[a-zA-Z0-9._-]+@([a-zA-Z0-9.-]{2,}\.)+[a-zA-Z]{2,4}$/;
	return(ieRegExpEmail.test(ieValor));
}


//Valida se um texto é um CPF válido.
//Entradas: (string) no padrão (xxx.xxx.xxx-xx)
//Retorno: (string), retorna o texto formatado.
//Nota: Utilize a função twFctFormataCpf para formatar seu texto. (Arq. twSistemaUtilitarios.js)
function twFctIsCpf(icCpf){

	var icCpfNumero = "";
	var icRegExpCpf = /^\d{3}\.{1}\d{3}\.{1}\d{3}-{1}\d{2}$/;
	var icRegExpSohNumeros = /^\d$/;

	//Verfica se o CPF fornecido esta no padrão (xxx.xxx.xxx-xx)
	if(!icRegExpCpf.test(icCpf)){ return(false); }
	if(icCpf=="111.111.111-11"){ return(false); }
	if(icCpf=="222.222.222-22"){ return(false); }
	if(icCpf=="333.333.333-33"){ return(false); }
	if(icCpf=="444.444.444-44"){ return(false); }
	if(icCpf=="555.555.555-55"){ return(false); }
	if(icCpf=="666.666.666-66"){ return(false); }
	if(icCpf=="777.777.777-77"){ return(false); }
	if(icCpf=="888.888.888-88"){ return(false); }
	if(icCpf=="999.999.999-99"){ return(false); }
	if(icCpf=="000.000.000-00"){ return(false); }
	//Deixa apenas os números
	for(ic_x = 0; ic_x < icCpf.length; ic_x ++)
		if(icRegExpSohNumeros.test(icCpf.charAt(ic_x)))
			icCpfNumero += icCpf.charAt(ic_x).toString();

	var icCpfDigitos = icCpfNumero.substr(9,2);
	var icVerificadorD1 = 0;

	//Inicio: Calculo de verificação
	for (ic_x = 0; ic_x < 9; ic_x++) { icVerificadorD1 += parseInt(icCpfNumero.charAt(ic_x)) * (10 - ic_x); }
	if (icVerificadorD1 == 0){ return(false); }
	icVerificadorD1 = 11 - (icVerificadorD1 % 11);
	if (icVerificadorD1 > 9){ icVerificadorD1 = 0; }
	if (parseInt(icCpfDigitos.charAt(0)) != icVerificadorD1) { return(false); }
	icVerificadorD1 *= 2;
	for (ic_x = 0; ic_x < 9; ic_x++) { icVerificadorD1 += parseInt(icCpfNumero.charAt(ic_x)) * (11 - ic_x); }
	icVerificadorD1 = 11 - (icVerificadorD1 % 11);
	if (icVerificadorD1 > 9){ icVerificadorD1 = 0; }
	if (icCpfDigitos.charAt(1) != icVerificadorD1) { return(false); }
	//Fim: Calculo de verificação

	return(true);
}

//Valida se um texto é um CNPJ válido.
//Entradas: (string) no padrão (xxx.xxx.xxx/xxxx-xx)
//Retorno: (string), retorna o texto formatado.
//Nota: Utilize a função twFctFormataCnpj para formatar seu texto. (Arq. twSistemaUtilitarios.js)
function twFctIsCnpj(icCnpj){

	var icCnpjNumero = "";
	var icRegExpCnpj = /^([0-9]{2}|0[0-9]{2})\.[0-9]{3}\.[0-9]{3}\/[0-9]{4}\-[0-9]{2}$/;
	var icRegExpSohNumeros = /^\d$/;

	//Verfica se o CNPJ fornecido esta no padrão (xxx.xxx.xxx/xxxx-xx)
	if(!icRegExpCnpj.test(icCnpj)){ return(false); }

	//Deixa apenas os números
	for(ic_x = 0; ic_x < icCnpj.length; ic_x ++)
		if(icRegExpSohNumeros.test(icCnpj.charAt(ic_x)))
			icCnpjNumero += icCnpj.charAt(ic_x).toString();

	//Valida o CNPJ
	var icCnpjValido = true;
	for(ic_g = 13; ic_g <= 14; ic_g ++){
		var icCaracterValidador = 0;
		var icIndicador = 2;
		for(ic_f = ic_g; ic_f > 0; ic_f --){
			icCaracterValidador += parseInt(icCnpjNumero.charAt(ic_f - 1)) * icIndicador;
			if(icIndicador > 8){ icIndicador = 2; }
			else { icIndicador ++; }
		}
		icCaracterValidador %= 11;
		if((icCaracterValidador == 0) || (icCaracterValidador == 1)){ icCaracterValidador = 0; }
		else { icCaracterValidador = 11 - icCaracterValidador; }
		if(icCaracterValidador != parseInt(icCnpjNumero.charAt(ic_g))){
			icCnpjValido = false;
			break;
		}
	}
	return(icCnpjValido);
}


//Valida todos os campos obrigatórios de um formulário especifico.
//    Se houver algum campo que não atenda todas as definições, retorna (false).
//    Se todas as definições forem atendidas, retorna (true);
function twFctValidaFomulario(vfFormulario){
	for(vf_a = 0; vf_a < vfFormulario.elements.length; vf_a ++){
		var vfCampo = vfFormulario.elements[vf_a];
		var vfValorMinimo = 1;
		if((vfCampo.getAttribute('minimo'))!=null){ vfValorMinimo = parseFloat(vfCampo.getAttribute('minimo')); }
		
		if(((vfCampo.getAttribute('obrigatorio'))!=null)||((vfCampo.getAttribute('opcional'))!=null)){
			if(((vfCampo.getAttribute('mensagem'))!=null)&&(!vfCampo.disabled)){
				switch (vfCampo.type){
					case "text":
						if((((vfCampo.getAttribute('opcional'))!=null)&&(vfCampo.value.length > 0))||((vfCampo.getAttribute('obrigatorio'))!=null)){
							if(!twFctCampoCheckMin(vfCampo, vfValorMinimo, vfCampo.getAttribute('mensagem'))){ return(false); }
							if((vfCampo.getAttribute('tipoEmail'))!=null){
								if(!twFctIsEmail(vfCampo.value)){ alert(vfCampo.getAttribute('mensagem')); vfCampo.focus(); return(false); }
							}
							if((vfCampo.getAttribute('tipoLogin'))!=null){
								if(!twFctIsLogin(vfCampo.value)){ alert(vfCampo.getAttribute('mensagem')); vfCampo.focus(); return(false); }
							}
							
							if(((vfCampo.getAttribute('tipoCpf'))!=null)&&((vfCampo.getAttribute('tipoCnpj'))!=null)){
								if((!twFctIsCpf(vfCampo.value))&&(!twFctIsCnpj(vfCampo.value))){ alert(vfCampo.getAttribute('mensagem')); vfCampo.focus(); return(false); }
							} else {
								if((vfCampo.getAttribute('tipoCpf'))!=null)
									if(!twFctIsCpf(vfCampo.value)){ alert(vfCampo.getAttribute('mensagem')); vfCampo.focus(); return(false); }
								if((vfCampo.getAttribute('tipoCnpj'))!=null)
									if(!twFctIsCnpj(vfCampo.value)){ alert(vfCampo.getAttribute('mensagem')); vfCampo.focus(); return(false); }
							}
							if((vfCampo.getAttribute('compararCom'))!=null){
								for(vf_b = 0; vf_b < vfFormulario.elements.length; vf_b ++){
									var vfCampoComparar = vfFormulario.elements[vf_b];
									if(vfCampoComparar.name == vfCampo.getAttribute('compararCom')){
										if(vfCampoComparar.value != vfCampo.value){
											alert(vfCampoComparar.getAttribute('mensagem'));
											vfCampoComparar.value = "";
											vfCampoComparar.focus();
											return(false);
										} else {
											break;
										}
									}
								}
							}
						}

						break;
					case "password":
						if((((vfCampo.getAttribute('opcional'))!=null)&&(vfCampo.value.length > 0))||((vfCampo.getAttribute('obrigatorio'))!=null)){
							if(!twFctCampoCheckMin(vfCampo, vfValorMinimo, vfCampo.getAttribute('mensagem'))){ return(false); }
							if((vfCampo.getAttribute('compararCom'))!=null){
								for(vf_b = 0; vf_b < vfFormulario.elements.length; vf_b ++){
									var vfCampoComparar = vfFormulario.elements(vf_b);
									if(vfCampoComparar.name == vfCampo.getAttribute('compararCom')){
										if(vfCampoComparar.value != vfCampo.value){
											alert(vfCampoComparar.getAttribute('mensagem'));
											vfCampoComparar.value = "";
											vfCampoComparar.focus();
											return(false);
										} else {
											break;
										}
									}
								}
							}
						}
						break;
					case "hidden":
						if((((vfCampo.getAttribute('opcional'))!=null)&&(vfCampo.value.length > 0))||((vfCampo.getAttribute('obrigatorio'))!=null)){
							if(!twFctCampoCheckMin(vfCampo, vfValorMinimo, vfCampo.getAttribute('mensagem'))){ return(false); }
							if((vfCampo.getAttribute('tipoEmail'))!=null){
								if(!twFctIsEmail(vfCampo.value)){ alert(vfCampo.getAttribute('mensagem')); vfCampo.focus(); return(false); }
							}
						}
						break;
					case "password":
						if((((vfCampo.getAttribute('opcional'))!=null)&&(vfCampo.value.length > 0))||((vfCampo.getAttribute('obrigatorio'))!=null)){
							if(!twFctCampoCheckMin(vfCampo, vfValorMinimo, vfCampo.getAttribute('mensagem'))){ return(false); }
							if((vfCampo.getAttribute('compararCom'))!=null){
								for(vf_b = 0; vf_b < vfFormulario.elements.length; vf_b ++){
									var vfCampoComparar = vfFormulario.elements[vf_b];
									if(vfCampoComparar.name == vfCampo.getAttribute('compararCom')){
										if(vfCampoComparar.value != vfCampo.value){
											alert(vfCampoComparar.getAttribute('mensagem'));
											vfCampoComparar.value = "";
											vfCampoComparar.focus();
											return(false);
										} else {
											break;
										}
									}
								}
							}
						}
						break;
					case "checkbox":
						if(!vfCampo.checked){ alert(vfCampo.getAttribute('mensagem')); return(false); }
						break;
					case "select-one":
						if(!twFctCampoCheckMin(vfCampo, vfValorMinimo, vfCampo.getAttribute('mensagem'))){ return(false); }
						break;
				}
			}
		}
		
	}
	for(vf_a = 0; vf_a < vfFormulario.length; vf_a ++){
		var vfCampo = vfFormulario[vf_a];
		if(vfCampo.type=='submit'){
			if(vfCampo.getAttribute('desabilitar')!=null){
				vfCampo.disabled = true;
			}
		}
	}
	return (true);
}

//Valida o login do cliente
function twFctIsLogin(ieValor) {
	var ieRegExp = /^[a-zA-Z0-9]{4,20}$/;
	return(ieRegExp.test(ieValor));
}
