/*******************************************
criação  	 : 03/2009
descricao    : Rotinas aplicáveis nos FORMULÁRIOS
 ********************************************/

/*******************************************************************************
 * INICIA ROTINA DE VALIDAÇÃO
 ******************************************************************************/
function validarFormulario() {
	var ok = true;
	
	/***************************************************************************
	 * CAMPOS OBRIGATÓRIOS
	 **************************************************************************/
	$('input[type$=text].obrigatorio').each( function() {

		$('#_' + replaceAll(this.id, '.', '')).removeClass('obrigatorioNaoPreenchido');
		$('#_' + replaceAll(this.id, '.', '')).removeClass('obrigatorio');
		
		if (this.value == "") {
			ok = false;
			$('#_' + replaceAll(this.id, '.', '')).addClass('obrigatorioNaoPreenchido');
		}else{
			$('#_' + replaceAll(this.id, '.', '')).addClass('obrigatorio');
		}
	});
	
	$('input[type$=password].obrigatorio').each( function() {
		
		$('#_' + replaceAll(this.id, '.', '')).removeClass('obrigatorioNaoPreenchido');
		$('#_' + replaceAll(this.id, '.', '')).removeClass('obrigatorio');
		
		if (this.value == "") {
			ok = false;
			$('#_' + replaceAll(this.id, '.', '')).addClass('obrigatorioNaoPreenchido');
		}else
			$('#_' + replaceAll(this.id, '.', '')).addClass('obrigatorio');
	});
	
	$('select.obrigatorio').each(function() {
		$('#_' + replaceAll(this.id, '.', '')).removeClass('obrigatorioNaoPreenchido');
		$('#_' + replaceAll(this.id, '.', '')).removeClass('obrigatorio');
		
		if ($("select[name$='"+this.name+"']").val() == "") {
			ok = false;
			$("#_"+this.id).addClass('obrigatorioNaoPreenchido');
		} else
			$("#_"+this.id).addClass('obrigatorio');
	
	});

	$('textarea.obrigatorio').each(function() {
		
		$('#_' + replaceAll(this.id, '.', '')).removeClass('obrigatorioNaoPreenchido');
		$('#_' + replaceAll(this.id, '.', '')).removeClass('obrigatorio');

		if (this.value == "") {
			ok = false;
			$('#_' + replaceAll(this.id, '.', '')).addClass('obrigatorioNaoPreenchido');
		} else
			$('#_' + replaceAll(this.id, '.', '')).addClass('obrigatorio');
	});

	$('input:radio.obrigatorio').each(function() {
		$("#_" + this.id).removeClass('obrigatorioNaoPreenchido');

		if ($("input[type=radio][id='"+this.id+"']:checked").length == 0) {
			ok = false;
			$("#_" + this.id).addClass('obrigatorioNaoPreenchido');
		}
		
	});

	// REVISAR
	$('input[type$=checkbox].obrigatorio').each(function() {
		checkAtual = this.name;
		nomeDiv = checkAtual.replace(/\[\]/g, "");
		$('#_' + nomeDiv).removeClass('obrigatorioNaoPreenchido');
		if ($('input[type$=checkbox][name$=' + nomeDiv + ']:checked').length == 0) {
			ok = false;
			$('#_' + nomeDiv).addClass('obrigatorioNaoPreenchido');
		}
	});
	
	if (!ok) {
		jAlert( "Os campos marcados com asterisco (*) são obrigatórios");
	
		// se houver Abas. Seleciona a mesma para identificação
		identificaAba();
		return ok;
	}

	/***************************************************************************
	 * CAMPOS NUMÉRICOS
	 **************************************************************************/
	$('input.numerico').each( function() {
		
		if (this.value!="")	{
			$('#_' + this.id.replace('.', '')).removeClass('obrigatorioNaoPreenchido');

			if (!validaInteiro(this.value)) {
				ok = false;
				$('#_' + replaceAll(this.id, '.', '')).addClass('obrigatorioNaoPreenchido');
			}
		}
	});

	if (!ok) {
		jAlert('Verifique o preenchimento correto de campos numéricos.');

		// se houver Abas. Seleciona a mesma para identificação
		identificaAba();
		return ok;
	}

	/***************************************************************************
	 * CAMPOS COM CNPJ
	 **************************************************************************/
	$("input.cnpj").each( function() {

		if (this.value!="")	{
			$('#_' + this.id.replace('.', '')).removeClass('obrigatorioNaoPreenchido');

			if (!validaCnpj(this.value)) {
				ok = false;
				$('#_' + replaceAll(this.id, '.', '')).addClass('obrigatorioNaoPreenchido');
				$(this).focus();
			}
		}
	});

	if (!ok) {
		jAlert('Verifique o preenchimento correto de campos com CNPJ.');

		// se houver Abas. Seleciona a mesma para identificação
		identificaAba();
		return ok;
	}	

	/***************************************************************************
	 * CONTADOR PARA O TEXTAREA
	 **************************************************************************/
	$('textarea.contadorTextarea').each(function() {
		
		var textarea = $(this).attr("id");
		var contador = $("#contador_"+textarea);
		var maximo = $("#contador_"+textarea).attr("maxlength");

		$('#_' + replaceAll(this.id, '.', '')).removeClass('obrigatorioNaoPreenchido');

		if ($(this).val().length>=(maximo+1)) {
			ok = false;
			$('#_' + replaceAll(this.id, '.', '')).addClass('obrigatorioNaoPreenchido');
			$(this).focus();
		}
		
		
	});

	if (!ok) {
		jAlert("A quantidade máxima de caracteres foi excedida");

		// se houver Abas. Seleciona a mesma para identificação
		identificaAba();
		return ok;
	}


	/***************************************************************************
	 * CAMPOS COM HORA
	 **************************************************************************/
	$('input.horaMinuto').each( function() {

		if (this.value!="")	{
			$('#_' + this.id.replace('.', '')).removeClass('obrigatorioNaoPreenchido');

			if (!validaHora(this.value)) {
				ok = false;
				$('#_' + replaceAll(this.id, '.', '')).addClass('obrigatorioNaoPreenchido');
			}
		}
	});
	
	if (!ok) {
		jAlert('Verifique o preenchimento correto de campos com Hora.');

		// se houver Abas. Seleciona a mesma para identificação
		identificaAba();
		return ok;
	}
	
	/***************************************************************************
	 * CAMPOS COM DATA
	 **************************************************************************/
	$('input.data').each( function() {

		if (this.value!="")	{
			$('#_' + this.id.replace('.', '')).removeClass('obrigatorioNaoPreenchido');

			if (!validaData(this.value)) {
				ok = false;
				$('#_' + replaceAll(this.id, '.', '')).addClass('obrigatorioNaoPreenchido');
			}
		}
	});
	
	if (!ok) {
		jAlert('Verifique o preenchimento correto de campos com Data.');

		// se houver Abas. Seleciona a mesma para identificação
		identificaAba();
		return ok;
	}

	/***************************************************************************
	 * CAMPOS COM E-MAIL
	 **************************************************************************/
	$('input.email').each( function() {

		if (this.value!="")	{
			$('#_' + this.id.replace('.', '')).removeClass('obrigatorioNaoPreenchido');

			if (!validaEmail(this.value)) {
				ok = false;
				$('#_' + replaceAll(this.id, '.', '')).addClass('obrigatorioNaoPreenchido');
			}
		}
	});
	
	if (!ok) {
		jAlert('Verifique o preenchimento correto de campos com E-mail.');

		// se houver Abas. Seleciona a mesma para identificação
		identificaAba();
		return ok;
	}	

	/***************************************************************************
	 * CAMPOS COM CPF
	 **************************************************************************/
	$("input.cpf").each( function() {
		
		if (this.value!="")	{
			$('#_' + this.id.replace('.', '')).removeClass('obrigatorioNaoPreenchido');

			if (!validaCpf(this.value)) {
				ok = false;
				$('#_' + replaceAll(this.id, '.', '')).addClass('obrigatorioNaoPreenchido');
				$(this).focus();
			}
		}
	});

	if (!ok) {
		jAlert('Verifique o preenchimento correto de campos com CPF.');

		// se houver Abas. Seleciona a mesma para identificação
		identificaAba();
		return ok;
	}

	return ok;
}

