horario_edicion.js 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359
  1. var _drag = false;
  2. var _editable = false;//permite editar horario o no
  3. $(document).ready(function(){
  4. ajustaTabla();
  5. hideBorraProfesor();
  6. hideBorraVinculo();
  7. loadCalendario();
  8. timer(_reloadTime);
  9. $('#materia').change(function(){
  10. ajustaTabla();
  11. });
  12. $('#modal_confirm').on('show.bs.modal', function (event) {
  13. var button = $(event.relatedTarget); // Button that triggered the modal
  14. var id = button.parents(".bloque-clase").data("id_obj");
  15. if(clasesObj[id].vinculos.length > 0){
  16. $("#confirm-vinculada").show();
  17. }else{
  18. $("#confirm-vinculada").hide();
  19. }
  20. $("#id_borrar").val(id);
  21. });
  22. $(".date-picker" ).datepicker(datepickerOptions);
  23. $(".date-picker" ).datepicker( $.datepicker.regional[ "es" ] );
  24. $(".date-picker").blur(function(){
  25. var fechaObj = fechaObjeto($(this).val());
  26. if( fechaObj !== false ){
  27. if(Date.parse(fechaObj) < Date.parse(fechaObjeto(_periodo_fecha_inicial))){
  28. $(this).val(_periodo_fecha_inicial);
  29. }else if(Date.parse(fechaObj) > Date.parse(fechaObjeto(_periodo_fecha_final))){
  30. $(this).val(_periodo_fecha_final);
  31. }
  32. }
  33. });
  34. $('.crea-horario').click(function(){//abre modal para crear
  35. $("#submitBtn").attr("disabled", false);
  36. if(_editable){
  37. if(!horarioCompleto()){
  38. $("#errorBox").collapse('hide');
  39. $("#errorBox_text").html("");
  40. $("#avanzadoBox").collapse('hide');
  41. $("#submitBtn").data('tipo', 1);
  42. $("#modalLabel").html("Crear Horario de materia");
  43. //modal.find("input[type=text]").val("");
  44. //$('.profesor').get(0).selectedIndex = 0;
  45. //$('.profesor-submateria').get(0).selectedIndex = 0;
  46. //$('.submateria-salon').get(0).selectedIndex = 0;
  47. $("#duracion").val(_grupo_duracion).change();
  48. $('#fecha_inicial').val(_periodo_fecha_inicial);
  49. $('#fecha_final').val(_periodo_fecha_final);
  50. var dia = getDiaNombre($(this).data("dia"));
  51. var hora = $(this).data("hora");
  52. if(hora < 10) hora = "0"+hora;
  53. var min = $(this).data("fraccion");
  54. if(min < 10) min = "0"+min;
  55. $('#dia').val($(this).data("dia"));
  56. $('#hora').val(hora+":"+min);
  57. $('#fecha_horario').html(dia+" - "+hora+":"+min+" hrs.");
  58. $('#duracion').removeClass('is-invalid');
  59. //desbloquea vinculos
  60. $("#vinculadas-block").find("button").attr("disabled", false);
  61. $("#vinculadas-block").find("select").attr("disabled", false);
  62. $('#modal').modal('show');
  63. }
  64. }//fin editable
  65. });
  66. $('#modal').on('hide.bs.modal', function (event) {//al cerrar verifica si se tiene que recargar
  67. if(_reloadOnClose){
  68. loadCalendario();
  69. _reloadOnClose = false;
  70. timer(_reloadTime);
  71. }
  72. });
  73. $('#modal_ver').on('hide.bs.modal', function (event) {//al cerrar verifica si se tiene que recargar
  74. if(_reloadOnClose){
  75. loadCalendario();
  76. _reloadOnClose = false;
  77. timer(_reloadTime);
  78. }
  79. });
  80. $("#agrega-profesor").click(function(){
  81. $("#profesor-list >tr:first-child").find('.date-picker.hasDatepicker').removeClass('hasDatepicker');
  82. var cloned = $("#profesor-list >tr:first-child").clone(true).appendTo("#profesor-list");
  83. cloned.find("input").val("");
  84. cloned.find("input.date-picker").prop("id", "");
  85. cloned.find(".date-picker" ).datepicker(datepickerOptions);
  86. cloned.find(".date-picker" ).datepicker( $.datepicker.regional[ "es" ] );
  87. $("#profesor-list >tr:first-child").find('.date-picker').datepicker(datepickerOptions);
  88. $("#profesor-list >tr:first-child").find('.date-picker').datepicker($.datepicker.regional[ "es" ]);
  89. cloned.find('select').get(0).selectedIndex = 0;
  90. var tipo = $('#materia').find(':selected').data('tipo');
  91. if(tipo == 1){
  92. cloned.find('.profesor-salon').val($("#profesor-list >tr:first-child").find('.profesor-salon').val()).change();
  93. }
  94. //cloned.datepicker();
  95. hideBorraProfesor();
  96. });
  97. $(".borra-profesor").click(function(){//quita profesor
  98. $(this).parents("tr").remove();
  99. hideBorraProfesor();
  100. });
  101. $("#agrega-vinculo").click(function(){
  102. var cloned = $("#vinculo-list >tr:first-child").clone(true).appendTo("#vinculo-list");
  103. cloned.find('select').get(0).selectedIndex = 0;
  104. hideBorraVinculo();
  105. });
  106. $(".borra-vinculo").click(function(){//quita profesor
  107. $(this).parents("tr").remove();
  108. hideBorraVinculo();
  109. });
  110. function enVinculo(arreglo, objBuscar){
  111. for(var i =0; i<arreglo.length; i++){
  112. if(arreglo[i].grupo == objBuscar.grupo && arreglo[i].materia == objBuscar.materia)
  113. return true;
  114. }
  115. return false;
  116. }
  117. $('#submitBtn').click(function(){
  118. //Crea Obj JSON y elemento HTML
  119. $(this).attr("disabled", true);
  120. if(_editable){
  121. $('#duracion').removeClass('is-invalid');
  122. $('#fecha_inicial').removeClass('is-invalid');
  123. $('#fecha_final').removeClass('is-invalid');
  124. var thisIndex;
  125. if($(this).data("tipo") == 1){//alta
  126. thisIndex = -1;
  127. }else{
  128. thisIndex = getIndexClase($('#id').val());
  129. $('#id_db').val(clasesObj[thisIndex].id_db);
  130. }
  131. if(validaDuracion(thisIndex, $('#dia').val(), $('#hora').val(), $('#duracion').val())){
  132. var salon_nombre = "";
  133. var submateriaArr = [];
  134. if($('#materia').find(':selected').data('tipo') != 0){
  135. $.each($('#submateria-list tr'), function(){
  136. var submateria = {
  137. submateria: $(this).find('.submateria-nombre').data('id'),
  138. submateria_nombre: $(this).find('.submateria-nombre').text(),
  139. fecha_inicial: $(this).find('.submateria-inicial').val(),
  140. fecha_final: $(this).find('.submateria-final').val(),
  141. /*salon: parseInt($(this).find('.submateria-salon').val()),
  142. salon_nombre: $(this).find('.submateria-salon option:selected').data("desc").toString(),
  143. salon_nombre_completo: $(this).find('.submateria-salon option:selected').text()*/
  144. activa: $(this).find('.submateria-activa').prop("checked"),
  145. }
  146. /*if(submateria.salon_nombre.length > 2){
  147. salon_nombre+= submateria.salon_nombre+", ";
  148. }*/
  149. if(submateria.submateria != "" && submateria != 0)
  150. submateriaArr.push(submateria);
  151. });
  152. /*if(salon_nombre.length > 2)
  153. salon_nombre = salon_nombre.substring(0, salon_nombre.length-2);*/
  154. }
  155. var profesorArr = [];
  156. $.each($('#profesor-list tr'), function(){
  157. if($(this).find('.profesor').val() != ""){
  158. var profesor = {
  159. profesor: $(this).find('.profesor').val(),
  160. profesor_nombre: $(this).find('.profesor option:selected').text(),
  161. submateria: $(this).find('.profesor-submateria').val(),
  162. salon: parseInt($(this).find('.profesor-salon').val()),
  163. salon_nombre: $(this).find('.profesor-salon option:selected').data("desc").toString(),
  164. salon_nombre_completo: $(this).find('.profesor-salon option:selected').text()
  165. }
  166. console.log("Profesor:");
  167. console.log(profesor);
  168. if(profesor.salon_nombre.length > 2){
  169. salon_nombre+= profesor.salon_nombre+", ";
  170. }
  171. if(submateriaArr.length>0){
  172. if(profesor.submateria != null && profesor.submateria != "" && profesor.submateria != 0)//Se seleccionó profesor
  173. profesorArr.push(profesor);
  174. }else{
  175. profesorArr.push(profesor);
  176. }
  177. }
  178. });
  179. if(salon_nombre.length > 2)
  180. salon_nombre = salon_nombre.substring(0, salon_nombre.length-2);
  181. var vinculadasArr = [];
  182. $.each($('#vinculo-list tr'), function(){
  183. if(parseInt($(this).find('.grupo_vinculo').val()) != 0 && parseInt($(this).find('.grupo_vinculo').val()) != ""){
  184. var vinculo = {
  185. id_db: parseInt($(this).find('.grupo_vinculo option:selected').data("id_db")),
  186. grupo: parseInt($(this).find('.grupo_vinculo option:selected').data("gpo")),
  187. //grupo_nombre: $(this).find('.grupo_vinculo option:selected').text(),
  188. materia: parseInt($(this).find('.grupo_vinculo option:selected').data("mat")),
  189. materia_nombre: $(this).find('.grupo_vinculo option:selected').text(),
  190. }
  191. if(vinculo.materia_nombre != "" && !enVinculo(vinculadasArr, vinculo)){
  192. vinculadasArr.push(vinculo);
  193. }
  194. }
  195. });
  196. var completo = 0;
  197. if( Date.parse(fechaGuion(_periodo_fecha_inicial)) == Date.parse(fechaGuion($('#fecha_inicial').val())) && Date.parse(fechaGuion(_periodo_fecha_final)) == Date.parse(fechaGuion($('#fecha_final').val())) ){
  198. completo = 1;
  199. }
  200. var clase = {
  201. id_obj: id_obj,
  202. id_db:0,
  203. grupo: _grupo_id,
  204. dia: parseInt($('#dia').val()),
  205. hora: $('#hora').val(),
  206. duracion: parseInt($('#duracion').val()),
  207. materia: parseInt($('#materia').val()),
  208. materia_nombre: $('#materia option:selected').text(),
  209. tipo: $('#materia').find(':selected').data('tipo'),
  210. salon: parseInt($('#salon').val()),
  211. salon_nombre: $('#salon option:selected').data("desc").toString(),
  212. salon_nombre_completo: $('#salon option:selected').text(),
  213. fecha_inicial: $('#fecha_inicial').val(),
  214. fecha_final: $('#fecha_final').val(),
  215. periodo_completo: completo,
  216. submaterias: submateriaArr,
  217. profesores: profesorArr,
  218. vinculos: vinculadasArr,
  219. color: $('#materia').find(':selected').data('color')
  220. };
  221. if(clase.tipo == 0){
  222. salon_nombre = clase.salon_nombre;
  223. if(clase.salon == 0 || clase.salon == "" || clase.salon === null || isNaN(clase.salon) || clase.salon === undefined){
  224. salon_nombre = "-Pendiente-";
  225. }
  226. }
  227. //Si está dentro de rango y no choca con materia siguiente
  228. if(validaFechasBloque(thisIndex, $('#dia').val(), $('#fecha_inicial').val(), $('#fecha_final').val(), $('#hora').val(), $('#duracion').val(), completo )){
  229. if($(this).data("tipo") == 1){//alta
  230. if(guardaHorario(1, clase, 0)){
  231. clase.dia_orig = clase.dia;
  232. clase.hora_orig = clase.hora;
  233. clase.materia_orig = clase.materia;
  234. clasesObj.push(clase);
  235. loadCalendario();
  236. }
  237. }else{//edición
  238. clase.dia_orig = clasesObj[thisIndex].dia_orig;
  239. clase.hora_orig = clasesObj[thisIndex].hora_orig;
  240. clase.materia_orig = clasesObj[thisIndex].materia_orig;
  241. clase.id_db = parseInt($('#id_db').val());
  242. clase.id_obj = parseInt($('#id').val());
  243. if(guardaHorario(0, clase, 0)){
  244. loadCalendario();
  245. }
  246. }
  247. //actualiza horas de materia
  248. actualizaHoras(clase.materia);
  249. $('#modal').modal('hide');
  250. }else{//chocan fechas
  251. $("#avanzadoBox").collapse('show');
  252. $('#fecha_inicial').addClass('is-invalid');
  253. $('#fecha_final').addClass('is-invalid');
  254. }//fin choque de fechas
  255. }//fin duración valida
  256. else{
  257. $("#avanzadoBox").collapse('show');
  258. $('#duracion').addClass('is-invalid');
  259. }
  260. }//fin editable
  261. });
  262. $('.btn-reload').click(function(){//recarga página para perder cambios
  263. if(confirm('¿Estás seguro de querer volver a cargar el horario?\nSe perderán los cambios que no estén guardados.')){
  264. $(this).parents("form").submit();
  265. }
  266. });
  267. });
  268. function creaHorarioHTML(id, posX, posY, alto, color, texto, salon, numProf, completo, link, editable, fini, ffin){//crea bloque HTML
  269. var completoClass = "";
  270. var linked = "";
  271. var edit_class = "";
  272. var fechaHTML = "";
  273. if(parseInt(completo) == 1){ completoClass = " d-none"; }//si está completo el horario no pone signo +
  274. else{ fechaHTML = '<br><span class="text-80"><span class="ing-importante2 mr-1"></span> '+fini+' a '+ffin+'</span>'; }
  275. if(parseInt(link) == 0){linked = " d-none"; }
  276. if(editable === true ){edit_class = "bloque-draggable ui-draggable ui-draggable-handle";}
  277. var nuevoHorario = '<div class="bloque-clase '+edit_class+'" id="bloque_'+id+'" data-id_obj="'+id+'"\
  278. style="top:'+posY+'px; left:'+posX+'px; background-color:'+color+'; height:'+alto+'px" >\
  279. <div class="menu-wrapper">\
  280. <p><span class="ing-importante ing-fw alerta d-none mr-1"></span> <span class="title">'+texto+'</span> <span class="ing-link ing-fw bloque-vinculada '+linked+'"></span> '+fechaHTML+'</p>\
  281. <div class="d-flex justify-content-between w-100">\
  282. <p class="salon my-0">'+salon+'</p> <p class="text-right my-0"><span class="ing-formacion mx-1"></span> <span class="profesores">'+numProf+'</span></p>\
  283. </div>\
  284. <div class="menu-flotante d-none">\
  285. <span class="float-left iconos">\
  286. <span class="ing-mas ing-fw bloque-agrega mx-1 '+completoClass+'" aria-hidden="true" title="Agregar materia en mismo horario"></span>\
  287. </span>\
  288. <span class="float-right iconos" >\
  289. <span class="ing-buscar ing-fw bloque-ver mx-1" aria-hidden="true" title="Ver detalle"></span>';
  290. if(editable === true ){
  291. nuevoHorario +='<span class="ing-editar ing-fw bloque-edita mx-1" aria-hidden="true" title="Editar materia"></span>\
  292. <span class="ing-basura ing-fw mx-1" aria-hidden="true" data-toggle="modal" data-target="#modal_confirm" title="Borrar materia"></span>';
  293. }
  294. nuevoHorario +='</span>\
  295. </div>\
  296. </div>\
  297. </div>';
  298. $(nuevoHorario).appendTo("#bloque-horarios");
  299. makeDraggable();
  300. }
  301. function hideBorraProfesor(){
  302. var total = $("#profesor-list >tr").length;//cuenta renglones actuales
  303. if(total == 1){
  304. $('.borra-profesor').hide();
  305. }else{
  306. $('.borra-profesor').show();
  307. }
  308. }
  309. function hideBorraVinculo(){
  310. var total = $("#vinculo-list >tr").length;//cuenta renglones actuales
  311. if(total == 1){
  312. $('.borra-vinculo').hide();
  313. }else{
  314. $('.borra-vinculo').show();
  315. }
  316. }
  317. function hideBorraVinculo(){
  318. var total = $("#vinculo-list >tr").length;//cuenta renglones actuales
  319. if(total == 1){
  320. $('.borra-vinculo').hide();
  321. }else{
  322. $('.borra-vinculo').show();
  323. }
  324. }
  325. function ajustaTabla(){
  326. var tipo = $('#materia').find(':selected').data('tipo');
  327. loadProfesores();
  328. loadSubmaterias();
  329. loadRelacionadas();
  330. switch(parseInt(tipo)){
  331. case 0:
  332. $('#salon').attr("disabled", false);
  333. $('.col-profesor-submateria').hide();
  334. $('.col-profesor-salon').hide();
  335. $('.profesor-submateria').parents('td').hide();
  336. $('#submaterias-block').hide();
  337. $(".profesor-submateria").attr("disabled", true);
  338. $(".submateria-inicial").attr("disabled", true);
  339. $(".submateria-final").attr("disabled", true);
  340. $('#btn-tipo-text').text("profesor");//Agrega __profesor__
  341. break;
  342. case 1://secuencial
  343. $('#salon').attr("disabled", true);
  344. $('.col-profesor-submateria').show();
  345. $('.col-profesor-salon').show();
  346. $('#submaterias-block').show();
  347. $('.col-submateria-inicial').show();
  348. $('.col-submateria-final').show();
  349. $('.submateria-inicial').parents('td').show();
  350. $('.submateria-final').parents('td').show();
  351. $('.profesor-submateria').parents('td').show();
  352. $(".profesor-submateria").attr("disabled", false);
  353. $(".submateria-inicial").attr("disabled", false);
  354. $(".submateria-final").attr("disabled", false);
  355. $('#salon').get(0).selectedIndex = 0;
  356. $('#btn-tipo-text').text("submateria");//Agrega __submateria__
  357. break;
  358. case 2://electiva
  359. $('#salon').attr("disabled", true);
  360. $('.col-profesor-submateria').show();
  361. $('.col-profesor-salon').show();
  362. $('#submaterias-block').show();
  363. $('.col-submateria-inicial').hide();
  364. $('.col-submateria-final').hide();
  365. $('.submateria-inicial').parents('td').hide();
  366. $('.submateria-final').parents('td').hide();
  367. $('.profesor-submateria').parents('td').show();
  368. $(".profesor-submateria").attr("disabled", false);
  369. $(".submateria-inicial").attr("disabled", true);
  370. $(".submateria-final").attr("disabled", true);
  371. $('#salon').get(0).selectedIndex = 0;
  372. $('#btn-tipo-text').text("profesor");//Agrega __submateria__
  373. break;
  374. }
  375. }
  376. function loadProfesores(){
  377. modal = $("#modal");
  378. $.ajax({
  379. url: './action/profesoresarea_select.php',
  380. type: 'POST',
  381. dataType: 'json',
  382. async: false,
  383. data: { id: $('#materia').val() },
  384. success: function(result) {
  385. if(result["error"]!= "" && result["error"] !== undefined){
  386. console.log("Ocurrió un error de load");
  387. modal.modal('hide');
  388. $("#errorBox").collapse('show');
  389. $("#errorBox_text").html(result["error"]);
  390. $('#messageBox')[0].scrollIntoView({ block: "end" });
  391. }else{
  392. $.each($(".profesor"), function(){
  393. $(this).children('option:not(:first)').remove();//quita todas las opciones menos la 1ra
  394. });
  395. if(result["profesorArr"] !== undefined){
  396. for(var i = 0; i < result["profesorArr"].length; i++){
  397. $('.profesor')
  398. .append($("<option></option>")
  399. .attr("value", result["profesorArr"][i]["id"])
  400. .text(result["profesorArr"][i]["nombre"]));
  401. }
  402. }
  403. }
  404. },
  405. error: function(jqXHR, textStatus, errorThrown ){
  406. modal.modal('hide');
  407. $("#errorBox").collapse('show');
  408. $("#errorBox_text").html("Error al obtener profesores.<br>"+errorThrown);
  409. $('#messageBox')[0].scrollIntoView({ block: "end" });
  410. //alert("ERROR! " + textStatus+ " - "+errorThrown);
  411. }
  412. });//ajax
  413. }
  414. function loadSubmaterias(){
  415. modal = $("#modal");
  416. $.ajax({
  417. url: './action/submateria_select.php',
  418. type: 'POST',
  419. dataType: 'json',
  420. async: false,
  421. data: { id: $('#materia').val() },
  422. success: function(result) {
  423. if(result["error"]!= "" && result["error"] !== undefined){
  424. console.log("Ocurrió un error de load");
  425. modal.modal('hide');
  426. $("#errorBox").collapse('show');
  427. $("#errorBox_text").html(result["error"]);
  428. $('#messageBox')[0].scrollIntoView({ block: "end" });
  429. }else{
  430. $.each($(".profesor-submateria"), function(){
  431. //$(this).children('option:not(:first)').remove();//quita todas las opciones menos la 1ra
  432. $(this).children('option').remove();//quita todas las opciones
  433. });
  434. if(result["submateriaArr"] !== undefined){
  435. var rows = $("#submateria-list > tr").length;//cuenta renglones actuales
  436. if(rows > result["submateriaArr"].length){//sobran
  437. //borrar renglones extra pero dejar al menos 1
  438. while(rows > result["submateriaArr"].length && rows > 1){
  439. $("#submateria-list >tr:last-child").remove();
  440. rows--;
  441. }
  442. }else{//faltan
  443. // clone more copies of the row
  444. for(var i=rows; i < result["submateriaArr"].length; i++){
  445. var cloned = $("#submateria-list >tr:first-child").clone(true).appendTo("#submateria-list");
  446. cloned.find("input").val("");
  447. cloned.find("input.date-picker").prop("id", "");
  448. cloned.find(".date-picker" ).datepicker(datepickerOptions);
  449. cloned.find(".date-picker" ).datepicker( $.datepicker.regional[ "es" ] );
  450. $("#submateria-list >tr:first-child").find('.date-picker').datepicker(datepickerOptions);
  451. $("#submateria-list >tr:first-child").find('.date-picker').datepicker($.datepicker.regional[ "es" ]);
  452. }
  453. }
  454. //actualiza datos
  455. $("#submateria-list").children().each(function(index) {
  456. if(index < result["submateriaArr"].length){//llenar info
  457. $(this).find(".submateria-nombre").text(result["submateriaArr"][index]["nombre"]);
  458. $(this).find(".submateria-nombre").data('id', result["submateriaArr"][index]["id"]);
  459. $(this).find(".submateria-inicial").val('');
  460. $(this).find(".submateria-final").val('');
  461. $(this).find(".submateria-activa").data("id", result["submateriaArr"][index]["id"]).data("nombre", result["submateriaArr"][index]["nombre"]);
  462. //console.log(result["submateriaArr"][index]["id"]);
  463. //console.log($(this).find(".submateria-nombre").data('id'));
  464. }
  465. });
  466. /* Ya no se cargan todas por default
  467. for(var i = 0; i < result["submateriaArr"].length; i++){
  468. $('.profesor-submateria')
  469. .append($("<option></option>")
  470. .attr("value", result["submateriaArr"][i]["id"])
  471. .text(result["submateriaArr"][i]["nombre"]));
  472. }*/
  473. }
  474. }
  475. },
  476. error: function(jqXHR, textStatus, errorThrown ){
  477. modal.modal('hide');
  478. $("#errorBox").collapse('show');
  479. $("#errorBox_text").html("Error al obtener submaterias.<br>"+errorThrown);
  480. $('#messageBox')[0].scrollIntoView({ block: "end" });
  481. //alert("ERROR! " + textStatus+ " - "+errorThrown);
  482. }
  483. });//ajax
  484. }
  485. function loadRelacionadas(){
  486. modal = $("#modal");
  487. if(parseInt($('#materia').val()) != 0){
  488. $(".grupo_vinculo").parents("#vinculo-list tr:not(:first)").remove();
  489. $.ajax({
  490. url: './action/materiarelacionada_select.php',
  491. type: 'POST',
  492. dataType: 'json',
  493. async: false,
  494. data: { mat: $('#materia').val(), gpo: _grupo_id },
  495. success: function(result) {
  496. if(result["error"]!= "" && result["error"] !== undefined){
  497. console.log("Ocurrió un error de load");
  498. modal.modal('hide');
  499. $("#errorBox").collapse('show');
  500. $("#errorBox_text").html(result["error"]);
  501. $('#messageBox')[0].scrollIntoView({ block: "end" });
  502. }else{
  503. $(".grupo_vinculo option:not(:first)").remove();//quita todas las opciones menos la 1ra
  504. if(result["vinculadaArr"] !== undefined && result["vinculadaArr"].length > 0){
  505. for(var i = 0; i < result["vinculadaArr"].length; i++){
  506. $(".grupo_vinculo").append($("<option></option>")
  507. .attr("value", result["vinculadaArr"][i]["id_gpo"])
  508. .text(result["vinculadaArr"][i]["nombre"])
  509. .data("gpo", result["vinculadaArr"][i]["id_gpo"])
  510. .data("mat", result["vinculadaArr"][i]["id_mat"])
  511. .data("id", result["vinculadaArr"][i]["id_db"])
  512. );
  513. }
  514. $("#vinculadas-block").removeClass("d-none");
  515. $("#no-vinculadas-block").addClass("d-none");
  516. }else{
  517. $("#vinculadas-block").addClass("d-none");
  518. $("#no-vinculadas-block").removeClass("d-none");
  519. }
  520. }
  521. },
  522. error: function(jqXHR, textStatus, errorThrown ){
  523. modal.modal('hide');
  524. $("#errorBox").collapse('show');
  525. $("#errorBox_text").html("Error al obtener materias relacionadas.<br>"+errorThrown);
  526. $('#messageBox')[0].scrollIntoView({ block: "end" });
  527. //alert("ERROR! " + textStatus+ " - "+errorThrown);
  528. }
  529. });//ajax
  530. }else{
  531. $.each(selectObj.parents("tr").find(".grupo_vinculo"), function(){
  532. $(this).children('option:not(:first)').remove();//quita todas las opciones menos la 1ra
  533. });
  534. }
  535. }
  536. function makeDraggable() {
  537. $(".bloque-draggable").draggable({
  538. cursor: "move",
  539. containment:".area-horario",
  540. grid: [_w, _h],
  541. stack: "#bloque-horarios div",
  542. revert : true,
  543. revertDuration: 0,
  544. start: function( event, ui ) { _drag = true;},
  545. stop: function( event, ui ) {
  546. //Valida que no colisione con otro objeto
  547. _drag = false;
  548. var error = false;
  549. var fechaObj = new Date();
  550. var horaArr;
  551. var objetoOrigen =[0,0,0];//x, y1, y2 (this)
  552. var objetoDestino =[0,0,0];//x, y1, y2
  553. var thisIndex = getIndexClase($(this).data("id_obj"));
  554. var top = ui.position.top;
  555. var left = ui.position.left;
  556. //Obtiene coordenadas de objeto actual
  557. objetoOrigen[0] = left;
  558. objetoOrigen[1] = top;
  559. objetoOrigen[2] = top + getAlto(clasesObj[thisIndex].duracion);
  560. for(var i=0; i < clasesObj.length; i++){
  561. if(clasesObj[i].id_obj != $(this).data("id_obj")){
  562. fechaObj = new Date();
  563. //no es el objeto actual, obtiene coordenadas
  564. objetoDestino[0] = getX(clasesObj[i].dia);
  565. objetoDestino[1] = getY(clasesObj[i].hora);
  566. horaArr = clasesObj[i].hora.split(":");
  567. fechaObj.setHours(horaArr[0]);
  568. fechaObj.setMinutes(horaArr[1]);
  569. fechaObj.setMinutes(fechaObj.getMinutes() + parseInt(clasesObj[i].duracion));
  570. objetoDestino[2] = getY(fechaObj.getHours()+":"+fechaObj.getMinutes());
  571. //valida si se sobreponen
  572. if(objetoOrigen[0] == objetoDestino[0]){
  573. if(
  574. (objetoOrigen[1] >= objetoDestino[1] && objetoOrigen[1] < objetoDestino[2]) ||
  575. (objetoDestino[1] >= objetoOrigen[1] && objetoDestino[1] < objetoOrigen[2])
  576. ){//si se sobreponen, lo regresa a su posición anterior
  577. if((clasesObj[thisIndex].periodo_completo == 1 || clasesObj[i].periodo_completo == 1) || (
  578. (Date.parse(fechaGuion(clasesObj[thisIndex].fecha_inicial)) <= Date.parse(fechaGuion(clasesObj[i].fecha_inicial)) && Date.parse(fechaGuion(clasesObj[thisIndex].fecha_final)) >= Date.parse(fechaGuion(clasesObj[i].fecha_inicial)) ) ||
  579. (Date.parse(fechaGuion(clasesObj[i].fecha_inicial)) <= Date.parse(fechaGuion(clasesObj[thisIndex].fecha_inicial)) && Date.parse(fechaGuion(clasesObj[i].fecha_final)) >= Date.parse(fechaGuion(clasesObj[thisIndex].fecha_inicial)) )
  580. ) ){
  581. //si son horario completo o si se enciman las fechas
  582. $(this).draggable( "option", "revert", true );
  583. error = true;
  584. //alert("No se puede mover la materia a ese horario.");
  585. $("#errorBox").collapse('show');
  586. $("#errorBox_text").html("No se puede mover la materia a ese horario.");
  587. $('#messageBox')[0].scrollIntoView({ block: "end" });
  588. console.log("Drag Revert");
  589. }
  590. }
  591. }
  592. }
  593. }
  594. if(!error){//no se sobreponen
  595. //Valida cuadricula
  596. top = Math.floor(top / _h)*_h;
  597. if(top < 0) top = 0;
  598. left = Math.floor(left / _w)*_w;
  599. if(left < 0) left = 0;
  600. //Actualiza objeto
  601. clasesObj[thisIndex].dia = getDia(left);
  602. clasesObj[thisIndex].hora = getHora(top)+":"+getMinutos(top);
  603. if(guardaHorario(0, clasesObj[thisIndex], 1)){
  604. $(this).css({top: top + "px", left: left + "px"});
  605. clasesObj[thisIndex].dia_orig = clasesObj[thisIndex].dia;
  606. clasesObj[thisIndex].hora_orig = clasesObj[thisIndex].hora;
  607. if(!clasesObj[thisIndex].periodo_completo){
  608. _reloadOnClose = true;
  609. }
  610. }else{
  611. $(this).draggable( "option", "revert", true );
  612. clasesObj[thisIndex].dia = clasesObj[thisIndex].dia_orig;
  613. clasesObj[thisIndex].hora = clasesObj[thisIndex].hora_orig;
  614. }
  615. }
  616. if(_reloadOnClose){
  617. _reloadOnClose = false;
  618. loadCalendario();
  619. }
  620. }
  621. });
  622. }
  623. $(document).on( "click", ".bloque-borra", function(event){
  624. var thisIndex = getIndexClase($("#id_borrar").val());
  625. $.ajax({
  626. url: './action/horariogrupo_delete.php',
  627. type: 'POST',
  628. dataType: 'json',
  629. async: false,
  630. data: { json: JSON.stringify(clasesObj[thisIndex])},
  631. beforeSend: function(x) {
  632. if (x && x.overrideMimeType) {
  633. x.overrideMimeType("application/j-son;charset=UTF-8");
  634. }
  635. },
  636. success: function(result) {
  637. if(result["error"]!= "" && result["error"] !== undefined){
  638. $("#errorBox").collapse('show');
  639. $("#errorBox_text").html("Error al borrar el horario.<br>"+result["error"]);
  640. $('#messageBox')[0].scrollIntoView({ block: "end" });
  641. }else{
  642. var mat = clasesObj[thisIndex].materia;
  643. $('#bloque_'+$("#id_borrar").val()).remove();
  644. clasesObj.splice(thisIndex, 1);
  645. actualizaHoras(mat);
  646. actualizaEditables();
  647. loadCalendario();
  648. }
  649. },
  650. error: function(jqXHR, textStatus, errorThrown ){
  651. $("#errorBox").collapse('show');
  652. $("#errorBox_text").html(errorThrown);
  653. $('#messageBox')[0].scrollIntoView({ block: "end" });
  654. }
  655. });//ajax
  656. $('#modal_confirm').modal("hide");
  657. });
  658. $(document).on( "click", ".bloque-edita", function(event){
  659. var btn = $(event.target);
  660. var thisIndex = getIndexClase(btn.parents('.bloque-clase').data("id_obj"));
  661. var dia = getDiaNombre(clasesObj[thisIndex].dia);
  662. $('#id').val(clasesObj[thisIndex].id_obj);
  663. $('#dia').val(clasesObj[thisIndex].dia);
  664. $('#hora').val(clasesObj[thisIndex].hora);
  665. $('#fecha_horario').html(dia+" - "+clasesObj[thisIndex].hora+" hrs.");
  666. $("#materia").find("option[value='"+clasesObj[thisIndex].materia+"']").prop("disabled",false);
  667. $("#materia").val(clasesObj[thisIndex].materia).change();
  668. var tipoMat = $('#materia').find(':selected').data('tipo');
  669. if(tipoMat == 0){
  670. if(isNaN(clasesObj[thisIndex].salon)){
  671. $('#salon').get(0).selectedIndex = 0;
  672. }else{
  673. $("#salon").val(clasesObj[thisIndex].salon).change();
  674. }
  675. }
  676. $("#duracion").val(clasesObj[thisIndex].duracion).change();
  677. $("#fecha_inicial").val(clasesObj[thisIndex].fecha_inicial);
  678. $("#fecha_final").val(clasesObj[thisIndex].fecha_final);
  679. $("#submitBtn").data('tipo', 2);
  680. $("#modalLabel").html("Editar Horario de materia");
  681. ajustaTabla();//ajusta columnas, carga submaterias
  682. //actualiza datos
  683. rows = $("#submateria-list > tr").length;//cuenta renglones actuales
  684. var i = 0;
  685. $("#submateria-list").children().each(function(index) {
  686. for(i=0; i < clasesObj[thisIndex].submaterias.length; i++){
  687. //console.log(parseInt(clasesObj[thisIndex].submaterias[i].submateria) +"=="+ parseInt($(this).find(".submateria-nombre").data('id')));
  688. if(parseInt(clasesObj[thisIndex].submaterias[i].submateria) == parseInt($(this).find(".submateria-nombre").data('id')) ){
  689. //$(this).find(".submateria-nombre").text(clasesObj[thisIndex].submaterias[index].submateria_nombre);
  690. //$(this).find(".submateria-nombre").data('id', clasesObj[thisIndex].submaterias[index].submateria);
  691. $(this).find(".submateria-inicial").val(clasesObj[thisIndex].submaterias[i].fecha_inicial);
  692. $(this).find(".submateria-final").val(clasesObj[thisIndex].submaterias[i].fecha_final);
  693. $(this).find(".submateria-activa").prop("checked", clasesObj[thisIndex].submaterias[i].activa);
  694. if(clasesObj[thisIndex].submaterias[i].activa){
  695. $('#profesor-list .profesor-submateria')
  696. .append($("<option></option>")
  697. .attr("value", clasesObj[thisIndex].submaterias[i].submateria)
  698. .text(clasesObj[thisIndex].submaterias[i].submateria_nombre));
  699. }
  700. }
  701. }
  702. });
  703. //carga renglones de profesor
  704. var rows = $("#profesor-list > tr").length;//cuenta renglones actuales
  705. if(rows > clasesObj[thisIndex].profesores.length){//sobran
  706. //borrar renglones extra pero dejar al menos 1
  707. while(rows > clasesObj[thisIndex].profesores.length && rows > 1){
  708. $("#profesor-list >tr:last-child").remove();
  709. rows--;
  710. }
  711. }else{//faltan
  712. // clone more copies of the row
  713. for(var i=rows; i < clasesObj[thisIndex].profesores.length; i++){
  714. var cloned = $("#profesor-list >tr:first-child").clone(true).appendTo("#profesor-list");
  715. cloned.find("input").val("");
  716. }
  717. }
  718. //actualiza datos
  719. $("#profesor-list").children().each(function(index) {
  720. if(index < clasesObj[thisIndex].profesores.length){//llenar info
  721. $(this).find(".profesor").val(clasesObj[thisIndex].profesores[index].profesor);
  722. $(this).find(".profesor-submateria").val(parseInt(clasesObj[thisIndex].profesores[index].submateria));
  723. if(clasesObj[thisIndex].profesores[index].salon != "" && clasesObj[thisIndex].profesores[index].salon !== undefined && !isNaN(clasesObj[thisIndex].profesores[index].salon))
  724. $(this).find(".profesor-salon").val(clasesObj[thisIndex].profesores[index].salon);
  725. else
  726. $(this).find(".profesor-salon").get(0).selectedIndex = 0;
  727. i++;
  728. }
  729. });
  730. //carga renglones de vinculos
  731. var rows = $("#vinculo-list > tr").length;//cuenta renglones actuales
  732. if(rows > clasesObj[thisIndex].vinculos.length){//sobran
  733. //borrar renglones extra pero dejar al menos 1
  734. while(rows > clasesObj[thisIndex].vinculos.length && rows > 1){
  735. $("#vinculo-list >tr:last-child").remove();
  736. rows--;
  737. }
  738. }else{//faltan
  739. // clone more copies of the row
  740. for(var i=rows; i < clasesObj[thisIndex].vinculos.length; i++){
  741. var cloned = $("#vinculo-list >tr:first-child").clone(true).appendTo("#vinculo-list");
  742. }
  743. }
  744. //actualiza datos
  745. $("#vinculo-list").children().each(function(index) {
  746. if(index < clasesObj[thisIndex].vinculos.length){//llenar info
  747. //$(this).find(".").val(clasesObj[thisIndex].vinculos[index].profesor);
  748. $(this).find(".grupo_vinculo").val(parseInt(clasesObj[thisIndex].vinculos[index].grupo));
  749. $(this).find('.grupo_vinculo option:selected').data("id_db", clasesObj[thisIndex].vinculos[index].id_db);
  750. //console.log("Data "+$(this).find('.grupo_vinculo option:selected').data("id_db"));
  751. }
  752. });
  753. //bloquea vinculos
  754. $("#vinculadas-block").find("button").attr("disabled", true);
  755. $("#vinculadas-block").find("select").attr("disabled", true);
  756. hideBorraProfesor();
  757. hideBorraVinculo();
  758. $('#modal').modal('show');
  759. });
  760. $(document).on( "click", ".bloque-agrega", function(event){//agregar materia en mismo horario
  761. var btn = $(event.target);
  762. var thisIndex = getIndexClase(btn.parents('.bloque-clase').data("id_obj"));
  763. if(_editable){
  764. $("#errorBox").collapse('hide');
  765. $("#errorBox_text").html("");
  766. $("#avanzadoBox").collapse('hide');
  767. $("#submitBtn").data('tipo', 1);
  768. $("#modalLabel").html("Crear Horario de materia");
  769. //modal.find("input[type=text]").val("");
  770. //$('.profesor').get(0).selectedIndex = 0;
  771. //$('.profesor-submateria').get(0).selectedIndex = 0;
  772. //$('.profesor-salon').get(0).selectedIndex = 0;
  773. $("#duracion").val(_grupo_duracion).change();
  774. //$('#nivel').prop("disabled", false);
  775. //$('#nivel').get(0).selectedIndex = 0;
  776. $('#fecha_inicial').val(_periodo_fecha_inicial);
  777. $('#fecha_final').val(_periodo_fecha_final);
  778. var dia = getDiaNombre(clasesObj[thisIndex].dia);
  779. $('#dia').val(clasesObj[thisIndex].dia);
  780. $('#hora').val(clasesObj[thisIndex].hora);
  781. $('#fecha_horario').html(dia+" - de "+clasesObj[thisIndex].hora+" hrs.");
  782. $('#duracion').removeClass('is-invalid');
  783. //desbloquea vinculos
  784. $("#vinculadas-block").find("button").attr("disabled", false);
  785. $("#vinculadas-block").find("select").attr("disabled", false);
  786. $('#modal').modal('show');
  787. }//fin editable
  788. });
  789. $('#modal').on('hidden.bs.modal', function () {
  790. actualizaHoras($("#materia").val());
  791. })
  792. $('#modal').on('show.bs.modal', function () {
  793. $("#submitBtn").attr("disabled", false);
  794. })
  795. function validaFechasBloque(pos, dia, fecha_ini, fecha_fin, hora_ini, duracion, periodo_completo){
  796. var horaObjIni = new Date();
  797. var horaObjFin;
  798. var horaArr = hora_ini.split(":");
  799. horaObjIni.setHours(horaArr[0]);
  800. horaObjIni.setMinutes(horaArr[1]);
  801. horaObjIni.setSeconds(0);
  802. horaObjFin = new Date(horaObjIni.getTime());
  803. horaObjFin.setMinutes(horaObjFin.getMinutes() + parseInt(duracion));
  804. for(var i=0; i < clasesObj.length; i++){
  805. var horaArr = clasesObj[i].hora.split(":");
  806. var horaClaseInicio = new Date();
  807. var horaClaseFin = new Date();
  808. horaClaseInicio.setHours(horaArr[0]);
  809. horaClaseInicio.setMinutes(horaArr[1]);
  810. horaClaseInicio.setSeconds(0);
  811. horaClaseFin = new Date(horaClaseInicio.getTime());
  812. horaClaseFin.setMinutes(horaClaseFin.getMinutes() + clasesObj[i].duracion);
  813. if(pos != i){
  814. //Objeto leído mismo día, hora de fin del objeto actual choca con hora de inicio objeto anterior
  815. if(parseInt(clasesObj[i].dia) == parseInt(dia) &&
  816. (( Date.parse(horaClaseInicio) < Date.parse(horaObjFin) && Date.parse(horaClaseInicio) >= Date.parse(horaObjIni)) ||
  817. ( Date.parse(horaObjIni) < Date.parse(horaClaseFin) && Date.parse(horaObjIni) >= Date.parse(horaClaseInicio))
  818. )
  819. ){
  820. if(
  821. ((Date.parse(fechaGuion(fecha_ini)) <= Date.parse(fechaGuion(clasesObj[i].fecha_inicial)) && Date.parse(fechaGuion(fecha_fin)) >= Date.parse(fechaGuion(clasesObj[i].fecha_inicial)) ) ||
  822. (Date.parse(fechaGuion(clasesObj[i].fecha_inicial)) <= Date.parse(fechaGuion(fecha_ini)) && Date.parse(fechaGuion(clasesObj[i].fecha_final)) >= Date.parse(fechaGuion(fecha_ini)) )
  823. )){
  824. return false;//Si existe, no es válido
  825. }
  826. }
  827. }
  828. }
  829. return true;//no existe, es válido
  830. }
  831. function validaHorasBloque(pos, dia, horaObjIni, horaObjFin){
  832. for(var i=0; i < clasesObj.length; i++){
  833. var horaArr = clasesObj[i].hora.split(":");
  834. var horaClaseInicio = new Date();
  835. horaClaseInicio.setHours(horaArr[0]);
  836. horaClaseInicio.setMinutes(horaArr[1]);
  837. horaClaseInicio.setSeconds(0);
  838. //Objeto leído no es el objeto actual, mismo día, hora de fin del objeto actual choca con hora de inicio objeto anterior
  839. if(pos != i && parseInt(clasesObj[i].dia) == parseInt(dia) && Date.parse(horaClaseInicio) < Date.parse(horaObjFin) && Date.parse(horaClaseInicio) > Date.parse(horaObjIni)){
  840. return false;//Si existe, no es válido
  841. }
  842. }
  843. return true;//no existe, es válido
  844. }
  845. 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
  846. var horaObjIni = new Date();
  847. var horaObjFin;
  848. var horaArr = hora_ini.split(":");
  849. horaObjIni.setHours(horaArr[0]);
  850. horaObjIni.setMinutes(horaArr[1]);
  851. horaObjIni.setSeconds(0);
  852. horaObjFin = new Date(horaObjIni.getTime());
  853. horaObjFin.setMinutes(horaObjFin.getMinutes() + parseInt(duracion));
  854. //Obtiene última hora de clase
  855. var fechaLimite = new Date();
  856. fechaLimite.setHours(parseInt($('.hora').last().data('hora')) + 1);
  857. fechaLimite.setMinutes(0);
  858. fechaLimite.setSeconds(0);
  859. if( Date.parse(horaObjFin) > Date.parse(fechaLimite)){
  860. return false;
  861. }
  862. return validaHorasBloque(pos, dia, horaObjIni, horaObjFin);//valida si choca con el siguiente
  863. }
  864. function loadCalendario(){
  865. $('.bloque-clase').remove();
  866. clasesObj = [];
  867. id_obj = 0;
  868. loadHorario(false);//carga horarios no editables del grupo
  869. loadHorario(true);//carga horarios editables del grupo
  870. }
  871. function loadHorario(editable){
  872. //carga horarios y crea bloques}
  873. //console.log("loadHorario");
  874. $.ajax({
  875. url: './action/horariogrupo_select.php',
  876. type: 'POST',
  877. dataType: 'json',
  878. data: { id: _grupo_id, puesto:true, editable: editable},
  879. success: function(result) {
  880. if(result["error"]!= "" && result["error"] !== undefined){
  881. //console.log("Ocurrió un error de load");
  882. $("#errorBox").collapse('show');
  883. $("#errorBox_text").html(result["error"]);
  884. $('#messageBox')[0].scrollIntoView({ block: "end" });
  885. }else{
  886. var i, j;
  887. for(i = 0; i< result["horario"].length; i++){
  888. var salon_nombre = "";
  889. var submateriaArr = [];
  890. var sinSalon_sub = false;
  891. var sinProfSubmateria = [];
  892. //console.log("salon_nombre:"+salon_nombre);
  893. if(result["horario"][i]["submaterias"].length > 0){
  894. for(j = 0; j < result["horario"][i]["submaterias"].length; j++){
  895. var submateria = {
  896. submateria: result["horario"][i]["submaterias"][j]["submateria"],
  897. submateria_nombre: result["horario"][i]["submaterias"][j]["submateria_nombre"],
  898. fecha_inicial: result["horario"][i]["submaterias"][j]["fecha_inicial"],
  899. fecha_final: result["horario"][i]["submaterias"][j]["fecha_final"],
  900. /*salon: result["horario"][i]["submaterias"][j]["salon"],
  901. salon_nombre: result["horario"][i]["submaterias"][j]["salon_nombre"],
  902. salon_nombre_completo: result["horario"][i]["submaterias"][j]["salon_nombre_completo"]*/
  903. activa: result["horario"][i]["submaterias"][j]["activa"],
  904. }
  905. sinProfSubmateria[submateria.submateria] = false;
  906. /*if(result["horario"][i]["submaterias"][j]["salon"] == ""){
  907. sinSalon_sub = true;
  908. }else{
  909. salon_nombre+= submateria.salon_nombre+", ";
  910. }*/
  911. if(submateria.submateria != "" && submateria != 0)
  912. submateriaArr.push(submateria);
  913. };
  914. /*if(salon_nombre.length > 2)
  915. salon_nombre = salon_nombre.substring(0, salon_nombre.length-2);*/
  916. }
  917. var profesorArr = [];
  918. for(j = 0; j < result["horario"][i]["profesores"].length; j++){
  919. var profesor = {
  920. profesor: result["horario"][i]["profesores"][j]["profesor"],
  921. profesor_nombre: result["horario"][i]["profesores"][j]["profesor_nombre"],
  922. submateria: result["horario"][i]["profesores"][j]["submateria"],
  923. salon: result["horario"][i]["profesores"][j]["salon"],
  924. salon_nombre: result["horario"][i]["profesores"][j]["salon_nombre"],
  925. salon_nombre_completo: result["horario"][i]["profesores"][j]["salon_nombre_completo"]
  926. }
  927. if(result["horario"][i]["profesores"][j]["salon"] != ""){
  928. salon_nombre+= profesor.salon_nombre+", ";
  929. }
  930. profesorArr.push(profesor);
  931. if(profesor.profesor === undefined || profesor.profesor == "" )
  932. sinProfSubmateria[profesor.submateria] = true;
  933. }
  934. if(salon_nombre == ""){
  935. sinSalon_sub = true;
  936. }
  937. if(salon_nombre.length > 2)
  938. salon_nombre = salon_nombre.substring(0, salon_nombre.length-2);
  939. var vinculadasArr = [];
  940. for(j = 0; j < result["horario"][i]["vinculada"].length; j++){
  941. var vinculo = {
  942. id_db: result["horario"][i]["vinculada"][j]["id_db"],/*horario*/
  943. grupo: result["horario"][i]["vinculada"][j]["id_gpo"],
  944. //grupo_nombre: result["horario"][i]["vinculada"][j]["grupo_vinculo_nombre"],
  945. materia: result["horario"][i]["vinculada"][j]["id_mat"],
  946. materia_nombre: result["horario"][i]["vinculada"][j]["nombre"],
  947. }
  948. vinculadasArr.push(vinculo);
  949. };
  950. var clase = {
  951. id_obj: id_obj,
  952. id_db: parseInt(result["horario"][i]["id"]),
  953. grupo: _grupo_id,
  954. dia: parseInt(result["horario"][i]["dia"]),
  955. dia_orig: parseInt(result["horario"][i]["dia"]),
  956. hora: result["horario"][i]["hora"],
  957. hora_orig: result["horario"][i]["hora"],
  958. duracion: parseInt(result["horario"][i]["duracion"]),
  959. materia: parseInt(result["horario"][i]["materia"]),
  960. materia_orig: parseInt(result["horario"][i]["materia"]),
  961. materia_nombre: result["horario"][i]["materia_nombre"],
  962. tipo: parseInt(result["horario"][i]["tipo"]),
  963. salon: parseInt(result["horario"][i]["salon"]),
  964. salon_nombre: result["horario"][i]["salon_nombre"],
  965. salon_nombre_completo: result["horario"][i]["salon_nombre_completo"],
  966. fecha_inicial: result["horario"][i]["fecha_inicial"],
  967. fecha_final: result["horario"][i]["fecha_final"],
  968. periodo_completo: result["horario"][i]["periodo_completo"],
  969. submaterias: submateriaArr,
  970. profesores: profesorArr,
  971. vinculos: vinculadasArr,
  972. color: result["horario"][i]["color"],
  973. colision: []
  974. };
  975. if(clase.tipo == 0){
  976. salon_nombre = clase.salon_nombre;
  977. if(clase.salon == 0 || clase.salon == "" || clase.salon === null || isNaN(clase.salon) || clase.salon === undefined){
  978. salon_nombre = "-Pendiente-";
  979. }
  980. }
  981. clasesObj.push(clase);
  982. creaHorarioHTML(id_obj, getX(clase.dia), getY(clase.hora), getAlto(clase.duracion) , clase.color, clase.materia_nombre, salon_nombre, clase.profesores.length, clase.periodo_completo, vinculadasArr.length, editable, clase.fecha_inicial, clase.fecha_final);
  983. if(result["horario"][i]["alerta"]){
  984. if(clase.tipo == 0){
  985. if(clase.profesores.length == 0 || clase.salon == 0 || clase.salon == "" || clase.salon === null || isNaN(clase.salon) || clase.salon === undefined){
  986. $("#bloque_"+id_obj+" .alerta").removeClass("d-none");
  987. //console.log(clase.materia+" Tipo 0 sin prof o sin salon");
  988. }
  989. }else{
  990. if(sinSalon_sub){
  991. $("#bloque_"+id_obj+" .alerta").removeClass("d-none");
  992. //console.log(clase.materia+" Tipo 1 sin salon "+sinSalon_sub);
  993. }
  994. if(clase.profesores.length == 0){
  995. $("#bloque_"+id_obj+" .alerta").removeClass("d-none");
  996. }
  997. /*var prof_sub = true;
  998. sinProfSubmateria.forEach(function (arrayItem) {
  999. prof_sub = prof_sub && arrayItem;
  1000. });
  1001. if(!prof_sub){
  1002. $("#bloque_"+id_obj+" .alerta").removeClass("d-none");
  1003. }*/
  1004. }
  1005. }
  1006. id_obj++;
  1007. //Actualiza horas asignadas
  1008. actualizaHoras(clase.materia);
  1009. }
  1010. }//fin for
  1011. ordenaHorario();
  1012. actualizaLista();
  1013. actualizaEditables();
  1014. _editable = true;
  1015. if(editable){
  1016. //Checa colisiones
  1017. for(var i=0; i< clasesObj.length; i++){
  1018. var colision = colisionHorario(i, getX(clasesObj[i].dia), getY(clasesObj[i].hora), getAlto(clasesObj[i].duracion));
  1019. clasesObj[i].colision = colision.slice();
  1020. cambiaAncho(i, colision);
  1021. }
  1022. }
  1023. },
  1024. error: function(jqXHR, textStatus, errorThrown ){
  1025. $("#errorBox").collapse('show');
  1026. $("#errorBox_text").html("Error al cargar horario.<br>"+errorThrown);
  1027. $('#messageBox')[0].scrollIntoView({ block: "end" });
  1028. //alert("ERROR! " + textStatus+ " - "+errorThrown);
  1029. _editable = true;
  1030. }
  1031. });//ajax
  1032. }
  1033. //funcion para guardar por ajax información
  1034. function guardaHorario(nuevo, objClase, justMove){
  1035. if(justMove != 1 && $("#materia").val() == null){
  1036. $("#errorBox").collapse('show');
  1037. $("#errorBox_text").html("El horario necesita una materia.<br>No existen materias de tu área académica para agregar.");
  1038. $('#messageBox')[0].scrollIntoView({ block: "end" });
  1039. return false;
  1040. }
  1041. $("#materia").removeClass('is-invalid');
  1042. _editable = false;
  1043. var url = './action/horariogrupo_insert.php';
  1044. if(nuevo != 1){
  1045. url = './action/horariogrupo_update.php';
  1046. }
  1047. //console.log(objClase);
  1048. var state = false;
  1049. $.ajax({
  1050. url: url,
  1051. type: 'POST',
  1052. dataType: 'json',
  1053. async: false,
  1054. data: { move: justMove, json: JSON.stringify(objClase)},
  1055. beforeSend: function(x) {
  1056. if (x && x.overrideMimeType) {
  1057. x.overrideMimeType("application/j-son;charset=UTF-8");
  1058. }
  1059. },
  1060. success: function(result) {
  1061. if(result["error"]!= "" && result["error"] !== undefined){
  1062. $("#errorBox").collapse('show');
  1063. $("#errorBox_text").html("Error al guardar el horario.<br>"+result["error"]);
  1064. $('#messageBox')[0].scrollIntoView({ block: "end" });
  1065. state = false;
  1066. }else{
  1067. state = true;
  1068. if(nuevo == 1){
  1069. objClase.id_db = result["id"];
  1070. if( Array.isArray(result["vinculos"]) && result["vinculos"].length > 0 ){
  1071. for(var i=0; i < result["vinculos"].length; i++ ){
  1072. objClase.vinculos[i].id_db = result["vinculos"][i];
  1073. }
  1074. }
  1075. actualizaEditables();
  1076. }
  1077. $("#errorBox").collapse('hide');
  1078. }
  1079. },
  1080. error: function(jqXHR, textStatus, errorThrown ){
  1081. $("#errorBox").collapse('show');
  1082. $("#errorBox_text").html("Error al guardar el horario");
  1083. $('#messageBox')[0].scrollIntoView({ block: "end" });
  1084. state = false;
  1085. }
  1086. });//ajax
  1087. _editable = true;
  1088. return state;
  1089. }
  1090. function checaActualizaciones(){
  1091. if(!_reloadOnClose && !_drag && !(($("#modal").data('bs.modal') || {_isShown: false})._isShown) && !(($("#modal_ver").data('bs.modal') || {_isShown: false})._isShown)){
  1092. //console.log("check");
  1093. ordenaHorario();
  1094. var strCheck = "";
  1095. for(var i=0; i < clasesObj.length; i++){
  1096. strCheck += clasesObj[i].dia+""+clasesObj[i].hora+""+clasesObj[i].materia+""+clasesObj[i].duracion+""+clasesObj[i].fecha_inicial+""+clasesObj[i].fecha_final+""+clasesObj[i].tipo;
  1097. }
  1098. strCheck = MD5(strCheck);
  1099. $.ajax({
  1100. url: './action/horariogrupo_validahash.php',
  1101. type: 'POST',
  1102. dataType: 'json',
  1103. data: { id: _grupo_id, check: strCheck},
  1104. success: function(result) {
  1105. if(result["error"]!= "" && result["error"] !== undefined){
  1106. $("#errorBox").collapse('show');
  1107. $("#errorBox_text").html("Error al guardar el horario.<br>"+result["error"]);
  1108. $('#messageBox')[0].scrollIntoView({ block: "end" });
  1109. }else{
  1110. var reload = result["reload"];
  1111. if(reload){
  1112. if(!_drag && !(($("#modal").data('bs.modal') || {_isShown: false})._isShown) && !(($("#modal_ver").data('bs.modal') || {_isShown: false})._isShown) ){//no están abiertos los modales{
  1113. loadCalendario();
  1114. }else{
  1115. _reloadOnClose = true;
  1116. }
  1117. }
  1118. }
  1119. },
  1120. error: function(jqXHR, textStatus, errorThrown ){
  1121. $("#errorBox").collapse('show');
  1122. $("#errorBox_text").html(errorThrown);
  1123. $('#messageBox')[0].scrollIntoView({ block: "end" });
  1124. }
  1125. });//ajax
  1126. timer(_reloadTime);
  1127. }else
  1128. timer(2);
  1129. }
  1130. function timer(tiempo = 0){
  1131. if(tiempo > 0){
  1132. setTimeout(checaActualizaciones, tiempo * 1000);
  1133. }
  1134. }
  1135. //revisa si se colocaron todas las horas
  1136. function horarioCompleto(){
  1137. /*var total = 0;
  1138. $.each($('#materiasBox').find('li .badge').find("span"), function(){
  1139. total+= parseFloat($(this).data("max"));
  1140. });
  1141. for(var i=0; i < clasesObj.length; i++){
  1142. total -= (clasesObj[i].duracion/60)
  1143. }
  1144. if(total == 0) return true;*/
  1145. return false;
  1146. }
  1147. function actualizaEditables(){
  1148. /*if(!horarioCompleto()){
  1149. if($("#calendario-body .editable").length == 0){
  1150. $("#calendario-body .fraccion").removeClass("no-editable").addClass("editable");
  1151. }
  1152. }else{
  1153. $("#calendario-body .fraccion").removeClass("editable").addClass("no-editable");
  1154. }*/
  1155. }
  1156. function traeAlFrente(index){
  1157. var classI = getIndexClase(index);
  1158. var posX = getX(clasesObj[classI].dia), posY = getY(clasesObj[classI].hora), alto = getAlto(clasesObj[classI].duracion);
  1159. var i=0;
  1160. for(i=0; i < clasesObj.length; i++){
  1161. if(posX == getX(clasesObj[i].dia) && i != classI){//mismo día, no es el horario actual
  1162. if((posY >= getY(clasesObj[i].hora) && posY <= getY(clasesObj[i].hora)+getAlto(clasesObj[i].duracion)) || (posY+alto >= getY(clasesObj[i].hora) && posY+alto <= getY(clasesObj[i].hora)+getAlto(clasesObj[i].duracion)) ){
  1163. var id = (clasesObj[i].id_obj);
  1164. $("#bloque_"+id).css({zIndex: i+10});
  1165. }
  1166. }
  1167. }
  1168. if(clasesObj.length > 0)//había otros
  1169. $("#bloque_"+index).css({zIndex: i+15});
  1170. }
  1171. $(document).on( "click", ".bloque-clase", function(event){//manda al frente de todos
  1172. var btn = $(event.target);
  1173. //var thisIndex = getIndexClase(btn.parents('.bloque-clase').data("id_obj"));
  1174. var thisIndex = btn.parents('.bloque-clase').data("id_obj");
  1175. traeAlFrente(thisIndex);
  1176. });
  1177. $(document).on( "change", ".submateria-activa", function(event){//activa submateria en lista de progesores
  1178. var check = $(event.target);
  1179. if(check.prop("checked")){
  1180. $(".profesor-submateria").each(function(){
  1181. $(this).append($("<option></option>")
  1182. .attr("value", check.data("id"))
  1183. .text(check.data("nombre")));
  1184. });
  1185. }else{
  1186. $(".profesor-submateria option").each(function(){
  1187. if($(this).attr("value") == check.data("id"))
  1188. $(this).remove();
  1189. });
  1190. }
  1191. });
  1192. /*se llama desde change
  1193. function hideOption(listObj, thisObj){
  1194. var val = thisObj.val();
  1195. $.each($(listObj).find('tr'), function(){
  1196. if($(this) != thisObj.parents("tr") && val != ""){
  1197. $(this).find('select option[value="'+val+'"]').css('display', 'none');
  1198. }
  1199. });
  1200. }
  1201. function showOption(listObj, val){
  1202. $.each($(listObj).find('tr'), function(){
  1203. $(this).find('select option[value="'+val+'"]').css('display', 'block');
  1204. });
  1205. }*/