
//variavel utilizada para verificar se campo ajax foi alterado, e caso seja alterado, limpar o campo id
var campoDescricaoAjax;

// Formata uma data que está sendo digitada
// com as barras separadora (dd/mm/aaaa). Recebe um 
// objeto cujo valor deve ser uma data. 
// No input deve ser chamado pela funcao onkeyup='mascara_data(this)'
function mascara_data(data){ 
      var mydata = ''; 
      mydata = mydata + data.value; 

      if (mydata.length > 2 && mydata.length<5){ 
      dd = mydata.substr(0,2);
      mm = mydata.substr(2);
      if (mm.substr(0,1) == "/")
        mm = mm.substr(1);
      mydata = dd + '/' + mm ; 
      data.value = mydata;
  } 
  if (mydata.length > 5){ 
      ddMM = mydata.substr(0,5);
      yyyy = mydata.substr(5);
      teste = yyyy.substr(0,1);

      if (teste == "/")
        yyyy = yyyy.substr(1);
      mydata = ddMM + '/' + yyyy ;
      data.value = mydata;
  } 
  if (mydata.length == 10){ 
      verifica_data(data); 
  } 
} 
           

// Validação de data. Recebe como parâmetro um objeto cujo
// valor seja uma data
function verifica_data (data) { 

    dia = (data.value.substring(0,2)); 
    mes = (data.value.substring(3,5)); 
    ano = (data.value.substring(6,10)); 

    situacao = ""; 
    // verifica o dia valido para cada mes 
    if ((dia < 01)||(dia < 01 || dia > 30) && (  mes == 04 || mes == 06 || mes == 09 || mes == 11 ) || dia > 31) { 
        situacao = "falsa"; 
    } 

    // verifica se o mes e valido 
    if (mes < 01 || mes > 12 ) { 
        situacao = "falsa"; 
    } 

    // verifica se e ano bissexto 
    if (mes == 2 && ( dia < 01 || dia > 29 || ( dia > 28 && (parseInt(ano / 4) != ano / 4)))) { 
        situacao = "falsa"; 
    } 

    if (data.value == "") { 
        situacao = "falsa"; 
    } 

    if (situacao == "falsa") { 
        alert("A data digitada é uma data inválida."); 
        data.focus(); 
    } 
} 


// Formata o CEP que está sendo digitado
// com a máscar 'xxxxx-xxx'. Recebe um objeto cujo
// valor deve ser um um CEP. 
// No input deve ser chamado pela funcao onkeyup='mascara_cep(this)'
function mascara_cep(cep){ 
      var meuCEP = ''; 
      meuCEP = meuCEP + cep.value; 

      if (meuCEP.length > 5 && meuCEP.length<8){ 
      inicio = meuCEP.substr(0,5);
      fim = meuCEP.substr(5);
      if (fim.substr(0,1) == "-")
        fim = fim.substr(1);
      meuCEP = inicio + '-' + fim ; 
      cep.value = meuCEP;
  } 
} 

//chamar a action novo
function novo() {
	document.forms[0].perform.value = "novo";
	document.forms[0].submit();
}

//efetuar o editar do form
function editar() {
	document.forms[0].perform.value = "editar";
	document.forms[0].submit();
}


//efetuar o salvar do form
function salvar() {
	document.forms[0].perform.value = "salvar";
	document.forms[0].submit();
}

//efetuar o excluir
function excluir() {
        
      if (confirm("Tem certeza que deseja excluir este registro ?"))
      {
      	  disableScreen();
      	  document.forms[0].perform.value = "excluir";
	  	  document.forms[0].submit();
      }
}

//função utlizada para fechar o popup
function cancelarPopup(){
	document.forms[0].perform.value = "cancelarPopup";
	document.forms[0].target = "_parent";
	document.forms[0].submit();		
}	


//função que chama o método "salvar em sessão" da action em questao (form)
function salvarEmSessao()
{
	document.forms[0].perform.value = "salvarEmSessao";
	document.forms[0].target = "_self";
	document.forms[0].submit();		
}


//função utilizada para fechar o popup (situação específica para os casos em 
//que o popup é uma tela de cadastro com a opção de continuar cadastrando
function sairPopup()
{
	if (document.forms[0].status.value == "sair")
		cancelarPopup();
}