/*************************************************************************
 * Verifica se uma data está no formato válido
 * 
 * @param String Uma data no formato dd/mm/yyyy
 ************************************************************************/
 function validaData(dataVerificar) {
	 var expReg = /^((0[1-9]|[12]\d)\/(0[1-9]|1[0-2])|30\/(0[13-9]|1[0-2])|31\/(0[13578]|1[02]))\/(19|20)?\d{2}$/;
	 var aRet = true;
	  if (dataVerificar.match(expReg)) {
	    var dia = parseInt(dataVerificar.substring(0,2));
	    var mes = parseInt(dataVerificar.substring(3,5));
	    var ano = parseInt(dataVerificar.substring(6,10));
	    if ((mes == 4 || mes == 6 || mes == 9 || mes == 11 )&& dia > 30){
	      aRet = false;
	      jAlert('mes == '+mes+'&& dia('+dia+') > 30');
	    }else
	      if ((ano % 4) != 0 && mes == 2 && dia > 28){
	        aRet = false;
	        jAlert('2');
	      }else
	        if ((ano%4) == 0 && mes == 2 && dia > 29){
	        	jAlert('3');
	        	aRet = false;
	        }
	  }else
	    aRet = false;  
	  
	  return aRet;
}

 /*************************************************************************
  * Verifica se uma hora está no formato válido
  * 
  * @param String Uma hora no formato 24:59:59
  ************************************************************************/
