$(function() { String.prototype.startsWith = function(prefix) { return this.indexOf(prefix) === 0; } String.prototype.endsWith = function(suffix) { return this.match(suffix+"$") == suffix; }; $().ajaxStart(function() { $("#bloquerBrowser").show(); }); $().ajaxComplete(function() { $("#bloquerBrowser").hide(); }); $().ajaxSuccess(function(evnt, request, settings) { $("#bloquerBrowser").hide(); }); $().ajaxError(function(request, settings, exception) { $("#bloquerBrowser").hide(); }); $("form").submit( function(eventObject) { $('#area-mensagens').hide(); // Solução encontrada para Corrigir problema ao fazer download // de relatorios, etc. if ($('#isRelatorio') == undefined || $('#isRelatorio').attr('value') == undefined || $('#isRelatorio').attr('value') == 'false') { try { selecionaItensTodasListas(); } catch (err) { } $("#bloquerBrowser").show(); } else { $('#isRelatorio').attr('value', 'false'); } // } }); $("input[type='submit']") .click(function(eventObject) { if (($(this).attr('value').toUpperCase() == 'CONSULTAR') || ($(this).attr('value').toUpperCase() == 'CONSULTA')) { var valor = $("input[name='paginaAtual']").val(); if (valor == undefined || (parseInt(valor) > 1)) { $("input[name='paginaAtual']").attr('value', '1'); } } }); // Dialog exemplo $('#dialog-exemplo').dialog({ autoOpen : false, modal : true, width : 600, height : 400, resizable : false }); // Dialog exemplo link $('#dialog-exemplo-link').click(function() { $('#dialog-exemplo').dialog('open'); return false; }); // Dialog confirm $('#dialog-confirm').dialog({ autoOpen : false, modal : true, resizable : false, buttons : { "Não" : function() { $(this).dialog("close"); }, "Sim" : function() { submeter(); $(this).dialog("close"); } } }); // Dialog confirm link $('#dialog-confirm-link').click(function() { $('#dialog-confirm').dialog('open'); return false; }); // Dialog fun��es gerais $('#dialog-funcoes').dialog({ autoOpen : false, modal : true, width : 600, height : 400, resizable : false }); // Dialog fiun��es gerais link $('#dialog-funcoes-link').click(function() { $('#dialog-funcoes').dialog('open'); return false; }); // Dialog fiun��es gerais link $('#dialog-situacao-link').click(function() { $('#dialog-situacao').dialog('open'); return false; }); // Datepicker $('#campo-data-de').datepicker({ changeMonth : true, changeYear : true, yearRange : '1900:2010' }); $('#campo-data-a').datepicker({ changeMonth : true, changeYear : true, yearRange : '1900:2010' }); dwr.engine.setErrorHandler(completeDwrErrorHandler); $('.touppercase').on('keypress keydown blur', function () { var currentVal = $(this).val(); $(this).val(currentVal.toUpperCase()); }); }); function fecharTodosOsModais(contexto) { _.forEach($('.ui-dialog-content', contexto.document), function(d){ if ($(d).dialog('isOpen')) { $(d).dialog('close'); } }); } function exibirMensagens(mensagens, tipo, contexto) { if (!tipo) { tipo = 'S';} if (!contexto) {contexto = window;} var tipos = { A: 'msg-alerta', S: 'msg-sucesso', I: 'msg-informativa', E: 'msg-erro', } var mensagemFormatada = ''; var $div = $('#area-mensagens', contexto.document); var $body = $('html, body', contexto.document); fecharTodosOsModais(contexto); if (typeof(mensagens) === typeof('')) { mensagemFormatada = mensagens.replace(/~$/, '').replace(/~/g, '
'); } else { mensagemFormatada = mensagens.join('
'); } $div.html('"); $div.show(); $body.animate({ scrollTop : $div.parent().offset().top }, 'slow'); } function limparMensagens(contexto) { $('#area-mensagens', contexto?contexto.document:window.document).html(''); } /** * Exibe uma mensagem de erro interno na área de mensagens * * @param e */ function erroInterno(e) { var tipoString = typeof(''); if (typeof(e) !== tipoString) { console.error(e); } $modalErroInterno = registrarModal({ largura:800, altura:600, msg: (typeof(e) === tipoString ? e : _.escape(e.toString())), img: null, titulo: 'Detalhes', removerAutomaticamente: true, eventos: { close: function() { limparMensagens(); } } }); exibirMensagens('Ocorreu um erro interno. ', 'E'); desbloquearBrowser(); } function completeDwrErrorHandler(mensagem, exception) { if (!exception.javaClassName.match('BusinessException')) { desbloquearBrowser(); var trace = ''; trace += mensagem + '
'; exception.stackTrace.map(function(val){trace += val?(val.className + "." + val.methodName + "[" + val.lineNumber + "]" + '
'):''}) var cause = exception.cause; while (cause) { trace += "Caused by:
" cause.stackTrace.map(function(val){trace += val?(val.className + "." + val.methodName + "[" + val.lineNumber + "]" + '
'):''}) cause = cause.cause; } erroInterno(trace); } else { dwrErrorHandler(mensagem, exception); } } /** * Realiza uma chamada à função informada, exibindo mensagem caso * aconteça algum erro. Evita que botões do tipo "submit" redirecionem * à tela inicial em caso de erro no script. * * @param f A função a ser chamada * @param args... Argumentos que serão informados à função * @returns false */ function pcall(f, event) { if (typeof(event) === 'object' && typeof(event.preventDefault) === 'function') event.preventDefault(); try { f.apply(this, _.drop(arguments)); } catch (e) { erroInterno(e); } } /** * Registra um modal sem a necessidade de incluir uma div na página. * * @param opcoes * @return O objeto jQuery do modal registrado. */ function registrarModal(opcoes) { if (opcoes.titulo === undefined) { opcoes.titulo = "Confirmação"; } var $divModal = $(''); $('#area-popup').append($divModal); var $divConteudo = $('
'); $divModal.append($divConteudo); if (opcoes.img === undefined) { opcoes.img = 'bkg-modal-confirm.gif'; } if (typeof(opcoes.img) === typeof('')) { $divConteudo.append('# ', opcoes.msg); } else { $divConteudo.append(opcoes.msg); } if (!opcoes.largura) opcoes.largura = 320; if (!opcoes.altura) opcoes.altura = 220; if (!opcoes.botoes) opcoes.botoes = {}; if (!opcoes.eventos) opcoes.eventos = {}; var opcoesDialog = { autoOpen : false, modal : true, resizable : false, width : opcoes.largura, height : opcoes.altura, buttons : {}, open: function() { $(this).parent().find('button:nth-child(1)').focus(); }, close: function() { if (typeof(opcoes.eventos.close) === typeof(function(){})) { opcoes.eventos.close(); } if (opcoes.removerAutomaticamente) { $divModal.remove(); } } } var labelsBotoes = {sim: "Sim", nao: "Não", ok: "Ok"}; _.forEach(opcoes.botoes, function(v,k){ opcoesDialog.buttons[labelsBotoes[k]] = function() { $(this).dialog("close"); if (v) pcall(v); } }); return $divModal.dialog(opcoesDialog); } function keydownLatitudeLongitude(e) { if (e.keyCode == 8) { if (this.selectionEnd >= this.value.length) { var caracter = this.value.charAt(this.selectionEnd - 1); if (caracter == ',' && (this.selectionEnd == 14 || this.selectionEnd == 13)) { this.value = this.value.substring(0, this.selectionEnd - 1); } else if (caracter == ' ') { this.value = this.value.substring(0, this.selectionEnd - 2); } else if (caracter == '°' || caracter == '"' || caracter == '\'') { this.value = this.value.substring(0, this.selectionEnd - 1); } } } } function keyupLatitudeLongitude(e, campo, isLatitude) { var orientacao = ''; if (e.keyCode >= 8 && e.keyCode <= 46) { return; } if (campo.value.length > 0) { if (isLatitude && (campo.value.charAt(0) == 'N' || campo.value.charAt(0) == 'n' || campo.value.charAt(0) == 'S' || campo.value .charAt(0) == 's')) { orientacao = campo.value.charAt(0).toUpperCase(); } else if (!isLatitude && (campo.value.charAt(0) == 'W' || campo.value.charAt(0) == 'w' || campo.value.charAt(0) == 'E' || campo.value .charAt(0) == 'e')) { orientacao = campo.value.charAt(0).toUpperCase(); } else { campo.value = ''; return; } } else { campo.value = ''; return; } campo.value = orientacao + " " + campo.value.replace(/[^0-9]/g, ''); var tamanhoMax = isLatitude ? 10 : 11; var tamanho = campo.value.length; if (tamanho > tamanhoMax) { tamanho = tamanhoMax; } var pos = isLatitude ? 1 : 0; if (campo.value.length >= (5 - pos) && campo.value.length < (7 - pos)) { campo.value = campo.value.substring(0, (5 - pos)) + '° ' + campo.value.substring((5 - pos), tamanho); } else if (campo.value.length >= (7 - pos) && campo.value.length < (9 - pos)) { campo.value = campo.value.substring(0, (5 - pos)) + '° ' + campo.value.substring((5 - pos), (7 - pos)) + '\' ' + campo.value.substring((7 - pos), tamanho); } else if (campo.value.length >= (9 - pos) && campo.value.length < (10 - pos)) { campo.value = campo.value.substring(0, (5 - pos)) + '° ' + campo.value.substring((5 - pos), (7 - pos)) + '\' ' + campo.value.substring((7 - pos), (9 - pos)) + ',' + campo.value.substring((9 - pos), tamanho); } else if (campo.value.length == (10 - pos)) { campo.value = campo.value.substring(0, (5 - pos)) + '° ' + campo.value.substring((5 - pos), (7 - pos)) + '\' ' + campo.value.substring((7 - pos), (9 - pos)) + ',' + campo.value.substring((9 - pos), tamanhoMax) + ''; } else if (campo.value.length >= (11 - pos)) { campo.value = campo.value.substring(0, (5 - pos)) + '° ' + campo.value.substring((5 - pos), (7 - pos)) + '\' ' + campo.value.substring((7 - pos), (9 - pos)) + ',' + campo.value.substring((9 - pos), tamanhoMax) + '"'; } } function converteGrauToHexa(campo, campoHX, isLatitude) { //var isLatitude = campo.val().length == 16 ? false : true; var orientacao = campo.val().substring(0, 1).trim().toUpperCase(); var isLatitude = (orientacao == "S" || orientacao == "N") ? true : false; var pos = isLatitude ? 1 : 0; var graus = parseInt(campo.val().substring(2, (5 - pos))); var minutos = parseInt(campo.val().substring((7 - pos), (9 - pos))); var segundos = parseFloat( campo.val().substring((11 - pos), (16 - pos)).replace(",", ".")) .toFixed(2); var inc = ""; var str = "" + graus; if (!isLatitude && str.length < 3) { var pad = "000"; inc = pad.substring(0, pad.length - str.length); } else if (isLatitude && str.length < 2) { var pad = "00"; inc = pad.substring(0, pad.length - str.length); } var num = (inc + (graus + (minutos / 60) + (segundos / 3600))).replace('.', ''); if (num.length == 3) { num += '0'; } if (!isLatitude) { var pad = "000,0000000000"; inc = pad.substring(str.length, pad.length); } else if (isLatitude) { var pad = "00,0000000000"; inc = pad.substring(str.length, pad.length); } var sinal = ""; if (orientacao == 'W' || orientacao == 'S') { sinal = "-"; } campoHX.val(sinal + num + inc); campoHX.trigger('keyup'); } function converteHexaToGrau(campoHX, campo, isLatitude) { var possuiSinalNegativo = campoHX.val().charAt(0) == "-"; var latitude = campoHX.val(); latitude = latitude.replace(/[\.]/g, ""); if (possuiSinalNegativo) { latitude = latitude.substring(1); } var graus = parseInt(latitude.split(",")[0]); var decimalGraus = parseFloat("0." + latitude.split(",")[1]) * 60; var minutos = ("" + decimalGraus).split('.')[0]; var bigDecimalGraus = parseFloat("0." + ("" + decimalGraus).split(".")[1]) * 60; var segundos = bigDecimalGraus.toFixed(2).replace('.', ','); var str = "" + graus; if (!isLatitude && str.length < 3) { var pad = "000"; graus = pad.substring(0, pad.length - str.length) + str; } else if (isLatitude && str.length < 2) { var pad = "00"; graus = pad.substring(0, pad.length - str.length) + str; } str = "" + minutos; if (str.length < 2) { var pad = "00"; minutos = pad.substring(0, pad.length - str.length) + str; } str = "" + segundos; if (str.length < 5) { var pad = "00,00"; segundos = pad.substring(0, pad.length - str.length) + str; } var orientacao = ""; if (possuiSinalNegativo && !isLatitude) { orientacao = "W"; } else if (possuiSinalNegativo && isLatitude) { orientacao = "S"; } else if (!possuiSinalNegativo && !isLatitude) { orientacao = "E"; } else if (!possuiSinalNegativo && isLatitude) { orientacao = "N"; } campo.val(orientacao + " " + graus + "° " + minutos + "' " + segundos + "\""); campo.trigger('keyup'); } function keydownLatitudeLongitudeHexa(e) { if (e.keyCode == 8) { if (this.value != undefined && this.selectionEnd >= this.value.length) { var caracter = this.value.charAt(this.selectionEnd - 1); if (caracter == ',') { this.value = this.value.substring(0, this.selectionEnd - 1); } } } } function keyupLatitudeLongitudeHexa(e, campo, isLatitude) { var sinal = ''; if (e.keyCode >= 8 && e.keyCode <= 46) { return; } if (campo.value.length > 0 && campo.value.charAt(0) == '-') { sinal = campo.value.charAt(0).toUpperCase(); } var tamanhoMax = 0; if (sinal == '' && !isLatitude) { tamanhoMax = 13; } else if (sinal == '-' && !isLatitude) { tamanhoMax = 14; } else if (sinal == '' && isLatitude) { tamanhoMax = 12; } else if (sinal == '-' && isLatitude) { tamanhoMax = 13; } campo.value = sinal + campo.value.replace(/[^0-9]/g, ''); var tamanho = campo.value.length; if (tamanho > tamanhoMax) { tamanho = tamanhoMax; } var tamanhoParteInteiraSinal = 0; if (sinal == '' && !isLatitude) { tamanhoParteInteiraSinal = 3; } else if (sinal == '-' && !isLatitude) { tamanhoParteInteiraSinal = 4; } else if (sinal == '' && isLatitude) { tamanhoParteInteiraSinal = 2; } else if (sinal == '-' && isLatitude) { tamanhoParteInteiraSinal = 3; } if (campo.value.length >= tamanhoParteInteiraSinal) { campo.value = campo.value.substring(0, tamanhoParteInteiraSinal) + ',' + campo.value.substring(tamanhoParteInteiraSinal, tamanho); } } function dwrErrorHandler(mensagem, exception) { desbloquearBrowser(); if (exception.javaClassName == 'br.gov.mapa.arquitetura.exception.BusinessExceptionAlert') { adicionarMensagem(mensagem, 'A'); } else if (exception.javaClassName == 'br.gov.mapa.arquitetura.exception.BusinessExceptionInfo') { adicionarMensagem(mensagem, 'S'); } else { adicionarMensagem(mensagem, 'E'); } } function adicionarMensagem(mensagem, tipo) { exibirMensagem("area-mensagens", mensagem, tipo); } function exibirMensagem(id, mensagem, tipo) { if (tipo == 'A') { $('#' + id).html( ""); } else if (tipo == 'S') { $('#' + id).html( ""); } else { $('#' + id).html( ""); } $('#' + id).show(); $('html, body').animate({ scrollTop : 0 }, 'slow'); } function bloquearBrowser() { $("#bloquerBrowser").show(); } function desbloquearBrowser() { $("#bloquerBrowser").hide(); } function chkBoxChildByName(objectCheck, nameChkChildArquivo) { var isChecked = !$(objectCheck).attr("checked"); $('input[name="' + nameChkChildArquivo + '"]').each(function() { if (this.disabled == false) { $(this).attr("checked", !isChecked); } }); return true; } function chkBoxChildByClass(objectCheck, classChkChildArquivo) { var isChecked = !$(objectCheck).attr("checked"); $('.'+classChkChildArquivo).each(function() { if (this.disabled == false) { $(this).attr("checked", !isChecked); } }); return true; } function controlCheckAll(objectCheck, nameCheckAll) { var name = $(objectCheck).attr('name'); var totalMarcados = $("input:checkbox[name='" + name + "']:checked").length; var totalChecks = $("input:checkbox[name='" + name + "']").length; var totalDesabilitados = $("input:checkbox[name='" + name + "']:disabled").length if (totalMarcados == (totalChecks - totalDesabilitados)) { $('#' + nameCheckAll).attr('checked', 'checked'); } else { $('#' + nameCheckAll).removeAttr('checked'); } } function controlCheckAllByClass(objectCheck, nameCheckAll) { var attrClass = $(objectCheck).attr('class'); var totalMarcados = $("."+attrClass+":checked").length; var totalChecks = $("."+attrClass).length; var totalDesabilitados = $("."+attrClass+":disabled").length if (totalMarcados == (totalChecks - totalDesabilitados)) { $('#' + nameCheckAll).attr('checked', 'checked'); } else { $('#' + nameCheckAll).removeAttr('checked'); } } /* * Remover a div de mensagens da popup */ function removerBarraMensagensPopup(popup) { $("#" + popup + " > div").hide(); } function removerBarraMensagens() { $('#area-mensagens').hide(); } /** * M�todo exclusivamente utilizando para remover valores de input type text, * select e textarea * * @return */ function removerValoresInputs() { $("input[type='text']").attr("value", ""); $("textarea").val(""); $("select").each(function(sel) { $(this).attr("selectedIndex", 0); }); } function abrirManualUsuario(ref) { window .open( 'paginas/manualusuario/MAPA-SISBRAVET_Manual_do_Usuário.htm#' + ref, 'SISBRAVET_AJUDA', 'toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=no,width=800,height=400'); } function desabilitarInputsDoForm(idContainerPai) { $('#' + idContainerPai).find(':text').attr('disabled', true); $('#' + idContainerPai).find(':radio').attr('disabled', true); $('#' + idContainerPai).find(':checkbox').attr('disabled', true); $('#' + idContainerPai).find('select').attr('disabled', true); $('#' + idContainerPai).find('textarea').attr('disabled', true); } function habilitarInputsDoForm(idContainerPai) { $('#' + idContainerPai).find(':text').removeAttr('disabled'); $('#' + idContainerPai).find(':radio').removeAttr('disabled'); $('#' + idContainerPai).find(':checkbox').removeAttr('disabled'); $('#' + idContainerPai).find('select').removeAttr('disabled'); $('#' + idContainerPai).find('textarea').removeAttr('disabled'); } function desabilitarInputsForm() { $("input[type='text']").attr("disabled", true); $("input[type='radio']").attr("disabled", true); $("input[type='checkbox']").attr("disabled", true); $("select").attr("disabled", true); $("textarea").attr("disabled", true); } function habilitaInputsForm() { $("input[type='text']").attr("disabled", false); $("input[type='radio']").attr("disabled", false); $("input[type='checkbox']").attr("disabled", false); $("select").attr("disabled", false); $("textarea").attr("disabled", false); } function habilitaInputs(input) { $(input).removeClass('form-disabled'); $(input).addClass('form-text'); $(input).attr('disabled', false); } function desabilitaInputs(input) { $(input).removeClass('form-text'); $(input).addClass('form-disabled'); $(input).attr('disabled', true); } // Habilita os inputs/object/element de todos os filhos do elemento pai(passando // o id do element pai). // IdElement parent, isHabilitar (false or true) function habilitaDesabilitaInputsChildsForm(idElement, isHabilitar) { var pegaTodos = { pega : function(maiorDeTodos) { var filho; // Passo por todos os controles. $(maiorDeTodos) .children() .each( function(i) { filho = $(this); var nomeTag = $.trim($(filho).attr("tagName")); if ($(filho).attr('type') != undefined && $.trim($(filho).attr('type') .toLowerCase()) != 'text/javascript' && $.trim($(filho).attr('type') .toLowerCase()) != 'hidden' && $.trim(nomeTag.toLowerCase()) != 'script') { if ($(filho).attr("disabled") == !isHabilitar) { $(filho).attr("disabled", isHabilitar); } if ($(filho).css("display") == 'hidden' || $(filho).css("display") == 'none' || $(filho).css("visibility") == 'hidden') { if (isHabilitar) { $(filho).show(); } else { $(filho).hide(); } } } if ($(filho).children().length != 0) { pegaTodos.pega($(filho)); } }); } }; pegaTodos.pega($("#" + idElement)); } function limitarCaracteres(limitField, limitNum) { limitField.value = limitField.value.replace(new RegExp("\r", "g"), " ") .replace(new RegExp("\n", "g"), " "); if (limitField.value.length > limitNum) { limitField.value = limitField.value.substring(0, limitNum); } } function removerAreaMensagem() { $('#area-mensagens').hide(); $('#areaMensagemDownload').html(''); } /* * Bloquear ctrl + v * */ function noCopy(event) { var tecla = String.fromCharCode(event.keyCode).toLowerCase(); if (event.ctrlKey && (tecla == "c" || tecla == "v")) { window.event ? event.returnValue = false : event.preventDefault(); return false; } } function retirarMascara(nr) { $(document).ready(function() { var idCampo = "#" + nr; $(idCampo).unmask(); }); } function maxLengthTextArea(object, maxLen) { var tamanho = object.value.length; var tex = object.value; if (tamanho >= maxLen) { object.value = tex.substring(0, maxLen); return false; } return true; } function htmlFocus(elemento) { if (document.getElementById(elemento) != undefined && document.getElementById(elemento).disabled == false) document.getElementById(elemento).focus(); } function selecionarItensLista(idLista) { var objectSelect = document.getElementById(idLista); if (objectSelect != null) { for (var i = 0; i < objectSelect.options.length; i++) { objectSelect.options[i].selected = true; } } } function tirarSelecaoItensLista(idLista) { var objectSelect = document.getElementById(idLista); if (objectSelect != null) { for (var i = 0; i < objectSelect.options.length; i++) { objectSelect.options[i].selected = false; } } } function OnDivScroll(idListaObjetos) { if (idListaObjetos.options.length > 8) { idListaObjetos.size = idListaObjetos.options.length; } else { idListaObjetos.size = 8; } } function noSubmit(event) { var tecla = event.keyCode || event.witch; if (tecla == 13) { return false; } } function retiraOpcoesLista(idLista, idListaSelecionados) { var i = 0; selecionarItensLista(idLista); selecionarItensLista(idListaSelecionados); var lista = dwr.util.getValue(idLista); var listaSelecionados = dwr.util.getValue(idListaSelecionados); while (listaSelecionados.length > 0 && i < listaSelecionados.length) { var id = listaSelecionados[i]; var existeLista = false; for (var j = 0; j < lista.length; j++) { if (id == lista[j]) { existe = true; break; } } var existeListaSelecionados = false; for (var j = 0; j < listaSelecionados.length; j++) { if (id == listaSelecionados[j]) { existe = true; break; } } if (!existeLista) { $("#" + idListaSelecionados + " option[value='" + id + "']") .remove(); } else { if (existeListaSelecionados) { $("#" + idLista + " option[value='" + id + "']").remove(); } } i++; } tirarSelecaoItensLista(idLista); tirarSelecaoItensLista(idListaSelecionados); } function validaData(digData) { var bissexto = 0; var data = digData.value; var tam = data.length; if (tam == 10) { var dia = data.substr(0, 2); var mes = data.substr(3, 2); var ano = data.substr(6, 4); if ((ano > 1900) || (ano < 2100)) { switch (mes) { case '01': case '03': case '05': case '07': case '08': case '10': case '12': if (dia <= 31) { return true; } break case '04': case '06': case '09': case '11': if (dia <= 30) { return true; } break case '02': /* Validando ano Bissexto / fevereiro / dia */ if ((ano % 4 == 0) || (ano % 100 == 0) || (ano % 400 == 0)) { bissexto = 1; } if ((bissexto == 1) && (dia <= 29)) { return true; } if ((bissexto != 1) && (dia <= 28)) { return true; } break } } digData.value = ''; } else { digData.value = ''; } return false; } function limitarTextArea(limitField, limitNum) { var length = 0; for (var i = 0; i < limitField.value.length; i++) { if (limitField.value[i] == '\r' || limitField.value[i] == '\n') { length += 2; if (i < limitNum) { limitNum = limitNum - 1; } } else { length++; } } if (length > limitNum) { limitField.value = limitField.value.substring(0, limitNum); } } function validaTamanhoCampo(campo, tamanhoPermitido) { var tamanho = campo.value.length; if (tamanho != tamanhoPermitido) { campo.value = ''; } } function somenteNumero(campo) { validarMascara(campo, '0123456789'); } function configuraData(data) { $("#" + data).setMask({ mask : "99/99/9999" }); $("#" + data).datepicker({ changeMonth : true, changeYear : true, yearRange : "1900:2050", showOn : 'focus', beforeShow : function(input) { $(input).dialog("widget").css({ "position" : "relative", "z-index" : 1000 }); }, onClose : function(input) { $(input).dialog("widget").css({ "position" : "initial", "z-index" : 0 }); $(this).css({ "position" : "initial", "z-index" : 0 }); } }); } function maxlengthTextarea(textarea, limit) { $(textarea).keypress(function(e) { if (this.value.length >= limit) { return false; } return true; }).keyup(function(e) { validarMaxlength(this, limit); }).mouseout(function(e) { validarMaxlength(this, limit); }).blur(function(e) { validarMaxlength(this, limit); }); } function validarMaxlength(campo, lengthTextArea) { if (campo.value.length >= lengthTextArea) { campo.value = campo.value.substr(0, lengthTextArea); } } function limparParametroOrdenacao() { $("input[name='paginaAtual']").attr('value', '1'); $("input[name='parametrosConsulta.parametroAscDesc']").val(''); $("input[name='parametrosConsulta.parametroOrdenacao']").val(''); } function aplicaMascaraCnpjCpf(campo) { idCampo = '#' + campo; var valor = $(idCampo).val(); if (typeof valor != "undefined") { valor = valor.replace(/[^0-9]/g, ''); if (valor.length == 11) { $(idCampo).setMask("999.999.999-99"); } else if (valor.length == 14) { $(idCampo).setMask("99.999.999/9999-99"); } else { $(idCampo).val(''); $(idCampo).setMask({ mask : "99999999999999" }); } } } function aplicaMascaraCnpjCpfOnMouseMove(campo) { validarMascara(campo, '0123456789-./'); } function validarMascara(campo, caracteresAceitaveis) { var campo_temp; if (campo.value != null && campo.value != undefined) { for (var i = 0; i < campo.value.length; i++) { campo_temp = campo.value.substring(i, i + 1); if (caracteresAceitaveis.indexOf(campo_temp) == -1) { campo.value = campo.value.substring(0, i); } } } } function limparMascaraCpfCnpj(campo) { var idCampo = '#' + campo; $(idCampo).setMask("99999999999999"); } function converteLatLon(num, tipo, id, id2) { // converção de latitude decimal para sexagesimal if (num != '') { var numero = num.split(","); var graus; var numStr = numero[0].replace(/[^0-9]/g, ''); if (tipo == "latitude") { // Verifica se o grau e negativo ou positivo if (numero[0].indexOf("-")) { graus = "N "; } else { graus = "S "; } } else if (tipo == "longitude") { if (numero[0].indexOf("-")) { graus = "E "; } else { graus = "W "; } } // exemplo // # Multiplique o decimal por 60 (0.9874 * 60 = 59.244) if (numero.length >= 1) { var concatMinuto; if (numero == 0) { concatMinuto = "0"; } else { concatMinuto = "0." + numero[1]; } var minuto = concatMinuto * 60; // divido o minuto em 2 para fazer a mutiplicação dos segundos var minuString = minuto.toString().split("."); var concatSegundo = ""; if (minuString == "0") { concatSegundo = "0." + minuString; } else { concatSegundo = "0." + minuString[1]; } var segundo = concatSegundo * 60; var segQue = segundo.toString().substring(0, 4); segQue = segQue.replace(".", ","); if (!isNaN(minuString[0]) && !isNaN(segQue[0])) { defineLatLon(graus, numStr, minuString[0], segQue, id2, tipo); } } } } function defineLatLon(graus, numeroGrau, minutos, segundos, id, tipo) { if (minutos.length == 1) { minutos = "0" + minutos; } if (segundos.length == 1) { segundos = "0,0" + segundos; } if (tipo == "latitude") { if (numeroGrau.length == 1) { $("#" + id).val( graus + "0" + numeroGrau + '° ' + minutos + "' " + segundos + '"'); } else if (numeroGrau.length == 2) { $("#" + id) .val(graus + numeroGrau + '° ' + minutos + "' " + segundos + '"'); } } else { if (numeroGrau.length == 1) { $("#" + id).val( graus + "00" + numeroGrau + '° ' + minutos + "' " + segundos + '"'); } else if (numeroGrau.length == 2) { $("#" + id).val( graus + "0" + numeroGrau + '° ' + minutos + "' " + segundos + '"'); } else if (numeroGrau.length == 3) { $("#" + id) .val( graus + numeroGrau + '° ' + minutos + "' " + segundos + '"'); } } } // converte de sexagesimal para decimal function sexagesimalDec(evt, tipo, id, id2) { var num = evt.target.value; if (evt.keyCode != 8 && evt.keyCode != 46 && evt.keyCode != 9) { // primeiro caracter digitado var res = num.substring(0, 1); // divide a string var quebraString = num.split(""); var total = num.length; if (num != '') { var numero = num.split(" "); var graus; var restante; var resultSegundo; if (numero[1] != null) { var numStr = numero[1].replace(/[^0-9]/g, ''); // Verifica se o grau e negativo ou positivo if (numero[0].indexOf('S') >= 0 || numero[0].indexOf('W') >= 0) { graus = "-" + parseInt(numStr); } else { graus = parseInt(numStr); } } if (numero[3] != null) { // converte os segundos para decimais var numStrSeg = numero[3].substring(0, 4); var segundo = parseInt(numStrSeg) / 60; var segString = segundo.toString().split('.'); if (segString != 0) { resultSegundo = segString[1]; } else { resultSegundo = segString; } } if (numero[2] != null) { // converte os minutos para decimais var numStrMinu = numero[2].replace(/[^0-9]/g, ''); var minutoSom = numStrMinu + '.' + resultSegundo; var minuto = minutoSom / 60; var minutoQue = minuto.toString().split('.'); // so preenche os campos com o calculo convertido atraves dessa // validação if (typeof (minutoQue[1]) !== "undefined" && minutoQue[1].length > 6 && !isNaN(minutoQue[1]) && !isNaN(minutoQue[0])) { restante = minutoQue[1].substring(0, 6); $("#" + id2).val(graus + ',' + restante); } else if (!isNaN(minutoQue)) { restante = minutoQue; $("#" + id2).val(graus + ',' + restante); } } } } } /** * Ordena os valores de uma combo-box. Ou de um dual-list. * Mesmo que os valores contenham acentuacao. * @param id_componente */ function ordenarSelect(id_componente){ var selectToSort = jQuery('#' + id_componente); var optionActual = selectToSort.val(); selectToSort.html(selectToSort.children('option').sort(function (a, b) { return a.text.localeCompare(b.text); })).val(optionActual); } function replaceAll(charSequence, oldChar, newChar) { var i = 0; while ((i = charSequence.indexOf(oldChar, i)) != -1) { charSequence = charSequence.replace(oldChar, newChar); } return charSequence; } function isVazio(texto) { return !isNaoVazio(texto); } function isNaoVazio(texto) { return texto && texto.trim() != '' && texto.trim() != 'null'; } function bloqueiaEnter(){ $('.form-text').keypress(function(e) { if(e.which == 13) { e.preventDefault(); } }); } function bloqueiaColar(){ $('.form-text').bind("cut copy paste",function(e) { $(this).val(""); e.preventDefault(); }); } function bloqueiaArrastaSolta(){ $('input').on('drop', function(event) { $(this).val(""); event.preventDefault(); }); } function desabilitarBotao(idBotao) { $('#' + idBotao).attr('disabled', 'disabled'); $('#' + idBotao).addClass('form-button-disabled'); } function habilitarBotao(idBotao) { $('#' + idBotao).removeAttr('disabled'); $('#' + idBotao).removeClass('form-button-disabled'); } function isPreenchido(valor) { return valor && valor != null && valor != '' && valor !== undefined; } function isNaoPreenchido(valor) { return !isPreenchido(valor); } function defineConversaoLatLon(){ $("#latitude").keydown(function(event){keydownLatitudeLongitude.call(this, event)}); $("#longitude").keydown(function(event){keydownLatitudeLongitude.call(this, event)}); $("#latitudeHX").keydown(function(event){keydownLatitudeLongitudeHexa.call(this, event)}); $("#longitudeHX").keydown(function(event){keydownLatitudeLongitudeHexa.call(this, event)}); $("#latitude").keyup(function(event){keyupLatitudeLongitude(event, this, true)}); $("#longitude").keyup(function(event){keyupLatitudeLongitude(event, this, false)}); $("#latitudeHX").keyup(function(event){keyupLatitudeLongitudeHexa(event, this, true)}); $("#longitudeHX").keyup(function(event){keyupLatitudeLongitudeHexa(event, this, false)}); $("#longitude").focusout(function () { if (this.value.length != 17) { $("#longitude").val(''); }else{ converteGrauToHexa($("#longitude"), $("#longitudeHX"), false); } }); $("#latitude").focusout(function () { if (this.value.length != 16) { $("#latitude").val(''); }else{ converteGrauToHexa($("#latitude"), $("#latitudeHX"), true); } }); $("#longitudeHX").focusout(function () { if (this.value.length <= 6) { $("#longitudeHX").val(''); }else{ converteHexaToGrau($("#longitudeHX"), $("#longitude"), false); } }); $("#latitudeHX").focusout(function () { if (this.value.length <= 5) { $("#latitudeHX").val(''); }else{ converteHexaToGrau($("#latitudeHX"), $("#latitude"), true); } }); if ($("#latitude").val().length == 16) { converteGrauToHexa($("#latitude"), $("#latitudeHX"), true); } if ($("#latitudeHX").val().length >= 5){ converteHexaToGrau($("#latitudeHX"), $("#latitude"), true); } if ($("#longitude").val().length == 17) { converteGrauToHexa($("#longitude"), $("#longitudeHX"), false); } if ($("#longitudeHX").val().length >= 5){ converteHexaToGrau($("#longitudeHX"), $("#longitude"), false); } } function getFloat(valorStr) { var valor = ''; if (isPreenchido(valorStr)) { valorStr = replaceAll(valorStr, '.', ''); valorStr = replaceAll(valorStr, ',', '.'); valor = parseFloat(valorStr); } return valor; } function replaceAll(valor, oldChar, newChar) { if (isPreenchido(valor)) { while (valor.indexOf(oldChar) >= 0) { valor = valor.replace(oldChar, newChar); } } return valor; } function getDate(dateStr) { var newDate; if (isPreenchido(dateStr)) { newDate = new Date(replaceAll(dateStr, '-', '/').replace(/(\d{2})\/(\d{2})\/(\d{4})/, '$2/$1/$3')); } return newDate; } function getDataFormatada(date) { return $.datepicker.formatDate('dd/mm/yy', date); } function isDataMaiorQueAtual(dataStr) { return isDataMaiorQue(dataStr, getDataFormatada(new Date())); } function isDataMaiorQue(dataStr1, dataStr2) { var date1 = getDate(dataStr1); var date2 = getDate(dataStr2); return date1 > date2; } function getDateStrDiff(dateStr1, dateStr2, interval) { return getDateDiff(getDate(dateStr1), getDate(dateStr2), interval); } function getDateDiff(date1, date2, interval) { var second = 1000; var minute = second * 60; var hour = minute * 60; var day = hour * 24; var week = day * 7; var dateone = new Date(date1).getTime(); var datetwo = new Date(date2).getTime(); var timediff = datetwo - dateone; var secdate = new Date(date2); var firdate = new Date(date1); if (isNaN(timediff)) { return NaN; } switch (interval) { case "anos": return secdate.getFullYear() - firdate.getFullYear(); case "meses": return ((secdate.getFullYear() * 12 + secdate.getMonth()) - (firdate.getFullYear() * 12 + firdate.getMonth())); case "semanas": return Math.floor(timediff / week); case "dias": return Math.floor(timediff / day); case "horas": return Math.floor(timediff / hour); case "minutos": return Math.floor(timediff / minute); case "segundos": return Math.floor(timediff / second); default: return undefined; } } function removeItensOpcoesSelecaoLista(param1, param2) { origem = '#'+param1+' option'; destino = '#'+param2+' option[value="'; $(origem).each(function (index, item) { $(destino + item.value +'"]').remove(); }); } function tratarSubmitAoClicarNaTeclaEnter(idForm) { if (isPreenchido(idForm)) { $('#' + idForm).keypress(function(e) { if(e.which == 13 && e.target.type != 'submit') {//13 - Tecla 'enter' e input diferente de submit e.preventDefault(); } }); } }