Commit inicial

This commit is contained in:
alexrg committed 2024-08-02 12:02:25 -06:00
commit ff7d678844
267 files changed
+101936

No files matched your search

+160
View File
@@ -0,0 +1,160 @@
import { createApp, reactive } from 'https://unpkg.com/petite-vue?module';
const store = reactive({
loading: false,
current: {
comentario: '',
clase_vista: null,
empty: '',
},
facultades: {
data: [],
async fetch() {
this.data = [];
const res = await fetch('action/action_facultad.php');
this.data = await res.json();
},
},
filters: {
facultad_id: null,
fecha: null,
fecha_inicio: null,
fecha_fin: null,
profesor: null,
estados: [],
switchFecha: false,
switchFechas() {
$(function () {
store.filters.fecha_inicio = store.filters.fecha_fin = store.filters.fecha = null;
$("#fecha, #fecha_inicio, #fecha_fin").datepicker({
minDate: -3,
maxDate: new Date(),
dateFormat: "yy-mm-dd",
showAnim: "slide",
});
const fecha = $("#fecha"), inicio = $("#fecha_inicio"), fin = $("#fecha_fin");
inicio.on("change", function () {
store.filters.fecha_inicio = inicio.val();
fin.datepicker("option", "minDate", inicio.val());
});
fin.on("change", function () {
store.filters.fecha_fin = fin.val();
inicio.datepicker("option", "maxDate", fin.val());
});
fecha.on("change", function () {
store.filters.fecha = fecha.val();
});
});
}
},
estados: {
data: [],
async fetch() {
this.data = [];
const res = await fetch('action/action_estado_supervisor.php');
this.data = await res.json();
},
getEstado(id) {
return this.data.find((estado) => estado.estado_supervisor_id === id);
},
printEstados() {
if (store.filters.estados.length > 0)
document.querySelector('#estados').innerHTML = store.filters.estados.map((estado) => `<span class="mx-2 badge badge-${store.estados.getEstado(estado).estado_color}">
<i class="${store.estados.getEstado(estado).estado_icon}"></i> ${store.estados.getEstado(estado).nombre}
</span>`).join('');
else
document.querySelector('#estados').innerHTML = `Todos los registros`;
}
},
toggle(arr, element) {
const newArray = arr.includes(element) ? arr.filter((item) => item !== element) : [...arr, element];
// if all are selected, then unselect all
if (newArray.length === this.estados.data.length)
return [];
return newArray;
},
});
createApp({
store,
get clase_vista() {
return store.current.clase_vista;
},
registros: {
data: [],
async fetch() {
this.loading = true;
this.data = [];
const res = await fetch('action/action_auditoria.php');
this.data = await res.json();
this.loading = false;
},
invertir() {
this.data = this.data.reverse();
},
mostrarComentario(registro_id) {
const registro = this.data.find((registro) => registro.registro_id === registro_id);
store.current.comentario = registro.comentario;
$('#ver-comentario').modal('show');
},
get relevant() {
/*
facultad_id: null,
fecha: null,
fecha_inicio: null,
fecha_fin: null,
profesor: null,
asistencia: null,
estado_id: null,
if one of the filters is null, then it is not relevant
*/
const filters = Object.keys(store.filters).filter((filtro) => store.filters[filtro] || store.filters[filtro]?.length > 0);
return this.data.filter((registro) => {
return filters.every((filtro) => {
switch (filtro) {
case 'fecha':
return registro.registro_fecha_ideal === store.filters[filtro];
case 'fecha_inicio':
return registro.registro_fecha_ideal >= store.filters[filtro];
case 'fecha_fin':
return registro.registro_fecha_ideal <= store.filters[filtro];
case 'profesor':
const textoFiltro = store.filters[filtro].toLowerCase();
if (/^\([^)]+\)\s[\s\S]+$/.test(textoFiltro)) {
const clave = registro.profesor_clave.toLowerCase();
const filtroClave = textoFiltro.match(/\((.*?)\)/)?.[1];
console.log(clave, filtroClave);
return clave.includes(filtroClave);
}
else {
const nombre = registro.profesor_nombre.toLowerCase();
return nombre.includes(textoFiltro);
}
case 'facultad_id':
return registro.facultad_id === store.filters[filtro];
case 'estados':
if (store.filters[filtro].length === 0)
return true;
return store.filters[filtro].includes(registro.estado_supervisor_id);
default:
return true;
}
});
});
},
},
get profesores() {
return this.registros.data.map((registro) => ({
profesor_id: registro.profesor_id,
profesor_nombre: registro.profesor_nombre,
profesor_correo: registro.profesor_correo,
profesor_clave: registro.profesor_clave,
profesor_grado: registro.profesor_grado,
})).sort((a, b) => a.profesor_nombre.localeCompare(b.profesor_nombre));
},
async mounted() {
await this.registros.fetch();
await store.facultades.fetch();
await store.estados.fetch();
store.filters.switchFechas();
}
}).mount('#app');
+41
View File
@@ -0,0 +1,41 @@
function barra(profesor, retardos) {
profesor.faltas = profesor.total - profesor.asistencias - profesor.retardos - profesor.justificaciones;
if (profesor.total != 0)
var porcentajes = {
"asistencias": profesor.asistencias / profesor.total * 100,
"retardos": profesor.retardos / profesor.total * 100,
"justificaciones": profesor.justificaciones / profesor.total * 100,
"faltas": 100 * profesor.faltas / profesor.total
}
else
var porcentajes = {
"asistencias": 0,
"retardos": 0,
"justificaciones": 0,
"faltas": 0
}
var html = `
<section id="profesor-${profesor.id}">
<div class="row">
<div class="col-12">
<div class="progress">
<div class="progress-bar bg-success" role="progressbar" style="width: ${porcentajes.asistencias}%" aria-valuenow="${porcentajes.asistencias}" aria-valuemin="0" aria-valuemax="100"></div>
<!-- Show retardos only if it's set to true -->
${retardos ? `<div class="progress-bar bg-warning" role="progressbar" style="width: ${porcentajes.retardos}%" aria-valuenow="${porcentajes.retardos}" aria-valuemin="0" aria-valuemax="100"></div>` : ``}
<div class="progress-bar bg-azul" role="progressbar" style="width: ${porcentajes.justificaciones}%" aria-valuenow="${porcentajes.justificaciones}" aria-valuemin="0" aria-valuemax="100"></div>
<div class="progress-bar bg-info" role="progressbar" style="width: ${porcentajes.faltas}%" aria-valuenow="${porcentajes.faltas}" aria-valuemin="0" aria-valuemax="100"></div>
</div>
</div>
</div>
<!-- Span Asistencias: # Retardos: # Faltas: # -->
<div class="row justify-content-center">
<span class="mx-3 mt-1">Asistencias: ${profesor.asistencias}</span>
${retardos ? `<span class="mx-3 mt-1">Retardos: ${profesor.retardos}</span>` : `` }
<span class="mx-3 mt-1">Justificaciones: ${profesor.justificaciones}</span>
<span class="mx-3 mt-1">Faltas: ${profesor.faltas}</span>
</div>
</div>
`;
return html;
}
+7
View File
@@ -0,0 +1,7 @@
/*!
* Bootstrap v4.1.3 (https://getbootstrap.com/)
* Copyright 2011-2018 The Bootstrap Authors (https://github.com/twbs/bootstrap/graphs/contributors)
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
*/
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("jquery")):"function"==typeof define&&define.amd?define(["exports","jquery"],t):t(e.bootstrap={},e.jQuery)}(this,function(e,t){"use strict";function i(e,t){for(var n=0;n<t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}function s(e,t,n){return t&&i(e.prototype,t),n&&i(e,n),e}function l(r){for(var e=1;e<arguments.length;e++){var o=null!=arguments[e]?arguments[e]:{},t=Object.keys(o);"function"==typeof Object.getOwnPropertySymbols&&(t=t.concat(Object.getOwnPropertySymbols(o).filter(function(e){return Object.getOwnPropertyDescriptor(o,e).enumerable}))),t.forEach(function(e){var t,n,i;t=r,i=o[n=e],n in t?Object.defineProperty(t,n,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[n]=i})}return r}for(var r,n,o,a,c,u,f,h,d,p,m,g,_,v,y,E,b,w,C,T,S,D,A,I,O,N,k,x,P,L,j,H,M,F,W,R,U,B,q,K,Q,Y,V,z,G,J,Z,X,$,ee,te,ne,ie,re,oe,se,ae,le,ce,ue,fe,he,de,pe,me,ge,_e,ve,ye,Ee,be,we=function(i){var t="transitionend";function e(e){var t=this,n=!1;return i(this).one(l.TRANSITION_END,function(){n=!0}),setTimeout(function(){n||l.triggerTransitionEnd(t)},e),this}var l={TRANSITION_END:"bsTransitionEnd",getUID:function(e){for(;e+=~~(1e6*Math.random()),document.getElementById(e););return e},getSelectorFromElement:function(e){var t=e.getAttribute("data-target");t&&"#"!==t||(t=e.getAttribute("href")||"");try{return document.querySelector(t)?t:null}catch(e){return null}},getTransitionDurationFromElement:function(e){if(!e)return 0;var t=i(e).css("transition-duration");return parseFloat(t)?(t=t.split(",")[0],1e3*parseFloat(t)):0},reflow:function(e){return e.offsetHeight},triggerTransitionEnd:function(e){i(e).trigger(t)},supportsTransitionEnd:function(){return Boolean(t)},isElement:function(e){return(e[0]||e).nodeType},typeCheckConfig:function(e,t,n){for(var i in n)if(Object.prototype.hasOwnProperty.call(n,i)){var r=n[i],o=t[i],s=o&&l.isElement(o)?"element":(a=o,{}.toString.call(a).match(/\s([a-z]+)/i)[1].toLowerCase());if(!new RegExp(r).test(s))throw new Error(e.toUpperCase()+': Option "'+i+'" provided type "'+s+'" but expected type "'+r+'".')}var a}};return i.fn.emulateTransitionEnd=e,i.event.special[l.TRANSITION_END]={bindType:t,delegateType:t,handle:function(e){if(i(e.target).is(this))return e.handleObj.handler.apply(this,arguments)}},l}(t=t&&t.hasOwnProperty("default")?t.default:t),Ce=(n="alert",a="."+(o="bs.alert"),c=(r=t).fn[n],u={CLOSE:"close"+a,CLOSED:"closed"+a,CLICK_DATA_API:"click"+a+".data-api"},f="alert",h="fade",d="show",p=function(){function i(e){this._element=e}var e=i.prototype;return e.close=function(e){var t=this._element;e&&(t=this._getRootElement(e)),this._triggerCloseEvent(t).isDefaultPrevented()||this._removeElement(t)},e.dispose=function(){r.removeData(this._element,o),this._element=null},e._getRootElement=function(e){var t=we.getSelectorFromElement(e),n=!1;return t&&(n=document.querySelector(t)),n||(n=r(e).closest("."+f)[0]),n},e._triggerCloseEvent=function(e){var t=r.Event(u.CLOSE);return r(e).trigger(t),t},e._removeElement=function(t){var n=this;if(r(t).removeClass(d),r(t).hasClass(h)){var e=we.getTransitionDurationFromElement(t);r(t).one(we.TRANSITION_END,function(e){return n._destroyElement(t,e)}).emulateTransitionEnd(e)}else this._destroyElement(t)},e._destroyElement=function(e){r(e).detach().trigger(u.CLOSED).remove()},i._jQueryInterface=function(n){return this.each(function(){var e=r(this),t=e.data(o);t||(t=new i(this),e.data(o,t)),"close"===n&&t[n](this)})},i._handleDismiss=function(t){return function(e){e&&e.preventDefault(),t.close(this)}},s(i,null,[{key:"VERSION",get:function(){return"4.1.3"}}]),i}(),r(document).on(u.CLICK_DATA_API,'[data-dismiss="alert"]',p._handleDismiss(new p)),r.fn[n]=p._jQueryInterface,r.fn[n].Constructor=p,r.fn[n].noConflict=function(){return r.fn[n]=c,p._jQueryInterface},p),Te=(g="button",v="."+(_="bs.button"),y=".data-api",E=(m=t).fn[g],b="active",w="btn",T='[data-toggle^="button"]',S='[data-toggle="buttons"]',D="input",A=".active",I=".btn",O={CLICK_DATA_API:"click"+v+y,FOCUS_BLUR_DATA_API:(C="focus")+v+y+" blur"+v+y},N=function(){function n(e){this._element=e}var e=n.prototype;return e.toggle=function(){var e=!0,t=!0,n=m(this._element).closest(S)[0];if(n){var i=this._element.querySelector(D);if(i){if("radio"===i.type)if(i.checked&&this._element.classList.contains(b))e=!1;else{var r=n.querySelector(A);r&&m(r).removeClass(b)}if(e){if(i.hasAttribute("disabled")||n.hasAttribute("disabled")||i.classList.contains("disabled")||n.classList.contains("disabled"))return;i.checked=!this._element.classList.contains(b),m(i).trigger("change")}i.focus(),t=!1}}t&&this._element.setAttribute("aria-pressed",!this._element.classList.contains(b)),e&&m(this._element).toggleClass(b)},e.dispose=function(){m.removeData(this._element,_),this._element=null},n._jQueryInterface=function(t){return this.each(function(){var e=m(this).datLine truncated
//# sourceMappingURL=bootstrap.bundle.min.js.map
+7
View File
@@ -0,0 +1,7 @@
/*!
* Bootstrap v4.1.3 (https://getbootstrap.com/)
* Copyright 2011-2018 The Bootstrap Authors (https://github.com/twbs/bootstrap/graphs/contributors)
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
*/
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("jquery"),require("popper.js")):"function"==typeof define&&define.amd?define(["exports","jquery","popper.js"],e):e(t.bootstrap={},t.jQuery,t.Popper)}(this,function(t,e,h){"use strict";function i(t,e){for(var n=0;n<e.length;n++){var i=e[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}function s(t,e,n){return e&&i(t.prototype,e),n&&i(t,n),t}function l(r){for(var t=1;t<arguments.length;t++){var o=null!=arguments[t]?arguments[t]:{},e=Object.keys(o);"function"==typeof Object.getOwnPropertySymbols&&(e=e.concat(Object.getOwnPropertySymbols(o).filter(function(t){return Object.getOwnPropertyDescriptor(o,t).enumerable}))),e.forEach(function(t){var e,n,i;e=r,i=o[n=t],n in e?Object.defineProperty(e,n,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[n]=i})}return r}e=e&&e.hasOwnProperty("default")?e.default:e,h=h&&h.hasOwnProperty("default")?h.default:h;var r,n,o,a,c,u,f,d,g,_,m,p,v,y,E,C,T,b,S,I,A,D,w,N,O,k,P,j,H,L,R,x,W,U,q,F,K,M,Q,B,V,Y,z,J,Z,G,$,X,tt,et,nt,it,rt,ot,st,at,lt,ct,ht,ut,ft,dt,gt,_t,mt,pt,vt,yt,Et,Ct,Tt,bt,St,It,At,Dt,wt,Nt,Ot,kt,Pt,jt,Ht,Lt,Rt,xt,Wt,Ut,qt,Ft,Kt,Mt,Qt,Bt,Vt,Yt,zt,Jt,Zt,Gt,$t,Xt,te,ee,ne,ie,re,oe,se,ae,le,ce,he,ue,fe,de,ge,_e,me,pe,ve,ye,Ee,Ce,Te,be,Se,Ie,Ae,De,we,Ne,Oe,ke,Pe,je,He,Le,Re,xe,We,Ue,qe,Fe,Ke,Me,Qe,Be,Ve,Ye,ze,Je,Ze,Ge,$e,Xe,tn,en,nn,rn,on,sn,an,ln,cn,hn,un,fn,dn,gn,_n,mn,pn,vn,yn,En,Cn,Tn,bn,Sn,In,An,Dn,wn,Nn,On,kn,Pn,jn,Hn,Ln,Rn,xn,Wn,Un,qn,Fn=function(i){var e="transitionend";function t(t){var e=this,n=!1;return i(this).one(l.TRANSITION_END,function(){n=!0}),setTimeout(function(){n||l.triggerTransitionEnd(e)},t),this}var l={TRANSITION_END:"bsTransitionEnd",getUID:function(t){for(;t+=~~(1e6*Math.random()),document.getElementById(t););return t},getSelectorFromElement:function(t){var e=t.getAttribute("data-target");e&&"#"!==e||(e=t.getAttribute("href")||"");try{return document.querySelector(e)?e:null}catch(t){return null}},getTransitionDurationFromElement:function(t){if(!t)return 0;var e=i(t).css("transition-duration");return parseFloat(e)?(e=e.split(",")[0],1e3*parseFloat(e)):0},reflow:function(t){return t.offsetHeight},triggerTransitionEnd:function(t){i(t).trigger(e)},supportsTransitionEnd:function(){return Boolean(e)},isElement:function(t){return(t[0]||t).nodeType},typeCheckConfig:function(t,e,n){for(var i in n)if(Object.prototype.hasOwnProperty.call(n,i)){var r=n[i],o=e[i],s=o&&l.isElement(o)?"element":(a=o,{}.toString.call(a).match(/\s([a-z]+)/i)[1].toLowerCase());if(!new RegExp(r).test(s))throw new Error(t.toUpperCase()+': Option "'+i+'" provided type "'+s+'" but expected type "'+r+'".')}var a}};return i.fn.emulateTransitionEnd=t,i.event.special[l.TRANSITION_END]={bindType:e,delegateType:e,handle:function(t){if(i(t.target).is(this))return t.handleObj.handler.apply(this,arguments)}},l}(e),Kn=(n="alert",a="."+(o="bs.alert"),c=(r=e).fn[n],u={CLOSE:"close"+a,CLOSED:"closed"+a,CLICK_DATA_API:"click"+a+".data-api"},f="alert",d="fade",g="show",_=function(){function i(t){this._element=t}var t=i.prototype;return t.close=function(t){var e=this._element;t&&(e=this._getRootElement(t)),this._triggerCloseEvent(e).isDefaultPrevented()||this._removeElement(e)},t.dispose=function(){r.removeData(this._element,o),this._element=null},t._getRootElement=function(t){var e=Fn.getSelectorFromElement(t),n=!1;return e&&(n=document.querySelector(e)),n||(n=r(t).closest("."+f)[0]),n},t._triggerCloseEvent=function(t){var e=r.Event(u.CLOSE);return r(t).trigger(e),e},t._removeElement=function(e){var n=this;if(r(e).removeClass(g),r(e).hasClass(d)){var t=Fn.getTransitionDurationFromElement(e);r(e).one(Fn.TRANSITION_END,function(t){return n._destroyElement(e,t)}).emulateTransitionEnd(t)}else this._destroyElement(e)},t._destroyElement=function(t){r(t).detach().trigger(u.CLOSED).remove()},i._jQueryInterface=function(n){return this.each(function(){var t=r(this),e=t.data(o);e||(e=new i(this),t.data(o,e)),"close"===n&&e[n](this)})},i._handleDismiss=function(e){return function(t){t&&t.preventDefault(),e.close(this)}},s(i,null,[{key:"VERSION",get:function(){return"4.1.3"}}]),i}(),r(document).on(u.CLICK_DATA_API,'[data-dismiss="alert"]',_._handleDismiss(new _)),r.fn[n]=_._jQueryInterface,r.fn[n].Constructor=_,r.fn[n].noConflict=function(){return r.fn[n]=c,_._jQueryInterface},_),Mn=(p="button",y="."+(v="bs.button"),E=".data-api",C=(m=e).fn[p],T="active",b="btn",I='[data-toggle^="button"]',A='[data-toggle="buttons"]',D="input",w=".active",N=".btn",O={CLICK_DATA_API:"click"+y+E,FOCUS_BLUR_DATA_API:(S="focus")+y+E+" blur"+y+E},k=function(){function n(t){this._element=t}var t=n.prototype;return t.toggle=function(){var t=!0,e=!0,n=m(this._element).closest(A)[0];if(n){var i=this._element.querySelector(D);if(i){if("radio"===i.type)if(i.checked&&this._element.classList.contains(T))t=!1;else{var r=n.querySelector(w);r&&m(r).removeClass(T)}if(t){if(i.hasAttribute("disLine truncated
//# sourceMappingURL=bootstrap.min.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"sources":["../../js/src/util.js","../../js/src/alert.js","../../js/src/button.js","../../js/src/carousel.js","../../js/src/collapse.js","../../js/src/dropdown.js","../../js/src/modal.js","../../js/src/tools/sanitizer.js","../../js/src/tooltip.js","../../js/src/popover.js","../../js/src/scrollspy.js","../../js/src/tab.js","../../js/src/toast.js"],"names":["transitionEndEmulator","duration","_this","this","called","$","one","Util","TRANSITION_END","setTimeout","triggerTransitionEnd","getUID","prefix","Math","random","document","getElementById","getSelectorFromElement","element","selector","getAttribute","hrefAttr","trim","querySelector","err","getTransitionDurationFromElement","transitionDuration","css","transitionDelay","floatTransitionDuration","parseFloat","floatTransitionDelay","split","reflow","offsetHeight","trigger","supportsTransitionEnd","Boolean","isElement","obj","nodeType","typeCheckConfig","componentName","config","configTypes","property","Object","prototype","hasOwnProperty","call","expectedTypes","value","valueType","toString","match","toLowerCase","RegExp","test","Error","toUpperCase","findShadowRoot","documentElement","attachShadow","getRootNode","root","ShadowRoot","parentNode","jQueryDetection","TypeError","version","fn","jquery","emulateTransitionEnd","event","special","bindType","delegateType","handle","target","is","handleObj","handler","apply","arguments","NAME","JQUERY_NO_CONFLICT","Alert","_element","close","rootElement","_getRootElement","_triggerCloseEvent","isDefaultPrevented","_removeElement","dispose","removeData","parent","closest","closeEvent","Event","removeClass","hasClass","_destroyElement","detach","remove","_jQueryInterface","each","$element","data","_handleDismiss","alertInstance","preventDefault","on","Constructor","noConflict","Button","toggle","triggerChangeEvent","addAriaPressed","input","type","checked","classList","contains","activeElement","focus","hasAttribute","setAttribute","toggleClass","button","initialButton","inputBtn","tagName","window","buttons","slice","querySelectorAll","i","len","length","add","EVENT_KEY","Default","interval","keyboard","slide","pause","wrap","touch","DefaultType","PointerType","TOUCH","PEN","Carousel","_items","_interval","_activeElement","_isPaused","_isSliding","touchTimeout","touchStartX","touchDeltaX","_config","_getConfig","_indicatorsElement","_touchSupported","navigator","maxTouchPoints","_pointerEvent","PointerEvent","MSPointerEvent","_addEventListeners","next","_slide","nextWhenVisible","hidden","prev","cycle","clearInterval","setInterval","visibilityState","bind","to","index","activeIndex","_getItemIndex","direction","off","_objectSpread2","_handleSwipe","absDeltax","abs","_this2","_keydown","_addTouchEventListeners","_this3","start","originalEvent","pointerType","clientX","touches","end","clearTimeout","e","move","which","indexOf","_getItemByDirection","isNextDirection","isPrevDirection","lastItemIndex","itemIndex","_triggerSlideEvent","relatedTarget","eventDirectionName","targetIndex","fromIndex","slideEvent","from","_setActiveIndicatorElement","indicators","nextIndicator","children","addClass","directionalClassName","orderClassName","_this4","activeElementIndex","nextElement","nextElementIndex","isCycling","slidEvent","nextElementInterval","parseInt","defaultInterval","CLASS_NAME_ACTIVE","action","ride","_dataApiClickHandler","slideIndex","carousels","$carousel","Collapse","_isTransitioning","_triggerArray","id","toggleList","elem","filterElement","filter","foundElem","_selector","push","_parent","_getParent","_addAriaAndCollapsedClass","hide","show","actives","activesData","not","startEvent","dimension","_getDimension","style","attr","setTransitioning","scrollSize","CLASS_NAME_COLLAPSE","getBoundingClientRect","triggerArrayLength","isTransitioning","_getTargetFromElement","triggerArray","isOpen","$this","currentTarget","$trigger","selectors","$target","REGEXP_KEYDOWN","ARROW_UP_KEYCODE","offset","flip","boundary","reference","display","popperConfig","Dropdown","_popper","_menu","_getMenuElement","_inNavbar","_detectNavbar","disabled","isActive","_clearMenus","usePopper","showEvent","_getParentFromElement","Popper","referenceElement","_getPopperConfig","body","noop","hideEvent","destroy","update","scheduleUpdate","stopPropagation","constructor","_getPlacement","$parentDropdown","placement","_getOffset","offsets","modifiers","enabled","preventOverflow","boundariesElement","applyStyle","toggles","context","clickEvent","dropdownMenu","_dataApiKeydownHandler","items","item","EVENT_CLICK_DATA_API","backdrop","Modal","_dialog","_backdrop","_isShown","_isBodyOverflowing","_ignoreBackdropClick","_scrollbarWidth","_checkScrollbar","_setScrollbar","_adjustDialog","_setEscapeEvent","_setResizeEvent","_showBackdrop","_showElement","transition","_hideModal","forEach","htmlElement","handleUpdate","_triggerBackdropTransition","hideEventPrevented","defaultPrevented","modalTransitionDuration","modalBody","Node","ELEMENT_NODELine truncated
+5
View File
@@ -0,0 +1,5 @@
/*
Copyright (C) Federico Zivolo 2018
Distributed under the MIT License (license terms are at http://opensource.org/licenses/MIT).
*/(function(e,t){'object'==typeof exports&&'undefined'!=typeof module?module.exports=t():'function'==typeof define&&define.amd?define(t):e.Popper=t()})(this,function(){'use strict';function e(e){return e&&'[object Function]'==={}.toString.call(e)}function t(e,t){if(1!==e.nodeType)return[];var o=e.ownerDocument.defaultView,n=o.getComputedStyle(e,null);return t?n[t]:n}function o(e){return'HTML'===e.nodeName?e:e.parentNode||e.host}function n(e){if(!e)return document.body;switch(e.nodeName){case'HTML':case'BODY':return e.ownerDocument.body;case'#document':return e.body;}var i=t(e),r=i.overflow,p=i.overflowX,s=i.overflowY;return /(auto|scroll|overlay)/.test(r+s+p)?e:n(o(e))}function r(e){return 11===e?re:10===e?pe:re||pe}function p(e){if(!e)return document.documentElement;for(var o=r(10)?document.body:null,n=e.offsetParent||null;n===o&&e.nextElementSibling;)n=(e=e.nextElementSibling).offsetParent;var i=n&&n.nodeName;return i&&'BODY'!==i&&'HTML'!==i?-1!==['TH','TD','TABLE'].indexOf(n.nodeName)&&'static'===t(n,'position')?p(n):n:e?e.ownerDocument.documentElement:document.documentElement}function s(e){var t=e.nodeName;return'BODY'!==t&&('HTML'===t||p(e.firstElementChild)===e)}function d(e){return null===e.parentNode?e:d(e.parentNode)}function a(e,t){if(!e||!e.nodeType||!t||!t.nodeType)return document.documentElement;var o=e.compareDocumentPosition(t)&Node.DOCUMENT_POSITION_FOLLOWING,n=o?e:t,i=o?t:e,r=document.createRange();r.setStart(n,0),r.setEnd(i,0);var l=r.commonAncestorContainer;if(e!==l&&t!==l||n.contains(i))return s(l)?l:p(l);var f=d(e);return f.host?a(f.host,t):a(e,d(t).host)}function l(e){var t=1<arguments.length&&void 0!==arguments[1]?arguments[1]:'top',o='top'===t?'scrollTop':'scrollLeft',n=e.nodeName;if('BODY'===n||'HTML'===n){var i=e.ownerDocument.documentElement,r=e.ownerDocument.scrollingElement||i;return r[o]}return e[o]}function f(e,t){var o=2<arguments.length&&void 0!==arguments[2]&&arguments[2],n=l(t,'top'),i=l(t,'left'),r=o?-1:1;return e.top+=n*r,e.bottom+=n*r,e.left+=i*r,e.right+=i*r,e}function m(e,t){var o='x'===t?'Left':'Top',n='Left'==o?'Right':'Bottom';return parseFloat(e['border'+o+'Width'],10)+parseFloat(e['border'+n+'Width'],10)}function h(e,t,o,n){return J(t['offset'+e],t['scroll'+e],o['client'+e],o['offset'+e],o['scroll'+e],r(10)?parseInt(o['offset'+e])+parseInt(n['margin'+('Height'===e?'Top':'Left')])+parseInt(n['margin'+('Height'===e?'Bottom':'Right')]):0)}function c(e){var t=e.body,o=e.documentElement,n=r(10)&&getComputedStyle(o);return{height:h('Height',t,o,n),width:h('Width',t,o,n)}}function g(e){return le({},e,{right:e.left+e.width,bottom:e.top+e.height})}function u(e){var o={};try{if(r(10)){o=e.getBoundingClientRect();var n=l(e,'top'),i=l(e,'left');o.top+=n,o.left+=i,o.bottom+=n,o.right+=i}else o=e.getBoundingClientRect()}catch(t){}var p={left:o.left,top:o.top,width:o.right-o.left,height:o.bottom-o.top},s='HTML'===e.nodeName?c(e.ownerDocument):{},d=s.width||e.clientWidth||p.right-p.left,a=s.height||e.clientHeight||p.bottom-p.top,f=e.offsetWidth-d,h=e.offsetHeight-a;if(f||h){var u=t(e);f-=m(u,'x'),h-=m(u,'y'),p.width-=f,p.height-=h}return g(p)}function b(e,o){var i=2<arguments.length&&void 0!==arguments[2]&&arguments[2],p=r(10),s='HTML'===o.nodeName,d=u(e),a=u(o),l=n(e),m=t(o),h=parseFloat(m.borderTopWidth,10),c=parseFloat(m.borderLeftWidth,10);i&&s&&(a.top=J(a.top,0),a.left=J(a.left,0));var b=g({top:d.top-a.top-h,left:d.left-a.left-c,width:d.width,height:d.height});if(b.marginTop=0,b.marginLeft=0,!p&&s){var y=parseFloat(m.marginTop,10),w=parseFloat(m.marginLeft,10);b.top-=h-y,b.bottom-=h-y,b.left-=c-w,b.right-=c-w,b.marginTop=y,b.marginLeft=w}return(p&&!i?o.contains(l):o===l&&'BODY'!==l.nodeName)&&(b=f(b,o)),b}function y(e){var t=1<arguments.length&&void 0!==arguments[1]&&arguments[1],o=e.ownerDocument.documentElement,n=b(e,o),i=J(o.clientWidth,window.innerWidth||0),r=J(o.clientHeight,window.innerHeight||0),p=t?0:l(o),s=t?0:l(o,'left'),d={top:p-n.top+n.marginTop,left:s-n.left+n.marginLeft,width:i,height:r};return g(d)}function w(e){var n=e.nodeName;return'BODY'===n||'HTML'===n?!1:'fixed'===t(e,'position')||w(o(e))}function E(e){if(!e||!e.parentElement||r())return document.documentElement;for(var o=e.parentElement;o&&'none'===t(o,'transform');)o=o.parentElement;return o||document.documentElement}function v(e,t,i,r){var p=4<arguments.length&&void 0!==arguments[4]&&arguments[4],s={top:0,left:0},d=p?E(e):a(e,t);if('viewport'===r)s=y(d,p);else{var l;'scrollParent'===r?(l=n(o(t)),'BODY'===l.nodeName&&(l=e.ownerDocument.documentElement)):'window'===r?l=e.ownerDocument.documentElement:l=r;var f=b(l,d,p);if('HTML'===l.nodeName&&!w(d)){var m=c(e.ownerDocument),h=m.height,g=m.width;s.top+=f.top-f.marginTop,s.bottom=h+f.top,s.left+=f.left-f.marginLeft,s.right=g+f.left}else s=f}i=i||0;var u='number'==typeof i;return s.left+=u?i:i.left||0,s.top+=u?i:i.top||0,s.right-=u?i:i.right||0,s.bottom-=u?i:i.bottom||0,s}function x(e){var t=e.width,o=e.height;return t*o}function O(e,t,o,n,i){var r=5<arLine truncated
//# sourceMappingURL=popper.min.js.map
+599
View File
@@ -0,0 +1,599 @@
var msgTime = 0;
var modalVisible = false;
var ultimos = [];
var checkInterval = null;
function az(i) {
return `${i < 10 ? '0' : ''}${i}`;
}
function init() {
setInterval(function () {
var current_time = new Date().getTime();
var excecution_time = parseInt((current_time - started_at) / 1000);
var s = new Date((server_time + excecution_time) * 1000);
drawClock(az(s.getHours()), az(s.getMinutes()));
drawFecha(az(s.getDate()), s.getDay(), s.getMonth(), s.getFullYear());
}, 1000);
}
function drawClock(hora, min) {
$('#min').text(min);
$('#hr').text(hora);
}
function drawFecha(dd, dnum, mm, yyyy) {
var meses = ['Ene', 'Feb', 'Mzo', 'Abr', 'May', 'Jun', 'Jul', 'Ago', 'Sep', 'Oct', 'Nov', 'Dic'];
$('#fecha').text(' ' + meses[mm] + ' ' + dd);
$('#ano').text(yyyy);
}
function modalTimer() {
if (checkInterval === null) {//no es error de internet
setTimeout(function () {
$(".sub-bloque ").addClass("d-none");
$("#registro").removeClass("d-none");
$("#cve").focus();
}
, 7000 + msgTime);
}
}
//--Sin conexión de internet ---
function checadorAlive() {
if (checkInterval == null) {
checkInterval = setInterval(isAlive, 2500);
}
}
function isAlive() {
var alive = false;
try {
$.ajax({
url: 'checador_alive.php',
type: 'POST',
dataType: 'json',
async: false,
timeout: 500,/*ms*/
success: function (result) {
if (result["ok"] != "" && result["ok"] !== undefined) {
cambiaVista('.sub-bloque', '#registro');
$('#db-error').text(result.error);
$("#cve").focus();
alive = true;
clearInterval(checkInterval);
checkInterval = null;
}
},
error: function (jqXHR, textStatus, errorThrown) {
console.log("Sin internet");
}
});//ajax*/
} catch (e) {
console.log("error! ", e);
}
return alive;
}
//--Fin sin conexión de internet ---
function cambiaVista(objHide, objShow) {
$(objHide).addClass("d-none");
$(objShow).removeClass("d-none");
}
function showAviso(avisos) {
cambiaVista('#registro', '#avisos');
const lista = document.querySelector('#lista-avisos');
lista.innerHTML = '';
avisos.forEach(({ aviso_texto: texto }) => {
const li = document.createElement('li');
li.innerHTML = texto;
lista.appendChild(li);
});
}
/*
$('#formaChecador').on('submit', function (e) {
e.preventDefault();
var clave = $("#cve").val();
console.log("clave: ", clave);
$.ajax({
url: 'checador_action.php',
type: 'POST',
dataType: 'json',
data: { cve: $("#cve").val(), facultad: $("#facultad_id").val() },
timeout: 3500,
success: function (result) {
if ((result?.error ?? "") != "") {
console.log(result["error"]);
// avisos
// alert("here")
if (result.nombre != undefined && result.ok == undefined) {
showAviso(result.avisos);
return
cambiaVista('#registro', '#result_no');
$("#nombre-profesor").text(result["nombre"]);
$('#result_no .clave').text(clave);
$("#last-error").text(result["error"]);
}
else if(result.nombre == undefined) {
cambiaVista('#registro', '#not_in_db');
$('#clave-no-encontrada').html(clave);
} else
cambiaVista('#registro', '#internet');
return;
}
$("#list-result").find(".mat-desc").html("");
$("#list-result").find(".mat-fecha").html("");
$("#list-result").find(".mat-salon").html("");
$("#list-result").find(".mat-gpo").html("");
$("#nombre").html(result["nombre"]);
var rows = $("#list-result > li").length;//limpia tabla actual
var resultRows = 0;
//nuevas
if (result["result"] !== undefined && result["result"] != null) resultRows += result["result"].length;
//viejas
if (result["asistencias"] !== undefined && result["asistencias"] != null) resultRows += result["asistencias"].length;
if (rows > resultRows) {//sobran
//borrar renglones extra (rows - result.length) pero dejar al menos 1
while (rows > resultRows && rows > 1) {
$("#list-result li:last-child").remove();
rows--;
}
} else {//faltan, clonar
for (var i = rows; i < resultRows; i++) {
$("#list-result li:first-child").clone(true).appendTo("#list-result");
}
}
//----------
var retardo = false;
//hay elementos checado nuevo?
if (result["result"] !== undefined && result["result"] != null && result["result"].length != 0) {
cambiaVista('#registro', '#result_ok');
$("#list-result").children().each(function (index) {
if (index < result["result"].length) {//llenar info
if (result["result"][index]["grupo"] != "") {
if (result["result"][index]["retardo"]) {
retardo = true;
} else {
retardo = false;
}
$(this).find(".mat-gpo").html("<b>Grupo:</b> " + result["result"][index]["grupo"]);
}
$(this).find(".mat-desc").html(result["result"][index]["materia"]);
$(this).find(".mat-fecha").html("Inicia " + result["result"][index]["hora_inicio"]);
if (result["result"][index]["salon"] != "")
$(this).find(".mat-salon").html("<b>Salón:</b> " + result["result"][index]["salon"]);
//else $(this).find(".mat-salon").html("");
}
});
}
var texto = "";
//hay elementos checado anterior?
if (result["asistencias"] !== undefined && result["asistencias"] != null && result["asistencias"].length != 0) {
cambiaVista('#registro', '#result_ok');
$("#list-result").children().each(function (index) {
if (index < result["asistencias"].length) {//llenar info
if (result["asistencias"][index]["grupo"] != "") {
if (result["asistencias"][index]["retardo"]) {
retardo = true;
} else {
retardo = false;
}
$(this).find(".mat-gpo").html("<b>Grupo:</b> " + result["asistencias"][index]["grupo"]);
}
$(this).find(".mat-desc").html(result["asistencias"][index]["materia"]);
$(this).find(".mat-fecha").html("Inicia " + result["asistencias"][index]["hora_inicio"]);
texto = "<span style=font-size:50%>" +
"Ya estaba registrada" +
"</span>"
if (result["asistencias"][index]["salon"] !== undefined && result["asistencias"][index]["salon"] != "")
$(this).find(".mat-salon").html("<b>Salón:</b> " + result["asistencias"][index]["salon"]);
}
});
}
console.log(texto);
if (retardo) {
$("#estado").find("img").prop("src", "imagenes/retardo.svg");
$("#estado").find("h2").text("Retardo").removeClass("text-success text-blue").addClass("text-warning");
} else {
$("#estado").find("img").prop("src", "imagenes/asistencia.svg");
if (texto == "")
$("#estado").find("h2").text("Asistencia").removeClass("text-warning text-blue").addClass("text-success");
else
$("#estado").find("h2").html("Asistencia<br>" + texto).removeClass("text-warning text-success").addClass("text-blue");
}
if (result.nombre.replace(/ /g, '') == "") {
// if (false) {
console.log(clave)
cambiaVista('#registro', '#not_in_db');
$("#clave-no-encontrada").html(clave);
} else if (resultRows == 0) {
console.log(result)
//$("#nombre-profesor").text(result["nombre"]);
cambiaVista('#registro', '#result_no');
}
},
error: function (jqXHR, textStatus, errorThrown) {
cambiaVista('#registro', '#internet');
$('#db-error').text(textStatus);
checadorAlive();//Muestra mensaje sin internet y comienza a checar hasta que haya
},
complete: function (jqXHR, textStatus) {
$("#cve").val('');
modalTimer();
}
});
});
*/
document.querySelector('#formaChecador').addEventListener('submit', async (e) => {
e.preventDefault();
const clave = document.querySelector('#cve');
if (clave.value == '') {
clave.focus(); return;
}
const data = new FormData();
data.append('cve', clave.value);
// try {
const result = await fetch('https://checadores.lci.ulsa.mx/action_checador.php', {
method: 'POST',
body: data
}).then(response => response.json());
if (!result.ok) {
function not_int_db(clave) {
cambiaVista('#registro', '#not_in_db');
document.querySelector('#clave-no-encontrada').innerHTML = clave;
}
function not_has_horario(nombre_profesor, from = '#registro') {
cambiaVista(from, '#result_no');
document.querySelector('#nombre-profesor').innerHTML = nombre_profesor;
}
switch (result.failure) {
case 'profesor':
not_int_db(clave.value);
break;
case 'horario':
let from;
if (result.avisos.length > 0) {
await show_avisos(result.avisos)
from = '#avisos';
}
else
from = '#registro';
not_has_horario(result.nombre, from);
break;
default:
alert('La clave no es válida');
location.reload();
}
setTimeout(() => {
location.reload();
}, 5000);
return;
}
function show_avisos(avisos) {
return new Promise(resolve => {
if (avisos.length == 0) {
resolve();
return;
}
const lista_avisos = document.querySelector('#lista-avisos');
avisos.forEach(aviso => lista_avisos.innerHTML += `<p>${aviso}</p><hr>`);
cambiaVista('#registro', '#avisos');
//$('#btn-aceptar-avisos').focus();
document.querySelector('#btn-aceptar-avisos').addEventListener('click', () => {
lista_avisos.innerHTML = '';
resolve();
});
});
}
function show_asistencia(nombre, horarios, from) {
cambiaVista(from, '#result_ok');
document.querySelector('#nombre').innerHTML = nombre;
const list_result = document.querySelector('#list-result');
const li_facultad_nombre = list_result.children[0];
const li_element = list_result.children[1];
list_result.innerHTML = '';
// foreach key is facultad (string), value
for (let facultad_nombre in horarios) {
let facultad = li_facultad_nombre.cloneNode(true);
facultad.innerHTML = facultad_nombre;
facultad = list_result.appendChild(facultad);
horarios[facultad_nombre].forEach(horario => {
console.log(horario);
let li = li_element.cloneNode(true);
li = list_result.appendChild(li);
li.querySelector(".mat-desc").innerHTML = horario.materia;
li.querySelector(".mat-fecha").innerHTML = `Inicia ${horario.horario_hora.slice(0, -3)}`;
li.querySelector(".salon").innerHTML = horario.salon;
li.querySelector(".mat-gpo").innerHTML = horario.horario_grupo;
})
}
}
function show_duplicadas(nombre, horarios, from) {
show_asistencia(nombre, horarios, from);
texto = `<span style=font-size:50%>
Ya estaba registrada
</span>`
document.querySelector('#estado').querySelector('img').src = 'imagenes/asistencia.svg';
$("#estado").find(".text-big").html("Asistencia<br>" + texto).removeClass("text-warning text-success").addClass("text-blue");
const estado = document.querySelector('#estado');
const h2 = estado.querySelector('.text-big');
h2.innerHTML = `Asistencia<br>${texto}`;
h2.classList.remove('text-warning', 'text-success');
}
function show_retardos(nombre, horarios, from) {
show_asistencia(nombre, horarios, from);
texto = `Retardo`;
const estado = document.querySelector('#estado');
const h2 = estado.querySelector('#asistencia');
h2.innerHTML = `Retardo`;
h2.classList.remove('text-success', 'text-blue');
h2.classList.add('text-warning');
estado.querySelector('img').src = 'imagenes/retardo.svg';
}
const { horarios, duplicadas, avisos } = result;
const { profesor_nombre } = result.profesor;
let retardos = {}, asistencia = {};
// if any horario has retardo = true horarios is an object with facultad as key
if (Object.values(horarios).some(horario => horario.some(h => h.registro_retardo)))
retardos = horarios;
// if any horario has duplicada = true horarios is an object with facultad as key
else
asistencia = horarios;
console.log(retardos, asistencia, avisos, duplicadas);
// Mostrar avisos
await show_avisos(avisos);
const from = avisos.length > 0 ? '#avisos' : '#registro';
// IF DUPLICADAS HAS ELEMENTS (JSON OBJECT)
if (Object.keys(duplicadas).length > 0)
show_duplicadas(profesor_nombre, duplicadas, from);
else if (Object.keys(retardos).length > 0)
show_retardos(profesor_nombre, retardos, from);
else
show_asistencia(profesor_nombre, asistencia, from);
// setTimeout(() => {
// location.reload();
// }, 5000);
/*} catch (error) {
console.log(error);
cambiaVista('.sub-bloque', '#internet');
checadorAlive(); //Muestra mensaje sin internet y comienza a checar hasta que haya
} */
// finally {
setTimeout(() => {
location.reload();
}, 5000);
// }
});
/*
async function test(type) {
let url;
switch (type) {
case 'retardo':
url = 'json/retardo.json';
break;
case 'duplicada':
url = 'json/duplicada.json';
break;
case 'asistencia':
url = 'json/asistencia.json';
break;
case 'sin_servicio':
url = 'json/no-internet.json';
break;
case 'error':
url = 'json/error.json';
break;
case 'internet':
url = 'json/internet.json';
break;
case 'sin_horario':
url = 'json/sin-horario.json';
break;
case 'clave':
url = 'json/clave-no-encontrada.json';
break;
case 'ok':
url = 'json/asistencia-aviso.json';
break;
case 'sin_horario_aviso':
url = 'json/sin-horario-aviso.json';
break;
}
try {
const result = await fetch(url).then(response => response.json());
if (!result.ok) {
const clave = { value: '123456' }
function not_int_db(clave) {
cambiaVista('#registro', '#not_in_db');
document.querySelector('#clave-no-encontrada').innerHTML = clave;
}
function not_has_horario(nombre_profesor, from = '#registro') {
cambiaVista(from, '#result_no');
document.querySelector('#nombre-profesor').innerHTML = nombre_profesor;
}
switch (result.failure) {
case 'profesor':
not_int_db(clave.value);
break;
case 'horario':
let from;
if (result.avisos.length > 0) {
await show_avisos(result.avisos)
from = '#avisos';
}
else
from = '#registro';
not_has_horario(result.nombre, from);
break;
case 'internet':
cambiaVista('#registro', '#internet');
break;
}
setTimeout(() => {
location.reload();
}, 5000);
return;
}
function show_avisos(avisos) {
return new Promise(resolve => {
if (avisos.length == 0) {
resolve();
return;
}
const lista_avisos = document.querySelector('#lista-avisos');
avisos.forEach(aviso => lista_avisos.innerHTML += `<p>${aviso}</p><hr>`);
cambiaVista('#registro', '#avisos');
//$('#btn-aceptar-avisos').focus();
document.querySelector('#btn-aceptar-avisos').addEventListener('click', () => {
lista_avisos.innerHTML = '';
resolve();
});
});
}
function show_asistencia(nombre, horarios, from) {
cambiaVista(from, '#result_ok');
document.querySelector('#nombre').innerHTML = nombre;
const list_result = document.querySelector('#list-result');
const li_facultad_nombre = list_result.children[0];
const li_element = list_result.children[1];
list_result.innerHTML = '';
// foreach key is facultad (string), value
for (let facultad_nombre in horarios) {
console.log(horarios[facultad_nombre]);
let facultad = li_facultad_nombre.cloneNode(true);
facultad.innerHTML = facultad_nombre;
facultad = list_result.appendChild(facultad);
horarios[facultad_nombre].forEach(horario => {
let li = li_element.cloneNode(true);
li = list_result.appendChild(li);
li.querySelector(".mat-desc").innerHTML = horario.materia;
li.querySelector(".mat-fecha").innerHTML = `Inicia ${horario.horario_hora.slice(0, -3)}`;
li.querySelector(".salon").innerHTML = horario.horario_salon;
li.querySelector(".mat-gpo").innerHTML = horario.horario_grupo;
})
}
const estado = document.querySelector('#estado');
estado.querySelector('img').src = 'imagenes/asistencia.svg';
const h2 = estado.querySelector('.text-big');
h2.innerHTML = `Asistencia registrada`;
h2.classList.remove('text-warning', 'text-success', 'txt-blue');
h2.classList.add('text-success');
}
function show_duplicadas(nombre, horarios, from) {
show_asistencia(nombre, horarios, from);
texto = `<span style=font-size:50%>
Ya estaba registrada
</span>`
document.querySelector('#estado').querySelector('img').src = 'imagenes/duplicada.svg';
$("#estado").find(".text-big").html("Asistencia<br>" + texto).removeClass("text-warning text-success").addClass("text-blue");
const estado = document.querySelector('#estado');
const h2 = estado.querySelector('.text-big');
h2.innerHTML = `Asistencia<br>${texto}`;
h2.classList.remove('text-warning', 'text-success');
}
function show_retardos(nombre, horarios, from) {
show_asistencia(nombre, horarios, from);
texto = `Retardo`;
const estado = document.querySelector('#estado');
const h2 = estado.querySelector('.text-big');
h2.innerHTML = `Retardo`;
h2.classList.remove('text-success', 'text-blue');
h2.classList.add('text-warning');
estado.querySelector('img').src = 'imagenes/retardo.svg';
}
const { horarios, duplicadas, avisos } = result;
const { nombre } = result.profesor;
let retardos = {}, asistencia = {};
// if any horario has retardo = true horarios is an object with facultad as key
if (Object.values(horarios).some(horario => horario.some(h => h.retardo)))
retardos = horarios;
// if any horario has duplicada = true horarios is an object with facultad as key
else
asistencia = horarios;
console.log(retardos, asistencia, avisos, duplicadas);
// Mostrar avisos
await show_avisos(avisos);
const from = avisos.length > 0 ? '#avisos' : '#registro';
// IF DUPLICADAS HAS ELEMENTS (JSON OBJECT)
if (Object.keys(duplicadas).length > 0)
show_duplicadas(nombre, duplicadas, from);
else if (Object.keys(retardos).length > 0)
show_retardos(nombre, retardos, from);
else
show_asistencia(nombre, asistencia, from);
// setTimeout(() => {
// location.reload();
// }, 5000);
} catch (error) {
console.log(error);
cambiaVista('.sub-bloque', '#error_bd');
checadorAlive(); //Muestra mensaje sin internet y comienza a checar hasta que haya
}
finally {
setTimeout(() => {
location.reload();
}, 5000);
}
}
*/
+120
View File
@@ -0,0 +1,120 @@
// @ts-ignore Import module
import { createApp, reactive } from 'https://unpkg.com/petite-vue?module';
const webServices = {
getPeriodosV1: async () => {
try {
const response = await fetch('periodos.v1.php');
return await response.json();
}
catch (error) {
console.log(error);
return [];
}
},
getPeriodosV2: async () => {
try {
const response = await fetch('periodos.v2.php');
return await response.json();
}
catch (error) {
console.log(error);
return [];
}
}
};
const store = reactive({
periodosV1: [],
periodosV2: [],
errors: [],
fechas(idPeriodo) {
const periodo = this.periodosV2.find((periodo) => periodo.IdPeriodo === idPeriodo);
return {
inicio: periodo ? periodo.FechaInicio : '',
fin: periodo ? periodo.FechaFin : ''
};
},
periodov1(idPeriodo) {
return this.periodosV1.find((periodo) => periodo.IdPeriodo === idPeriodo);
},
periodov2(idPeriodo) {
return this.periodosV2.filter((periodo) => periodo.IdPeriodo === idPeriodo);
},
async addPeriodo(periodo) {
try {
const result = await fetch('backend/periodos.php', {
method: 'POST',
body: JSON.stringify({
...periodo,
...this.fechas(periodo.IdPeriodo)
}),
headers: {
'Content-Type': 'application/json'
}
}).then((response) => response.json());
if (result.success) {
this.periodosV1 = this.periodosV1.map((periodoV1) => {
if (periodoV1.IdPeriodo === periodo.IdPeriodo) {
periodoV1.in_db = true;
}
return periodoV1;
});
return result;
}
else {
this.errors.push(result.message);
}
}
catch (error) {
this.errors.push(error);
}
},
async addCarreras(idPeriodo) {
try {
const periodoV1 = this.periodov1(idPeriodo);
const periodoV2 = this.periodov2(idPeriodo);
const data = periodoV2.map(({ ClaveCarrera, NombreCarrera }) => ({
ClaveCarrera: ClaveCarrera,
NombreCarrera: NombreCarrera,
IdNivel: periodoV1.IdNivel,
}));
const result = await fetch('backend/carreras.php', {
method: 'POST',
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json'
}
}).then((response) => response.json());
if (result.success) {
await webServices.getPeriodosV1().then((periodosV1) => {
this.periodosV1 = periodosV1;
});
await webServices.getPeriodosV2().then((periodosV2) => {
this.periodosV2 = periodosV2;
});
}
}
catch (error) {
this.errors.push(error);
}
}
});
createApp({
store,
info(IdPeriodo) {
const periodo = store.periodosV2.find((periodo) => periodo.IdPeriodo === IdPeriodo &&
periodo.FechaInicio != '' && periodo.FechaFin != '');
return periodo;
},
complete(IdPeriodo) {
const info = this.info(IdPeriodo);
return info !== undefined;
},
mounted: async () => {
await webServices.getPeriodosV1().then((periodosV1) => {
store.periodosV1 = periodosV1;
});
await webServices.getPeriodosV2().then((periodosV2) => {
store.periodosV2 = periodosV2;
});
}
}).mount();
+731
View File
@@ -0,0 +1,731 @@
/*!
* ClockPicker v{package.version} (http://weareoutman.github.io/clockpicker/)
* Copyright 2014 Wang Shenwei.
* Licensed under MIT (https://github.com/weareoutman/clockpicker/blob/gh-pages/LICENSE)
*/
;(function(){
var $ = window.jQuery,
$win = $(window),
$doc = $(document),
$body;
// Can I use inline svg ?
var svgNS = 'http://www.w3.org/2000/svg',
svgSupported = 'SVGAngle' in window && (function(){
var supported,
el = document.createElement('div');
el.innerHTML = '<svg/>';
supported = (el.firstChild && el.firstChild.namespaceURI) == svgNS;
el.innerHTML = '';
return supported;
})();
// Can I use transition ?
var transitionSupported = (function(){
var style = document.createElement('div').style;
return 'transition' in style ||
'WebkitTransition' in style ||
'MozTransition' in style ||
'msTransition' in style ||
'OTransition' in style;
})();
// Listen touch events in touch screen device, instead of mouse events in desktop.
var touchSupported = 'ontouchstart' in window,
mousedownEvent = 'mousedown' + ( touchSupported ? ' touchstart' : ''),
mousemoveEvent = 'mousemove.clockpicker' + ( touchSupported ? ' touchmove.clockpicker' : ''),
mouseupEvent = 'mouseup.clockpicker' + ( touchSupported ? ' touchend.clockpicker' : '');
// Vibrate the device if supported
var vibrate = navigator.vibrate ? 'vibrate' : navigator.webkitVibrate ? 'webkitVibrate' : null;
function createSvgElement(name) {
return document.createElementNS(svgNS, name);
}
function leadingZero(num) {
return (num < 10 ? '0' : '') + num;
}
// Get a unique id
var idCounter = 0;
function uniqueId(prefix) {
var id = ++idCounter + '';
return prefix ? prefix + id : id;
}
// Clock size
var dialRadius = 100,
outerRadius = 80,
// innerRadius = 80 on 12 hour clock
innerRadius = 54,
tickRadius = 13,
diameter = dialRadius * 2,
duration = transitionSupported ? 350 : 1;
// Popover template
var tpl = [
'<div class="popover clockpicker-popover">',
'<div class="arrow"></div>',
'<div class="popover-title">',
'<span class="clockpicker-span-hours text-azul-ing"></span>',
' : ',
'<span class="clockpicker-span-minutes"></span>',
'<span class="clockpicker-span-am-pm"></span>',
'</div>',
'<div class="popover-content">',
'<div class="clockpicker-plate">',
'<div class="clockpicker-canvas"></div>',
'<div class="clockpicker-dial clockpicker-hours"></div>',
'<div class="clockpicker-dial clockpicker-minutes clockpicker-dial-out"></div>',
'</div>',
'<span class="clockpicker-am-pm-block">',
'</span>',
'</div>',
'</div>'
].join('');
// ClockPicker
function ClockPicker(element, options) {
var popover = $(tpl),
plate = popover.find('.clockpicker-plate'),
hoursView = popover.find('.clockpicker-hours'),
minutesView = popover.find('.clockpicker-minutes'),
amPmBlock = popover.find('.clockpicker-am-pm-block'),
isInput = element.prop('tagName') === 'INPUT',
input = isInput ? element : element.find('input'),
addon = element.find('.input-group-addon'),
self = this,
timer;
this.id = uniqueId('cp');
this.element = element;
this.options = options;
this.isAppended = false;
this.isShown = false;
this.currentView = 'hours';
this.isInput = isInput;
this.input = input;
this.addon = addon;
this.popover = popover;
this.plate = plate;
this.hoursView = hoursView;
this.minutesView = minutesView;
this.amPmBlock = amPmBlock;
this.spanHours = popover.find('.clockpicker-span-hours');
this.spanMinutes = popover.find('.clockpicker-span-minutes');
this.spanAmPm = popover.find('.clockpicker-span-am-pm');
this.amOrPm = "PM";
// Setup for for 12 hour clock if option is selected
if (options.twelvehour) {
var amPmButtonsTemplate = ['<div class="clockpicker-am-pm-block">',
'<button type="button" class="btn btn-sm btn-default clockpicker-button clockpicker-am-button">',
'AM</button>',
'<button type="button" class="btn btn-sm btn-default clockpicker-button clockpicker-pm-button">',
'PM</button>',
'</div>'].join('');
var amPmButtons = $(amPmButtonsTemplate);
//amPmButtons.appendTo(plate);
////Not working b/c they are not shown when this runs
//$('clockpicker-am-button')
// .on("click", function() {
// self.amOrPm = "AM";
// $('.clockpicker-span-am-pm').empty().append('AM');
// });
//
//$('clockpicker-pm-button')
// .on("click", function() {
// self.amOrPm = "PM";
// $('.clockpicker-span-am-pm').empty().append('PM');
// });
$('<button type="button" class="btn btn-sm btn-default clockpicker-button am-button">' + "AM" + '</button>')
.on("click", function() {
self.amOrPm = "AM";
$('.clockpicker-span-am-pm').empty().append('AM');
}).appendTo(this.amPmBlock);
$('<button type="button" class="btn btn-sm btn-default clockpicker-button pm-button">' + "PM" + '</button>')
.on("click", function() {
self.amOrPm = 'PM';
$('.clockpicker-span-am-pm').empty().append('PM');
}).appendTo(this.amPmBlock);
}
if (! options.autoclose) {
// If autoclose is not setted, append a button
$('<button type="button" class="btn btn-sm btn-default btn-block clockpicker-button">' + options.donetext + '</button>')
.click($.proxy(this.done, this))
.appendTo(popover);
}
// Placement and arrow align - make sure they make sense.
if ((options.placement === 'top' || options.placement === 'bottom') && (options.align === 'top' || options.align === 'bottom')) options.align = 'left';
if ((options.placement === 'left' || options.placement === 'right') && (options.align === 'left' || options.align === 'right')) options.align = 'top';
popover.addClass(options.placement);
popover.addClass('clockpicker-align-' + options.align);
this.spanHours.click($.proxy(this.toggleView, this, 'hours'));
this.spanMinutes.click($.proxy(this.toggleView, this, 'minutes'));
// Show or toggle
input.on('focus.clockpicker click.clockpicker', $.proxy(this.show, this));
addon.on('click.clockpicker', $.proxy(this.toggle, this));
// Build ticks
var tickTpl = $('<div class="clockpicker-tick"></div>'),
i, tick, radian, radius;
// Hours view
if (options.twelvehour) {
for (i = 1; i < 13; i += 1) {
tick = tickTpl.clone();
radian = i / 6 * Math.PI;
radius = outerRadius;
//tick.css('font-size', '120%');
tick.css({
left: dialRadius + Math.sin(radian) * radius - tickRadius,
top: dialRadius - Math.cos(radian) * radius - tickRadius
});
tick.html(i === 0 ? '00' : i);
hoursView.append(tick);
tick.on(mousedownEvent, mousedown);
}
} else {
for (i = 0; i < 24; i += 1) {
tick = tickTpl.clone();
radian = i / 6 * Math.PI;
var inner = i > 0 && i < 13;
radius = inner ? innerRadius : outerRadius;
tick.css({
left: dialRadius + Math.sin(radian) * radius - tickRadius,
top: dialRadius - Math.cos(radian) * radius - tickRadius
});
/*if (inner) {
tick.css('font-size', '120%');
}*/
tick.html(i === 0 ? '00' : i);
hoursView.append(tick);
tick.on(mousedownEvent, mousedown);
}
}
// Minutes view
for (i = 0; i < 60; i += 5) {
tick = tickTpl.clone();
radian = i / 30 * Math.PI;
tick.css({
left: dialRadius + Math.sin(radian) * outerRadius - tickRadius,
top: dialRadius - Math.cos(radian) * outerRadius - tickRadius
});
//tick.css('font-size', '120%');
tick.html(leadingZero(i));
minutesView.append(tick);
tick.on(mousedownEvent, mousedown);
}
// Clicking on minutes view space
plate.on(mousedownEvent, function(e){
if ($(e.target).closest('.clockpicker-tick').length === 0) {
mousedown(e, true);
}
});
// Mousedown or touchstart
function mousedown(e, space) {
var offset = plate.offset(),
isTouch = /^touch/.test(e.type),
x0 = offset.left + dialRadius,
y0 = offset.top + dialRadius,
dx = (isTouch ? e.originalEvent.touches[0] : e).pageX - x0,
dy = (isTouch ? e.originalEvent.touches[0] : e).pageY - y0,
z = Math.sqrt(dx * dx + dy * dy),
moved = false;
// When clicking on minutes view space, check the mouse position
if (space && (z < outerRadius - tickRadius || z > outerRadius + tickRadius)) {
return;
}
e.preventDefault();
// Set cursor style of body after 200ms
var movingTimer = setTimeout(function(){
$body.addClass('clockpicker-moving');
}, 200);
// Place the canvas to top
if (svgSupported) {
plate.append(self.canvas);
}
// Clock
self.setHand(dx, dy, ! space, true);
// Mousemove on document
$doc.off(mousemoveEvent).on(mousemoveEvent, function(e){
e.preventDefault();
var isTouch = /^touch/.test(e.type),
x = (isTouch ? e.originalEvent.touches[0] : e).pageX - x0,
y = (isTouch ? e.originalEvent.touches[0] : e).pageY - y0;
if (! moved && x === dx && y === dy) {
// Clicking in chrome on windows will trigger a mousemove event
return;
}
moved = true;
self.setHand(x, y, false, true);
});
// Mouseup on document
$doc.off(mouseupEvent).on(mouseupEvent, function(e){
$doc.off(mouseupEvent);
e.preventDefault();
var isTouch = /^touch/.test(e.type),
x = (isTouch ? e.originalEvent.changedTouches[0] : e).pageX - x0,
y = (isTouch ? e.originalEvent.changedTouches[0] : e).pageY - y0;
if ((space || moved) && x === dx && y === dy) {
self.setHand(x, y);
}
if (self.currentView === 'hours') {
self.toggleView('minutes', duration / 2);
} else {
if (options.autoclose) {
self.minutesView.addClass('clockpicker-dial-out');
setTimeout(function(){
self.done();
}, duration / 2);
}
}
plate.prepend(canvas);
// Reset cursor style of body
clearTimeout(movingTimer);
$body.removeClass('clockpicker-moving');
// Unbind mousemove event
$doc.off(mousemoveEvent);
});
}
if (svgSupported) {
// Draw clock hands and others
var canvas = popover.find('.clockpicker-canvas'),
svg = createSvgElement('svg');
svg.setAttribute('class', 'clockpicker-svg');
svg.setAttribute('width', diameter);
svg.setAttribute('height', diameter);
var g = createSvgElement('g');
g.setAttribute('transform', 'translate(' + dialRadius + ',' + dialRadius + ')');
var bearing = createSvgElement('circle');
bearing.setAttribute('class', 'clockpicker-canvas-bearing');
bearing.setAttribute('cx', 0);
bearing.setAttribute('cy', 0);
bearing.setAttribute('r', 2);
var hand = createSvgElement('line');
hand.setAttribute('x1', 0);
hand.setAttribute('y1', 0);
var bg = createSvgElement('circle');
bg.setAttribute('class', 'clockpicker-canvas-bg');
bg.setAttribute('r', tickRadius);
var fg = createSvgElement('circle');
fg.setAttribute('class', 'clockpicker-canvas-fg');
fg.setAttribute('r', 3.5);
g.appendChild(hand);
g.appendChild(bg);
g.appendChild(fg);
g.appendChild(bearing);
svg.appendChild(g);
canvas.append(svg);
this.hand = hand;
this.bg = bg;
this.fg = fg;
this.bearing = bearing;
this.g = g;
this.canvas = canvas;
}
raiseCallback(this.options.init);
}
function raiseCallback(callbackFunction) {
if (callbackFunction && typeof callbackFunction === "function") {
callbackFunction();
}
}
// Default options
ClockPicker.DEFAULTS = {
'default': '', // default time, 'now' or '13:14' e.g.
fromnow: 0, // set default time to * milliseconds from now (using with default = 'now')
placement: 'bottom', // clock popover placement
align: 'left', // popover arrow align
donetext: 'Aceptar', // done button text
autoclose: false, // auto close when minute is selected
twelvehour: false, // change to 12 hour AM/PM clock from 24 hour
vibrate: true // vibrate the device when dragging clock hand
};
// Show or hide popover
ClockPicker.prototype.toggle = function(){
this[this.isShown ? 'hide' : 'show']();
};
// Set popover position
ClockPicker.prototype.locate = function(){
var element = this.element,
popover = this.popover,
offset = element.offset(),
width = element.outerWidth(),
height = element.outerHeight(),
placement = this.options.placement,
align = this.options.align,
styles = {},
self = this;
popover.show();
// Place the popover
switch (placement) {
case 'bottom':
styles.top = offset.top + height;
break;
case 'right':
styles.left = offset.left + width;
break;
case 'top':
styles.top = offset.top - popover.outerHeight();
break;
case 'left':
styles.left = offset.left - popover.outerWidth();
break;
}
// Align the popover arrow
switch (align) {
case 'left':
styles.left = offset.left;
break;
case 'right':
styles.left = offset.left + width - popover.outerWidth();
break;
case 'top':
styles.top = offset.top;
break;
case 'bottom':
styles.top = offset.top + height - popover.outerHeight();
break;
}
popover.css(styles);
};
// Show popover
ClockPicker.prototype.show = function(e){
// Not show again
if (this.isShown) {
return;
}
raiseCallback(this.options.beforeShow);
var self = this;
// Initialize
if (! this.isAppended) {
// Append popover to body
$body = $(document.body).append(this.popover);
// Reset position when resize
$win.on('resize.clockpicker' + this.id, function(){
if (self.isShown) {
self.locate();
}
});
this.isAppended = true;
}
// Get the time
var value = ((this.input.prop('value') || this.options['default'] || '') + '').split(':');
if (value[0] === 'now') {
var now = new Date(+ new Date() + this.options.fromnow);
value = [
now.getHours(),
now.getMinutes()
];
}
this.hours = + value[0] || 0;
this.minutes = + value[1] || 0;
this.spanHours.html(leadingZero(this.hours));
this.spanMinutes.html(leadingZero(this.minutes));
// Toggle to hours view
this.toggleView('hours');
// Set position
this.locate();
this.isShown = true;
// Hide when clicking or tabbing on any element except the clock, input and addon
$doc.on('click.clockpicker.' + this.id + ' focusin.clockpicker.' + this.id, function(e){
var target = $(e.target);
if (target.closest(self.popover).length === 0 &&
target.closest(self.addon).length === 0 &&
target.closest(self.input).length === 0) {
self.hide();
}
});
// Hide when ESC is pressed
$doc.on('keyup.clockpicker.' + this.id, function(e){
if (e.keyCode === 27) {
self.hide();
}
});
raiseCallback(this.options.afterShow);
};
// Hide popover
ClockPicker.prototype.hide = function(){
raiseCallback(this.options.beforeHide);
this.isShown = false;
// Unbinding events on document
$doc.off('click.clockpicker.' + this.id + ' focusin.clockpicker.' + this.id);
$doc.off('keyup.clockpicker.' + this.id);
this.popover.hide();
raiseCallback(this.options.afterHide);
};
// Toggle to hours or minutes view
ClockPicker.prototype.toggleView = function(view, delay){
var raiseAfterHourSelect = false;
if (view === 'minutes' && $(this.hoursView).css("visibility") === "visible") {
raiseCallback(this.options.beforeHourSelect);
raiseAfterHourSelect = true;
}
var isHours = view === 'hours',
nextView = isHours ? this.hoursView : this.minutesView,
hideView = isHours ? this.minutesView : this.hoursView;
this.currentView = view;
this.spanHours.toggleClass('text-azul-ing', isHours);
this.spanMinutes.toggleClass('text-azul-ing', ! isHours);
// Let's make transitions
hideView.addClass('clockpicker-dial-out');
nextView.css('visibility', 'visible').removeClass('clockpicker-dial-out');
// Reset clock hand
this.resetClock(delay);
// After transitions ended
clearTimeout(this.toggleViewTimer);
this.toggleViewTimer = setTimeout(function(){
hideView.css('visibility', 'hidden');
}, duration);
if (raiseAfterHourSelect) {
raiseCallback(this.options.afterHourSelect);
}
};
// Reset clock hand
ClockPicker.prototype.resetClock = function(delay){
var view = this.currentView,
value = this[view],
isHours = view === 'hours',
unit = Math.PI / (isHours ? 6 : 30),
radian = value * unit,
radius = isHours && value > 0 && value < 13 ? innerRadius : outerRadius,
x = Math.sin(radian) * radius,
y = - Math.cos(radian) * radius,
self = this;
if (svgSupported && delay) {
self.canvas.addClass('clockpicker-canvas-out');
setTimeout(function(){
self.canvas.removeClass('clockpicker-canvas-out');
self.setHand(x, y);
}, delay);
} else {
this.setHand(x, y);
}
};
// Set clock hand to (x, y)
ClockPicker.prototype.setHand = function(x, y, roundBy5, dragging){
var radian = Math.atan2(x, - y),
isHours = this.currentView === 'hours',
unit = Math.PI / (isHours || roundBy5 ? 6 : 30),
z = Math.sqrt(x * x + y * y),
options = this.options,
inner = isHours && z < (outerRadius + innerRadius) / 2,
radius = inner ? innerRadius : outerRadius,
value;
if (options.twelvehour) {
radius = outerRadius;
}
// Radian should in range [0, 2PI]
if (radian < 0) {
radian = Math.PI * 2 + radian;
}
// Get the round value
value = Math.round(radian / unit);
// Get the round radian
radian = value * unit;
// Correct the hours or minutes
if (options.twelvehour) {
if (isHours) {
if (value === 0) {
value = 12;
}
} else {
if (roundBy5) {
value *= 5;
}
if (value === 60) {
value = 0;
}
}
} else {
if (isHours) {
if (value === 12) {
value = 0;
}
value = inner ? (value === 0 ? 12 : value) : value === 0 ? 0 : value + 12;
} else {
if (roundBy5) {
value *= 5;
}
if (value === 60) {
value = 0;
}
}
}
// Once hours or minutes changed, vibrate the device
if (this[this.currentView] !== value) {
if (vibrate && this.options.vibrate) {
// Do not vibrate too frequently
if (! this.vibrateTimer) {
navigator[vibrate](10);
this.vibrateTimer = setTimeout($.proxy(function(){
this.vibrateTimer = null;
}, this), 100);
}
}
}
this[this.currentView] = value;
this[isHours ? 'spanHours' : 'spanMinutes'].html(leadingZero(value));
// If svg is not supported, just add an active class to the tick
//if (! svgSupported) {
this[isHours ? 'hoursView' : 'minutesView'].find('.clockpicker-tick').each(function(){
var tick = $(this);
tick.toggleClass('active', value === + tick.html());
});
//return;
//}
// Place clock hand at the top when dragging
if (dragging || (! isHours && value % 5)) {
this.g.insertBefore(this.hand, this.bearing);
this.g.insertBefore(this.bg, this.fg);
this.bg.setAttribute('class', 'clockpicker-canvas-bg clockpicker-canvas-bg-trans');
} else {
// Or place it at the bottom
this.g.insertBefore(this.hand, this.bg);
this.g.insertBefore(this.fg, this.bg);
this.bg.setAttribute('class', 'clockpicker-canvas-bg');
}
// Set clock hand and others' position
var cx = Math.sin(radian) * radius,
cy = - Math.cos(radian) * radius;
this.hand.setAttribute('x2', cx);
this.hand.setAttribute('y2', cy);
this.bg.setAttribute('cx', cx);
this.bg.setAttribute('cy', cy);
this.fg.setAttribute('cx', cx);
this.fg.setAttribute('cy', cy);
};
// Hours and minutes are selected
ClockPicker.prototype.done = function() {
raiseCallback(this.options.beforeDone);
this.hide();
var last = this.input.prop('value'),
value = leadingZero(this.hours) + ':' + leadingZero(this.minutes);
if (this.options.twelvehour) {
value = value + this.amOrPm;
}
this.input.prop('value', value);
if (value !== last) {
this.input.triggerHandler('change');
if (! this.isInput) {
this.element.trigger('change');
}
}
if (this.options.autoclose) {
this.input.trigger('blur');
}
raiseCallback(this.options.afterDone);
};
// Remove clockpicker from input
ClockPicker.prototype.remove = function() {
this.element.removeData('clockpicker');
this.input.off('focus.clockpicker click.clockpicker');
this.addon.off('click.clockpicker');
if (this.isShown) {
this.hide();
}
if (this.isAppended) {
$win.off('resize.clockpicker' + this.id);
this.popover.remove();
}
};
// Extends $.fn.clockpicker
$.fn.clockpicker = function(option){
var args = Array.prototype.slice.call(arguments, 1);
return this.each(function(){
var $this = $(this),
data = $this.data('clockpicker');
if (! data) {
var options = $.extend({}, ClockPicker.DEFAULTS, $this.data(), typeof option == 'object' && option);
$this.data('clockpicker', new ClockPicker($this, options));
} else {
// Manual operatsions. show, hide, remove, e.g.
if (typeof data[option] === 'function') {
data[option].apply(data, args);
}
}
});
};
}());
+288
View File
@@ -0,0 +1,288 @@
// initial state
const días = ["lunes", "martes", "miércoles", "jueves", "viernes", "sábado"];
const horas_estándar = /* range from 7 to 22 */ Array.from(Array(22 - 7 + 1).keys()).map(x => x + 7);
// fill the table with empty cells
for (let i = 0; i < horas_estándar.length - 1; i++) {
const hora = horas_estándar[i];
const tr = document.createElement("tr");
tr.id = `hora-${hora}-00`;
tr.classList.add(hora > 13 ? "tarde" : "mañana");
const th = document.createElement("th");
th.classList.add("text-center");
th.scope = "row";
th.rowSpan = 4;
th.innerText = `${hora}:00`;
th.style.verticalAlign = "middle";
tr.appendChild(th);
for (let j = 0; j < días.length; j++) {
const día = días[j];
const td = document.createElement("td");
td.id = `hora-${hora}-00-${día}`;
tr.appendChild(td);
}
document.querySelector("tbody#horario")?.appendChild(tr);
// add 7 rows for each hour
const hours = [15, 30, 45];
for (let j = 1; j < 4; j++) {
const tr = document.createElement("tr");
tr.id = `hora-${hora}-${hours[j - 1]}`;
tr.classList.add(hora > 13 ? "tarde" : "mañana");
for (let k = 0; k < días.length; k++) {
const día = días[k];
const td = document.createElement("td");
td.id = `hora-${hora}-${hours[j - 1]}-${día}`;
// td.innerText = `hora-${hora}-${hours[j - 1]}-${día}`;
tr.appendChild(td);
}
document.querySelector("tbody#horario")?.appendChild(tr);
}
}
// add an inital height to the table cells
const tds = document.querySelectorAll("tbody#horario td");
tds.forEach(td => td.style.height = "2rem");
var table = document.querySelector("table");
var empty_table = table?.innerHTML || "";
// hide the table
table.style.display = "none";
document.getElementById('dlProfesor')?.addEventListener('input', function () {
var input = document.getElementById('dlProfesor');
var value = input.value;
var option = document.querySelector(`option[value="${value}"]`);
if (option) {
var id = option.getAttribute('data-id');
const input_profesor = document.getElementById('editor_profesor');
input_profesor.value = id;
// remove is invalid class
input.classList.remove("is-invalid");
// add is valid class
input.classList.add("is-valid");
}
else {
const input_profesor = document.getElementById('editor_profesor');
input_profesor.value = "";
// remove is valid class
input.classList.remove("is-valid");
// add is invalid class
input.classList.add("is-invalid");
}
});
/**
* Functions and Methods
**/
const buscarGrupo = async () => {
// Add loading animation in the button
const btn = document.querySelector("#btn-buscar");
btn.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Cargando...';
btn.disabled = true;
const carrera = document.querySelector("#filter_carrera")?.value;
const grupo = document.querySelector("#filter_grupo")?.value;
console.log(`Carrera: ${carrera}, Grupo: ${grupo}`);
if (carrera == "" || grupo == "") {
triggerMessage("El nombre del grupo y la carrera son requeridos", "Faltan campos");
// Remove loading animation in the button
btn.innerHTML = '<i class="ing-buscar ing"></i> Buscar';
btn.disabled = false;
return;
}
const formData = new FormData();
formData.append("carrera", carrera);
formData.append("grupo", grupo);
formData.append("periodo", document.querySelector("#periodo")?.value);
const thisScript = document.currentScript;
const facultad = thisScript.getAttribute("data-facultad");
formData.append('facultad', facultad);
try {
const response = await fetch("action/action_horario.php", {
method: "POST",
body: formData
}).then(res => res.json());
if (response.status == "success") {
let limits = {
min: 22,
max: 7
};
let sábado = false;
const horario = response.horario;
// show the table
table.style.display = "table";
// clear the table
table.innerHTML = empty_table;
// fill the table
for (let i = 0; i < horario.length; i++) {
const dia = horario[i].dia;
if (dia == "sábado")
sábado = true;
const { hora, minutos } = {
hora: parseInt(horario[i].hora.split(":")[0]),
minutos: horario[i].hora.split(":")[1]
};
// update the limits
if (hora < limits.min) {
limits.min = hora;
}
if (hora > limits.max) {
limits.max = hora;
}
const materia = horario[i].materia;
const profesor = horario[i].profesor;
const salon = horario[i].salon;
const id = horario[i].horario_id;
const prof_id = horario[i].profesor_id;
const cell = document.querySelector(`#hora-${hora}-${minutos}-${dia}`);
cell.innerHTML =
`
<div>
<small class="text-gray">${hora}:${minutos}</small>
<b class="title">${materia}</b> <br>
<br><span>Salón: </span>${salon} <br>
<span class="ing ing-formacion mx-1"></span>${profesor}
</div>
`;
const html = `<div class="menu-flotante p-2">
<a
class="mx-2"
href="#"
data-toggle="modal"
data-target="#modal-editar"
data-dia="${dia}"
data-hora="${hora}:${minutos}"
data-materia="${materia}"
data-profesor="${prof_id}"
data-salon="${salon}"
data-id="${id}"
>
<i class="ing-editar ing"></i>
</a>
<a
class="mx-2"
href="#"
data-toggle="modal"
data-target="#modal-borrar"
data-hoario_id="${id}"
>
<i class="ing-basura ing"></i>
</a>
</div>`;
const td = cell.closest("td");
td.innerHTML += html;
td.classList.add("position-relative");
// this cell spans 4 rows
cell.rowSpan = 6;
cell.classList.add("bloque-clase", "overflow");
for (let j = 1; j < 6; j++) {
const minute = (parseInt(minutos) + j * 15);
const next_minute = (minute % 60).toString().padStart(2, "0");
const next_hour = (hora + Math.floor(minute / 60));
const next_cell = document.querySelector(`#hora-${next_hour}-${next_minute}-${dia}`);
next_cell.remove();
}
}
// remove the elements that are not in the limits
const horas = document.querySelectorAll("tbody#horario tr");
for (let i = 0; i < horas.length; i++) {
const hora = horas[i];
const hora_id = parseInt(hora.id.split("-")[1]);
if (hora_id < limits.min || hora_id > limits.max) {
hora.remove();
}
}
// if there is no sábado, remove the column
if (!sábado) {
document.querySelectorAll("tbody#horario td").forEach(td => {
if (td.id.split("-")[3] == "sábado") {
td.remove();
}
});
// remove the header (the last)
const headers = document.querySelector("#headers");
headers.lastElementChild?.remove();
}
// adjust width
const ths = document.querySelectorAll("tr#headers th");
const width = 95 / (ths.length - 1);
ths.forEach((th, key) => th.style.width = (key == 0) ? "5%" : `${width}%`);
// search item animation
const menúFlontantes = document.querySelectorAll(".menu-flotante");
menúFlontantes.forEach((element) => {
element.classList.add("d-none");
element.parentElement?.addEventListener("mouseover", () => {
element.classList.remove("d-none");
});
element.parentElement?.addEventListener("mouseout", () => {
element.classList.add("d-none");
});
});
}
else {
triggerMessage(response.message, "Error");
// Remove loading animation in the button
btn.innerHTML = '<i class="ing-buscar ing"></i> Buscar';
btn.disabled = false;
}
}
catch (error) {
triggerMessage("Error al cargar el horario", "Error");
triggerMessage(error, "Error");
}
// Remove loading animation in the button
btn.innerHTML = '<i class="ing-buscar ing"></i> Buscar';
btn.disabled = false;
};
async function guardar(id) {
const btn = document.querySelector("#btn-guardar");
const clone = btn.cloneNode(true);
btn.innerHTML = '<i class="ing-cargando ing"></i> Guardando...';
btn.disabled = true;
const data = {
hora: document.querySelector("#editor_hora"),
dia: document.querySelector("#editor_dia"),
salon: document.querySelector("#editor_salón"),
profesor: document.querySelector("#editor_profesor"),
};
const hora = data.hora.value; // h:mm
const { compareHours } = await import('./date_functions');
const hora_antes = compareHours(hora, "07:15") < 0;
const hora_después = compareHours(hora, "21:30") > 0;
if (hora_antes || hora_después) {
alert(`La hora ${hora} no es válida`);
triggerMessage("Selecciona una hora", "Error");
btn.innerHTML = clone.innerHTML;
btn.disabled = false;
data.hora.focus();
data.hora.classList.add("is-invalid");
return;
}
const dia = data.dia.value;
const salon = data.salon.value;
const profesor = data.profesor.value;
const formData = new FormData();
formData.append("id", id);
formData.append("hora", hora);
formData.append("dia", dia);
formData.append("salon", salon);
formData.append("profesor", profesor);
const response = await fetch("action/action_horario_update.php", {
method: "POST",
body: formData
}).then(res => res.json());
if (response.status == "success") {
triggerMessage(response.message, "Éxito", "success");
btn.innerHTML = '<i class="ing-aceptar ing"></i> Guardado';
btn.classList.add("btn-success");
btn.classList.remove("btn-primary");
// return to the initial state
setTimeout(() => {
buscarGrupo();
btn.replaceWith(clone);
$("#modal-editar").modal("hide");
}, 1000);
}
else {
triggerMessage(response.message, "Error");
btn.replaceWith(clone);
$("#modal-editar").modal("hide");
}
}
function triggerMessage(message, header, colour = "danger") {
throw new Error('Function not implemented.');
}
+981
View File
@@ -0,0 +1,981 @@
import {
triggerMessage
} from './module/messages.js';
var gHorarios = [];
/**@Auxiliary functions */
function listProfesor({
id,
grado,
profesor,
clave
}) {
const li = document.createElement('li');
li.setAttribute('data-id', id);
li.classList.add('list-group-item', 'd-flex', 'justify-content-between', 'align-items-center');
li.innerHTML = `${clave} | ${grado} ${profesor}`
const btn = document.createElement('button');
btn.setAttribute('type', 'button');
btn.classList.add('badge', 'badge-danger', 'badge-pill', 'border-0');
btn.onclick = _ => li.remove();
const i = document.createElement('i');
i.classList.add('ing-cancelar');
btn.appendChild(i);
li.appendChild(btn);
document.getElementById("profesores").appendChild(li);
}
// function for comparing two hours in format hh:mm (24 hours) and return the spaceship operator
function compareHours(hora1, hora2) {
// parseInt each hour and minute
const [h1, m1, ] = hora1.split(":").map(x => parseInt(x));
const [h2, m2, ] = hora2.split(":").map(x => parseInt(x));
if (h1 > h2)
return 1;
else if (h1 < h2)
return -1;
else if (m1 > m2)
return 1;
else if (m1 < m2)
return -1;
else
return 0;
}
async function buscarGrupo() {
// Add loading animation in the button
const btn = document.querySelector("#btn-buscar");
btn.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Cargando...';
btn.disabled = true;
const carrera = document.querySelector("#filter_carrera").value;
const grupo = document.querySelector("#filter_grupo").value;
if (carrera == "" || grupo == "") {
triggerMessage("El nombre del grupo y la carrera son requeridos", "Faltan campos");
// Remove loading animation in the button
btn.innerHTML = '<i class="ing-buscar ing"></i> Buscar';
btn.disabled = false;
return;
}
const formData = new FormData();
formData.append("carrera", carrera);
formData.append("grupo", grupo);
formData.append("periodo", document.querySelector("#periodo").value);
formData.append('facultad', '<?= $user->facultad['facultad_id'] ?>');
try {
gHorarios = [];
const {
status,
horario: horarios,
} = await fetch("action/action_horario.php", {
method: "POST",
body: formData
}).then(res => res.json());
if (status != "success") {
triggerMessage(response.message, "Error");
// Remove loading animation in the button
btn.innerHTML = /* HTML */ `<i class="ing-buscar ing"></i> Buscar`;
btn.disabled = false;
}
// show the table
table.style.display = "table";
document.querySelectorAll('.hidden').forEach(element => element.style.display = "block");
// clear the table
table.innerHTML = empty_table;
if (horarios.length == 0) {
// reload window
window.location.reload();
return;
}
// fill the table
gHorarios = horarios;
function conflicts(horario1, horario2) {
const {
hora: hora_inicio1,
hora_final: hora_final1,
dia: dia1,
} = horario1;
const {
hora: hora_inicio2,
hora_final: hora_final2,
dia: dia2,
} = horario2;
// if the days are different, there is no conflict
if (dia1 != dia2) {
return false;
}
const compareInicios = compareHours(hora_inicio1, hora_inicio2);
const compareFinales = compareHours(hora_final1, hora_final2);
const compareInicioFinal = compareHours(hora_inicio1, hora_final2);
const compareFinalInicio = compareHours(hora_final1, hora_inicio2);
// if the horario is inside the other
if (compareInicios === 0 || compareFinales === 0)
return true
if (compareInicios === 1 && compareInicioFinal === -1)
return true
if (compareFinales === -1 && compareFinalInicio === 1)
return true
// if the horario is outside the other
if (compareInicios === -1 && compareFinales === 1)
return true
return false;
}
// remove the next 5 cells
function removeNextCells(horas, minutos, dia, cells = 5) {
[...Array(cells).keys()].map(i => i + 1).forEach(i => {
const minute = (minutos + i * 15)
const next_minute = (minute % 60).toString().padStart(2, "0");
const next_hour = (horas + Math.floor(minute / 60))
document.getElementById(`hora-${next_hour}:${next_minute}-${dia}`).remove()
});
}
function newBlock(horario, edit = false) {
function move(horario, cells) {
const {
hora: hora_inicio,
dia,
} = horario;
const [horas, minutos] = hora_inicio.split(":").map(x => parseInt(x));
const cell = document.getElementById(`hora-${horas}:${minutos.toString().padStart(2, "0")}-${dia}`);
const {
top,
left
} = cell.getBoundingClientRect();
const block = document.getElementById(`block-${horario.id}`);
block.style.top = `${top}px`;
block.style.left = `${left}px`;
removeNextCells(horas, minutos, dia, cells);
}
const {
id,
materia,
salon,
profesores,
hora: hora_inicio,
dia,
bloques
} = horario;
const [horas, minutos] = hora_inicio.split(":").map(x => parseInt(x));
const hora = `${horas}:${minutos.toString().padStart(2, "0")}`;
horario.hora = hora;
const cell = document.getElementById(`hora-${hora}-${dia}`);
cell.dataset.ids = id;
cell.innerHTML = /*html*/ `
<small class="text-gray">${hora}</small>
<b class="title">${materia}</b> <br>
<br><span>Salón: </span>${salon} <br>
<small class="overflow-auto my-2" style="max-height: 3rem; display: block;">
${profesores.map(({grado, profesor}) => /*html*/ ` <span class = "ing ing-formacion mx-1" > </span> ${grado} ${profesor}`).join("<br>")}
</small>`
if (edit)
cell.innerHTML += /*html*/
`<div class="menu-flotante p-2" style="opacity: .7;" >
<a class="mx-2" href="#" data-toggle="modal" data-target="#modal-editar">
<i class="ing-editar ing"></i>
</a>
<a class="mx-2" href="#" data-toggle="modal" data-target="#modal-borrar">
<i class="ing-basura ing" > </i>
</a>
</div>
`
cell.classList.add("bloque-clase", "position-relative");
cell.rowSpan = bloques;
// draggable
cell.draggable = <?= $write ? "true" : "false" ?>;
bloques > 0 ? removeNextCells(horas, minutos, dia, bloques - 1) : null;
}
function newConflictBlock(horarios, edit = false) {
const first_horario = horarios[0];
const [horas, minutos] = first_horario.hora.split(":").map(x => parseInt(x));
const hora = `${horas}:${minutos.toString().padStart(2, "0")}`;
const ids = horarios.map(horario => horario.id);
const cell = document.getElementById(`hora-${hora}-${first_horario.dia}`);
if (cell == null) {
console.error(`Error: No se encontró la celda: hora-${hora}-${first_horario.dia}`);
return;
}
cell.dataset.ids = ids.join(",");
// replace the content of the cell
cell.innerHTML = /* HTML */ `
<small class = 'text-danger'>
${hora}
</small>
<div class="d-flex justify-content-center align-items-center mt-4">
<div class="d-flex flex-column justify-content-center align-items-center">
<span class="ing ing-importante text-danger" style="font-size: 2rem;"></span>
<b class='text-danger'>
Empalme de ${ids.length} horarios
</b> <hr>
<i class="text-danger">Ver horarios &#8230;</i>
</div>
</div>
`;
// the text must be centered
// cell.style.backgroundColor = "#f6cfd6";
cell.classList.add("conflict", "bloque-clase");
// add cursor clickable role = "button"
cell.setAttribute("role", "button");
// add the event listener for the cell
cell.addEventListener("click", () => {
$("#modal-choose").modal("show");
const ids = cell.getAttribute("data-ids").split(",").map(x => parseInt(x));
const horarios = gHorarios.filter(horario => ids.includes(horario.id));
const tbody = document.querySelector("#modal-choose tbody");
tbody.innerHTML = "";
horarios.sort((a, b) => compareHours(a.hora, b.hora)).forEach(horario => {
const {
materia,
dia,
hora,
hora_final,
profesores,
salon,
id,
} = horario;
// remove the last 00 of the hour
const [horaFmt, hora_finalFmt] = [hora, hora_final].map(hora => hora.slice(0, -3))
const buttons = /* HTML */ `
<td class="text-center">
<button class="btn btn-sm btn-primary dismiss-editar" data-toggle="modal" data-target="#modal-editar">
<i class="ing-editar ing"></i>
</button>
</td>
<td class="text-center">
<button class="btn btn-sm btn-danger dismiss-editar" data-toggle="modal" data-target="#modal-borrar">
<i class="ing-basura ing"></i>
</button>
</td>`
tbody.innerHTML += /* HTML */ `
<tr data-ids="${id}">
<td><small>${horaFmt}-${hora_finalFmt}</small></td>
<td>${materia}</td>
<td>
${profesores.map(({ grado, profesor }) => `${grado} ${profesor}`).join(", ")}
</td>
<td>${salon}</td>
${edit ? buttons : ""}
</tr>`;
});
document.querySelectorAll(".dismiss-editar").forEach(btn => {
btn.addEventListener("click", () => $("#modal-choose").modal("hide"));
});
});
// blocks is (firsthour - lasthour) / 15 minutes
// sum the duracion_bloques of each horario
function getDuration(hora_i, hora_f) {
const [horas_i, minutos_i] = hora_i.split(":").map(x => parseInt(x));
const [horas_f, minutos_f] = hora_f.split(":").map(x => parseInt(x));
const date_i = new Date(0, 0, 0, horas_i, minutos_i);
const date_f = new Date(0, 0, 0, horas_f, minutos_f);
const diff = date_f - date_i;
return diff / (1000 * 60 * 15);
}
const lastHorario = horarios[horarios.length - 1];
// remove the next cells
// get the max hora_final
const maxHoraFinal = horarios.reduce((max, horario) => {
const [horas, minutos] = horario.hora_final.split(":").map(x => parseInt(x));
const date = new Date(0, 0, 0, horas, minutos);
return date > max ? date : max;
}, new Date(0, 0, 0, 0, 0));
const blocks = getDuration(first_horario.hora, `${maxHoraFinal.getHours()}:${maxHoraFinal.getMinutes()}`);
cell.rowSpan = blocks
removeNextCells(horas, minutos, first_horario.dia, blocks - 1);
}
const conflictBlocks = horarios.filter((horario, index, arrayHorario) =>
arrayHorario.filter((_, i) => i != index).some(horario2 =>
conflicts(horario, horario2)))
.sort((a, b) => compareHours(a.hora, b.hora));
const classes = horarios.filter(horario => !conflictBlocks.includes(horario));
const conflictBlocksPacked = []; // array of sets
conflictBlocks.forEach(horario => {
const setIndex = conflictBlocksPacked.findIndex(set => set.some(horario2 => conflicts(horario, horario2)));
if (setIndex === -1) {
conflictBlocksPacked.push([horario]);
} else {
conflictBlocksPacked[setIndex].push(horario);
}
})
classes.forEach(horario =>
newBlock(horario, <?= $write ?>)
)
conflictBlocksPacked.forEach(horarios =>
newConflictBlock(horarios, <?= $write ?>)
)
// remove the elements that are not in the limits
let max_hour = Math.max(...horarios.map(horario => {
const lastMoment = moment(horario.hora, "HH:mm").add(horario.bloques * 15, "minutes");
const lastHour = moment(`${lastMoment.hours()}:00`, "HH:mm");
const hourInt = parseInt(lastMoment.format("HH"));
return lastMoment.isSame(lastHour) ? hourInt - 1 : hourInt;
}));
let min_hour = Math.min(...horarios.map(horario => parseInt(horario.hora.split(":")[0])));
document.querySelectorAll("tbody#horario tr").forEach(hora => {
const hora_id = parseInt(hora.id.split("-")[1].split(":")[0]);
(hora_id < min_hour || hora_id > max_hour) ? hora.remove(): null;
})
// if there is no sábado, remove the column
if (!horarios.some(horario => horario.dia == "sábado")) {
document.querySelectorAll("tbody#horario td").forEach(td => {
if (td.id.split("-")[2] == "sábado") {
td.remove();
}
});
// remove the header (the last)
document.querySelector("#headers").lastElementChild.remove();
}
// adjust width
const ths = document.querySelectorAll("tr#headers th");
ths.forEach((th, key) =>
th.style.width = (key == 0) ? "5%" : `${95 / (ths.length - 1)}%`
);
// search item animation
const menúFlontantes = document.querySelectorAll(".menu-flotante");
menúFlontantes.forEach((element) => {
element.classList.add("d-none");
element.parentElement.addEventListener("mouseover", () =>
element.classList.remove("d-none")
);
element.parentElement.addEventListener("mouseout", (e) =>
element.classList.add("d-none")
);
});
} catch (error) {
triggerMessage("Error al cargar el horario", "Error");
triggerMessage(error, "Error");
}
// droppables
// forall the .bloque-elements add the event listeners for drag and drop
<?php if ($write) : ?>
document.querySelectorAll(".bloque-clase").forEach(element => {
function dragStart() {
this.classList.add("dragging");
}
function dragEnd() {
this.classList.remove("dragging");
}
element.addEventListener("dragstart", dragStart);
element.addEventListener("dragend", dragEnd);
});
// forall the cells that are not .bloque-clase add the event listeners for drag and drop
document.querySelectorAll("td:not(.bloque-clase)").forEach(element => {
function dragOver(e) {
e.preventDefault();
this.classList.add("dragging-over");
}
function dragLeave() {
this.classList.remove("dragging-over");
}
function drop() {
this.classList.remove("dragging-over");
const dragging = document.querySelector(".dragging");
const id = /* for data-ids */ dragging.getAttribute("data-ids");
const hora = /* for data-hora */ this.id.split("-")[1];
const días = ["lunes", "martes", "miércoles", "jueves", "viernes", "sábado"];
let día = /* for data-dia */ this.id.split("-")[2];
día = días.indexOf(día) + 1;
// rowspan
const bloques = parseInt(dragging.getAttribute("rowspan"));
const horaMoment = moment(hora, "HH:mm");
const horaFin = horaMoment.add(bloques * 15, "minutes");
const limit = moment('22:00', 'HH:mm');
if (horaFin.isAfter(limit)) {
triggerMessage("No se puede mover el bloque a esa hora", "Error");
// scroll to the top
window.scrollTo(0, 0);
return;
}
moveHorario(id, día, hora);
}
element.addEventListener("dragover", dragOver);
element.addEventListener("dragleave", dragLeave);
element.addEventListener("drop", drop);
});
<?php endif; ?>
// Remove loading animation in the button
btn.innerHTML = '<i class="ing-buscar ing"></i> Buscar';
btn.disabled = false;
// console.table(gHorarios);
}
async function guardar(id) {
const btn = document.querySelector("#btn-guardar");
const clone = btn.cloneNode(true);
btn.innerHTML = '<i class="ing-cargando ing"></i> Guardando...';
btn.disabled = true;
const data = {
dia: document.querySelector("#editor_dia"),
salon: document.querySelector("#editor_salón"),
//vprofesor: document.querySelector("#editor_profesor"),
duración: document.querySelector("#editor_duración")
};
const dia = data.dia.value;
const salon = data.salon.value;
if (salon == "") {
btn.innerHTML = clone.innerHTML;
btn.disabled = false;
return;
}
const hora = document.querySelector("#selector_horas").value;
const minutos = document.querySelector("#selector_minutos").value;
const bloques = document.querySelector("#dlduración li.selected").getAttribute("data-bloques");
const start = moment(`${hora}:${minutos}`, "HH:mm").add(bloques * 15, "minutes");
const end = moment("22:00", "HH:mm");
if (start.isAfter(end)) {
btn.innerHTML = clone.innerHTML;
btn.disabled = false;
document.querySelector("#dlduración").classList.add("is-invalid");
return;
}
const profesoresList = [...document.querySelectorAll("#profesores li")];
if (profesoresList.length == 0) {
btn.innerHTML = clone.innerHTML;
btn.disabled = false;
return;
}
const formData = new FormData();
// const id = btn.getAttribute("data-id");
formData.append("id", id);
const horas = document.querySelectorAll("#selector_horas, #selector_minutos")
formData.append("hora", `${horas[0].value}:${horas[1].value}`);
formData.append("día", dia);
formData.append("salón", salon);
const profesores = profesoresList.map(li => li.getAttribute("data-id"));
formData.append("duración", data.duración.value);
formData.append("profesores", profesores.join(","));
const response = await fetch("action/action_horario_update.php", {
method: "POST",
body: formData
}).then(res => res.json());
if (response.status == "success") {
triggerMessage("Horario actualizado", "Éxito", "success");
btn.innerHTML = '<i class="ing-aceptar ing"></i> Guardado';
btn.classList.add("btn-success");
btn.classList.remove("btn-primary");
// return to the initial state
setTimeout(() => {
buscarGrupo();
btn.replaceWith(clone);
$("#modal-editar").modal("hide");
}, 100);
} else {
triggerMessage(response.message, "Error");
btn.replaceWith(clone);
$("#modal-editar").modal("hide");
}
}
async function borrarHorario(id) {
const btn = document.querySelector("#btn-borrar");
const clone = btn.cloneNode(true);
btn.innerHTML = '<i class="ing-cargando ing"></i> Borrando...';
btn.disabled = true;
const formData = new FormData();
formData.append("id", id);
const response = await fetch("action/action_horario_delete.php", {
method: "POST",
body: formData
}).then(res => res.json());
if (response.status == "success") {
triggerMessage('Horario borrado', "Éxito", "success");
btn.innerHTML = '<i class="ing-aceptar ing"></i> Borrado';
btn.classList.add("btn-success");
btn.classList.remove("btn-danger");
// return to the initial state
setTimeout(() => {
buscarGrupo();
btn.replaceWith(clone);
$("#modal-borrar").modal("hide");
}, 1000);
} else {
triggerMessage(response.message, "Error");
btn.replaceWith(clone);
$("#modal-borrar").modal("hide");
}
}
function guardarHorario() {
let goBack = false;
const btn = document.querySelector("#btn-guardar-horario");
const clone = btn.cloneNode(true);
btn.innerHTML = '<i class="ing-cargando ing"></i> Guardando...';
btn.disabled = true;
const data = {
dia: document.querySelector("#new_dia"),
salon: document.querySelector("#new_salón"),
profesor: document.querySelector("#new_profesor"),
duración: document.querySelector("#new_duración"),
materia: document.querySelector("#new_materia")
};
const dia = data.dia.value;
const salon = data.salon.value;
const profesor = data.profesor.value;
const materia = data.materia.value;
const duración = data.duración.value;
if (duración == "") {
invalidDatalist("#new_duración");
goBack = true;
}
if (profesor == "") {
data.profesor.classList.add("is-invalid");
goBack = true;
}
if (salon == "") {
data.salon.classList.add("is-invalid");
goBack = true;
}
if (dia == "") {
invalidDatalist("#new_dia");
goBack = true;
}
if (materia == "") {
data.materia.classList.add("is-invalid");
goBack = true;
}
const hora = document.querySelector("#new_horas").value;
if (hora == "") {
invalidDatalist("#new_horas");
goBack = true;
}
const minutos = document.querySelector("#new_minutos").value;
if (minutos == "") {
invalidDatalist("#new_minutos");
goBack = true;
}
const bloques = document.querySelector("#dlNewDuración li.selected")?.getAttribute("data-bloques");
const start = moment(`${hora}:${minutos}`, "HH:mm").add(bloques * 15, "minutes");
const end = moment("22:00", "HH:mm");
if (start.isAfter(end)) {
document.querySelector("#dlNewDuración").classList.add("is-invalid");
goBack = true;
}
if (goBack) {
btn.innerHTML = clone.innerHTML;
btn.disabled = false;
return;
}
const formData = new FormData();
formData.append("grupo", document.querySelector("#filter_grupo").value);
formData.append("hora", `${hora}:${minutos}`);
formData.append("día", dia);
formData.append("salón", salon);
formData.append("profesor", profesor);
formData.append("duración", data.duración.value);
formData.append("periodo", "<?= $user->periodo ?>");
formData.append("materia", materia);
formData.append("facultad", "<?= $user->facultad['facultad_id'] ?>");
fetch("action/action_horario_create.php", {
method: "POST",
body: formData
}).then(res => res.json()).then(response => {
if (response.status == "success") {
triggerMessage("Horario guardado", "Éxito", "success");
btn.innerHTML = /* html */ `<i class="ing-aceptar ing"></i> Guardado`;
btn.classList.add("btn-success");
btn.classList.remove("btn-primary");
// return to the initial state
setTimeout(() => {
btn.innerHTML = clone.innerHTML;
btn.disabled = false;
btn.classList.remove("btn-success");
btn.classList.add("btn-primary");
// this modal
$("#modal-nuevo").modal("hide");
const modalNuevo = document.querySelector("#modal-nuevo");
modalNuevo.querySelectorAll("input").forEach(input => {
input.value = "";
});
// reset the datalist
modalNuevo.querySelectorAll(".datalist").forEach(datalist => {
const cloneDatalist = modalNuevoClone.querySelector(`#${datalist.id}`).cloneNode(true);
// log
datalist.replaceWith(cloneDatalist);
});
// remove all is-valid and is-invalid
modalNuevo.querySelectorAll(".is-valid, .is-invalid").forEach(el => {
el.classList.remove("is-valid", "is-invalid");
});
}, 100);
} else {
triggerMessage(response.message, "Error");
btn.innerHTML = clone.innerHTML;
btn.disabled = false;
$("#modal-nuevo").modal("hide");
}
}).then(() => {
buscarGrupo();
}).catch(err => {
triggerMessage(err, "Error");
btn.innerHTML = clone.innerHTML;
btn.disabled = false;
$("#modal-nuevo").modal("hide");
});
// buscarGrupo();
}
function moveHorario(id, día, hora) {
const formData = new FormData();
formData.append("id", id);
formData.append("hora", hora);
formData.append("día", día);
fetch("action/action_horario_update.php", {
method: "POST",
body: formData
}).then(res => res.json()).then(response => {
if (response.status == "success") {
triggerMessage("Horario movido", "Éxito", "success");
} else {
triggerMessage(response.message, "Error");
}
}).then(() => {
buscarGrupo();
}).catch(err => {
triggerMessage(err, "Error");
});
}
// initial state
{
// fill the table with empty cells
[...Array(16).keys()].map(x => x + 7).forEach(hora => {
// add 7 rows for each hour
[0, 15, 30, 45].map(minute => minute.toString().padStart(2, '0')).forEach(minute => {
const tr = document.createElement("tr");
tr.id = `hora-${hora}:${minute}`;
tr.classList.add(hora > 13 ? "tarde" : "mañana");
if (minute == 0) {
const th = document.createElement("th");
th.classList.add("text-center");
th.scope = "row";
th.rowSpan = 4;
th.innerText = `${hora}:00`;
th.style.verticalAlign = "middle";
tr.appendChild(th);
}
["lunes", "martes", "miércoles", "jueves", "viernes", "sábado"].forEach(día => {
const td = document.createElement("td");
td.id = `hora-${hora}:${minute}-${día}`;
tr.appendChild(td);
});
document.querySelector("tbody#horario").appendChild(tr);
});
})
// add an inital height to the table cells
// query selector All tds and ths inside the tbody#horario
// previous query selector: "tbody#horario td, tbody#horario tr"
document.querySelectorAll("tbody#horario td, tbody#horario tr").forEach(element => element.style.height = "2rem");
document.getElementById('btn-buscar').addEventListener('click', buscarGrupo);
document.getElementById('dlProfesor').addEventListener('input', function(e) {
var input = document.getElementById('dlProfesor');
var value = input.value;
var option = document.querySelector(`option[value="${value}"]`);
if (!option) {
document.getElementById('editor_profesor').value = "";
// remove is valid class
input.classList.remove("is-valid");
// add is invalid class
input.classList.add("is-invalid");
return
}
var id = option.getAttribute('data-id');
if (!document.querySelector(`li[data-id="${id}"]`))
listProfesor({
id: id,
grado: option.getAttribute('data-grado'),
profesor: option.getAttribute('data-profesor'),
clave: option.getAttribute('data-clave')
});
e.target.value = "";
});
}
// state
const table = document.querySelector("table");
const empty_table = table.innerHTML;
document.querySelectorAll('.hidden').forEach(element => element.style.display = "none");
// hide the table
table.style.display = "none";
disableDatalist("#filter_grupo");
document.getElementById("btn-excel-horario").addEventListener("click", () => {
const formData = new FormData();
const grupo = document.getElementById("filter_grupo").value;
formData.append("grupo", grupo);
formData.append('sábado', gHorarios.some(horario => horario.dia == "sábado"));
formData.append("horarios", JSON.stringify(gHorarios));
// min and max hour
formData.append("min", gHorarios.reduce((min, horario) => {
const hora = horario.hora.split(":").map(x => parseInt(x))[0]
return Math.min(hora, min);
}, 24));
formData.append("max", gHorarios.reduce((max, horario) => {
const {
hora,
bloques
} = horario;
// after hour
const lastHour = moment(hora, "HH:mm").add(bloques * 15, "minutes");
const lastMoment = moment(`${lastHour.format("HH")}:00`, "HH:mm");
const intHour = parseInt(lastHour.format("HH"));
return Math.max(lastMoment.isSame(lastHour) ? intHour - 1 : intHour, max);
}, 0));
fetch("export/horario_excel.php", {
method: "POST",
body: formData
})
.then(response => response.blob())
.then(blob => {
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.style.display = 'none';
a.setAttribute('href', url);
a.setAttribute('download', `horario-${grupo}.xlsx`);
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
})
.catch(() => triggerMessage("error", "Error al exportar el horario"));
});
// on click the li element, inside datalist #dlcarera
document.querySelectorAll("#dlcarrera li").forEach(async li => {
li.addEventListener("click", async () => {
// get the data-id from the li element
const carrera = li.getAttribute("data-id");
const facultad = '<?= $user->facultad['facultad_id'] ?>';
const periodo = '<?= $user->periodo ?>';
const formData = new FormData();
formData.append("carrera", carrera);
formData.append("facultad", facultad);
formData.append("periodo", periodo);
try {
const {
status,
grupos
} = await fetch("action/action_grupo.php", {
method: "POST",
body: formData
}).then(res => res.json());
if (status != "success") {
throw new Error("Error al cargar los grupos");
} else if (grupos.length == 0) {
throw new Error("No hay grupos para esta carrera");
}
const dlgrupo = document.querySelector("#dlgrupo ul");
const prompt = document.querySelector("#dlgrupo .datalist-input");
dlgrupo.innerHTML = "";
grupos.forEach(grupo => {
const li = document.createElement("li");
// data-id is the id of the group
li.setAttribute("data-id", grupo);
li.textContent = grupo;
dlgrupo.appendChild(li);
});
// write Seleccionar grupo
prompt.textContent = "Seleccionar grupo";
disableDatalist("#filter_grupo", false);
// to #filter_grupo input value
const filter_grupo = document.querySelector("#filter_grupo");
filter_grupo.value = "";
} catch (error) {
// remove Error: from the error message
error = error.toString().replace("Error: ", "");
triggerMessage(error, "Error");
console.error(error);
}
const datalist = document.querySelector("#materias");
const materias = await fetch("action/action_materias.php", {
method: "POST",
body: formData
}).then(res => res.json());
});
})
// on modal edit, show the data
$("#modal-editar").on("show.bs.modal", async function(event) {
document.querySelectorAll("#modal-editar .is-invalid, #modal-editar .is-valid")?.forEach(element => element.classList.remove("is-invalid", "is-valid"));
const button = event.relatedTarget;
const parentId = button.parentElement.parentElement.getAttribute("data-ids");
const {
id,
dia,
hora,
materia,
salon,
profesores,
duracion
} = gHorarios?.find(horario => horario.id == parentId);
// search the data-id of the day and click it
const númeroDía = ['domingo', 'lunes', 'martes', 'miércoles', 'jueves', 'viernes', 'sábado'].reduce((acc, curr, key) => (curr == dia) ? key : acc);
document.querySelector(`#dldia li[data-id="${númeroDía}"]`)?.click();
document.querySelector(`#dlduración li[data-id="${duracion}"]`)?.click();
const horas = hora.split(":")[0];
const minutos = hora.split(":")[1];
setDatalist("#selector_horas", horas);
setDatalist("#selector_minutos", minutos);
document.getElementById('editor_salón').value = salon;
// get the option with data-id profesor
document.getElementById("profesores").innerHTML = "";
profesores.forEach(listProfesor);
const btnGuardar = document.getElementById('btn-guardar');
btnGuardar.onclick = () => guardar(id);
})
$("#modal-borrar").modal({
show: false,
backdrop: "static",
keyboard: false,
})
$("#modal-borrar").on("show.bs.modal", async function(event) {
const button = event.relatedTarget;
const id = button.parentElement.parentElement.getAttribute("data-ids");
const btnBorrar = document.getElementById('btn-borrar');
btnBorrar.onclick = () => borrarHorario(id);
})
+75
View File
@@ -0,0 +1,75 @@
/*
jQuery Custom Input File Plugin - version 1.0
Copyright 2014, Ángel Espro, www.aesolucionesweb.com.ar,
Licence : GNU General Public License
Site: www.aesolucionesweb.com.ar/plugins/custom-input-file
You must not remove these lines. Read gpl.txt for further legal information.
*/
(function($){CustomFile=function(elem,options){this.elem=$(elem);this.itemFileList=[];this.defaults={type:'all',allowed:'all',notAllowed:[],addContainerAfter:$(elem),multiple:true,maxFiles:5,maxMB:0,maxKBperFile:2048,fileWrapper:'<div class="cif-parent"></div>',filePicker:'<h3>Soltar archivos aquí</h3><p>o clic para seleccionar desde carpeta</p><div class="cif-icon-picker"></div>',image:{crop:false,preview:{display:true,maxWidth:300},cropSize:[320,225],minSize:[0,0],maxSize:[0,0]},messages:{errorType:"Tipo de archivo no permitido",errorMaxMB:"Peso máximo de archivos acumulado excedido",errorFileKB:"Archivo muy pesado",errorMaxFiles:"Cantidad máxima de archivos alcanzada",errorBigImage:"Imagen muy grande",errorSmallImage:"Imagen muy pequeña",errorOnReading:"Aplicación ocupada. Inténtelo más tarde.",errorMultipleDisable:"Suelte un archivo por vez."},popup:{active:true,autoclose:true,delay:10000},callbacks:{onComplete:function(app){},beforeRead:function(file){},onSuccess:function(item,callback){},onError:function(file,msg){},beforeRemove:function(item){},}}
this.settings=$.extend(true,{},this.defaults,options);this.status='stop';this.init();}
CustomFile.prototype={init:function(){var attnm=this.elem.attr("name");if(attnm=='')var attnm="inputfile";this.name=(attnm.indexOf("[]",attnm-2)===-1)?attnm+"[]":attnm;this.form=this.elem.parents('form');this.container=$('<div class="cif-file-container cif-container-'+this.settings.type+'-type">');var image=this.settings.image;image.minSize=(typeof(image.minSize)!=='object'||image.minSize.length!==2)?[0,0]:image.minSize;if(image.crop){var minSize=[];for(i=0;i<image.minSize.length;i++){var value=(image.minSize[i]>image.cropSize[i])?image.minSize[i]:image.cropSize[i];minSize.push(value);}
image.minSize=minSize}
this.setFileWrapper();this.appendContainer();this.filePicker=new FilePicker(this);$.customFile.elements.push(this);},onSuccess:function(item,callback){this.itemFileList.push(item);if(this.settings.callbacks.onSuccess(item,callback)===false)return;callback();},onError:function(file,msg){this.settings.callbacks.onError(file,msg);var popupSet=this.settings.popup;if(popupSet.active)
for(k=0;k<msg.length;k++){var fileExt=file.name.substr(file.name.lastIndexOf('.')+1);var fileName=file.name.substr(0,file.name.lastIndexOf('.'));if(fileName.length>42)var fileName=fileName.substr(0,40)+"...";msg[k]+=' ('+fileName+'.'+fileExt+')';$.customFile.popup.add(msg[k],popupSet.autoclose,popupSet.delay,'error');}},onComplete:function(){this.status="completed";if(this.settings.multiple){var response=this.checkMaxFiles()
var popupSet=this.settings.popup;if(response&&popupSet.active)$.customFile.popup.add(response,popupSet.autoclose,popupSet.delay,'ok');}else{if(this.itemFileList.length>1)this.itemFileList[0].destroy();}
this.settings.callbacks.onComplete(this);},read:function(fileList,currentItem){var i=currentItem;if(i+1>fileList.length)this.status='completed';if(this.status==='completed'){this.onComplete();return false;}
var beforeRead=this.settings.callbacks.beforeRead(fileList[i]);if(beforeRead===false)return this.read(fileList,i+1);app=this;var response=app.checkMaxFiles(fileList[i]);if(typeof(response)==='string'){this.onError(fileList[i],[response]);return this.read(fileList,i+1);}
var msg=[];var checklist=["checkFileKB","checkFileType","checkTotalMB"]
for(j=0;j<checklist.length;j++){var response=app[checklist[j]](fileList[i]);if(response)msg.push(response)}
if(msg.length>0){this.onError(fileList[i],msg);return this.read(fileList,i+1);}
new FileItem(this,fileList,i);},appendContainer:function(){var sett=this.settings;if(sett.fileWrapper.parent().length!=0&&sett.appendAfter!=this.elem){sett.addContainerAfter=sett.fileWrapper;}
sett.addContainerAfter.after(this.container);},setFileWrapper:function(){var app=this;var fwr=this.settings.fileWrapper;if(typeof(fwr)==='string')this.settings.fileWrapper=$(fwr);this.settings.fileWrapper=$('<div>',{class:"cif-file-row"}).append(this.settings.fileWrapper);var fwr=this.settings.fileWrapper;fwr.find(':input').each(function(index){var $this=$(this);var attnm=$this.attr("name");if(!attnm)var attnm=app.name.substr(0,app.name.indexOf("[]",-2))+"-"+index;if(attnm.indexOf("[]",-2)===-1){$this.attr("name",attnm+"[]");}});if(fwr.find('.cif-img').length==0&&this.settings.type=='image'){var parent=fwr.find('.cif-parent');if(parent.length===0){var $img=fwr.find('img');var parent=$('<div>',{class:'cif-parent'});parent.append($img);fwr.append(parent);}
if(parent.find('img').length===0)parent.append('<img>')
parent.find('img').addClass("cif-img");}
if(fwr.find('.cif-parent').length==0){fwr.prepend('<div class="cif-parent"></div>');}},checkFileKB:function(file){if(file.size>this.settings.maxKBperFile*1024&&this.settings.maxKBperFile!=0){var msg=this.settings.messages.errorFileKB;}
return msg;},checkFileType:function(file){var ext=file.name.substr(file.name.lastIndexOf('.')+1);var ext=ext.toLowerCase();var imageCropAllowed=["jpeg","jpg","png"]
if((this.settings.type=='image'&&this.settings.image.crop&&imageCropAllowed.indexOf(ext)==-1)||(this.settings.type=='image'&&!file.type.match(/image\//))||(this.settings.allowed!='all'&&this.settings.allowed.indexOf(ext)==-1)||(this.settings.notAllowed.indexOf(ext)!=-1))
{var msg=this.settings.messages.errorType;}
return msg;},checkMaxFiles:function(file){if(this.settings.maxFiles<=this.itemFileList.length&&this.settings.maxFiles){var msg=this.settings.messages.errorMaxFiles;this.filePicker.btn.addClass('inactive');}else{this.filePicker.btn.removeClass('inactive');}
return msg;},checkTotalMB:function(file){var fileSize=(typeof(file)!=='undefined')?file.size:0;var totalSize=0;for(var obj in this.itemFileList){totalSize+=this.itemFileList[obj].file.size;}
if(fileSize+totalSize>this.settings.maxMB*1024*1024&&this.settings.maxMB!=0){var msg=this.settings.messages.errorMaxMB;}
return msg;},checkImageSize:function(img,file){var stt=this.settings.image
if((stt.minSize[0]&&img.width<stt.minSize[0])||(stt.minSize[1]&&img.height<stt.minSize[1])){var msg=this.settings.messages.errorSmallImage;if(stt.minSize[0])msg+=' Ancho mínimo:'+stt.minSize[0]+'px.';if(stt.minSize[1])msg+=' Alto mínimo: '+stt.minSize[1]+'px.';}
if((stt.maxSize[0]&&img.width>stt.maxSize[0])||(stt.maxSize[1]&&img.height>stt.maxSize[1])){var msg=this.settings.messages.errorBigImage;if(stt.maxSize[0])msg+=' Ancho máximo:'+stt.maxSize[0]+'px.';if(stt.maxSize[1])msg+=' Alto máximo: '+stt.maxSize[1]+'px.';}
return msg;},}
FilePicker=function(app){this.btn=$('<div class="cif-file-picker"></div>').append(app.settings.filePicker);this.init(app);}
FilePicker.prototype={init:function(app){var multiple=(app.settings.multiple||app.elem.attr("multiple")=="multiple")?'multiple="multiple"':' ';this.inputHidden=$('<input type="file" '+multiple+'/>');app.elem.after(this.btn);var elem=app.elem.clone();app.elem.detach();app.elem=elem;this.btn.addClass("cif-pkr-"+app.elem.attr("name"));var btn=this.btn;var inputHidden=this.inputHidden;inputHidden.change(function(){var popupSet=app.settings.popup;if(app.status=='reading')return $.customFile.popup.add(app.settings.messages.errorOnReading,popupSet.autoclose,popupSet.delay,'error');$.customFile.popup.close();fileList=$(this)[0].files;app.status='reading';app.read(fileList,0);});btn.on({click:function(){if(!$(this).is('.inactive'))inputHidden.click();return false;},dragover:function(e){e=e||window.event;e.preventDefault();if($(this).is('.inactive'))e.dataTransfer.dropEffect='none';btn.addClass('dragover');return false;},dragleave:function(e){btn.removeClass('dragover');return false;},drop:function(e){e=window.event;e.preventDefault();btn.removeClass('dragover');var popupSet=app.settings.popup;if(app.status=='reading')return $.customFile.popup.add(app.settings.messages.errorOnReading,popupSet.autoclose,popupSet.delay,'error');$.customFile.popup.close();var fileList=e.dataTransfer.files;if(fileList.length>1&&!app.settings.multiple)return $.customFile.popup.add(app.settings.messages.errorMultipleDisable,popupSet.autoclose,popupSet.delay,'error');app.status='reading';app.read(fileList,0);}});},};FileItem=function(app,fileList,currentItem){this.file=fileList[currentItem];this.app=app;this.fileList=fileList;this.currentItem=currentItem;this.init();}
FileItem.prototype={init:function(){this.jcropObj=null;this.node=this.app.settings.fileWrapper.clone();this.img=null;this.btnClose=$('<div class="cif-close" title="Remove">close</div>');this.btnClose.click(function(){fileObj.destroy();});this.fr=new FileReader;var fr=this.fr;var app=this.app;var fileObj=this;var fileList=this.fileList;var currentItem=this.currentItem;var callback=function(){app.onSuccess(fileObj,function(){app.read(fileList,currentItem+1);});delete fileObj.fr;delete fileObj.fileList;delete fileObj.currentItem;}
fr.onload=function(){switch(app.settings.type){case"image":fileObj.readImage(callback);break;default:fileObj.readAllTypes(callback);break;}}
fr.readAsDataURL(this.file);},destroy:function(){this.app.settings.callbacks.beforeRemove(this);if(this.node)this.node.remove();var i=this.app.itemFileList.indexOf(this);this.app.itemFileList.splice(i,1);this.app.checkMaxFiles();},serialize:function(){return $.customFile.serialize([{key:this.app.name,value:this.file}]);},readImage:function(callback){var fileObj=this;var fr=this.fr;var app=this.app;var imgNode=fileObj.node.find("img.cif-img");fileObj.img=new Image;fileObj.img.src=fr.result;fileObj.img.onload=function(){msg=app.checkImageSize(fileObj.img,fileObj.file);if(msg){app.onError(fileObj.file,[msg]);return app.read(fileObj.fileList,fileObj.currentItem+1);}
imgNode.attr("src",fr.result);imgNode.parent().prepend(fileObj.btnClose);app.container.append(fileObj.node);if(app.settings.image.crop===true){fileObj.jcropObj=fileObj.initJcrop(app.settings.image,imgNode.parent(),fileObj.img,app.name);}
callback();}},readAllTypes:function(callback){fileObj=this;var parent=fileObj.node.find('.cif-parent');var FileExt=fileObj.file.name.substr(fileObj.file.name.lastIndexOf('.')+1);var FileName=fileObj.file.name.substr(0,fileObj.file.name.lastIndexOf('.'));if(FileName.length>42)var FileName=FileName.substr(0,40)+"...";var fileSize=(fileObj.file.size<102400)?(fileObj.file.size/1024).toFixed(2):Math.round(fileObj.file.size/1024);parent.append($('<div class="cif-all-type">'+FileName+'.'+FileExt+' <span class="cif-file-size">('+fileSize+'KB)</span><div>')).append(fileObj.btnClose);this.app.container.append(fileObj.node)
callback();},initJcrop:function(options,parent,img,appName){var jcrop_api,boundx,boundy;if(options.preview.display){appName=appName.replace("[]","");prevMaxWidth=options.preview.maxWidth;prevSize=(options.cropSize[0]>prevMaxWidth)?[prevMaxWidth,options.cropSize[1]/options.cropSize[0]*prevMaxWidth]:options.cropSize;parent.append('<div class="preview-pane" style="width:'+prevSize[0]+'px;height:'+prevSize[1]+'px;"><div class="preview-container" style="width:'+prevSize[0]+'px;height:'+prevSize[1]+'px; overflow:hidden"><img src="'+img.src+'" class="jcrop-preview im-prv" /></div></div> '
+'<input type="hidden" class="jcropx" name="'+appName+'-x[]" /><input type="hidden" class="jcropy" name="'+appName+'-y[]" /><input type="hidden" class="jcropw" name="'+appName+'-w[]" /><input type="hidden" class="jcroph" name="'+appName+'-h[]" />');parent.css("min-height",prevSize[1]+20+"px");}
var $preview=parent.find('.preview-pane'),$pcnt=$preview.find('.preview-container'),$pimg=$preview.find('.preview-container img'),xsize=$pcnt.width(),ysize=$pcnt.height();api=parent.find('.cif-img').Jcrop({keySupport:false,onChange:updatePreview,onSelect:updatePreview,aspectRatio:options.cropSize[0]/options.cropSize[1],minSize:options.cropSize,trueSize:[img.width,img.height]},function(){var bounds=this.getBounds();boundx=bounds[0];boundy=bounds[1];jcrop_api=this;jcrop_api.animateTo([0,0,options.cropSize[0]]);$preview.appendTo(jcrop_api.ui.holder);});function updatePreview(c){if(parseInt(c.w)>0&&options.preview.display){var rx=xsize / c.w;var ry=ysize / c.h;$pimg.css({width:Math.round(rx*boundx)+'px',height:Math.round(ry*boundy)+'px',marginLeft:'-'+Math.round(rx*c.x)+'px',marginTop:'-'+Math.round(ry*c.y)+'px'});}
updateCoords(c);};function updateCoords(c){parent.find('.jcropx').val(c.x);parent.find('.jcropy').val(c.y);parent.find('.jcropw').val(c.w);parent.find('.jcroph').val(c.h);}
return jcrop_api;}}
$.customFile={elements:[],getElements:function(selector){var elements=[];var selector=selector.split(",");var el=$.customFile.elements;for(k=0;k<selector.length;k++){selector[k]=selector[k].trim()
for(i=0;i<el.length;i++){if(el[i].name===selector[k]+"[]"||el[i].name===selector[k])
elements.push({type:"pseudoinput",obj:el[i]});if($(selector[k]).is('form')){$(selector[k]).each(function(){elements.push({type:"form",obj:$(this),pseudoChild:(el[i].form[0]===$(this)[0])});});}
if($(selector[k]).is(':input')){$(selector[k]).not(':submit').each(function(){elements.push({type:"input",obj:$(this)});});}}}
var indexToRemove=[]
for(i=0;i<elements.length;i++){if(indexToRemove.indexOf(i)!==-1)continue;for(j=0;j<elements.length;j++){if(j===i||indexToRemove.indexOf(j)!==-1)continue;switch(elements[i].type){case"form":var el=elements[i].obj[0];if(el===elements[j].obj[0]||(elements[j].type==="pseudoinput"&&el==elements[j].obj.form[0])||(elements[j].type==="input"&&el==elements[j].obj.parents('form')[0])){indexToRemove.push(j);}
break;case"input":var el=elements[i].obj[0];if(el===elements[j].obj[0])
indexToRemove.push(j);break;case"pseudoinput":var el=elements[i].obj.name;if(el===elements[j].obj.name||el+"[]"===elements[j].obj.name)
indexToRemove.push(j);break;}}}
var result=[];for(i=0;i<elements.length;i++){if(indexToRemove.indexOf(i)===-1)result.push(elements[i]);}
return result;},serialize:function(elements){formData=null;if(typeof(elements)==='object'){formData=formData||new FormData();if(!elements.length)var elements=[elements]
for(j=0;j<elements.length;j++){if(elements[j].hasOwnProperty("key")&&elements[j].hasOwnProperty("value")){formData.append(elements[j].key,elements[j].value);}}}
if(typeof(elements)==='string'){elements=this.getElements(elements);for(j=0;j<elements.length;j++){formData=formData||new FormData();var elem=elements[j];switch(elem.type){case'pseudoinput':$.each(elem.obj.itemFileList,function(index,element){formData.append(elem.obj.name,element.file);});break;case"form":$.each(elem.obj.find(':input'),function(){if($(this).not(':submit'))
formData.append($(this).attr("name"),$(this).val());});var app=elem.obj.data("appCustomFile");if(typeof(app)=="undefined"){elem.obj.data("appCustomFile",[]);}
$.each(app,function(){appThis=this;$.each(appThis.itemFileList,function(index,element){formData.append(appThis.name,element.file);});});break;case"input":formData.append(elem.obj.attr("name"),elem.obj.val());break;}}}
return formData},ajax:function(el,options){if(typeof(el)==='string'){var element=this.getElements(el)[0];switch(element.type){case"form":var action=element.obj.attr("action");break;case"input":var action=element.obj.parents("form").attr("action");break;case"pseudoinput":var action=element.obj.form.attr("action");break;}
var formData=$.customFile.serialize(el);}
if(typeof(el)==='object'&&el instanceof FileItem){var formData=el.serialize();var action=el.app.form.attr("action");}
var defaults={cache:false,contentType:false,data:formData,processData:false,url:action,type:'POST',progressBar:{active:true,markup:'<div class="cf-progressbar-wr"><div class="cf-progressbar"><span width="0"></span></div></div>',appendTo:$('body'),removeAfterComplete:true,node:null},progress:function(e,total,position,percent){this.progressBar.node.find("span").width(percent+'%');},xhr:function(){var ax=this;var xhr=$.ajaxSettings.xhr();xhr.upload.onprogress=function(e){var e=e||window.event;var position=e.position||e.loaded;var total=e.totalSize||e.total;var percent=((e.loaded/e.total)*100)+"";ax.progress(e,total,position,percent);};xhr.upload.onload=function(){ax.progressBar.node.find("span").width('100%');if(ax.progressBar.removeAfterComplete)
ax.progressBar.node.fadeOut(function(){$(this).remove();});};return xhr;},beforeSend:function(){},complete:function(){},success:function(xml){},}
var settings=$.extend(true,{},defaults,options);if(!settings.progressBar.active)settings.progress=function(){};settings.progressBar.node=$(settings.progressBar.markup);var settBefore=settings.beforeSend;if(settings.progressBar.active){settings.beforeSend=function(){settBefore();settings.progressBar.appendTo.append(settings.progressBar.node);};}
$.ajax(settings);},validate:function(elements,options){elements=this.getElements(elements);for(j=0;j<elements.length;j++){el=elements[j];switch(el.type){case"form":break;case"input":break;case"pseudoinput":break;}}},popup:{wrapper:$('<div id="cif-msg-wr"><div class="cif-msg-close">close</div></div>'),open:function(){var popup=this;this.wrapper.find('.cif-msg-close').click(function(){popup.close()});$('body').append(popup.wrapper);},add:function(msg,autoclose,delay,type){if(!delay)delay=3000;switch(type){case"error":var icon='<span class="cif-msg-icon cif-msg-icon-error"></span>';break;case"ok":var icon='<span class="cif-msg-icon cif-msg-icon-ok"></span>';break;default:var icon='';}
var popup=this;if($('body').find(popup.wrapper).length<1)popup.open();this.wrapper.append('<div class="cif-msg">'+icon+msg+'</div>');if(typeof(fftimeout)!=='undefined')clearTimeout(fftimeout);if(autoclose)
fftimeout=setTimeout(function(){popup.close();},delay);},close:function(){this.wrapper.find(".cif-msg").remove();this.wrapper.detach();}}}
$.fn.customFile=function(options){return this.each(function(){var element=$(this);var tagName=element[0].tagName.toLowerCase();if(tagName=='input'){var customFile=new CustomFile(this,options);var prop=customFile.form
if(typeof(customFile.form.data("appCustomFile"))!="undefined"){var formData=customFile.form.data("appCustomFile");formData.push(customFile);}else{var formData=new Array(customFile);}
customFile.form.data("appCustomFile",formData);}});};})(jQuery);
+264
View File
@@ -0,0 +1,264 @@
/*
* Selects con datalist
*/
var click_in_process = false;
var visible = false;
$('.datalist-text .datalist-input').on('focusin', function () {
var elementRoot = $(this).parents('.datalist');
elementRoot.find(".icono").show();
elementRoot.find("ul").show();
elementRoot.find(".datalist-input").trigger("keyup");
});
function ocultaList(e) {
(e.data.padre).find('.icono').removeClass('ing-cancelar iconoAzul pointer').addClass('ing-buscar');
(e.data.padre).find('ul').hide();
// $('.datalist .icono').removeClass('ing-cancelar iconoAzul pointer').addClass('ing-buscar');
// $('.datalist ul').hide();
}
function ocultaTodos() {
$('.datalist .icono').removeClass('ing-cancelar iconoAzul pointer').addClass('ing-buscar');
$('.datalist ul').hide();
}
//$('.datalist-input').click(function(){
$(document).on('click', '.datalist-input', function () {
var elementRoot = $(this).parent();
limpiaInput({ "data": { "padre": elementRoot } });
const alreadyOpen = elementRoot.find('ul').is(':visible');
if (alreadyOpen) {
setTimeout(() => {
ocultaTodos();
}, 0);
// stop all jquery animations
return;
}
if (!elementRoot.hasClass("disabled")) {
elementRoot.find('ul').show();
elementRoot.find('.datalist-input').focus();
elementRoot.find('ul').show();
elementRoot.find('.icono').removeClass('ing-buscar').addClass('ing-cancelar iconoAzul pointer');
elementRoot.find('.icono').on('click', { "padre": elementRoot }, limpiaInput);
elementRoot.find('.icono').on('click', { "padre": elementRoot }, ocultaList);
}
// if other datalist is open, close it
$('.datalist').each(function () {
// get the input hidden from the datalist
var inputHidden = $(this).find('input[type="hidden"]').attr('id');
// get the input hidden from the datalist that was clicked
var inputHiddenClicked = elementRoot.find('input[type="hidden"]').attr('id');
if ($(this).find('ul').is(':visible') && inputHidden != inputHiddenClicked) {
$(this).find('ul').hide();
$(this).find('.icono').removeClass('ing-cancelar iconoAzul pointer').addClass('ing-buscar');
}
});
});
//usar class="selected" para marcar seleccioando por default
$(function () {
$.each($(".datalist").find('ul li:not(.not-selectable)'), function () {
if ($(this).hasClass("selected")) {
var elementRoot = $(this).parents('.datalist');
elementRoot.find('.datalist-input').html($(this).html().replace(/[\t\n]+/g, ' ').trim());
var cid = $(this).data('id');
elementRoot.find("input[type=hidden]").val(cid);
}
});
// add not-selectable class to all li elements and the .datalist-input element
$('.datalist-input ul li, .datalist-input').addClass('user-select-none');
});
$(document).on('click', '.datalist-select > ul li:not(.not-selectable)', function () {
var elementRoot = $(this).parents('.datalist');
elementRoot.find('.datalist-input').html($(this).html().replace(/[\t\n]+/g, ' ').trim());
// $(this).parent('ul').siblings('input[type="text"]').blur();
ocultaList({ "data": { "padre": elementRoot } });
var cid = $(this).data('id');
elementRoot.find("input[type=hidden]").val(cid);
elementRoot.find("li").removeClass("selected");
$(this).addClass("selected");
elementRoot.removeClass("datalist-invalid");
});
$('.modal').on('hide.bs.modal', function (e) {
$('.datalist .icono').removeClass('ing-cancelar iconoAzul pointer').addClass('ing-buscar');
$('.datalist ul').hide();
});
function setDatalist(selector, value = -1) {
var elementRoot = $(selector).parents('.datalist');
$.each(elementRoot.find('ul li:not(.not-selectable)'), function () {
if ($(this).data("id") == value) {
elementRoot.find('.datalist-input').text($(this).html().replace(/[\t\n]+/g, ' ').trim());
$(selector).val(value);
elementRoot.find("li").removeClass("selected");
$(this).addClass("selected");
}
});
}
function setDatalistFirst(selector) {
var index = 1;
var elementRoot = $(selector).parents('.datalist');
var num = elementRoot.find('ul li:not(.not-selectable)').length;
if (index <= num) {
while (elementRoot.find('ul li:nth-child(' + index + ')').hasClass("not-selectable") && index <= num) {
index++;
}
var element = elementRoot.find('ul li:nth-child(' + index + ')');
elementRoot.find('.datalist-input').text(element.html().replace(/[\t\n]+/g, ' ').trim());
$(selector).val(element.data("id"));
elementRoot.find("li").removeClass("selected");
element.addClass("selected");
}
}
function disableDatalist(selector, disabled = true) {
var elementRoot = $(selector).parents('.datalist');
if (disabled) {
elementRoot.addClass("disabled");
ocultaList({ "data": { "padre": elementRoot } });
} else
elementRoot.removeClass("disabled");
}
function invalidDatalist(selector, invalid = true) {
var elementRoot = $(selector).parents('.datalist');
if (invalid) {
elementRoot.addClass("datalist-invalid");
} else
elementRoot.removeClass("datalist-invalid");
}
function buscaDatalist(selector, valor) {
selector.find('ul li').each(function () {
var elem = $(this);
if ($(this).parent().is('li'))
elem = $(this).parent();
if (!$(this).html().toUpperCase().includes(valor.toUpperCase())) {
$(elem).hide();
selector.find('.datalist-input').val("");
selector.find("input[type=hidden]").val("");
} else
$(elem).show();
});
}
function getDatalistText(selector, valor) {
var elementRoot = $(selector).parents('.datalist');
var text = "";
$.each(elementRoot.find('ul li:not(.not-selectable)'), function () {
if ($(this).data("id") == valor) {
text = $(this).html();
}
});
return text;
}
//---
$('.datalist-text .datalist-input').keyup(function () {
var elementRoot = $(this).parents('.datalist');
var input = $(this);
elementRoot.find('ul li').each(function () {
var elem = $(this);
if ($(this).parent().is('li'))
elem = $(this).parent();
if (!$(this).html().toUpperCase().includes(input.val().toUpperCase()))
$(elem).hide();
else
$(elem).show();
});
});
/*
$('.datalist-text input').blur(function() {
var elementRoot = $(this).parents('.datalist');
console.log("Click? "+click_in_process);
if(!click_in_process) {
buscaDatalist(elementRoot, elementRoot.find('.datalist-input').val());
elementRoot.find('.icono').removeClass('ing-cancelar iconoAzul pointer').addClass('ing-buscar');
elementRoot.find('ul').children('li').show();
elementRoot.find('ul').hide();
}
click_in_process = false;
});
*/
$('.datalist-text > ul li:not(.not-selectable)').click(function () {
console.log("Li click!" + $(this).html());
var elementRoot = $(this).parents('.datalist');
elementRoot.find('.datalist-input').val($(this).html().replace(/[\t\n]+/g, ' ').trim());
//$(this).parent('ul').siblings('input[type="text"]').blur();
var cid = $(this).data('id');
elementRoot.find("input[type=hidden]").val(cid);
elementRoot.find("li").removeClass("selected");
$(this).addClass("selected");
click_in_process = true;
//elementRoot.find('.datalist-input').blur();
ocultaList({ "data": { "padre": elementRoot } });
});
/* $('.datalist-text .datalist-input').click(function () {
var elementRoot = $(this).parents('.datalist');
limpiaInput({ "data": { "padre": elementRoot } });
const alreadyOpen = elementRoot.find('ul').is(':visible');
console.log("Click! " + alreadyOpen);
elementRoot.find('ul').show();
elementRoot.find('input').focus();
elementRoot.find('ul').show();
elementRoot.find('.icono').removeClass('ing-buscar').addClass('ing-cancelar iconoAzul pointer');
elementRoot.find('.icono').on('click', { "padre": elementRoot }, limpiaInput);
}); */
$(document).on('click', function (e) {
var target = $(e.target);
// or if you click in the .datalist-input and the datalist is visible
let isDatalist = target.parents().addBack().is('.datalist');
// alert(isDatalist);
if (!isDatalist)
ocultaList({ "data": { "padre": $('.datalist') } });
// if the data list is visible and you click in the input, hide the list
});
function limpiaInput(e) {
(e.data.padre).find('.datalist-input').val('');
(e.data.padre).find('.datalist-input').parent().children('ul').children('li').show();
(e.data.padre).find('li:first').focus();
(e.data.padre).find('.datalist-input').focus();
}
// function make required
function makeRequiredDatalist(selector, required = true) {
var elementRoot = $(selector).parents('.datalist');
if (required)
elementRoot.addClass("required");
else
elementRoot.removeClass("required");
}
// function validate
function validateDatalist(selector) {
var elementRoot = $(selector).parents('.datalist');
if (elementRoot.hasClass("required") && $(selector).val() == "") {
invalidDatalist(selector, true);
return false;
}
invalidDatalist(selector, false);
return true;
}
+14
View File
@@ -0,0 +1,14 @@
// function that receives two hours in hh:mm format and compares as a spaceship operator
export function compareHours(h1, h2) {
const [h1h, h1m] = h1.split(":").map(Number);
const [h2h, h2m] = h2.split(":").map(Number);
if (h1h > h2h)
return 1;
if (h1h < h2h)
return -1;
if (h1m > h2m)
return 1;
if (h1m < h2m)
return -1;
return 0;
}
+37
View File
@@ -0,0 +1,37 @@
/* Inicialización en español para la extensión 'UI date picker' para jQuery. */
/* Traducido por Vester (xvester@gmail.com). */
( function( factory ) {
if ( typeof define === "function" && define.amd ) {
// AMD. Register as an anonymous module.
define( [ "../widgets/datepicker" ], factory );
} else {
// Browser globals
factory( jQuery.datepicker );
}
}( function( datepicker ) {
datepicker.regional.es = {
closeText: "Cerrar",
prevText: "&#x3C;Ant",
nextText: "Sig&#x3E;",
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é","jue","vie","sáb" ],
dayNamesMin: [ "D","L","M","X","J","V","S" ],
weekHeader: "Sm",
dateFormat: "dd/mm/yy",
firstDay: 1,
isRTL: false,
showMonthAfterYear: false,
yearSuffix: "" };
datepicker.setDefaults( datepicker.regional.es );
return datepicker.regional.es;
} ) );
View File
Whitespace-only changes.
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

+44
View File
@@ -0,0 +1,44 @@
var submit = function (url, data) {
// create a form
var form = document.createElement('form');
form.method = 'POST';
form.action = url;
form.style.display = 'none';
// add the form data to the form
for (var key in data) {
var input = document.createElement('input');
input.type = 'hidden';
input.name = key;
input.value = data[key];
form.appendChild(input);
}
// submit the form
document.body.appendChild(form);
form.submit();
}
var toFormData = function (obj) {
var formData = new FormData();
for (var key in obj) {
formData.append(key, obj[key]);
}
return formData;
}
var fetchPHP = async function (url, data = {}) {
return response = await fetch(
url,
{ method: 'POST', body: toFormData(data) }
)
.then(response => {
try {
return response.json()
}
catch (e) {
var message = 'Error en la respuesta del servidor';
Promise.reject(message)
}
})
.then(response => response.error ? Promise.reject(response.error) : Promise.resolve(response))
}
+414
View File
@@ -0,0 +1,414 @@
const compareHours = (hora1, hora2) => {
const [h1, m1] = hora1.split(":").map(Number);
const [h2, m2] = hora2.split(":").map(Number);
if (h1 !== h2) {
return h1 > h2 ? 1 : -1;
}
if (m1 !== m2) {
return m1 > m2 ? 1 : -1;
}
return 0;
};
let horarios = [];
const table = document.querySelector("table");
if (!(table instanceof HTMLTableElement)) {
triggerMessage("No se ha encontrado la tabla", "Error", "error");
throw new Error("No se ha encontrado la tabla");
}
[...Array(16).keys()].map(x => x + 7).forEach(hora => {
// add 7 rows for each hour
[0, 15, 30, 45].map((minute) => `${minute}`.padStart(2, '0')).forEach((minute) => {
const tr = document.createElement("tr");
tr.id = `hora-${hora}:${minute}`;
tr.classList.add(hora > 13 ? "tarde" : "mañana");
if (minute == "00") {
const th = document.createElement("th");
th.classList.add("text-center");
th.scope = "row";
th.rowSpan = 4;
th.innerText = `${hora}:00`;
th.style.verticalAlign = "middle";
tr.appendChild(th);
}
["lunes", "martes", "miércoles", "jueves", "viernes", "sábado"].forEach(día => {
const td = document.createElement("td");
td.id = `hora-${hora}:${minute}-${día}`;
tr.appendChild(td);
});
const tbody = document.querySelector("tbody#horario");
if (!(tbody instanceof HTMLTableSectionElement)) {
throw new Error("No se ha encontrado el tbody");
}
tbody.appendChild(tr);
});
});
const empty_table = table.cloneNode(true);
document.querySelectorAll('.hidden').forEach((element) => {
element.style.display = "none";
});
// hide the table
table.style.display = "none";
function moveHorario(id, día, hora) {
const formData = new FormData();
formData.append("id", id);
formData.append("hora", hora);
formData.append("día", día);
fetch("action/action_horario_update.php", {
method: "POST",
body: formData
}).then(res => res.json()).then(response => {
if (response.status == "success") {
triggerMessage("Horario movido", "Éxito", "success");
}
else {
triggerMessage(response.message, "Error");
}
}).then(() => {
renderHorario();
}).catch(err => {
triggerMessage(err, "Error");
});
}
function renderHorario() {
if (horarios.length == 0) {
triggerMessage("Este profesor hay horarios para mostrar", "Error", "info");
table.style.display = "none";
document.querySelectorAll('.hidden').forEach((element) => element.style.display = "none");
return;
}
// show the table
table.style.display = "table";
document.querySelectorAll('.hidden').forEach((element) => element.style.display = "block");
// clear the table
table.innerHTML = empty_table.outerHTML;
function conflicts(horario1, horario2) {
const { hora: hora_inicio1, hora_final: hora_final1, dia: dia1 } = horario1;
const { hora: hora_inicio2, hora_final: hora_final2, dia: dia2 } = horario2;
if (dia1 !== dia2) {
return false;
}
const compareInicios = compareHours(hora_inicio1, hora_inicio2);
const compareFinales = compareHours(hora_final1, hora_final2);
if (compareInicios >= 0 && compareInicios <= compareFinales ||
compareFinales >= 0 && compareFinales <= -compareInicios) {
return true;
}
return false;
}
// remove the next 5 cells
function removeNextCells(horas, minutos, dia, cells = 5) {
for (let i = 1; i <= cells; i++) {
const minute = minutos + i * 15;
const nextMinute = (minute % 60).toString().padStart(2, "0");
const nextHour = horas + Math.floor(minute / 60);
const cellId = `hora-${nextHour}:${nextMinute}-${dia}`;
const cellElement = document.getElementById(cellId);
if (cellElement) {
cellElement.remove();
}
else {
console.log(`No se ha encontrado la celda ${cellId}`);
break;
}
}
}
function newBlock(horario, edit = false) {
function move(horario, cells = 5) {
const [horas, minutos] = horario.hora.split(":").map(Number);
const cell = document.getElementById(`hora-${horas}:${minutos.toString().padStart(2, "0")}-${horario.dia}`);
const { top, left } = cell.getBoundingClientRect();
const block = document.getElementById(`block-${horario.id}`);
block.style.top = `${top}px`;
block.style.left = `${left}px`;
removeNextCells(horas, minutos, horario.dia, cells);
}
const [horas, minutos] = horario.hora.split(":").map(x => parseInt(x));
const hora = `${horas}:${minutos.toString().padStart(2, "0")}`;
horario.hora = hora;
const cell = document.getElementById(`hora-${horario.hora}-${horario.dia}`);
if (!cell)
return;
cell.dataset.ids = `${horario.id}`;
const float_menu = edit ?
`<div class="menu-flotante p-2" style="opacity: .7;">
<a class="mx-2" href="#" data-toggle="modal" data-target="#modal-editar">
<i class="ing-editar ing"></i>
</a>
<a class="mx-2" href="#" data-toggle="modal" data-target="#modal-borrar">
<i class="ing-basura ing"></i>
</a>
</div>`
: '';
cell.innerHTML =
`<div style="overflow-y: auto; overflow-x: hidden; height: 100%;" id="block-${horario.id}" class="position-absolute w-100 h-100">
<small class="text-gray">${horario.hora}</small>
<b class="title">${horario.materia}</b> <br>
<br><span>Salón: </span>${horario.salon} <br>
<small class="my-2">
${horario.profesores.map((profesor) => ` <span class="ing ing-formacion mx-1"></span>${profesor.grado ?? ''} ${profesor.profesor}`).join("<br>")}
</small>
</div>
${float_menu}`;
cell.classList.add("bloque-clase", "position-relative");
cell.rowSpan = horario.bloques;
// draggable
cell.draggable = write;
if (horario.bloques > 0) {
removeNextCells(horas, minutos, horario.dia, horario.bloques - 1);
}
}
function newConflictBlock(horarios, edit = false) {
const first_horario = horarios[0];
const [horas, minutos] = first_horario.hora.split(":").map(x => parseInt(x));
const hora = `${horas}:${minutos.toString().padStart(2, "0")}`;
const ids = horarios.map(horario => horario.id);
const cell = document.getElementById(`hora-${hora}-${first_horario.dia}`);
if (cell == null) {
console.error(`Error: No se encontró la celda: hora-${hora}-${first_horario.dia}`);
return;
}
cell.dataset.ids = ids.join(",");
// replace the content of the cell
cell.innerHTML = `
<small class='text-danger'>
${hora}
</small>
<div class="d-flex justify-content-center align-items-center mt-4">
<div class="d-flex flex-column justify-content-center align-items-center">
<span class="ing ing-importante text-danger" style="font-size: 2rem;"></span>
<b class='text-danger'>
Empalme de ${ids.length} horarios
</b>
<hr>
<i class="text-danger">Ver horarios &#8230;</i>
</div>
</div>
`;
// Add classes and attributes
cell.classList.add("conflict", "bloque-clase");
cell.setAttribute("role", "button");
// Add event listener for the cell
cell.addEventListener("click", () => {
$("#modal-choose").modal("show");
const ids = cell.getAttribute("data-ids").split(",").map(x => parseInt(x));
const tbody = document.querySelector("#modal-choose tbody");
tbody.innerHTML = "";
horarios.filter(horario => ids.includes(horario.id)).sort((a, b) => compareHours(a.hora, b.hora)).forEach(horario => {
tbody.innerHTML += `
<tr data-ids="${horario.id}">
<td><small>${horario.hora.slice(0, -3)}-${horario.hora_final.slice(0, -3)}</small></td>
<td>${horario.materia}</td>
<td>
${horario.profesores.map(({ grado, profesor }) => `${grado ?? ''} ${profesor}`).join(", ")}
</td>
<td>${horario.salon}</td>
${edit ? `
<td class="text-center">
<button class="btn btn-sm btn-primary dismiss-editar" data-toggle="modal" data-target="#modal-editar">
<i class="ing-editar ing"></i>
</button>
</td>
<td class="text-center">
<button class="btn btn-sm btn-danger dismiss-editar" data-toggle="modal" data-target="#modal-borrar">
<i class="ing-basura ing"></i>
</button>
</td>
` : ""}
</tr>`;
});
document.querySelectorAll(".dismiss-editar").forEach(btn => {
btn.addEventListener("click", () => $("#modal-choose").modal("hide"));
});
});
function getDuration(hora_i, hora_f) {
const [horas_i, minutos_i] = hora_i.split(":").map(x => parseInt(x));
const [horas_f, minutos_f] = hora_f.split(":").map(x => parseInt(x));
const date_i = new Date(0, 0, 0, horas_i, minutos_i);
const date_f = new Date(0, 0, 0, horas_f, minutos_f);
const diffInMilliseconds = date_f.getTime() - date_i.getTime();
const diffInMinutes = diffInMilliseconds / (1000 * 60);
const diffIn15MinuteIntervals = diffInMinutes / 15;
return Math.floor(diffIn15MinuteIntervals);
}
const maxHoraFinal = horarios.reduce((max, horario) => {
const [horas, minutos] = horario.hora_final.split(":").map(x => parseInt(x));
const date = new Date(0, 0, 0, horas, minutos);
return date > max ? date : max;
}, new Date(0, 0, 0, 0, 0));
const horaFinalMax = new Date(0, 0, 0, maxHoraFinal.getHours(), maxHoraFinal.getMinutes());
const blocks = getDuration(first_horario.hora, `${horaFinalMax.getHours()}:${horaFinalMax.getMinutes()}`);
cell.setAttribute("rowSpan", blocks.toString());
removeNextCells(horas, minutos, first_horario.dia, blocks - 1);
}
const conflictBlocks = horarios.filter((horario, index, arrayHorario) => arrayHorario.filter((_, i) => i != index).some(horario2 => conflicts(horario, horario2)))
.sort((a, b) => compareHours(a.hora, b.hora));
const classes = horarios.filter(horario => !conflictBlocks.includes(horario));
const conflictBlocksPacked = []; // array of sets
conflictBlocks.forEach(horario => {
const setIndex = conflictBlocksPacked.findIndex(set => set.some(horario2 => conflicts(horario, horario2)));
if (setIndex === -1) {
conflictBlocksPacked.push([horario]);
}
else {
conflictBlocksPacked[setIndex].push(horario);
}
});
classes.forEach(horario => newBlock(horario, write));
conflictBlocksPacked.forEach(horarios => newConflictBlock(horarios, write));
// remove the elements that are not in the limits
let max_hour = Math.max(...horarios.map(horario => {
const lastMoment = moment(horario.hora, "HH:mm").add(horario.bloques * 15, "minutes");
const lastHour = moment(`${lastMoment.hours()}:00`, "HH:mm");
const hourInt = parseInt(lastMoment.format("HH"));
return lastMoment.isSame(lastHour) ? hourInt - 1 : hourInt;
}));
let min_hour = Math.min(...horarios.map(horario => parseInt(horario.hora.split(":")[0])));
document.querySelectorAll("tbody#horario tr").forEach(hora => {
const hora_id = parseInt(hora.id.split("-")[1].split(":")[0]);
(hora_id < min_hour || hora_id > max_hour) ? hora.remove() : null;
});
// if there is no sábado, remove the column
if (!horarios.some(horario => horario.dia == "sábado")) {
document.querySelectorAll("tbody#horario td").forEach(td => {
if (td.id.split("-")[2] == "sábado") {
td.remove();
}
});
// remove the header (the last)
document.querySelector("#headers").lastElementChild.remove();
}
// adjust width
const ths = document.querySelectorAll("tr#headers th");
ths.forEach((th, key) => th.style.width = (key == 0) ? "5%" : `${95 / (ths.length - 1)}%`);
// search item animation
const menúFlontantes = document.querySelectorAll(".menu-flotante");
menúFlontantes.forEach((element) => {
element.classList.add("d-none");
element.parentElement.addEventListener("mouseover", () => element.classList.remove("d-none"));
element.parentElement.addEventListener("mouseout", (e) => element.classList.add("d-none"));
});
// droppables
// forall the .bloque-elements add the event listeners for drag and drop
document.querySelectorAll(".bloque-clase").forEach(element => {
function dragStart() {
this.classList.add("dragging");
}
function dragEnd() {
this.classList.remove("dragging");
}
element.addEventListener("dragstart", dragStart);
element.addEventListener("dragend", dragEnd);
});
// forall the cells that are not .bloque-clase add the event listeners for drag and drop
document.querySelectorAll("td:not(.bloque-clase)").forEach(element => {
function dragOver(e) {
e.preventDefault();
this.classList.add("dragging-over");
}
function dragLeave() {
this.classList.remove("dragging-over");
}
function drop() {
this.classList.remove("dragging-over");
const dragging = document.querySelector(".dragging");
const id = dragging.getAttribute("data-ids");
const hora = this.id.split("-")[1];
const días = ["lunes", "martes", "miércoles", "jueves", "viernes", "sábado"];
let día = this.id.split("-")[2];
día = días.indexOf(día) + 1;
// rowspan
const bloques = parseInt(dragging.getAttribute("rowspan"));
const horaMoment = moment(hora, "HH:mm");
const horaFin = horaMoment.add(bloques * 15, "minutes");
const limit = moment('22:00', 'HH:mm');
if (horaFin.isAfter(limit)) {
triggerMessage("No se puede mover el bloque a esa hora", "Error");
// scroll to the top
window.scrollTo(0, 0);
return;
}
// get the horario
// remove the horario
const bloque = document.querySelector(`.bloque-clase[data-ids="${id}"]`);
// remove all children
while (bloque.firstChild) {
bloque.removeChild(bloque.firstChild);
}
// prepend a loading child
const loading = `<div class="spinner-border" role="status" style="width: 3rem; height: 3rem;">
<span class="sr-only">Loading...</span>
</div>`;
bloque.insertAdjacentHTML("afterbegin", loading);
// add style vertical-align: middle
bloque.style.verticalAlign = "middle";
bloque.classList.add("text-center");
// remove draggable
bloque.removeAttribute("draggable");
moveHorario(id, día, hora);
}
element.addEventListener("dragover", dragOver);
element.addEventListener("dragleave", dragLeave);
element.addEventListener("drop", drop);
});
}
const form = document.getElementById('form');
if (!(form instanceof HTMLFormElement)) {
triggerMessage('No se ha encontrado el formulario', 'Error', 'danger');
throw new Error("No se ha encontrado el formulario");
}
form.querySelector('#clave_profesor').addEventListener('input', function (e) {
const input = form.querySelector('#clave_profesor');
const option = form.querySelector(`option[value="${input.value}"]`);
if (input.value == "") {
input.classList.remove("is-invalid", "is-valid");
return;
}
if (!option) {
input.classList.remove("is-valid");
input.classList.add("is-invalid");
}
else {
const profesor_id = form.querySelector('#profesor_id');
profesor_id.value = option.dataset.id;
input.classList.remove("is-invalid");
input.classList.add("is-valid");
}
});
form.addEventListener('submit', async function (e) {
e.preventDefault();
const input = form.querySelector('#clave_profesor');
if (input.classList.contains("is-invalid")) {
triggerMessage('El profesor no se encuentra registrado', 'Error', 'danger');
return;
}
const formData = new FormData(form);
try {
const buttons = document.querySelectorAll("button");
buttons.forEach(button => {
button.disabled = true;
button.classList.add("disabled");
});
const response = await fetch('action/action_horario_profesor.php', {
method: 'POST',
body: formData,
});
const data = await response.json();
buttons.forEach(button => {
button.disabled = false;
button.classList.remove("disabled");
});
if (data.status == 'success') {
horarios = data.data;
renderHorario();
}
else {
triggerMessage(data.message, 'Error en la consulta', 'warning');
}
}
catch (error) {
triggerMessage('Fallo al consutar los datos ', 'Error', 'danger');
console.log(error);
}
});
const input = form.querySelector('#clave_profesor');
const option = form.querySelector(`option[value="${input.value}"]`);
+30
View File
@@ -0,0 +1,30 @@
import 'es6-promise/auto';
declare function triggerMessage(message: string, title: string, type: string): void;
const form = document.getElementById('form') as HTMLFormElement;
if (form instanceof HTMLFormElement) {
form.addEventListener('submit', async function (e) {
e.preventDefault();
const formData = new FormData(form);
try {
const response = await fetch('action/action_horario_profesor.php', {
method: 'POST',
body: formData,
});
const data = await response.json();
if (data.status == 'ok') {
}
else {
triggerMessage(data.message, 'Error en la consulta', 'warning');
}
} catch (error) {
triggerMessage('Fallo al consutar los datos ', 'Error', 'danger');
}
});
}
else {
triggerMessage('No se ha encontrado el formulario', 'Error', 'danger');
}
+13
View File
@@ -0,0 +1,13 @@
/*! jQuery UI - v1.12.1 - 2016-09-14
* http://jqueryui.com
* Includes: widget.js, position.js, data.js, disable-selection.js, effect.js, effects/effect-blind.js, effects/effect-bounce.js, effects/effect-clip.js, effects/effect-drop.js, effects/effect-explode.js, effects/effect-fade.js, effects/effect-fold.js, effects/effect-highlight.js, effects/effect-puff.js, effects/effect-pulsate.js, effects/effect-scale.js, effects/effect-shake.js, effects/effect-size.js, effects/effect-slide.js, effects/effect-transfer.js, focusable.js, form-reset-mixin.js, jquery-1-7.js, keycode.js, labels.js, scroll-parent.js, tabbable.js, unique-id.js, widgets/accordion.js, widgets/autocomplete.js, widgets/button.js, widgets/checkboxradio.js, widgets/controlgroup.js, widgets/datepicker.js, widgets/dialog.js, widgets/draggable.js, widgets/droppable.js, widgets/menu.js, widgets/mouse.js, widgets/progressbar.js, widgets/resizable.js, widgets/selectable.js, widgets/selectmenu.js, widgets/slider.js, widgets/sortable.js, widgets/spinner.js, widgets/tabs.js, widgets/tooltip.js
* Copyright jQuery Foundation and other contributors; Licensed MIT */
(function(t){"function"==typeof define&&define.amd?define(["jquery"],t):t(jQuery)})(function(t){function e(t){for(var e=t.css("visibility");"inherit"===e;)t=t.parent(),e=t.css("visibility");return"hidden"!==e}function i(t){for(var e,i;t.length&&t[0]!==document;){if(e=t.css("position"),("absolute"===e||"relative"===e||"fixed"===e)&&(i=parseInt(t.css("zIndex"),10),!isNaN(i)&&0!==i))return i;t=t.parent()}return 0}function s(){this._curInst=null,this._keyEvent=!1,this._disabledInputs=[],this._datepickerShowing=!1,this._inDialog=!1,this._mainDivId="ui-datepicker-div",this._inlineClass="ui-datepicker-inline",this._appendClass="ui-datepicker-append",this._triggerClass="ui-datepicker-trigger",this._dialogClass="ui-datepicker-dialog",this._disableClass="ui-datepicker-disabled",this._unselectableClass="ui-datepicker-unselectable",this._currentClass="ui-datepicker-current-day",this._dayOverClass="ui-datepicker-days-cell-over",this.regional=[],this.regional[""]={closeText:"Done",prevText:"Prev",nextText:"Next",currentText:"Today",monthNames:["January","February","March","April","May","June","July","August","September","October","November","December"],monthNamesShort:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],dayNames:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],dayNamesShort:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],dayNamesMin:["Su","Mo","Tu","We","Th","Fr","Sa"],weekHeader:"Wk",dateFormat:"mm/dd/yy",firstDay:0,isRTL:!1,showMonthAfterYear:!1,yearSuffix:""},this._defaults={showOn:"focus",showAnim:"fadeIn",showOptions:{},defaultDate:null,appendText:"",buttonText:"...",buttonImage:"",buttonImageOnly:!1,hideIfNoPrevNext:!1,navigationAsDateFormat:!1,gotoCurrent:!1,changeMonth:!1,changeYear:!1,yearRange:"c-10:c+10",showOtherMonths:!1,selectOtherMonths:!1,showWeek:!1,calculateWeek:this.iso8601Week,shortYearCutoff:"+10",minDate:null,maxDate:null,duration:"fast",beforeShowDay:null,beforeShow:null,onSelect:null,onChangeMonthYear:null,onClose:null,numberOfMonths:1,showCurrentAtPos:0,stepMonths:1,stepBigMonths:12,altField:"",altFormat:"",constrainInput:!0,showButtonPanel:!1,autoSize:!1,disabled:!1},t.extend(this._defaults,this.regional[""]),this.regional.en=t.extend(!0,{},this.regional[""]),this.regional["en-US"]=t.extend(!0,{},this.regional.en),this.dpDiv=n(t("<div id='"+this._mainDivId+"' class='ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>"))}function n(e){var i="button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a";return e.on("mouseout",i,function(){t(this).removeClass("ui-state-hover"),-1!==this.className.indexOf("ui-datepicker-prev")&&t(this).removeClass("ui-datepicker-prev-hover"),-1!==this.className.indexOf("ui-datepicker-next")&&t(this).removeClass("ui-datepicker-next-hover")}).on("mouseover",i,o)}function o(){t.datepicker._isDisabledDatepicker(m.inline?m.dpDiv.parent()[0]:m.input[0])||(t(this).parents(".ui-datepicker-calendar").find("a").removeClass("ui-state-hover"),t(this).addClass("ui-state-hover"),-1!==this.className.indexOf("ui-datepicker-prev")&&t(this).addClass("ui-datepicker-prev-hover"),-1!==this.className.indexOf("ui-datepicker-next")&&t(this).addClass("ui-datepicker-next-hover"))}function a(e,i){t.extend(e,i);for(var s in i)null==i[s]&&(e[s]=i[s]);return e}function r(t){return function(){var e=this.element.val();t.apply(this,arguments),this._refresh(),e!==this.element.val()&&this._trigger("change")}}t.ui=t.ui||{},t.ui.version="1.12.1";var h=0,l=Array.prototype.slice;t.cleanData=function(e){return function(i){var s,n,o;for(o=0;null!=(n=i[o]);o++)try{s=t._data(n,"events"),s&&s.remove&&t(n).triggerHandler("remove")}catch(a){}e(i)}}(t.cleanData),t.widget=function(e,i,s){var n,o,a,r={},h=e.split(".")[0];e=e.split(".")[1];var l=h+"-"+e;return s||(s=i,i=t.Widget),t.isArray(s)&&(s=t.extend.apply(null,[{}].concat(s))),t.expr[":"][l.toLowerCase()]=function(e){return!!t.data(e,l)},t[h]=t[h]||{},n=t[h][e],o=t[h][e]=function(t,e){return this._createWidget?(arguments.length&&this._createWidget(t,e),void 0):new o(t,e)},t.extend(o,n,{version:s.version,_proto:t.extend({},s),_childConstructors:[]}),a=new i,a.options=t.widget.extend({},a.options),t.each(s,function(e,s){return t.isFunction(s)?(r[e]=function(){function t(){return i.prototype[e].apply(this,arguments)}function n(t){return i.prototype[e].apply(this,t)}return function(){var e,i=this._super,o=this._superApply;return this._super=t,this._superApply=n,e=s.apply(this,arguments),this._super=i,this._superApply=o,e}}(),void 0):(r[e]=s,void 0)}),o.prototype=t.widget.extend(a,{widgetEventPrefix:n?a.widgetEventPrefix||e:e},r,{constructor:o,namespace:h,widgetName:e,widgetFullName:l}),n?(t.each(n._childConstructors,function(e,i){var s=i.prototype;t.widget(s.namespace+"."+s.widgetName,o,i._proto)}),delete n._childConstructors):i._childConstructors.push(o),t.widget.bridge(e,o),o},t.widget.extend=function(e){for(var i,s,n=l.call(arguments,1),o=0,a=n.length;a>Line truncated
}}(t.fn.show),hide:function(t){return function(s){if(i(s))return t.apply(this,arguments);var n=e.apply(this,arguments);return n.mode="hide",this.effect.call(this,n)}}(t.fn.hide),toggle:function(t){return function(s){if(i(s)||"boolean"==typeof s)return t.apply(this,arguments);var n=e.apply(this,arguments);return n.mode="toggle",this.effect.call(this,n)}}(t.fn.toggle),cssUnit:function(e){var i=this.css(e),s=[];return t.each(["em","px","%","pt"],function(t,e){i.indexOf(e)>0&&(s=[parseFloat(i),e])}),s},cssClip:function(t){return t?this.css("clip","rect("+t.top+"px "+t.right+"px "+t.bottom+"px "+t.left+"px)"):s(this.css("clip"),this)},transfer:function(e,i){var s=t(this),n=t(e.to),o="fixed"===n.css("position"),a=t("body"),r=o?a.scrollTop():0,h=o?a.scrollLeft():0,l=n.offset(),c={top:l.top-r,left:l.left-h,height:n.innerHeight(),width:n.innerWidth()},u=s.offset(),d=t("<div class='ui-effects-transfer'></div>").appendTo("body").addClass(e.className).css({top:u.top-r,left:u.left-h,height:s.innerHeight(),width:s.innerWidth(),position:o?"fixed":"absolute"}).animate(c,e.duration,e.easing,function(){d.remove(),t.isFunction(i)&&i()})}}),t.fx.step.clip=function(e){e.clipInit||(e.start=t(e.elem).cssClip(),"string"==typeof e.end&&(e.end=s(e.end,e.elem)),e.clipInit=!0),t(e.elem).cssClip({top:e.pos*(e.end.top-e.start.top)+e.start.top,right:e.pos*(e.end.right-e.start.right)+e.start.right,bottom:e.pos*(e.end.bottom-e.start.bottom)+e.start.bottom,left:e.pos*(e.end.left-e.start.left)+e.start.left})}}(),function(){var e={};t.each(["Quad","Cubic","Quart","Quint","Expo"],function(t,i){e[i]=function(e){return Math.pow(e,t+2)}}),t.extend(e,{Sine:function(t){return 1-Math.cos(t*Math.PI/2)},Circ:function(t){return 1-Math.sqrt(1-t*t)},Elastic:function(t){return 0===t||1===t?t:-Math.pow(2,8*(t-1))*Math.sin((80*(t-1)-7.5)*Math.PI/15)},Back:function(t){return t*t*(3*t-2)},Bounce:function(t){for(var e,i=4;((e=Math.pow(2,--i))-1)/11>t;);return 1/Math.pow(4,3-i)-7.5625*Math.pow((3*e-2)/22-t,2)}}),t.each(e,function(e,i){t.easing["easeIn"+e]=i,t.easing["easeOut"+e]=function(t){return 1-i(1-t)},t.easing["easeInOut"+e]=function(t){return.5>t?i(2*t)/2:1-i(-2*t+2)/2}})}();var f=t.effects;t.effects.define("blind","hide",function(e,i){var s={up:["bottom","top"],vertical:["bottom","top"],down:["top","bottom"],left:["right","left"],horizontal:["right","left"],right:["left","right"]},n=t(this),o=e.direction||"up",a=n.cssClip(),r={clip:t.extend({},a)},h=t.effects.createPlaceholder(n);r.clip[s[o][0]]=r.clip[s[o][1]],"show"===e.mode&&(n.cssClip(r.clip),h&&h.css(t.effects.clipToBox(r)),r.clip=a),h&&h.animate(t.effects.clipToBox(r),e.duration,e.easing),n.animate(r,{queue:!1,duration:e.duration,easing:e.easing,complete:i})}),t.effects.define("bounce",function(e,i){var s,n,o,a=t(this),r=e.mode,h="hide"===r,l="show"===r,c=e.direction||"up",u=e.distance,d=e.times||5,p=2*d+(l||h?1:0),f=e.duration/p,g=e.easing,m="up"===c||"down"===c?"top":"left",_="up"===c||"left"===c,v=0,b=a.queue().length;for(t.effects.createPlaceholder(a),o=a.css(m),u||(u=a["top"===m?"outerHeight":"outerWidth"]()/3),l&&(n={opacity:1},n[m]=o,a.css("opacity",0).css(m,_?2*-u:2*u).animate(n,f,g)),h&&(u/=Math.pow(2,d-1)),n={},n[m]=o;d>v;v++)s={},s[m]=(_?"-=":"+=")+u,a.animate(s,f,g).animate(n,f,g),u=h?2*u:u/2;h&&(s={opacity:0},s[m]=(_?"-=":"+=")+u,a.animate(s,f,g)),a.queue(i),t.effects.unshift(a,b,p+1)}),t.effects.define("clip","hide",function(e,i){var s,n={},o=t(this),a=e.direction||"vertical",r="both"===a,h=r||"horizontal"===a,l=r||"vertical"===a;s=o.cssClip(),n.clip={top:l?(s.bottom-s.top)/2:s.top,right:h?(s.right-s.left)/2:s.right,bottom:l?(s.bottom-s.top)/2:s.bottom,left:h?(s.right-s.left)/2:s.left},t.effects.createPlaceholder(o),"show"===e.mode&&(o.cssClip(n.clip),n.clip=s),o.animate(n,{queue:!1,duration:e.duration,easing:e.easing,complete:i})}),t.effects.define("drop","hide",function(e,i){var s,n=t(this),o=e.mode,a="show"===o,r=e.direction||"left",h="up"===r||"down"===r?"top":"left",l="up"===r||"left"===r?"-=":"+=",c="+="===l?"-=":"+=",u={opacity:0};t.effects.createPlaceholder(n),s=e.distance||n["top"===h?"outerHeight":"outerWidth"](!0)/2,u[h]=l+s,a&&(n.css(u),u[h]=c+s,u.opacity=1),n.animate(u,{queue:!1,duration:e.duration,easing:e.easing,complete:i})}),t.effects.define("explode","hide",function(e,i){function s(){b.push(this),b.length===u*d&&n()}function n(){p.css({visibility:"visible"}),t(b).remove(),i()}var o,a,r,h,l,c,u=e.pieces?Math.round(Math.sqrt(e.pieces)):3,d=u,p=t(this),f=e.mode,g="show"===f,m=p.show().css("visibility","hidden").offset(),_=Math.ceil(p.outerWidth()/d),v=Math.ceil(p.outerHeight()/u),b=[];for(o=0;u>o;o++)for(h=m.top+o*v,c=o-(u-1)/2,a=0;d>a;a++)r=m.left+a*_,l=a-(d-1)/2,p.clone().appendTo("body").wrap("<div></div>").css({position:"absolute",visibility:"visible",left:-a*_,top:-o*v}).parent().addClass("ui-effects-explode").css({position:"absolute",overflow:"hidden",width:_,height:v,left:r+(g?l*_:0),top:h+(g?c*v:0),opacity:g?0:1}).animate({left:r+(g?0:l*_),top:h+(g?0:c*v),opacLine truncated
this.isMultiLine=o||!a&&this._isContentEditable(this.element),this.valueMethod=this.element[o||a?"val":"text"],this.isNewMenu=!0,this._addClass("ui-autocomplete-input"),this.element.attr("autocomplete","off"),this._on(this.element,{keydown:function(n){if(this.element.prop("readOnly"))return e=!0,s=!0,i=!0,void 0;e=!1,s=!1,i=!1;var o=t.ui.keyCode;switch(n.keyCode){case o.PAGE_UP:e=!0,this._move("previousPage",n);break;case o.PAGE_DOWN:e=!0,this._move("nextPage",n);break;case o.UP:e=!0,this._keyEvent("previous",n);break;case o.DOWN:e=!0,this._keyEvent("next",n);break;case o.ENTER:this.menu.active&&(e=!0,n.preventDefault(),this.menu.select(n));break;case o.TAB:this.menu.active&&this.menu.select(n);break;case o.ESCAPE:this.menu.element.is(":visible")&&(this.isMultiLine||this._value(this.term),this.close(n),n.preventDefault());break;default:i=!0,this._searchTimeout(n)}},keypress:function(s){if(e)return e=!1,(!this.isMultiLine||this.menu.element.is(":visible"))&&s.preventDefault(),void 0;if(!i){var n=t.ui.keyCode;switch(s.keyCode){case n.PAGE_UP:this._move("previousPage",s);break;case n.PAGE_DOWN:this._move("nextPage",s);break;case n.UP:this._keyEvent("previous",s);break;case n.DOWN:this._keyEvent("next",s)}}},input:function(t){return s?(s=!1,t.preventDefault(),void 0):(this._searchTimeout(t),void 0)},focus:function(){this.selectedItem=null,this.previous=this._value()},blur:function(t){return this.cancelBlur?(delete this.cancelBlur,void 0):(clearTimeout(this.searching),this.close(t),this._change(t),void 0)}}),this._initSource(),this.menu=t("<ul>").appendTo(this._appendTo()).menu({role:null}).hide().menu("instance"),this._addClass(this.menu.element,"ui-autocomplete","ui-front"),this._on(this.menu.element,{mousedown:function(e){e.preventDefault(),this.cancelBlur=!0,this._delay(function(){delete this.cancelBlur,this.element[0]!==t.ui.safeActiveElement(this.document[0])&&this.element.trigger("focus")})},menufocus:function(e,i){var s,n;return this.isNewMenu&&(this.isNewMenu=!1,e.originalEvent&&/^mouse/.test(e.originalEvent.type))?(this.menu.blur(),this.document.one("mousemove",function(){t(e.target).trigger(e.originalEvent)}),void 0):(n=i.item.data("ui-autocomplete-item"),!1!==this._trigger("focus",e,{item:n})&&e.originalEvent&&/^key/.test(e.originalEvent.type)&&this._value(n.value),s=i.item.attr("aria-label")||n.value,s&&t.trim(s).length&&(this.liveRegion.children().hide(),t("<div>").text(s).appendTo(this.liveRegion)),void 0)},menuselect:function(e,i){var s=i.item.data("ui-autocomplete-item"),n=this.previous;this.element[0]!==t.ui.safeActiveElement(this.document[0])&&(this.element.trigger("focus"),this.previous=n,this._delay(function(){this.previous=n,this.selectedItem=s})),!1!==this._trigger("select",e,{item:s})&&this._value(s.value),this.term=this._value(),this.close(e),this.selectedItem=s}}),this.liveRegion=t("<div>",{role:"status","aria-live":"assertive","aria-relevant":"additions"}).appendTo(this.document[0].body),this._addClass(this.liveRegion,null,"ui-helper-hidden-accessible"),this._on(this.window,{beforeunload:function(){this.element.removeAttr("autocomplete")}})},_destroy:function(){clearTimeout(this.searching),this.element.removeAttr("autocomplete"),this.menu.element.remove(),this.liveRegion.remove()},_setOption:function(t,e){this._super(t,e),"source"===t&&this._initSource(),"appendTo"===t&&this.menu.element.appendTo(this._appendTo()),"disabled"===t&&e&&this.xhr&&this.xhr.abort()},_isEventTargetInWidget:function(e){var i=this.menu.element[0];return e.target===this.element[0]||e.target===i||t.contains(i,e.target)},_closeOnClickOutside:function(t){this._isEventTargetInWidget(t)||this.close()},_appendTo:function(){var e=this.options.appendTo;return e&&(e=e.jquery||e.nodeType?t(e):this.document.find(e).eq(0)),e&&e[0]||(e=this.element.closest(".ui-front, dialog")),e.length||(e=this.document[0].body),e},_initSource:function(){var e,i,s=this;t.isArray(this.options.source)?(e=this.options.source,this.source=function(i,s){s(t.ui.autocomplete.filter(e,i.term))}):"string"==typeof this.options.source?(i=this.options.source,this.source=function(e,n){s.xhr&&s.xhr.abort(),s.xhr=t.ajax({url:i,data:e,dataType:"json",success:function(t){n(t)},error:function(){n([])}})}):this.source=this.options.source},_searchTimeout:function(t){clearTimeout(this.searching),this.searching=this._delay(function(){var e=this.term===this._value(),i=this.menu.element.is(":visible"),s=t.altKey||t.ctrlKey||t.metaKey||t.shiftKey;(!e||e&&!i&&!s)&&(this.selectedItem=null,this.search(null,t))},this.options.delay)},search:function(t,e){return t=null!=t?t:this._value(),this.term=this._value(),t.length<this.options.minLength?this.close(e):this._trigger("search",e)!==!1?this._search(t):void 0},_search:function(t){this.pending++,this._addClass("ui-autocomplete-loading"),this.cancelSearch=!1,this.source({term:t},this._response())},_response:function(){var e=++this.requestIndex;return t.proxy(function(t){e===this.requestIndex&&this.__response(t),this.pendinLine truncated
}},_updateDatepicker:function(e){this.maxRows=4,m=e,e.dpDiv.empty().append(this._generateHTML(e)),this._attachHandlers(e);var i,s=this._getNumberOfMonths(e),n=s[1],a=17,r=e.dpDiv.find("."+this._dayOverClass+" a");r.length>0&&o.apply(r.get(0)),e.dpDiv.removeClass("ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4").width(""),n>1&&e.dpDiv.addClass("ui-datepicker-multi-"+n).css("width",a*n+"em"),e.dpDiv[(1!==s[0]||1!==s[1]?"add":"remove")+"Class"]("ui-datepicker-multi"),e.dpDiv[(this._get(e,"isRTL")?"add":"remove")+"Class"]("ui-datepicker-rtl"),e===t.datepicker._curInst&&t.datepicker._datepickerShowing&&t.datepicker._shouldFocusInput(e)&&e.input.trigger("focus"),e.yearshtml&&(i=e.yearshtml,setTimeout(function(){i===e.yearshtml&&e.yearshtml&&e.dpDiv.find("select.ui-datepicker-year:first").replaceWith(e.yearshtml),i=e.yearshtml=null},0))},_shouldFocusInput:function(t){return t.input&&t.input.is(":visible")&&!t.input.is(":disabled")&&!t.input.is(":focus")},_checkOffset:function(e,i,s){var n=e.dpDiv.outerWidth(),o=e.dpDiv.outerHeight(),a=e.input?e.input.outerWidth():0,r=e.input?e.input.outerHeight():0,h=document.documentElement.clientWidth+(s?0:t(document).scrollLeft()),l=document.documentElement.clientHeight+(s?0:t(document).scrollTop());return i.left-=this._get(e,"isRTL")?n-a:0,i.left-=s&&i.left===e.input.offset().left?t(document).scrollLeft():0,i.top-=s&&i.top===e.input.offset().top+r?t(document).scrollTop():0,i.left-=Math.min(i.left,i.left+n>h&&h>n?Math.abs(i.left+n-h):0),i.top-=Math.min(i.top,i.top+o>l&&l>o?Math.abs(o+r):0),i},_findPos:function(e){for(var i,s=this._getInst(e),n=this._get(s,"isRTL");e&&("hidden"===e.type||1!==e.nodeType||t.expr.filters.hidden(e));)e=e[n?"previousSibling":"nextSibling"];return i=t(e).offset(),[i.left,i.top]},_hideDatepicker:function(e){var i,s,n,o,a=this._curInst;!a||e&&a!==t.data(e,"datepicker")||this._datepickerShowing&&(i=this._get(a,"showAnim"),s=this._get(a,"duration"),n=function(){t.datepicker._tidyDialog(a)},t.effects&&(t.effects.effect[i]||t.effects[i])?a.dpDiv.hide(i,t.datepicker._get(a,"showOptions"),s,n):a.dpDiv["slideDown"===i?"slideUp":"fadeIn"===i?"fadeOut":"hide"](i?s:null,n),i||n(),this._datepickerShowing=!1,o=this._get(a,"onClose"),o&&o.apply(a.input?a.input[0]:null,[a.input?a.input.val():"",a]),this._lastInput=null,this._inDialog&&(this._dialogInput.css({position:"absolute",left:"0",top:"-100px"}),t.blockUI&&(t.unblockUI(),t("body").append(this.dpDiv))),this._inDialog=!1)},_tidyDialog:function(t){t.dpDiv.removeClass(this._dialogClass).off(".ui-datepicker-calendar")},_checkExternalClick:function(e){if(t.datepicker._curInst){var i=t(e.target),s=t.datepicker._getInst(i[0]);(i[0].id!==t.datepicker._mainDivId&&0===i.parents("#"+t.datepicker._mainDivId).length&&!i.hasClass(t.datepicker.markerClassName)&&!i.closest("."+t.datepicker._triggerClass).length&&t.datepicker._datepickerShowing&&(!t.datepicker._inDialog||!t.blockUI)||i.hasClass(t.datepicker.markerClassName)&&t.datepicker._curInst!==s)&&t.datepicker._hideDatepicker()}},_adjustDate:function(e,i,s){var n=t(e),o=this._getInst(n[0]);this._isDisabledDatepicker(n[0])||(this._adjustInstDate(o,i+("M"===s?this._get(o,"showCurrentAtPos"):0),s),this._updateDatepicker(o))},_gotoToday:function(e){var i,s=t(e),n=this._getInst(s[0]);this._get(n,"gotoCurrent")&&n.currentDay?(n.selectedDay=n.currentDay,n.drawMonth=n.selectedMonth=n.currentMonth,n.drawYear=n.selectedYear=n.currentYear):(i=new Date,n.selectedDay=i.getDate(),n.drawMonth=n.selectedMonth=i.getMonth(),n.drawYear=n.selectedYear=i.getFullYear()),this._notifyChange(n),this._adjustDate(s)},_selectMonthYear:function(e,i,s){var n=t(e),o=this._getInst(n[0]);o["selected"+("M"===s?"Month":"Year")]=o["draw"+("M"===s?"Month":"Year")]=parseInt(i.options[i.selectedIndex].value,10),this._notifyChange(o),this._adjustDate(n)},_selectDay:function(e,i,s,n){var o,a=t(e);t(n).hasClass(this._unselectableClass)||this._isDisabledDatepicker(a[0])||(o=this._getInst(a[0]),o.selectedDay=o.currentDay=t("a",n).html(),o.selectedMonth=o.currentMonth=i,o.selectedYear=o.currentYear=s,this._selectDate(e,this._formatDate(o,o.currentDay,o.currentMonth,o.currentYear)))},_clearDate:function(e){var i=t(e);this._selectDate(i,"")},_selectDate:function(e,i){var s,n=t(e),o=this._getInst(n[0]);i=null!=i?i:this._formatDate(o),o.input&&o.input.val(i),this._updateAlternate(o),s=this._get(o,"onSelect"),s?s.apply(o.input?o.input[0]:null,[i,o]):o.input&&o.input.trigger("change"),o.inline?this._updateDatepicker(o):(this._hideDatepicker(),this._lastInput=o.input[0],"object"!=typeof o.input[0]&&o.input.trigger("focus"),this._lastInput=null)},_updateAlternate:function(e){var i,s,n,o=this._get(e,"altField");o&&(i=this._get(e,"altFormat")||this._get(e,"dateFormat"),s=this._getDate(e),n=this.formatDate(i,s,this._getFormatConfig(e)),t(o).val(n))},noWeekends:function(t){var e=t.getDay();return[e>0&&6>e,""]},iso8601Week:function(t){var e,i=new Date(t.getTime());return i.setDate(i.getDate()+4-(i.getDay()||7))Line truncated
},_cacheMargins:function(){this.margins={left:parseInt(this.element.css("marginLeft"),10)||0,top:parseInt(this.element.css("marginTop"),10)||0,right:parseInt(this.element.css("marginRight"),10)||0,bottom:parseInt(this.element.css("marginBottom"),10)||0}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var e,i,s,n=this.options,o=this.document[0];return this.relativeContainer=null,n.containment?"window"===n.containment?(this.containment=[t(window).scrollLeft()-this.offset.relative.left-this.offset.parent.left,t(window).scrollTop()-this.offset.relative.top-this.offset.parent.top,t(window).scrollLeft()+t(window).width()-this.helperProportions.width-this.margins.left,t(window).scrollTop()+(t(window).height()||o.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top],void 0):"document"===n.containment?(this.containment=[0,0,t(o).width()-this.helperProportions.width-this.margins.left,(t(o).height()||o.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top],void 0):n.containment.constructor===Array?(this.containment=n.containment,void 0):("parent"===n.containment&&(n.containment=this.helper[0].parentNode),i=t(n.containment),s=i[0],s&&(e=/(scroll|auto)/.test(i.css("overflow")),this.containment=[(parseInt(i.css("borderLeftWidth"),10)||0)+(parseInt(i.css("paddingLeft"),10)||0),(parseInt(i.css("borderTopWidth"),10)||0)+(parseInt(i.css("paddingTop"),10)||0),(e?Math.max(s.scrollWidth,s.offsetWidth):s.offsetWidth)-(parseInt(i.css("borderRightWidth"),10)||0)-(parseInt(i.css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left-this.margins.right,(e?Math.max(s.scrollHeight,s.offsetHeight):s.offsetHeight)-(parseInt(i.css("borderBottomWidth"),10)||0)-(parseInt(i.css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top-this.margins.bottom],this.relativeContainer=i),void 0):(this.containment=null,void 0)},_convertPositionTo:function(t,e){e||(e=this.position);var i="absolute"===t?1:-1,s=this._isRootNode(this.scrollParent[0]);return{top:e.top+this.offset.relative.top*i+this.offset.parent.top*i-("fixed"===this.cssPosition?-this.offset.scroll.top:s?0:this.offset.scroll.top)*i,left:e.left+this.offset.relative.left*i+this.offset.parent.left*i-("fixed"===this.cssPosition?-this.offset.scroll.left:s?0:this.offset.scroll.left)*i}},_generatePosition:function(t,e){var i,s,n,o,a=this.options,r=this._isRootNode(this.scrollParent[0]),h=t.pageX,l=t.pageY;return r&&this.offset.scroll||(this.offset.scroll={top:this.scrollParent.scrollTop(),left:this.scrollParent.scrollLeft()}),e&&(this.containment&&(this.relativeContainer?(s=this.relativeContainer.offset(),i=[this.containment[0]+s.left,this.containment[1]+s.top,this.containment[2]+s.left,this.containment[3]+s.top]):i=this.containment,t.pageX-this.offset.click.left<i[0]&&(h=i[0]+this.offset.click.left),t.pageY-this.offset.click.top<i[1]&&(l=i[1]+this.offset.click.top),t.pageX-this.offset.click.left>i[2]&&(h=i[2]+this.offset.click.left),t.pageY-this.offset.click.top>i[3]&&(l=i[3]+this.offset.click.top)),a.grid&&(n=a.grid[1]?this.originalPageY+Math.round((l-this.originalPageY)/a.grid[1])*a.grid[1]:this.originalPageY,l=i?n-this.offset.click.top>=i[1]||n-this.offset.click.top>i[3]?n:n-this.offset.click.top>=i[1]?n-a.grid[1]:n+a.grid[1]:n,o=a.grid[0]?this.originalPageX+Math.round((h-this.originalPageX)/a.grid[0])*a.grid[0]:this.originalPageX,h=i?o-this.offset.click.left>=i[0]||o-this.offset.click.left>i[2]?o:o-this.offset.click.left>=i[0]?o-a.grid[0]:o+a.grid[0]:o),"y"===a.axis&&(h=this.originalPageX),"x"===a.axis&&(l=this.originalPageY)),{top:l-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+("fixed"===this.cssPosition?-this.offset.scroll.top:r?0:this.offset.scroll.top),left:h-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+("fixed"===this.cssPosition?-this.offset.scroll.left:r?0:this.offset.scroll.left)}},_clear:function(){this._removeClass(this.helper,"ui-draggable-dragging"),this.helper[0]===this.element[0]||this.cancelHelperRemoval||this.helper.remove(),this.helper=null,this.cancelHelperRemoval=!1,this.destroyOnClear&&this.destroy()},_trigger:function(e,i,s){return s=s||this._uiHash(),t.ui.plugin.call(this,e,[i,s,this],!0),/^(drag|start|stop)/.test(e)&&(this.positionAbs=this._convertPositionTo("absolute"),s.offset=this.positionAbs),t.Widget.prototype._trigger.call(this,e,i,s)},plugins:{},_uiHash:function(){return{helper:this.helper,position:this.position,originalPosition:this.originalPosition,offset:this.positionAbs}}}),t.ui.plugin.add("draggable","connectToSortable",{start:function(e,i,s){var n=t.extend({},i,{item:s.element});s.sortables=[],t(s.options.connectToSortable).each(function(){var i=t(this).sortable("instance");i&&!i.options.disabled&&(s.sortables.push(i),i.refreshPositions(),i._trigger("activate",e,n))})},stop:function(e,i,s){var n=t.extend({},i,{item:s.eleLine truncated
},disable:t.noop,enable:t.noop,close:function(e){var i=this;this._isOpen&&this._trigger("beforeClose",e)!==!1&&(this._isOpen=!1,this._focusedElement=null,this._destroyOverlay(),this._untrackInstance(),this.opener.filter(":focusable").trigger("focus").length||t.ui.safeBlur(t.ui.safeActiveElement(this.document[0])),this._hide(this.uiDialog,this.options.hide,function(){i._trigger("close",e)}))},isOpen:function(){return this._isOpen},moveToTop:function(){this._moveToTop()},_moveToTop:function(e,i){var s=!1,n=this.uiDialog.siblings(".ui-front:visible").map(function(){return+t(this).css("z-index")}).get(),o=Math.max.apply(null,n);return o>=+this.uiDialog.css("z-index")&&(this.uiDialog.css("z-index",o+1),s=!0),s&&!i&&this._trigger("focus",e),s},open:function(){var e=this;return this._isOpen?(this._moveToTop()&&this._focusTabbable(),void 0):(this._isOpen=!0,this.opener=t(t.ui.safeActiveElement(this.document[0])),this._size(),this._position(),this._createOverlay(),this._moveToTop(null,!0),this.overlay&&this.overlay.css("z-index",this.uiDialog.css("z-index")-1),this._show(this.uiDialog,this.options.show,function(){e._focusTabbable(),e._trigger("focus")}),this._makeFocusTarget(),this._trigger("open"),void 0)},_focusTabbable:function(){var t=this._focusedElement;t||(t=this.element.find("[autofocus]")),t.length||(t=this.element.find(":tabbable")),t.length||(t=this.uiDialogButtonPane.find(":tabbable")),t.length||(t=this.uiDialogTitlebarClose.filter(":tabbable")),t.length||(t=this.uiDialog),t.eq(0).trigger("focus")},_keepFocus:function(e){function i(){var e=t.ui.safeActiveElement(this.document[0]),i=this.uiDialog[0]===e||t.contains(this.uiDialog[0],e);i||this._focusTabbable()}e.preventDefault(),i.call(this),this._delay(i)},_createWrapper:function(){this.uiDialog=t("<div>").hide().attr({tabIndex:-1,role:"dialog"}).appendTo(this._appendTo()),this._addClass(this.uiDialog,"ui-dialog","ui-widget ui-widget-content ui-front"),this._on(this.uiDialog,{keydown:function(e){if(this.options.closeOnEscape&&!e.isDefaultPrevented()&&e.keyCode&&e.keyCode===t.ui.keyCode.ESCAPE)return e.preventDefault(),this.close(e),void 0;if(e.keyCode===t.ui.keyCode.TAB&&!e.isDefaultPrevented()){var i=this.uiDialog.find(":tabbable"),s=i.filter(":first"),n=i.filter(":last");e.target!==n[0]&&e.target!==this.uiDialog[0]||e.shiftKey?e.target!==s[0]&&e.target!==this.uiDialog[0]||!e.shiftKey||(this._delay(function(){n.trigger("focus")}),e.preventDefault()):(this._delay(function(){s.trigger("focus")}),e.preventDefault())}},mousedown:function(t){this._moveToTop(t)&&this._focusTabbable()}}),this.element.find("[aria-describedby]").length||this.uiDialog.attr({"aria-describedby":this.element.uniqueId().attr("id")})},_createTitlebar:function(){var e;this.uiDialogTitlebar=t("<div>"),this._addClass(this.uiDialogTitlebar,"ui-dialog-titlebar","ui-widget-header ui-helper-clearfix"),this._on(this.uiDialogTitlebar,{mousedown:function(e){t(e.target).closest(".ui-dialog-titlebar-close")||this.uiDialog.trigger("focus")}}),this.uiDialogTitlebarClose=t("<button type='button'></button>").button({label:t("<a>").text(this.options.closeText).html(),icon:"ui-icon-closethick",showLabel:!1}).appendTo(this.uiDialogTitlebar),this._addClass(this.uiDialogTitlebarClose,"ui-dialog-titlebar-close"),this._on(this.uiDialogTitlebarClose,{click:function(t){t.preventDefault(),this.close(t)}}),e=t("<span>").uniqueId().prependTo(this.uiDialogTitlebar),this._addClass(e,"ui-dialog-title"),this._title(e),this.uiDialogTitlebar.prependTo(this.uiDialog),this.uiDialog.attr({"aria-labelledby":e.attr("id")})},_title:function(t){this.options.title?t.text(this.options.title):t.html("&#160;")},_createButtonPane:function(){this.uiDialogButtonPane=t("<div>"),this._addClass(this.uiDialogButtonPane,"ui-dialog-buttonpane","ui-widget-content ui-helper-clearfix"),this.uiButtonSet=t("<div>").appendTo(this.uiDialogButtonPane),this._addClass(this.uiButtonSet,"ui-dialog-buttonset"),this._createButtons()},_createButtons:function(){var e=this,i=this.options.buttons;return this.uiDialogButtonPane.remove(),this.uiButtonSet.empty(),t.isEmptyObject(i)||t.isArray(i)&&!i.length?(this._removeClass(this.uiDialog,"ui-dialog-buttons"),void 0):(t.each(i,function(i,s){var n,o;s=t.isFunction(s)?{click:s,text:i}:s,s=t.extend({type:"button"},s),n=s.click,o={icon:s.icon,iconPosition:s.iconPosition,showLabel:s.showLabel,icons:s.icons,text:s.text},delete s.click,delete s.icon,delete s.iconPosition,delete s.showLabel,delete s.icons,"boolean"==typeof s.text&&delete s.text,t("<button></button>",s).button(o).appendTo(e.uiButtonSet).on("click",function(){n.apply(e.element[0],arguments)})}),this._addClass(this.uiDialog,"ui-dialog-buttons"),this.uiDialogButtonPane.appendTo(this.uiDialog),void 0)},_makeDraggable:function(){function e(t){return{position:t.position,offset:t.offset}}var i=this,s=this.options;this.uiDialog.draggable({cancel:".ui-dialog-content, .ui-dialog-titlebar-close",handle:".ui-dialog-titlebar",containment:"document",start:functionLine truncated
},_refresh:function(){this._createRange(),this._createHandles(),this._setupEvents(),this._refreshValue()},_createHandles:function(){var e,i,s=this.options,n=this.element.find(".ui-slider-handle"),o="<span tabindex='0'></span>",a=[];for(i=s.values&&s.values.length||1,n.length>i&&(n.slice(i).remove(),n=n.slice(0,i)),e=n.length;i>e;e++)a.push(o);this.handles=n.add(t(a.join("")).appendTo(this.element)),this._addClass(this.handles,"ui-slider-handle","ui-state-default"),this.handle=this.handles.eq(0),this.handles.each(function(e){t(this).data("ui-slider-handle-index",e).attr("tabIndex",0)})},_createRange:function(){var e=this.options;e.range?(e.range===!0&&(e.values?e.values.length&&2!==e.values.length?e.values=[e.values[0],e.values[0]]:t.isArray(e.values)&&(e.values=e.values.slice(0)):e.values=[this._valueMin(),this._valueMin()]),this.range&&this.range.length?(this._removeClass(this.range,"ui-slider-range-min ui-slider-range-max"),this.range.css({left:"",bottom:""})):(this.range=t("<div>").appendTo(this.element),this._addClass(this.range,"ui-slider-range")),("min"===e.range||"max"===e.range)&&this._addClass(this.range,"ui-slider-range-"+e.range)):(this.range&&this.range.remove(),this.range=null)},_setupEvents:function(){this._off(this.handles),this._on(this.handles,this._handleEvents),this._hoverable(this.handles),this._focusable(this.handles)},_destroy:function(){this.handles.remove(),this.range&&this.range.remove(),this._mouseDestroy()},_mouseCapture:function(e){var i,s,n,o,a,r,h,l,c=this,u=this.options;return u.disabled?!1:(this.elementSize={width:this.element.outerWidth(),height:this.element.outerHeight()},this.elementOffset=this.element.offset(),i={x:e.pageX,y:e.pageY},s=this._normValueFromMouse(i),n=this._valueMax()-this._valueMin()+1,this.handles.each(function(e){var i=Math.abs(s-c.values(e));(n>i||n===i&&(e===c._lastChangedValue||c.values(e)===u.min))&&(n=i,o=t(this),a=e)}),r=this._start(e,a),r===!1?!1:(this._mouseSliding=!0,this._handleIndex=a,this._addClass(o,null,"ui-state-active"),o.trigger("focus"),h=o.offset(),l=!t(e.target).parents().addBack().is(".ui-slider-handle"),this._clickOffset=l?{left:0,top:0}:{left:e.pageX-h.left-o.width()/2,top:e.pageY-h.top-o.height()/2-(parseInt(o.css("borderTopWidth"),10)||0)-(parseInt(o.css("borderBottomWidth"),10)||0)+(parseInt(o.css("marginTop"),10)||0)},this.handles.hasClass("ui-state-hover")||this._slide(e,a,s),this._animateOff=!0,!0))},_mouseStart:function(){return!0},_mouseDrag:function(t){var e={x:t.pageX,y:t.pageY},i=this._normValueFromMouse(e);return this._slide(t,this._handleIndex,i),!1},_mouseStop:function(t){return this._removeClass(this.handles,null,"ui-state-active"),this._mouseSliding=!1,this._stop(t,this._handleIndex),this._change(t,this._handleIndex),this._handleIndex=null,this._clickOffset=null,this._animateOff=!1,!1},_detectOrientation:function(){this.orientation="vertical"===this.options.orientation?"vertical":"horizontal"},_normValueFromMouse:function(t){var e,i,s,n,o;return"horizontal"===this.orientation?(e=this.elementSize.width,i=t.x-this.elementOffset.left-(this._clickOffset?this._clickOffset.left:0)):(e=this.elementSize.height,i=t.y-this.elementOffset.top-(this._clickOffset?this._clickOffset.top:0)),s=i/e,s>1&&(s=1),0>s&&(s=0),"vertical"===this.orientation&&(s=1-s),n=this._valueMax()-this._valueMin(),o=this._valueMin()+s*n,this._trimAlignValue(o)},_uiHash:function(t,e,i){var s={handle:this.handles[t],handleIndex:t,value:void 0!==e?e:this.value()};return this._hasMultipleValues()&&(s.value=void 0!==e?e:this.values(t),s.values=i||this.values()),s},_hasMultipleValues:function(){return this.options.values&&this.options.values.length},_start:function(t,e){return this._trigger("start",t,this._uiHash(e))},_slide:function(t,e,i){var s,n,o=this.value(),a=this.values();this._hasMultipleValues()&&(n=this.values(e?0:1),o=this.values(e),2===this.options.values.length&&this.options.range===!0&&(i=0===e?Math.min(n,i):Math.max(n,i)),a[e]=i),i!==o&&(s=this._trigger("slide",t,this._uiHash(e,i,a)),s!==!1&&(this._hasMultipleValues()?this.values(e,i):this.value(i)))},_stop:function(t,e){this._trigger("stop",t,this._uiHash(e))},_change:function(t,e){this._keySliding||this._mouseSliding||(this._lastChangedValue=e,this._trigger("change",t,this._uiHash(e)))},value:function(t){return arguments.length?(this.options.value=this._trimAlignValue(t),this._refreshValue(),this._change(null,0),void 0):this._value()},values:function(e,i){var s,n,o;if(arguments.length>1)return this.options.values[e]=this._trimAlignValue(i),this._refreshValue(),this._change(null,e),void 0;if(!arguments.length)return this._values();if(!t.isArray(arguments[0]))return this._hasMultipleValues()?this._values(e):this.value();for(s=this.options.values,n=arguments[0],o=0;s.length>o;o+=1)s[o]=this._trimAlignValue(n[o]),this._change(null,o);this._refreshValue()},_setOption:function(e,i){var s,n=0;switch("range"===e&&this.options.range===!0&&("min"===i?(this.options.value=this._values(0),this.options.valuLine truncated
this._delay(function(){n===this.counter&&this.refreshPositions(!s)})},_clear:function(t,e){function i(t,e,i){return function(s){i._trigger(t,s,e._uiHash(e))}}this.reverting=!1;var s,n=[];if(!this._noFinalSort&&this.currentItem.parent().length&&this.placeholder.before(this.currentItem),this._noFinalSort=null,this.helper[0]===this.currentItem[0]){for(s in this._storedCSS)("auto"===this._storedCSS[s]||"static"===this._storedCSS[s])&&(this._storedCSS[s]="");this.currentItem.css(this._storedCSS),this._removeClass(this.currentItem,"ui-sortable-helper")}else this.currentItem.show();for(this.fromOutside&&!e&&n.push(function(t){this._trigger("receive",t,this._uiHash(this.fromOutside))}),!this.fromOutside&&this.domPosition.prev===this.currentItem.prev().not(".ui-sortable-helper")[0]&&this.domPosition.parent===this.currentItem.parent()[0]||e||n.push(function(t){this._trigger("update",t,this._uiHash())}),this!==this.currentContainer&&(e||(n.push(function(t){this._trigger("remove",t,this._uiHash())}),n.push(function(t){return function(e){t._trigger("receive",e,this._uiHash(this))}}.call(this,this.currentContainer)),n.push(function(t){return function(e){t._trigger("update",e,this._uiHash(this))}}.call(this,this.currentContainer)))),s=this.containers.length-1;s>=0;s--)e||n.push(i("deactivate",this,this.containers[s])),this.containers[s].containerCache.over&&(n.push(i("out",this,this.containers[s])),this.containers[s].containerCache.over=0);if(this.storedCursor&&(this.document.find("body").css("cursor",this.storedCursor),this.storedStylesheet.remove()),this._storedOpacity&&this.helper.css("opacity",this._storedOpacity),this._storedZIndex&&this.helper.css("zIndex","auto"===this._storedZIndex?"":this._storedZIndex),this.dragging=!1,e||this._trigger("beforeStop",t,this._uiHash()),this.placeholder[0].parentNode.removeChild(this.placeholder[0]),this.cancelHelperRemoval||(this.helper[0]!==this.currentItem[0]&&this.helper.remove(),this.helper=null),!e){for(s=0;n.length>s;s++)n[s].call(this,t);this._trigger("stop",t,this._uiHash())}return this.fromOutside=!1,!this.cancelHelperRemoval},_trigger:function(){t.Widget.prototype._trigger.apply(this,arguments)===!1&&this.cancel()},_uiHash:function(e){var i=e||this;return{helper:i.helper,placeholder:i.placeholder||t([]),position:i.position,originalPosition:i.originalPosition,offset:i.positionAbs,item:i.currentItem,sender:e?e.element:null}}}),t.widget("ui.spinner",{version:"1.12.1",defaultElement:"<input>",widgetEventPrefix:"spin",options:{classes:{"ui-spinner":"ui-corner-all","ui-spinner-down":"ui-corner-br","ui-spinner-up":"ui-corner-tr"},culture:null,icons:{down:"ui-icon-triangle-1-s",up:"ui-icon-triangle-1-n"},incremental:!0,max:null,min:null,numberFormat:null,page:10,step:1,change:null,spin:null,start:null,stop:null},_create:function(){this._setOption("max",this.options.max),this._setOption("min",this.options.min),this._setOption("step",this.options.step),""!==this.value()&&this._value(this.element.val(),!0),this._draw(),this._on(this._events),this._refresh(),this._on(this.window,{beforeunload:function(){this.element.removeAttr("autocomplete")}})},_getCreateOptions:function(){var e=this._super(),i=this.element;return t.each(["min","max","step"],function(t,s){var n=i.attr(s);null!=n&&n.length&&(e[s]=n)}),e},_events:{keydown:function(t){this._start(t)&&this._keydown(t)&&t.preventDefault()},keyup:"_stop",focus:function(){this.previous=this.element.val()},blur:function(t){return this.cancelBlur?(delete this.cancelBlur,void 0):(this._stop(),this._refresh(),this.previous!==this.element.val()&&this._trigger("change",t),void 0)},mousewheel:function(t,e){if(e){if(!this.spinning&&!this._start(t))return!1;this._spin((e>0?1:-1)*this.options.step,t),clearTimeout(this.mousewheelTimer),this.mousewheelTimer=this._delay(function(){this.spinning&&this._stop(t)},100),t.preventDefault()}},"mousedown .ui-spinner-button":function(e){function i(){var e=this.element[0]===t.ui.safeActiveElement(this.document[0]);e||(this.element.trigger("focus"),this.previous=s,this._delay(function(){this.previous=s}))}var s;s=this.element[0]===t.ui.safeActiveElement(this.document[0])?this.previous:this.element.val(),e.preventDefault(),i.call(this),this.cancelBlur=!0,this._delay(function(){delete this.cancelBlur,i.call(this)}),this._start(e)!==!1&&this._repeat(null,t(e.currentTarget).hasClass("ui-spinner-up")?1:-1,e)},"mouseup .ui-spinner-button":"_stop","mouseenter .ui-spinner-button":function(e){return t(e.currentTarget).hasClass("ui-state-active")?this._start(e)===!1?!1:(this._repeat(null,t(e.currentTarget).hasClass("ui-spinner-up")?1:-1,e),void 0):void 0},"mouseleave .ui-spinner-button":"_stop"},_enhance:function(){this.uiSpinner=this.element.attr("autocomplete","off").wrap("<span>").parent().append("<a></a><a></a>")},_draw:function(){this._enhance(),this._addClass(this.uiSpinner,"ui-spinner","ui-widget ui-widget-content"),this._addClass("ui-spinner-input"),this.element.attr("role","spinbutton"),this.buttons=this.uiSpinnLine truncated
+11
View File
@@ -0,0 +1,11 @@
/*!
* jQuery UI Touch Punch 0.2.3
*
* Copyright 2011–2014, Dave Furfero
* Dual licensed under the MIT or GPL Version 2 licenses.
*
* Depends:
* jquery.ui.widget.js
* jquery.ui.mouse.js
*/
!function (a) { function f(a, b) { if (!(a.originalEvent.touches.length > 1)) { a.preventDefault(); var c = a.originalEvent.changedTouches[0], d = document.createEvent("MouseEvents"); d.initMouseEvent(b, !0, !0, window, 1, c.screenX, c.screenY, c.clientX, c.clientY, !1, !1, !1, !1, 0, null), a.target.dispatchEvent(d) } } if (a.support.touch = "ontouchend" in document, a.support.touch) { var e, b = a.ui.mouse.prototype, c = b._mouseInit, d = b._mouseDestroy; b._touchStart = function (a) { var b = this; !e && b._mouseCapture(a.originalEvent.changedTouches[0]) && (e = !0, b._touchMoved = !1, f(a, "mouseover"), f(a, "mousemove"), f(a, "mousedown")) }, b._touchMove = function (a) { e && (this._touchMoved = !0, f(a, "mousemove")) }, b._touchEnd = function (a) { e && (f(a, "mouseup"), f(a, "mouseout"), this._touchMoved || f(a, "click"), e = !1) }, b._mouseInit = function () { var b = this; b.element.bind({ touchstart: a.proxy(b, "_touchStart"), touchmove: a.proxy(b, "_touchMove"), touchend: a.proxy(b, "_touchEnd") }), c.call(b) }, b._mouseDestroy = function () { var b = this; b.element.unbind({ touchstart: a.proxy(b, "_touchStart"), touchmove: a.proxy(b, "_touchMove"), touchend: a.proxy(b, "_touchEnd") }), d.call(b) } } }(jQuery);
+2
View File
@@ -0,0 +1,2 @@
/*! jQuery v3.3.1 | (c) JS Foundation and other contributors | jquery.org/license */
!function(e,t){"use strict";"object"==typeof module&&"object"==typeof module.exports?module.exports=e.document?t(e,!0):function(e){if(!e.document)throw new Error("jQuery requires a window with a document");return t(e)}:t(e)}("undefined"!=typeof window?window:this,function(e,t){"use strict";var n=[],r=e.document,i=Object.getPrototypeOf,o=n.slice,a=n.concat,s=n.push,u=n.indexOf,l={},c=l.toString,f=l.hasOwnProperty,p=f.toString,d=p.call(Object),h={},g=function e(t){return"function"==typeof t&&"number"!=typeof t.nodeType},y=function e(t){return null!=t&&t===t.window},v={type:!0,src:!0,noModule:!0};function m(e,t,n){var i,o=(t=t||r).createElement("script");if(o.text=e,n)for(i in v)n[i]&&(o[i]=n[i]);t.head.appendChild(o).parentNode.removeChild(o)}function x(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?l[c.call(e)]||"object":typeof e}var b="3.3.1",w=function(e,t){return new w.fn.init(e,t)},T=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;w.fn=w.prototype={jquery:"3.3.1",constructor:w,length:0,toArray:function(){return o.call(this)},get:function(e){return null==e?o.call(this):e<0?this[e+this.length]:this[e]},pushStack:function(e){var t=w.merge(this.constructor(),e);return t.prevObject=this,t},each:function(e){return w.each(this,e)},map:function(e){return this.pushStack(w.map(this,function(t,n){return e.call(t,n,t)}))},slice:function(){return this.pushStack(o.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(e){var t=this.length,n=+e+(e<0?t:0);return this.pushStack(n>=0&&n<t?[this[n]]:[])},end:function(){return this.prevObject||this.constructor()},push:s,sort:n.sort,splice:n.splice},w.extend=w.fn.extend=function(){var e,t,n,r,i,o,a=arguments[0]||{},s=1,u=arguments.length,l=!1;for("boolean"==typeof a&&(l=a,a=arguments[s]||{},s++),"object"==typeof a||g(a)||(a={}),s===u&&(a=this,s--);s<u;s++)if(null!=(e=arguments[s]))for(t in e)n=a[t],a!==(r=e[t])&&(l&&r&&(w.isPlainObject(r)||(i=Array.isArray(r)))?(i?(i=!1,o=n&&Array.isArray(n)?n:[]):o=n&&w.isPlainObject(n)?n:{},a[t]=w.extend(l,o,r)):void 0!==r&&(a[t]=r));return a},w.extend({expando:"jQuery"+("3.3.1"+Math.random()).replace(/\D/g,""),isReady:!0,error:function(e){throw new Error(e)},noop:function(){},isPlainObject:function(e){var t,n;return!(!e||"[object Object]"!==c.call(e))&&(!(t=i(e))||"function"==typeof(n=f.call(t,"constructor")&&t.constructor)&&p.call(n)===d)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},globalEval:function(e){m(e)},each:function(e,t){var n,r=0;if(C(e)){for(n=e.length;r<n;r++)if(!1===t.call(e[r],r,e[r]))break}else for(r in e)if(!1===t.call(e[r],r,e[r]))break;return e},trim:function(e){return null==e?"":(e+"").replace(T,"")},makeArray:function(e,t){var n=t||[];return null!=e&&(C(Object(e))?w.merge(n,"string"==typeof e?[e]:e):s.call(n,e)),n},inArray:function(e,t,n){return null==t?-1:u.call(t,e,n)},merge:function(e,t){for(var n=+t.length,r=0,i=e.length;r<n;r++)e[i++]=t[r];return e.length=i,e},grep:function(e,t,n){for(var r,i=[],o=0,a=e.length,s=!n;o<a;o++)(r=!t(e[o],o))!==s&&i.push(e[o]);return i},map:function(e,t,n){var r,i,o=0,s=[];if(C(e))for(r=e.length;o<r;o++)null!=(i=t(e[o],o,n))&&s.push(i);else for(o in e)null!=(i=t(e[o],o,n))&&s.push(i);return a.apply([],s)},guid:1,support:h}),"function"==typeof Symbol&&(w.fn[Symbol.iterator]=n[Symbol.iterator]),w.each("Boolean Number String Function Array Date RegExp Object Error Symbol".split(" "),function(e,t){l["[object "+t+"]"]=t.toLowerCase()});function C(e){var t=!!e&&"length"in e&&e.length,n=x(e);return!g(e)&&!y(e)&&("array"===n||0===t||"number"==typeof t&&t>0&&t-1 in e)}var E=function(e){var t,n,r,i,o,a,s,u,l,c,f,p,d,h,g,y,v,m,x,b="sizzle"+1*new Date,w=e.document,T=0,C=0,E=ae(),k=ae(),S=ae(),D=function(e,t){return e===t&&(f=!0),0},N={}.hasOwnProperty,A=[],j=A.pop,q=A.push,L=A.push,H=A.slice,O=function(e,t){for(var n=0,r=e.length;n<r;n++)if(e[n]===t)return n;return-1},P="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",M="[\\x20\\t\\r\\n\\f]",R="(?:\\\\.|[\\w-]|[^\0-\\xa0])+",I="\\["+M+"*("+R+")(?:"+M+"*([*^$|!~]?=)"+M+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+R+"))|)"+M+"*\\]",W=":("+R+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+I+")*)|.*)\\)|)",$=new RegExp(M+"+","g"),B=new RegExp("^"+M+"+|((?:^|[^\\\\])(?:\\\\.)*)"+M+"+$","g"),F=new RegExp("^"+M+"*,"+M+"*"),_=new RegExp("^"+M+"*([>+~]|"+M+")"+M+"*"),z=new RegExp("="+M+"*([^\\]'\"]*?)"+M+"*\\]","g"),X=new RegExp(W),U=new RegExp("^"+R+"$"),V={ID:new RegExp("^#("+R+")"),CLASS:new RegExp("^\\.("+R+")"),TAG:new RegExp("^("+R+"|[*])"),ATTR:new RegExp("^"+I),PSEUDO:new RegExp("^"+W),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+M+"*(even|odd|(([+-]|)(\\d*)n|)"+M+"*(?:([+-]|)"+M+"*(\\d+)|))"+M+"*\\)|)","i"),bool:new RegExp("^(?:"+P+")$","i"),needsContext:new RegExp("^"+M+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)Line truncated
+36
View File
@@ -0,0 +1,36 @@
function triggerMessage(message, header, color = "danger", selector = "message") {
const container = document.getElementById(selector);
container.innerHTML = '';
/* Template message_tmp */
var node = /* html */`
<article class="alert alert-${color} alert-dismissible fade show" role="alert" id="alert-color">
<h4 class="alert-heading"><span class="ing-${(color !== 'success') ? 'importante' : 'aceptar'}"></span> ${header}</h4>
<span id="message-alert">${message}</span>
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</article>
`
setTimeout(function () {
container.innerHTML = node;
}, 100);
/* setTimeout(function () {
container.innerHTML = '';
}, 5000); */
}
function messageMissingInputs(required) {
var message = 'Faltan los siguientes campos: ';
required.forEach(function (item, index) {
let last = required.length - 1;
if (index == last)
message += item;
else if (index == last - 1)
message += item + ' y ';
else
message += item + ', ';
});
triggerMessage(message, 'Error', 'danger');
}
+39
View File
@@ -0,0 +1,39 @@
<script>
function triggerMessage(message, header, color = "danger", selector = "message") {
const container = document.getElementById(selector);
let logo;
container.innerHTML = '';
/* Template message_tmp */
var node = /* html */`
<article class="alert alert-${color} alert-dismissible fade show" role="alert" id="alert-color">
<h4 class="alert-heading"><span class="ing-${(color !== 'success') ? 'importante' : 'aceptar'}"></span> ${header}</h4>
<span id="message-alert">${message}</span>
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</article>
`
setTimeout(function() {
container.innerHTML = node;
}, 100);
/* setTimeout(function() {
container.innerHTML = '';
}, 5000); */
}
function messageMissingInputs(required) {
var message = 'Faltan los siguientes campos: ';
required.forEach(function(item, index) {
let last = required.length - 1;
if (index == last)
message += item;
else if (index == last - 1)
message += item + ' y ';
else
message += item + ', ';
});
triggerMessage(message, 'Error', 'danger');
}
</script>
+2
View File
@@ -0,0 +1,2 @@
!function(e,a){"object"==typeof exports&&"undefined"!=typeof module?module.exports=a():"function"==typeof define&&define.amd?define(a):e.moment=a()}(this,function(){"use strict";var E;function M(){return E.apply(null,arguments)}function F(e){return e instanceof Array||"[object Array]"===Object.prototype.toString.call(e)}function z(e){return null!=e&&"[object Object]"===Object.prototype.toString.call(e)}function l(e,a){return Object.prototype.hasOwnProperty.call(e,a)}function N(e){if(Object.getOwnPropertyNames)return 0===Object.getOwnPropertyNames(e).length;for(var a in e)if(l(e,a))return;return 1}function d(e){return void 0===e}function J(e){return"number"==typeof e||"[object Number]"===Object.prototype.toString.call(e)}function R(e){return e instanceof Date||"[object Date]"===Object.prototype.toString.call(e)}function C(e,a){for(var t=[],s=e.length,n=0;n<s;++n)t.push(a(e[n],n));return t}function I(e,a){for(var t in a)l(a,t)&&(e[t]=a[t]);return l(a,"toString")&&(e.toString=a.toString),l(a,"valueOf")&&(e.valueOf=a.valueOf),e}function U(e,a,t,s){return Fa(e,a,t,s,!0).utc()}function h(e){return null==e._pf&&(e._pf={empty:!1,unusedTokens:[],unusedInput:[],overflow:-2,charsLeftOver:0,nullInput:!1,invalidEra:null,invalidMonth:null,invalidFormat:!1,userInvalidated:!1,iso:!1,parsedDateParts:[],era:null,meridiem:null,rfc2822:!1,weekdayMismatch:!1}),e._pf}function G(e){if(null==e._isValid){var a=h(e),t=B.call(a.parsedDateParts,function(e){return null!=e}),t=!isNaN(e._d.getTime())&&a.overflow<0&&!a.empty&&!a.invalidEra&&!a.invalidMonth&&!a.invalidWeekday&&!a.weekdayMismatch&&!a.nullInput&&!a.invalidFormat&&!a.userInvalidated&&(!a.meridiem||a.meridiem&&t);if(e._strict&&(t=t&&0===a.charsLeftOver&&0===a.unusedTokens.length&&void 0===a.bigHour),null!=Object.isFrozen&&Object.isFrozen(e))return t;e._isValid=t}return e._isValid}function V(e){var a=U(NaN);return null!=e?I(h(a),e):h(a).userInvalidated=!0,a}var B=Array.prototype.some||function(e){for(var a=Object(this),t=a.length>>>0,s=0;s<t;s++)if(s in a&&e.call(this,a[s],s,a))return!0;return!1},K=M.momentProperties=[],q=!1;function Z(e,a){var t,s,n,r=K.length;if(d(a._isAMomentObject)||(e._isAMomentObject=a._isAMomentObject),d(a._i)||(e._i=a._i),d(a._f)||(e._f=a._f),d(a._l)||(e._l=a._l),d(a._strict)||(e._strict=a._strict),d(a._tzm)||(e._tzm=a._tzm),d(a._isUTC)||(e._isUTC=a._isUTC),d(a._offset)||(e._offset=a._offset),d(a._pf)||(e._pf=h(a)),d(a._locale)||(e._locale=a._locale),0<r)for(t=0;t<r;t++)d(n=a[s=K[t]])||(e[s]=n);return e}function $(e){Z(this,e),this._d=new Date(null!=e._d?e._d.getTime():NaN),this.isValid()||(this._d=new Date(NaN)),!1===q&&(q=!0,M.updateOffset(this),q=!1)}function Q(e){return e instanceof $||null!=e&&null!=e._isAMomentObject}function X(e){!1===M.suppressDeprecationWarnings&&"undefined"!=typeof console&&console.warn&&console.warn("Deprecation warning: "+e)}function e(r,d){var i=!0;return I(function(){if(null!=M.deprecationHandler&&M.deprecationHandler(null,r),i){for(var e,a,t=[],s=arguments.length,n=0;n<s;n++){if(e="","object"==typeof arguments[n]){for(a in e+="\n["+n+"] ",arguments[0])l(arguments[0],a)&&(e+=a+": "+arguments[0][a]+", ");e=e.slice(0,-2)}else e=arguments[n];t.push(e)}X(r+"\nArguments: "+Array.prototype.slice.call(t).join("")+"\n"+(new Error).stack),i=!1}return d.apply(this,arguments)},d)}var ee={};function ae(e,a){null!=M.deprecationHandler&&M.deprecationHandler(e,a),ee[e]||(X(a),ee[e]=!0)}function te(e){return"undefined"!=typeof Function&&e instanceof Function||"[object Function]"===Object.prototype.toString.call(e)}function se(e,a){var t,s=I({},e);for(t in a)l(a,t)&&(z(e[t])&&z(a[t])?(s[t]={},I(s[t],e[t]),I(s[t],a[t])):null!=a[t]?s[t]=a[t]:delete s[t]);for(t in e)l(e,t)&&!l(a,t)&&z(e[t])&&(s[t]=I({},s[t]));return s}function ne(e){null!=e&&this.set(e)}M.suppressDeprecationWarnings=!1,M.deprecationHandler=null;var re=Object.keys||function(e){var a,t=[];for(a in e)l(e,a)&&t.push(a);return t};function de(e,a,t){var s=""+Math.abs(e);return(0<=e?t?"+":"":"-")+Math.pow(10,Math.max(0,a-s.length)).toString().substr(1)+s}var ie=/(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|N{1,5}|YYYYYY|YYYYY|YYYY|YY|y{2,4}|yo?|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g,_e=/(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g,oe={},me={};function s(e,a,t,s){var n="string"==typeof s?function(){return this[s]()}:s;e&&(me[e]=n),a&&(me[a[0]]=function(){return de(n.apply(this,arguments),a[1],a[2])}),t&&(me[t]=function(){return this.localeData().ordinal(n.apply(this,arguments),e)})}function ue(e,a){return e.isValid()?(a=le(a,e.localeData()),oe[a]=oe[a]||function(s){for(var e,n=s.match(ie),a=0,r=n.length;a<r;a++)me[n[a]]?n[a]=me[n[a]]:n[a]=(e=n[a]).match(/\[[\s\S]/)?e.replace(/^\[|\]$/g,""):e.replace(/\\/g,"");return function(e){for(var a="",t=0;t<r;t++)a+=te(n[t])?n[t].call(e,s):n[t];return a}}(a),oe[a](e)):e.localeData().invalidDate()}function le(e,a){var t=5;function s(e){return a.longDateFormat(e)||e}for(Line truncated
//# sourceMappingURL=moment-with-locales.min.js.map
+178
View File
@@ -0,0 +1,178 @@
// Get references to the HTML elements
const form = document.getElementById('form');
const steps = Array.from(form.querySelectorAll('.step'));
const nextButton = document.getElementById('next-button');
const prevButton = document.getElementById('prev-button');
let currentStep = 0;
// #clave_profesor on change => show step 2
const clave_profesor = document.getElementById('clave_profesor');
const horario_reponer = document.getElementById('horario_reponer');
const fechas_clase = document.getElementById('fechas_clase');
const fecha_reponer = $('#fecha_reponer');
const hora_reponer = $('#hora_reponer');
const minutos_reponer = $('#minutos_reponer');
clave_profesor.addEventListener('change', async () => {
const step2 = document.getElementById('step-2');
clave_profesor.disabled = true;
// get option which value is the same as clave_profesor.value
const option = document.querySelector(`option[value="${clave_profesor.value}"]`);
// make a form data with #form
const profesor_id = document.getElementById('profesor_id');
profesor_id.value = option.dataset.id;
const formData = new FormData(form);
const response = await fetch(`./action/action_horario_profesor.php`, {
method: 'POST',
body: formData
});
const data = await response.json();
if (data['success'] === false) {
const message = "Hubo un error al obtener los horarios del profesor.";
const title = 'Error';
const color = 'danger';
triggerMessage(message, title, color);
return;
}
const horarios = data.data;
const initial = document.createElement('option');
initial.value = '';
initial.textContent = 'Seleccione un horario';
initial.selected = true;
initial.disabled = true;
horario_reponer.innerHTML = '';
horario_reponer.appendChild(initial);
horarios.forEach((horario) => {
const dias = ['Lunes', 'Martes', 'Miercoles', 'Jueves', 'Viernes', 'Sabado', 'Domingo'];
const option = document.createElement('option');
option.value = `${horario.id}`;
// materia máx 25 caracteres, if materia.length > 25 then slice(0, 20)
const max = 25;
option.textContent = `${horario.materia.slice(0, max) + (horario.materia.length > max ? '...' : '')} - Grupo: ${horario.grupo} - ${horario.hora.slice(0, 5)}-${horario.hora_final.slice(0, 5)} - Salon: ${horario.salon} - ${horario.dia}`;
option.dataset.materia = `${horario.materia}`;
option.dataset.grupo = `${horario.grupo}`;
option.dataset.hora = `${horario.hora.slice(0, 5)}`; // slice(0, 5) => HH:MM
option.dataset.hora_final = `${horario.hora_final.slice(0, 5)}`;
option.dataset.salon = `${horario.salon}`;
option.dataset.dia = `${horario.dia}`;
option.dataset.id = `${horario.id}`;
horario_reponer.appendChild(option);
});
currentStep = 1;
step2.style.display = 'block';
prevButton.disabled = false;
});
// disable clave_profesor
// from second step to first step
prevButton.addEventListener('click', () => {
const inputs = [clave_profesor, horario_reponer, fechas_clase, fecha_reponer, hora_reponer];
switch (currentStep) {
case 1:
case 2:
case 3:
const step = document.getElementById(`step-${currentStep + 1}`);
step.style.display = 'none';
inputs[currentStep - 1].disabled = false;
inputs[currentStep - 1].value = '';
if (--currentStep === 0) {
prevButton.disabled = true;
}
break;
case 4:
const step5 = document.getElementById('step-5');
step5.style.display = 'none';
fecha_reponer.prop('disabled', false);
fecha_reponer.val('');
hora_reponer.parent().removeClass('disabled');
hora_reponer.siblings('.datalist-input').text('hh');
hora_reponer.val('');
minutos_reponer.parent().removeClass('disabled');
minutos_reponer.siblings('.datalist-input').text('mm');
minutos_reponer.val('');
currentStep--;
break;
}
nextButton.disabled = true;
});
// #horario_reponer on change => show step 3
horario_reponer.addEventListener('change', async () => {
const selected = horario_reponer.querySelector(`option[value="${horario_reponer.value}"]`);
horario_reponer.title = `Materia: ${selected.dataset.materia} - Grupo: ${selected.dataset.grupo} - Horario: ${selected.dataset.hora}-${selected.dataset.hora_final} - Salon: ${selected.dataset.salon} - Día: ${selected.dataset.dia}`;
const step3 = document.getElementById('step-3');
horario_reponer.disabled = true;
// make a form data with #form
const response = await fetch(`./action/action_fechas_clase.php?horario_id=${horario_reponer.value}`, {
method: 'GET',
});
const data = await response.json();
if (data['success'] === false) {
const message = "Hubo un error al obtener las fechas de clase.";
const title = 'Error';
const color = 'danger';
triggerMessage(message, title, color);
return;
}
const meses = ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'];
const fechas = data.data;
const initial = document.createElement('option');
initial.value = '';
initial.textContent = 'Seleccione la fecha de la falta';
initial.selected = true;
initial.disabled = true;
fechas_clase.innerHTML = '';
fechas_clase.appendChild(initial);
fechas_clase.title = 'Seleccione la fecha de la falta';
fechas.forEach((fecha) => {
const option = document.createElement('option');
option.value = `${fecha}`;
option.textContent = `${fecha.dia_mes} de ${meses[fecha.month - 1]} de ${fecha.year}`;
fechas_clase.appendChild(option);
});
step3.style.display = 'block';
currentStep = 2;
});
// #fechas_clase on change => show step 4
fechas_clase.addEventListener('change', () => {
const step4 = document.getElementById('step-4');
step4.style.display = 'block';
fechas_clase.disabled = true;
currentStep = 3;
});
// when both #fecha_reponer and #hora_reponer are selected => show step 5
const lastStep = () => {
// timeout to wait for the value to be set
setTimeout(() => {
if (fecha_reponer.val() !== '' && hora_reponer.val() !== '' && minutos_reponer.val() !== '') {
const step5 = document.getElementById('step-5');
step5.style.display = 'block';
// disable both
fecha_reponer.prop('disabled', true);
hora_reponer.parent().addClass('disabled');
minutos_reponer.parent().addClass('disabled');
const nextButton = document.getElementById('next-button');
// remove property disabled
nextButton.removeAttribute('disabled');
currentStep = 4;
}
}, 100);
};
fecha_reponer.on('change', lastStep);
// on click on the sibling ul>li of #hora_reponer and #minutos_reponer
hora_reponer.siblings('ul').children('li').on('click', lastStep);
minutos_reponer.siblings('ul').children('li').on('click', lastStep);
// Initialize the form
hideSteps();
showCurrentStep();
function hideSteps() {
steps.forEach((step) => {
step.style.display = 'none';
});
}
function showCurrentStep() {
steps[currentStep].style.display = 'block';
prevButton.disabled = currentStep === 0;
}
function handleSubmit(event) {
event.preventDefault();
// Handle form submission
// You can access the form data using the FormData API or serialize it manually
}
export {};
+1947
View File
File diff suppressed because it is too large. Load diff
+31
View File
@@ -0,0 +1,31 @@
const scrollButtons = `
<a href="#up" id="scroll-up" class="btn btn-primary btn-sm" role="button" aria-pressed="true" style="display: sticky; position: fixed; bottom: 3rem; right: 1rem;">
<span class="ing-caret ing-rotate-180 ing-fw"></span>
</a>
<a href="#down" id="scroll-down" class="btn btn-primary btn-sm" role="button" aria-pressed="true" style="display: sticky; position: fixed; bottom: 1rem; right: 1rem;">
<span class="ing-caret ing-fw"></span>
</a>
`
document.body.insertAdjacentHTML('beforeend', scrollButtons);
const scroll_up = document.querySelector('#scroll-up');
const scroll_down = document.querySelector('#scroll-down');
scroll_up.style.transition = scroll_down.style.transition = 'display 1.5s ease-in-out';
scroll_up.style.display = scroll_down.style.display = 'none';
scroll_up.addEventListener('click', () =>
window.scrollTo({ top: 0, behavior: 'smooth' }))
scroll_down.addEventListener('click', () =>
window.scrollTo({ top: document.body.scrollHeight, behavior: 'smooth' }))
const check = () => {
scroll_down.style.display = (window.scrollY + window.innerHeight) > document.body.scrollHeight * .8 ? 'none' : 'block'
scroll_up.style.display = (window.scrollY) < document.body.scrollHeight * .2 ? 'none' : 'block'
}
['scroll', 'resize'].forEach(e => window.addEventListener(e, check))
+49
View File
@@ -0,0 +1,49 @@
/*
* JQuery para el manejo de menu
*/
$('#dismiss, .overlay').on('click', function () {
// hide sidebar
$('#sidebar').removeClass('active');
// hide overlay
$('.overlay').removeClass('active');
$('.menu').css('visibility', 'visible');
});
$('#sidebarCollapse').on('click', function () {
// open sidebar
$('#sidebar').addClass('active');
// fade in the overlay
$('.overlay').addClass('active');
$('.menu').css('visibility', 'hidden');
//$('.collapse.in').toggleClass('in');
$('a[aria-expanded=true]').attr('aria-expanded', 'false');
});
/*
var Nightly = new Nightly(true, {
//body: "backgorund color", // Default: #282828
//texts: "texts color", // Default: #f5f5f5
//inputs: {
// color: "text color inside inputs", // Default: #f5f5f5
// backgroundColor: "background color" // Default #313131
//},
//buttons: {
// color: "button's text color", // Default: #f5f5f5
// backgroundColor: "button's backgournd color" // #757575
//},
links: "#ffffff", // Default: #009688
classes: [// Classes to apply when enabling the dark mode on certain elements
{ apply: 'bg-head-dark', to: 'bg-head', },
{ apply: 'form-control-dark', to: 'form-control', },
{ apply: 'subMenu-dark', to: 'subMenu', },
{ apply: 'sistema.text-white', to: 'sistema.text-secondary', },
]
});
if($(".fa-adjust")){
$(".fa-adjust").click(function(){
Nightly.toggle();
});
}*/
+187
View File
@@ -0,0 +1,187 @@
/*\
|*| ========================================================================
|*| Bootstrap Toggle: bootstrap4-toggle.js v3.6.1
|*| https://gitbrent.github.io/bootstrap4-toggle/
|*| ========================================================================
|*| Copyright 2018-2019 Brent Ely
|*| Licensed under MIT
|*| ========================================================================
\*/
+function ($) {
'use strict';
// TOGGLE PUBLIC CLASS DEFINITION
// ==============================
var Toggle = function (element, options) {
this.$element = $(element)
this.options = $.extend({}, this.defaults(), options)
this.render()
}
Toggle.VERSION = '3.7.0-beta'
Toggle.DEFAULTS = {
on: 'On',
off: 'Off',
onstyle: 'primary',
offstyle: 'light',
size: 'normal',
style: '',
width: null,
height: null
}
Toggle.prototype.defaults = function() {
return {
on: this.$element.attr('data-on') || Toggle.DEFAULTS.on,
off: this.$element.attr('data-off') || Toggle.DEFAULTS.off,
onstyle: this.$element.attr('data-onstyle') || Toggle.DEFAULTS.onstyle,
offstyle: this.$element.attr('data-offstyle') || Toggle.DEFAULTS.offstyle,
size: this.$element.attr('data-size') || Toggle.DEFAULTS.size,
style: this.$element.attr('data-style') || Toggle.DEFAULTS.style,
width: this.$element.attr('data-width') || Toggle.DEFAULTS.width,
height: this.$element.attr('data-height') || Toggle.DEFAULTS.height
}
}
Toggle.prototype.render = function () {
this._onstyle = 'btn-' + this.options.onstyle
this._offstyle = 'btn-' + this.options.offstyle
var size
= this.options.size === 'large' || this.options.size === 'lg' ? 'btn-lg'
: this.options.size === 'small' || this.options.size === 'sm' ? 'btn-sm'
: this.options.size === 'mini' || this.options.size === 'xs' ? 'btn-xs'
: ''
var $toggleOn = $('<label for="'+ this.$element.prop('id') +'" class="btn">').html(this.options.on)
.addClass(this._onstyle + ' ' + size)
var $toggleOff = $('<label for="'+ this.$element.prop('id') +'" class="btn">').html(this.options.off)
.addClass(this._offstyle + ' ' + size)
var $toggleHandle = $('<span class="toggle-handle btn btn-light">')
.addClass(size)
var $toggleGroup = $('<div class="toggle-group">')
.append($toggleOn, $toggleOff, $toggleHandle)
var $toggle = $('<div class="toggle btn" data-toggle="toggle" role="button">')
.addClass( this.$element.prop('checked') ? this._onstyle : this._offstyle+' off' )
.addClass(size).addClass(this.options.style)
this.$element.wrap($toggle)
$.extend(this, {
$toggle: this.$element.parent(),
$toggleOn: $toggleOn,
$toggleOff: $toggleOff,
$toggleGroup: $toggleGroup
})
this.$toggle.append($toggleGroup)
var width = this.options.width || Math.max($toggleOn.outerWidth(), $toggleOff.outerWidth())+($toggleHandle.outerWidth()/2)
var height = this.options.height || Math.max($toggleOn.outerHeight(), $toggleOff.outerHeight())
$toggleOn.addClass('toggle-on')
$toggleOff.addClass('toggle-off')
this.$toggle.css({ width: width, height: height })
if (this.options.height) {
$toggleOn.css('line-height', $toggleOn.height() + 'px')
$toggleOff.css('line-height', $toggleOff.height() + 'px')
}
this.update(true)
this.trigger(true)
}
Toggle.prototype.toggle = function () {
if (this.$element.prop('checked')) this.off()
else this.on()
}
Toggle.prototype.on = function (silent) {
if (this.$element.prop('disabled')) return false
this.$toggle.removeClass(this._offstyle + ' off').addClass(this._onstyle)
this.$element.prop('checked', true)
if (!silent) this.trigger()
}
Toggle.prototype.off = function (silent) {
if (this.$element.prop('disabled')) return false
this.$toggle.removeClass(this._onstyle).addClass(this._offstyle + ' off')
this.$element.prop('checked', false)
if (!silent) this.trigger()
}
Toggle.prototype.enable = function () {
this.$toggle.removeClass('disabled')
this.$toggle.removeAttr('disabled')
this.$element.prop('disabled', false)
}
Toggle.prototype.disable = function () {
this.$toggle.addClass('disabled')
this.$toggle.attr('disabled', 'disabled')
this.$element.prop('disabled', true)
}
Toggle.prototype.update = function (silent) {
if (this.$element.prop('disabled')) this.disable()
else this.enable()
if (this.$element.prop('checked')) this.on(silent)
else this.off(silent)
}
Toggle.prototype.trigger = function (silent) {
this.$element.off('change.bs.toggle')
if (!silent) this.$element.change()
this.$element.on('change.bs.toggle', $.proxy(function() {
this.update()
}, this))
}
Toggle.prototype.destroy = function() {
this.$element.off('change.bs.toggle')
this.$toggleGroup.remove()
this.$element.removeData('bs.toggle')
this.$element.unwrap()
}
// TOGGLE PLUGIN DEFINITION
// ========================
function Plugin(option) {
var optArg = Array.prototype.slice.call( arguments, 1 )[0]
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.toggle')
var options = typeof option == 'object' && option
if (!data) $this.data('bs.toggle', (data = new Toggle(this, options)))
if (typeof option === 'string' && data[option] && typeof optArg === 'boolean') data[option](optArg)
else if (typeof option === 'string' && data[option]) data[option]()
//else if (option && !data[option]) console.log('bootstrap-toggle: error: method `'+ option +'` does not exist!');
})
}
var old = $.fn.bootstrapToggle
$.fn.bootstrapToggle = Plugin
$.fn.bootstrapToggle.Constructor = Toggle
// TOGGLE NO CONFLICT
// ==================
$.fn.toggle.noConflict = function () {
$.fn.bootstrapToggle = old
return this
}
// TOGGLE DATA-API
// ===============
$(function() {
$('input[type=checkbox][data-toggle^=toggle]').bootstrapToggle()
})
$(document).on('click.bs.toggle', 'div[data-toggle^=toggle]', function(e) {
var $checkbox = $(this).find('input[type=checkbox]')
$checkbox.bootstrapToggle('toggle')
e.preventDefault()
})
}(jQuery);
+105
View File
@@ -0,0 +1,105 @@
/*
* utilidades js
*/
function trim(cadena){
for(i=0; i<cadena.length; ){
if(cadena.charAt(i)==" ")
cadena=cadena.substring(i+1, cadena.length);
else
break;
}
for(i=cadena.length-1; i>=0; i=cadena.length-1){
if(cadena.charAt(i)==" ")
cadena=cadena.substring(0,i);
else
break;
}
return cadena;
}
function getDiaNombre(num){
switch(parseInt(num)){
case 0: return "Domingo";
case 1: return "Lunes";
case 2: return "Martes";
case 3: return "Miércoles";
case 4: return "Jueves";
case 5: return "Viernes";
case 6: return "Sábado";
}
}
function fechaGuion(fechaTxt){//de dd/mm/aaaa a aaaa-mm-dd
fechaTxt = trim(fechaTxt);
if(fechaTxt.substr(2,1) == "/" && fechaTxt.substr(5,1) == "/"){// dd/mm/aaaa
var fechaArr = fechaTxt.split("/");
return fechaArr[2]+"-"+fechaArr[1]+"-"+fechaArr[0];
}
if(fechaTxt.substr(4,1) == "-" && fechaTxt.substr(7,1) == "-")// aaaa-mm-dd
return fechaTxt;
return "";
}
function fechaObjeto(fechaTxt){//de dd/mm/aaaa a aaaa-mm-dd
fechaTxt = trim(fechaTxt);
if(fechaTxt.substr(2,1) == "/" && fechaTxt.substr(5,1) == "/"){// dd/mm/aaaa
var fechaArr = fechaTxt.split("/");
return new Date(parseInt(fechaArr[2]), parseInt(fechaArr[1])-1, parseInt(fechaArr[0]) );
}
if(fechaTxt.substr(4,1) == "-" && fechaTxt.substr(7,1) == "-"){// aaaa-mm-dd
var fechaArr = fechaTxt.split("-");
return new Date(parseInt(fechaArr[0]), parseInt(fechaArr[1])-1, parseInt(fechaArr[2]) );
}
return false;
}
function validaFecha(fechaTxt){
if(fechaTxt.charAt(4) == "-" && fechaTxt.charAt(7) == "-"){//yyyy-mm-dd
var fechaArr = fechaTxt.split("-");
var ano= fechaArr[0];
var mes= fechaArr[1];
var dia= fechaArr[2];
}
if(fechaTxt.charAt(2) == "/" && fechaTxt.charAt(5) == "/"){//dd-mm-aaaa
var fechaArr = fechaTxt.split("/");
var ano= fechaArr[2];
var mes= fechaArr[1];
var dia= fechaArr[0];
}
var d = new Date();
var anoActual = d.getFullYear();
if (isNaN(ano) || ano.length < 4 || parseInt(ano, 10) < (anoActual-1)){ return false; }
if (isNaN(mes) || parseInt(mes, 10) < 1 || parseInt(mes, 10) > 12){ return false; }
if (isNaN(dia) || parseInt(dia, 10) < 1 || parseInt(dia, 10) > 31){ return false; }
if (mes == 4 || mes == 6 || mes == 9 || mes== 11) {
if (dia > 30) { return false; }
} else{
if (mes == 2) {
if(dia <= 28 )
return true;
else{
if ((ano % 4 == 0) && dia == 29) return true;
else return false;
}
}
}
return true;
}
function validaPass(str, vacio = false){
if(vacio && str == "") return true;
return str.match(/\S*(?=\S{5,})(?=\S*[a-zA-Z])(?=\S*[\d])(?=\S*[\W])\S*$/);
}
/*
$('.toggle-password').click(function(){
var campo = $(this).parents(".form-group").find(".toggle-field");
if (campo.prop('type') === "password") {
campo.prop('type', 'text');
} else {
campo.prop('type', 'password');
}
});*/
+65
View File
@@ -0,0 +1,65 @@
$(".date-picker").datepicker($.datepicker.regional["es"]);
$(".date-picker").datepicker({
dateFormat: "dd/mm/yyyy",
changeMonth: true,
});
$("#fecha_inicial").datepicker("option", "minDate", fecha_inicial);
$("#fecha_inicial").datepicker("option", "maxDate", limit);
$("#fecha_final").datepicker("option", "minDate", fecha_inicial);
$("#fecha_final").datepicker("option", "maxDate", limit);
var today = new Date();
var fecha_inicial = new Date(<?= isset($fecha_inicial) ? $fecha_inicial->format("Y, m-1, d") : date("Y, m-1, d", strtotime($periodo['inicio'])) ?>);
var fecha_final = new Date(<?= isset($fecha_final) ? $fecha_final->format("Y, m-1, d") : date("Y, m-1, d", strtotime($periodo['fin'])) ?>);
var limit = new Date(Math.min(today, fecha_final));
// if today is in the period, set the initial date to today
$("#fecha_inicial").datepicker("setDate", fecha_inicial);
$("#fecha_final").datepicker("setDate", today <= fecha_final ? today : fecha_final);
function reset_form() {
$("#fecha_inicial").datepicker("setDate", fecha_inicial);
$("#fecha_final").datepicker("setDate", today <= fecha_final ? today : fecha_final);
$("#dlcarrera").find("li").removeClass("selected");
$("#dlcarrera").find("li[data-value='0']").addClass("selected");
$("#dlmateria").find("li").removeClass("selected");
$("#dlmateria").find("li[data-value='0']").addClass("selected");
$("#filter_carrera").val("");
$("#filter_materia").val("");
console.log(`Todos los campos han sido limpiados.`);
}
<?php if (empty($carrera)) { ?>
disableDatalist("#filter_materia", true);
<?php } ?>
reset_form();
// $("#fecha_inicial").on("change", function() {
// var fecha_inicial = $("#fecha_inicial").datepicker("getDate");
// var fecha_final = $("#fecha_final").datepicker("getDate");
// if (fecha_final < fecha_inicial) {
// $("#fecha_final").datepicker("setDate", fecha_inicial);
// }
// $("#fecha_final").datepicker("option", "minDate", fecha_inicial);
// });
// $("#fecha_final").on("change", function() {
// var fecha_inicial = $("#fecha_inicial").datepicker("getDate");
// var fecha_final = $("#fecha_final").datepicker("getDate");
// if (fecha_final < fecha_inicial) {
// $("#fecha_inicial").datepicker("setDate", fecha_final);
// }
// $("#fecha_inicial").datepicker("option", "maxDate", fecha_final);
// });
// Datalist carrera then select materia
$(document).on('click', '#dlcarrera li', function() {
// if this is empty
// console.log($(this).attr('data-value'));
if ($(this).attr('data-value') == '0')
disableDatalist("#filter_materia", true);
});