//****************************************************************************

// FUNÇÃO PARA IDENTIFICAR O NAVEGADOR

//****************************************************************************

var listaDeCamposAlterados=new Array();
function limpaCamposNaoPreenchidos(){
	//Teste para limpar campos do formulario
	for (var i=0; i < document.forms[0].elements.length; i++) {
		var obj = document.forms[0].elements[i];
		if (obj.type=="text" || obj.type=="textarea"){
			  limpaCampoCondicional(obj);
		}
	}
}

function isElementoNaLista(obj){
	for (var i=0; i < listaDeCamposAlterados.length; i++) {
		if (listaDeCamposAlterados[i]==obj){
			return true;
		}
	}
	return false;
}

//Função que controla o onfocus (limpa o input)
function limpaCampoCondicional(obj){
	if(!isElementoNaLista(obj)){
		listaDeCamposAlterados.push(obj);
		if(obj.value == obj.defaultValue){
			obj.value = "";
			obj.select();
		}
	}
}

// Variável que armazena o navegador ( IE6 | IE7 | MOZILLA )
var valorNavegador;

function identificaNavegador() {
	
	var versaoIE;
	
	if (navigator.appName == "Microsoft Internet Explorer"){
		versaoIE = navigator.appVersion.search("7.0");
		if(versaoIE > -1){
			valorNavegador = "IE7";
		} else {
			valorNavegador = "IE6";
		}
	} else {
		valorNavegador = "MOZILLA";
	}
	
}


//****************************************************************************

// FUNÇÕES DE INTERAÇÃO

//****************************************************************************

// Função para abertura de pop-up
function openWindow(theURL,winName,features) {
  window.open(theURL,winName,features);
}

// Função para abertura de Alert
function alertMsg(msg) {
  alert(msg);
}

// Função para abertura de Confirm
function confirmMsg(msg) {
  return confirm(msg);
}

// Função para goToURL funcionar no IE

var controle = true;

function validaForm(){
	
	if (controle) {
		return true;
	} else {
		return false;
	}
}

//Função que controla o onfocus (limpa o input)
function limpaCampo(obj){
	if(obj.value == obj.defaultValue){
		obj.value = "";
	}
		
}


function limpaCampoSenha(obj){
	document.getElementById('formTemlateBase:mensagem').value = '';
	if(obj.value == " " || obj.value == ""){
		obj.value = "";
	}
		
}

//Função que controla o preenchimento do campo com o onblur
	function preencheCampo(obj){
		if(obj.value == ""){
			obj.value = obj.defaultValue;
		}	
	}

// Função para redirecionamento de página
function goToURL() {
	
	controle=false;
	var i, args=goToURL.arguments; document.returnValue = false;
	for (i=0; i<(args.length-1); i+=2) eval(args[i]+".location='"+args[i+1]+"'");
	document.form_principal.submit;
}



// Função para Contador de caracteres de textarea
function atualizaContador(i, campo, contador) {
               
	field = document.getElementById(campo);
	
	if ( field ) {
		if(valorNavegador == "MOZILLA") {
			field.value = field.value.substr(0, i - field.value.split('\n').length + 1);
		} else {
			if(field.value.length >= i)
				field.value = field.value.substr(0, i);
			if (field.value.length > i) {
				field.value = field.value.substr(0, field.value.length - 2);
			}
		}
	}
	txt_field = document.getElementById(contador);
	if ( txt_field ) {
		if(valorNavegador == "MOZILLA") {
			txt_field.innerHTML =  i - field.value.length - field.value.split('\n').length + 1;
		} else {
			txt_field.innerHTML =  i - field.value.length;
		}
	}
}

