/*
* Document : app.js
* Author : pixelcave
* Description: Custom scripts and plugin initializations (available to all pages)
*
* Feel free to remove the plugin initilizations from uiInit() if you would like to
* use them only in specific pages. Also, if you remove a js plugin you won't use, make
* sure to remove its initialization from uiInit().
*/
var App = function() {
/* Cache variables of some often used jquery objects */
var page = $('#page-container');
var header = $('header');
/* Sidebar */
var sToggleSm = $('#sidebar-toggle-sm');
var sToggleLg = $('#sidebar-toggle-lg');
var sScroll = $('.sidebar-scroll');
/* Initialization UI Code */
var uiInit = function() {
// Initialize Sidebar Functionality
handleSidebar('init');
// Sidebar Navigation functionality
handleNav();
// Scroll to top functionality
scrollToTop();
// Template Options, change features
templateOptions();
// Add the correct copyright year at the footer
var yearCopy = $('#year-copy'), d = new Date();
if (d.getFullYear() === 2014) { yearCopy.html('2014'); } else { yearCopy.html('2014-' + d.getFullYear().toString().substr(2,2)); }
// Set min-height to #page-content, so that footer is visible at the bottom if there is not enough content
$('#page-content').css('min-height', $(window).height() -
(header.outerHeight() + $('footer').outerHeight()) + 'px');
/*$(window).resize(function() {
$('#page-content').css('min-height', $(window).height() -
(header.outerHeight() + $('footer').outerHeight()) + 'px');
});*/
// Initialize tabs
$('[data-toggle="tabs"] a, .enable-tabs a').click(function(e){ e.preventDefault(); $(this).tab('show'); });
// Initialize Tooltips
if (typeof $ !== 'undefined' && $.fn.tooltip) {
var selectors = $('[data-toggle="tooltip"], .enable-tooltip');
if (selectors.length) {
selectors.tooltip({container: 'body', html: true, animation: false});
}
}
// Initialize Popovers
if (typeof $ !== 'undefined' && $.fn.popover) {
var selectors = $('[data-toggle="popover"], .enable-popover');
if (selectors.length) {
selectors.popover({container: 'body', animation: true});
}
}
$.extend(true, $.magnificPopup.defaults, {
tClose: 'Cerrar (Esc)',
tLoading: 'Cargando...',
gallery: {
tPrev: 'Anterior',
tNext: 'Siguiente',
tCounter: '%curr% de %total%'
},
image: {
tError: 'La imagen no se puede mostrar.'
},
ajax: {
tError: 'El contenido no se pudo mostrar.'
}
});
// Initialize single image lightbox
$('[data-toggle="lightbox-image"]').magnificPopup({type: 'image', image: {titleSrc: 'title'}});
// Initialize image gallery lightbox
$('[data-toggle="lightbox-gallery"]').magnificPopup({
delegate: 'a.gallery-link',
type: 'image',
gallery: {
enabled: true,
navigateByImgClick: true,
arrowMarkup: ''
},
image: {
titleSrc: function(item) {
var caption = item.el.attr('title');
var urlImage = item.el.attr('href');
return caption + ' Ver a pantalla completa';
}
}
});
// Initialize Editor
$('.textarea-editor').wysihtml5();
// Initialize Chosen
$('.select-chosen').chosen({width: "100%"});
// Initiaze Slider for Bootstrap
$('.input-slider').slider();
// Initialize Tags Input
$('.input-tags').tagsInput({ width: 'auto', height: 'auto'});
// Initialize Datepicker
$('.input-datepicker, .input-daterange').datepicker({weekStart: 1});
$('.input-datepicker-close').datepicker({weekStart: 1}).on('changeDate', function(e){ $(this).datepicker('hide'); });
// Initialize Timepicker
$('.input-timepicker').timepicker({minuteStep: 1,showSeconds: true,showMeridian: true});
$('.input-timepicker24').timepicker({minuteStep: 1,showSeconds: true,showMeridian: false});
// Easy Pie Chart
$('.pie-chart').easyPieChart({
barColor: $(this).data('bar-color') ? $(this).data('bar-color') : '#777777',
trackColor: $(this).data('track-color') ? $(this).data('track-color') : '#eeeeee',
lineWidth: $(this).data('line-width') ? $(this).data('line-width') : 3,
size: $(this).data('size') ? $(this).data('size') : '80',
animate: 800,
scaleColor: false
});
// Initialize Placeholder
$('input, textarea').placeholder();
};
/* Sidebar Navigation functionality */
var handleNav = function() {
// Animation Speed, change the values for different results
var upSpeed = 250;
var downSpeed = 250;
// Get all vital links
var allTopLinks = $('.sidebar-nav a');
var menuLinks = $('.sidebar-nav-menu');
var submenuLinks = $('.sidebar-nav-submenu');
// Primary Accordion functionality
menuLinks.click(function(){
var link = $(this);
if (link.parent().hasClass('active') !== true) {
if (link.hasClass('open')) {
link.removeClass('open').next().slideUp(upSpeed);
}
else {
$('.sidebar-nav-menu.open').removeClass('open').next().slideUp(upSpeed);
link.addClass('open').next().slideDown(downSpeed);
}
}
return false;
});
// Submenu Accordion functionality
submenuLinks.click(function(){
var link = $(this);
if (link.parent().hasClass('active') !== true) {
if (link.hasClass('open')) {
link.removeClass('open').next().slideUp(upSpeed);
}
else {
link.closest('ul').find('.sidebar-nav-submenu.open').removeClass('open').next().slideUp(upSpeed);
link.addClass('open').next().slideDown(downSpeed);
}
}
return false;
});
};
// Controlamos la altura de page-content por si el sidebar de vecinos se extiende demasiado
function ajustarAlturaPageContent() {
const isOpen = document.querySelector('.sidebar-nav-menu.open');
const alturaSidebar = document.querySelector('#sidebar')?.offsetHeight;
const pageContent = document.querySelector('#page-content');
if (!alturaSidebar || !pageContent) return;
isOpen ? pageContent.style.height = alturaSidebar + 'px' : pageContent.style.height = 'initial';
}
// Creamos un observer para monitorear cambios en el sidebar
const observer = new MutationObserver(mutations => {
ajustarAlturaPageContent(); // Salta cuando el sidebar cambia
});
// Opciones del observer
const config = { attributes: true, childList: true, subtree: true };
// Seleccionamos el elemento a observar (el sidebar)
const target = document.querySelector('#sidebar');
// Iniciamos la observación
if (target) observer.observe(target, config);
/* Sidebar Functionality */
var handleSidebar = function(mode) {
if (mode === 'init') {
// Init Scrolling (if we have a fixed header)
if (header.hasClass('navbar-fixed-top') || header.hasClass('navbar-fixed-bottom')) {
handleSidebar('init-scroll');
}
// Init Sidebar
sToggleSm.click(function(){ handleSidebar('toggle-sm'); });
sToggleLg.click(function(){ handleSidebar('toggle-lg'); });
}
else if (mode === 'toggle-lg') { // Toggle Sidebar in large screens (> 991px)
page.toggleClass('sidebar-full');
}
else if (mode === 'toggle-sm') { // Toggle Sidebar in small screens (< 992px)
page.toggleClass('sidebar-open');
}
else if (mode === 'open-sm') { // Open Sidebar in small screens (< 992px)
page.addClass('sidebar-open');
}
else if (mode === 'close-sm') { // Close Sidebar in small screens (< 992px)
page.removeClass('sidebar-open');
}
else if (mode === 'open-lg') { // Open Sidebar in large screens (> 991px)
page.addClass('sidebar-full');
}
else if (mode === 'close-lg') { // Close Sidebar in large screens (> 991px)
page.removeClass('sidebar-full');
}
else if (mode == 'init-scroll') { // Init Sidebar Scrolling
if (sScroll.length && (!sScroll.parent('.slimScrollDiv').length)) {
// Initialize Slimscroll plugin
sScroll.slimScroll({ height: $(window).height(), color: '#fff', size: '3px', touchScrollStep: 100 });
// Resize sidebar scrolling height on window resize or orientation change
$(window).resize(sidebarScrollResize);
$(window).bind('orientationchange', sidebarScrollResizeOrient);
}
} else if (mode == 'destroy-scroll') { // Destroy Sidebar Scrolling
if (sScroll.parent('.slimScrollDiv').length) {
// Remove Slimscroll by replacing .slimScrollDiv (added by Slimscroll plugin) with sScroll
sScroll.parent().replaceWith(function() {return $( this ).contents();});
// Save the new .sidebar-scroll div to our sScroll variable
sScroll = $('.sidebar-scroll');
// Remove inline styles (added by Slimscroll plugin) from our new sScroll
sScroll.removeAttr('style');
// Disable functions running on window scroll and orientation change
$(window).off('resize', sidebarScrollResize);
$(window).unbind('orientationchange', sidebarScrollResizeOrient);
}
}
};
// Sidebar Scrolling Resize Height on window resize and orientation change
var sidebarScrollResize = function() { sScroll.css('height', $(window).height()); };
var sidebarScrollResizeOrient = function() { setTimeout(sScroll.css('height', $(window).height()), 500); };
/* Scroll to top functionality */
var scrollToTop = function() {
// Get link
var link = $('#to-top');
$(window).scroll(function() {
// If the user scrolled a bit (150 pixels) show the link
if ($(this).scrollTop() > 150) {
link.fadeIn(100);
} else {
link.fadeOut(100);
}
});
// On click get to top
link.click(function() {
$('html, body').animate({scrollTop: 0}, 400);
return false;
});
};
/* Template Options, change features functionality */
var templateOptions = function() {
/*
* Color Themes
*/
var colorList = $('.sidebar-themes');
var themeLink = $('#theme-link');
var theme;
if (themeLink.length) {
theme = themeLink.attr('href');
$('li', colorList).removeClass('active');
$('a[data-theme="' + theme + '"]', colorList).parent('li').addClass('active');
}
$('a', colorList).click(function(e){
// Get theme name
theme = $(this).data('theme');
$('li', colorList).removeClass('active');
$(this).parent('li').addClass('active');
if (theme === 'default') {
if (themeLink.length) {
themeLink.remove();
themeLink = $('#theme-link');
}
} else {
if (themeLink.length) {
themeLink.attr('href', theme);
} else {
$('link[href="css/themes.css"]').before('');
themeLink = $('#theme-link');
}
}
});
// Prevent template options dropdown from closing on clicking options
$('.dropdown-options a').click(function(e){ e.stopPropagation(); });
/* Page Style */
var optMainStyle = $('#options-main-style');
var optMainStyleAlt = $('#options-main-style-alt');
if (page.hasClass('style-alt')) {
optMainStyleAlt.addClass('active');
} else {
optMainStyle.addClass('active');
}
optMainStyle.click(function() {
setCookie('config_mainStyle', 'style', 365);
page.removeClass('style-alt');
$(this).addClass('active');
optMainStyleAlt.removeClass('active');
});
optMainStyleAlt.click(function() {
setCookie('config_mainStyle', 'style-alt', 365);
page.addClass('style-alt');
$(this).addClass('active');
optMainStyle.removeClass('active');
});
if (getCookie('config_mainStyle') == 'style-alt') {
optMainStyleAlt.click();
}
/* Header options */
var optHeaderDefault = $('#options-header-default');
var optHeaderInverse = $('#options-header-inverse');
var optHeaderTop = $('#options-header-top');
var optHeaderBottom = $('#options-header-bottom');
if (header.hasClass('navbar-default')) {
optHeaderDefault.addClass('active');
} else {
optHeaderInverse.addClass('active');
}
if (header.hasClass('navbar-fixed-top')) {
optHeaderTop.addClass('active');
} else if (header.hasClass('navbar-fixed-bottom')) {
optHeaderBottom.addClass('active');
}
optHeaderDefault.click(function() {
setCookie('config_header', 'clear', 365);
header.removeClass('navbar-inverse').addClass('navbar-default');
$(this).addClass('active');
optHeaderInverse.removeClass('active');
});
optHeaderInverse.click(function() {
setCookie('config_header', 'dark', 365);
header.removeClass('navbar-default').addClass('navbar-inverse');
$(this).addClass('active');
optHeaderDefault.removeClass('active');
});
if (getCookie('config_header') == 'dark') {
optHeaderInverse.click();
}
optHeaderTop.click(function() {
setCookie('config_posHeader', 'top', 365);
page.removeClass('header-fixed-bottom').addClass('header-fixed-top');
header.removeClass('navbar-fixed-bottom').addClass('navbar-fixed-top');
$(this).addClass('active');
optHeaderBottom.removeClass('active');
handleSidebar('init-scroll');
});
optHeaderBottom.click(function() {
setCookie('config_posHeader', 'bottom', 365);
page.removeClass('header-fixed-top').addClass('header-fixed-bottom');
header.removeClass('navbar-fixed-top').addClass('navbar-fixed-bottom');
$(this).addClass('active');
optHeaderTop.removeClass('active');
handleSidebar('init-scroll');
});
if (getCookie('config_posHeader') == 'bottom') {
optHeaderBottom.click();
}
};
/* Datatables Basic Bootstrap integration (pagination integration included under the Datatables plugin in plugins.js) */
var dtIntegration = function() {
$.extend(true, $.fn.dataTable.defaults, {
"sDom": "<'row'<'col-sm-6 col-xs-5'l><'col-sm-6 col-xs-7'f>r>t<'row'<'col-sm-5 hidden-xs'i><'col-sm-7 col-xs-12 clearfix'p>>",
"sPaginationType": "bootstrap",
"oLanguage": {
"sLengthMenu": "_MENU_",
"sSearch": "
_INPUT_
",
"sInfo": '_START_-_END_ de _TOTAL_ registros',
"sInfoFiltered": '(filtrado de _MAX_ registros)',
"sInfoEmpty": 'Mostrando 0 de 0',
"sZeroRecords": 'No se han encontrado registros',
"sEmptyTable": 'No se han encontrado registros',
"oPaginate": {
"sPrevious": "",
"sNext": ""
}
}
});
};
return {
init: function() {
uiInit(); // Initialize UI Code
},
sidebar: function(mode) {
handleSidebar(mode); // Handle Sidebar Functionality
},
datatables: function() {
dtIntegration(); // Datatables Bootstrap integration
}
};
}();
$(function(){ App.init(); chkPass(); setTimeout('verifSession()', 2000); });
var isMobile = {
Android: function() {
return navigator.userAgent.match(/Android/i);
},
BlackBerry: function() {
return navigator.userAgent.match(/BlackBerry/i);
},
iOS: function() {
return navigator.userAgent.match(/iPhone|iPad|iPod/i);
},
Opera: function() {
return navigator.userAgent.match(/Opera Mini/i);
},
Windows: function() {
return navigator.userAgent.match(/IEMobile/i);
}
};
function setTheme(theme) {
if (theme == 'default') {
delCookie('color_theme');
document.getElementById('css_theme').href='';
}
else {
setCookie('color_theme', theme, 365);
document.getElementById('css_theme').href='css/themes/' + theme + '.css';
}
}
function changeCmd(cmd) {
var form = document.getElementById('listaCmd');
form.codcmd.value = cmd;
form.submit();
}
function printMessage() {
width = 800;
height = 600;
left = parseInt((window.screen.width - width) / 2);
window.open('', 'vPrint', 'menubar=no, directories=no, toolbar=no, resizable=1, scrollbars=yes, width=' + width + ', height=' + height + ', left=' + left + ', top=' + parseInt((window.screen.height - height) / 2));
document.getElementById('frmPrint').submit();
return false;
}
function introField(e, funcion) {
var keynum;
if (window.event) { // IE
keynum = e.keyCode;
}
else if (e.which) { // Netscape/Firefox/Opera
keynum = e.which;
}
if (keynum == 13 && !e.shiftKey) {
eval(funcion);
return false;
}
else
return true;
}
function onlyCheck(e, objeto, nextObject) {
// Controla únicamente que si pulsamos Intro se vaya al objeto 'nextObject'.
var keynum;
if (window.event) { // IE
keynum = e.keyCode;
}
else if (e.which) { // Netscape/Firefox/Opera
keynum = e.which;
}
if (keynum == 13 && nextObject != null) {
selectText(nextObject.id);
return false;
}
return true;
}
function onlyAlfa(e, objeto, nextObject) {
// Controla que el texto introducido en todo momento sea unicamente numeros enteros, incluso del keypad o letras a-z y A-Z.
// Si pulsamos Intro, pondremos el foco en 'nextObject'.
var keynum;
if (window.event) { // IE
keynum = e.keyCode;
}
else if (e.which) { // Netscape/Firefox/Opera
keynum = e.which;
}
if (keynum == 13) {
if (nextObject.type == 'text')
selectText(nextObject.id);
else if (typeof nextObject == 'string')
eval(nextObject);
else
setTimeout("document.getElementById('" + nextObject.id + "').focus()", 50);
return false;
}
var mays = (keynum == 16);
var homend = (keynum >= 35 && keynum <= 36);
var flechas = (keynum >= 37 && keynum <= 40);
var numeric = (keynum >= 48 && keynum <= 57 && !e.shiftKey);
var alfa = (keynum >= 65 && keynum <= 90);
var keypad = (keynum >= 96 && keynum <= 105);
var backsp = (keynum == 8);
var tab = (keynum == 9);
var del = (keynum == 46);
return (numeric || keypad || alfa || flechas || backsp || tab || del || mays || homend);
}
function selectText(idTexto) {
// Selecciona todo el texto de un cuadro de texto
// Si es un SELECT, pon el foco en él
var tb = document.getElementById(idTexto);
if (document.getElementById(idTexto).type == 'text')
tb.select();
document.getElementById(idTexto).focus();
}
function zeroleft(objeto, digits) {
while (objeto.value.length < digits)
objeto.value = '0' + objeto.value + '';
}
function urlencode(str) {
str = (str + '').toString();
str = encodeURIComponent(str);
str = str.replace(/!/g, '%21');
str = str.replace(/'/g, '%27');
str = str.replace(/\(/g, '%28');
str = str.replace(/\)/g, '%29');
str = str.replace(/\*/g, '%2A');
return str;
}
var idFila = 0;
function addUrl(url) {
var padre, x, elems=0, elem, elem2, campo, campo2;
idFila++;
padre = document.getElementById('attachments');
for (x=0,y=0;x < document.getElementsByTagName('div').length;x++) {
elem = document.getElementsByTagName('div')[x];
if (elem.id != null && typeof elem.id != 'undefined') {
if (elem.id.substr(0, 6) == "divUrl") {
if (y == 0) {
ind = parseInt(elem.id.substr(6));
campo = document.getElementById('URL' + ind);
padre2 = campo.parentNode;
if (padre2.childNodes.length == 1) {
campo.style.maxWidth = '94%';
campo.style.marginRight = '10px';
campo.style.display = 'inline-block';
campo = document.createElement('a');
campo.setAttribute('href', '#');
campo.onclick = function () {
return delUrl(parseInt(this.parentNode.parentNode.id.substr(6)));
}
campo2 = document.createElement('i');
campo2.className = 'fa fa-times fa-2x';
campo2.style.display = 'inline-block';
campo.appendChild(campo2);
padre2.appendChild(campo);
}
}
y++;
elems++;
}
}
}
elem = document.createElement('div');
elem.setAttribute('id', 'divUrl' + idFila);
elem.className = 'form-group';
campo = document.createElement('label');
campo.className = 'col-md-1 control-label';
campo.htmlFor = 'telefono';
campo.innerHTML = 'URL';
elem.appendChild(campo);
elem2 = document.createElement('div');
elem2.className = 'col-md-11';
campo = document.createElement('input');
campo.setAttribute('type', 'text');
campo.setAttribute('name', 'URL' + idFila);
campo.setAttribute('id', 'URL' + idFila);
campo.setAttribute('value', url);
campo.className = 'form-control';
if (elems > 0) {
campo.style.maxWidth = '94%';
campo.style.marginRight = '10px';
campo.style.display = 'inline-block';
}
campo.onkeydown = function (e) {
var keynum;
if (window.event) { // IE
keynum = e.keyCode;
}
else if (e.which) { // Netscape/Firefox/Opera
keynum = e.which;
}
var mays = (keynum == 16);
var homend = (keynum >= 35 && keynum <= 36);
var flechas = (keynum >= 37 && keynum <= 40);
var backsp = (keynum == 8);
var tab = (keynum == 9);
var del = (keynum == 46);
if (!mays && !homend && !flechas && !backsp && !tab && !del &&
parseInt(this.id.substr(3)) == idFila)
addUrl('');
}
campo.onchange = function () {
verifURL(this);
}
elem2.appendChild(campo);
if (elems > 0) {
campo = document.createElement('a');
campo.setAttribute('href', '#');
campo.onclick = function () {
return delUrl(parseInt(this.parentNode.parentNode.id.substr(6)));
}
campo2 = document.createElement('i');
campo2.className = 'fa fa-times fa-2x';
campo2.style.display = 'inline-block';
campo.appendChild(campo2);
elem2.appendChild(campo);
}
elem.appendChild(elem2);
padre.appendChild(elem);
}
function delUrl(fila) {
var padre, elem, x, ind;
padre = document.getElementById('attachments');
elem = document.getElementById('divUrl' + fila);
padre.removeChild(elem);
idFila = 0;
// Renumerar los índices
for (x=0;x < document.getElementsByTagName('div').length;x++) {
elem = document.getElementsByTagName('div')[x];
if (elem.id != null && typeof elem.id != 'undefined') {
if (elem.id.substr(0, 6) == "divUrl") {
ind = parseInt(elem.id.substr(6));
idFila++;
elem.setAttribute('id', 'divUrl' + idFila);
document.getElementById('URL' + ind).setAttribute('name', 'URL' + idFila);
document.getElementById('URL' + ind).setAttribute('id', 'URL' + idFila);
}
}
}
// Si ya solo queda un elemento, quitarle la imagen de borrado
if (idFila == 1) {
campo = document.getElementById('URL' + idFila);
campo.style.maxWidth = '100%';
campo.style.marginRight = '0px';
campo.style.display = 'block';
padre2 = campo.parentNode;
padre2.removeChild(padre2.childNodes[1]);
}
}
function sendCertRequest() {
var x, elem, form = document.forms['certification_request'];
dataPost = {};
for (x=0;x < form.elements.length;x++) {
elem = form.elements[x];
if (elem.type == 'checkbox' || elem.type == 'radio') {
if (elem.checked == true)
dataPost[elem.name] = elem.value;
}
else if (elem.type == 'text' || elem.type == 'hidden' || elem.type == 'password' || elem.type == 'textarea')
dataPost[elem.name] = elem.value;
}
$.ajax({
type: "POST",
async: true,
url: "ajax/sendCertificationRequest.php",
data: dataPost
}).done(
function(msg) {
if (msg != '')
alert(msg);
else {
alert('Su solicitud ha sido enviada correctamente.');
document.forms['certification_request'].reset();
$('#modal-cert-request').modal('hide');
}
}
);
}
function closeCertRequest() {
document.forms['certification_request'].reset();
$('#modal-cert-request').modal('hide');
}
function sendDebitRequest() {
var x, elem, form = document.forms['debit_request'];
dataPost = {};
for (x=0;x < form.elements.length;x++) {
elem = form.elements[x];
if (elem.type == 'checkbox' || elem.type == 'radio') {
if (elem.checked == true)
dataPost[elem.name] = elem.value;
}
else if (elem.type == 'text' || elem.type == 'hidden' || elem.type == 'password' || elem.type == 'textarea')
dataPost[elem.name] = elem.value;
}
$.ajax({
type: "POST",
async: true,
url: "ajax/sendDebitRequest.php",
data: dataPost
}).done(
function(msg) {
var x, y, iban, cuenta;
if (msg != '')
alert(msg);
else {
alert('Su forma de cobro de recibos ha sido actualizada correctamente.');
// Actualizar cuenta en el formulario
if (document.getElementById('cuenta').checked == true) {
if (document.getElementById('IBAN') != null && typeof document.getElementById('IBAN') != 'undefined')
iban = document.getElementById('IBAN').value + ' ';
else
iban = '';
cuenta = '';
for (x=1;;x++) {
if (document.getElementById('CuentaBanco_G' + x) != null && typeof document.getElementById('CuentaBanco_G' + x) != 'undefined') {
if (x > 1)
cuenta += ' ';
/*if (x == 2 || x == 3 || x == 5) {
for (y=0;y < document.getElementById('CuentaBanco_G' + x).value.length;y++) {
if (y > 1)
cuenta += '*';
else
cuenta += document.getElementById('CuentaBanco_G' + x).value.substr(y, 1);
}
} else {
cuenta += document.getElementById('CuentaBanco_G' + x).value;
}*/
// Mostramos la cuenta sin asteriscos
cuenta += document.getElementById('CuentaBanco_G' + x).value;
}
else
break;
}
document.getElementById('formaCobro').innerHTML = iban + cuenta;
}
else if (document.getElementById('porteria').checked == true)
document.getElementById('formaCobro').innerHTML = 'En portería';
else if (document.getElementById('despacho').checked == true)
document.getElementById('formaCobro').innerHTML = 'En el despacho';
else
document.getElementById('formaCobro').innerHTML = 'Ingreso/Transferencia';
document.forms['debit_request'].reset();
$('#modal-debit-request').modal('hide');
}
}
);
}
function closeDebitRequest() {
document.forms['debit_request'].reset();
$('#modal-debit-request').modal('hide');
}
function verifURL(obj) {
// Verifica que la URL corresponde a un fichero de vídeo o a un documento localizable en la web
$.ajax({
type: "POST",
async: true,
url: "ajax/verifURL.php",
data: {
url: obj.value
}
}).done(
function(msg) {
if (msg == "KO") {
alert('La URL introducida no es válida. Debe indicar la URL del video o archivo.');
obj.value = '';
setTimeout("document.getElementById('" + obj.id + "').focus()", 5);
}
else if (msg != 'OK')
alert(msg);
}
);
}
function saveChanges() {
var campo, x, elem, ind;
campo = document.getElementById('formMessage').attachs;
campo.value = '';
for (x=0;x < document.getElementsByTagName('div').length;x++) {
elem = document.getElementsByTagName('div')[x];
if (elem.id != null && typeof elem.id != 'undefined') {
if (elem.id.substr(0, 6) == "divUrl") {
ind = parseInt(elem.id.substr(6));
if (document.getElementById('URL' + ind).value != "") {
if (campo.value != "")
campo.value += ";";
campo.value += document.getElementById('URL' + ind).value + "";
}
}
}
}
for (x = (document.getElementsByTagName('div').length - 1);x >= 0;x--) {
elem = document.getElementsByTagName('div')[x];
if (elem.id != null && typeof elem.id != 'undefined') {
if (elem.id.substr(0, 6) == "divUrl") {
ind = parseInt(elem.id.substr(6));
if (document.getElementById('URL' + ind).value == "")
delUrl(ind);
}
}
}
addUrl('');
$('#modal-attachments').modal('hide');
}
function dropChanges() {
var campo, x, elem, ind;
for (x = (document.getElementsByTagName('div').length - 1);x >= 0;x--) {
elem = document.getElementsByTagName('div')[x];
if (elem.id != null && typeof elem.id != 'undefined') {
if (elem.id.substr(0, 6) == "divUrl") {
ind = parseInt(elem.id.substr(6));
delUrl(ind);
}
}
}
campo = document.getElementById('formMessage').attachs;
if (campo.value != "") {
if (campo.value.indexOf(';') > -1)
urls = campo.value.split(';');
else
urls = Array(campo.value);
}
else
urls = Array();
for (x=0;x < urls.length;x++)
addUrl(urls[x]);
addUrl('');
$('#modal-attachments').modal('hide');
}
function sendPersonalData() {
var x, elem, seguir, dataPost, fuerza, patron, form = document.forms['personal_information'];
dataPost = {};
seguir = false;
patron = /^([2-9a-zA-Z~!@#$%^&*\(\)_+-=\\|\[\]{};:,\.\/<>\?]){6,}$/;
form.email.value = form.email.value.trim();
if (form.direccion.value.trim() == '')
alert('ERROR. Debe indicar su dirección.');
else if (form.cp.value.trim() == '' || form.cp.value.trim().length < 5)
alert('ERROR. Debe indicar su código postal.');
else if (form.poblacion.value.trim() == '')
alert('ERROR. Debe indicar su población.');
else if (form.provincia.value.trim() == '')
alert('ERROR. Debe indicar la provincia.');
else
seguir = true;
if (seguir) {
for (x=0;x < form.elements.length;x++) {
elem = form.elements[x];
if (elem.type == 'checkbox' || elem.type == 'radio') {
if (elem.checked == true)
dataPost[elem.name] = elem.value;
}
else if (elem.type == 'text' || elem.type == 'hidden' || elem.type == 'password' || elem.type == 'textarea')
dataPost[elem.name] = elem.value.trim();
}
$.ajax({
type: "POST",
async: true,
url: "ajax/savePersonalData.php",
data: dataPost
}).done(
function(msg) {
if (msg != '') {
alert(msg);
document.forms['personal_information'].reset();
}
else {
alert('Datos personales guardados correctamente');
updateNewChangesModalUserSettings();
$('#modal-user-settings').modal('hide');
}
}
);
}
}
function updateNewChangesModalUserSettings() {
const emailInput = document.querySelector("input[name='email']");
const emailDefaultInput = document.querySelector("input[name='email_default']");
const direccionInput = document.querySelector("input[name='direccion']");
const direccionDefaultInput = document.querySelector("input[name='direccion_default']");
const telefonoInput = document.querySelector("input[name='telefono']");
const telefonoDefaultInput = document.querySelector("input[name='telefono_default']");
if (emailInput && emailDefaultInput) {
emailDefaultInput.value = emailInput.value;
}
if (direccionInput && direccionDefaultInput) {
direccionDefaultInput.value = direccionInput.value;
}
if (telefonoInput && telefonoDefaultInput) {
telefonoDefaultInput.value = telefonoInput.value;
}
}
function discardPersonalData() {
document.forms['personal_information'].reset();
chkPass();
$('#modal-user-settings').modal('hide');
//$('#modal-user-account').modal('hide');
}
function sendLoginData(usuario, data, passwordParam = "") {
var dataPost, patron;
let actual_link = "https://oficinavirtual.ryeadministradores.es";
dataPost = {};
patron = /^([2-9a-zA-Z~!@#$%^&*\(\)_+-=\\|\[\]{};:,\.\/<>\?]){6,}$/;
usuario = usuario.trim();
if (usuario == '' || usuario.length < 6 || !patron.test(usuario)) {
alert('ERROR. Debe indicar un nombre de usuario de al menos 6 caracteres.');
}
else {
dataPost['usuario'] = usuario;
dataPost['data'] = data;
dataPost['password'] = passwordParam;
$.ajax({
type: "POST",
async: true,
url: "ajax/saveLoginData.php",
data: dataPost
}).done(
function(msg) {
console.log(msg);
if (msg != '') {
if (msg == "OK" && passwordParam != "") {
alert("Contraseña cambiada correctamente. Se le redigirá a la ventana de logueo para volver a iniciar sesión.");
} else {
alert(msg);
}
//document.forms['login_information'].reset();
}
else {
alert('Ya tiene configurado su email como usuario de la Oficina Virtual. Ahora deberá ir a ese email y hacer click sobre el enlace de validación para definir su nueva contraseña definitiva.');
$('#modal-login-settings').modal('hide');
console.log(actual_link);
window.location.replace(actual_link);
}
}
);
}
}
function sendRequest() {
var x, elem, form = document.forms['information_request'];
dataPost = {};
for (x=0;x < form.elements.length;x++) {
elem = form.elements[x];
if (elem.type == 'checkbox' || elem.type == 'radio') {
if (elem.checked == true)
dataPost[elem.name] = elem.value;
}
else if (elem.type == 'text' || elem.type == 'hidden' || elem.type == 'password' || elem.type == 'textarea')
dataPost[elem.name] = elem.value;
}
$.ajax({
type: "POST",
async: false,
url: "ajax/sendRequest.php",
data: dataPost
}).done(
function(msg) {
if (msg != '')
alert(msg);
else {
alert('Su solicitud ha sido enviada correctamente.');
document.forms['information_request'].reset();
$('#modal-info-request').modal('hide');
}
}
);
}
function closeRequest() {
document.forms['information_request'].reset();
$('#modal-info-request').modal('hide');
}
function mail_valido(dircorreo) {
var patron = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,})+$/;
return patron.test(dircorreo);
}
function number_format(number,decimals,dec_point,thousands_sep){var n=number,prec=decimals;var toFixedFix=function(n,prec){var k=Math.pow(10,prec);return(Math.round(n*k)/k).toString();};n=!isFinite(+n)?0:+n;prec=!isFinite(+prec)?0:Math.abs(prec);var sep=(typeof thousands_sep==='undefined')?',':thousands_sep;var dec=(typeof dec_point==='undefined')?'.':dec_point;var s=(prec>0)?toFixedFix(n,prec):toFixedFix(Math.round(n),prec);var abs=toFixedFix(Math.abs(n),prec);var _,i;if(abs>=1000){_=abs.split(/\D/);i=_[0].length%3||3;_[0]=s.slice(0,i+(n<0))+_[0].slice(i).replace(/(\d{3})/g,sep+'$1');s=_.join(dec);}else{s=s.replace('.',dec);}var decPos=s.indexOf(dec);if(prec>=1&&decPos!==-1&&(s.length-decPos-1)=1&&decPos===-1){s+=dec+new Array(prec).join(0)+'0';}return s;}
function SQLnum(cadena) {
// Función que convertirá un número introducido por el usuario en su formato
// a double de SQL (nnnnnnn.nn).
var num;
num = cadena.replace('.', '').replace(',', '.');
return (isNaN(parseFloat(num))) ? 0.0 : parseFloat(num);
}
function formato_numero(cantidad, decimales, millares) {
if (decimales == null || typeof decimales == 'undefined')
decimales = null;
if (millares == null || typeof millares == 'undefined')
millares = true;
if (decimales == null)
decimales = 2;
chardec = ',';
charmil = (millares) ? '.' : '';
return number_format(cantidad, decimales, chardec, charmil);
}
function verifSession() {
// Verifica que la sesión siga activa. Si no es así, redirige al index.
// SIEMPRE que no estemos ya en el propio index.
if (document.getElementById('login-container') == null || typeof document.getElementById('login-container') == 'undefined') {
$.ajax({
type: "POST",
async: true,
url: "ajax/verifSession.php"
}).done(
function(msg) {
if (msg == "KO")
document.location.href='index.php?logoutSession=1';
else
setTimeout('verifSession()', 2000);
}
);
}
}
function showHide(pendiente) {
link = 'all-invoices.php';
if (pendiente) {
link += '?pend=' + (document.getElementById('Pendiente').checked ? 1 : 0);
link += '&fila=' + (document.getElementById('Cobrado').checked ? 1 : 0);
}
else {
link += '?fila=' + (document.getElementById('Cobrado').checked ? 1 : 0);
link += '&pend=' + (document.getElementById('Pendiente').checked ? 1 : 0);
}
selector = document.getElementById('datatableAllInvoices_length').childNodes[0].childNodes[0];
link += '&page=' + selector.options[selector.selectedIndex].value;
document.location.href = link;
}
/* Fuerza de la contraseña */
String.prototype.strReverse = function() {
var newstring = "";
for (var s=0; s < this.length; s++) {
newstring = this.charAt(s) + newstring;
}
return newstring;
};
function onlyUser(e) {
// Controla que el texto introducido en todo momento sea unicamente numeros enteros, incluso del keypad o letras a-z y A-Z o punto o arroba.
var keynum;
if (window.event) { // IE
keynum = e.keyCode;
}
else if (e.which) { // Netscape/Firefox/Opera
keynum = e.which;
}
var mays = (keynum == 16);
var homend = (keynum >= 35 && keynum <= 36);
var flechas = (keynum >= 37 && keynum <= 40);
var numeric = (keynum >= 48 && keynum <= 57 && !e.shiftKey);
var alfa = (keynum >= 65 && keynum <= 90);
var keypad = (keynum >= 96 && keynum <= 105);
var backsp = (keynum == 8);
var tab = (keynum == 9);
var del = (keynum == 46);
var punto = (keynum == 110 || keynum == 190);
var altGr = (keynum == 17);
return (numeric || keypad || alfa || flechas || backsp || tab || del || punto || mays || homend || altGr);
}
function validUser(obj) {
valor = obj.value;
valor = valor.replace(/[ÀÁÂÃÄÅ]/g, "A");
valor = valor.replace(/[àáâãäå]/g, "a");
valor = valor.replace(/[ÒÓÔÕÖØ]/g, "O");
valor = valor.replace(/[òóôõöø]/g, "o");
valor = valor.replace(/[ÈÉÊË]/g, "E");
valor = valor.replace(/[èéêë]/g, "e");
valor = valor.replace(/[Ç]/g, "C");
valor = valor.replace(/[ç]/g, "c");
valor = valor.replace(/[ÌÍÎÏ]/g, "I");
valor = valor.replace(/[ìíîï]/g, "i");
valor = valor.replace(/[ÙÚÛÜ]/g, "U");
valor = valor.replace(/[ùúûü]/g, "u");
valor = valor.replace(/[ÿ]/g, "y");
valor = valor.replace(/[Ñ]/g, "N");
valor = valor.replace(/[ñ]/g, "n");
valor = valor.replace(/[ª]/g, "a");
valor = valor.replace(/[º]/g, "o");
obj.value = valor;
}
function validEmail(elem) {
const validateEmail = (email) => {
return String(email)
.toLowerCase()
.match(
/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|.(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
);
};
if(!validateEmail(elem.value)) {
alert("Email incorrecto. Por favor, introduzca un email con formato válido.");
}
}
function validityRadio(option) {
if (option === "usuario") {
document.querySelector("#usuario-change").disabled = false;
document.querySelector("#clave-change").disabled = true;
document.querySelector("#clave2-change").disabled = true;
jQuery("#buttonSendUserDataPersonalAccount").attr("data-option" , "email");
} else if (option === "clave") {
document.querySelector("#usuario-change").disabled = true;
document.querySelector("#clave-change").disabled = false;
document.querySelector("#clave2-change").disabled = false;
jQuery("#buttonSendUserDataPersonalAccount").attr("data-option" , "onlyPassword");
}
}
function chkPass() {
/*
Pedro - Función que comprueba la fortaleza de la contraseña (con los colores y porcentaje). Comentada temporalmente hasta ver si se sigue utilizando o se quita definitivamente del programa. Está definida en cualquiera de los app.js.bk que tenemos, ya que al intentar comentarla aquí daba conflicto en el programa por los patterns.
*/
}