function validaHora(horaVerificar) {
	var retorno = true;
	
	var hora	= parseInt(horaVerificar.substring(0,2));
	var min		= parseInt(horaVerificar.substring(3,5));
	var seg 	= parseInt(horaVerificar.substring(6,8));
	
	if (hora>23 || min >59 || seg>59) {
		retorno = false;
	}

	return retorno;
 }

/*************************************************************************
 * Verifica se um cep está no formato válido
 * 
 * @param String Um cep no formato 99999-999
 ************************************************************************/
function validaCep(cepVerificar) {
	var retorno = true;
	
	var expReg = /^\d{3}-\d{3}$/;
	 
	if (!cepVerificar.match(expReg)) {
		 retorno = false;  
	 }	

	return retorno;
}

/*************************************************************************
 * Verifica se um cpf está no formato válido
 * 
 * @param Número um CPF para ser verificado
 ************************************************************************/
function validaCpf(cpfVerificar) {
	var retorno = true;
	
	if (!validaInteiro(cpfVerificar)) {
		return false;
	}
	else {
		var numeros, digitos, soma, i, resultado, digitos_iguais;
		var cpf = cpfVerificar;
		
		digitos_iguais = 1;
		if (cpf.length < 11) {
			retorno = false;
		}
	      	
		for (i = 0; i < cpf.length - 1; i++) {
			if (cpf.charAt(i) != cpf.charAt(i + 1)) {
				digitos_iguais = 0;
				break;
			}
		}
		
		if (!digitos_iguais) {
        	digitos = cpf.substring(9);

        	numeros = cpf.substring(0,9);
        	soma = 0;
			
			for (i = 10; i > 1; i--) {
				soma += numeros.charAt(10 - i) * i;
			}
			
			resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
			
			if (resultado != digitos.charAt(0)) {
				retorno = false;
			}
			
			numeros = cpf.substring(0,10);
			soma = 0;
			
			for (i = 11; i > 1; i--) {
				soma += numeros.charAt(11 - i) * i;
			}
			
			resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
			
			if (resultado != digitos.charAt(1)) {
				retorno = false;
			}
		}
		else {
			retorno = false;
		}
	}
	return retorno;
}

/*************************************************************************
 * Verifica se um CNPJ está no formato válido
 * 
 * @param Número um cnpj para ser verificado
 ************************************************************************/