function atualizaContadorEvent(e, i, campo, contador) {
	field = document.getElementById(campo);
	var e = !(e)?window.event:e;
	var numEnters = field.value.split('\n').length;
 	var tecla = (window.event)?window.event.keyCode:((e)?e.which:null);
	if ( field ) {
		if(valorNavegador == "MOZILLA") {
			if(field.value.length + numEnters > i) {
				if((e.type == "blur") || (e.ctrlKey && tecla == 86)) {
					field.value = field.value.substr(0, i - numEnters + 1);
					if(field.value.length + numEnters > i) {
						field.value = field.value.substr(0, i - numEnters + 1);
					}
				} else {
					if ((tecla != 9)  && (tecla != 8)  && (tecla != 46)  && (tecla != 45) && (tecla != 16) &&
		          		(tecla != 35) && (tecla != 36)  && (tecla != 37) && (tecla != 38) && 
		    			(tecla != 39) && (tecla != 40)  && (tecla != 17) && (tecla != 18) && 
		    			!(e.ctrKey && tecla == 67)) {
						e.preventDefault();
						field.value = field.value.substr(0, i - numEnters + 1);
					}
				}
			}
		} else {
			if(field.value.length >= i) {
				if((e.type == "blur") || (e.ctrlKey && tecla == 86)) {
					field.value = field.value.substr(0, i);
					if(field.value.length > i) {
						field.value = field.value.substr(0, i - 1);
					}
				} else {
					if ((tecla != 9)  && (tecla != 8)  && (tecla != 46)  && (tecla != 45) && (tecla != 16) &&
		          		(tecla != 35) && (tecla != 36)  && (tecla != 37) && (tecla != 38) && 
		    			(tecla != 39) && (tecla != 40)  && (tecla != 17) && (tecla != 18) && 
		    			!(e.ctrKey && tecla == 67))
						e.returnValue = false;
						if(field.value.length > i) {
							field.value = field.value.substr(0, i);
						}
				}
			}
		}
	}
	txt_field = document.getElementById(contador);
	var value = 0;
	if ( txt_field ) {
		value = i - field.value.length;
		if (valorNavegador == "MOZILLA") {
			value -= numEnters - 1;
		}
		if(value < 0){
			value = 0
		}
		txt_field.innerHTML =  value;
	}
}

function limpaTextarea(campo) {
	document.getElementById(campo).innerHTML = '';
}

//****************************************************************************

// FUNÇÃO PARA MASCARA DE CAMPOS INPUT TYPE = TEXT

//****************************************************************************

/*
caracteres: # - caracter a ser mascarado
            | - separador de mascaras
Exemplos:
mascara simples: "###-####"                   mascara utilizando a mascara passada
mascara composta: "###-####|####-####"        mascara de acordo com o tamanho (length) do valor passado
mascara dinâmica: "[###.]###,##"              multiplica o valor entre colchetes de acordo com o length
                                              do valor para que a mascara seja dinâmica ex: ###.###.###.###,##
utilizar no onkeyup do objeto
ex: onkeyup="this.value = mascara_global('#####-###',this.value);"
tratar o maxlength do objeto na página (a função não trata isso)
*/

function mascara_global(mascara, valor){
      var mascara_utilizar;
      var mascara_limpa;
      var temp;
      var i;
      var j;
      var caracter;
      var separador;
      var dif;
      var validar;
      var mult;
      var ret;
      var tam;
      var tvalor;
      var valorm;
      var masct;
      valor=concatena(recebeFrase(valor));
      tvalor = "";
      ret = "";
      caracter = "#";
      separador = "|";
      mascara_utilizar = "";
      //valor = trim(valor);
      if (valor == "")return valor;
      temp = mascara.split(separador);
      dif = 1000;
      valorm = valor;
      //tirando mascara do valor já existente
      for (i=0;i<valor.length;i++){
            if (!isNaN(valor.substr(i,1))){
                  tvalor = tvalor + valor.substr(i,1);
            }
      }
      valor = tvalor;
      //formatar mascara dinamica
      for (i = 0; i<temp.length;i++){
            mult = "";
            validar = 0;
            for (j=0;j<temp[i].length;j++){
                  if (temp[i].substr(j,1) == "]"){
                        temp[i] = temp[i].substr(j+1);
                        break;
                  }
                  if (validar == 1)mult = mult + temp[i].substr(j,1);
                  if (temp[i].substr(j,1) == "[")validar = 1;
            }
            for (j=0;j<valor.length;j++){
                  temp[i] = mult + temp[i];
            }
      }
      //verificar qual mascara utilizar
      if (temp.length == 1){
            mascara_utilizar = temp[0];
            mascara_limpa = "";
            for (j=0;j<mascara_utilizar.length;j++){
                  if (mascara_utilizar.substr(j,1) == caracter){
                        mascara_limpa = mascara_limpa + caracter;
                  }
            }
            tam = mascara_limpa.length;
      }else{
            //limpar caracteres diferente do caracter da máscara
            for (i=0;i<temp.length;i++){
                  mascara_limpa = "";
                  for (j=0;j<temp[i].length;j++){
                        if (temp[i].substr(j,1) == caracter){
                             mascara_limpa = mascara_limpa + caracter;
                        }
                  }
                  if (valor.length > mascara_limpa.length){
                        if (dif > (valor.length - mascara_limpa.length)){
                             dif = valor.length - mascara_limpa.length;
                             mascara_utilizar = temp[i];
                             tam = mascara_limpa.length;
                        }
                  }else if (valor.length < mascara_limpa.length){
                        if (dif > (mascara_limpa.length - valor.length)){
                             dif = mascara_limpa.length - valor.length;
                             mascara_utilizar = temp[i];
                             tam = mascara_limpa.length;
                        }
                  }else{
                        mascara_utilizar = temp[i];
                        tam = mascara_limpa.length;
                        break;
                  }
            }
      }
      //validar tamanho da mascara de acordo com o tamanho do valor
      if (valor.length > tam){
            valor = valor.substr(0,tam);
      }else if (valor.length < tam){
            masct = "";
            j = valor.length;
            for (i = mascara_utilizar.length-1;i>=0;i--){
                  if (j == 0) break;
                  if (mascara_utilizar.substr(i,1) == caracter){
                        j--;
                  }
                  masct = mascara_utilizar.substr(i,1) + masct;
            }
            mascara_utilizar = masct;
      }
      //mascarar
      j = mascara_utilizar.length -1;
      for (i = valor.length - 1;i>=0;i--){
            if (mascara_utilizar.substr(j,1) != caracter){
                  ret = mascara_utilizar.substr(j,1) + ret;
                  j--;
            }
            ret = valor.substr(i,1) + ret;
            j--;
      }
      return ret;
}


