Files
Plataforma-de-desarrolladores/SIG.Web/Scripts/custom.js
Jorge Luis caudillo esparza 58af3ffece tramites
2026-08-19 03:23:04 -07:00

3262 lines
131 KiB
JavaScript

/*
* custom.js
* Cleaned for the new C# WebForms project.
* Notes:
* - The main Metronic initialization lives in this file, not in Site.master.
* - Do not render this file twice in bundles.
* - Removed legacy AddFunctionPS because it depends on old Productos/Almacenes AJAX behavior.
*/
var IHAVEALLTHEPOWER = false;
var objscollapse = null;
var objsexpand = null;
var adscrollerposition = [];
var error = false;
conf = {
error: console.error,
info: console.info,
log: console.log,
warn: console.warn,
debug: console.debug
};
console.error = function () {
setTimeout(function () {
if (
typeof Metronic !== 'undefined' &&
Metronic &&
typeof Metronic.unblockUI === 'function'
) {
Metronic.unblockUI();
}
}, 10);
conf.error.apply(console, arguments);
};
function SaveCsv(filename, data) {
var blob = new Blob([data], { type: 'text/csv' });
if (window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveBlob(blob, filename);
}
else {
var elem = window.document.createElement('a');
elem.href = window.URL.createObjectURL(blob);
elem.download = filename;
document.body.appendChild(elem);
elem.click();
document.body.removeChild(elem);
}
}
function alertatoast(tipo, Mensaje, Funcion, timeout) {
if (timeout) {
timeout = timeout * 1000;//convierto a milisegundos
} else { timeout = 0; }
let opciones = {
"closeButton": true,
"debug": false,
"positionClass": "toast-top-right",
"onclick": Funcion,
"showDuration": 0,
"hideDuration": 0,
"timeOut": timeout,
"extendedTimeOut": 0,
"showEasing": "swing",
"hideEasing": "linear",
"showMethod": "fadeIn",
"hideMethod": "fadeOut"
}
switch (tipo) {
case 5:
toastr.success(Mensaje, "", opciones);
break;
case 6:
toastr.info(Mensaje, "", opciones);
break;
case 7:
toastr.error(Mensaje, "", opciones);
break;
case 8:
toastr.warning(Mensaje, "", opciones);
break;
default:
toastr.info(Mensaje, "", opciones);
}
}
function log(mensaje) {
console.log(mensaje);
}
function soval(dropdown) {
return $('option:selected', '#' + dropdown).val();
}
function sotext(dropdown) {
return $('option:selected', '#' + dropdown).text();
}
function FiltrarTabla(idtxt, idtable, idcontador) {
if ($('#' + idtxt).val() == '') { $('table#' + idtable + ' tr').css('display', ''); }
else {
$('table#' + idtable + ' tr:not(.ADtr)').css('display', 'none'); $('table#' + idtable + ' tr:contains("' + $('#' + idtxt).val() + '")').css('display', '');
$('div.ADScroller .ADScroller-header table#' + idtable + ' tr:not(.ADtr)').css('display', '');
}
if ($('#' + idcontador).length > 0) {
$('#' + idcontador).html($('#' + idtable + ' tr:visible:not(.ADtr)').length);
}
}
function FiltrarTablaStr(str, idtable, idcontador) {
if (str == '' || str == "-1" || str == 'Todos') { $('table#' + idtable + ' tr').css('display', ''); }
else {
$('table#' + idtable + ' tr:not(.ADtr)').css('display', 'none');
$('table#' + idtable + ' tr:contains("' + str + '")').css('display', '');
$('div.ADScroller .ADScroller-header table#' + idtable + ' tr:not(.ADtr)').css('display', '');
}
if ($('#' + idcontador).length > 0) {
$('#' + idcontador).html($('#' + idtable + ' tr:visible:not(.hidetrad):not(.ADtr)').length);
}
}
function FiltrarTablaStrMulti(idtable, idcontador /*, str1, str2, str3...*/) {
if (arguments.length <= 2) { return; }
let strc = '';
for (let i = 2 /*a partir del 3er argumento obtiene los str*/; i < arguments.length; i++) {
let str = arguments[i];
if (str != '' && str != "-1" && str != 'Todos') {
strc += ':contains("' + str + '")';
}
}
$('table#' + idtable + ' tr:not(.ADtr)').css('display', 'none');
$('table#' + idtable + ' tr' + strc).css('display', '');
$('div.ADScroller .ADScroller-header table#' + idtable + ' tr:not(.ADtr)').css('display', '');
if (idcontador) {
if ($('#' + idcontador).length > 0) {
$('#' + idcontador).html($('#' + idtable + ' tr:visible:not(.hidetrad):not(.ADtr)').length);
}
}
}
function FiltrarTablaClass(idtxt, idtable, idcontador, resta) {
if (resta == null) {
resta = 1
}
if ($('#' + idtxt).val() == '') { $('table#' + idtable + ' tr').removeClass('hidetrad') }
else {
$('table#' + idtable + ' tr:not(.ADtr)').addClass('hidetrad'); $('table#' + idtable + ' tr:contains("' + $('#' + idtxt).val() + '")').removeClass('hidetrad');
$('div.ADScroller .ADScroller-header table#' + idtable + ' tr:not(.ADtr)').removeClass('hidetrad');
}
if ($('#' + idcontador).length > 0) {
let numconta = $('#' + idtable + ' tr:visible:not(.hidetrad):not(.ADtr)').length;
if (numconta > 0) { numconta - resta }
$('#' + idcontador).html(numconta);
}
}
function FiltrarTablaV2(idtxt, idtable, idcontador) {
if ($(idtxt).val() == '') { $(idtable + ' tr').css('display', ''); }
else {
$(idtable + ' tr:not(.ADtr)').css('display', 'none'); $(idtable + ' tr:contains("' + $(idtxt).val() + '")').css('display', '');
$('div.ADScroller .ADScroller-header ' + idtable + ' tr:not(.ADtr)').css('display', '');
}
if ($('#' + idcontador).length > 0) {
$('#' + idcontador).html($(idtable + ' tr:visible:not(.hidetrad):not(.ADtr)').length);
}
}
function FiltrarTablaFreezcol(idtxt, idtable, idcontador) {
if ($('' + idtxt).val() == '') { $('div.ADSCroll:not(.RHeader) table' + idtable + ' tr').css('display', ''); }
else {
let idxlist = [];
$('div.ADSCroll:not(.RHeader) table' + idtable + ' tr:contains("' + $('' + idtxt).val() + '")').each(function () { let idx = $(this).index(); idxlist.push(idx) });
idxlist = idxlist.filter((x, i, a) => a.indexOf(x) == i)
$('div.ADSCroll:not(.RHeader) table' + idtable + ' tr:not(.ADtr):not(.SearchADHeader):not(.ADSRow):not(.Titulos)').each(function () {
let _tthis = $(this);
let idx = _tthis.index();
if (idxlist.includes(idx)) {
_tthis.css('display', '');
} else {
_tthis.css('display', 'none');
}
});
}
if ($('' + idcontador).length > 0) {
$('' + idcontador).html('(' + $('div.ADSCroll:not(.RHeader) ' + idtable + ' tr:not(.ADtr):not(.ADSRow):not(.SearchADHeader):visible').length + '/' + $('div.ADSCroll:not(.RHeader) ' + idtable + ' tr:not(.ADtr):not(.ADSRow):not(.SearchADHeader)').length + ')');
}
}
function clonsbuttons() {
var copiasdelete = $('.clonehbutton_copy');
if (copiasdelete) {
copiasdelete.remove();
}
var clonehbuttonarray = $('.clonehbutton');
if (clonehbuttonarray) {
for (var i = 0; i < clonehbuttonarray.length; i++) {
var clonebutton = $(clonehbuttonarray[i]);
clonebutton.attr('data-clonebutton', i)
var clonebutton_copy = clonebutton.clone()
clonebutton_copy.addClass('clonehbutton_copy');
clonebutton_copy.addClass('btn-fit-height');
clonebutton_copy.removeClass('clonehbutton');
clonebutton_copy.click(function () {
clonebutton.click();
});
clonebutton_copy.insertBefore("#btnmaster_actionssidebar")
}
}
}
var hiddenshow = $(".collapseclick , .expandclick");
if (hiddenshow) {
hiddenshow.click(function () {
var ocultarmostrar = $('#' + $(this).attr('data-hiddenitem'));
if (ocultarmostrar) {
if ($(this).hasClass('collapseclick')) {
$(this).removeClass('collapseclick');
$(this).addClass('expandclick');
ocultarmostrar.slideUp(200);
} else {
$(this).removeClass('expandclick');
$(this).addClass('collapseclick');
ocultarmostrar.slideDown(200);
}
}
});
}
function buscadorMenuCaudi() {
let hasmenusearch = true;/*
try {
hasmenusearch = (localStorage.getItem("HasMenu").toString() == "1")
} catch (error) { }*/
let idTxtMaster = "txtMasterMenu";
if (!($('#' + idTxtMaster).hasClass("txtMasterMenukeychange")) && hasmenusearch) {
/*let buscador = $('' +
'<div class="sidebar-search " style="margin-top: 12px;">' +
' <div class="input-group">' +
' <input type="text" id="' + idTxtMaster + '" class="form-control" placeholder="Buscar...">' +
' <span class="input-group-btn">' +
' <a href="javascript:;" class="btn BuscarMenu">' +
' <i class="icon-magnifier"></i>' +
' </a>' +
' </span>' +
' </div>' +
'</div>')
$('ul#ulmenulateralmaster li.sidebar-toggler-wrapper').append(buscador);*/
let tickBar = 0;
let input = $('#' + idTxtMaster);
input.addClass("txtMasterMenukeychange");
let BuscarMenu = function () {
tickBar = tickBar + 1;
tickBarnew = tickBar;
setTimeout(function () {
if (tickBarnew == tickBar) {
if (input.val() == '') { $('ul#ulmenulateralmasterB li').css('display', ''); }
else {
$('ul#ulmenulateralmasterB li:not(.sidebar-toggler-wrapper)').css('display', 'none');
$('ul#ulmenulateralmasterB li:contains("' + input.val() + '")').css('display', '');
$('ul#ulmenulateralmasterB li > a[href="javascript:;"]:contains("' + input.val() + '")').parent().find('>ul>li').css('display', '');
}
}
}, 500);
}
input.unbind();
input.bind({
copy: function () { BuscarMenu(); }
, paste: function () { var tthis = $(this); BuscarMenu(); }
, cut: function () { var tthis = $(this); BuscarMenu(); }
, keydown: function (event) { if (event.which == 13) { event.preventDefault(); } }
, keyup: function () { BuscarMenu(); }
});
}
}
/*
var Buscadormenu = $('#BuscarMenu');
if (Buscadormenu) {
Buscadormenu.keyup(function (e) {
var ulid = 'ulmenulateralmaster';
var texto = $(this).val();
if (texto == '') {
if ($('ul#' + ulid + '')) { $('ul#' + ulid + '').removeClass("listainvicible"); }
} else {
if ($('ul#' + ulid).hasClass('listainvicible') == false) { $('ul#' + ulid).addClass("listainvicible"); }
if ($('ul#' + ulid + ' li.livisible')) { $('ul#' + ulid + ' li.livisible').removeClass("livisible"); }
var li
if ($('ul#' + ulid + ' li:contains("' + texto + '")')) {
$('ul#' + ulid + ' li:contains("' + texto + '")').addClass("livisible");
$('ul#' + ulid + ' li:contains("' + texto + '") li').addClass("livisible");
}
}
if (e.which == 13) {
return false;
}
});
}*/
function notifyMe(mensaje) {
// Let's check if the browser supports notifications
if (!("Notification" in window)) {
alert("This browser does not support desktop notification");
}
// Let's check whether notification permissions have already been granted
else if (Notification.permission === "granted") {
// If it's okay let's create a notification
var notification = new Notification(mensaje);
}
// Otherwise, we need to ask the user for permission
else {
alert("This browser does not support desktop notification");
}
}
setchecktotag = function () {
var mychecktotag = $(".make-checktotag");
if (mychecktotag) {
for (var i = 0; i < mychecktotag.length; i++) {
var id = $(mychecktotag.get(i)).attr("id");
var lista = $("#" + id + " :checkbox");
var dropdown = "<select multiple class='form-control input-sm input-medium' id='dropdown" + id + "' >";
$.each(lista, function (index, value) {
value = $(value);
label = $("#" + id + " label[for='" + value.attr("id") + "']");
dropdown += "<option value='" + value.val() + "'>" + label.text() + "</option>";
});
dropdown += "</select>";
dropdown = $(dropdown);
$("#" + id).before(dropdown);
//dropdown.on("change", function(e) { console.log("change "+JSON.stringify({val:e.val, added:e.added, removed:e.removed})); })
dropdown.on("change", function (e) {
if (e.added) {
$("input[value='" + e.added.id + "']").prop("checked", true)
} else {
$("input[value='" + e.removed.id + "']").prop("checked", false)
}
});
dropdown.select2();
$(mychecktotag.get(i)).css({ "display": "none" });
}
}
};
setswitch = function () {
if ($("span.make-switchsd input")) {
var mycheckswitch = $("span.make-switchsd input");
var mycheckswitchcontainer = $("span.make-switchsd ");
for (var i = 0; i < mycheckswitch.length; i++) {
var containermycheckswitch = $(mycheckswitchcontainer.get(i));
var mycheckswitchi = $(containermycheckswitch.find('input'));
var dataontext = 'Si';
var datanotext = 'No';
if (containermycheckswitch.attr('data-on-text')) {
dataontext = containermycheckswitch.attr('data-on-text');
}
if (containermycheckswitch.attr('data-off-text')) {
datanotext = containermycheckswitch.attr('data-off-text');
}
if (containermycheckswitch.attr('data-size')) {
mycheckswitchi.attr('data-size', containermycheckswitch.attr('data-size'));
}
mycheckswitchi.addClass("make-switch");
mycheckswitchi.attr('data-on-text', dataontext);
mycheckswitchi.attr('data-off-text', datanotext);
}
}
if ($("span.md-checksd input")) {
$('span.md-checksd').each(function (index) {
var mdcheckbox = $($(this).find('input'));
var mdcheckboxcontainer = $('<div class="md-checkbox"> </div>');
var label;
var labeltext = ' ';
if ($($(this).find('label')).html()) {
labeltext = $($(this).find('label')).html();
}
label = '<label for="' + mdcheckbox.attr("id") + '" > <span></span><span class="check"></span><span class="box"></span>' + labeltext + '</label>';
label = $(label);
mdcheckbox.addClass('md-check');
mdcheckboxcontainer.append(mdcheckbox);
mdcheckboxcontainer.append(label);
$(this).html(mdcheckboxcontainer);
});
}
if ($("span.md-checksd2 input")) {
$('span.md-checksd2').each(function (index) {
var mdcheckbox = $($(this).find('input'));
var mdcheckboxcontainer = $('<div class="md-checkbox"> </div>');
var label;
var labeltext = ' ';
if ($($(this).find('label')).html()) {
labeltext = $($(this).find('label')).html();
}
label = '<label for="' + mdcheckbox.attr("id") + '" > <span></span><span class="check"></span><span class="box"></span>' + labeltext + '</label>';
label = $(label);
mdcheckbox.addClass('md-check');
mdcheckboxcontainer.append(mdcheckbox);
mdcheckboxcontainer.append(label);
$(this).html(mdcheckboxcontainer);
});
}
if ($("span.yt-uix-checkbox-on-off input")) {
var mdspans = $('span.yt-uix-checkbox-on-off');
for (var i = 0; i < mdspans.length; i++) {
var mdspan = $(mdspans.get(i));
var mdcheckboxe = $(mdspan.find('input'));
var mdlbel = '<label for="' + mdcheckboxe.attr("id") + '" > <span class="checked">&nbsp;</span> <span class="unchecked"></span> <span class="toggle">&nbsp;</span></label>';
mdlbel = $(mdlbel);
mdcheckboxe.addClass('switchmincheck');
mdspan.html('');
mdspan.append(mdcheckboxe);
mdspan.append(mdlbel);
}
}
};
function adssigscrollJSLoad() {
$('table.adssigrid-scroll:not(.adssigscroll)').each(function () {
try {
let Tthis = $(this);
let Tid = Tthis.attr('id');
let rowVisibles = isNaN(Number(Tthis.data('rows'))) ? 1 : Number(Tthis.data('rows'));
let colVisibles = isNaN(Number(Tthis.data('cols'))) ? 0 : Number(Tthis.data('cols'));
let divcontainer = $(`<div id="container${Tid}" class="divContainerads"></div>`);
let jsrows;
let jscols;
let stylosrow = '';
Tthis.addClass('adssigscroll');
if (rowVisibles > 0) {
jsrows = $(`table#${Tid}.adssigscroll tr:nth-child(-n+${rowVisibles})`);
if (jsrows) {
jsrows.addClass('stickyRow');
}
if (rowVisibles > 1) {
let numberitem = 1;
let top = -1;
jsrows.each(function () {
let Trowthis = $(this);
stylosrow = `${stylosrow}
table#${Tid}.adssigscroll tr:nth-child(${numberitem}) { top: ${top}px; }`;
top = top + (Trowthis.outerHeight(true) - 1);
numberitem = numberitem + 1;
});
}
}
if (colVisibles > 0) {
stylosrow = `${stylosrow}
table#${Tid}.adssigscroll tr td:nth-child(-n+${colVisibles}),table#${Tid}.adssigscroll tr th:nth-child(-n+${colVisibles}) {
position: sticky;
left: 0;
z-index: 3;
}
table#${Tid}.adssigscroll tr td:nth-child(-n+${colVisibles}) {
background-color: inherit;
}`;
if (colVisibles > 1 && $(`table#${Tid}.adssigscroll tr:nth-last-child(1)`)) {
let left = 0;
for (let i = 1; i <= colVisibles; i++) {
stylosrow = `${stylosrow}
table#${Tid}.adssigscroll tr td:nth-child(${i}),table#${Tid}.adssigscroll tr th:nth-child(${i}) {
left: ${left}px;
}`;
let item = $(`table#${Tid}.adssigscroll tr:nth-last-child(1) > *:nth-child(${i})`);
if (item) {
left = left + item.outerWidth(true);
}
}
}
}
if (rowVisibles > 0 && colVisibles > 0) {
stylosrow = `${stylosrow}
table#${Tid}.adssigscroll tr.stickyRow th:nth-child(-n+${colVisibles}),table#${Tid}.adssigscroll tr.stickyRow td:nth-child(-n+${colVisibles}) { z-index: 5; }`;
}
Tthis.before($(stylosrow = `<style>${stylosrow}</style>`));
Tthis.before(divcontainer);
divcontainer.append(Tthis);
}
catch (err) {
console.log("adssigrid-scroll Error:" + err.message);
}
});
}
function LoadSortSticky() {
$('body').on('click', 'table.adssigscroll.adssigrid-order tr:not(.tsorterblock) > th ', function (e) {
var tthis = $(this);
if (tthis.closest('.NoClick').length == 0 && !($(e.target).is('a,input'))) {
Metronic.blockUI({ animate: true });
var index = tthis.index();
var multiplicador = -1;
var tipodato = tthis.data('tipodato');
var table = $(tthis.closest('.table')[0]);
var tabletr = table.find('> tr:not(.stickyRow),> tbody > tr:not(.stickyRow),> thead > tr:not(.stickyRow)');
if (1 == 1) {
if (tabletr.length > 0) {
el = $(tabletr[0]);
var tdtexto = el.find("> td");
texto = $(tdtexto[index]).data('order');
if (texto) {
tipodato = 'dataorder';
}
}
}
//console.log({ tipodato })
tthis.closest('tr').addClass('tsorterblock');
setTimeout(
function () {
if (tthis.hasClass('desc')) {
tthis.closest('tr').find('th').removeClass('asce');
tthis.closest('tr').find('th').removeClass('desc');
tthis.addClass('asce');
}
else {
tthis.closest('tr').find('th').removeClass('asce');
tthis.closest('tr').find('th').removeClass('desc');
tthis.addClass('desc');
multiplicador = 1;
}
function reordenaruno() {
var re = new RegExp(",", 'g');
tipostring = 0;
tiponumeric = 0;
tipodate = 0;
var mapped = tabletr.map(function (i, el) {
el = $(el);
var texto = el.find("> td");
var textod = null;
var texton = 0;
if (texto && texto.length > index) {
texto = $(texto[index]).text();
texto = texto.toLowerCase().trim();
if (texto.length > 0) {
var vnum = texto.replace("$", "").replace("%", "").replace("-", "").replace("(", "").replace(")", "").replace(re, "").trim();
if (vnum.length > 0) {
if ($.isNumeric(vnum)) {
texton = Number(vnum);
tiponumeric = 1;
} else {
var splited = texto.split("-")
if (splited.length == 3) {
var d = new Date(splited[2] + "-" + splited[1] + "-" + splited[0])
if (!(d.toString == "Invalid Date")) {
textod = d;
tipodate = 1;
}
} else {
var splited = texto.split("/")
if (splited.length == 3) {
var d = new Date(splited[2] + "/" + splited[1] + "/" + splited[0])
if (!(d.toString == "Invalid Date")) {
textod = d;
tipodate = 1;
}
} else {
tipostring = 1
}
}
}
} else {
texto = null;
}
} else {
texto = null;
}
} else {
texto = null;
}
return { index: i, value: texto, valued: textod, valuen: texton, obj: el };
});
if (tipostring == 1) {
mapped.sort(function (a, b) {
return (+(a.value > b.value) || +(a.value === b.value) - 1) * multiplicador;
});
//tthis.closest('tr').find('th').data('tipodato', 'string')
} else {
if (tipodate == 1) {
mapped.sort(function (a, b) {
return (+(a.valued > b.valued) || +(a.valued === b.valued) - 1) * multiplicador;
});
//tthis.closest('tr').find('th').data('tipodato', 'date')
} else {
mapped.sort(function (a, b) {
return (+(a.valuen > b.valuen) || +(a.valuen === b.valuen) - 1) * multiplicador;
});
//tthis.closest('tr').find('th').data('tipodato', 'numeric')
}
}
mapped.each(function (i, el) {
table.append(this.obj);
});
}
function reordenardos() {
var re = new RegExp(",", 'g');
tipostring = 0;
tiponumeric = 0;
tipodate = 0;
var mapped = tabletr.map(function (i, el) {
el = $(el);
var tdtexto = el.find("> td");
var texto = null;
if (tdtexto && tdtexto.length > index) {
texto = $(tdtexto[index]).text();
texto = texto.toLowerCase().trim();
} else {
texto = null;
}
return { index: i, value: texto, obj: el };
});
mapped.sort(function (a, b) {
return (+(a.value > b.value) || +(a.value === b.value) - 1) * multiplicador;
});
mapped.each(function (i, el) {
table.append(this.obj);
});
}
function reordenartres() {
var re = new RegExp(",", 'g');
tipostring = 0;
tiponumeric = 0;
tipodate = 0;
var mapped = tabletr.map(function (i, el) {
el = $(el);
var tdtexto = el.find("> td");
var texto = null;
var textod = null;
if (tdtexto && tdtexto.length > index) {
texto = $(tdtexto[index]).text();
texto = texto.toLowerCase().trim();
var splited = texto.split("-")
if (splited.length == 3) {
var d = new Date(splited[2] + "-" + splited[1] + "-" + splited[0])
if (!(d.toString == "Invalid Date")) {
textod = d;
}
} else {
var splited = texto.split("/")
if (splited.length == 3) {
var d = new Date(splited[2] + "/" + splited[1] + "/" + splited[0])
if (!(d.toString == "Invalid Date")) {
textod = d;
}
}
}
} else {
texto = null;
}
return { index: i, value: textod, obj: el };
});
mapped.sort(function (a, b) {
return (+(a.value > b.value) || +(a.value === b.value) - 1) * multiplicador;
});
mapped.each(function (i, el) {
table.append(this.obj);
});
}
function reordenarcuatro() {
var re = new RegExp(",", 'g');
tipostring = 0;
tiponumeric = 0;
tipodate = 0;
var mapped = tabletr.map(function (i, el) {
el = $(el);
var tdtexto = el.find("> td");
var texto = null;
var texton = 0;
if (tdtexto && tdtexto.length > index) {
texto = $(tdtexto[index]).text();
texto = texto.toLowerCase().trim();
if (texto.length > 0) {
var vnum = texto.replace("$", "").replace("%", "").replace("-", "").replace("(", "").replace(")", "").replace(re, "").trim();
if (vnum.length > 0) {
if ($.isNumeric(vnum)) {
texton = Number(vnum);
}
}
}
} else {
texto = null;
}
return { index: i, value: texton, obj: el };
});
mapped.sort(function (a, b) {
return (+(a.value > b.value) || +(a.value === b.value) - 1) * multiplicador;
});
mapped.each(function (i, el) {
table.append(this.obj);
});
}
function reordenarcinco() {
var re = new RegExp(",", 'g');
tipostring = 0;
tiponumeric = 0;
tipodate = 0;
var mapped = tabletr.map(function (i, el) {
el = $(el);
var tdtexto = el.find("> td");
var texto = null;
var texton = 0;
if (tdtexto && tdtexto.length > index) {
texton = Number($(tdtexto[index]).data('order'));
} else {
texto = null;
}
return { index: i, value: texton, obj: el };
});
//console.log(mapped)
mapped.sort(function (a, b) {
return (+(a.value > b.value) || +(a.value === b.value) - 1) * multiplicador;
});
mapped.each(function (i, el) {
table.append(this.obj);
});
}
switch (tipodato) {
case 'string':
reordenardos();
break;
case 'date':
reordenartres();
break;
case 'numeric':
reordenarcuatro();
break;
case 'dataorder':
reordenarcinco();
break;
default:
reordenaruno();
}
tthis.closest('tr').removeClass('tsorterblock');
Metronic.unblockUI();
}, 100);
}
});
}
function ADScroller2() {
adssigscrollJSLoad();
$('table.ADSCROLLER2').each(function () {
try {
var Tthis = $(this);
var TWidth = Tthis.width() + 15;
var Tid = Tthis.attr('id');
var rowVisibles = isNaN(Number(Tthis.data('rows'))) ? 1 : Number(Tthis.data('rows'));
var colVisibles = isNaN(Number(Tthis.data('cols'))) ? 1 : Number(Tthis.data('cols'));
var WidthMenos = isNaN(Number(Tthis.data('widthmenos'))) ? 280 : Number(Tthis.data('widthmenos'));
var HeightMenos = isNaN(Number(Tthis.data('heightmenos'))) ? 290 : Number(Tthis.data('heightmenos'));
var Heightfijo = isNaN(Number(Tthis.data('heightfijo'))) ? 0 : Number(Tthis.data('heightfijo'));
var widthGral = $(document).width() - WidthMenos;
var heightGral = $(window).height() - HeightMenos;
if (Heightfijo > 0) { heightGral = Heightfijo; }
if (widthGral < 300) { widthGral = 300; }
if (heightGral < 300) { heightGral = 300; }
widthGral = Tthis.parent().parent().width();
Tthis.removeClass('ADSCROLLER2');
var trrowh = $('<tr class="ADSRow"></tr>');
var numColumnas = 3;
var ancho1 = 0;
$('table#' + Tid + ' > tbody > tr:nth-child(1) > th').each(function () {
var width = $(this).outerWidth();
var tdrow = $('<td></td>');
tdrow.append($('<div style="width:' + width + 'px;height:1px;"></div>'));
trrowh.append(tdrow);
if (numColumnas - 3 < colVisibles) {
ancho1 += width;
}
numColumnas++;
});
trrowh.prependTo($('table#' + Tid + ' > tbody'));
var columnstoinsert = [];
$('table#' + Tid + ' > tbody > tr > td:nth-child(1),table#' + Tid + ' > tbody > tr > th:nth-child(1)').each(function () {
var Height = $(this).outerHeight();
var tdrow = $('<td class="adsCol"> </td>');
var padre = $(this).parent();
tdrow.append($('<div style="width:1px;height:' + Height + 'px;"></div>'));
columnstoinsert.push([tdrow, padre]);
});
for (var i = columnstoinsert.length - 1; i >= 0; i--) {
columnstoinsert[i][0].prependTo(columnstoinsert[i][1]);
}
TVisibleCols = Tthis.clone();
TVisibleCols.attr('id', ('ADCol' + Tid));
Tthis.before(TVisibleCols);
Tthis.css("width", (TWidth - ancho1 - 15));
for (var i = numColumnas; i > colVisibles + 1; i--) {
$('table#ADCol' + Tid + ' > tbody > tr > td:nth-child(' + i + '),table#ADCol' + Tid + ' > tbody > tr > th:nth-child(' + i + ')').each(function () {
$(this).remove();
});
}
for (var i = colVisibles + 1; i > 1; i--) {
$('table#' + Tid + ' > tbody > tr > td:nth-child(' + i + '),table#' + Tid + ' > tbody > tr > th:nth-child(' + i + ')').each(function () {
$(this).remove();
});
}
var txx1 = $('table#ADCol' + Tid + ' > tbody > tr > td:nth-child(1) > div');
var txx2 = $('table#' + Tid + ' > tbody > tr > td:nth-child(1) > div');
if (txx1 && txx2 && txx1.length > 0 && txx1.length == txx1.length) {
for (var i = 0; i < txx1.length; i++) {
tr1 = $(txx1[i]).closest('tr');
td1 = $(txx1[i]).closest('td');
tr1.append(td1);
var hr1 = tr1.outerHeight();
var hr2 = $(txx2[i]).closest('tr').outerHeight();
if (hr1 > hr2) {
$(txx1[i]).css('height', hr1);
$(txx2[i]).css('height', hr1);
}
if (hr2 > hr1) {
$(txx1[i]).css('height', hr2);
$(txx2[i]).css('height', hr2);
}
}
}
var contenedor = $('<div class="ADSContainer" style="width:' + widthGral + 'px;height:' + heightGral + 'px;"></div>');
var divheader = $('<div class="HeaderContainer" style="width:' + widthGral + 'px;"></div>');
var divcenter = $('<div class="CenterContainer" style="width:' + widthGral + 'px;"></div>');
var divheader1 = $('<div class="AdsCEll" ></div>');
var divheader2 = $('<div class="AdsRHeader"></div>');
var divcenterCols = $('<div class="AdsCHeader"></div>');
var divcenterbody = $('<div class="AdsBody" ></div>');
Tthis.before(contenedor);
contenedor.append(divheader);
THeader1 = $('<tbody></tbody>');
THeader2 = $('<tbody></tbody>');
for (var i = rowVisibles + 1; i >= 2; i--) {
$('table#ADCol' + Tid + ' > tbody > tr:nth-child(' + i + ')').prependTo(THeader1);
$('table#' + Tid + ' > tbody > tr:nth-child(' + i + ')').prependTo(THeader2);
}
$('table#ADCol' + Tid + ' > tbody > tr:nth-child(1)').clone().prependTo(THeader1);
$('table#' + Tid + ' > tbody > tr:nth-child(1)').clone().prependTo(THeader2);
THeader1 = $('<table></table>').append(THeader1).addClass(Tthis.attr('class'));
THeader2 = $('<table></table>').append(THeader2).addClass(Tthis.attr('class'));
THeader1.removeClass('table-advance');
THeader2.removeClass('table-advance');
divheader.append(divheader1);
divheader.append(divheader2);
divheader1.append(THeader1);
var anchoc1 = divheader1.outerWidth();
var divheader1button = $('<div></div>');
divheader1button.width(anchoc1);
divheader1.append(divheader1button);
divheader1button.append(THeader1);
var altoc1 = divheader1.outerHeight() + 15;
divheaderScroll = $('<div class="ADSCroll RHeader" style="width:' + (widthGral - anchoc1) + 'px;"></div>').append(THeader2);
divheader2.append(divheaderScroll);
contenedor.append(divcenter);
divcenter.append(divcenterCols);
divcolsScroll = $('<div class="ADSCroll" style="height:' + (heightGral - altoc1) + 'px;"></div>').append(TVisibleCols);
divcolsScroll.width(anchoc1);
divcenterCols.append(divcolsScroll);
divcenter.append(divcenterbody);
divbodyScroll = $('<div class="ADSCroll" style="width:' + (widthGral - anchoc1) + 'px;height:' + (heightGral - altoc1 + 20) + 'px;"></div>').append(Tthis);
divcenterbody.append(divbodyScroll);
let fncScroll = function (obj, $this, divheaderScroll, idx) {
if (idx) {
divheaderScroll.scrollLeft($this.scrollLeft());
}
obj.scrollTop($this.scrollTop());
};
divbodyScroll.mouseover(function () {
divbodyScroll.scroll(function () { fncScroll(divcolsScroll, divbodyScroll, divheaderScroll, true); });
});
divcolsScroll.mouseover(function () {
divcolsScroll.scroll(function () { fncScroll(divbodyScroll, divcolsScroll, divheaderScroll, false); });
});
divbodyScroll.mouseleave(function () {
divbodyScroll.unbind('scroll');
});
divcolsScroll.mouseleave(function () {
divcolsScroll.unbind('scroll');
});
let sizeoftablefunc = function () {
let widthtx = divheader1.outerWidth() + divheader2.outerWidth();
let widthtxb = divcenterCols.outerWidth() + divcenterbody.outerWidth();
divheader.css('width', widthtx);
divcenter.css('width', widthtx);
let sizetable = Tthis.outerHeight();
if (sizetable < divbodyScroll.height()) {
sizetable = sizetable + 20;
divcolsScroll.css('height', sizetable);
divbodyScroll.css('height', sizetable);
contenedor.css('width', sizetable + altoc1);
}
};
let resizefncscroller = function () {
//var widthGral = $(window).width() - WidthMenos;
/*console.log(widthGral);*/
//contenedor.css('width', 1);
//widthGral = Tthis.parent().parent().parent().parent().parent().width();
widthGral = Tthis.parent().parent().width();
/* console.log(widthGral);*/
var heightGral = $(window).height() - HeightMenos;
//console.log(heightGral);
if (Heightfijo > 0) { heightGral = Heightfijo; }
if (widthGral < 300) { widthGral = 300; }
if (heightGral < 300) { heightGral = 300; }
contenedor.css('width', widthGral);
divheader.css('width', widthGral);
divcenter.css('width', widthGral);
divheaderScroll.css('width', (widthGral - anchoc1));
divcolsScroll.css('height', (heightGral - altoc1 + 20));
divbodyScroll.css('width', (widthGral - anchoc1));
divbodyScroll.css('height', (heightGral - altoc1 + 20));
setTimeout(sizeoftablefunc, 100);
};
//$(window).resize(function () {
// setTimeout(resizefncscroller, 50);
// setTimeout(sizeoftablefunc, 150);
//});
$('table#ADCol' + Tid + ' tr').hover(
function () { $('table#' + Tid + ' tr:nth-child(' + ($(this).index() + 1) + ')').addClass('hover'); },
function () { $('table#' + Tid + ' tr:nth-child(' + ($(this).index() + 1) + ')').removeClass('hover'); });
$('table#' + Tid + ' tr').hover(
function () { $('table#ADCol' + Tid + ' tr:nth-child(' + ($(this).index() + 1) + ')').addClass('hover'); },
function () { $('table#ADCol' + Tid + ' tr:nth-child(' + ($(this).index() + 1) + ')').removeClass('hover'); });
setTimeout(sizeoftablefunc, 100);
Tthis.parent().parent().bind('resize', function () {
setTimeout(resizefncscroller, 100);
})
let found = adscrollerposition.find(element => element.id = 'C_Tab_TabNominas_GvNominas');
if (found != null) {
divheaderScroll.scrollLeft(found.scrollLeft);
divbodyScroll.scrollLeft(found.scrollLeft);
divcolsScroll.scrollTop(found.scrollTop);
divbodyScroll.scrollTop(found.scrollTop);
}
}
catch (err) {
console.log("ADSCROLLER2 Error:" + err.message);
}
});
}
function CargaPickers() {
if ($.datetimepicker) {
$.datetimepicker.setLocale('es');
$('input.ADDateTimePicker').each(function () {
let TThis = $(this);
let datetimeButton = TThis.attr('datetimeButton')
TThis.datetimepicker({
dayOfWeekStart: 1,
lang: 'es',
format: 'd/m/Y H:i',
formatDate: 'd/m/Y H:i',
step: 30
});
if (datetimeButton && datetimeButton.length) {
let button = $(datetimeButton);
if (button && button.length) {
button.unbind("click");
button.bind("click", function () {
TThis.datetimepicker('show')
});
} else {
console.error('no se encontro el boton :' + datetimeButton)
}
} else//creoBoton
{
var Div = TThis.parent()
var boton = document.createElement('span');
boton.className = "input-group-btn"
var subboton = document.createElement('a')
subboton.className = "btn default"
subboton.innerHTML = "<i class='fa fa-calendar'></i>"
subboton.addEventListener('click', function () {
TThis.datetimepicker('show')
});
boton.appendChild(subboton)
var agregar = true;
for (var i = 0; i < Div[0].children.length; i++) {
if (Div[0].children[i].isEqualNode(boton)) {
agregar = false;
}
}
if (agregar) {
//Div[0].appendChild(boton);
TThis.after(boton);
}
}
//Div[0].appendChild(boton)
});
} else {
console.error("caught TypeError: datetimepicker is undefined");
}
}
//function DataTablePaginatorScroll() {
// $('.table.ADScrollPaginator').each(function () {
// var Tthis = $(this);
// if (!$.fn.DataTable.isDataTable(Tthis) && Tthis.find("th").length > 0) {
// Tthis.prepend(("<thead></thead>"));
// Tthis.find('thead').append($("#C_GvBarra").find("tr:first"));
// Tthis.DataTable({
// deferRender: true,
// deferLoading: 100,
// scrollY: 130,
// scrollCollapse: true,
// scroller: {
// displayBuffer: 20
// },
// ordering: false
// });
// //Tthis.bind('mousewheel', function (e) {
// // if (e.originalEvent.wheelDelta < 0) {
// // //scroll down
// // $(".paginate_button.next").click()
// // } else {
// // //scroll up
// // $(".paginate_button.previous").click()
// // }
// // //prevent page fom scrolling
// // return false;
// //});
// var parent = Tthis.parent().parent().parent()
// $('.dataTables_scrollHeadInner > .table.ADScrollPaginator').find('th').addClass('importantth');
// parent.find(".dataTables_paginate").css("display", "none")
// parent.find(".dataTables_length").css("display", "none")
// }
// });
//}
function DataTablePaginatorScroll() {
$('.table.ADScrollPaginator').each(function () {
var Tthis = $(this);
if (!$.fn.DataTable.isDataTable(Tthis) && Tthis.find("th").length > 0) {
Tthis.prepend(("<thead></thead>"));
Tthis.find('thead').append($("#C_GvBarra").find("tr:first"));
Tthis.DataTable({
"sPagingType": "scroll",
"lengthMenu": [[5, 8, 10], [5, 8, 10]],
"bSort": false
});
Tthis.bind('mousewheel', function (e) {
if (e.originalEvent.wheelDelta < 0) {
//scroll down
$(".paginate_button.next").click()
} else {
//scroll up
$(".paginate_button.previous").click()
}
//prevent page fom scrolling
return false;
});
Tthis.find('th').addClass("importantth");
var parent = Tthis.parent()
parent.find(".dataTables_paginate").css("display", "none")
parent.find(".dataTables_length").css("display", "none")
}
});
}
function DataTablePaginatorScroll2() {
$('.table.ADScrollPaginator2').each(function () {
var Tthis = $(this);
if (!$.fn.DataTable.isDataTable(Tthis) && Tthis.find("th").length > 0) {
Tthis.prepend(("<thead></thead>"));
Tthis.find('thead').append($("#C_GvBarra").find("tr:first"));
//var table = Tthis.DataTable({
// deferRender: true,
// scrollY: 130,
// scrollCollapse: true,
// scroller: true,
// keys: true
//});
var table = Tthis.DataTable({
deferRender: true,
deferLoading: 100,
scrollY: 130,
scrollCollapse: true,
scroller: {
displayBuffer: 20
},
ordering: true
});
var tkeys = new $.fn.dataTable.KeyTable(table, {
// options
});
//tkeys.on('key', function (e, datatable, key, cell, originalEvent) {
// console.log("teclando.....");
// if (key === 13) { // return
// editor
// .one('close', function () {
// table.keys.enable();
// })
// .inline(cell);
// table.keys.disable();
// }
//});
//Tthis.bind('mousewheel', function (e) {
// if (e.originalEvent.wheelDelta < 0) {
// //scroll down
// $(".paginate_button.next").click()
// } else {
// //scroll up
// $(".paginate_button.previous").click()
// }
// //prevent page fom scrolling
// return false;
//});
var parent = Tthis.parent().parent().parent()
$('.dataTables_scrollHeadInner > .table.ADScrollPaginator2').find('th').addClass('importantth');
parent.find(".dataTables_paginate").css("display", "none")
parent.find(".dataTables_length").css("display", "none")
}
});
}
function loadadscroll() {
/*
$('table.ScrollAD').each(function (index) {
var freezecols = 0; //filas congeladas
var freezerows = 1;//columnascongeladas
var alto = 0;
if ($(this).data('freezecols')) {
freezecols = $(this).data('freezecols');
}
if ($(this).data('freezerows')) {
freezerows = $(this).data('freezerows');
}
if ($(this).data('height')) {
alto = $(this).data('height');
}
else {
var error = 300;
if ($(this).data('heighterror')) {
error = $(this).data('heighterror');
}
var Tam = TamañoVentana();
var alto = Tam.height - error;
if (alto < 100) {
alto = 100;
}
}
this.id = $(this).attr('id');
ADScroller(this.id, alto, freezerows, freezecols);
});
*/
var Tam = TamañoVentana();
$('table.ScrollAD').each(function () {
var height = 0;
var TThis = $(this);
if (TThis.data('freezerows')) {
TThis.data('rows', $(this).data('freezerows'));
}
if (Number(TThis.data('height'))) {
height = TThis.data('height');
}
else {
var error = 340;
if (Number(TThis.data('heighterror'))) {
error = TThis.data('heighterror');
}
height = Tam.height - error;
if (height < 200) {
height = 200;
}
TThis.data('height', height);
}
//ADSCROLLER2
var colVisibles = isNaN(Number(TThis.data('cols'))) ? 0 : Number(TThis.data('cols'));
if (colVisibles > 0) {
if ((Number(TThis.data('heighterror'))) && !(Number(TThis.data('heightmenos')))) { TThis.data('heightmenos', TThis.data('heighterror')); }
TThis.removeClass("ScrollAD");
TThis.addClass("ADSCROLLER2");
} else {
ADSScroll(TThis);
}
});
}
ADSScroll = function (tablescroll) {
if (tablescroll.is(':visible')) {
//tablescroll.unbind("resize");
// console.log(tablescroll.attr('id') + ' ' + tablescroll.width());
let fncafter = tablescroll.data('fncafter')
let sort = false;
try {
sort = tablescroll.data('sort') ? JSON.parse(tablescroll.data('sort')) : sort;
} catch (e) { }
if (sort && (tablescroll.find('>tbody > tr,>thead > tr').length > 0) && (!$(tablescroll.find('>tbody > tr,>thead > tr')[0]).hasClass('tsorter'))) {
$(tablescroll.find('>tbody > tr,>thead > tr')[0]).addClass('tsorter');
$(tablescroll.find('>tbody > tr,>thead > tr')[0]).find('>th').each(function () {
var html = $(this).html();
$(this).html('<div>' + html + '</div>');
});
}
sort = false;
let divcontainer = $('<div class="ADScroller"></div>');
let divbody = $('<div class="ADScroller-body"></div>');
let divheader = $('<div class="ADScroller-header"></div>');
let divfooter = $('<div class="ADScroller-footer"></div>');
let tableheader = $('<table></table>').append($('<tbody></tbody>'));
tableheader.attr('id', 'ADSH-' + tablescroll.attr('id'));
let tablefooter = $('<table></table>').append($('<tbody></tbody>'));
tablefooter.attr('id', 'ADSF-' + tablescroll.attr('id'));
let trWwidth = $('<tr class="trnopadding ADtr SearchADHeader"></tr>');
let idTheader = tablescroll.data('tableheader');
let scrollwidthrow = tablescroll.data('scrollwidthrow') ? tablescroll.data('scrollwidthrow') : "";
let rowVisibles = isNaN(Number(tablescroll.data('rows'))) ? 1 : Number(tablescroll.data('rows'));
let rowFooter = isNaN(Number(tablescroll.data('footer'))) ? 0 : Number(tablescroll.data('footer'));
let heightBody = isNaN(Number(tablescroll.data('height'))) ? 200 : Number(tablescroll.data('height'));
if (Number(tablescroll.data('height'))) {
heightBody = Number(tablescroll.data('height'));
}
else {
Tamheight = window.innerHeight || document.documentElement.clientHeight || document.getElementsByTagName('body')[0].clientHeight;
var error = 300;
if (Number(tablescroll.data('heighterror'))) {
error = Number(tablescroll.data('heighterror'));
}
heightBody = Tamheight - error;
if (heightBody < 200) {
heightBody = 200;
}
}
if (sort) {
trWwidth.addClass('TRSort');
}
tablescroll.removeClass("ScrollAD");
tableheader.addClass(tablescroll.attr('class')).removeClass("table-advance");
tableheader.attr('style', tablescroll.attr('style'));
tablefooter.addClass(tablescroll.attr('class')).removeClass("table-advance");
tablefooter.attr('style', tablescroll.attr('style'));
/* Se Combinan las tablas titulo y cuerpo */
if (idTheader && idTheader.length) {
if ($(idTheader).length) {
$($(idTheader + "> tbody > tr," + idTheader + "> thead > tr," + idTheader + "> tr").get().reverse()).each(function () {
var trthis = $(this);
tablescroll.prepend(trthis);
rowVisibles += 1;
});
} else {
log("Tabla titulo No encontrada '" + idTheader + "'.");
}
}
let firsttr = null;
tablescroll.find('> tbody > tr' + scrollwidthrow + ',> thead > tr' + scrollwidthrow + ',> tr' + scrollwidthrow + '').each(function () {
var retorno = false;
firsttr = $(this);
if (firsttr.find(' > td[colspan], > th[colspan]').length) { retorno = true; }
return retorno;
});
if (firsttr == null) {
tablescroll.find('> tbody > tr,> thead > tr,> tr').each(function () {
var retorno = false;
firsttr = $(this);
if (firsttr.find(' > td[colspan], > th[colspan]').length) { retorno = true; }
return retorno;
});
}
tablescroll.before(divcontainer);
divcontainer.append(divheader);
divcontainer.append(divbody);
divcontainer.append(divfooter);
divbody.append(tablescroll);
divheader.append(tableheader);
divfooter.append(tablefooter);
//var objDiv = $('<div style="width:' + (tablescroll.width() - 10) + 'px;"></div>');
//tablescroll.before(objDiv);
//objDiv.append(tablescroll);
if (firsttr) {
let childitem = firsttr.find('> td,th').length;
let contador = 1
firsttr.find('> td,th').each(function () {
var thistd = $(this);
let widthitem = thistd.width();
if ((childitem == contador) && widthitem > 0) {
widthitem = widthitem - 10;
}
trWwidth.append($('<td><div style="width:' + widthitem + 'px;"></br></div></td>'));
contador++;
});
}
//objDiv.before(tablescroll);
//objDiv.remove();
var index = 1;
tablescroll.find('> tbody > tr,> thead > tr,> tr').each(function () {
firsttr = $(this);
tableheader.append(firsttr);
if (rowVisibles == index) return false;
index += 1;
});
index = 0;
$(tablescroll.find('> tbody > tr,> thead > tr,> tr').get().reverse()).each(function () {
if (rowFooter == index) return false;
firsttr = $(this);
tablefooter.prepend(firsttr);
index += 1;
});
tableheader.prepend(trWwidth);
tablefooter.prepend(trWwidth.clone().removeClass('TRSort').addClass('trfooter'));
tablescroll.prepend(trWwidth.clone().removeClass('TRSort'));
divbody.css('max-height', heightBody);
if (rowFooter == 0) {
divfooter.css('overflow-x', 'hidden');
divbody.scroll(function () {
divheader.scrollLeft($(this).scrollLeft());
});
} else {
divbody.css('overflow-x', 'hidden');
divfooter.scroll(function () {
divheader.scrollLeft($(this).scrollLeft());
divbody.scrollLeft($(this).scrollLeft());
});
}
if (fncafter) {
try {
eval(fncafter)
} catch (e) {
console.error('fncafter : ' + e)
}
}
}
//else {
// tablescroll.bind('resize', function () {
// let table = tablescroll
// setTimeout(
// function () {
// console.log(tablescroll.attr('id') + ' ' + tablescroll.width());
// ADSScroll(table)
// }, 10);
// })
//}
};
function ADScroller(tablaid, height, freezrows, freezcols) {
if (elementexist('#' + tablaid)) {
var tablita = $('#' + tablaid);
if (!(tablita.hasClass('ADScroller-table') || tablita.hasClass('ADScroller-header'))) {
var contenedor = $('<div id="ADS-' + tablaid + '" class="ADScroller"></div>');//contenedor de todos los objetos incluyendo la tabla
var body = $('<div id="ADSB-' + tablaid + '" class="ADScroller-body"></div>');//este sera elcuerpo scrolleable
var headertable = $('<table id="ADSH-' + tablaid + '" class="ADScroller-header ' + tablita.attr('class') + '"></table>');//inicializo la tabla donde estara los titulos
contenedor.append(headertable);
contenedor.append(body);
tablita.before(contenedor);
body.append(tablita);
var inserted = 1;
if (elementexist('#' + tablaid + ' tr:nth-child(1) th')) {
var mywidthrow = $('<tr class="trnopadding ADtr"></tr>');
$('#' + tablaid + ' tr:nth-child(1) th').each(function (index) {
cols = "";
if (+$(this).attr('colspan') > 1) {
cols = "colspan=" + $(this).attr('colspan');
}
mywidthrow.append($('<th ' + cols + '><div style="width:' + $(this).width() + 'px"></div></th>'));
});
headertable.prepend(mywidthrow);
tablita.prepend(mywidthrow.clone());
inserted = 2;
} else {
if (elementexist('#' + tablaid + ' tr:nth-child(1) td')) {
var mywidthrow = $('<tr class="trnopadding ADtr"></tr>');
$('#' + tablaid + ' tr:nth-child(1) td').each(function (index) {
cols = "";
if (+$(this).attr('colspan') > 1) {
cols = "colspan=" + $(this).attr('colspan');
}
mywidthrow.append($('<th ' + cols + '><div style="width:' + $(this).width() + 'px"></div></th>'));
});
headertable.prepend(mywidthrow);
tablita.prepend(mywidthrow.clone());
inserted = 2;
}
}
//inserto las filas que seran titulos
for (var i = inserted; i < freezrows + inserted; i++) {
headertable.append($('#' + tablaid + ' tr:nth-child(2)'));
}
body.css({ 'max-height': height });
body.css("margin-right", "-8px");
tablita.addClass('ADScroller-table');//le digo que ya tiene el scroll corectamente
}
}
}
function ADDropzone(txtid) {
//initialize variables
//var txt;
var domain = window.location.origin;
var txt = $('#' + txtid); if (txt.val() == '') { txt.val('[]'); }
if (txt.data('loaded') == '1') { }
else {
txt.data('loaded', '1');
var urlup = txt.data('urlup'); if ((urlup) && (urlup != "")) { } else { urlup = domain + "/Ashx/SIGWeb.ashx?metodo=Uploadfile"; }
var urldown = txt.data('urldown'); if ((urldown) && (urldown != "")) { } else { urldown = domain + "/Ashx/SIGWeb.ashx"; }
var urlget = txt.data('urlget'); if ((urlget) && (urlget != "")) { } else { urlget = domain + "/temp/"; }
var maxFilesize = txt.data('maxfilesize'); if (maxFilesize) { } else { maxFilesize = 30; }
var maxFile = txt.attr('data-maxFile'); if (maxFile) { } else { maxFile = null; }
var mydiv = $("<div id='" + txtid + "-drop' class='addropzone'></div>");
var mypaste = $("<div id='" + txtid + "-paste' contenteditable='true' class='mypaste'></div>")
var apppendin = txt.data('append'); if (apppendin) { $('#' + apppendin).html(mydiv); } else { txt.after(mydiv); }
mydiv.append(mypaste);
//inicialice dropdown
//mydiv.dropzone(
var myDropzone = new Dropzone("#" + txtid + "-drop", {
url: urlup,
maxFilesize: maxFilesize,
maxFiles: maxFile,
parallelUploads: 1,
uploadMultiple: false,//envia de uno en uno
init: function () {
var TxtField = txt;
var urlDown = urldown;
this.on("addedfile", function (file) {
// Create the remove button
var removeButton = Dropzone.createElement("<button class='btn btn-sm btn-block'>Quitar archivo</button>");
// Capture the Dropzone instance as closure.
var _this = this;
_this.urldown = urlDown;
// Listen to the click event
removeButton.addEventListener("click", function (e) {
// Make sure the button click doesn't submit the form:
e.preventDefault();
e.stopPropagation();
$.ajax({
url: _this.urldown,
type: "POST",
data: { "metodo": "Downfile", "nombre": file.obj.filename },
success: function (data) {
}
});
var objfiles = JSON.parse(TxtField.val());
for (var i = objfiles.length; i--;) {
if (objfiles[i].filename == file.obj.filename) objfiles.splice(i, 1);
}
TxtField.val(JSON.stringify(objfiles));
_this.removeFile(file);
});
var titulo = Dropzone.createElement("<div>" + file.name + "</div>");
// Add the button to the file preview element.
file.previewElement.appendChild(titulo);
file.previewElement.appendChild(removeButton);
});
this.on("removedfile", function (file) {
});
document.getElementById(txtid + '-paste').onpaste = function (event) {
var __This = myDropzone;
var objfiles = JSON.parse(TxtField.val());
if ((maxFile != null) || (maxFile < 1) || objfiles.length < maxFile) {
// use event.originalEvent.clipboard for newer chrome versions
var items = (event.clipboardData || event.originalEvent.clipboardData).items;
//console.log(JSON.stringify(items)); // will give you the mime types
// find pasted image among pasted items
var blob = null;
for (var i = 0; i < items.length; i++) {
if (items[i].type.indexOf("image") === 0) {
blob = items[i].getAsFile();
}
}
// load image if there is a pasted image
if (blob !== null) {
var reader = new FileReader();
reader.onload = function (event) {
$.ajax({
url: urlup,
type: "POST",
data: { "File": event.target.result, "Cve": "ie" },
success: function (data) {
var objfiles = JSON.parse(TxtField.val());
var fileobj = { filename: data + '-ie.png' };
objfiles.push(fileobj);
TxtField.val(JSON.stringify(objfiles));
var mockFile = { obj: fileobj, name: 'ie.png', size: 0, type: 'image/jpeg', status: Dropzone.ADDED, serverID: 0, accepted: true };
__This.emit("addedfile", mockFile);
// __This.emit("thumbnail", mockFile, urlget + data + '-ie.png');
__This.emit("thumbnail", mockFile, event.target.result);
__This.files.push(mockFile);
}
});
};
reader.readAsDataURL(blob);
}
} else {
bootbox.dialog({ message: 'Hay un limite de archivos de ' + maxFile, className: 'header-yellow', title: 'Limite de Archivos excedido', buttons: { main: { label: 'Aceptar', className: 'default', callback: function () { } } } });
this.html(' ')
}
};
var objfiles = JSON.parse(TxtField.val());
for (var i = objfiles.length; i--;) {
objfiles[i].url = urlget + objfiles[i].filename;
var objname = objfiles[i].filename.split('-', 2)[1];
var objtype = objname.split('.');
var objtype = objtype[objtype.length - 1];
if (objtype == 'jpg' || objtype == 'png') { objtype = 'image/jpeg' }
var mockFile = { obj: objfiles[i], name: objname, size: 0, type: objtype, status: Dropzone.ADDED, serverID: 0, accepted: true };
this.emit("addedfile", mockFile);
if (objtype == 'image/jpeg') { this.emit("thumbnail", mockFile, objfiles[i].url); }
this.files.push(mockFile);
}
this.on("success", function (file, Response) {
var objfiles = JSON.parse(TxtField.val());
file.obj = { filename: Response + "-" + file.name };
objfiles.push(file.obj);
TxtField.val(JSON.stringify(objfiles));
});
this.on("maxfilesexceeded", function (file, Response) {
this.removeFile(file);
bootbox.dialog({ message: 'Hay un limite de archivos de ' + maxFile, className: 'header-yellow', title: 'Límite de Archivos excedido', buttons: { main: { label: 'Aceptar', className: 'default', callback: function () { } } } });
});
}
});
}
}
function loadAdDropzone() {
$('input.ADSdropzone').each(function (index) {
if (!elementexist('#' + $(this).attr('id') + '-drop')) {
ADDropzone($(this).attr('id'));
}
});
}
function ADDropzoneLocal(txtid) {
var txt = $('#' + txtid);
if (!txt.length) {
return null;
}
if (txt.attr('data-sig-dropzone-local-initialized') === '1') {
return window.ADSLocalDropzone
? window.ADSLocalDropzone.instance(txtid)
: null;
}
var maxFilesize = Number(txt.attr('data-maxfilesize')) || 30;
var maxFile = parseInt(
txt.attr('data-maxFile') || txt.attr('data-maxfile'),
10);
var acceptedFiles = txt.attr('data-acceptedfiles') || null;
var message = txt.attr('data-message') ||
'Arrastra un archivo aquí o haz clic para seleccionarlo.';
var appendId = txt.attr('data-append');
var dropId = txtid + '-drop';
var existing = $('#' + dropId);
if (existing.length) {
existing.remove();
}
var mydiv = $(
'<div id="' + dropId + '" class="addropzone ADSdropzoneLocalContainer" tabindex="0">' +
' <div class="dz-message">' + $('<div/>').text(message).html() + '</div>' +
'</div>');
if (appendId && $('#' + appendId).length) {
$('#' + appendId).empty().append(mydiv);
} else {
txt.after(mydiv);
}
function registerInstance(instance) {
txt.attr('data-sig-dropzone-local-initialized', '1');
window.ADSLocalDropzone = window.ADSLocalDropzone || {};
window.ADSLocalDropzone.instances =
window.ADSLocalDropzone.instances || {};
window.ADSLocalDropzone.instances[txtid] = instance;
return instance;
}
function isAccepted(file) {
if (!acceptedFiles) {
return true;
}
var name = String(file && file.name || '').toLowerCase();
var type = String(file && file.type || '').toLowerCase();
var accepted = acceptedFiles.split(',');
for (var i = 0; i < accepted.length; i++) {
var rule = $.trim(accepted[i]).toLowerCase();
if (!rule) {
continue;
}
if (rule.charAt(0) === '.' && name.slice(-rule.length) === rule) {
return true;
}
if (rule.slice(-2) === '/*' &&
type.indexOf(rule.substring(0, rule.length - 1)) === 0) {
return true;
}
if (type && type === rule) {
return true;
}
}
return false;
}
function readFile(file, instance) {
if (!file) {
return;
}
if (!isAccepted(file)) {
txt.trigger('adsdropzone:fileerror', [
file,
'El tipo de archivo no está permitido.',
instance
]);
return;
}
if (file.size > maxFilesize * 1024 * 1024) {
txt.trigger('adsdropzone:fileerror', [
file,
'El archivo excede el tamaño permitido.',
instance
]);
return;
}
var reader = new FileReader();
reader.onload = function (event) {
txt.trigger('adsdropzone:fileadded', [
file,
event.target.result,
instance
]);
};
reader.onerror = function () {
txt.trigger('adsdropzone:fileerror', [
file,
'No fue posible leer el archivo seleccionado.',
instance
]);
};
reader.readAsText(file);
}
/*
* El proyecto recibido conserva el helper histórico ADDropzone(), pero no
* contiene la librería Dropzone dentro de sus bundles. Para que el GIS no
* dependa de una referencia externa, este componente tiene un fallback
* nativo que mantiene la misma experiencia: clic, drag/drop, vista del
* archivo y los mismos eventos adsdropzone:* consumidos por la pantalla.
* Si Dropzone está cargado en otra instalación, se usa normalmente.
*/
if (typeof Dropzone === 'undefined') {
var input = $('<input type="file" style="display:none;" />');
if (acceptedFiles) {
input.attr('accept', acceptedFiles);
}
if (isNaN(maxFile) || maxFile !== 1) {
input.attr('multiple', 'multiple');
}
mydiv.append(input);
var fallback = {
files: [],
removeFile: function (file) {
var index = this.files.indexOf(file);
if (index >= 0) {
this.files.splice(index, 1);
}
renderFallback();
txt.trigger('adsdropzone:fileremoved', [file, fallback]);
},
removeAllFiles: function () {
var files = this.files.slice(0);
this.files = [];
renderFallback();
$.each(files, function (_, file) {
txt.trigger('adsdropzone:fileremoved', [file, fallback]);
});
}
};
function renderFallback() {
mydiv.find('.ADSdropzoneLocalFallbackPreview').remove();
mydiv.find('.dz-message').toggle(fallback.files.length === 0);
$.each(fallback.files, function (_, file) {
var preview = $('<div class="ADSdropzoneLocalFallbackPreview"></div>');
$('<div class="ADSdropzoneLocalFileName"></div>')
.text(file.name)
.appendTo(preview);
$('<button type="button" class="btn btn-sm btn-block default">Quitar archivo</button>')
.on('click', function (event) {
event.preventDefault();
event.stopPropagation();
fallback.removeFile(file);
})
.appendTo(preview);
mydiv.append(preview);
});
}
function addFallbackFile(file) {
if (!file) {
return;
}
if (!isAccepted(file)) {
txt.trigger('adsdropzone:fileerror', [
file,
'El tipo de archivo no está permitido.',
fallback
]);
return;
}
if (file.size > maxFilesize * 1024 * 1024) {
txt.trigger('adsdropzone:fileerror', [
file,
'El archivo excede el tamaño permitido.',
fallback
]);
return;
}
if (!isNaN(maxFile) && maxFile > 0 && fallback.files.length >= maxFile) {
fallback.removeAllFiles();
}
fallback.files.push(file);
renderFallback();
readFile(file, fallback);
}
input.on('change', function () {
var files = this.files || [];
for (var i = 0; i < files.length; i++) {
addFallbackFile(files[i]);
}
this.value = '';
});
/*
* El input file vive dentro de mydiv. Si usamos input.trigger('click'),
* el click burbujea nuevamente a mydiv y vuelve a disparar el input,
* provocando recursión infinita (Maximum call stack size exceeded).
*/
input.on('click', function (event) {
event.stopPropagation();
});
mydiv.on('click', function (event) {
if ($(event.target).closest('button, input[type="file"]').length) {
return;
}
var fileInput = input.get(0);
if (fileInput) {
fileInput.click();
}
});
mydiv.on('keydown', function (event) {
if (event.which === 13 || event.which === 32) {
event.preventDefault();
var fileInput = input.get(0);
if (fileInput) {
fileInput.click();
}
}
});
mydiv.on('dragenter dragover', function (event) {
event.preventDefault();
event.stopPropagation();
mydiv.addClass('is-dragging');
});
mydiv.on('dragleave', function (event) {
event.preventDefault();
event.stopPropagation();
mydiv.removeClass('is-dragging');
});
mydiv.on('drop', function (event) {
event.preventDefault();
event.stopPropagation();
mydiv.removeClass('is-dragging');
var original = event.originalEvent;
var files = original && original.dataTransfer
? original.dataTransfer.files
: null;
if (!files) {
return;
}
for (var i = 0; i < files.length; i++) {
addFallbackFile(files[i]);
}
});
return registerInstance(fallback);
}
var instance;
try {
instance = new Dropzone('#' + dropId, {
url: window.location.href,
autoProcessQueue: false,
uploadMultiple: false,
parallelUploads: 1,
maxFiles: isNaN(maxFile) || maxFile <= 0 ? null : maxFile,
maxFilesize: maxFilesize,
acceptedFiles: acceptedFiles,
addRemoveLinks: true,
dictDefaultMessage: message,
dictRemoveFile: 'Quitar archivo',
dictInvalidFileType: 'El tipo de archivo no está permitido.',
dictFileTooBig: 'El archivo excede el tamaño permitido.',
dictMaxFilesExceeded: 'Se excedió el número máximo de archivos.',
init: function () {
var dz = this;
dz.on('addedfile', function (file) {
if (dz.options.maxFiles && dz.files.length > dz.options.maxFiles) {
dz.removeFile(file);
return;
}
readFile(file, dz);
});
dz.on('removedfile', function (file) {
txt.trigger('adsdropzone:fileremoved', [file, dz]);
});
dz.on('error', function (file, errorMessage) {
txt.trigger('adsdropzone:fileerror', [
file,
typeof errorMessage === 'string'
? errorMessage
: 'El archivo seleccionado no es válido.',
dz
]);
});
}
});
} catch (ex) {
mydiv.remove();
txt.removeAttr('data-sig-dropzone-local-initialized');
console.error('ADDropzoneLocal Error:', ex);
return null;
}
return registerInstance(instance);
}
window.ADSLocalDropzone = window.ADSLocalDropzone || {};
window.ADSLocalDropzone.instances = window.ADSLocalDropzone.instances || {};
window.ADSLocalDropzone.instance = function (txtid) {
return window.ADSLocalDropzone.instances[txtid] || null;
};
window.ADSLocalDropzone.getFiles = function (txtid) {
var instance = window.ADSLocalDropzone.instance(txtid);
return instance && instance.files ? instance.files.slice(0) : [];
};
window.ADSLocalDropzone.getFile = function (txtid) {
var files = window.ADSLocalDropzone.getFiles(txtid);
return files.length ? files[files.length - 1] : null;
};
window.ADSLocalDropzone.clear = function (txtid) {
var instance = window.ADSLocalDropzone.instance(txtid);
if (instance && typeof instance.removeAllFiles === 'function') {
instance.removeAllFiles(true);
}
};
function loadAdDropzoneLocal() {
$('.ADSdropzoneLocal[id]').each(function () {
ADDropzoneLocal($(this).attr('id'));
});
}
function setwebservice(idDdlWS, idhdValue, idhdText, btn) {
var DdlWS = $("#" + idDdlWS);
var hdValue = $("#" + idhdValue);
var hdText = $("#" + idhdText);
var CveClasificacion;
var CveSubFamilia;
if (DdlWS) {
if (!(hdValue.val() == '')) {
//AddItem(hdText.val(), hdValue.val(), DdlWS);
DdlWS.append($('<option value="' + hdValue.val() + '">' + hdText.val() + '</option>'));
}
if (DdlWS.data('contodos') == "1" && !(hdValue.val() == '-1')) {
DdlWS.append($('<option value="-1">Todos</option>'));
}
}
if (DdlWS.data('creado') == '1') { } else {
DdlWS.select2({
ajax: {
url: "/Ashx/SIGWeb.ashx",
dataType: 'json',
delay: 500,
data: function (params) {
debugger;
return {
Name: params.term, // search term
CveSubFamilia: (!(DdlWS.attr('data-idSubFamilia')) || DdlWS.attr('data-idSubFamilia') == '') ? ((!(DdlWS.data('subFamilia'))) ? DdlWS.data('subfamilia') : -2) : $('#' + DdlWS.attr('data-idSubFamilia') + ' option:selected').val(),
//CveClasificacion: (!(DdlWS.attr('data-idclasificacion')) || DdlWS.attr('data-idclasificacion') == '') ? ((!(DdlWS.data('clasificacion'))) ? DdlWS.data('clasificacion') : -2) : $('#' + DdlWS.attr('data-idclasificacion') + ' option:selected').val(),
CveClasificacionPresupuesto: (!(DdlWS.attr('data-idClasificacionPresupuesto')) || DdlWS.attr('data-idClasificacionPresupuesto') == '') ? ((!(DdlWS.data('clasificacionpresupuesto'))) ? DdlWS.data('clasificacionpresupuesto') : -2) : $('#' + DdlWS.attr('data-idClasificacionPresupuesto') + ' option:selected').val(),
FuePorXml: (!(DdlWS.data('fueporxml')) || DdlWS.data('fueporxml') == '') ? -2 : DdlWS.data('fueporxml'),
Estatus: (!(DdlWS.data('estatus')) || DdlWS.data('estatus') == '') ? 1 : DdlWS.data('estatus'),
CveClasificacion: (!(DdlWS.data('cveclasificacion')) || DdlWS.data('cveclasificacion') == '') ? -1 : DdlWS.data('cveclasificacion'),
CveSucursal: (!(DdlWS.data('cvesucursal')) || DdlWS.data('cvesucursal') == '') ? ((!(DdlWS.parent().data('cvesucursal')) || DdlWS.parent().data('cvesucursal') == '') ? -1 : DdlWS.parent().data('cvesucursal')) : DdlWS.data('cvesucursal'),
CveSubProyecto: (!(DdlWS.data('cvesubproyecto')) || DdlWS.data('cvesubproyecto') == '') ? ((!(DdlWS.parent().data('cvesubproyecto')) || DdlWS.parent().data('cvesubproyecto') == '') ? -1 : DdlWS.parent().data('cvesubproyecto')) : DdlWS.data('cvesubproyecto'),
metodo: (!(DdlWS.data('metodo')) || DdlWS.data('metodo') == 'getps') ? ((!(DdlWS.parent().data('metodo')) || DdlWS.parent().data('metodo') == 'getps') ? 'getps' : DdlWS.parent().data('metodo')) : DdlWS.data('metodo'),
Pagina: (!(DdlWS.data('pagina')) || DdlWS.data('pagina') == '') ? '-2' : DdlWS.data('pagina'),
ColTexto: (!(DdlWS.data('coltexto')) || DdlWS.data('coltexto') == '') ? 'NC' : DdlWS.data('coltexto'),
aplicaparaventa: (!(DdlWS.data('aplicaparaventa')) || DdlWS.data('aplicaparaventa') == '') ? -1 : DdlWS.data('aplicaparaventa'),
cvemarca: (!(DdlWS.data('cvemarca')) || DdlWS.data('cvemarca') == '') ? -1 : DdlWS.data('cvemarca'),
esdistribuidor: (!(DdlWS.data('esdistribuidor')) || DdlWS.data('esdistribuidor') == '') ? -1 : DdlWS.data('esdistribuidor'),
cveclienteclasificacion: (!(DdlWS.data('cveclienteclasificacion')) || DdlWS.data('cveclienteclasificacion') == '') ? -1 : DdlWS.data('cveclienteclasificacion'),
cvealmacen: (!(DdlWS.data('cvealmacen')) || DdlWS.data('cvealmacen') == '') ? -1 : DdlWS.data('cvealmacen'),
se: (!(DdlWS.data('se')) || DdlWS.data('se') == '') ? -1 : DdlWS.data('se')
//Metodo: metodo
};
},
processResults: function (data, params) {
// parse the results into the format expected by Select2
// since we are using custom formatting functions we do not need to
// alter the remote JSON data, except to indicate that infinite
// scrolling can be used
var onresult = (!(DdlWS.data('onresult')) || DdlWS.data('onresult') == '') ? ((!(DdlWS.parent().data('onresult')) || DdlWS.parent().data('onresult') == '') ? '' : DdlWS.parent().data('onresult')) : DdlWS.data('onresult');
if (onresult.length > 0) {
eval(onresult + '(data,params)');
}
if (DdlWS.data('contodos') == "1") {
data.unshift({ id: "-1", text: "Todos" })
}
params.page = params.page || 1;
return {
results: data
//,pagination: {
// more: (params.page * 30) < data.total_count
//}
};
},
cache: true,
allowClear: false
},
escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
minimumInputLength: 3
});
DdlWS.data('creado', '1')
}
if (DdlWS) {
DdlWS.on("select2:select", function (e) {
var base = '#' + $(this).attr("id").replace('ddlWS', '');
hdValue.val(e.params.data.id);
hdText.val(e.params.data.text);
$("#" + btn).click();
});
}
}
function loadwebservice() {
$('.select2ws').each(function (index) {
var _this = $(this);
//try {
setwebservice(_this.attr("id"), _this.attr("data-txtvalue"), _this.attr("data-txttext"), _this.attr("data-btn"))
_this.removeClass("select2me");
_this.removeClass("select2ws");
//}
//catch (err) { }
});
}
function loadADSortable() {
$('.ADsortable').each(function (index) {
var _this = $(this);
if (_this.data("ADsortable") != "load") {
$(_this.find('ul.ADSortable-list')).sortable({
_thisUL: $(this),
connectWith: '#' + _this.attr('id') + ' .ADSortable-list',
start: function (event, ui) { downMove = false; },
stop: function (event, ui) {
var objitem = ui.item.data('id');
var objparent = $(ui.item.parent()).data('id');
var data = ['VER', objitem, objparent];
var id = $('#' + _this.attr('id')).data('obj');
var btn = $('#' + _this.attr('id')).data('btn');
$(id).val(JSON.stringify(data));
$(btn).click();
//console.log(' el: ' + objitem + ' a ' + objparent)
}
});
}
_this.data("ADsortable", "load")
});
}
function movepanel() {
var downMove = null;
var x;
var y;
var top;
var left;
$(".backmove").mousedown(function (e) {
e.preventDefault();
downMove = $(this);
x = e.pageX;
y = e.pageY;
top = $(this).scrollTop();
left = $(this).scrollLeft();
});
$("body").mousemove(function (e) {
if (downMove) {
var newX = e.pageX;
var newY = e.pageY;
downMove.scrollTop(top - newY + y);
downMove.scrollLeft(left - newX + x);
}
});
$("body").mouseup(function (e) { downMove = false; });
}
function AdsTabWizard() {
setTimeout(function () {
$('.tab-wizard,.tab-wizard2').each(function () {
let total = $(this).find('> .ajax__tab_header > span').length;
let maximo = $(this).find('> .ajax__tab_header > span.ajax__tab_active').index() + 1;
if ($(this).find('> .bar.tab-wizard').length == 0) {
let barout = $('<div class="bar progress tab-wizard progress-striped active"></div>');
let barin = $('<div class="progress-bar" role="progressbar" aria-valuenow="10" aria-valuemin="0" aria-valuemax="100" style="width: ' + ((maximo / total) * 100) + '%;"></div>');
barout.append(barin);
$(this).find('> .ajax__tab_body').before(barout);
} else {
let padre = $(this);
let total = padre.find('> .ajax__tab_header > span').length;
let maximo = $(this).find('> .ajax__tab_header > span.ajax__tab_active').index() + 1;
padre.find('> .progress.tab-wizard > .progress-bar').css('width', '' + ((maximo / total) * 100) + '%');
$(this).find('> .bar.tab-wizard')
}
});
}, 10)
}
function MoveFixedDiv() {
var downMove = null;
var x;
var y;
$("body").on('mousedown', '.modal-content >.modal-header', function (e) {
e.preventDefault();
downMove = $(this).parent().parent();
x = e.pageX;
y = e.pageY;
//console.log(y+","+y)
});
$("body").mousemove(function (e) {
if (downMove) {
var newX = e.pageX - x;
var newY = e.pageY - y;
x = e.pageX;
y = e.pageY;
topy = parseInt(downMove.css('margin-top').replace('px', '')) + newY
left = parseInt(downMove.css('margin-left').replace('px', '')) + newX
//console.log(topy + "," + left)
downMove.css('margin-top', topy)
downMove.css('margin-left', left)
}
});
$("body").mouseup(function (e) { downMove = false; });
}
function changeurlmodal(url) {
}
var ADSSignalR = function () {
var addToCampanita = function (Tipo, Notificacion, TipoNotificacion, Imagen) {
//var Tipo = 2;
//var Imagen = '<i class="material-icons">&#xE15C;</i>';
//var TipoNotificacion = "Documento Rechazado"
var noti = $('#header_notification_bar > ul > li > div > ul > li > a[data-tipo="' + Tipo + '"]');
if ((noti) && (noti.html())) {
var contador = parseInt(noti.data("count")) + 1;
noti.data("count", contador);
noti = $('#header_notification_bar > ul > li > div > ul > li > a[data-tipo="' + Tipo + '"] span.time');
noti.html(contador);
} else {
noti = $('<li><a href="javascript:void(0)" onclick="loadnotificacion(' + Tipo + ');" data-tipo="' + Tipo + '" data-count="1"><span class="time">1</span><span class="details"><span class="label label-sm label-icon label-success"> &nbsp;' + Imagen + '&nbsp;</span>' + TipoNotificacion + '</span></a></li>');
$('#header_notification_bar > ul > li > div > ul').append(noti)
}
//loadcampanita();
var obj = '{ "Tipo":"' + Tipo + '" , "Notificacion":"' + Notificacion.replace("\"", "'") + '", "TipoNotificacion":"' + TipoNotificacion.replace("\"", "'") + '", "Imagen":"' + Imagen.replace("\"", "'").replace("\"", "'") + '" }';
//ObjNotificacion(Tipo, Notificacion, TipoNotificacion, Imagen);
localStorage.setItem("signaladdToCampanita", obj);
localStorage.removeItem("signaladdToCampanita");
}
var sendNotificacionERP = function (titulo, message, tipo) {
var tipoNotificacion = "success";
switch (tipo) {
case 0:
tipoNotificacion = "info";
break;
case 1:
tipoNotificacion = "error";
break;
case 2:
tipoNotificacion = "warning";
break;
default:
tipoNotificacion = "success";
}
var obj = { Tipo: tipoNotificacion, Titulo: titulo, Mensaje: message };
var json = JSON.stringify(obj);
console.log("entro el evento");
localStorage.setItem("signalsendNotificationERP", json);
localStorage.removeItem("signalsendNotificationERP");
}
var receivenotification = function (mensaje, url) {
if ((url) && url.length > 0) {
toastr.options = { onclick: function () { window.location.replace(url); } }
}
toastr.warning(mensaje);
localStorage.setItem("signalreceivenotification", mensaje);
localStorage.removeItem("signalreceivenotification");
}
var broadcastMessage = function (name, mensaje) {
console.log(name + ' : ' + mensaje);
}
var addsignalrconexion = function () {
if (false) {
IHAVEALLTHEPOWER = true;
var proxy = $.connection.myHub;
/*$.connection.hub.url = '/signalr';*/
$.connection.hub.disconnected(function () {
setTimeout(function () {
$.connection.hub.start();
}, 45000); // Restart connection after 25 seconds.
});
toastr.options = {
"closeButton": true,
"debug": false,
"positionClass": "toast-top-right",
"showDuration": "10000",
"hideDuration": "10000",
"timeOut": "10000",
"extendedTimeOut": "15000",
"showEasing": "swing",
"hideEasing": "linear",
"showMethod": "fadeIn",
"hideMethod": "fadeOut"
};
//addToCampanita(Notificacion, TipoNotificacion, Imagen)
proxy.client.addToCampanita = addToCampanita;
proxy.client.receivenotification = receivenotification;
proxy.client.broadcastMessage = broadcastMessage;
proxy.client.sendNotificacionERP = sendNotificacionERP;
$.connection.hub.start().done(function () {
console.log('conected');
});
}
}
function enviarmensajeAdsistemas(mensaje) {
if (IHAVEALLTHEPOWER) {
$.connection.myHub.server.senmessage(mensaje);
} else {
localStorage.setItem("senmessage", mensaje);
}
}
function storageEventHandler(evt) {
console.log("localstorage");
switch (evt.key + "") {
case 'SignalONOFF':
reloadSignalR(evt.key)
break;
case 'signalreceivenotification':
if (evt.newValue && evt.newValue != null) {
toastr.warning(evt.newValue);
}
break;
case 'signaladdToCampanita':
if (evt.newValue && evt.newValue != null) {
console.log(evt.newValue);
var obj = JSON.parse(evt.newValue);
var Tipo = obj.Tipo;
var Imagen = obj.Imagen;
var TipoNotificacion = obj.TipoNotificacion;
var noti = $('#header_notification_bar > ul > li > div > ul > li > a[data-tipo="' + Tipo + '"]');
if ((noti) && (noti.html())) {
var contador = parseInt(noti.data("count")) + 1;
noti.data("count", contador);
noti = $('#header_notification_bar > ul > li > div > ul > li > a[data-tipo="' + Tipo + '"] span.time');
noti.html(contador);
} else {
noti = $('<li><a href="javascript:void(0)" onclick="loadnotificacion(' + Tipo + ');" data-tipo="' + Tipo + '" data-count="1"><span class="time">1</span><span class="details"><span class="label label-sm label-icon label-success"> &nbsp;' + Imagen + '&nbsp;</span>' + TipoNotificacion + '</span></a></li>');
$('#header_notification_bar > ul > li > div > ul').append(noti)
}
//loadcampanita();
}
break;
case 'signalsendNotificationERP':
console.log("signalsendNotificationERP");
if (evt.newValue && evt.newValue != null) {
console.log(evt.newValue);
var obj = JSON.parse(evt.newValue);
ShowToastERP(obj.Mensaje, obj.Titulo, obj.Tipo);
}
break;
case 'Response':
if (evt.newValue && evt.newValue != null) {
$("body").append($("<div>" + evt.newValue + "</div>"));
}
break;
case 'senmessage':
if (evt.newValue && evt.newValue != null) {
if (IHAVEALLTHEPOWER) {
var obj = JSON.parse(evt.newValue);
$.connection.myHub.server.senmessage(obj.msg, obj.to);
}
}
break;
}
}
function reloadSignalR(value) {
/*
var valueactual = localStorage.getItem("SignalONOFF");
var d = new Date();
var n = d.getHours();
if (valueactual != n) {
window.addEventListener("beforeunload", function (e) {
localStorage.removeItem("SignalONOFF");
});
addsignalrconexion();
localStorage.setItem("SignalONOFF", n);
}*/
}
//function enviarmensajeAdsistemas(mensaje, para) {
// $.connection.myHub.server.senmessage(mensaje);
//}
//window.addEventListener('storage', storageEventHandler, false);
//reloadSignalR('');
};
function ShowToastERP(text, header, type) {
toastr.options = {
"closeButton": true,
"debug": false,
"newestOnTop": true,
"progressBar": false,
"positionClass": "toast-bottom-right",
"preventDuplicates": false,
"showDuration": "300",
"hideDuration": "1000",
"timeOut": "10000",
"extendedTimeOut": "1000",
"showEasing": "swing",
"hideEasing": "linear",
"showMethod": "fadeIn",
"hideMethod": "fadeOut"
}
toastr[type](text, header);
}
function portletshowhide() {
if (objsexpand) {
objsexpand.each(function () {
var idthis = '#' + $(this).attr('id');
$(idthis + ' > .portlet-body').hide();
$(idthis + ' > .portlet-title .collapse').removeClass('collapse').addClass('expand');
});
}
if (objscollapse) {
objscollapse.each(function () {
var idthis = '#' + $(this).attr('id');
$(idthis + ' > .portlet-body').show();
$(idthis + ' > .portlet-title .expand').removeClass('expand').addClass('collapse');
});
}
objsexpand = null;
objscollapse = null;
}
function ADSBegin() {
}
function ADSReady() {
}
function loadsortadscroll() {
LoadSortSticky();
$('body').on('click', '.ADScroller > div > table > tbody > tr.tsorter:not(.tsorterblock) >th ,.ADScroller > div > table > thead > tr.tsorter:not(.tsorterblock) >th ', function (e) {
var tthis = $(this);
if (tthis.closest('.NoClick').length == 0 && !($(e.target).is('a,input'))) {
Metronic.blockUI({ animate: true });
var index = tthis.index();
var multiplicador = -1;
var tipodato = tthis.closest('tr').find('th').data('tipodato')
if (1 == 1) {
var table = $(tthis.closest('.ADScroller').find('.ADScroller-body > table ')[0]);
var tabletr = table.find('> tr:not(.trnopadding.ADtr),> tbody > tr:not(.trnopadding.ADtr),> thead > tr:not(.trnopadding.ADtr)');
if (tabletr.length > 0) {
el = $(tabletr[0]);
var tdtexto = el.find("> td");
texto = $(tdtexto[index]).data('order');
if (texto) {
tipodato = 'dataorder';
}
}
}
//console.log({ tipodato })
tthis.closest('tr').addClass('tsorterblock');
setTimeout(
function () {
if (tthis.hasClass('DESC')) {
tthis.closest('tr').find('th').removeClass('ASCE');
tthis.closest('tr').find('th').removeClass('DESC');
tthis.addClass('ASCE');
}
else {
tthis.closest('tr').find('th').removeClass('ASCE');
tthis.closest('tr').find('th').removeClass('DESC');
tthis.addClass('DESC');
multiplicador = 1;
}
function reordenaruno() {
var re = new RegExp(",", 'g');
var table = $(tthis.closest('.ADScroller').find('.ADScroller-body > table ')[0]);
var tabletr = table.find('> tr:not(.trnopadding.ADtr),> tbody > tr:not(.trnopadding.ADtr),> thead > tr:not(.trnopadding.ADtr)');
tipostring = 0;
tiponumeric = 0;
tipodate = 0;
var mapped = tabletr.map(function (i, el) {
el = $(el);
var texto = el.find("> td");
var textod = null;
var texton = 0;
if (texto && texto.length > index) {
texto = $(texto[index]).text();
texto = texto.toLowerCase().trim();
if (texto.length > 0) {
var vnum = texto.replace("$", "").replace("%", "").replace("-", "").replace("(", "").replace(")", "").replace(re, "").trim();
if (vnum.length > 0) {
if ($.isNumeric(vnum)) {
texton = Number(vnum);
tiponumeric = 1;
} else {
var splited = texto.split("-")
if (splited.length == 3) {
var d = new Date(splited[2] + "-" + splited[1] + "-" + splited[0])
if (!(d.toString == "Invalid Date")) {
textod = d;
tipodate = 1;
}
} else {
var splited = texto.split("/")
if (splited.length == 3) {
var d = new Date(splited[2] + "/" + splited[1] + "/" + splited[0])
if (!(d.toString == "Invalid Date")) {
textod = d;
tipodate = 1;
}
} else {
tipostring = 1
}
}
}
} else {
texto = null;
}
} else {
texto = null;
}
} else {
texto = null;
}
return { index: i, value: texto, valued: textod, valuen: texton, obj: el };
});
if (tipostring == 1) {
mapped.sort(function (a, b) {
return (+(a.value > b.value) || +(a.value === b.value) - 1) * multiplicador;
});
//tthis.closest('tr').find('th').data('tipodato', 'string')
} else {
if (tipodate == 1) {
mapped.sort(function (a, b) {
return (+(a.valued > b.valued) || +(a.valued === b.valued) - 1) * multiplicador;
});
//tthis.closest('tr').find('th').data('tipodato', 'date')
} else {
mapped.sort(function (a, b) {
return (+(a.valuen > b.valuen) || +(a.valuen === b.valuen) - 1) * multiplicador;
});
//tthis.closest('tr').find('th').data('tipodato', 'numeric')
}
}
mapped.each(function (i, el) {
table.append(this.obj);
});
}
function reordenardos() {
var re = new RegExp(",", 'g');
var table = $(tthis.closest('.ADScroller').find('.ADScroller-body > table ')[0]);
var tabletr = table.find('> tr:not(.trnopadding.ADtr),> tbody > tr:not(.trnopadding.ADtr),> thead > tr:not(.trnopadding.ADtr)');
tipostring = 0;
tiponumeric = 0;
tipodate = 0;
var mapped = tabletr.map(function (i, el) {
el = $(el);
var tdtexto = el.find("> td");
var texto = null;
if (tdtexto && tdtexto.length > index) {
texto = $(tdtexto[index]).text();
texto = texto.toLowerCase().trim();
} else {
texto = null;
}
return { index: i, value: texto, obj: el };
});
mapped.sort(function (a, b) {
return (+(a.value > b.value) || +(a.value === b.value) - 1) * multiplicador;
});
mapped.each(function (i, el) {
table.append(this.obj);
});
}
function reordenartres() {
var re = new RegExp(",", 'g');
var table = $(tthis.closest('.ADScroller').find('.ADScroller-body > table ')[0]);
var tabletr = table.find('> tr:not(.trnopadding.ADtr),> tbody > tr:not(.trnopadding.ADtr),> thead > tr:not(.trnopadding.ADtr)');
tipostring = 0;
tiponumeric = 0;
tipodate = 0;
var mapped = tabletr.map(function (i, el) {
el = $(el);
var tdtexto = el.find("> td");
var texto = null;
var textod = null;
if (tdtexto && tdtexto.length > index) {
texto = $(tdtexto[index]).text();
texto = texto.toLowerCase().trim();
var splited = texto.split("-")
if (splited.length == 3) {
var d = new Date(splited[2] + "-" + splited[1] + "-" + splited[0])
if (!(d.toString == "Invalid Date")) {
textod = d;
}
} else {
var splited = texto.split("/")
if (splited.length == 3) {
var d = new Date(splited[2] + "/" + splited[1] + "/" + splited[0])
if (!(d.toString == "Invalid Date")) {
textod = d;
}
}
}
} else {
texto = null;
}
return { index: i, value: textod, obj: el };
});
mapped.sort(function (a, b) {
return (+(a.value > b.value) || +(a.value === b.value) - 1) * multiplicador;
});
mapped.each(function (i, el) {
table.append(this.obj);
});
}
function reordenarcuatro() {
var re = new RegExp(",", 'g');
var table = $(tthis.closest('.ADScroller').find('.ADScroller-body > table ')[0]);
var tabletr = table.find('> tr:not(.trnopadding.ADtr),> tbody > tr:not(.trnopadding.ADtr),> thead > tr:not(.trnopadding.ADtr)');
tipostring = 0;
tiponumeric = 0;
tipodate = 0;
var mapped = tabletr.map(function (i, el) {
el = $(el);
var tdtexto = el.find("> td");
var texto = null;
var texton = 0;
if (tdtexto && tdtexto.length > index) {
texto = $(tdtexto[index]).text();
texto = texto.toLowerCase().trim();
if (texto.length > 0) {
var vnum = texto.replace("$", "").replace("%", "").replace("-", "").replace("(", "").replace(")", "").replace(re, "").trim();
if (vnum.length > 0) {
if ($.isNumeric(vnum)) {
texton = Number(vnum);
}
}
}
} else {
texto = null;
}
return { index: i, value: texton, obj: el };
});
mapped.sort(function (a, b) {
return (+(a.value > b.value) || +(a.value === b.value) - 1) * multiplicador;
});
mapped.each(function (i, el) {
table.append(this.obj);
});
}
function reordenarcinco() {
var re = new RegExp(",", 'g');
var table = $(tthis.closest('.ADScroller').find('.ADScroller-body > table ')[0]);
var tabletr = table.find('> tr:not(.trnopadding.ADtr),> tbody > tr:not(.trnopadding.ADtr),> thead > tr:not(.trnopadding.ADtr)');
tipostring = 0;
tiponumeric = 0;
tipodate = 0;
var mapped = tabletr.map(function (i, el) {
el = $(el);
var tdtexto = el.find("> td");
var texto = null;
var texton = 0;
if (tdtexto && tdtexto.length > index) {
texton = Number($(tdtexto[index]).data('order'));
} else {
texto = null;
}
return { index: i, value: texton, obj: el };
});
//console.log(mapped)
mapped.sort(function (a, b) {
return (+(a.value > b.value) || +(a.value === b.value) - 1) * multiplicador;
});
mapped.each(function (i, el) {
table.append(this.obj);
});
}
switch (tipodato) {
case 'string':
reordenardos();
break;
case 'date':
reordenartres();
break;
case 'numeric':
reordenarcuatro();
break;
case 'dataorder':
reordenarcinco();
break;
default:
reordenaruno();
}
tthis.closest('tr').removeClass('tsorterblock');
Metronic.unblockUI();
}, 100);
}
});
}
var listaADScroller = [];
function saveposicionADScroller() {
$('.ADScroller-body>table').each(function () {
let _this = $(this);
let id = _this.attr("id");
let scrollleft = $(_this.parent()).scrollLeft();
let scrolltop = $(_this.parent()).scrollTop();
listaADScroller.push({ id: id, scrollleft: scrollleft, scrolltop: scrolltop })
});
}
function setposicionADScroller() {
setTimeout(
function () {
listaADScroller.forEach(function (_this) {
let id = _this.id;
let scrollleft = _this.scrollleft;
let scrolltop = _this.scrolltop;
$($('#' + id).parent()).scrollLeft(scrollleft);
$($('#' + id).parent().parent()).find('> .ADScroller-header').scrollLeft(scrollleft);
$($('#' + id).parent()).scrollTop(scrolltop);
});
}, 99);
}
function loaderinit() {
setTimeout(
function () {
Metronic.blockUI({ animate: true });
}, 10);
}
function loaderEnd() {
setTimeout(
function () {
Metronic.unblockUI();
}, 10);
}
/*
* Global error interface for full and asynchronous WebForms requests.
*
* Site.master may declare the modal using these IDs:
* - sigGlobalErrorModal
* - sigGlobalErrorCode
* - sigGlobalErrorDetail
*
* If the markup is not present, this code creates it under <body>.
* Therefore, it remains outside every UpdatePanel.
*/
window.SIGErrorUI = window.SIGErrorUI || (function () {
var modalSelector = '#sigGlobalErrorModal';
var codeSelector = '#sigGlobalErrorCode';
var codeContainerSelector = '#sigGlobalErrorCodeContainer';
var detailSelector = '#sigGlobalErrorDetail';
function asegurarModal() {
var modal = $(modalSelector);
if (modal.length) {
return modal;
}
var html = [
'<div id="sigGlobalErrorModal" class="modal fade" tabindex="-1" role="dialog" aria-hidden="true">',
' <div class="modal-dialog" role="document">',
' <div class="modal-content">',
' <div class="modal-header">',
' <button type="button" class="close" data-dismiss="modal" aria-label="Cerrar">',
' <span aria-hidden="true">&times;</span>',
' </button>',
' <h4 class="modal-title">',
' <i class="fa fa-exclamation-triangle"></i> Error',
' </h4>',
' </div>',
' <div class="modal-body">',
' <div id="sigGlobalErrorCodeContainer" style="display:none; margin-bottom:10px;">',
' <strong>Codigo:</strong> <span id="sigGlobalErrorCode"></span>',
' </div>',
' <div id="sigGlobalErrorDetail"></div>',
' </div>',
' <div class="modal-footer">',
' <button type="button" class="btn btn-danger" data-dismiss="modal">Cerrar</button>',
' </div>',
' </div>',
' </div>',
'</div>'
].join('');
$('body').append(html);
return $(modalSelector);
}
function mostrar(codigo, detalle) {
var modal = asegurarModal();
var codigoLimpio = $.trim(codigo || '');
var detalleLimpio = $.trim(detalle || '');
if (!detalleLimpio) {
detalleLimpio = 'Ocurrio un error inesperado. Intente nuevamente.';
}
$(codeSelector).text(codigoLimpio);
$(detailSelector).text(detalleLimpio);
$(codeContainerSelector).toggle(codigoLimpio.length > 0);
if ($.fn.modal) {
modal.modal({
backdrop: 'static',
keyboard: true,
show: true
});
} else {
modal.show();
}
}
function ocultar() {
var modal = $(modalSelector);
if (!modal.length) {
return;
}
$(codeSelector).text('');
$(detailSelector).text('');
$(codeContainerSelector).hide();
if ($.fn.modal && modal.hasClass('in')) {
modal.modal('hide');
} else {
modal.hide();
}
}
return {
mostrar: mostrar,
ocultar: ocultar
};
})();
function registrarEventosAjaxSIG(loadjquerysCallback) {
if (
!window.Sys ||
!Sys.WebForms ||
!Sys.WebForms.PageRequestManager
) {
return;
}
var prm = Sys.WebForms.PageRequestManager.getInstance();
if (!prm._sigEventosAjaxRegistrados) {
prm._sigEventosAjaxRegistrados = true;
prm.add_initializeRequest(function () {
error = false;
SIGErrorUI.ocultar();
objscollapse = $('.portlet-title .collapse').closest('.portlet[id]');
objsexpand = $('.portlet-title .expand').closest('.portlet[id]');
adscrollerposition = [];
$('.ADSContainer .AdsBody .ADSCroll table').each(function () {
var table = $(this);
var scrollContainer = table.parent();
adscrollerposition.push({
id: table.attr('id'),
scrollLeft: scrollContainer.scrollLeft(),
scrollTop: scrollContainer.scrollTop()
});
});
saveposicionADScroller();
loaderinit();
});
prm.add_endRequest(function (sender, args) {
finalizarLoaderSeguro();
var requestError = args.get_error();
if (requestError) {
args.set_errorHandled(true);
var informacion = obtenerInformacionErrorSIG(
args,
requestError
);
SIGErrorUI.mostrar(
informacion.codigo,
informacion.detalle
);
error = true;
return;
}
try {
portletshowhide();
error = false;
} catch (ex) {
console.error(ex);
error = true;
SIGErrorUI.mostrar(
'SIG-JS',
ex && ex.message
? ex.message
: 'No fue posible actualizar la interfaz.'
);
}
});
}
if (!window.SIG_APPLICATION_LOAD_REGISTERED) {
window.SIG_APPLICATION_LOAD_REGISTERED = true;
Sys.Application.add_load(function () {
finalizarLoaderSeguro();
try {
setswitch();
if (
typeof Metronic !== 'undefined' &&
Metronic &&
typeof Metronic.initAjax === 'function'
) {
Metronic.initAjax();
}
if (typeof loadjquerysCallback === 'function') {
loadjquerysCallback();
}
setposicionADScroller();
if (!error) {
SIGErrorUI.ocultar();
}
} catch (ex) {
console.error(ex);
error = true;
SIGErrorUI.mostrar(
'SIG-JS',
ex && ex.message
? ex.message
: 'No fue posible inicializar la interfaz.'
);
}
});
}
}
jQuery(document).ready(function () {
if (window.SIG_CUSTOM_READY_INITIALIZED === true) {
return;
}
window.SIG_CUSTOM_READY_INITIALIZED = true;
$("body").on("click", ".ajax__tab_outer .ajax__tab_inner .ajax__tab_tab", function () {
setTimeout(loadadscroll, 10);
});
//KeppMenuOpen
{
let varpath = window.location.pathname;
if (window.location.pathname != '') {
let textfinder = '.page-sidebar-menu a[href="' + varpath + '"]';
let objmenu = $($(textfinder)[0]);
objmenu.parents().filter("li").addClass('active open')
objmenu.parents().filter(".sub-menu").css("display", "")
}
}
$('body').on('click', '.tab-wizard > .ajax__tab_header > span,.tab-wizard2 > .ajax__tab_header > span', function (e) {
let padre = $(this).closest('.tab-wizard,.tab-wizard2 ');
let total = padre.find('> .ajax__tab_header > span').length;
let maximo = $(this).index() + 1;
padre.find('> .progress.tab-wizard > .progress-bar').css('width', '' + ((maximo / total) * 100) + '%');
});
$(window).on('shown.bs.modal', function () {
setTimeout(loadadscroll, 10);
});
loadsortadscroll();
MoveFixedDiv();
setswitch();
function ocultarbtnmaster() { if ($('#btnmaster_actionssidebar + ul').text().trim() == "") { $('#btnmaster_actionssidebar').css('display', 'none'); } else { $('#btnmaster_actionssidebar').css('display', 'block'); } }
function loadjquerys() {
$('.ADSckeditor[id]').each(function () {
let $Tthis = $(this);
$Tthis.val($Tthis.val().replace(/< /gi, '<'));
let id = $Tthis.attr('id');
$(this).removeClass("ADSckeditor");
$(this).addClass("ckeditorADS");
let ckedit = CKEDITOR.replace(id, { /*height: 260,*/autoUpdateElement: false });
ckedit.on('change', function () { $Tthis.val(ckedit.getData().replace(/</gi, '< ')); });
ckedit.on("instanceReady", function () { $Tthis.val($Tthis.val().replace(/</gi, '< ')); });
//CKEDITOR.instances[id].on('change', function () { CKEDITOR.instances[i].updateElement(); });
});
buscadorMenuCaudi();
AdsTabWizard();
ADSBegin();
loadwebservice();
ocultarbtnmaster();
movepanel();
loadADSortable();
loadadscroll();
CargaPickers();
DataTablePaginatorScroll();
DataTablePaginatorScroll2();
loadAdDropzone();
loadAdDropzoneLocal();
clonsbuttons();
ADScroller2();
//setTimeout(ADScroller2, 500);
$('body').removeClass('page-portlet-fullscreen');
$('.form-md-floating-label input').each(function () {
if ($(this).val().length > 0) {
$(this).toggleClass('edited', true);
} else {
$(this).toggleClass('edited', false);
}
});
$('input.MaskMoney').each(function () {
$(this).maskMoney({ thousands: ',', decimal: '.', allowZero: true, allowNegative: true, prefix: '', suffix: '' });
});
$('input[data-adstype="number"]').each(function () {
var decimales = 2;
if ($(this).data('adsdecimal')) {
decimales = parseInt($(this).data('adsdecimal'));
}
$(this).number(true, decimales);
$(this).data('adstype', 'number22');
});
//INICIA FUNCION TOOLTIP
$('[data-toggle="tooltip"]').tooltip();
$('table.ConBuscador').each(function () {
let $this = $(this);
let tickBarBmaster = 0;
let strtxtBuscador = $this.data('txtBuscador');
let input = $(strtxtBuscador);
if (strtxtBuscador && strtxtBuscador.length > 0) {
let showhideRows = function () {
usuariotext = input.val();
let strusuario = usuariotext.length > 0 ? ':contains("' + usuariotext + '")' : '';// td:nth-child(2)
$this.find('tr.items').attr('hide', '1');//oculto todos
$this.find('tr.items' + strusuario).attr('hide', '');//muestro los que tienen filtro
};
let txtOnchange = function () {
let obj = input;
let text = '';
tickBarBmaster = tickBarBmaster + 1;
tickBarnew = tickBarBmaster;
setTimeout(function () {
if (tickBarnew == tickBarBmaster) {
if ((text = obj.val().trim()) != usuariotext) {
usuariotext = text;
showhideRows();
}
}
}, 500);
};
if (!input.hasClass('ConEvento')) {
input.bind({
copy: txtOnchange
, paste: txtOnchange
, cut: txtOnchange
, keydown: txtOnchange
, keyup: txtOnchange
});
input.addClass('ConEvento');
}
showhideRows();
}
});
ADSReady();
}
if (("Notification" in window)) {
if (Notification.permission !== 'denied') {
Notification.requestPermission(function (permission) {
// If the user accepts, let's create a notification
//if (permission === "granted") { }
});
}
}
if (typeof Metronic !== 'undefined' && Metronic.init) {
Metronic.init(); // init metronic core components
}
if (typeof Layout !== 'undefined' && Layout.init) {
Layout.init(); // init current layout
}
if (typeof QuickSidebar !== 'undefined' && QuickSidebar.init) {
QuickSidebar.init();
}
if (typeof Demo !== 'undefined' && Demo.init) {
Demo.init();
}
loadjquerys();
/* modal */
$('#ajax').on('hidden.bs.modal', function () {
$('#ajaxidmodal').addClass("hidden");
$('#ajaxmodalloading').removeClass("hidden");
});
$('#ajaxidmodal').addClass("hidden");
$('#ajaxmodalloading').removeClass("hidden");
/*modal*/
registrarEventosAjaxSIG(loadjquerys);
ADSSignalR();
});
function finalizarLoaderSeguro() {
try {
loaderEnd();
} catch (ex) {
console.error('No fue posible cerrar el loader.', ex);
}
}
function obtenerInformacionErrorSIG(
e,
requestError
) {
var textoError = '';
var contenidoRespuesta = '';
var codigoHeader = '';
if (
requestError &&
requestError.message
) {
textoError = requestError.message;
}
try {
var response = e.get_response();
if (response) {
codigoHeader =
response.getResponseHeader(
'X-SIG-Error-Code'
) || '';
contenidoRespuesta =
response.get_responseData() || '';
}
} catch (ex) {
console.error(
'No fue posible leer la respuesta del servidor.',
ex
);
}
var textoCompleto =
textoError + ' ' + contenidoRespuesta;
var coincidencia = textoCompleto.match(
/SIG_ERROR\|(SIG-\d{8}-[A-F0-9]{6})(?:\|([A-Za-z0-9+/=]+))?/i
);
if (coincidencia) {
return {
codigo: coincidencia[1].toUpperCase(),
detalle:
decodificarDetalleSIG(
coincidencia[2] || ''
) ||
limpiarMensajeErrorSIG(textoError)
};
}
return {
codigo: codigoHeader
? codigoHeader.toUpperCase()
: 'SIG-AJAX',
detalle:
limpiarMensajeErrorSIG(textoError) ||
'Ocurrio un error durante la solicitud.'
};
}
function limpiarMensajeErrorSIG(mensaje) {
var texto = $.trim(mensaje || '');
if (!texto) {
return '';
}
texto = texto.replace(
/^Sys\.WebForms\.PageRequestManager(?:Server|Parser|Timeout)ErrorException:\s*/i,
''
);
texto = texto.replace(
/SIG_ERROR\|SIG-\d{8}-[A-F0-9]{6}(?:\|[A-Za-z0-9+/=]+)?/ig,
''
);
texto = $.trim(texto);
if (
/<!doctype html|<html|server error in/i.test(texto)
) {
return 'Ocurrio un error en el servidor. Intente nuevamente.';
}
if (texto.length > 1000) {
texto = texto.substring(0, 1000) + '...';
}
return texto;
}
function decodificarDetalleSIG(valorBase64) {
if (!valorBase64) {
return '';
}
try {
var binario = window.atob(valorBase64);
if (window.TextDecoder) {
var bytes = new Uint8Array(binario.length);
for (var i = 0; i < binario.length; i++) {
bytes[i] = binario.charCodeAt(i);
}
return new TextDecoder('utf-8').decode(bytes);
}
var codificado = '';
for (var indice = 0; indice < binario.length; indice++) {
codificado += '%' + (
'00' + binario.charCodeAt(indice).toString(16)
).slice(-2);
}
return decodeURIComponent(codificado);
} catch (ex) {
console.error(
'No fue posible decodificar el detalle tecnico.',
ex
);
return '';
}
}