// common-functions.js
//-----------------------------------------------
function criaMascara(_refObjeto, _modelo){
var valorAtual = _refObjeto.value;
var valorNumerico = '';
var nIndexModelo = 0;
var nIndexString = 0;
var valorFinal = '';
var adicionarValor = true;
for (i=0; i < _modelo.length; i++){
if (_modelo.substr(i,1) != '#'){
valorAtual = valorAtual.replace(_modelo.substr(i,1),'');
}
}
for (i=0; i < valorAtual.length; i++){
if (!isNaN(parseFloat(valorAtual.substr(i,1)))) {
valorNumerico = valorNumerico + valorAtual.substr(i,1);
}
}
for (i=0; i < _modelo.length; i++){
if (_modelo.substr(i,1) == '#'){
if (valorNumerico.substr(nIndexModelo,1) != ''){
valorFinal = valorFinal + valorNumerico.substr(nIndexModelo, 1);
nIndexModelo++;
nIndexString++;
} else {
adicionarValor = false;
}
} else {
if (adicionarValor && valorNumerico.substr(nIndexModelo,1) != ''){
valorFinal = valorFinal + _modelo.substr(nIndexString,1);
nIndexString++;
}
}
}
_refObjeto.value = valorFinal
}
function retornaValorRadio(obj) {
var value = "";
var tam = obj.length;
if(tam > 1) {
for(var i=0; i < tam; i++) {
if(obj[i].checked == true) {
value = obj[i].value;
}
}
} else {
value = obj.value;
}
return value;
}
function retiraEspaco(form){
if(form == null)
form = document.forms[0];
for (var i = 0; i < form.elements.length; i++){
form.elements[i].value = Trim(form.elements[i].value);
}
}
function lTrim(str) {
while (str.substr(0, 1)==' ')
str = str.substr(1);
return str;
}
function rTrim(str) {
while(str.substr(str.length -1 , 1)==' ')
str = str.substr(0,str.length - 1);
return str;
}
function Trim(str){
return rTrim(lTrim(str));
}
function somenteNumero(event, objFormElement){
var e = new CrossEvent(event);
var obj_keycode = e.charCode;
if(obj_keycode == 0 || obj_keycode == 13){return true};
if(!validateStrDigits(String.fromCharCode(obj_keycode))){
alert('Atenção: ' + ((getElement('lbf_' + objFormElement.name)) ? 'O campo ' + getElement('lbf_' + objFormElement.name).firstChild.nodeValue : 'Este campo') + ' deve conter um valor numérico.');
objFormElement.focus();
return false
}
} //somenteNumero - ok
function pulaProximo(valor, max, strObjeto) {
var objeto = getElement(strObjeto);
var tam = valor.length;
if(tam >= max) {
objeto.focus();
}
}
function validaData(obj, exibeMsg){
var dia = obj.value;
if(!validateStrDate(dia, 4)) {
msg = dia + " não é uma data válida. Informe a data no formato DD/MM/AAAA";
exibeMsgError(obj, "inline", msg, exibeMsg);
return false;
} else if(obj.value) {
var date = obj.value.split(/\//g);
if(!isBissexto(date[0], date[1], date[2])){
exibeMsgError(obj, "inline", "O mês informado possui somente 28 dias", exibeMsg);
return false;
}
}
exibeMsgError(obj, "", "", "");
return true
} //validaData - ok
function validaEmail(obj, exibeMsg){
if(!validateStrEmail(obj.value, 3)){
msg = obj.value + " não é um endereço de e-mail válido.";
exibeMsgError(obj, "inline", msg, exibeMsg);
return false;
}
exibeMsgError(obj, "", "", "");
return true
}
function isBissexto(day, month, year){
if(month == 2){
if (year % 4 != 0){
if (day > 28){
return false;
}
}
}
return true;
} //isBissexto
function toggleVisibility() {
if( document.getElementById("loading").style.visibility == "hidden" ) {
document.getElementById("loading").style.visibility = "visible";
} else {
document.getElementById("loading").style.visibility = "hidden";
}
}
function createParam(form) {
var elements = form.elements;
var pairs = new Array();
for (var i = 0; i < elements.length; i++) {
if ((name = elements[i].name) && (value = elements[i].value))
pairs.push(name + "=" + encodeURIComponent(value));
}
return pairs.join("&");
}
/**
* @version 1.0, 2007
* @class common-function
*
*/
function inicializarIndices() {
if (document.CargaInicial == null) {
document.CargaInicial = false; // Seta para só fazer uma vez por documento
var ctrlAnterior = null;
var IndAnt = 0;
for (var i = 0; i < document.forms[0].elements.length; i++) {
var e = document.forms[0].elements[i];
if (e.type != "hidden" && e.type != "image") {
if (ctrlAnterior != null)
ctrlAnterior.IndicePosterior = i;
ctrlAnterior = e;
e.Indice = i;
e.IndiceAnterior = i-1;
}
}
}
} //inicializarIndices - ok
function getElement(psID) {
if(document.all) {
return document.all[psID];
} else {
return document.getElementById(psID);
}
} //getElement - ok
function setarFoco(ind) {
if (isNaN(ind) && document.forms[0].elements[ind].type != "hidden")
document.forms[0].elements[ind].focus();
else
for (; ind < document.forms[0].elements.length; ind++)
if (document.forms[0].elements[ind].type != "hidden")
break;
if (ind <= document.forms[0].elements.length)
document.forms[0].elements[ind].focus();
} //setarFoco - ok
function exibeDisplay(htmlObj, isDisplay) {
var o = getElement(htmlObj);
(isDisplay) ? o.style.display = isDisplay : o.style.display = isDisplay;
} //exibeDisplay - ok
function exibeMsgError(o, fExibe, msg, eDiv){
var divErrorName = "divError" + o.name;
if(!getElement(divErrorName)){
var oDiv = document.createElement('div');
oDiv.setAttribute('id', divErrorName);
var parentFirst = o.parentNode;
parentFirst.appendChild(oDiv);
}
if(fExibe == null || fExibe == "") {
fExibe = "none"
};
if(fExibe != "none"){
if(eDiv){
if(eDiv != 'no')
getElement(divErrorName).innerHTML = '
' + msg + '';
} else {
alert(msg);
}
}
if(getElement(divErrorName))
exibeDisplay(divErrorName, fExibe);
return (fExibe == "none")? true : false;
} // exibeDivError - ok
/**
* Valida uma string no formato de e-mail.
* @param String pStr
* E-mail para ser validada.
* @param String pFmt
* Tipo de validação: 1 ou 2 ou 3
*
* 1.Livre: reEmail1 aceita nome-local com todos os caracteres permitidos na RFC 2822: [\w!#$%&'*+/=?^`{|}~-]; e o domínio
* tem definição bem livre, por nome basicamente fixando apenas que o TLD deve ter entre 2 e 6
* caracteres: [A-Za-z]{2,6}; ou por número IP entre colchetes: \[\d{1,3}(\.\d{1,3}){3}\].
* 2.Compacto: reEmail2 limita os caracteres permitidos no nome-local de forma mais compacta e restritiva, porém cobre os casos
* mais comuns. Aceita como nome-local uma ou mais palavras separadas por ponto ([\w-]+(\.[\w-]+)*), onde
* cada palavra é definida por [\w-]+ permitindo assim letra, dígito, sublinhado e hífen. Também limita o
* tamanho de nomes de domínio entre 2 e 63 caracteres apenas com letras, dígitos, sublinhado e hífen: [\w-]{2,63}.
* 3.Restrito: reEmail3 é uma variação da ReEmail2, mas força nomes de domínio entre 2 e 63 caracteres, deixa de usar a
* seqüência \w para não permitir o sublinhado e garante que não há hífen nem na primeira nem na última
* posição, conforme RFC 1034/1035. O resultado é o seguinte para representar um nome de
* domínio: [A-Za-z\d][A-Za-z\d-]{0,61}[A-Za-z\d].
*
* @return true se for uma data valida.
*/
function validateStrEmail(pStr, pFmt) {
var reEmail1 = /^[\w!#$%&'*+\/=?^`{|}~-]+(\.[\w!#$%&'*+\/=?^`{|}~-]+)*@(([\w-]+\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{1,3}){3}\])$/;
var reEmail2 = /^[\w-]+(\.[\w-]+)*@(([\w-]{2,63}\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{1,3}){3}\])$/;
var reEmail3 = /^[\w-]+(\.[\w-]+)*@(([A-Za-z\d][A-Za-z\d-]{0,61}[A-Za-z\d]\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{1,3}){3}\])$/;
var reEmail = reEmail3;
eval("reEmail = reEmail" + pFmt);
if (reEmail.test(pStr)) {
return true;
} else if (pStr != null && pStr != "") {
return false;
}
return true;
} // validateStrEmail
/**
* Valida uma string no formato de data.
* @param String pStr
* Data para ser validada.
* @param String pFmt
* Tipo de validação: 1 ou 2 ou 3 ou 4 ou 5
*
* 1.Simples: reDate1 valida apenas o uso de dígitos, nas posições e quantidade certas: 1 a 2 dígitos para dia e para mês,
* 1 a 4 dígitos para ano.
* 2.Média: reDate2 testa os dígitos possíveis em cada posição: o primeiro dígito do dia, se houver, deve ser de
* 0 a 3 ([0-3]?\d); o primeiro dígito do mês, se houver, deve ser 0 ou 1 ([01]?\d); passamos a aceitar
* apenas 2 ou 4 dígitos para o ano.
* 3.Avançada: reDate3 garante as faixas de valores corretas para dias 1 a 31 ((0?[1-9]|[12]\d|3[01])) e meses
* 1 a 12 ((0?[1-9]|1[0-2])). E aqui optamos por forçar os 2 primeiros dígitos do ano (correspondentes
* ao século), quando fornecidos, a serem 19 ou 20 ((19|20)?\d{2}).
* 4.Completa: reDate4 valida os dias permitidos de acordo com o mês. Para este último, foram criados três grupos alternativos
* de pares dia/mês:
* * Os dias 1 a 29 ((0?[1-9]|[12]\d)) são aceitos em todos os meses (1 a 12): (0?[1-9]|1[0-2])
* * Dia 30 é válido em todos os meses, exceto fevereiro (02): (0?[13-9]|1[0-2])
* * Dia 31 é permitido em janeiro (01), março (03), maio (05), julho (07), agosto (08), outubro (10) e dezembro (12): (0?[13578]|1[02]).
* 5.Tradicional: reDate5 data no formato DD/MM/AAAA, basicamente é a data Completa, porém sem a opcionalidade do zero à esquerda
* no dia ou mês menor que 10 e sem a opcionalidade e verificação de século no ano, aceitando qualquer
* seqüência de 4 dígitos (\d{4}) como ano.
*
* @return true se for uma data valida.
*/
function validateStrDate(pStr, pFmt) {
var reDate1 = /^\d{1,2}\/\d{1,2}\/\d{1,4}$/;
var reDate2 = /^[0-3]?\d\/[01]?\d\/(\d{2}|\d{4})$/;
var reDate3 = /^(0?[1-9]|[12]\d|3[01])\/(0?[1-9]|1[0-2])\/(19|20)?\d{2}$/;
var reDate4 = /^((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 reDate5 = /^((0[1-9]|[12]\d)\/(0[1-9]|1[0-2])|30\/(0[13-9]|1[0-2])|31\/(0[13578]|1[02]))\/\d{4}$/;
var reDate = reDate4;
eval("reDate = reDate" + pFmt);
if (!reDate.test(pStr) && (pStr != null && pStr != "")) {
return false;
}
return true;
} // validateStrDate
function validateStrDigits(pStr){
var reDigits = /^\d+$/;
if (reDigits.test(pStr)) {
return true;
} else if (pStr != null && pStr != "") {
return false;
}
return true;
} //validateStrDigits
/**
* Verifica se a segunda data é menor que a primeira.
* @param Object objDate2
* Primeira data.
* @param Object objDate1
* Segunda data
* @return true se a primeira data é menor que a segunda.
*/
function dateDifference(objDate1, objDate2){
var datDate1 = Date.parse(objDate1.value);
var datDate2 = Date.parse(objDate2.value);
if(isNaN(datDate1) && isNaN(datDate2)){
return true;
}
var nDateDiff = 0;
if(isNaN(datDate1) && !isNaN(datDate2)){
alert("Data de início precisa ser preenchida !");
objDate1.focus();
return false;
}
nDateDiff = ((datDate2 - datDate1) / (24*60*60*1000));
if (nDateDiff < 0){
alert("'" + objDate2.value + "' é menor que data de início !");
objDate2.value = "";
objDate2.focus();
return false;
}
return true;
} // dateDifference
/**
* Verifica se a data é até a data corrente.
* @param Object objDate
* Campo data sendo tratado (DD/MM/YYYY).
* @param Object dateType
* Formato da data:
* type 1 : 19970529 * type 2 : 970529 * type 3 : 29/05/1997 * type 4 : 29/05/97* @return
true se a data é menor ou igual que a corrente.
*/
function isitUntilTodayDate(objDate, dateType) {
datDate1 = Date.parse(objDate.value);
if(isNaN(datDate1)) {
return true;
}
if (objDate.value.length != 10) {
return false;
}
if(!validaData(objDate)){
return false;
}
var now = date_today; // variavel global definida no layout-principal.jsp
var today = new Date(now.getYear(),now.getMonth(),now.getDate());
if (dateType == 1) {
var testdate = new Date(objDate.value.substring(0,4), objDate.value.substring(4,6)-1, objDate.value.substring(6,8));
} else if (dateType == 2) {
var testdate = new Date(objDate.value.substring(0,2), objDate.value.substring(2,4)-1, objDate.value.substring(4,6));
} else if (dateType == 3) {
var testdate = new Date(objDate.value.substring(6,10),objDate.value.substring(3,5)-1,objDate.value.substring(0,2));
} else if (dateType == 4) {
var testdate = new Date(objDate.value.substring(6,8), objDate.value.substring(3,5)-1, objDate.value.substring(0,2));
}
if (testdate <= now) {
return true;
} else {
alert("'" + objDate.value + "' é maior que data atual !");
objDate.value = "";
objDate.focus();
return false;
}
} // isitUntilTodayDate
function fun_set_focus(form_element, str_form_to_set, event){
var form_to_set = getElement(str_form_to_set);
if(form_element.value.length >= form_element.maxLength){
if(!fun_verify_event(event)){
form_to_set.focus();
}
}
} //fun_set_focus
function fun_verify_event(event){
var obj_keycode = ((event.keyCode) ? event.keyCode : event.which);
return ((obj_keycode != 9 && obj_keycode != 16 && obj_keycode != 17 && obj_keycode != 18 && obj_keycode != 20 && obj_keycode != 35 && obj_keycode != 36 && obj_keycode != 37 && obj_keycode != 38 && obj_keycode != 39 && obj_keycode != 40 && obj_keycode != 45 && obj_keycode != 46) ? false : true);
} //fun_verify_event