/* Apaga todos os options de um select para passar na 
   validacao jsf  */
function clearAllOptions(id){
	var endSelect = document.getElementById(id);
	while (endSelect.options.length > 0) {
    	endSelect.options[0] = null;
	}
}
/*Mostra as mensagens de alerta no sistema*/
function mostrarMensagemAlerta(){
      var texto = document.getElementById('formTemlateBase:mensagem').value;
      var flag = document.getElementById('formTemlateBase:flag').value;
      var msg;
      if(texto.trim() != null && texto.trim() != ''){
            var aux = texto.split('||');
            var alerta = '';
            for (var i=0; i < aux.length; i++) {
                  alerta += aux[i]+"\n";
            }
              alert(alerta);
              if(flag == 'false') 
                  mudaPaginaSucesso();
      }
      if(document.getElementById('formTemlateBase:msg') != null){
            msg = document.getElementById('formTemlateBase:msg').value;
      }
      if(msg != null && msg.trim() != ''){  
              alert(msg)  
      }
}

/*Mostra as mensagens de alerta no login*/
function mostrarMensagemAlertaLogin(){
      var texto = document.getElementById('formTemlateLogin:mensagem').value;
      var flag = document.getElementById('formTemlateLogin:flag').value;
      var msg;
      if(texto.trim() != null && texto.trim() != ''){
            var aux = texto.split('||');
            var alerta = '';
            for (var i=0; i < aux.length; i++) {
                  alerta += aux[i]+"\n";
            }
              alert(alerta);
              if(flag == 'false') 
                  mudaPaginaSucesso();
      }
      if(document.getElementById('formTemlateLogin:msg') != null){
            msg = document.getElementById('formTemlateLogin:msg').value;
      }
      if(msg != null && msg.trim() != ''){  
              alert(msg)  
      }
}

function mudaPaginaSucesso(){
	var pagina = document.getElementById('formTemlateBase:paginaSucesso');
   	if(pagina != null && pagina.value.trim() != ''){
        alterarPagina(pagina.value);
    }
}

function mostrarMsgAlerta(){	
    
}

function alterarPagina(pagina){
	window.location.href = pagina;
}

// Função para abertura de pop-up ou focus numa existente
function abreJanela(theURL,winName,features) {
  var janela = window.open(theURL,winName,features);
  janela.focus();
}

//Função que irá enviar os dados do cep para a janela que chamou a pop up de pesquisa de cep
function selecionaCep(){
	var cep = document.getElementById('formTemlateBase:cep').value;
	var cidade = document.getElementById('formTemlateBase:cidade').value;
	var codCidade = document.getElementById("formTemlateBase:codCidade").value;
	var uf = document.getElementById("formTemlateBase:uf").value;
	var endereco = document.getElementById("formTemlateBase:endereco").value;
	var bairro = document.getElementById("formTemlateBase:bairro").value;
	var complemento = document.getElementById("formTemlateBase:complemento").value;
	cep=mascara_global('##.###-###',cep);
	
	if(cep==""){
		alertMsg("Uma opção deve ser selecionada.");
	}else{
		opener.document.getElementById('formTemlateBase:cep').value=cep;
		opener.document.getElementById('formTemlateBase:cidade').value=cidade;
		opener.document.getElementById('formTemlateBase:codCidade').value=codCidade;
		opener.document.getElementById("formTemlateBase:uf").value=uf;
		opener.document.getElementById("formTemlateBase:endereco").value=endereco;
		opener.document.getElementById("formTemlateBase:bairro").value=bairro;
		opener.document.getElementById("formTemlateBase:complemento").value=complemento;
		
		opener.document.getElementById('formTemlateBase:cidadeDescricao').value=cidade;
		opener.document.getElementById('formTemlateBase:cepDescricao').value=cep;
		opener.document.getElementById("formTemlateBase:enderecoDescricao").value=endereco;
		opener.document.getElementById("formTemlateBase:bairroDescricao").value=bairro;
		opener.document.getElementById("formTemlateBase:complementoDescricao").value=complemento;
		opener.document.getElementById("formTemlateBase:ufDescricao").value=uf;
		opener.document.getElementById('formTemlateBase:cidadeHidden').value = cidade;
		opener.document.getElementById('formTemlateBase:ufHidden').value = uf;
		
		window.close();
	}
}	