function abrePopup(url,titulo,largura,altura,perform)
{
	if (perform != "")
	{
		document.forms[0].perform.value = perform;
		document.forms[0].target = "frameOculto";
		document.forms[0].submit();		
	}	
        // alert(url+","+titulo+","+largura+","+altura);
	openDialog(url,titulo,largura,altura);
}

//Função presente em layout.jsp e que abre um popup sempre que especificado na propriedade status.
/*
        function abrePopup(){
            if (document.forms[0].popup != null)
            {
                var popup = document.forms[0].popup.value;
                if (popup != '' && popup != '0'){
                        document.getElementById('frame').src = document.forms[0].srcPopup.value;
                        var titulo = 'Sistema de Organogramas e Endereços';
                        if (document.forms[0].tituloPopup.value != '')
                                titulo = document.forms[0].tituloPopup.value;
                        var altura = 300;
                        if (document.forms[0].alturaPopup.value != '')
                                altura = parseInt(document.forms[0].alturaPopup.value);
                        var largura = 500;
                        if (document.forms[0].larguraPopup.value != '')
                                largura = parseInt(document.forms[0].larguraPopup.value);
                        openDialog('popup',titulo,largura,altura);
                }
             }
        }
*/

// Retira pontos e vírgulas e posiciona o ponto da casa decimal.
function FormatarToDouble(valor) { 
	var result = "";
	var posPonto = -1;
	var aux = 0;
	for (var i=0; i < valor.length; i++) {
		if ((valor.substring(i, i + 1) != ".") && (valor.substring(i, i + 1) != ",")) {
			result += valor.substring(i, i + 1);
  		}
  		else {
   			posPonto = i - aux;
   			aux += 1;
  		}
 	}
 	if (posPonto >= 0){
  		result = result.substring(0, posPonto) + "." + result.substring(posPonto, result.length);
 	}
 	return result;
}

// Retira caracteres inválidos da string
function LimparNumero(valor, validos) { 
	var result = "";
	var aux;
	for (var i=0; i < valor.length; i++) {
		aux = validos.indexOf(valor.substring(i, i+1));
		if (aux>=0) {
			result += aux;
		}
	}
	return result;
}

// Formata número tipo moeda usando o evento onKeyDown
function FormatarNumero(campo,tammax,teclapres) { 
	var tecla = teclapres.keyCode;
	vr = LimparNumero(campo.value,"0123456789");
	tam = vr.length;
	
                 
        zeroEsquerda = true;
        for (i=0; i<=tam; i++){
            if (vr.charAt(i) != '0')
                zeroEsquerda = false;
            if (!zeroEsquerda){
                vr = vr.substring(i,tam+1);
                break;
            }
        }
        tam = vr.length;

        
	if (tam < tammax && tecla != 8){ tam = vr.length + 1 ; }
	
	if (tecla == 8 ){ tam = tam - 1 ; }
	
	if ( tecla == 8 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105 ){
		dec=2
		if ( tam <= dec ){
                    if (tam < 1)
                        campo.value = "";
                    if (tam == 1)
                            campo.value = "0,0" + vr ;                        
                    else
                        if (tam == 2)
                            {
                                campo.value = "0," + vr ;
                            }
                            
                }   
		
		if ( (tam > dec) && (tam <= 5) ){
			campo.value = vr.substr( 0, tam - 2 ) + "," + vr.substr( tam - dec, tam ) ; 
		}
		if ( (tam >= 6) && (tam <= 8) ){
			campo.value = vr.substr( 0, tam - 5 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - dec, tam ) ; 
		}
		if ( (tam >= 9) && (tam <= 11) ){
			campo.value = vr.substr( 0, tam - 8 ) + "." + vr.substr( tam - 8, 3 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - dec, tam ) ; 
		}
		if ( (tam >= 12) && (tam <= 14) ){
			campo.value = vr.substr( 0, tam - 11 ) + "." + vr.substr( tam - 11, 3 ) + "." + vr.substr( tam - 8, 3 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - dec, tam ) ; 
		}
		if ( (tam >= 15) && (tam <= 17) ){
			campo.value = vr.substr( 0, tam - 14 ) + "." + vr.substr( tam - 14, 3 ) + "." + vr.substr( tam - 11, 3 ) + "." + vr.substr( tam - 8, 3 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - 2, tam ) ;
		}
	}

                    


}