function validaCnpj(cnpjVerificar) {
	var numeros, digitos, soma, i, resultado, pos, tamanho, digitos_iguais, retorno;
	retorno = true;
	
	digitos_iguais = 1;
	
	cnpj = cnpjVerificar;
	
	if (cnpj == null || cnpj == "") {
		return true;
	}

	cnpj = cnpj.toString().replace( ".", "");
	cnpj = cnpj.toString().replace( ".", "");
	cnpj = cnpj.toString().replace( "/", "");
	cnpj = cnpj.toString().replace( "-", "");
	
	if (cnpj.length != 14) {
		return false;
	}
	
     for (b = 0; b < cnpj.length - b; b++) { 
         if (cnpj.charAt(b) != cnpj.charAt(b + 1)){
        	 digitos_iguais = 0;
        	 break;
         }
     }
   
     if (!digitos_iguais) {
         tamanho = cnpj.length - 2
         numeros = cnpj.substring(0,tamanho);
         digitos = cnpj.substring(tamanho);
         soma = 0;
         pos = tamanho - 7;
         for (a = tamanho; a >= 1; a--) {
        	 soma += numeros.charAt(tamanho - a) * pos--;
             if (pos < 2) {
            	 pos = 9;
             }
         }
         
         resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
         if (resultado != digitos.charAt(0)) {
        	 retorno = false;
        	 }
         
         tamanho = tamanho + 1;
         numeros = cnpj.substring(0,tamanho);
         soma = 0;
         pos = tamanho - 7;
         
         for (t = tamanho; t >= 1; t--) {
        	 soma += numeros.charAt(tamanho - t) * pos--;
             if (pos < 2){
            	 pos = 9;
             }
         }
         
         resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
         
        if (resultado != digitos.charAt(1)) {
				retorno = false;
		}
     } else {
     retorno = false;
     }

     return retorno;
}

 /*************************************************************************
 * Verifica se o valor que foi digitado é inteiro
 * 
 * @param int
 ************************************************************************/
 function validaInteiro(numero) { 
	 var expReg = /^[0-9]{1,}$/;
	 var aRet = true;
	 
	 if (numero!="") {
		 if (! numero.match(expReg)) {
			 aRet = false;  
		 }
	 }		 
	 
	  return aRet;
 }
 
 /*************************************************************************
  * Verifica se o e-mail válido
  * 
  * @param String
  ************************************************************************/
  function validaEmail(email) { 
	 //var expReg = /^([a-z]{1,}\.?)+[a-z]{1,}@[a-z]{3,}(\.([a-z]{2,3})(\.[a-z]{2})?)+$/;
	 //var expReg = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{1,3})+$/;
	 var expReg = /^[a-zA-Z0-9_\.-]{2,}@([A-Za-z0-9_-]{2,}\.)+[A-Za-z]{2,4}$/;
	 
	 var aRet = true;
	 
	 if (! email.match(expReg)) {
		 aRet = false;  
	 }
	 
	  return aRet;
  }
  
  

/**
 * se houver Abas. Seleciona a mesma para identificação de campos não preenchidos
 * @param 
 */
function identificaAba() {
	var ok = true;

	$("div.abaConteudo").each( function() {
	ok = true;
	
	var abaCont = 0;
	var abaId = $(this).attr("id");

	$("#_"+abaId).removeClass('abaObrigatorioNaoPreenchido');
	$("#_"+abaId+" sup").html("");
	
	$(this).children(".obrigatorioNaoPreenchido").each( function() {
			abaCont++;
			ok = false;
		});
	
	if (!ok) {
		$("#_"+abaId).addClass('abaObrigatorioNaoPreenchido');
		$("#_"+abaId+" sup").html($("#_"+abaId+" sup").html()+abaCont);
	}
	});
}

/***************************************************************************
VALIDA FORMULÁRIOS OBRIGATÓRIOS - SEM ID PRÉ DEFINIDO
******************************************************************************/
$(function(){
	$('#form.conferir').submit( function() {
		return validarFormulario();
	});
});

/***************************************************************************
VALIDA FORMULÁRIOS (OBRIGATÓRIOS - COM ID PRÉ DEFINIDO)
******************************************************************************/
$(function(){
	$("#form_login").submit(function() {
		$("#_usuariologin").css('color','#414141')
		$("#_usuariosenha").css('color','#414141');
		
		if ($("#usuariologin").val()=="" || $("#usuariosenha").val()=="") {
			jAlert("Informe E-mail e Senha de acesso.");
			
			if ($("#usuariologin").val()=="")
				$("#_usuariologin").css('color','#dd4c4c');
			
			if ($("#usuariosenha").val()=="")
				$("#_usuariosenha").css('color','#dd4c4c');

			return false;
		}
		
		return true;
	});	

	$("#form_menu").submit(function() {
		if (validarFormulario()) {
			window.onunload = recarregaPai;
			return true;			
		}
	
	return false;
	});	
	
	$("#form_usuario").submit(function() {
		if (validarFormulario()) {
			/* muda o name do combo de cidade para evitar erro de integridade */
			if ($("#usuarioenderecoProjetoibge_codigo").val()=="") {
				$("#usuarioenderecoProjetoibge_codigo").attr("name","temp_enderecoProjetoibge_codigo")
			}
		return true;			
		}
	
	return false;
	});	

	$("#form_usuarioNegocio").submit(function() {
		if (validarFormulario())
			if (salvaUsuarioNegocio(this)) {

				/* muda o name do combo de cidade para evitar erro de integridade */
				if (parent.$("#usuarioenderecoProjetoibge_codigo").val()=="") {
					parent.$("#usuarioenderecoProjetoibge_codigo").attr("name","temp_enderecoProjetoibge_codigo")
				}

				parent.tb_remove();
				parent.document.form_usuario.submit();
				return true;
				
			} else {
				return false;
			}
	
	return false;
	});	
});