// Função que limpa os campos do cep quando o usuário troca o valor informado
function limpaCamposCep(){
	document.getElementById('formTemlateBase:cidade').value = "";
	document.getElementById('formTemlateBase:uf').value = "";
	document.getElementById('formTemlateBase:bairro').value = "";
	document.getElementById('formTemlateBase:id_0000000521').value = "";
	document.getElementById('formTemlateBase:endereco').value = "";
	document.getElementById('formTemlateBase:codCidade').value = "";
	document.getElementById('formTemlateBase:complemento').value = "";
	document.getElementById('formTemlateBase:enderecoDescricao').value = "";
	document.getElementById('formTemlateBase:complementoDescricao').value = "";
	document.getElementById('formTemlateBase:bairroDescricao').value = "";
	document.getElementById('formTemlateBase:cidadeDescricao').value = "";
	document.getElementById('formTemlateBase:ufDescricao').value = "";
	document.getElementById('formTemlateBase:cidadeHidden').value = "";
	document.getElementById('formTemlateBase:ufHidden').value = "";
}	

// Função que verifica se o campo cep mudou de valor.	
function verificaMudancaCampo(novoValor) {
	if (novoValor != document.getElementById("formTemlateBase:cep").value
		&& novoValor != mascara_global('##.###-###',document.getElementById("formTemlateBase:cep").value)) {
		limpaCamposCep();
	}
}

//Função que irá enviar os dados do cep para a janela que chamou a pop up de pesquisa de cep
function populaCamposCep(cep,uf,cidade,codCidade,endereco,complemento,bairro){
	document.getElementById('formTemlateBase:cep').value=cep;
	document.getElementById("formTemlateBase:uf").value=uf;
	document.getElementById('formTemlateBase:cidade').value=cidade;
	document.getElementById('formTemlateBase:codCidade').value=codCidade;
	document.getElementById("formTemlateBase:endereco").value=endereco;
	document.getElementById("formTemlateBase:bairro").value=bairro;
	document.getElementById("formTemlateBase:complemento").value=complemento;
	document.getElementById('formTemlateBase:cidadeHidden').value = cidade;
	document.getElementById('formTemlateBase:ufHidden').value = uf;
}	

// FUNÇÃO ASSOCIADA AO LABEL DOS ICONES
function mensagemLabel(strMensagem,strLabel) {
	
	if ((strLabel == '') || (strLabel == null)){ 
		document.getElementById('label_botao').innerHTML = strMensagem;
	} else {
		document.getElementById(strLabel).innerHTML = strMensagem;	
	}
}

function definirValorPadraoParaCombo(id){
	var endSelect = document.getElementById(id);
	while (endSelect.options.length > 0) {
    	endSelect.options[0] = null;
	}
	endSelect.options[0] = new Option("aguarde...","");
}

//Função que irá submeter a janela que chamou a popup
function submeteJanelaPai(){
	opener.document.formTemlateBase.submit();
}

//Função que irá submeter a janela 
function foward(){
	document.form.comando.value=nome;
	document.form.submit();
}

function submeteFormulario(){
	document.forms[0].submit();
}

function verificarTab(){
      var tecla=window.event.keyCode;
      if (tecla == 13 || tecla == 32){
            return true;
      } else {
            return false;
     }
}
function controlaFocoSair(){
   inicio = 0;
    if(verificaTab()){
        if(inicio == 0) { 
		  inicio = 1; 
		  if (confirm('Deseja sair do sistema? Os dados não salvos serão perdidos.')){
            inicio = 0;
            window.close();
			}                                  

        }

    }  
}
function controlaFocoCancelar(){
   inicio = 0;
    if(verificaTab()){
        if(inicio == 0) { 
		  inicio = 1; 
		  if (confirm('Deseja cancelar a operação e retornar à tela anterior?')){
            inicio = 0;
            window.close();
			}                                  

        }

    }  
}
function controlaFocoInicio(){
   inicio = 0;
    if(verificaTab()){
        if(inicio == 0) { 
		  inicio = 1; 
		  if (confirm('Deseja retornar ao menu principal? Os dados não salvos serão perdidos.')){
            inicio = 0;
            window.close();
			}                                  

        }

    }  
}
function controlaFocoAlert(){
   inicio = 0;
    if(verificaTab()){
        if(inicio == 0) { 
		  inicio = 1; 
		  alert('Operação efetuada com sucesso.')
          inicio = 0;                             

        }
    }  
}

