/* ------------------------------------------------------------------------------ * * # Custom JS code * * Place here all your custom js. Make sure it's loaded after app.js * * ---------------------------------------------------------------------------- */ var Carga = function() { // // Setup module components // // Loading button var _componentLoadingButton = function() { $('.btn-loading').on('click', function () { var btn = $(this), initialText = btn.data('initial-text'), loadingText = btn.data('loading-text'); btn.html(loadingText).addClass('disabled'); //setTimeout(function () { // btn.html(initialText).removeClass('disabled'); //}, 3000) }); }; // Floating labels config var _componentFloatingLabels = function() { // Variables var showClass = 'is-visible', animateClass = 'animate', labelWrapperClass = 'form-group-float', labelClass = 'form-group-float-label'; // Setup $('input:not(.token-input):not(.bootstrap-tagsinput > input), textarea, select').on('checkval change', function () { // Define label var label = $(this).parents('.' + labelWrapperClass).children('.' + labelClass); // Toggle label if (this.value !== '') { label.addClass(showClass); } else { label.removeClass(showClass).addClass(animateClass); } }).on('keyup', function () { $(this).trigger('checkval'); }).trigger('checkval').trigger('change'); // Remove animation on page load $(window).on('load', function() { $('.' + labelWrapperClass).find('.' + showClass).removeClass(animateClass); }); }; // Select2 var _componentSelect2 = function() { if (!$().select2) { console.warn('Warning - select2.min.js is not loaded.'); return; } $.fn.select2.defaults.set('language', 'es'); $('.select2-normal').select2({ templateResult: iconFormat, templateSelection: iconFormat, escapeMarkup: function(m) { return m; } }); $('.select2-roles').select2({ dropdownParent: $("#modalTab1"), minimumResultsForSearch: Infinity, templateResult: iconFormat, templateSelection: iconFormat, escapeMarkup: function(m) { return m; } }) .on('change', function () { formulariotab1.revalidateField(this.id); }); $('.select2-tab1').select2({ dropdownParent: $("#modalTab1"), templateResult: iconFormat, templateSelection: iconFormat, escapeMarkup: function(m) { return m; } }) .on('change', function () { formulariotab1.revalidateField(this.id); }); $('.select2-tab2').select2({ dropdownParent: $("#modalTab2"), templateResult: iconFormat, templateSelection: iconFormat, escapeMarkup: function(m) { return m; } }) .on('change', function () { formulariotab2.revalidateField(this.id); }); $('.select2-tab3').select2({ dropdownParent: $("#modalTab3"), templateResult: iconFormat, templateSelection: iconFormat, escapeMarkup: function(m) { return m; } }) .on('change', function () { formulariotab3.revalidateField(this.id); }); $('.select2-tab4').select2({ dropdownParent: $("#modalTab4"), templateResult: iconFormat, templateSelection: iconFormat, escapeMarkup: function(m) { return m; } }) .on('change', function () { formulariotab4.revalidateField(this.id); }); $('.select2-tab5').select2({ dropdownParent: $("#modalTab5"), templateResult: iconFormat, templateSelection: iconFormat, escapeMarkup: function(m) { return m; } }) .on('change', function () { formulariotab5.revalidateField(this.id); }); $('.select2-tab6').select2({ dropdownParent: $("#modalTab6"), templateResult: iconFormat, templateSelection: iconFormat, escapeMarkup: function(m) { return m; } }) .on('change', function () { formulariotab6.revalidateField(this.id); }); $('.select2-tab7').select2({ dropdownParent: $("#modalTab7"), templateResult: iconFormat, templateSelection: iconFormat, escapeMarkup: function(m) { return m; } }) .on('change', function () { formulariotab7.revalidateField(this.id); }); // // Single select with icons // // Format icon function iconFormat(icon) { var originalOption = icon.element; if (!icon.id) { return icon.text; } $icon = '' + icon.text; return $icon; } // Initialize with options $('.select2-icons').select2({ templateResult: iconFormat, templateSelection: iconFormat, escapeMarkup: function(m) { return m; } }); }; var _componentValidation = function() { if (!$().validate) { console.warn('Warning - validate.min.js is not loaded.'); return; } // Initialize var validator = $('.form-validate-jquery').validate({ ignore: 'input[type=hidden], .select2-search__field', // ignore hidden fields errorClass: 'validation-invalid-label', successClass: 'validation-valid-label', validClass: 'validation-valid-label', lang: 'es', // onsubmit: false, onkeyup: function(element, event) { if(event.which === 9 && this.elementValue(element) === "") { return; } else { this.element(element); } }, highlight: function(element, errorClass) { $(element).removeClass(errorClass); }, unhighlight: function(element, errorClass) { $(element).removeClass(errorClass); }, submitHandler: function(form) { // To use loading button var btn = $('.btn-loading'); var btn2 = $('.btn-cancel'); loadingText = btn.data('loading-text'); btn.html(loadingText).addClass('disabled'); btn2.addClass('disabled'); form.submit(); }, /* success: function(label) { label.addClass('validation-valid-label').text('Success.'); // remove to hide Success message },*/ // Different components require proper error label placement errorPlacement: function(error, element) { // Unstyled checkboxes, radios if (element.parents().hasClass('form-check')) { error.appendTo( element.parents('.form-check').parent() ); } // Input with icons and Select2 else if (element.parents().hasClass('form-group-feedback') || element.hasClass('select2-hidden-accessible')) { error.appendTo( element.parent() ); } // Input group, styled file input else if (element.parent().is('.uniform-uploader, .uniform-select') || element.parents().hasClass('input-group')) { error.appendTo( element.parent().parent() ); } // Other elements else { error.insertAfter(element); } } }); // Reset form $('#reset').on('click', function() { validator.resetForm(); }); }; // Basic Datatable examples var _componentDatatable = function() { if (!$().DataTable) { console.warn('Warning - datatables.min.js is not loaded.'); return; } // Setting datatable defaults $.extend( $.fn.dataTable.defaults, { autoWidth: false, // responsive: true, columnDefs: [{ orderable: false, width: 100 // targets: [ 5 ] }], dom: '<"datatable-header"fBl><"datatable-scroll-wrap"t><"datatable-footer"ip>', language: { sProcessing: 'Procesando...', sSearch: 'Filtro: _INPUT_', sEmptyTable: 'Ningún dato disponible en esta tabla.', sInfoFiltered: '(filtrado de un total de _MAX_ registros)', sZeroRecords: 'Ningún registro encontrado.', sSearchPlaceholder: 'Escriba para filtrar....', sInfo: 'Mostrando registros del _START_ al _END_ de un total de _TOTAL_ registros. ', sInfoEmpty: '', sLengthMenu: 'Mostrar _MENU_', paginate: { 'first': 'Primero', 'last': 'Último', 'next': $('html').attr('dir') == 'rtl' ? '←' : '→', 'previous': $('html').attr('dir') == 'rtl' ? '→' : '←' } } }); $('.datatablecarga').DataTable({ dom: '<"datatable-header"B><"datatable-scroll-wrap"t><"datatable-footer"ip>', buttons: { buttons: [ { extend: 'excelHtml5', text: ' Descargar Plantilla', className: 'btn btn-light bg-blue', sheetName: 'Datos', title: '', exportOptions: { columns: ':visible' } } ] } }); $('.datatable').DataTable({ buttons: { buttons: [ { extend: 'print', text: ' Imprimir', className: 'btn btn-light bg-blue', exportOptions: { columns: ':visible' } }, { extend: 'excelHtml5', text: ' Excel', className: 'btn btn-light bg-blue', sheetName: 'Datos', exportOptions: { columns: ':visible' } }, { extend: 'pdfHtml5', text: ' PDF', className: 'btn btn-light bg-blue', exportOptions: { columns: ':visible' } }, { extend: 'colvis', text: '', className: 'btn btn-light bg-blue btn-icon dropdown-toggle' } ] }, "initComplete": function () { var orderInit = this.api().order(); this.api().columns('.dt-filter-select').every( function () { var column = this; var select = $('') .appendTo($(column.footer()).not(':last-child').empty()) .on('change', function() { var val = $.fn.dataTable.util.escapeRegex( $(this).val() ); //debug in firefox alert(select.toSource()); column .search( val ? '^'+val+'$' : '', true, false ) .draw(); }); /* column.data().unique().sort().each(function (d, j) { select.append('') }); */ // Para evitar filas repetidas var texto = ""; column.order('asc').draw(false).data().unique().each( function ( d, j ) { var val = $('
').html(d).text().trim(); if(val !== texto) { select.append(''); } texto = val; } ); }); // Restore initial order this.api().order(orderInit).draw(false); }, "fnDrawCallback": function() { var today = new Date(); var year = today.getFullYear(); var year100 = year - 100; var year1 = year + 1; $('.progress-bar').progressbar({display_text: 'fill'}); $('.texto50').editable({ validate: function(value) { if (value.length > 49) return 'Este campo no puede ser de más de 50 caracteres.'; }, error: function (xhr, status) { var data=xhr.responseText; var jsonResponse = JSON.parse(data); if(jsonResponse["message"].indexOf("SQLSTATE[23000]") != -1) { return 'El valor "' + status + '" ya existe en la base de datos.'; } else { return 'Error al actualizar el registro.'; } } }); $('.texto50req').editable({ validate: function(value) { if($.trim(value) == '') return 'Este campo es requerido.'; else if (value.length > 49) return 'Este campo no puede ser de más de 50 caracteres.'; }, error: function (xhr, status) { var data=xhr.responseText; var jsonResponse = JSON.parse(data); return jsonResponse["message"]; if(jsonResponse["message"].indexOf("SQLSTATE[23000]") != -1) { return 'El valor "' + status + '" ya existe en la base de datos.'; } else { return 'Error al actualizar el registro.'; } } }); $('.texto100').editable({ validate: function(value) { if (value.length > 99) return 'Este campo no puede ser de más de 100 caracteres.'; }, error: function (xhr, status) { var data=xhr.responseText; var jsonResponse = JSON.parse(data); if(jsonResponse["message"].indexOf("SQLSTATE[23000]") != -1) { return 'El valor "' + status + '" ya existe en la base de datos.'; } else { return 'Error al actualizar el registro.'; } } }); $('.texto100req').editable({ validate: function(value) { if($.trim(value) == '') return 'Este campo es requerido.'; else if (value.length > 99) return 'Este campo no puede ser de más de 100 caracteres.'; }, error: function (xhr, status) { var data=xhr.responseText; var jsonResponse = JSON.parse(data); return jsonResponse["message"]; if(jsonResponse["message"].indexOf("SQLSTATE[23000]") != -1) { return 'El valor "' + status + '" ya existe en la base de datos.'; } else { return 'Error al actualizar el registro.'; } } }); $('.texto255req').editable({ validate: function(value) { if($.trim(value) == '') return 'Este campo es requerido.'; else if (value.length > 254) return 'Este campo no puede ser de más de 255 caracteres.'; }, error: function (xhr, status) { var data=xhr.responseText; var jsonResponse = JSON.parse(data); return jsonResponse["message"]; if(jsonResponse["message"].indexOf("SQLSTATE[23000]") != -1) { return 'El valor "' + status + '" ya existe en la base de datos.'; } else { return 'Error al actualizar el registro.'; } } }); $('.texto255').editable({ validate: function(value) { if (value.length > 254) return 'Este campo no puede ser de más de 255 caracteres.'; }, error: function (xhr, status) { var data=xhr.responseText; var jsonResponse = JSON.parse(data); if(jsonResponse["message"].indexOf("SQLSTATE[23000]") != -1) { return 'El valor "' + status + '" ya existe en la base de datos.'; } else { return 'Error al actualizar el registro.'; } } }); $('.textoarea').editable({ validate: function(value) { if (value.length > 2500) return 'Este campo no puede ser de más de 2500 caracteres.'; }, error: function (xhr, status) { var data=xhr.responseText; var jsonResponse = JSON.parse(data); if(jsonResponse["message"].indexOf("SQLSTATE[23000]") != -1) { return 'El valor "' + status + '" ya existe en la base de datos.'; } else { return 'Error al actualizar el registro.'; } } }); $('.textoareareq').editable({ validate: function(value) { if($.trim(value) == '') return 'Este campo es requerido.'; else if (value.length > 2500) return 'Este campo no puede ser de más de 2500 caracteres.'; }, error: function (xhr, status) { var data=xhr.responseText; var jsonResponse = JSON.parse(data); if(jsonResponse["message"].indexOf("SQLSTATE[23000]") != -1) { return 'El valor "' + status + '" ya existe en la base de datos.'; } else { return 'Error al actualizar el registro.'; } } }); $('.textoemail').editable({ validate: function(value) { var re = /^(([^<>()[\]\\.,;:\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(!re.test(value)) return 'E-mail invalido.'; else if (value.length > 254) return 'Este campo no puede ser de más de 255 caracteres.'; }, error: function (xhr, status) { var data=xhr.responseText; var jsonResponse = JSON.parse(data); if(jsonResponse["message"].indexOf("SQLSTATE[23000]") != -1) { return 'El valor "' + status + '" ya existe en la base de datos.'; } else { return 'Error al actualizar el registro.'; } } }); $('.selectreq').editable({ error: function (xhr, status) { var data=xhr.responseText; var jsonResponse = JSON.parse(data); if(jsonResponse["message"].indexOf("SQLSTATE[23000]") != -1) { return 'Debe seleccionar una opción.'; } else { return 'Error al actualizar el registro.'; } }/*, success: function(response, newValue){ alert(response.toSource()); }*/ }); $('.selecttags').editable({ select2: { tags: ['html', 'javascript', 'css', 'ajax'], tokenSeparators: [",", " "] }, error: function (xhr, status) { var data=xhr.responseText; var jsonResponse = JSON.parse(data); if(jsonResponse["message"].indexOf("SQLSTATE[23000]") != -1) { return 'Debe seleccionar una opción.'; } else { return 'Error al actualizar el registro.'; } } }); $('.tags').editable({ inputclass: 'input-large', select2: { tags: ['html', 'javascript', 'css', 'ajax'], tokenSeparators: [",", " "] } }); $('.coeficiente').editable({ validate: function(value) { if($.trim(value) === '') return 'Este campo es requerido.'; else if (value.replace(",", ".") > 100) return 'Este campo no puede ser de mayor de 100.'; else if (value.replace(",", ".") < 0) return 'Este campo no puede ser de menor de 0.'; var regex = /^(\d+)?([,]?\d{0,6})?$/; if(! regex.test(value)) { return 'Escribe un número valido entre 0 y 100, con máximo seis decimales.'; } }, error: function (xhr, status) { var data=xhr.responseText; var jsonResponse = JSON.parse(data); if(jsonResponse["message"].indexOf("SQLSTATE[23000]") != -1) { return 'Error al actualizar el registro.'; } else { return 'Error al actualizar el registro.'; } } }); $('.textomodelo').editable({ validate: function(value) { if ($.isNumeric(value) == '') { return 'Solo números permitidos'; } else if (value > year1) return 'Este campo no puede ser mayor a ' + year1 + '.'; else if (value < year100) return 'Este campo no puede ser menor a ' + year100 + '.'; }, error: function (xhr, status) { var data=xhr.responseText; var jsonResponse = JSON.parse(data); if(jsonResponse["message"].indexOf("SQLSTATE[23000]") != -1) { return 'Error al actualizar el registro.'; } else { return 'Error al actualizar el registro.'; } } }); $('.textoentero').editable({ validate: function(value) { if ($.isNumeric(value) == '') { return 'Solo números permitidos'; } }, error: function (xhr, status) { var data=xhr.responseText; var jsonResponse = JSON.parse(data); if(jsonResponse["message"].indexOf("SQLSTATE[23000]") != -1) { return 'Error al actualizar el registro.'; } else { return 'Error al actualizar el registro.'; } } }); $('.textoentero99req').editable({ validate: function(value) { if($.trim(value) === '') return 'Este campo es requerido.'; else if ($.isNumeric(value) == '') return 'Solo números permitidos'; else if (value.replace(",", ".") > 99) return 'Este campo no puede ser de mayor de 99.'; else if (value.replace(",", ".") < 1) return 'Este campo no puede ser de menor de 1.'; }, error: function (xhr, status) { var data=xhr.responseText; var jsonResponse = JSON.parse(data); if(jsonResponse["message"].indexOf("SQLSTATE[23000]") != -1) { return 'Error al actualizar el registro.'; } else { return 'Error al actualizar el registro.'; } } }); $('.textoentero99').editable({ validate: function(value) { if ($.isNumeric(value) == '') return 'Solo números permitidos'; else if (value.replace(",", ".") > 99) return 'Este campo no puede ser de mayor de 99.'; else if (value.replace(",", ".") < 1) return 'Este campo no puede ser de menor de 1.'; }, error: function (xhr, status) { var data=xhr.responseText; var jsonResponse = JSON.parse(data); if(jsonResponse["message"].indexOf("SQLSTATE[23000]") != -1) { return 'Error al actualizar el registro.'; } else { return 'Error al actualizar el registro.'; } } }); $('.generoreq').editable({ source: [ {value: 'M', text: 'Masculino'}, {value: 'F', text: 'Femenino'} ], error: function (xhr, status) { var data = xhr.responseText; var jsonResponse = JSON.parse(data); if (jsonResponse["message"].indexOf("SQLSTATE[23000]") != -1) { return 'Debe seleccionar una opción.'; } else { return 'Error al actualizar el registro.'; } } }); $('.fechareq').editable({ format: 'DD/MM/YYYY', viewformat: 'DD/MM/YYYY', template: 'D MMM YYYY', combodate: { minYear: year100, maxYear: year, smartDays: true }, error: function (xhr, status) { var data=xhr.responseText; var jsonResponse = JSON.parse(data); if(jsonResponse["message"].indexOf("Data missing") != -1) { return 'Verifique que el mes seleccionado si tiene ese número de días.'; } else { return 'Error al actualizar el registro.'; } } }); $('.messelect').editable({ source: [ {value: '1', text: 'Enero'}, {value: '2', text: 'Febrero'}, {value: '3', text: 'Marzo'}, {value: '4', text: 'Abril'}, {value: '5', text: 'Mayo'}, {value: '6', text: 'Junio'}, {value: '7', text: 'Julio'}, {value: '8', text: 'Agosto'}, {value: '9', text: 'Septiembre'}, {value: '10', text: 'Octubre'}, {value: '11', text: 'Noviembre'}, {value: '12', text: 'Diciembre'} ], error: function (xhr, status) { var data=xhr.responseText; var jsonResponse = JSON.parse(data); return(jsonResponse["message"]); if(jsonResponse["message"].indexOf("SQLSTATE[23000]") != -1) { return 'Debe seleccionar una opción.'; } else { return 'Error al actualizar el registro.'; } } //,success: function(response, newValue){alert(response.toSource());} }); $('.noaplica').editable({ source: [ {value: '0', text: 'No'}, {value: '1', text: 'Si'}, {value: '2', text: 'No Aplica'} ], error: function (xhr, status) { var data=xhr.responseText; var jsonResponse = JSON.parse(data); if(jsonResponse["message"].indexOf("SQLSTATE[23000]") != -1) { return 'Debe seleccionar una opción.'; } else { return 'Error al actualizar el registro.'; } } }); $('.sino').editable({ source: [ {value: '0', text: 'No'}, {value: '1', text: 'Si'} ], error: function (xhr, status) { var data=xhr.responseText; var jsonResponse = JSON.parse(data); if(jsonResponse["message"].indexOf("SQLSTATE[23000]") != -1) { return 'Debe seleccionar una opción.'; } else { return 'Error al actualizar el registro.'; } } /*, display: function(value, response) { //recreartabla(); //$(this).text(response.new_value); // alert(response.toSource()); }, ,success: function(response, newValue){ recreartabla(); } */ }); $('.tipomantenimiento').editable({ source: [ {value: '0', text: 'Correcctivo'}, {value: '1', text: 'Preventivo'} ], error: function (xhr, status) { var data=xhr.responseText; var jsonResponse = JSON.parse(data); if(jsonResponse["message"].indexOf("SQLSTATE[23000]") != -1) { return 'Debe seleccionar una opción.'; } else { return 'Error al actualizar el registro.'; } } }); } }); function recreartabla(){ //tabla.rows().invalidate('data').draw(true); //datatable.rows().invalidate('data').draw(false); //tabla.rows().invalidate('dom'); } /* tabla.on( 'buttons-action', function ( e, buttonApi, dataTable, node, config ) { // dataTable.rows().invalidate().draw(false); } ); */ }; // X-Editable var _componentXEditable = function() { if (!$().editable) { console.warn('Warning - x-editable.min.js is not loaded.'); return; } // $.fn.editable.defaults.mode = 'inline'; $.fn.editable.defaults.emptytext = 'Vacío'; $.fn.editable.defaults.send = 'always'; $.fn.editable.defaults.clear = false; $.fn.editable.defaults.ajaxOptions = { dataType: 'json' }; $.fn.editable.defaults.params = function (params) { params._token = $("#_token").data("token"); if( $("#tipo").length ) { params.tipo = $("#tipo").val(); } else { params.tipo = $(this).editable().data('tipo'); } if( $(this).editable().data('persona')!='undefined' ) { params.persona = $(this).editable().data('persona'); } return params; }; $('.estadoeditar').on('switchChange.bootstrapSwitch',function(){ var pk = $(this).attr("data-pk"); var estado = $(this).bootstrapSwitch('state'); var name = $(this).attr("data-name"); var url = $(this).attr("data-url"); var tipo = $(this).attr("data-tipo"); var mensaje = ""; var id = $(this).attr("id"); if(estado) { value = 1; mensaje = "Activo";} else { value = 0; mensaje = "Inactivo";} $.ajax({ url: url, method: 'post', data: {pk: pk, value: value, name: name, tipo: tipo, _token: $('input[name="_token"]').val()}, success: function(data){ $("#" + id + "mensaje" + pk).html(''); $("#" + id + "mensajeoculto" + pk).html('' + mensaje + ''); }, error: function (xhr, status) { var data=xhr.responseText; var jsonResponse = JSON.parse(data); $("#" + id + "mensaje" + pk).html('Error'); } }); }); $('.calificacioneditar').on('change',function(){ var pk = $(this).attr("data-pk"); var valor = $(this).val(); var name = $(this).attr("data-name"); var url = $(this).attr("data-url"); var tipo = $(this).attr("data-tipo"); var mensaje = ""; var id = $(this).attr("id"); if(valor=='0') { mensaje = "Sin Calificar";} else { mensaje = valor;} $.ajax({ url: url, method: 'post', data: {pk: pk, value: valor, name: name, tipo: tipo, _token: $('input[name="_token"]').val()}, success: function(data){ $("#" + id + "mensaje").html(''); $("#" + id + "oculto").html('' + mensaje + ''); }, error: function (xhr, status) { var data=xhr.responseText; var jsonResponse = JSON.parse(data); $("#" + id + "mensaje" + pk).html('Error'); } }); }); }; // Bootstrap switch var _componentBootstrapSwitch = function() { if (!$().bootstrapSwitch) { console.warn('Warning - switch.min.js is not loaded.'); return; } // Initialize $('.form-check-input-switch').bootstrapSwitch(); }; // Datepicker var _componentUiDatepicker = function() { if (!$().datepicker) { console.warn('Warning - jQuery UI components are not loaded.'); return; } $.datepicker.regional['es'] = { closeText: 'Cerrar', prevText: '', currentText: 'Hoy', monthNames: ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'], monthNamesShort: ['Ene','Feb','Mar','Abr', 'May','Jun','Jul','Ago','Sep', 'Oct','Nov','Dic'], dayNames: ['Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado'], dayNamesShort: ['Dom','Lun','Mar','Mié','Juv','Vie','Sáb'], dayNamesMin: ['Do','Lu','Ma','Mi','Ju','Vi','Sá'], weekHeader: 'Sm', dateFormat: 'dd/mm/yy', firstDay: 1, isRTL: $('html').attr('dir') == 'rtl' ? true : false, showMonthAfterYear: false, yearSuffix: '', changeMonth: true, changeYear: true }; $.datepicker.setDefaults($.datepicker.regional['es']); // Month and year menu $('.datepicker-nacimiento').datepicker({ yearRange: "-100:+0", minDate: '-100y', maxDate: '0' }) .on('change', function () { formulariotab1.revalidateField(this.id); }); $('.datepicker-nacimiento2').datepicker({ yearRange: "-99:-7", minDate: '-99y', maxDate: '-7y' }) .on('change', function () { formulariotab1.revalidateField(this.id); }); $('.datepicker-encuesta').datepicker({ yearRange: "-100:+100", }) .on('change', function () { formulariotab1.revalidateField(this.id); }); $('.datepicker-fecha').datepicker({ yearRange: "+0:+1", minDate: '-1y', maxDate: '+1y' }) .on('change', function () { formulariotab5.revalidateField(this.id); }); $('.datepicker-fecha2').datepicker({ yearRange: "+0:+1", minDate: '-1y', maxDate: '+1y' }) .on('change', function () { formulariotab1.revalidateField(this.id); }); $('.datepicker-reserva').datepicker({ yearRange: "+0:+1", minDate: '+0', maxDate: '+1y' }) .on('change', function () { formulariotab1.revalidateField(this.id); }); $('.datepicker-diagnostico').datepicker({ yearRange: "-1:+7", minDate: '-1y', maxDate: '+7y' }) .on('change', function () { formulariotab1.revalidateField(this.id); }); $('.datepicker-mantenimiento').datepicker({ yearRange: "+0:+1", minDate: '+0', maxDate: '+3y' }) .on('change', function () { formulariotab1.revalidateField(this.id); }); $('.datepicker-mes').datepicker({ minDate: '-1y', maxDate: '+1y', changeMonth: true, changeYear: true, showButtonPanel: true, dateFormat: 'MM yy', closeText: 'Seleccionar', onClose: function(dateText, inst) { function isDonePressed(){ return ($('#ui-datepicker-div').html().indexOf('ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all ui-state-hover') > -1); } if (isDonePressed()){ var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val(); var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val(); $(this).datepicker('setDate', new Date(year, month, 1)).trigger('change'); $('.date-picker').focusout()//Added to remove focus from datepicker input box on selecting date } }, beforeShow : function(input, inst) { inst.dpDiv.addClass('month_year_datepicker') if ((datestr = $(this).val()).length > 0) { year = datestr.substring(datestr.length-4, datestr.length); month = datestr.substring(0, 2); $(this).datepicker('option', 'defaultDate', new Date(year, month-1, 1)); $(this).datepicker('setDate', new Date(year, month-1, 1)); $(".ui-datepicker-calendar").hide(); } } }) .on('change', function () { formulariotab1.revalidateField(this.id); }); }; // Pickatime picker var _componentPickatime = function() { if (!$().pickatime) { console.warn('Warning - picker.js and/or picker.time.js is not loaded.'); return; } // Default functionality, $('.pickatime-reserva').pickatime({ formatSubmit: 'HH:i', interval: 30, clear: '' }) .on('change', function () { formulariotab1.revalidateField(this.id); }); }; var _componentFullCalendar = function() { if (!$().fullCalendar) { console.warn('Warning - fullcalendar.min.js is not loaded.'); return; } $('.fullcalendar-reservas').fullCalendar({ header: { left: 'prev,next today', center: 'title', right: 'month,basicWeek,basicDay,listMonth' }, locale: 'es', defaultDate: moment(new Date()), editable: true, events: events, eventLimit: true, isRTL: $('html').attr('dir') == 'rtl' ? true : false, eventClick: function(event, jsEvent, view) { $("#divFecha").html(moment(event.start).format('DD/MM/Y')); $("#divHoraInicio").html(event.horainicio); $("#divHoraFin").html(event.horafin); $("#divMotivo").html(event.title); $("#divEstado").html(event.estado); $("#divCopropiedad").html(event.copropiedad); $("#divObservaciones").html(event.observaciones); $('#reserva').val(event.id); $('#modalTab2').modal('show'); if(event.idestado > 2) { $("#info-cambio").hide(); $("#btn-cambiar").hide(); } else { $("#info-cambio").show(); $("#btn-cambiar").show(); } // change the border color just for fun //$(this).css('border-color', 'red'); } }); $('.fullcalendar-reservassinaprobar').fullCalendar({ header: { left: '', center: 'title', right: '' }, views: { siglo: { type: 'list', titleFormat: '[Reservas sin Aprobar]', duration: { years: 200 } } }, defaultDate: moment(new Date()).subtract(100, 'years'), defaultView: 'siglo', editable: true, events: events, eventLimit: false, timeFormat: 'hh:mm A', isRTL: $('html').attr('dir') == 'rtl' ? true : false, eventClick: function(event, jsEvent, view) { $("#divFecha").html(moment(event.start).format('DD/MM/Y')); $("#divHoraInicio").html(event.horainicio); $("#divHoraFin").html(event.horafin); $("#divMotivo").html(event.title); $("#divEstado").html(event.estado); $("#divCopropiedad").html(event.copropiedad); $("#divObservaciones").html(event.observaciones); $('#reserva').val(event.id); $('#modalTab2').modal('show'); if(event.idestado > 2) { $("#info-cambio").hide(); $("#btn-cambiar").hide(); } else { $("#info-cambio").show(); $("#btn-cambiar").show(); } } }); $('.fullcalendar-tareas').fullCalendar({ header: { left: 'prev,next today', center: 'title', right: 'month,agendaWeek,agendaDay,listMonth' }, locale: 'es', defaultDate: moment(new Date()), editable: true, events: events, eventLimit: true, timeFormat: 'hh:mm A', isRTL: $('html').attr('dir') == 'rtl' ? true : false, eventClick: function(event, jsEvent, view) { $("#divFecha").html(moment(event.start).format('DD/MM/Y')); if(event.todo === '0') { $("#divHora").html(' de ' + event.horainicio + ' a ' + event.horafin); } else { $("#divHora").html(' (Todo el día)'); } $("#divTitulo").html(event.title); $("#divCopropiedad").html(event.copropiedad); $("#divDescripcion").html(event.desc); $("#divEstado").html(event.estado); $("#divObservaciones").html(event.observaciones); $('#tarea').val(event.id); $('#modalTab2').modal('show'); if(event.idestado > 6) { $("#info-cambio").hide(); $("#btn-cambiar").hide(); } else { $("#info-cambio").show(); $("#btn-cambiar").show(); } if(event.id==='0') { $("#info-cambio").hide(); $("#btn-cambiar").hide(); $("#Observacionesdiv").hide(); } else { $("#Observacionesdiv").show(); } } }); $('.fullcalendar-plan').fullCalendar({ header: { left: '', center: 'title', right: '' }, views: { siglo: { type: 'list', titleFormat: '[Plan de Trabajo]', duration: { years: 200 } } }, locale: 'es', defaultDate: moment(new Date()).subtract(100, 'years'), defaultView: 'siglo', editable: true, events: events, eventLimit: false, timeFormat: 'hh:mm A', isRTL: $('html').attr('dir') == 'rtl' ? true : false, eventClick: function(event, jsEvent, view) { $("#divFecha").html(moment(event.start).format('DD/MM/Y')); if(event.todo === '0') { $("#divHora").html(' de ' + event.horainicio + ' a ' + event.horafin); } else { $("#divHora").html(' (Todo el día)'); } $("#divTitulo").html(event.title); $("#divCopropiedad").html(event.copropiedad); $("#divDescripcion").html(event.desc); $("#divEstado").html(event.estado); $("#divObservaciones").html(event.observaciones); $('#tarea').val(event.id); $('#modalTab2').modal('show'); if(event.idestado > 6) { $("#info-cambio").hide(); $("#btn-cambiar").hide(); } else { $("#info-cambio").show(); $("#btn-cambiar").show(); } } }); $('.fullcalendar-eventos').fullCalendar({ header: { left: 'prev,next today', center: 'title', right: 'month,agendaWeek,agendaDay,listMonth' }, locale: 'es', defaultDate: moment(new Date()), editable: true, events: events, eventLimit: true, timeFormat: 'hh:mm A', isRTL: $('html').attr('dir') == 'rtl' ? true : false, eventClick: function(event, jsEvent, view) { $("#divFechaInicio").html(moment(event.start).format('DD/MM/Y')); $("#divFechaFin").html(moment(event.end).format('DD/MM/Y')); if(event.todo === '0') { $("#divHoraInicio").html(' a las ' + event.horainicio); $("#divHoraFin").html(' a las ' + event.horafin); } else { $("#divHoraInicio").html(' (Todo el día)'); $("#divHoraFin").html(' (Todo el día)'); } $("#divTipoEvento").html(event.tipo); $("#divTitulo").html(event.title); $("#divCopropiedad").html(event.copropiedad); $("#divDescripcion").html(event.desc); $("#divRoles").html(event.roles); if(event.estado==1) { $("#divEstado").html('Programado'); } else { $("#divEstado").html('Cancelado'); } $('#pk').val(event.id); $('#modalTab2').modal('show'); if(event.estado === '0') { $("#btn-cambiar").hide(); } else { $("#info-cambio").show(); } } }); $('.fullcalendar-presupuesto').fullCalendar({ header: { left: 'prev,next today', center: 'title', right: 'month,basicWeek,basicDay,listMonth' }, locale: 'es', defaultDate: moment(fecha), editable: true, events: events, eventLimit: true, isRTL: $('html').attr('dir') == 'rtl' ? true : false, eventClick: function(event, jsEvent, view) { $("#divFecha").html(moment(event.start).format('DD/MM/Y')); $("#divFechaReal").html(event.fechareal); $("#divTitulo").html(event.title); $("#divValor").html(event.valor); $("#divValorReal").html(event.valorreal); $("#divEstado").html(event.estado); $("#divObservaciones").html(event.desc); $('#idMovimiento').val(event.id); $('#modalTab1').modal('show'); if(event.tipo == 'ingreso') { $("#estadoingreso").show(); $("#estadoegreso").hide(); } else if(event.tipo == 'egreso') { $("#estadoingreso").hide(); $("#estadoegreso").show(); } if(event.idestado > 1) { $("#info-cambio").hide(); $("#btn-cambiar").hide(); } else { $("#info-cambio").show(); $("#btn-cambiar").show(); } } }); }; var _componentStarrr = function() { if (!$().rating) { console.warn('Warning - starrr.js is not loaded.'); return; } $('.star-tabla').rating({ min: 0, max: 5, step: 1, size: "xxs", stars: "5", 'showCaption': true, 'showClear': false }); /* $('#star1').starrr({ max: 10, change: function(e, value){ if (value) { $('#calificacionlabel').text(value); $('#calificacion').val(value); } else { $('#calificacionlabel').text(""); $('#calificacion').val(""); } } }); $('.star2').starrr({ max: 10, rating: parseInt($(this).attr("data-calificacion")), init: alert($('#calificacion' + $(this).attr("id")).text()), change: function(e, value){ if (value) { $('#calificacion' + $(this).attr("id")).text(value); } else { $('#calificacion' + $(this).attr("id")).text(""); } } }); */ }; // Enhanced progress bars var _componentProgress = function() { if (!$().progressbar) { console.warn('Warning - progressbar.min.js is not loaded.'); return; } var $pb = $('#h-fill-basic .progress-bar'); $pb.attr('data-transitiongoal', $pb.attr('data-transitiongoal-backup')); $pb.progressbar({display_text: 'fill'}); }; var _componentFileUpload = function() { if (!$().fileinput) { console.warn('Warning - fileinput.min.js is not loaded.'); return; } // Buttons inside zoom modal var previewZoomButtonClasses = { toggleheader: 'btn btn-light btn-icon btn-header-toggle btn-sm', fullscreen: 'btn btn-light btn-icon btn-sm', borderless: 'btn btn-light btn-icon btn-sm', close: 'btn btn-light btn-icon btn-sm' }; // Icons inside zoom modal classes var previewZoomButtonIcons = { prev: '', next: '', toggleheader: '', fullscreen: '', borderless: '', close: '' }; // File actions var fileActionSettingsExcel = { showZoom: false, // zoomClass: '', // zoomIcon: '', // dragClass: 'p-2', // dragIcon: '', removeClass: '', removeErrorClass: 'text-danger', removeIcon: '', indicatorNew: '', indicatorSuccess: '', indicatorError: '', indicatorLoading: '' }; // Modal template var modalTemplate = '\n'; $('.file-input-excel').fileinput({ allowedFileExtensions: ["xlsx", "xls"], language: 'es', previewFileType: 'image', browseClass: 'btn bg-primary', browseIcon: '', removeClass: 'btn btn-danger', removeIcon: '', uploadClass: 'btn bg-success', uploadIcon: '', // layoutTemplates: { // icon: '', // modal: modalTemplate // }, initialCaption: "Por favor seleccionar un archivo", msgNoFilesSelected: "Por favor selecciona un archivo válido", mainClass: 'input-group', previewZoomButtonClasses: previewZoomButtonClasses, previewZoomButtonIcons: previewZoomButtonIcons, fileActionSettings: fileActionSettingsExcel }); $('.file-input-archivo').fileinput({ allowedFileExtensions: ["xlsx", "xls", "doc", "docx", "ppt", "pptx", "pdf", "jpg", "gif", "png", "txt", "mp3"], language: 'es', // previewFileType: 'image', browseClass: 'btn bg-primary', browseIcon: '', removeClass: 'btn btn-danger', removeIcon: '', uploadClass: 'btn bg-success', uploadIcon: '', initialCaption: "Por favor seleccionar un archivo", msgNoFilesSelected: "Por favor selecciona un archivo válido", mainClass: 'input-group', fileActionSettings: fileActionSettingsExcel }); }; // Uniform var _componentUniform = function() { if (!$().uniform) { console.warn('Warning - uniform.min.js is not loaded.'); return; } // Default initialization $('.form-check-input-styled').uniform(); }; // Return objects assigned to module // return { init: function() { // _componentLoadingButton(); // _componentValidation(); // _componentProgress(); _componentFloatingLabels(); _componentXEditable(); _componentDatatable(); _componentSelect2(); _componentBootstrapSwitch(); _componentUiDatepicker(); _componentPickatime(); _componentFullCalendar(); _componentStarrr(); _componentFileUpload(); _componentUniform(); } } }(); // Initialize module // ------------------------------ document.addEventListener('DOMContentLoaded', function() { Carga.init(); }); function formsubmit(form, btn1, btn2) { loadingText = btn1.data('loading-text'); btn1.html(loadingText).addClass('disabled'); btn2.addClass('disabled'); form.submit(); } function formsubmitnew(form, btn1, btn2) { loadingText = btn1.data('loading-text'); btn1.html(loadingText).addClass('disabled'); btn2.addClass('disabled'); }