// Formata número tipo moeda
function FormatarValorNumerico(vr) { 
	campo = "";
	tam = vr.length;
	if ((vr.substr( tam - 2, 1 ) == ".") || ((vr.substr( tam - 2, 1 ) == ","))){
		vr = vr + "0";
	}
	vr = LimparNumero(vr,"0123456789");
	tam = vr.length;
	
	dec=2
	if ( tam <= dec ){ campo = vr ; }
	
	if ( (tam > dec) && (tam <= 5) ){
		campo = vr.substr( 0, tam - 2 ) + "," + vr.substr( tam - dec, tam ) ; 
	}
	if ( (tam >= 6) && (tam <= 8) ){
		campo = vr.substr( 0, tam - 5 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - dec, tam ) ; 
	}
	if ( (tam >= 9) && (tam <= 11) ){
		campo = vr.substr( 0, tam - 8 ) + "." + vr.substr( tam - 8, 3 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - dec, tam ) ; 
	}
	if ( (tam >= 12) && (tam <= 14) ){
		campo = vr.substr( 0, tam - 11 ) + "." + vr.substr( tam - 11, 3 ) + "." + vr.substr( tam - 8, 3 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - dec, tam ) ; 
	}
	if ( (tam >= 15) && (tam <= 17) ){
		campo = vr.substr( 0, tam - 14 ) + "." + vr.substr( tam - 14, 3 ) + "." + vr.substr( tam - 11, 3 ) + "." + vr.substr( tam - 8, 3 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - 2, tam ) ;
	} 
	
	return campo;
}

//função para verificar se campos usando ajax estão válidos, e caso inválidos, mostrar mensagem indicativa de erro
function validarCampoAjax( codigoId, descricaoId, imagemId, rootPath ) {
	var codigo = document.getElementById( codigoId );
	var descricao = document.getElementById( descricaoId );
	var imagem = document.getElementById( imagemId );
		
	if( ( codigo.value == "" ) && ( descricao.value != "" ) ) {
		imagem.src = rootPath + "img/iErrorAjax.gif";
	}
	else {
		imagem.src = rootPath + "img/iVazioAjax.gif";
	}
}

//armazenar campo descricao ajax para que na função limparId seja verificado se o campo foi alterado ou não.
//Este método deve ser chamado em onkeypress e limparId em onkeyup.
function antesLimparId( descricao ) {
	campoDescricaoAjax = descricao.value;	
}

//verifica se campo descricao foi alterado, caso foi alterado, limpa campo id.
//limparId deve ser chamado em onkeyup e trabalha em conjunto com a função antesLimparId.
function limparId( descricao, codigoId, evento ) {
	if( ehTeclaDescarte( evento ) ) {
		return;
	}
	
	if( descricao.value != campoDescricaoAjax ) {
		//campo foi alterado, limpar id
		var codigo = document.getElementById( codigoId );
		codigo.value = '';
	}
}

//verifica se a tecla deve ser descartada.
//Ex. de Utilização: O método limparId utiliza esta função para não limpar o id caso estas teclas sejam pressionadas
function ehTeclaDescarte( e ) {
      var tecla =  window.event ? window.event.keyCode
           : e            ? e.which
           :                0;
      
      if( ( tecla == 13 ) || ( tecla == 9 ) ) {
      	  return true;
      }
      else {
 		  return false;   
      }
}

//Trava edição de campos (ex. cnpj) para aceitar números e teclas de função
function soNumero(evt){
    evt = (evt) ? evt : window.event;
	var charCode = (evt.which) ? evt.which : evt.keyCode;
	if (charCode < 48 || charCode > 57){
		if (charCode == 37 || charCode == 13 || charCode == 39 || charCode == 36 || charCode == 27 || 
			charCode == 35 || charCode == 9 || charCode == 8 || charCode == 46){
			return true;
		}
		else{
			return false;
		}
	}
	else{
		return true;
	}
}