function executaAcaoCancelar(url){
		var retorno = confirm('Deseja cancelar a operação e retornar à tela anterior?');
		if(retorno){
			goToURL('parent',url);
		}
	}
	
function setarFocusCampoSelecionado(){
	var campo = document.getElementById('formTemlateBase:idCampoFocus');
	if(campo != null){
		var campoIndicado = document.getElementById('formTemlateBase:' + campo.value);
		if(campoIndicado != null){
			campoIndicado.focus();
		}
	}
}

function setaIdCampoFocusSelecionado(id){
	var campo = document.getElementById('formTemlateBase:idCampoFocus');
	if(campo != null){
		campo.value = id;
	}
}

function verificarKeyEnterSpace(evt, obj){
	var tecla = evt.which;
	if (tecla == 0) {
		tecla = evt.keyCode;
	}
	if(tecla ==32){
		obj.onclick();
	}	
	return tecla != 13 || tecla !=32;
}

function verificarKeyEnter(evt){
      var tecla = evt.which;
      if (tecla == 0) {
      	tecla = evt.keyCode;
      }
     return tecla !=13;
}

function habilitaEnter(evento){
}

function hablitaEnterNoLink(evento, indice){
	if(verificarKeyEnter(evento)){
		document.links[indice].onclick();
	}
}

function formataValorMonetario(campo) {
	var s = "";
	var cp = "";
	vr = campo.value;
	tam = vr.length;
	for (i = 0; i < tam ; i++) {
		if (vr.substring(i,i + 1) != "/" && vr.substring(i,i + 1) != "-" && vr.substring(i,i + 1) != "."  && vr.substring(i,i + 1) != "," ){
		 	s = s + vr.substring(i,i + 1);}
	}
	campo.value = s;
	vr = campo.value;
	tam = vr.length;

	if ( tam <= 2 )
 		campo.value = vr;
 	if ( (tam > 2) && (tam <= 5) )
 		campo.value = vr.substr( 0, tam - 2 ) + ',' + vr.substr( tam - 2, tam ) ;
 	if ( (tam >= 6) && (tam <= 8) )
 		campo.value = vr.substr( 0, tam - 5 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, 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 - 2, 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 - 2, tam ) ;
 	if ( (tam >= 15) && (tam <= 18) )
 		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 ) ;

}function upperCase(x){
	var y=document.getElementById(x).value
	document.getElementById(x).value=y.toUpperCase()
}


function retiraEspaco(valor){
		var array  = valor.split(" ");
		return array;
}

function recebeFrase(txt){
	var array  = txt.split(" ");
	return array;
}
function concatena(array){
	var txtfinal = "";
	for(i=0; i<array.length; i++){
		txtfinal += array[i];
	}
	return txtfinal;
}

function verificarKeyEnterForm(evt){
    var validate = false;
    var tecla = evt.which;
    var elementoOriginario = evt.srcElement;
      if (tecla == null || tecla == 0) {
            tecla = evt.keyCode;
    }
      if(evt.srcElement == null){
            elementoOriginario = evt.target;
      }
      if(elementoOriginario.type == 'submit' || elementoOriginario.type == '' || elementoOriginario.type == 'button' || elementoOriginario.type == 'image'){
            if(tecla == 13 || tecla == 9){
                  validate = true;
            }
      } else {
            validate = tecla != 13
      }
    if(elementoOriginario.type == 'textarea'){
		validate = true;
	}
    return validate;
}

