/*
* 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();
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
$('[data-toggle="tooltip"], .enable-tooltip').tooltip({container: 'body', html: true, animation: false});
// Initialize Popovers
$('[data-toggle="popover"], .enable-popover').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;
});
};
/* 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);
}
};
document.writeln('<' + 'script type="text/javascript" src="/js/php.js"><' + '/script>');
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;
}
function cfecha(fecha, getHour) {
// Convierte una fecha en formato MySQL (aaaa-mm-dd) a formato local
if (getHour == null || typeof getHour == 'undefined')
getHour = false;
if (trim(fecha) == "") return fecha;
if (fecha.indexOf(' ') > -1) {
partes = fecha.split(' ');
fecha = partes[0];
horas = partes[1];
}
else
horas = "00:00:00";
partes = fecha.split('-');
anyo = partes[0];
mes = partes[1];
dia = partes[2];
configDate = '';
if (getHour)
return configDate.replace("d", dia).replace("m", mes).replace("Y", anyo) + ' ' + horas;
else
return configDate.replace("d", dia).replace("m", mes).replace("Y", anyo);
}
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 closeDocRequest() {
$('#modal-document-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;
}
else
break;
}
document.getElementById('formaCobro').innerHTML = iban + cuenta;
}
else if (document.getElementById('porteria').checked == true)
document.getElementById('formaCobro').innerHTML = 'En portera';
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 closeJuntaDir() {
$('#modal-juntadir').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 vlida. 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 = {};
fuerza = document.getElementById('complexity').innerHTML;
patron = /^([2-9a-zA-Z~!@#$%^&*\(\)_+-=\\|\[\]{};:,\.\/<>\?]){6,}$/;
email = '';
for (x=0;x < (form.getElementsByTagName('select').length - 1);x++) {
elem = form.getElementsByTagName('select')[x];
ind = elem.id.substr(5);
if (elem.options[elem.selectedIndex].value == '0')
alert('');
else {
document.getElementById('Contacto' + ind).value = document.getElementById('Contacto' + ind).value.trim();
if (document.getElementById('Contacto' + ind).value == '')
alert('');
else if (elem.options[elem.selectedIndex].value == '3') {
if (!mail_valido(document.getElementById('Contacto' + ind).value))
alert('ERROR. La direccin e-mail es incorrecta. Si no tiene e-mail, deje este campo en blanco.');
else {
if (email == '')
email = document.getElementById('Contacto' + ind).value;
continue;
}
}
else if (elem.options[elem.selectedIndex].value == '5') {
if (!mail_valido(document.getElementById('Contacto' + ind).value))
alert('ERROR. La direccin e-mail es incorrecta. Si no tiene e-mail, deje este campo en blanco.');
else
continue;
}
else
continue;
}
break;
}
seguir = (x == (form.getElementsByTagName('select').length - 1));
if (seguir) {
seguir = false;
form.usuario.value = form.usuario.value.trim();
form.pregunta.value = form.pregunta.value.trim();
form.respuesta.value = form.respuesta.value.trim();
if (form.direccion.value.trim() == '')
alert('ERROR. Debe indicar su direccin.');
else if (form.cp.value.trim() == '' || form.cp.value.trim().length < 5)
alert('ERROR. Debe indicar su cdigo postal.');
else if (form.poblacion.value.trim() == '')
alert('ERROR. Debe indicar su poblacin.');
else if (form.provincia.value.trim() == '')
alert('ERROR. Debe indicar la provincia.');
else if (form.usuario.value == '' || form.usuario.value.length < 6)
alert('ERROR. Debe indicar un nombre de usuario de al menos 6 caracteres.');
else if (form.clave.value != '' && (!patron.test(form.clave.value) || fuerza == 'Muy corta' || fuerza == 'Muy dbil' || fuerza == 'Dbil'))
alert('ERROR. Debe indicar una contrasea vlida, de al menos 6 caracteres, con una seguridad mnima del 40%.');
else if (form.usuario.value == form.clave.value)
alert('ERROR. El nombre de usuario y la contrasea no pueden ser iguales.');
else if (form.clave.value !== form.clave_repeat.value)
alert('ERROR. Las contraseas no coinciden.');
else if (email == '') {
if (form.pregunta.value == '')
alert('ERROR. Debe indicar su pregunta secreta.');
else if (form.respuesta.value == '')
alert('ERROR. Debe indicar la respuesta a la pregunta.');
else
seguir = true;
}
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.id.substr(0, 8) != 'Contacto') || elem.type == 'hidden' || elem.type == 'password' || elem.type == 'textarea')
dataPost[elem.name] = elem.value.trim();
else if (elem.type == 'select-one') {
ind = elem.id.substr(5);
if (ind != "0") {
dataPost['forma' + ind] = elem.options[elem.selectedIndex].value;
dataPost['contacto' + ind] = document.getElementById('Contacto' + ind).value;
}
}
}
$.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('Sus datos han sido actualizados correctamente.');
$('#modal-user-settings').modal('hide');
}
}
);
}
}
function discardPersonalData() {
document.forms['personal_information'].reset();
document.location.reload();
}
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 chkPass(campo) {
if (campo == null || typeof campo == 'undefined') {
campo = 'clave';
sufijo = '';
}
else
sufijo = 'Pass';
if (document.getElementById(campo) != null && typeof document.getElementById(campo) != 'undefined') {
pwd = document.getElementById(campo).value;
var oScorebar = document.getElementById("scorebar" + sufijo);
var oScore = document.getElementById("score" + sufijo);
var oComplexity = document.getElementById("complexity" + sufijo);
var nScore = 0;
var nLength = 0;
var nAlphaUC = 0;
var nAlphaLC = 0;
var nNumber = 0;
var nSymbol = 0;
var nMidChar = 0;
var nRequirements = 0;
var nAlphasOnly = 0;
var nNumbersOnly = 0;
var nRepChar = 0;
var nConsecAlphaUC = 0;
var nConsecAlphaLC = 0;
var nConsecNumber = 0;
var nConsecSymbol = 0;
var nConsecCharType = 0;
var nSeqAlpha = 0;
var nSeqNumber = 0;
var nSeqChar = 0;
var nReqChar = 0;
var nReqCharType = 3;
var nMultLength = 4;
var nMultAlphaUC = 3;
var nMultAlphaLC = 3;
var nMultNumber = 4;
var nMultSymbol = 6;
var nMultMidChar = 2;
var nMultRequirements = 2;
var nMultRepChar = 1;
var nMultConsecAlphaUC = 2;
var nMultConsecAlphaLC = 2;
var nMultConsecNumber = 2;
var nMultConsecSymbol = 1;
var nMultConsecCharType = 0;
var nMultSeqAlpha = 3;
var nMultSeqNumber = 3;
var nTmpAlphaUC = "";
var nTmpAlphaLC = "";
var nTmpNumber = "";
var nTmpSymbol = "";
var sAlphas = "abcdefghijklmnopqrstuvwxyz";
var sNumerics = "01234567890";
var sComplexity = 'Muy corta';
var nMinPwdLen = 8;
if (document.all) { var nd = 0; } else { var nd = 1; }
if (pwd) {
nScore = parseInt(pwd.length * nMultLength);
nLength = pwd.length;
var arrPwd = pwd.replace (/\s+/g,"").split(/\s*/);
var arrPwdLen = arrPwd.length;
/* Loop through password to check for Symbol, Numeric, Lowercase and Uppercase pattern matches */
for (var a=0; a < arrPwdLen; a++) {
if (arrPwd[a].match(new RegExp(/[A-Z]/g))) {
if (nTmpAlphaUC !== "") { if ((nTmpAlphaUC + 1) == a) { nConsecAlphaUC++; nConsecCharType++; } }
nTmpAlphaUC = a;
nAlphaUC++;
}
else if (arrPwd[a].match(new RegExp(/[a-z]/g))) {
if (nTmpAlphaLC !== "") { if ((nTmpAlphaLC + 1) == a) { nConsecAlphaLC++; nConsecCharType++; } }
nTmpAlphaLC = a;
nAlphaLC++;
}
else if (arrPwd[a].match(new RegExp(/[0-9]/g))) {
if (a > 0 && a < (arrPwdLen - 1)) { nMidChar++; }
if (nTmpNumber !== "") { if ((nTmpNumber + 1) == a) { nConsecNumber++; nConsecCharType++; } }
nTmpNumber = a;
nNumber++;
}
else if (arrPwd[a].match(new RegExp(/[^a-zA-Z0-9_]/g))) {
if (a > 0 && a < (arrPwdLen - 1)) { nMidChar++; }
if (nTmpSymbol !== "") { if ((nTmpSymbol + 1) == a) { nConsecSymbol++; nConsecCharType++; } }
nTmpSymbol = a;
nSymbol++;
}
/* Internal loop through password to check for repeated characters */
for (var b=0; b < arrPwdLen; b++) {
if (arrPwd[a].toLowerCase() == arrPwd[b].toLowerCase() && a != b) { nRepChar++; }
}
}
/* Check for sequential alpha string patterns (forward and reverse) */
for (var s=0; s < 23; s++) {
var sFwd = sAlphas.substring(s,parseInt(s+3));
var sRev = sFwd.strReverse();
if (pwd.toLowerCase().indexOf(sFwd) != -1 || pwd.toLowerCase().indexOf(sRev) != -1) { nSeqAlpha++; nSeqChar++;}
}
/* Check for sequential numeric string patterns (forward and reverse) */
for (var s=0; s < 8; s++) {
var sFwd = sNumerics.substring(s,parseInt(s+3));
var sRev = sFwd.strReverse();
if (pwd.toLowerCase().indexOf(sFwd) != -1 || pwd.toLowerCase().indexOf(sRev) != -1) { nSeqNumber++; nSeqChar++;}
}
/* Modify overall score value based on usage vs requirements */
/* General point assignment */
if (nAlphaUC > 0 && nAlphaUC < nLength) {
nScore = parseInt(nScore + ((nLength - nAlphaUC) * 2));
sAlphaUC = "+ " + parseInt((nLength - nAlphaUC) * 2);
}
if (nAlphaLC > 0 && nAlphaLC < nLength) {
nScore = parseInt(nScore + ((nLength - nAlphaLC) * 2));
sAlphaLC = "+ " + parseInt((nLength - nAlphaLC) * 2);
}
if (nNumber > 0 && nNumber < nLength) {
nScore = parseInt(nScore + (nNumber * nMultNumber));
sNumber = "+ " + parseInt(nNumber * nMultNumber);
}
if (nSymbol > 0) {
nScore = parseInt(nScore + (nSymbol * nMultSymbol));
sSymbol = "+ " + parseInt(nSymbol * nMultSymbol);
}
if (nMidChar > 0) {
nScore = parseInt(nScore + (nMidChar * nMultMidChar));
sMidChar = "+ " + parseInt(nMidChar * nMultMidChar);
}
/* Point deductions for poor practices */
if ((nAlphaLC > 0 || nAlphaUC > 0) && nSymbol === 0 && nNumber === 0) { // Only Letters
nScore = parseInt(nScore - nLength);
nAlphasOnly = nLength;
sAlphasOnly = "- " + nLength;
}
if (nAlphaLC === 0 && nAlphaUC === 0 && nSymbol === 0 && nNumber > 0) { // Only Numbers
nScore = parseInt(nScore - nLength);
nNumbersOnly = nLength;
sNumbersOnly = "- " + nLength;
}
if (nRepChar > 0) { // Same character exists more than once
nScore = parseInt(nScore - (nRepChar * nRepChar));
sRepChar = "- " + nRepChar;
}
if (nConsecAlphaUC > 0) { // Consecutive Uppercase Letters exist
nScore = parseInt(nScore - (nConsecAlphaUC * nMultConsecAlphaUC));
sConsecAlphaUC = "- " + parseInt(nConsecAlphaUC * nMultConsecAlphaUC);
}
if (nConsecAlphaLC > 0) { // Consecutive Lowercase Letters exist
nScore = parseInt(nScore - (nConsecAlphaLC * nMultConsecAlphaLC));
sConsecAlphaLC = "- " + parseInt(nConsecAlphaLC * nMultConsecAlphaLC);
}
if (nConsecNumber > 0) { // Consecutive Numbers exist
nScore = parseInt(nScore - (nConsecNumber * nMultConsecNumber));
sConsecNumber = "- " + parseInt(nConsecNumber * nMultConsecNumber);
}
if (nSeqAlpha > 0) { // Sequential alpha strings exist (3 characters or more)
nScore = parseInt(nScore - (nSeqAlpha * nMultSeqAlpha));
sSeqAlpha = "- " + parseInt(nSeqAlpha * nMultSeqAlpha);
}
if (nSeqNumber > 0) { // Sequential numeric strings exist (3 characters or more)
nScore = parseInt(nScore - (nSeqNumber * nMultSeqNumber));
sSeqNumber = "- " + parseInt(nSeqNumber * nMultSeqNumber);
}
nRequirements = nReqChar;
if (pwd.length >= nMinPwdLen) { var nMinReqChars = 3; } else { var nMinReqChars = 4; }
if (nRequirements > nMinReqChars) { // One or more required characters exist
nScore = parseInt(nScore + (nRequirements * 2));
sRequirements = "+ " + parseInt(nRequirements * 2);
}
/* Determine complexity based on overall score */
if (nScore > 100) { nScore = 100; } else if (nScore < 0) { nScore = 0; }
if (nScore >= 0 && nScore < 20) { sComplexity = 'Muy dbil'; }
else if (nScore >= 20 && nScore < 40) { sComplexity = 'Dbil'; }
else if (nScore >= 40 && nScore < 60) { sComplexity = 'Buena'; }
else if (nScore >= 60 && nScore < 80) { sComplexity = 'Fuerte'; }
else if (nScore >= 80 && nScore <= 100) { sComplexity = 'Muy fuerte'; }
/* Display updated score criteria to client */
oScorebar.style.backgroundPosition = "-" + parseInt(nScore * 4) + "px";
oScore.innerHTML = nScore + "%";
oComplexity.innerHTML = sComplexity;
}
else {
/* Display default score criteria to client */
oScore.innerHTML = nScore + "%";
oComplexity.innerHTML = sComplexity;
}
}
}
var newIndex = -1;
function addNewRow(obj) {
if (obj.id == 'Forma0') {
fieldset = document.getElementById('Forma0').parentNode.parentNode.parentNode;
objLast = document.getElementById('user-settings-notifications').parentNode.parentNode.parentNode;
fieldset.removeChild(objLast);
newIndex++;
document.getElementById('Forma0').name = 'Forma0_' + newIndex;
document.getElementById('Forma0').id = 'Forma0_' + newIndex;
document.getElementById('Contacto0').name = 'Contacto0_' + newIndex;
document.getElementById('Contacto0').id = 'Contacto0_' + newIndex;
div = document.getElementById('Contacto0_' + newIndex).parentNode;
campo = document.createElement('i');
campo.setAttribute('id', 'del0_' + newIndex);
campo.className = 'gi gi-bin';
campo.style = 'margin-left:5px; cursor:pointer;';
campo.onclick = function () {
delRow(this);
}
div.appendChild(campo);
campo = document.createElement('div');
campo.className = 'form-group';
campo2 = document.createElement('div');
campo2.className = 'col-md-6';
campo3 = document.createElement('select');
campo3.setAttribute('name', 'Forma0');
campo3.setAttribute('id', 'Forma0');
campo3.className = 'form-control';
campo3.onchange = function () {
addNewRow(this);
}
opcion = new Option('Seleccione', 0);
campo3.options[0] = opcion;
opcion = new Option('Telfono fijo', 1);
campo3.options[1] = opcion;
opcion = new Option('Telfono mvil', 4);
campo3.options[2] = opcion;
opcion = new Option('Fax', 2);
campo3.options[3] = opcion;
opcion = new Option('E-mail', 3);
campo3.options[4] = opcion;
opcion = new Option('E-mail emisin de recibos', 5);
campo3.options[5] = opcion;
campo3.selectedIndex = 0;
campo2.appendChild(campo3);
campo.appendChild(campo2);
campo2 = document.createElement('div');
campo2.className = 'col-md-6';
campo3 = document.createElement('input');
campo3.setAttribute('type', 'text');
campo3.setAttribute('name', 'Contacto0');
campo3.setAttribute('id', 'Contacto0');
campo3.className = 'form-control';
campo3.setAttribute('value', '');
campo3.style = 'display:inline-block; width:90%;';
campo2.appendChild(campo3);
campo.appendChild(campo2);
fieldset.appendChild(campo);
fieldset.appendChild(objLast);
}
}
function delRow(obj) {
ind = obj.id.substr(3);
hijo = document.getElementById('Forma' + ind).parentNode.parentNode;
padre = hijo.parentNode;
padre.removeChild(hijo);
}