/* * Para crear horario de administrativos */ $(document).ready(function(){ loadHorarioEdicion(); $('#modal_confirm').on('show.bs.modal', function (event) { var button = $(event.relatedTarget); // Button that triggered the modal var id = button.parents(".bloque-clase").data("id_obj"); $("#id_borrar").val(id); }); $('.editable').click(function(){//abre modal para crear $("#errorBox").collapse('hide'); $("#errorBox_text").html(""); var dia = getDiaNombre($(this).data("dia")); var hora = $(this).data("hora"); if(hora < 10) hora = "0"+hora; var min = $(this).data("fraccion"); if(min < 10) min = "0"+min; $('#dia').val($(this).data("dia")); $('#hora').val(hora+":"+min); $('#fecha_horario').html(dia+" - "+hora+":"+min+" hrs."); $("#submitBtn").data('tipo', 1); $("#modalLabel").html("Crear Horario"); $('#duracion').removeClass('is-invalid'); $('#modal').modal('show'); }); $('#submitBtn').click(function(){ //Crea Obj JSON y elemento HTML if(validaDuracion(-1, $('#dia').val(), $('#hora').val(), parseInt($('#duracion').val())*60)){ var horario = { id_obj: id_obj, id_db:0, dia: parseInt($('#dia').val()), dia_orig: parseInt($('#dia').val()), hora: $('#hora').val(), duracion: parseInt($('#duracion').val())*60, tipo: parseInt($('#tipo').find(':selected').val()), tipo_nombre: $('#tipo').find(':selected').text(), editable: true, color: $('#tipo').find(':selected').data('color') }; if(guardaHorario(1, horario)){ horariosObj.push(horario); //Crea horario HMTL calculaTotalDia(horario.dia); calculaTotalTipo(horario.tipo); creaHorarioHTML(id_obj, getX(horario.dia), getY(horario.hora), getAlto(horario.duracion) ,horario.color, horario.tipo_nombre, horario.editable, "#bloque-horarios"); id_obj++; calculaTotalHorarios(); } $('#modal').modal('hide'); }//fin duración valida else{ $("#avanzadoBox").collapse('show'); $('#duracion').addClass('is-invalid'); } }); }); function validaDuracion(pos, dia, hora_ini, duracion){//valida que la materia no tenga conflictos con la siguiente y que esté dentro del límite del horario var horaObjIni = new Date(); var horaObjFin; var horaArr = hora_ini.split(":"); horaObjIni.setHours(horaArr[0]); horaObjIni.setMinutes(horaArr[1]); horaObjIni.setSeconds(0); horaObjFin = new Date(horaObjIni.getTime()); horaObjFin.setMinutes(horaObjFin.getMinutes() + parseInt(duracion)); //Obtiene última hora de clase var fechaLimite = new Date(); fechaLimite.setHours(parseInt($('.hora').last().data('hora')) + 1); fechaLimite.setMinutes(0); fechaLimite.setSeconds(0); if( Date.parse(horaObjFin) > Date.parse(fechaLimite)){ return false; } return validaHorasBloque(pos, dia, horaObjIni, horaObjFin);//valida si choca con el siguiente } function validaHorasBloque(pos, dia, horaObjIni, horaObjFin){ for(var i=0; i < horariosObj.length; i++){ var horaArr = horariosObj[i].hora.split(":"); var horaClaseInicio = new Date(); horaClaseInicio.setHours(horaArr[0]); horaClaseInicio.setMinutes(horaArr[1]); horaClaseInicio.setSeconds(0); //Objeto leído no es el objeto actual, mismo día, hora de fin del objeto actual choca con hora de inicio objeto anterior if(pos != i && parseInt(horariosObj[i].dia) == parseInt(dia) && Date.parse(horaClaseInicio) < Date.parse(horaObjFin) && Date.parse(horaClaseInicio) > Date.parse(horaObjIni)){ return false;//Si existe, no es válido } } return true;//no existe, es válido } //funcion para guardar por ajax información function guardaHorario(nuevo, objClase){ console.log("Guardar"); _editable = false; var url = './action/mihorario_insert.php'; if(nuevo != 1){ url = './action/mihorario_update.php'; } var state = false; $.ajax({ url: url, type: 'POST', dataType: 'json', async: false, data: { json: JSON.stringify(objClase)}, beforeSend: function(x) { if (x && x.overrideMimeType) { x.overrideMimeType("application/j-son;charset=UTF-8"); } }, success: function(result) { if(result["error"]!= "" && result["error"] !== undefined){ $("#errorBox").collapse('show'); $("#errorBox_text").html("Error al guardar el horario.
"+result["error"]); $('#messageBox')[0].scrollIntoView({ block: "end" }); state = false; }else{ state = true; if(nuevo == 1){ objClase.id_db = result["id"]; } } }, error: function(jqXHR, textStatus, errorThrown ){ $("#errorBox").collapse('show'); $("#errorBox_text").html(errorThrown); $('#messageBox')[0].scrollIntoView({ block: "end" }); state = false; } });//ajax _editable = true; return state; } function loadHorarioEdicion(){ $('.bloque-clase').remove(); horariosObj = []; id_obj = 0; //carga horarios y crea bloques $.ajax({ url: './action/mihorario_select.php', type: 'POST', dataType: 'json', data: { autorizacion: _horarioEstado, fecha: $("#filter_fecha").val()}, success: function(result) { if(result["error"]!= "" && result["error"] !== undefined){ console.log("Ocurrió un error de load"); $("#errorBox").collapse('show'); $("#errorBox_text").html(result["error"]); $('#messageBox')[0].scrollIntoView({ block: "end" }); }else{ if(result["errorArr"] !== undefined){ $("#errorBox").collapse('show'); $("#errorBox_text").html("Hay bloques en el horario propuesto que tienen conflicto, crea uno nuevo"); $('#messageBox')[0].scrollIntoView({ block: "end" }); } var i, j; for(i = 0; i< result["horario"].length; i++){ var horario = { id_obj: id_obj, id_db: parseInt(result["horario"][i]["id"]), dia: parseInt(result["horario"][i]["dia"]), dia_orig: parseInt(result["horario"][i]["dia"]), hora: result["horario"][i]["hora"], duracion: parseInt(result["horario"][i]["duracion"]), tipo: parseInt(result["horario"][i]["tipo"]), tipo_nombre: result["horario"][i]["tipo_nombre"], editable: result["horario"][i]["editable"], color: result["horario"][i]["color"] }; horariosObj.push(horario); calculaTotalDia(horario.dia); calculaTotalTipo(horario.tipo); creaHorarioHTML(id_obj, getX(horario.dia), getY(horario.hora), getAlto(horario.duracion) ,horario.color, horario.tipo_nombre, horario.editable, "#bloque-horarios"); id_obj++; }//fin for calculaTotalHorarios(); } _editable = true; }, error: function(jqXHR, textStatus, errorThrown ){ $("#errorBox").collapse('show'); $("#errorBox_text").html("Error al cargar horario.
"+errorThrown); $('#messageBox')[0].scrollIntoView({ block: "end" }); _editable = true; } });//ajax } function creaHorarioHTML(id, posX, posY, alto, color, texto, editable, parentBox){//crea bloque HTML var edit_class = ""; var zindex = ""; if(editable === true ){ edit_class = "bloque-draggable ui-draggable ui-draggable-handle bloque-resizable"; zindex = "3"; }else{ zindex = "1"; } var nuevoHorario = '
\ \
'; $(nuevoHorario).appendTo(parentBox); makeDraggable(); makeResizable(); } function makeDraggable() { $(".bloque-draggable").draggable({ cursor: "move", containment:"#area-horario", grid: [_w, _h], stack: "#bloque-horarios div", revert : true, revertDuration: 0, start: function( event, ui ) { _drag = true; }, drag: function( event, ui ) { $(this).find('.menu-flotante').addClass('d-none');}, stop: function( event, ui ) { $(this).find('.menu-flotante').removeClass('d-none'); //Valida que no colisione con otro objeto _drag = false; var error = false; var fechaObj = new Date(); var horaArr; var objetoOrigen =[0,0,0];//x, y1, y2 (this) var objetoDestino =[0,0,0];//x, y1, y2 var thisIndex = getIndexClase($(this).data("id_obj")); var top = ui.position.top; var left = ui.position.left; //Obtiene coordenadas de objeto actual objetoOrigen[0] = left; objetoOrigen[1] = top; objetoOrigen[2] = top + getAlto(horariosObj[thisIndex].duracion); for(var i=0; i < horariosObj.length; i++){ if(horariosObj[i].id_obj != $(this).data("id_obj")){ fechaObj = new Date(); //no es el objeto actual, obtiene coordenadas objetoDestino[0] = getX(horariosObj[i].dia); objetoDestino[1] = getY(horariosObj[i].hora); horaArr = horariosObj[i].hora.split(":"); fechaObj.setHours(horaArr[0]); fechaObj.setMinutes(horaArr[1]); fechaObj.setMinutes(fechaObj.getMinutes() + parseInt(horariosObj[i].duracion)); objetoDestino[2] = getY(fechaObj.getHours()+":"+fechaObj.getMinutes()); //valida si se sobreponen if(objetoOrigen[0] == objetoDestino[0]){ if( (objetoOrigen[1] >= objetoDestino[1] && objetoOrigen[1] < objetoDestino[2]) || (objetoDestino[1] >= objetoOrigen[1] && objetoDestino[1] < objetoOrigen[2]) ){//si se sobreponen, lo regresa a su posición anterior //si son horario completo o si se enciman las fechas $(this).draggable( "option", "revert", true ); error = true; //alert("No se puede mover el horario."); } } } } if(!error){//no se sobreponen //Valida cuadricula top = Math.floor(top / _h)*_h; if(top < 0) top = 0; left = Math.floor(left / _w)*_w; if(left < 0) left = 0; //Actualiza objeto horariosObj[thisIndex].dia = getDia(left); horariosObj[thisIndex].hora = getHora(top)+":"+getMinutos(top); calculaTotalDia(horariosObj[thisIndex].dia); calculaTotalDia(horariosObj[thisIndex].dia_orig); if(guardaHorario(0, horariosObj[thisIndex])){ $(this).css({top: top + "px", left: left + "px"}); horariosObj[thisIndex].dia_orig = horariosObj[thisIndex].dia; }else{ $(this).draggable( "option", "revert", true ); horariosObj[thisIndex].dia = horariosObj[thisIndex].dia_orig; } } } }); } function makeResizable() { $(".bloque-resizable").resizable({ containment:"#area-horario", maxWidth: _w, minWidth: 1, minHeight: _frac, grid: [_w, _h], handles: "s", autoHide: true, start: function( event, ui ) { _drag = true;}, stop: function( event, ui ) { //Valida que no colisione con otro objeto _drag = false; var error = false; var thisIndex = getIndexClase($(this).data("id_obj")); var fechaObj = new Date(); var horaArr; var objetoOrigen =[0,0,0];//x, y1, y2 (this) var objetoDestino =[0,0,0];//x, y1, y2 var top = ui.position.top; var height = ui.size.height; var left = ui.position.left; //Obtiene coordenadas de objeto actual objetoOrigen[0] = left; objetoOrigen[1] = top; objetoOrigen[2] = top + height; for(var i=0; i < horariosObj.length; i++){ if(horariosObj[i].id_obj != $(this).data("id_obj")){ fechaObj = new Date(); //no es el objeto actual, obtiene coordenadas objetoDestino[0] = getX(horariosObj[i].dia); objetoDestino[1] = getY(horariosObj[i].hora); horaArr = horariosObj[i].hora.split(":"); fechaObj.setHours(horaArr[0]); fechaObj.setMinutes(horaArr[1]); fechaObj.setMinutes(fechaObj.getMinutes() + parseInt(horariosObj[i].duracion)); objetoDestino[2] = getY(fechaObj.getHours()+":"+fechaObj.getMinutes()); //valida si se sobreponen if(objetoOrigen[0] == objetoDestino[0]){ if( (objetoOrigen[2] > objetoDestino[1] && objetoOrigen[1] < objetoDestino[1]) ){//si se sobreponen, lo regresa a su posición anterior //si son horario completo o si se enciman las fechas $(this).css('height', ui.originalSize.height + 2); error = true; //alert("No se puede mover el horario."); } } } } if(!error){//no se sobreponen //Valida cuadricula height = Math.ceil(height / _h)*_h; //Actualiza objeto horariosObj[thisIndex].duracion = height/(_h*_frac) * 60; calculaTotalDia(horariosObj[thisIndex].dia); calculaTotalTipo(horariosObj[thisIndex].tipo); calculaTotalHorarios(); if(guardaHorario(0, horariosObj[thisIndex])){ $(this).css({height: height + "px"}); $(this).find(".tiempo").text(height/(_h*_frac)); // $(this).css('height', {height: (ui.originalSize.height) + "px"}); }else{ ui.element.css('height', ui.originalSize.height + 2); } }else{ } }, }); } function getIndexClase(idobj){//busca en qué posición del arreglo está el id del horario for(var i=0; i < horariosObj.length; i++){ if(horariosObj[i].id_obj == idobj){ return i; } } return -1; } function calculaTotalDia(dia){ var total_d = 0; for(var i =0; i < horariosObj.length; i++){ if(horariosObj[i].dia == dia){ total_d+= (horariosObj[i].duracion/60); } } $("#total_"+dia).text(total_d); } function calculaTotalTipo(tipo){ var total_t = 0; for(var i =0; i < horariosObj.length; i++){ if(horariosObj[i].tipo == tipo){ total_t+= (horariosObj[i].duracion/60); } } $("#total_tipo_"+tipo).text(total_t); } function calculaTotalHorarios(){ var total_t = 0; for(var i =0; i < horariosObj.length; i++){ total_t+= (horariosObj[i].duracion/60); } $("#total_all").text(total_t); } $(document).on( "click", ".borrar-todo", function(event){ //Borra todos los horarios propuestos var i; for(i = 0; i < horariosObj.length; i++){ if(horariosObj[i]["tipo"] != 3){//no borra horarios docentes $.ajax({ url: './action/mihorario_delete.php', type: 'POST', dataType: 'json', async: false, data: { json: JSON.stringify(horariosObj[i])}, beforeSend: function(x) { if (x && x.overrideMimeType) { x.overrideMimeType("application/j-son;charset=UTF-8"); } }, success: function(result) { if(result["error"]!= "" && result["error"] !== undefined){ $("#errorBox").collapse('show'); $("#errorBox_text").html("Error al borrar el horario."); $('#messageBox')[0].scrollIntoView({ block: "end" }); }else{ $('#bloque_'+horariosObj[i]["id_obj"]).remove(); var deletedObj = horariosObj.splice(i, 1); calculaTotalDia(deletedObj[0].dia); calculaTotalTipo(deletedObj[0].tipo); } }, error: function(jqXHR, textStatus, errorThrown ){ $("#errorBox").collapse('show'); $("#errorBox_text").html(errorThrown); $('#messageBox')[0].scrollIntoView({ block: "end" }); } });//ajax $(this).parents(".modal").modal("hide"); } } calculaTotalHorarios(); }); $(document).on( "click", ".bloque-borra", function(event){ var thisIndex = getIndexClase($("#id_borrar").val()); $.ajax({ url: './action/mihorario_delete.php', type: 'POST', dataType: 'json', async: false, data: { json: JSON.stringify(horariosObj[thisIndex])}, beforeSend: function(x) { if (x && x.overrideMimeType) { x.overrideMimeType("application/j-son;charset=UTF-8"); } }, success: function(result) { if(result["error"]!= "" && result["error"] !== undefined){ $("#errorBox").collapse('show'); $("#errorBox_text").html("Error al borrar el horario."); $('#messageBox')[0].scrollIntoView({ block: "end" }); }else{ $('#bloque_'+$("#id_borrar").val()).remove(); var deletedObj = horariosObj.splice(thisIndex, 1); calculaTotalDia(deletedObj[0].dia); calculaTotalTipo(deletedObj[0].tipo); calculaTotalHorarios(); } }, error: function(jqXHR, textStatus, errorThrown ){ $("#errorBox").collapse('show'); $("#errorBox_text").html(errorThrown); $('#messageBox')[0].scrollIntoView({ block: "end" }); } });//ajax $(this).parents(".modal").modal("hide"); }); $(document).on( "click", ".bloque-send", function(event){ var btnSend = $(this); $.ajax({ url: './action/mihorarioestado_update.php', type: 'POST', dataType: 'json', async: false, data: { orig: btnSend.data("orig"), dest: btnSend.data("dest"), fecha:$("#filter_fecha").val()}, success: function(result) { if(result["error"]!= "" && result["error"] !== undefined){ $("#errorBox").collapse('show'); $("#errorBox_text").html(result["error"]); $('#messageBox')[0].scrollIntoView({ block: "end" }); }else{ if(result["conflictoCount"] !== undefined && result["conflictoCount"] > 0) window.location.href = "mihorario.php?ok=0&error=5"; else window.location.href = "mihorario.php?ok=0"; } }, error: function(jqXHR, textStatus, errorThrown ){ $("#errorBox").collapse('show'); $("#errorBox_text").html(errorThrown); $('#messageBox')[0].scrollIntoView({ block: "end" }); } });//ajax $(this).parents(".modal").modal("hide"); });