/********************************************************************************/
/*Esconde um objeto pelo id e muda a imagen do objeto do tipo input type="image"*/
/********************************************************************************/
function abreGaveta(obj, id){
	sit = document.getElementById(id).style.display;					
	if(sit == "none"){
		document.getElementById(id).style.display = "block";
		obj.src = "../imagens/bot_fechar.jpg";
	} else {
		document.getElementById(id).style.display = "none";
		obj.src = "../imagens/bot_abrir.jpg";
	}
}
	// função para trocar opções de uma lista para outra
	function alternaDadosLista(origem,destino){
		var comboOrigem = document.getElementById(origem);
		var elementoDestino = document.getElementById(destino);	
		for(i=0;i<comboOrigem.length;i++){
			if(comboOrigem.options[i].selected==true){ 				
				var novoItem = new Option(comboOrigem.options[i].text,comboOrigem.options[i].value);
				comboOrigem.remove(i);
				elementoDestino.options[elementoDestino.length] = novoItem; 			
				i--;
			}  
		}	
    }

    // função para trocar todas as opções de uma lista para outra
    function alternaTodosDadosLista(origem,destino){
		var comboOrigem = document.getElementById(origem);
		var elementoDestino = document.getElementById(destino);	
		var elementoParaTransferir = comboOrigem.selectedIndex; 
		while (comboOrigem.length!=0){ 
			var novoItem = new Option(comboOrigem.options[0].text,comboOrigem.options[0].value);
			elementoDestino.options[elementoDestino.length] = novoItem;
			comboOrigem.remove(0);   			
		}
    }

	function selecionaTodosOsElementos(nomeDaLista) {
		reinicializaEstadoDeSelecao(document.getElementById(nomeDaLista), true);
	}
	
	function deSelecionaTodosOsElementos(nomeDaLista) {
		reinicializaEstadoDeSelecao(document.getElementById(nomeDaLista), false);
	}
	
	function reinicializaEstadoDeSelecao(lista, selecionado) {
		for(i = 0; i < lista.length; i++) {
			lista[i].selected = selecionado;
		}
	}
	
	function habilitaDesabilitaElementos(form, estado) {
  		lista = form.elements;
  		for(i=0;i<lista.length;i++) {
    		lista[i].disabled = estado;
  		}
  	}
  	
  	function habilitaElementos(nomeDoForm) {
  		habilitaDesabilitaElementos(document.getElementById(nomeDoForm), false);
  		mudaDisplayDosLinks('');
  	}
  	
  	function desabilitaElementos(nomeDoForm) {
  		habilitaDesabilitaElementos(document.getElementById(nomeDoForm), true);
  		mudaDisplayDosLinks('none');
  	}
  	
  	function mudaDisplayDosLinks(display){
  		objLinks = document.links;
  		for(i=0;i<objLinks.length;i++){
  			objLinks[i].style.display = display;
  		}
	}
  	
  	//Scripts do Eric Pascarello
	function DisableEnableLinks(xHow){
  		objLinks = document.links;
  for(i=0;i<objLinks.length;i++){
    objLinks[i].disabled = xHow;
    //link with onclick
    if(objLinks[i].onclick && xHow){  
        objLinks[i].onclick = new Function("return false;" + objLinks[i].onclick.toString().getFuncBody());
    }
    //link without onclick
    else if(xHow){  
      objLinks[i].onclick = 'function(){return false;}';
    }
    //remove return false with link without onclick
    else if(!xHow && objLinks[i].onclick.toString().indexOf("function(){return false;}") != -1){            
      objLinks[i].onclick = null;
    }
    //remove return false link with onclick
    else if(!xHow && objLinks[i].onclick.toString().indexOf("return false;") != -1){  
      strClick = objLinks[i].onclick.toString().getFuncBody().replace("return false;","")
      objLinks[i].onclick = new Function(strClick);
    }
  }
}

