// Obtener hijos de un elemento HTML
function getHijos (elemento) {
var todos = document.getElementsByTagName('*');
var hijos = [];
for ( var i=0; i<todos.length; i++ ) {
if ( todos[i].parentNode == elemento ) {
hijos.push(todos[i]);
}
}
return hijos;
}
// Obtener elementos po tagName, class o id
function getElements (cadena) {
var res = null;
var abc = [ 'a','b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' ];
if ( cadena.charAt(0) == '.' ) {
var res2 = document.getElementsByClassName(cadena.substring(1));
var res = [];
for ( let k=0; k<res2.length; k++ ) {
if ( res2[k].localName ) {
let nodo = res2[k];
res.push(nodo);
}
}
if (res.length == 0) {
res = [];
}
} else if ( cadena.charAt(0) == '#' ) {
let nodo = document.getElementById(cadena.substring(1));
res = nodo;
} else if ( cadena.charAt(0) == ':' ) {
res = [];
var dataset = cadena.split(':')[1];
var valor = cadena.split(':')[2];
var todos = document.getElementsByTagName('*');
for ( var i=0; i<todos.length; i++ ) {
if (todos[i].attributes[dataset]) {
if ( todos[i].attributes[dataset].nodeValue == valor ) {
let nodo = todos[i];
res.push(nodo);
}
}
}
} else {
for ( var i=0; i<abc.length; i++ ) {
if ( cadena.charAt(0) == abc[i] ) {
let nodos = document.getElementsByTagName(cadena);
let nodos2 = [];
for ( let k=0; k<nodos.length; k++ ) {
let nodo = nodos[k];
nodos2.push(nodo);
}
res = nodos2;
break;
}
}
if ( res.length == 0 ) {
res = [];
}
}
return res;
}
// Obtener elementos po tagName, class o id
Element.prototype.getElements = function (cadena) {
let dom = this;
var res = null;
var abc = [ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' ];
if ( cadena.charAt(0) == '.' ) {
var res2 = dom.getElementsByClassName(cadena.substring(1));
var res = [];
for ( let k=0; k<res2.length; k++ ) {
if ( res2[k].localName ) {
let nodo = res2[k];
res.push(nodo);
}
}
if (res.length == 0) {
res = [];
}
} else if ( cadena.charAt(0) == '#' ) {
let nodo = dom.getElementById(cadena.substring(1));
res = nodo;
} else if ( cadena.charAt(0) == ':' ) {
res = [];
var dataset = cadena.split(':')[1];
var valor = cadena.split(':')[2];
var todos = dom.getElementsByTagName('*');
for ( var i=0; i<todos.length; i++ ) {
if (todos[i].attributes[dataset]) {
if ( todos[i].attributes[dataset].nodeValue == valor ) {
let nodo = todos[i];
res.push(nodo);
}
}
}
} else {
for ( var i=0; i<abc.length; i++ ) {
if ( cadena.charAt(0) == abc[i] ) {
let nodos = dom.getElementsByTagName(cadena);
let nodos2 = [];
for ( let k=0; k<nodos.length; k++ ) {
let nodo = nodos[k];
nodos2.push(nodo);
}
res = nodos2;
break;
}
}
if ( res.length == 0 ) {
res = [];
}
}
return res;
}
// Comprobar input, texarea u otro TAG está vacio
function vacio (elemento) {
var condicion = false;
if ( elemento.tagName == 'INPUT' || elemento.tagName == 'TEXTAREA' || elemento.tagName == 'SELECT' ) {
if ( elemento.value == '' || elemento.value == ' ' || elemento.value == ' ' ) {
condicion = true;
// elemento.classList.add('vacio');
}
} else if ( elemento.tagName == 'IMG' ) {
var xhr = new XMLHttpRequest();
xhr.open('HEAD', elemento.src, false);
xhr.send(null);
if ( xhr.status == 200 ) {
condicion = true;
}
} else {
if ( elemento.innerHTML == '' || elemento.innerText == '' ) {
condicion = true;
}
}
return condicion;
}
// Comprobar si hay coincidencia entre dos Strings
function coincidencia (cadena, busqueda) {
var condicion = false;
if ( Array.isArray(busqueda) && typeof cadena == 'string' ) {
for ( var i=0; i<busqueda.length; i++ ) {
if ( busqueda[i] != '' ) {
if ( cadena.indexOf(busqueda[i]) != -1 ) {
condicion = true;
break;
}
}
}
} else if ( typeof busqueda == 'string' && typeof cadena == 'string' ) {
if ( busqueda != '' ) {
if ( cadena.indexOf(busqueda) != -1 ) {
condicion = true;
}
}
} else {
var error = new Error('Distinto tipo, sugerencia: coincidencia(string, string) || coincidencia(string, array)');
}
if (error) {
throw error;
} else {
return condicion;
}
}
// Comprobar si hay coincidencia entre dos Strings
function coincidenciax (cadena, busqueda) {
var condicion = true;
if ( Array.isArray(busqueda) && typeof cadena == 'string' ) {
for ( var i=0; i<busqueda.length; i++ ) {
if ( busqueda[i] != '' ) {
if ( cadena.indexOf(busqueda[i]) == -1 ) {
condicion = false;
break;
}
}
}
} else if ( typeof busqueda == 'string' && typeof cadena == 'string' ) {
if ( busqueda != '' ) {
if ( cadena.indexOf(busqueda) == -1 ) {
condicion = false;
}
}
} else {
var error = new Error('Distinto tipo, sugerencia: coincidenciax(string, string) || coincidenciax(string, array)');
}
if (error) {
throw error;
} else {
return condicion;
}
}
// Comprobar si hay coincidencia entre dos Strings
function igual (cadena, busqueda) {
var condicion = false;
if ( Array.isArray(busqueda) && typeof cadena == 'string' ) {
for ( var i=0; i<busqueda.length; i++ ) {
if ( busqueda[i] != '' ) {
if ( cadena == busqueda[i] ) {
condicion = true;
break;
}
}
}
} else if ( typeof busqueda == 'string' && typeof cadena == 'string' ) {
if ( busqueda != '' ) {
if ( cadena == busqueda ) {
condicion = true;
}
}
} else {
var error = new Error('Distinto tipo, sugerencia: igual(string, string) || igual(string, array)');
}
if (error) {
throw error;
} else {
return condicion;
}
}
// Hacer verdadero todos los inputs checkbox
function trueChecks () {
var inputs = getElements('input');
var checks = [];
for ( var i=0; i<inputs.length; i++ ) {
inputs[i].checked = true;
checks.push(inputs[i]);
}
}
function falseChecks () {
var inputs = getElements('input');
var checks = [];
for ( var i=0; i<inputs.length; i++ ) {
inputs[i].checked = false;
checks.push(inputs[i]);
}
}
function ultimo (elem) {
var res = null;
if (Array.isArray(elem) || elem.constructor.name == 'HTMLCollection') {
res = elem[elem.length - 1];
} else if (typeof elem == 'string') {
res = elem.charAt(elem.length - 1);
} else if (typeof elem == 'number') {
elem = elem.toString();
res = elem.charAt(elem.length - 1);
} else {
let type = elem.constructor.name;
var mensaje = `Error: tipo no aceptado. Sugerencia: (Array) || (String) || (int). No soporta: ${type}`;
res = new Error(mensaje);
var errorCond = true;
}
if (errorCond) {
throw res;
} else {
return res;
}
}
// Reemplazar texto
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
function reemplazarTexto ( cadena, busc, reem ) {
let res = '';
let condicion = true;
if ( typeof busc == 'string' && typeof reem == 'string' ) {
res = cadena.replace(new RegExp(escapeRegExp(busc), 'g'),reem);
} else if ( Array.isArray(busc) && Array.isArray(reem) ) {
if ( busc.length == reem.length ) {
for ( let i=0; i<busc.length; i++ ) {
let b = busc[i];
b = new RegExp(escapeRegExp(b), 'g');
// console.log(`cadena:${cadena} b:${b} reem[${i}]:${reem[i]}`);
cadena = cadena.replace(b,reem[i]);
}
res = cadena;
} else {
let mensajeError = 'Distinta longitud de Array\'s';
condicion = false;
}
} else if ( Array.isArray(busc) && typeof reem == 'string' ) {
for ( let i=0; i<busc.length; i++ ) {
cadena = cadena.replace(new RegExp(escapeRegExp(busc[i]), 'g'),reem);
}
res = cadena;
} else {
let mensajeError = 'Parametros no válidos, sugerencia: (string, array, array) || (string, array, string) || (string, string, string)';
condicion = false;
}
if (condicion) {
return res;
} else {
let error = new Error(mensajeError);
throw error;
}
}
String.prototype.reemplazarTexto = function ( busc, reem ) {
let res = '';
let condicion = true;
let cadena = this;
if ( typeof busc == 'string' && typeof reem == 'string' ) {
res = cadena.replace(new RegExp(escapeRegExp(busc), 'g'),reem);
} else if ( Array.isArray(busc) && Array.isArray(reem) ) {
if ( busc.length == reem.length ) {
for ( let i=0; i<busc.length; i++ ) {
let b = busc[i];
b = new RegExp(escapeRegExp(b), 'g');
// console.log(`cadena:${cadena} b:${b} reem[${i}]:${reem[i]}`);
cadena = cadena.replace(b,reem[i]);
}
res = cadena;
} else {
let mensajeError = 'Distinta longitud de Array\'s';
condicion = false;
}
} else if ( Array.isArray(busc) && typeof reem == 'string' ) {
for ( let i=0; i<busc.length; i++ ) {
cadena = cadena.replace(new RegExp(escapeRegExp(busc[i]), 'g'),reem);
}
res = cadena;
} else {
let mensajeError = 'Parametros no válidos, sugerencia: (string, array, array) || (string, array, string) || (string, string, string)';
condicion = false;
}
if (condicion) {
return res;
} else {
let error = new Error(mensajeError);
throw error;
}
}
// Comprobar que un String sirva para
// crear un JSON
function isJsonString (str) {
try {
var json = JSON.parse(str);
} catch (e) {
return false;
}
return true;
}
function isDOMObject (str) {
try {
var dom = new DOMParser();
nodo = dom.parseFromString(str, 'text/xml');
} catch (e) {
return false;
}
return true;
}
var consola = true;
function consolelog (w) {
if (consola) {
console.warn(w);
}
}
function funcion(func, args=[]) {
if ( !window[func] ) {
var error = new Error(`${func}() no está definida`);
throw error;
} else {
if ( typeof eval(func) !== 'function' ) {
var error = new Error(`${func}() no es una función`);
throw error;
}
if (args==null || args.length==0) {
return window[func]();
} else {
return window[func].apply(window, args);
}
}
}
function noInputsVacios (ob, clase=true) {
var condicion = true;
var num = false;
if ( typeof ob === 'object' ) {
for ( let k in ob ) {
if ( ob[k].value == '' ) {
condicion = false;
num = k;
if (clase) ob[k].classList.add('mal');
}
}
} else {
if ( ob.value == '' ) {
condicion = false;
num = 0;
}
}
if (condicion) {
return condicion;
} else {
return num;
}
}
function noInputsVacios2 (ob) {
var condicion = true;
var num = false;
if ( typeof ob === 'object' ) {
for ( let k in ob ) {
if ( ob[k].value == '' ) {
condicion = false;
num = k;
ob[k].classList.add('maluma');
}
}
} else {
if ( ob.value == '' ) {
condicion = false;
num = 0;
}
}
if (condicion) {
return condicion;
} else {
return num;
}
}
function mostrar (boton, elemento) {
if ( boton === event.target ) {
elemento.classList.toggle('mostrar');
}
}
function existeFecha (fecha) {
if (fecha != '0000-00-00 00:00:00') {
return true;
}
return false;
}
function clickLabel (label) {
var id = label.dataset.for;
var input = getElements('#'+id);
if (input) {
input.click();
} else {
console.error(`No existe objeto con el id: ${id}`);
}
}
function getMes (num) {
var meses = [
'Enero',
'Febrero',
'Marzo',
'Abril',
'Mayo',
'Junio',
'Julio',
'Agosto',
'Septiembre',
'Octubre',
'Noviembre',
'Diciembre'
];
return meses[num];
}
function mostrarMensaje (str) {
var p = getElements('#p-mensaje-alerta');
p.innerHTML = str;
var modal = getElements('#modal-mensaje-alerta');
modal.classList.add('mostrar');
// penultimoModal = ultimoModal;
// ultimoModal = modal;
}
function mostrarToast (str) {
let p = getElements('#parrafo-toast');
p.innerHTML = str;
let toast = getElements('#toast');
toast.classList.add('mostrar');
setTimeout(function () {
toast.classList.remove('mostrar');
}, 3000);
}
function cerrarModal (elem, modal, call) {
if (elem == event.target) {
if ( modal != undefined ) {
modal.classList.remove('mostrar');
if ( call != undefined ) {
call();
}
} else {
elem.classList.remove('mostrar');
if ( call != undefined ) {
call();
}
}
}
}
function es_tipo_imagen (tipo) {
var condicion = false;
if ( coincidencia(tipo, 'image/') ) {
condicion = true;
}
return condicion;
}
function es_tipo_texto (tipo) {
var condicion = false;
if (coincidencia(tipo, 'text/')) {
condicion = true;
}
return condicion;
}
function es_tipo_pdf (tipo) {
var condicion = false;
if (tipo == 'application/pdf') {
condicion = true;
}
return condicion;
}
function es_tipo_excel (tipo) {
var formatos = 'application/msword, ';
formatos += 'application/vnd.ms-word.document.macroEnabled.12, ';
formatos += 'application/vnd.openxmlformats-officedocument.wordprocessingml.document, ';
formatos += 'application/vnd.ms-word.template.macroEnabled.12, ';
formatos += 'application/vnd.openxmlformats-officedocument.wordprocessingml.template, ';
formatos += 'application/vnd.oasis.opendocument.text, ';
var condicion = false;
if ( coincidencia( formatos, tipo ) ) {
condicion = true;
}
return condicion;
}
function es_tipo_word (tipo) {
var formatos = 'application/vnd.ms-excel, ';
formatos += 'multipart/related, ';
formatos += 'application/vnd.ms-excel.sheet.binary.macroEnabled.12, ';
formatos += 'application/vnd.ms-excel.sheet.macroEnabled.12, ';
formatos += 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, ';
formatos += 'application/vnd.ms-excel.template.macroEnabled.12, ';
formatos += 'application/vnd.openxmlformats-officedocument.spreadsheetml.template, ';
formatos += 'application/vnd.ms-xpsdocument, ';
formatos += 'application/vnd.oasis.opendocument.spreadsheet, ';
var condicion = false;
if ( coincidencia( formatos, tipo ) ) {
condicion = true;
}
return condicion;
}
function es_tipo_powerpoint (tipo) {
var formatos = 'application/vnd.oasis.opendocument.presentation, ';
formatos += 'application/vnd.ms-powerpoint, ';
formatos += 'application/vnd.ms-powerpoint.template.macroEnabled.12, ';
formatos += 'application/vnd.openxmlformats-officedocument.presentationml.template, ';
formatos += 'application/vnd.ms-powerpoint.slideshow.macroEnabled.12, ';
formatos += 'application/vnd.openxmlformats-officedocument.presentationml.slideshow, ';
formatos += 'application/vnd.ms-powerpoint.presentation.macroEnabled.12, ';
formatos += 'application/vnd.openxmlformats-officedocument.presentationml.presentation, ';
formatos += 'application/vnd.ms-officetheme, ';
var condicion = false;
if ( coincidencia( formatos, tipo ) ) {
condicion = true;
}
return condicion;
}
function es_tipo_array (variable) {
if ( variable.__proto__.constructor.name == "Array" ||
variable.__proto__.constructor.name == "HTMLCollection" ) {
return true;
}
return false;
}
function es_tipo_json (variable) {
if ( variable.__proto__.constructor.name == "Object" ) {
return true;
}
return false;
}
function botonEstadoEspera (boton) {
var hijos = getHijos(boton);
for ( var k in hijos ) {
if ( coincidencia( hijos[k].className, 'fa-' ) ) {
var i = hijos[k];
hijos[k].className = 'fa fa-circle-notch';
}
}
if (i) {
return true;
}
return false;
}
function botonEstadoBien (boton) {
var hijos = getHijos(boton);
for ( var k in hijos ) {
if ( coincidencia( hijos[k].className, 'fa-' ) ) {
var i = hijos[k];
hijos[k].className = 'fa fa-check';
}
}
if (i) {
return true;
}
return false;
}
function botonEstadoMal (boton) {
var hijos = getHijos(boton);
for ( var k in hijos ) {
if ( coincidencia( hijos[k].className, 'fa-' ) ) {
var i = hijos[k];
hijos[k].className = 'fa fa-times';
}
}
if (i) {
return true;
}
return false;
}
var mesesL = {
'00': 'M',
'01': 'Enero',
'02': 'Febrero',
'03': 'Marzo',
'04': 'Abril',
'05': 'Mayo',
'06': 'Junio',
'07': 'Julio',
'08': 'Agosto',
'09': 'Septiembre',
'10': 'Octubre',
'11': 'Noviembre',
'12': 'Diciembre'
};
var mesesC = {
'00': 'M',
'01': 'En',
'02': 'Feb',
'03': 'Mar',
'04': 'Abr',
'05': 'May',
'06': 'Jun',
'07': 'Jul',
'08': 'Ago',
'09': 'Sep',
'10': 'Oct',
'11': 'Nov',
'12': 'Dic'
};
var diasSemanaCorto = {
1: 'Lun',
2: 'Mar',
3: 'Mié',
4: 'Jue',
5: 'Vie',
6: 'Sáb',
7: 'Dom'
}
var diasSemanaLargo = {
1: 'Lunes',
2: 'Martes',
3: 'Miércoles',
4: 'Jueves',
5: 'Viernes',
6: 'Sábado',
7: 'Domingo'
}
function segundostoDuracion (segundos=getTimestamp(), formato="Y-m-d H:i:s") {
var t = new Date(0);
t.setSeconds(segundos);
t.setDate(t.getDate()-31);
t.setMonth(t.getMonth()-11);
let ano = t.getFullYear() - 1970;
if (ano < 0) {
ano = 0;
}
if ( ano < 10 ) {
ano = `000${ano}`;
} else if ( ano < 100 ) {
ano = `00${ano}`;
} else if ( ano < 1000 ) {
ano = `0${ano}`;
}
let mes = (t.getMonth()) < 10 ? `0${(t.getMonth())}` : (t.getMonth());
let dia = t.getDate() < 10 ? `0${t.getDate()}` : t.getDate();
let horas = t.getHours() - 19;
if ( horas < 0 ) {
horas = 24 + horas;
}
horas = horas < 10 ? `0${horas}` : horas;
let minutos = t.getMinutes() < 10 ? `0${t.getMinutes()}` : t.getMinutes();
let seg = t.getSeconds() < 10 ? `0${t.getSeconds()}` : t.getSeconds();
if ( !coincidenciax('00', [horas, minutos, seg]) ) {
dia = dia - 1;
if ( dia < 0) {
dia = 0;
}
dia = dia < 10 ? `0${dia}` : dia;
}
if ( segundos%86400 < 18000 ) {
dia = parseInt(dia) + 1;
if ( dia > 31) {
dia = 0;
}
dia = dia < 10 ? `0${dia}` : dia;
}
if ( segundos < (86400*30) ) {
mes = '00';
}
if ( segundos < 86400 ) {
dia = '00';
}
return reemplazarTexto( formato, [ 'Y', 'm', 'd', 'H', 'i', 's' ], [ ano, mes, dia, horas, minutos, seg ] );
}
function date (formato="Y-m-d H:i:s", fecha=new Date()) {
let ano = fecha.getFullYear();
let mes = (fecha.getMonth()+1) >= 10 ? fecha.getMonth()+1 : '0'+(fecha.getMonth()+1);
let dia = (fecha.getDate()) >= 10 ? fecha.getDate() : '0'+(fecha.getDate());
let hora = (fecha.getHours()) >= 10 ? fecha.getHours() : '0'+(fecha.getHours());
let minutos = (fecha.getMinutes()) >= 10 ? fecha.getMinutes() : '0'+(fecha.getMinutes());
let segundos = (fecha.getSeconds()) >= 10 ? fecha.getSeconds() : '0'+(fecha.getSeconds());
// let ahoraCompleto = `${ano}-${mes}-${dia} ${hora}:${minutos}:${segundos}`;
let ahora = reemplazarTexto( formato, [ 'Y', 'm', 'd', 'H', 'i', 's' ], [ ano, mes, dia, hora, minutos, segundos ] );
return ahora;
}
function DateFormat (date=new Date(), formato="Y-m-d H:i:s", suma='+ 0 d') {
if (date == null) {
date = new Date();
} else if ( typeof date == 'string' ) {
date = new Date(date);
}
if (formato == null) {
formato = "Y-m-d H:i:s";
}
suma = suma.split(' ');
if ( suma[0] == '+' ) {
if ( suma[2] == 'Y' ) {
date.setFullYear(date.getFullYear() + parseInt(suma[1]));
} else if ( suma[2] == 'm' ) {
date.setMonth(date.getMonth() + parseInt(suma[1]));
} else if ( suma[2] == 'd' ) {
date.setDate(date.getDate() + parseInt(suma[1]));
} else if ( suma[2] == 'H' ) {
date.setHours(date.getHours() + parseInt(suma[1]));
} else if ( suma[2] == 'i' ) {
date.setMinutes(date.getMinutes() + parseInt(suma[1]));
} else if ( suma[2] == 's' ) {
date.setSeconds(date.getSeconds() + parseInt(suma[1]));
}
} else {
if ( suma[2] == 'Y' ) {
date.setFullYear(date.getFullYear() - parseInt(suma[1]));
} else if ( suma[2] == 'm' ) {
date.setMonth(date.getMonth() - parseInt(suma[1]));
} else if ( suma[2] == 'd' ) {
date.setDate(date.getDate() - parseInt(suma[1]));
} else if ( suma[2] == 'H' ) {
date.setHours(date.getHours() - parseInt(suma[1]));
} else if ( suma[2] == 'i' ) {
date.setMinutes(date.getMinutes() - parseInt(suma[1]));
} else if ( suma[2] == 's' ) {
date.setSeconds(date.getSeconds() - parseInt(suma[1]));
}
}
let ano = date.getFullYear();
let mes = (date.getMonth()+1) >= 10 ? date.getMonth()+1 : '0'+(date.getMonth()+1);
let mesL = mesesL[mes];
let mesC = mesesC[mes];
let dia = (date.getDate()) >= 10 ? date.getDate() : '0'+(date.getDate());
let diaSL = diasSemanaLargo[date.getDay()];
let diaSC = diasSemanaCorto[date.getDay()];
let hora = (date.getHours()) >= 10 ? date.getHours() : '0'+(date.getHours());
let minutos = (date.getMinutes()) >= 10 ? date.getMinutes() : '0'+(date.getMinutes());
let segundos = (date.getSeconds()) >= 10 ? date.getSeconds() : '0'+(date.getSeconds());
let ahora = reemplazarTexto( formato, [ 'Y', 'm', 'd', 'H', 'i', 's', 'F', 'M', 'l', 'L' ], [ '%Y', '%m', '%d', '%H', '%i', '%s', '%F', '%M', '%l', '%L' ] );
ahora = reemplazarTexto( ahora, [ '%Y', '%m', '%d', '%H', '%i', '%s', '%F', '%M', '%l', '%L' ], [ ano, mes, dia, hora, minutos, segundos, mesL, mesC, diaSC, diaSL ] );
return ahora;
}
function dateFormat (date, formato="Y-m-d H:i:s") {
let sep = "T";
let obDate = new Date(date);
date = reemplazarTexto(date, ['-', ':', ' '], [sep,sep,sep]);
let fecha = date.split(sep);
let ano = fecha[0];
let mes = fecha[1];
let mesL = mesesL[fecha[1]];
let mesC = mesesC[fecha[1]];
let dia = fecha[2];
let diaSL = diasSemanaLargo[obDate.getDay()];
let diaSC = diasSemanaCorto[obDate.getDay()];
let hora = fecha[3];
let minutos = fecha[4];
let segundos = fecha[5];
// let ahoraCompleto = `${ano}-${mes}-${dia} ${hora}:${minutos}:${segundos}`;
let ahora = reemplazarTexto( formato, [ 'Y', 'm', 'd', 'H', 'i', 's', 'F', 'M', 'l', 'L' ], [ ano, mes, dia, hora, minutos, segundos, mesL, mesC, diaSC, diaSL ] );
return ahora;
}
function getTimestamp (date=null) {
var res;
if (date == null) {
res = Date.now();
} else if (typeof date == 'string') {
let dateres = new Date(date);
res = dateres.getTime();
} else if (typeof date == 'object') {
res = date.getTime();
} else {
throw new Error('Tipo erroneo. Sugerencia: getTimestamp("2019-01-01") || getTimestamp(new Date("2019-01-01"))');
}
return parseInt(res/1000);
}
var Correo = {
test: (email) => {
let exp = /^\w+([\.\+\-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/;
return exp.test(email);
}
};
var Base64 = {
'encode': function (str) {
// str = reemplazarTexto( str, '–', '-' );
return btoa(str);
},
'decode': function (base) {
return atob(base);
}
};
function mostrarSesion(variable=null) {
var formPost = new FormData();
var xhr = new XMLHttpRequest();
formPost.append('accion', 'mostrar_sesion');
if ( variable != null ) {
formPost.append('variable', variable);
}
function success () {
var res = this.responseText;
if ( isJsonString(res) ) {
var resJson = JSON.parse(res);
if (resJson.estado) {
console.log(resJson.sesion);
} else {
console.error('Error: '+ resJson.mensaje);
}
} else {
console.log(res);
}
}
xhr.addEventListener('load', success);
// xhr.open('post', 'sources/php/procesos_libreria_hisham.php');
xhr.open('post', '/sys/corredor/sources/php/procesos_libreria_hisham.php');
xhr.send(formPost);
}
function unirArrays (arr1=null, arr2=null) {
var retorno;
if ( es_tipo_array(arr1) && es_tipo_array(arr2) ) {
retorno = [];
for ( let k=0; k<arr1.length; k++ ) {
retorno.push(arr1[k]);
}
for ( let k=0; k<arr2.length; k++ ) {
retorno.push(arr2[k]);
}
return retorno;
} else if ( es_tipo_json(arr1) && es_tipo_json(arr2) ) {
retorno = {};
for ( let k in arr1 ) {
retorno[k] = arr1[k];
}
for ( let k in arr2 ) {
retorno[k] = arr2[k];
}
return retorno;
} else {
throw new Error('Tipos erroneos: sugerencia unirArrays(Array,Array) || unirArrays(Json,Json)');
}
}
function Nodo (ob, svgnamespace='') {
/*
ob : {
tag: localName,
attr: {
value: '',
class: '',
id: ''
},
even: {
load: funcion(),
click: funcion()
}
inner: contenidoHTML
}*/
let nodo = svgnamespace == '' ? document.createElement(ob.tag) : document.createElementNS(svgnamespace, ob.tag);
if ( ob.attr ) {
for ( let a in ob.attr ) {
nodo.setAttribute(a, ob.attr[a]);
}
}
if ( ob.even ) {
for ( let a in ob.even ) {
nodo.addEventListener(a, ob.even[a]);
}
}
if ( ob.inner ) {
nodo.innerHTML = ob.inner;
}
// nodo.remover = ()=> {
// var padre = nodo.parentNode;
// padre.removeChild(nodo);
// }
// nodo.agregar = (hijo)=> {
// nodo.appendChild(hijo);
// }
return nodo;
}
Math.gradostoRadianes = (grados) => {
return grados * Math.PI / 180;
}
var $get;
if ( coincidencia(location.href, '?') ) {
$get = [];
let indice = location.href.indexOf('?');
let stringget = location.href.substring(indice+1);
let arrayget = stringget.split('&');
for ( let k in arrayget ) {
let temp = arrayget[k].split('=');
$get[temp[0]] = temp[1];
}
}
function rgbtoHexa (rgb) {
rgb = reemplazarTexto( rgb, [ ' ', 'rgba', 'rgb', '(', ')' ], '' ).split(',');
for ( let c in rgb ) {
rgb[c] = Number(rgb[c]) < 10 ? `0${Number(rgb[c])}` : Number(rgb[c]);
// consolelog(rgb[c]);
}
// consolelog(rgb);
return `#${rgb[0].toString(16)}${rgb[1].toString(16)}${rgb[2].toString(16)}`;
}
const nodef = undefined;
function parseBoolean (string) {
let cond;
if ( typeof string == 'string' ) {
cond = string == 'true' ? true : cond;
cond = string == 'false' ? false : cond;
if ( cond === true || cond === false ) {
return cond;
} else {
throw "Texto no reconocido";
}
} else if (string==undefined) {
throw "Falta variable de tipo 'string'";
} else {
throw "Tipo de variable no aceptado. Sugerencia 'string'";
}
}
function estadoBoton2 (boton, estado) {
if ( estado == 'espera' ) {
getHijos(boton)[0].className = 'fa fa-circle-notch';
getHijos(boton)[0].innerHTML = '';
} else if ( estado == 'mal' ) {
getHijos(boton)[0].className = 'fa fa-times';
getHijos(boton)[0].innerHTML = '';
} else if ( estado == 'bien' ) {
getHijos(boton)[0].className = 'fa fa-check';
getHijos(boton)[0].innerHTML = '';
} else if ( estado == 'normal' ) {
getHijos(boton)[0].className = '';
getHijos(boton)[0].innerHTML = boton.dataset.texto;
}
}
function estadoIcono2 (boton, estado) {
if ( estado == 'espera' ) {
getHijos(boton)[0].className = 'fa fa-circle-notch';
} else if ( estado == 'mal' ) {
getHijos(boton)[0].className = 'fa fa-times';
} else if ( estado == 'bien' ) {
getHijos(boton)[0].className = 'fa fa-check';
} else if ( estado == 'normal' ) {
getHijos(boton)[0].className = boton.dataset.icono;
}
}
String.prototype.quitarEspaciosLargos = function () {
let nums = {
trece: " ",
diez: " ",
siete: " ",
cinco: " ",
tres: " ",
dos: " "
};
return this.reemplazarTexto( [ nums.trece, nums.diez, nums.siete, nums.cinco, nums.tres, nums.dos, nums.siete, nums.cinco, nums.tres, nums.dos ], ' ' );
}
function getPuntosPath ( path ) {
let dstring = path.getAttribute('d').quitarEspaciosLargos();
for ( let k=0; k<dstring.length; k++ ) {
if ( dstring.charAt(0) == ' ' ) {
dstring = dstring.substring(1);
} else {
break;
}
}
let puntostemp = dstring.split(' L').map( mat => mat.split(' ') );
let puntos = [];
for ( let k in puntostemp ) {
let ar = puntostemp[k];
let ar2 = {};
ar2.x = ar[0].reemplazarTexto( 'M', '' ).int();
ar2.y = ar[1].reemplazarTexto( 'M', '' ).int();
puntos[k] = ar2;
}
return puntos;
}
var puntosdeestafuncion = {};
function animacionPath (path, arraypuntos, key, coor, s=1, div=10, aumento=1) {
let svg = path.parentNode;
let sizesvg = {
x: svg.getAttribute('width').reemplazarTexto( [ ' ', 'px' ], '' ).int(),
y: svg.getAttribute('height').reemplazarTexto( [ ' ', 'px' ], '' ).int(),
};
let segundos = (s * 1000) / arraypuntos.length / div;
let d = "";
// path.setAttribute('d', '');
for ( let k=0; k<key; k++ ) {
d += k == 0 ? `M${arraypuntos[k].x} ${arraypuntos[k].y}` : ` L${arraypuntos[k].x} ${arraypuntos[k].y}`;
}
let xant = arraypuntos[key-1] != undefined ? arraypuntos[key-1].x : 0;
let yant = arraypuntos[key-1] != undefined ? arraypuntos[key-1].y : 0;
let dx = arraypuntos[key].x - xant;
let dy = arraypuntos[key].y - yant;
let xporc = dx / div * coor;
let yporc = dy / div * coor;
let x = xant + xporc;
let y = yant + yporc;
d += key == 0 ? `M${x} ${y}` : ` L${x} ${y}`;
path.setAttribute('d', d);
coor += aumento;
if ( coor > div ) {
coor = aumento;
key += 1;
}
if ( key != arraypuntos.length ) {
setTimeout(function () {
animacionPath(path, arraypuntos, key, coor, s);
}, segundos);
}
}
function joinmatriz (matriz, sep1, sep2) {
return matriz.map( e => e.join(sep2) ).join(sep1);
}
Object.defineProperty(Array.prototype, 'joinmatriz', {
enumerable: false,
value: function (sep1, sep2) {
let matriz = this;
return matriz.map( e => e.join(sep2) ).join(sep1);
}
});
Object.defineProperty(Element.prototype, 'remover', {
enumerable: false,
value: function () {
let nodo = this;
let padre = nodo.parentNode;
padre.removeChild(nodo);
}
});
Object.defineProperty(Element.prototype, 'agregar', {
enumerable: false,
value: function (hijo) {
let nodo = this;
nodo.appendChild(hijo);
}
});
Object.defineProperty(String.prototype, 'upperLow', {
enumerable: false,
value: function () {
let uno = this.charAt(0).toUpperCase();
let resto = this.substring(1).toLowerCase();
return `${uno}${resto}`;
}
});
Object.defineProperty(String.prototype, 'firstUpper', {
enumerable: false,
value: function () {
let uno = this.charAt(0).toUpperCase();
let resto = this.substring(1);
return `${uno}${resto}`;
}
});
Object.defineProperty(String.prototype, 'allFirstUpper', {
enumerable: false,
value: function () {
let str = this;
let res = "";
let pals = [];
let palabras = str.split(' ');
for ( let k in palabras ) {
let p = palabras[k];
let uno = p.charAt(0).toUpperCase();
let resto = p.substring(1).toLowerCase();
p = `${uno}${resto}`;
if ( p != '' ) pals.push(p);
}
return pals.join(' ');
}
});
Object.defineProperty(String.prototype, 'int', {
enumerable: false,
value: function () {
return parseInt(this);
}
});
Object.defineProperty(Array.prototype, 'enArray', {
enumerable: false,
value: function (el) {
if ( typeof el === 'object' ) {
throw new Error("Tipo no comparable");
} else {
let ar = this;
for ( let k=0; k<ar.length; k++ ) {
if ( ar[k] === el ) {
return true;
}
}
return false;
}
}
});
Object.defineProperty(Array.prototype, 'iguales', {
enumerable: false,
value: function (arraydos) {
if ( !Array.isArray(arraydos) ) {
return false;
}
let arrayuno = this;
condicion = true;
if ( arrayuno.length === arraydos.length ) {
for ( let asdasdasd in arrayuno ) {
if ( arrayuno[asdasdasd] != arraydos[asdasdasd] ) {
condicion = false;
}
}
} else {
condicion = false;
}
return condicion;
}
});
Object.defineProperty(Object.prototype, 'iguales', {
enumerable: false,
value: function (arraydos) {
if ( typeof arraydos != 'object' ) {
return false;
}
let arrayuno = this, longitud1 = 0, longitud2 = 0;
condicion = true;
for ( let k in arrayuno ) {
longitud1++;
}
for ( let k in arraydos ) {
longitud2++;
}
if ( longitud1 === longitud2 ) {
for ( let asdasdasd in arrayuno ) {
if ( arrayuno[asdasdasd] != arraydos[asdasdasd] ) {
condicion = false;
}
}
} else {
condicion = false;
}
return condicion;
}
});
Object.defineProperty(Element.prototype, 'nodoidclass', {
enemerable: false,
value: function () {
let localName = this.localName;
let idp = this.id == '' ? '' : '#'+ this.id;
let clasep = this.className == '' ? '' : '.'+ this.className.split(' ').join('.');
return `${localName}${idp}${clasep}`;
}
});
Object.defineProperty(Element.prototype, 'asignarValor', {
enumerable: false,
value: function (texto) {
let nodo = this;
if ( nodo.localName == 'input' || nodo.localName == 'select' || nodo.localName == 'textarea' ) {
nodo.value = nodo.type == 'datetime-local' ? texto.reemplazarTexto( ' ', 'T' ) : nodo.type == 'date' ? texto.split(' ')[0] : texto;
} else {
throw new Error("Este elemento no es una entrada de texto.");
}
}
});
Object.defineProperty(Element.prototype, 'change', {
enumerable: false,
value: function () {
let node = this;
let eventName = 'change';
// Make sure we use the ownerDocument from the provided node to avoid cross-window problems
var doc;
if (node.ownerDocument) {
doc = node.ownerDocument;
} else if (node.nodeType == 9){
// the node may be the document itself, nodeType 9 = DOCUMENT_NODE
doc = node;
} else {
throw new Error("Invalid node passed to fireEvent: " + node.id);
}
if (node.dispatchEvent) {
// Gecko-style approach (now the standard) takes more work
var eventClass = "";
// Different events have different event classes.
// If this switch statement can't map an eventName to an eventClass,
// the event firing is going to fail.
switch (eventName) {
case "click": // Dispatching of 'click' appears to not work correctly in Safari. Use 'mousedown' or 'mouseup' instead.
case "mousedown":
case "mouseup":
eventClass = "MouseEvents";
break;
case "focus":
case "change":
case "blur":
case "select":
eventClass = "HTMLEvents";
break;
default:
throw "fireEvent: Couldn't find an event class for event '" + eventName + "'.";
break;
}
var event = doc.createEvent(eventClass);
event.initEvent(eventName, true, true); // All events created as bubbling and cancelable.
event.synthetic = true; // allow detection of synthetic events
// The second parameter says go ahead with the default action
node.dispatchEvent(event, true);
} else if (node.fireEvent) {
// IE-old school style, you can drop this if you don't need to support IE8 and lower
var event = doc.createEventObject();
event.synthetic = true; // allow detection of synthetic events
node.fireEvent("on" + eventName, event);
}
}
});
Object.defineProperty(Array.prototype, 'inArray', {
enumerable: false,
value: function (string) {
if ( typeof string == 'string' ) {
let arr = this;
for ( let i in arr ) {
if ( arr[i] == string ) {
return true;
}
}
return false;
} else {
throw new Error('El argumento debe ser una cadena de texto');
}
}
});