String.prototype.getFuncBody = function(){ 
  var str=this.toString(); 
  str=str.replace(/[^{]+{/,"");
  str=str.substring(0,str.length-1);   
  str = str.replace(/\n/gi,"");
  if(!str.match(/\(.*\)/gi))str += ")";
  return str; 
} 

/////////////////////////////***********************************////////////////////////////////



identificaNavegador();


function desabilitaTecla(e){
	if(valorNavegador == "MOZILLA") {
		e.preventDefault();
		return true;
	} else {
		e.returnValue = false;
		return false;
	}	
}

//Função para retornar a tecla pressinada
function verificakKeycode(e) {
     if(e){
          e = e
     } else {
          e = window.event
     }
     if(e.which){
          var keycode = e.which
     } else {
          var keycode = e.keyCode
     }
	return keycode;
}	


function validaTecla(evento){
	//variavel que controla o if se a tecla foi pressinada
	var teste = false;
	//Captura a tecla que foi acionada
	var t = verificakKeycode(evento);
	//se a tecla for algum numero do teclado ou o backspace então retornar true
	/*Teclas permitidas:
		0-9
		setas
		DELETE
		BACKSPACE
		HOME
		END
	*/
	if( ( ( 48 <= t ) && ( t <= 57 ) ) || ( ( 96 <= t ) && ( t <= 105 ) ) || 
		( ( 35 <= t ) && ( t <= 40 ) ) || t == 8 || t == 9 || t == 46 ){
		teste = true;
	} else {
		teste = desabilitaTecla(evento);	
	}
	return teste;
}
function soNumerico(e){
	return validaTecla(e);
}
	
function removeMascara(obj){
	var str = obj.value;
	var strFinal = "";
	for( i = 0; i < str.length; i++ ){
		if( str.charAt(i).search(/\D/g) ){
			strFinal +=str.charAt(i);
		}	
	}
	obj.value = strFinal;
	setSelecao(obj, 0, strFinal.length);
}
function montaMascara(mascaraArray, obj){
	str = "";	
	strAux = obj.value.replace(/\D/g, "");
	var valorList = getArrayString(strAux);
	var countStr = 0;
	if(strAux != ""){
		for(i=0; i<mascaraArray.length; i++){
			if(mascaraArray[i] == "#")	{
				if( valorList[countStr] == undefined ){
					str += " ";
				} else {
					str += valorList[countStr];					
				}			
				countStr++;			
			} else {
				str += mascaraArray[i];	
			}
		}		
	}
	
	return str;
}
function mascara_campo(obj, e, mascara, valor){

      var mascara_utilizar;
      var mascara_limpa;
      var temp;      
	  var i;
      var j;
	  var caracter;
      var separador;
      var dif;
      var validar;
      var mult;
      var ret;
      var tam;
      var tvalor;
      var valorm;
      var masct;
      tvalor = "";
      ret = "";
      caracter = "#";
      separador = "|";
      mascara_utilizar = "";

      //valor = trim(valor);
      if (valor == "")return valor;
      temp = mascara.split(separador);
      dif = 1000;
      valorm = valor;
      //tirando mascara do valor já existente
      for (i=0;i<valor.length;i++){
            if (!isNaN(valor.substr(i,1)) && valor.substr(i,1) != ' '){
                  tvalor = tvalor + valor.substr(i,1);
            }
      }

      valor = tvalor;
      //formatar mascara dinamica
      for (i = 0; i<temp.length;i++){
            mult = "";
            validar = 0;
            for (j=0;j<temp[i].length;j++){
                  if (temp[i].substr(j,1) == "]"){
                        temp[i] = temp[i].substr(j+1);
                        break;
                  }
                  if (validar == 1)mult = mult + temp[i].substr(j,1);
                  if (temp[i].substr(j,1) == "[")validar = 1;
            }
            for (j=0;j<valor.length;j++){
                  temp[i] = mult + temp[i];
            }
      }

      //verificar qual mascara utilizar
      if (temp.length == 1){
            mascara_utilizar = temp[0];
            mascara_limpa = "";
            for (j=0;j<mascara_utilizar.length;j++){
                  if (mascara_utilizar.substr(j,1) == caracter){
                        mascara_limpa = mascara_limpa + caracter;
                  }
            }
            tam = mascara_limpa.length;
      }else{
            //limpar caracteres diferente do caracter da máscara
            for (i=0;i<temp.length;i++){
                  mascara_limpa = "";
                  for (j=0;j<temp[i].length;j++){
                        if (temp[i].substr(j,1) == caracter){
                             mascara_limpa = mascara_limpa + caracter;
                        }
                  }

                  if (valor.length > mascara_limpa.length){
                        if (dif > (valor.length - mascara_limpa.length)){
                             dif = valor.length - mascara_limpa.length;
                             mascara_utilizar = temp[i];
                             tam = mascara_limpa.length;
                        }

                  }else if (valor.length < mascara_limpa.length){
                        if (dif > (mascara_limpa.length - valor.length)){
                             dif = mascara_limpa.length - valor.length;
                             mascara_utilizar = temp[i];
                             tam = mascara_limpa.length;
                        }
                  }else{
                        mascara_utilizar = temp[i];
                        tam = mascara_limpa.length;
                        break;
                  }
            }
      }

      //validar tamanho da mascara de acordo com o tamanho do valor
      if (valor.length > tam){
            valor = valor.substr(0,tam);
      }else if (valor.length < tam){
            masct = "";
            j = valor.length;
            for (i = mascara_utilizar.length-1;i>=0;i--){
                  if (j == 0) break;
                  if (mascara_utilizar.substr(i,1) == caracter){
                        j--;
                  }
                  masct = mascara_utilizar.substr(i,1) + masct;
            }
            mascara_utilizar = masct;
      }

      //mascarar
      j = mascara_utilizar.length -1;
      for (i = valor.length - 1;i>=0;i--){
            if (mascara_utilizar.substr(j,1) != caracter){
                  ret = mascara_utilizar.substr(j,1) + ret;
                  j--;
            }
            ret = valor.substr(i,1) + ret;
            j--;
      }
      obj.value = ret;
}


var is_gecko = /gecko/i.test(navigator.userAgent);
var is_ie = /MSIE/.test(navigator.userAgent);

function setSelecao(input, start, end) {
	if (is_gecko) {
		input.setSelectionRange(start, end);
	} else {
		// assumed IE
		var range = input.createTextRange();
		range.collapse(true);
		range.moveStart("character", start);
		range.moveEnd("character", end - start);
		range.select();
	}
}

	function selecionaPrimeiroRadio(){
		for (var i=0; i < document.forms[0].elements.length; i++) {
			var obj = document.forms[0].elements[i];
			if (obj.type=="radio"){
				obj.click();
				obj.checked = true;
				break;
			}
		}
	}

	//Função que irá enviar os dados do cep para a janela que chamou a pop up de pesquisa de cep
	//Definir var documentoPai = opener.document; na página que usar a funcao
	//Definir var documentoOriginal = document; na página que usar a funcao
	function selecionaCepGlobal(){
		var cep = documentoOriginal.getElementById('formTemlateBase:cep').value;
		var cidade = documentoOriginal.getElementById('formTemlateBase:cidade').value;
		var codCidade = documentoOriginal.getElementById("formTemlateBase:codCidade").value;
		var uf = documentoOriginal.getElementById("formTemlateBase:uf").value;
		var endereco = documentoOriginal.getElementById("formTemlateBase:endereco").value;
		var bairro = documentoOriginal.getElementById("formTemlateBase:bairro").value;
		var complemento = documentoOriginal.getElementById("formTemlateBase:complemento").value;
		cep=mascara_global('##.###-###',cep);
		if(cep==""){
			alertMsg("Uma opção deve ser selecionada.");
		}else{
			documentoPai.getElementById('formTemlateBase:cep').value=cep;
			documentoPai.getElementById('formTemlateBase:cidade').value=cidade;
			documentoPai.getElementById('formTemlateBase:codCidade').value=codCidade;
			documentoPai.getElementById("formTemlateBase:uf").value=uf;
			documentoPai.getElementById("formTemlateBase:endereco").value=endereco;
			documentoPai.getElementById("formTemlateBase:complemento").value=complemento;
			documentoPai.getElementById("formTemlateBase:bairro").value=bairro;
			documentoPai.getElementById("formTemlateBase:bairroDescricao").value=bairro;
			documentoPai.getElementById('formTemlateBase:cidadeDescricao').value=cidade;
			documentoPai.getElementById('formTemlateBase:cepDescricao').value=cep;
			documentoPai.getElementById("formTemlateBase:enderecoDescricao").value=endereco;
			documentoPai.getElementById("formTemlateBase:ufDescricao").value=uf;
			documentoPai.getElementById('formTemlateBase:cidadeHidden').value = cidade;
			documentoPai.getElementById('formTemlateBase:ufHidden').value = uf;
			documentoPai.getElementById("formTemlateBase:complementoDescricao").value=complemento;
			window.close();
		}
	}

	function naoPermiteEspeciais(campo) {
		campo.value = campo.value.replace(/\W+/m, '');
		campo.value = campo.value.replace(/_+/, '');
	}
	
	 
	//Função que irá enviar os dados do cep para a janela que chamou a pop up de pesquisa de cep
	//Definir var documentoOriginal = document; na página que usar a funcao
	function populaCamposCepGlobal(cep,uf,cidade,codCidade,endereco,complemento,bairro){
		documentoOriginal.getElementById('formTemlateBase:cep').value=cep;
		documentoOriginal.getElementById("formTemlateBase:uf").value=uf;
		documentoOriginal.getElementById('formTemlateBase:cidade').value=cidade;
		documentoOriginal.getElementById('formTemlateBase:codCidade').value=codCidade;
		documentoOriginal.getElementById("formTemlateBase:endereco").value=endereco;
		documentoOriginal.getElementById("formTemlateBase:bairro").value=bairro;
		documentoOriginal.getElementById("formTemlateBase:complemento").value=complemento;
	}
	
	//Função que seta o foco no campo de senha quando houver uma ex
	function campoASetarFocus(){
	    if(document.getElementById('formTemlateBase:Login').value != ' '){
	    	document.getElementById('formTemlateBase:Senha').focus();
	    }else{
	    	document.getElementById('formTemlateBase:Login').focus();
	    }
	}
  	
  	String.prototype.trim = function(){    var re = /^\s+|\s+$/g;
    return function(){ return this.replace(re, ""); };}();
	
	function apagaCamposComEspaco() {
		var elementos = document.forms[0].elements;
		for(i=0; i<elementos.length; i++) {
			if(elementos[i].type != 'hidden' && elementos[i].value != null) {
				if (elementos[i].type == 'select-one') {
				   if(elementos[i].options[0] != null){
					elementos[i].options[0].value = elementos[i].options[0].value.trim();
				   }
			  	}
				elementos[i].value = elementos[i].value.trim();
			}
		}
	}
	
function abreJanelaCorreios(theURL,winName) {
  	var janela = window.open(theURL,winName);
  	janela.focus();
}
