   /* global bootbox */

   function segundaCarga() {
      listarProyectos();
      listarTipoDeUsuario();
      listarMenu();
      formeditarMenu();
      validarCombos();
      asignarDetalle();
      eliminarMenuDetalle();
      cambiarOrdenAbajo();
      cambiarOrdenArriba();
   }

   var proyecto;
   var detalle = "";
   var modified = false;
   $('#tblMenu').on('draw.dt', function () {
      $('[data-toggle="tooltip"]').tooltip();
   });
   function listarProyectos() {
      $.ajax({
         type: 'POST',
         url: "../servlet/MantenimientoMenuServlet?accion=listarProyecto",
         dataType: 'JSON',
         success: function (result) {
            var print = " <option value=''>SELECCIONE PROYECTO</option> ";
            for (var i in result) {
               print += " <option value =" + result[i].codigoProyecto + ">" + result[i].nombreProyecto + "</option> ";
            }
            $("#cboProyecto").html(print);
         }
      });
   }

   $('#btnLimpiar').click(function () {
      $('#cboTipoUsuario').val("");
      $('#cboProyecto').val("");
      $('#cboTipoUsuario').attr('disabled', true);
      $('#btnBuscar').attr('disabled', true);
      recargar();
      $('#panelTabla').addClass('hide');
      $('#panel-leyenda').addClass('hide');
   });
   function listarTipoDeUsuario() {
      $('#cboProyecto').on('change', function () {
         var proyecto = $('#cboProyecto').val();
         var json = {
            "codigo": proyecto
         };
         $.ajax({
            type: 'POST',
            url: "../servlet/MantenimientoMenuServlet?accion=listarTipoUsuario",
            dataType: 'JSON',
            data: json,
            success: function (result) {
               var print = " <option value=''>SELECCIONE TIPO DE USUARIO</option> ";
               print += " <option value='0' class='text-bold'>VISTA GENERAL</option> ";
               for (var i in result) {
                  print += " <option value =" + result[i].codigoDetalle + ">" + result[i].nombreTipoUsuario + "</option> ";
               }
               $("#cboTipoUsuario").html(print);
            }
         });
      });
   }

   var table;
   function listarMenu() {
      var json = {
         "codigo": detalle,
         "proyecto": proyecto,
         "tipo": 0
      };
      if (detalle !== "") {
         $('#panelTabla').removeClass('hide');
         table = $("#tblMenu").DataTable({
            "language": {
               "lengthMenu": "Mostrar: _MENU_",
               "zeroRecords": "&nbsp;&nbsp;&nbsp; No se encontraron resultados",
               "info": "&nbsp;&nbsp;&nbsp; Mostrando del _START_ al _END_ de un total de _TOTAL_ Menús",
               "infoEmpty": "&nbsp;&nbsp;&nbsp; Mostrando 0 de 0 registros",
               "search": "Filtrar:",
               "loadingRecords": "Cargando...",
               "processing": '<span style="width:100%;"><img src="http://www.snacklocal.com/images/ajaxload.gif"></span>',
               "paginate": {
                  "first": "First",
                  "last": "Last",
                  "next": "Siguiente",
                  "previous": "Anterior"
               }
            },
            dom: '<"datatable-scroll"t>r<"datatable-footers"ip>',
            "ajax": {
               type: 'POST',
               "url": '../servlet/MantenimientoMenuServlet?accion=listarMenu',
               "data": json
            },
            "bSort": false,
            "bFilter": false,
            "serverSide": true,
            "processing": true,
            "aaSorting": [],
            "ordering": false,
            "bLengthChange": false,
            "bInfo": false,
            "scrollCollapse": true,
            "paging": false,
            "aLengthMenu": [
               [25, 50, 100, 200, -1],
               [25, 50, 100, 200, "All"]
            ],
            "iDisplayLength": -1,
            "columnDefs": [
               {targets: 0, orderable: false, width: "45%"},
               {targets: 1, orderable: false, width: "5%", className: "text-center"},
               {targets: 2, orderable: false, width: "7%", className: "text-center"},
               {targets: 3, orderable: false, width: "10%"},
               {targets: 4, orderable: false, width: "15%", className: "text-center"}
            ],
            "columns": [
               {"data": "jerarquia",
                  render: function (data, type, row) {
                     var retorno = '';
                     if (data === 1) {
                        retorno = `<span class='titulo'><span class='label bg-success border-success-600' style="color: white">${row.nombre}</span></span>`;
                     } else if (data === 2) {
                        retorno = `<span class='modulo'><i class="fa fa-level-up fa-rotate-90" style="font-size: 16px;"></i>&nbsp;<span class="label bg-blue-700 border-blue-800" style="color: white">${row.nombre}</span></span>`;
                     } else if (data === 3) {
                        retorno = `<span class='categoria'><i class="fa fa-level-up fa-rotate-90" style="font-size: 16px;"></i>&nbsp;<span class="label bg-orange border-orange-600" style="color: white">${row.nombre}</span></span>`;
                     } else if (data === 4) {
                        retorno = `<span class='subcategoria'><i class="fa fa-level-up fa-rotate-90" style="font-size: 16px;"></i>&nbsp;<span class="label bg-danger border-danger-600" style="color: white">${row.nombre}</span></span>`;
                     }
                     return retorno;
                  }
               },
               {"data": "icono", "render": function (data, type, row) {
                     return `<a role="button" style="color: black;"><i class="fa ${data}" style="font-size: 19px"></i></a>`;
                  }
               },
               {"data": "tipo", "render": function (data, type, row) {
                     let retorno = "";
                     if (data === 1) {
                        retorno = "<span class='label bg-slate-600 border-slate-700' style='color: white'>ÚNICO</span>";
                     } else if (data === 2) {
                        retorno = '<span class="label bg-info-600 border-info-700" style="color: white">DESPLEGABLE</span>';
                     }
                     return retorno;
                  }
               },
               {"data": "url"},
               {"data": "jerarquia", "render": function (data, type, row) {
                     let retorno = ``;
                     let nombre = "";
                     switch (data) {
                        case 1:
                           nombre = "Modulo";
                           break;
                        case 2:
                           nombre = "Categoria";
                           break;
                        case 3:
                           nombre = "Subcategoría";
                           break;
                        case 4:
                           nombre = "Nada";
                           break;
                     }
                     if (data !== 4 && row.url === '#' || row.url === '') {
                        retorno += `<span data-toggle="tooltip"  title="Crear ${nombre}" style="cursor: pointer"> <i class='crear glyphicon glyphicon-plus text-slate-800' style="font-size: 15px"></i>&nbsp;&nbsp; </span>`;
                     }
                     retorno += `<span data-toggle="tooltip"  title="Editar" style="cursor: pointer"> <i class='editar glyphicon glyphicon-pencil text-teal-800' style="font-size: 15px"></i>&nbsp;&nbsp; </span>`;
                     if (row.configuracion !== 0) {
                        retorno += `<span data-toggle="tooltip"  title="Bajar" style="cursor: pointer"> <i class='abajo fa fa-chevron-circle-down text-primary-800' style="font-size: 16px"></i>&nbsp;&nbsp; </span>`;
                        retorno += `<span data-toggle="tooltip"  title="Subir" style="cursor: pointer"> <i class='arriba fa fa-chevron-circle-up text-primary-800' style="font-size: 16px"></i>&nbsp;&nbsp; </span>`;
                     }
                     retorno += `<span data-toggle="tooltip"  title="Eliminar" style="cursor: pointer"> <i class='eliminar fa fa-trash text-danger-800' style="font-size: 16px"></i>&nbsp;&nbsp; </span>`;
                     return retorno;
                  }

               }
            ], initComplete: function (nopor, data) {
               $("#tblMenu").addClass("table table-responsive table-striped table-hover table-bordered");
            }
         });
      } else {
         table = $("#tblMenu").DataTable();
      }
   }

   function formeditarMenu() {
      $('#tblMenu tbody').on('click', '.editar', function () {
         var dataTabla = "";
         dataTabla = table.row($(this).parents('tr')).data();
         var codigo = dataTabla["codigo"];
         var jerarquia = dataTabla["jerarquia"];
         var json = {
            codigo: codigo,
            jerarquia: jerarquia
         };
         $.ajax({
            type: 'POST',
            url: "../servlet/MantenimientoMenuServlet?accion=validarEdicionMenu",
            dataType: 'JSON',
            data: {
               json: JSON.stringify(json)
            },
            success: function (data, textStatus, jqXHR) {
               if (data.status === false) {
                  bootbox.dialog({
                     className: "dialogExtraSmall",
                     title: "<i class='ace-icon fa fa-exclamation-circle white'></i> <span class='white'>Advertencia</span>",
                     headerClass: "modal-bg-warning",
                     message: "Este menú está siendo usado por otro proyecto",
                     buttons: {
                        si: {
                           label: "<i class='fa fa-check bigger-110'></i>&nbsp; OK",
                           className: "btn bg-orange border-orange-600 btn-xs",
                           callback: function () {
                           }
                        }
                     }
                  });
               } else {
                  crearFormEdicion(dataTabla);
               }
            }
         });
      });
   }

   function crearFormEdicion(data) {
      console.log(data);
      var tipo = data["tipo"];
      var codigo = data["codigo"];
      var jerarquia = data["jerarquia"];
      var nombre = data["nombre"];
      var url = data["url"];
      var visible = data["esVisible"];
      var txturl;
      if (tipo === 1 || jerarquia === 4) {
         txturl = url.slice(0, -4);
      } else {
         txturl = url;
      }
      var icono = data["icono"];
      var formEditar = bootbox.dialog({
         title: "<span><i class='ace-icon fa fa-tags'></i> <span>EDITAR MENU</span>",
         headerClass: "modal-bg-primary",
         size: "medium",
         message: `<form id="formEditarMenu" onsubmit="return false" autocomplete="off">
                                    <div class='divCont row'>  
                                        <div class="frm col-md-6" id="formNombre">                                            
                                            <label style="font-size: small">
                                                Nombre: 
                                            </label>
                                            <span id="spanAterik" class="asterisk"> (*)</span>
                                            <input type="text" id="editarNombre" name="txtNombre" class="form-control" value="${capitalizeWords(nombre)}" placeholder="INGRESE NOMBRE DEL MENU" style="text-transform:uppercase">                                            
                                        </div>
                                        <div class='frm col-md-6' id="formIcono">
                                            <label style="font-size: small">
                                                Icono: 
                                            </label>
                                            <span id="spanAterik" class="asterisk"> (*)</span>
                                            <input id="editarIcono" name="txtIcono" class="icp-opts form-control" type="text" value="${icono}" placeholder="INGRESE ICONO"/>
                                        </div>                                     
                   
                                        <div class="frm col-md-6" id="formTipo">                                            
                                            <label style="font-size: small">
                                                Tipo: 
                                            </label>
                                            <span id="spanAterik" class="asterisk"> (*)</span>
                                            <select id="editarTipo" name="cboTipo" class="form-control">
                                                <option value="">SELECCIONE TIPO</option>                                                
                                                <option value="2">DESPLEGABLE</option>
                                                <option value="1">UNICO</option>
                                            </select>
                                        </div>
                                        <div class="frm col-md-6" id ="formUrl"> 
                                            <label style="font-size: small">
                                                Url: 
                                            </label>
                                            <span id="spanAterik" class="asterisk"> (*)</span>
                                            <div class="input-group" id="formClave">
                                                    <input type="text" id="editarUrl" name="txtUrl" value="${txturl}" class="form-control" placeholder="INGRESE URL">  
                                                    <span class="input-group-addon"><div class="" style="color:#848484">.jsp</div></span>
                                            </div> 
                                        </div>
                                        <div class='frm col-md-6' id="formEsVisible">
                                            <label style="font-size: small">
                                                Es visible: 
                                            </label>
                                            <input id="chkVisible" name="chkEsVisible" class="icp-opts form-control switch" type="checkbox"/>
                                        </div>   
                                        <div class='col-md-12 hide' id="formHide">
                                            &nbsp;
                                        </div>
                                    </div>                                    
                                        <div class="col-md-12 pull-right form-group">                                              
                                            <div class="text-right" style="font-size: small"> 
                                                <span class="text-danger">(*) </span>  Campo obligatorio
                                            </div>
                                        </div> 
                                </form>`,
         buttons: {
            si: {
               label: "<i class='fa fa-check bigger-110'></i>&nbsp; Editar",
               className: "btn bg-primary border-primary-600 btn-xs buttonOk",
               callback: function () {
                  var validar = $("#formEditarMenu").validate({
                     rules: {
                        txtNombre: {required: true},
                        txtIcono: {required: true},
                        cboTipo: {required: true},
                        txtUrl: {required: true}
                     },
                     messages: {
                        txtNombre: {required: "<b>&times; Ingrese un Nombre</b>"},
                        txtIcono: {required: "<b>&times; Seleccione un Icono</b>"},
                        cboTipo: {required: "<b>&times; Seleccione un Tipo de Menú</b>"},
                        txtUrl: {required: "<b>&times; Ingrese una Url</b>"}
                     },
                     errorPlacement:
                             function (error, element) {
                                if (element.attr("id") === "editarUrl") {
                                   error.insertAfter("#formClave");
                                } else {
                                   error.insertAfter(element);
                                }
                             }
                  });
                  if (validar.form()) {
                     editarMenu(data);
                  } else {
                     return false;
                  }
               }
            },
            no: {
               label: "<i class='fa fa-times bigger-110'></i>&nbsp; Cancelar",
               className: "btn bg-danger border-danger-600 btn-xs",
               callback: function () {
               }
            }
         }
      });
      formEditar.init(function () {
         $('#editarTipo').val(tipo);
         validarInput();
         if (tipo === 2) {
            $('#editarTipo').change();
         }
         if (jerarquia === 2 || jerarquia === 3) {
            validarDependenciaEditar(data);
         }
         
         if(visible){
            $("#chkVisible").prop("checked", true);
         }else{
             $("#chkVisible").removeAttr("checked");
         }
         
         validarFormulario(jerarquia);
         submitKey('formEditarMenu', '.buttonOk');
         validCaracForm();
      });
   }

   function recargar() {
      table.destroy();
      listarMenu();
   }

   function refrescar() {
      table.ajax.reload()
   }

   function validarDependenciaEditar(data) {
      tdata = $("#tblMenu").dataTable().fnGetData();
      var conta = 0;
      for (var i = 0; i < tdata.length; i++) {
         if (tdata[i].padre === data.codigo && tdata[i].jerarquia === data.jerarquia + 1) {
            conta++;
         }
      }
      if (conta >= 1) {
         $('#formTipo').addClass('hide');
         $('#formUrl').addClass('hide');
         if (data.jerarquia === 3) {
            $('#formNombre').removeClass('col-md-6')
            $('#formNombre').addClass('col-md-12')
         }
      }
   }

   function validCaracForm() {
//      new Input({el: '#editarUrl', param: 'text'}).validate();
//      new Input({el: '#editarNombre', param: 'text'}).validate();
//      s Input({el: '#editarIcono', param: 'text'}).validate();
   }

   function validarFormulario(jerarquia) {
      if (jerarquia === 1) {
         $('#formTipo').addClass('hide');
         $('#formUrl').addClass('hide');
      } else if (jerarquia === 3) {
         $('#formIcono').addClass('hide');
      } else if (jerarquia === 4) {
         $('#formIcono').addClass('hide');
         $('#formTipo').addClass('hide');
         $('.divCont').removeClass('col-md-12');
         $('#formHide').removeClass('hide');
      }
   }

   function validarInput() {
      $('#editarTipo').on('change', function () {
         var tipo = $('#editarTipo').val();
         if (tipo === "2") {
            $('#editarUrl').attr('disabled', true);
            $('#editarUrl').val("#");
         } else {
            $('#editarUrl').attr('disabled', false);
            $('#editarUrl').val("");
         }
      });
   }

   function editarMenu(data) {
      var tipoMenu = $('#editarTipo').val();
      var url = $('#editarUrl').val();
      var txturl;
      if (tipoMenu === "1" || data.jerarquia === 4) {
         txturl = url + '.jsp';
      } else {
         txturl = url;
      }
      
      var json = {
         "codigo": data.codigo,
         "jerarquia": data.jerarquia,
         "tipo": tipoMenu,
         "url": txturl,
         "nombre": $('#editarNombre').val(),
         "icono": $('#editarIcono').val(),
         "esVisible": $("#chkVisible").is(':checked')
      };
      $.ajax({
         type: 'POST',
         url: "../servlet/MantenimientoMenuServlet?accion=editarMenu",
         dataType: 'JSON',
         data: {
            json: JSON.stringify(json)
         },
         success: function (data, textStatus, jqXHR) {
            if (data.status === true) {
               bootbox.dialog({
                  className: "dialogExtraSmall",
                  title: "<i class='ace-icon fa fa-tags white'></i> <span class='white'>Notificación</span>",
                  headerClass: "modal-bg-success",
                  message: "Menú correctamente modificado",
                  buttons: {
                     si: {
                        label: "<i class='fa fa-check bigger-110'></i>&nbsp; Aceptar",
                        className: "btn bg-success border-success-600 btn-xs",
                        callback: function () {
                           recargar();
                        }
                     }
                  }
               });
            } else {
               bootbox.dialog({
                  className: "dialogExtraSmall",
                  title: "<i class='ace-icon fa fa-exclamation-circle white'></i> <span class='white'>Advertencia</span>",
                  headerClass: "modal-bg-warning",
                  message: "Ha ocurrido un error",
                  buttons: {
                     si: {
                        label: "<i class='fa fa-check bigger-110'></i>&nbsp; Aceptar",
                        className: "btn bg-orange border-orange-600 btn-xs",
                        callback: function () {
                        }
                     }
                  }
               });
            }
         }
      });
   }

   $('#btnBuscar').click(function () {
      proyecto = $('#cboProyecto').val();
      detalle = $('#cboTipoUsuario').val();
      recargar();
      $('#btnNuevoTitulo').removeClass('hide');
      $('#panel-leyenda').removeClass('hide');
   });

//   function activarIconPicker() {
//      $('.icp-opts').iconpicker({
//         hideOnSelect: true,
//         icons: ['fa-adjust', 'fa-anchor', 'fa-archive', 'fa-area-chart', 'fa-arrows', 'fa-arrows-h', 'fa-arrows-v', 'fa-asterisk', 'fa-at', 'fa-automobile', 'fa-ban', 'fa-bank', 'fa-bar-chart', 'fa-barcode', 'fa-bars', 'fa-bed', 'fa-beer', 'fa-bell', 'fa-bell-o', 'fa-bell-slash', 'fa-bell-slash-o', 'fa-bicycle', 'fa-binoculars', 'fa-birthday-cake', 'fa-bolt', 'fa-bomb', 'fa-book', 'fa-bookmark', 'fa-bookmark-o', 'fa-briefcase', 'fa-bug', 'fa-building', 'fa-building-o', 'fa-bullhorn', 'fa-bullseye', 'fa-bus', 'fa-cab', 'fa-calculator', 'fa-calendar', 'fa-calendar-o', 'fa-camera', 'fa-camera-retro', 'fa-car', 'fa-caret-square-o-down', 'fa-caret-square-o-left', 'fa-caret-square-o-right', 'fa-caret-square-o-up', 'fa-cart-arrow-down', 'fa-cart-plus', 'fa-cc', 'fa-certificate', 'fa-check', 'fa-check-circle', 'fa-check-circle-o', 'fa-check-square', 'fa-check-square-o', 'fa-child', 'fa-circle', 'fa-circle-o', 'fa-circle-o-notch', 'fa-circle-thin', 'fa-clock-o', 'fa-close', 'fa-cloud', 'fa-cloud-download', 'fa-cloud-upload', 'fa-code', 'fa-code-fork', 'fa-coffee', 'fa-cog', 'fa-cogs', 'fa-comment', 'fa-comment-o', 'fa-comments', 'fa-comments-o', 'fa-compass', 'fa-copyright', 'fa-credit-card', 'fa-crop', 'fa-crosshairs', 'fa-cube', 'fa-cubes', 'fa-cutlery', 'fa-dashboard', 'fa-database', 'fa-desktop', 'fa-diamond', 'fa-dot-circle-o', 'fa-download', 'fa-edit', 'fa-ellipsis-h', 'fa-ellipsis-v', 'fa-envelope', 'fa-envelope-o', 'fa-envelope-square', 'fa-eraser', 'fa-exchange', 'fa-exclamation', 'fa-exclamation-circle', 'fa-exclamation-triangle', 'fa-external-link', 'fa-external-link-square', 'fa-eye', 'fa-eye-slash', 'fa-eyedropper', 'fa-fax', 'fa-female', 'fa-fighter-jet', 'fa-file-archive-o', 'fa-file-audio-o', 'fa-file-code-o', 'fa-file-excel-o', 'fa-file-image-o', 'fa-file-movie-o', 'fa-file-pdf-o', 'fa-file-photo-o', 'fa-file-picture-o', 'fa-file-powerpoint-o', 'fa-file-sound-o', 'fa-file-video-o', 'fa-file-word-o', 'fa-file-zip-o', 'fa-film', 'fa-filter', 'fa-fire', 'fa-fire-extinguisher', 'fa-flag', 'fa-flag-checkered', 'fa-flag-o', 'fa-flash', 'fa-flask', 'fa-folder', 'fa-folder-o', 'fa-folder-open', 'fa-folder-open-o', 'fa-frown-o', 'fa-futbol-o', 'fa-gamepad', 'fa-gavel', 'fa-gear', 'fa-gears', 'fa-genderless', 'fa-gift', 'fa-glass', 'fa-globe', 'fa-graduation-cap', 'fa-group', 'fa-hdd-o', 'fa-headphones', 'fa-heart', 'fa-heart-o', 'fa-heartbeat', 'fa-history', 'fa-home', 'fa-hotel', 'fa-image', 'fa-inbox', 'fa-info', 'fa-info-circle', 'fa-institution', 'fa-key', 'fa-keyboard-o', 'fa-language', 'fa-laptop', 'fa-leaf', 'fa-legal', 'fa-lemon-o', 'fa-level-down', 'fa-level-up', 'fa-life-saver', 'fa-lightbulb-o', 'fa-line-chart', 'fa-location-arrow', 'fa-lock', 'fa-magic', 'fa-magnet', 'fa-mail-forward', 'fa-mail-reply', 'fa-mail-reply-all', 'fa-male', 'fa-map-marker', 'fa-meh-o', 'fa-microphone', 'fa-microphone-slash', 'fa-minus', 'fa-minus-circle', 'fa-minus-square', 'fa-minus-square-o', 'fa-mobile', 'fa-mobile-phone', 'fa-money', 'fa-moon-o', 'fa-mortar-board', 'fa-motorcycle', 'fa-music', 'fa-navicon', 'fa-newspaper-o', 'fa-paint-brush', 'fa-paper-plane', 'fa-paper-plane-o', 'fa-paw', 'fa-pencil', 'fa-pencil-square', 'fa-pencil-square-o', 'fa-phone', 'fa-phone-square', 'fa-photo', 'fa-picture-o', 'fa-pie-chart', 'fa-plane', 'fa-plug', 'fa-plus', 'fa-plus-circle', 'fa-plus-square', 'fa-plus-square-o', 'fa-power-off', 'fa-print', 'fa-puzzle-piece', 'fa-qrcode', 'fa-question', 'fa-question-circle', 'fa-quote-left', 'fa-quote-right', 'fa-random', 'fa-recycle', 'fa-refresh', 'fa-remove', 'fa-reorder', 'fa-reply', 'fa-reply-all', 'fa-retweet', 'fa-road', 'fa-rocket', 'fa-rss', 'fa-rss-square', 'fa-search', 'fa-search-minus', 'fa-search-plus', 'fa-send', 'fa-send-o', 'fa-server', 'fa-share', 'fa-share-alt', 'fa-share-alt-square', 'fa-share-square', 'fa-share-square-o', 'fa-shield', 'fa-ship', 'fa-shopping-cart', 'fa-sign-in', 'fa-sign-out', 'fa-signal', 'fa-sitemap', 'fa-sliders', 'fa-smile-o', 'fa-soccer-ball-o', 'fa-sort', 'fa-sort-alpha-asc', 'fa-sort-alpha-desc', 'fa-sort-amount-asc', 'fa-sort-amount-desc', 'fa-sort-asc', 'fa-sort-desc', 'fa-sort-downsort-numeric-asc', 'fa-sort-numeric-desc', 'fa-sort-up', 'fa-space-shuttle', 'fa-spinner', 'fa-spoon', 'fa-square', 'fa-square-o', 'fa-star', 'fa-star-half', 'fa-star-half-empty', 'fa-star-half-full', 'fa-star-half-o', 'fa-star-o', 'fa-street-view', 'fa-suitcase', 'fa-sun-o', 'fa-support', 'fa-tablet', 'fa-tachometer', 'fa-tag', 'fa-tags', 'fa-tasks', 'fa-taxi', 'fa-terminal', 'fa-thumb-tack', 'fa-thumbs-down', 'fa-thumbs-o-down', 'fa-thumbs-o-up', 'fa-thumbs-up', 'fa-ticket', 'fa-times', 'fa-times-circle', 'fa-times-circle-o', 'fa-tint', 'fa-toggle-down', 'fa-toggle-left', 'fa-toggle-off', 'fa-toggle-on', 'fa-toggle-right', 'fa-toggle-up', 'fa-trash', 'fa-trash-o', 'fa-tree', 'fa-trophy', 'fa-truck', 'fa-tty', 'fa-umbrella', 'fa-university', 'fa-unlock', 'fa-unlock-alt', 'fa-unsorted', 'fa-upload', 'fa-user', 'fa-user-plus', 'fa-user-secret', 'fa-user-times', 'fa-users', 'fa-video-camera', 'fa-volume-down', 'fa-volume-off', 'fa-volume-up', 'fa-warning', 'fa-wheelchair', 'fa-wifi', 'fa-wrench', 'fa-bed', 'fa-buysellads', 'fa-cart-arrow-down', 'fa-cart-plus', 'fa-connectdevelop', 'fa-dashcube', 'fa-diamond', 'fa-facebook-official', 'fa-forumbee', 'fa-heartbeat', 'fa-hotel', 'fa-leanpub', 'fa-mars', 'fa-mars-double', 'fa-mars-stroke', 'fa-mars-stroke-h', 'fa-mars-stroke-v', 'fa-medium', 'fa-mercury', 'fa-motorcycle', 'fa-neuter', 'fa-pinterest-p', 'fa-sellsy', 'fa-server', 'fa-ship', 'fa-shirtsinbulk', 'fa-simplybuilt', 'fa-skyatlas', 'fa-street-view', 'fa-subway', 'fa-train', 'fa-transgender', 'fa-transgender-alt', 'fa-user-plus', 'fa-user-secret', 'fa-user-times', 'fa-venus', 'fa-venus-double', 'fa-venus-mars', 'fa-viacoin', 'fa-whatsapp', 'fa-circle-o-notch', 'fa-cog', 'fa-gear', 'fa-refresh', 'fa-spinner', 'fa-check-square', 'fa-check-square-o', 'fa-circle', 'fa-circle-o', 'fa-dot-circle-o', 'fa-minus-square', 'fa-minus-square-o', 'fa-plus-square', 'fa-plus-square-o', 'fa-square', 'fa-square-o', 'fa-area-chart', 'fa-bar-chart', 'fa-bar-chart-o', 'fa-line-chart', 'fa-pie-chart', 'fa-bitcoin', 'fa-btc', 'fa-cny', 'fa-dollar', 'fa-eur', 'fa-euro', 'fa-gbp', 'fa-ils', 'fa-inr', 'fa-jpy', 'fa-krw', 'fa-money', 'fa-rmb', 'fa-rouble', 'fa-rub', 'fa-ruble', 'fa-rupee', 'fa-shekel', 'fa-sheqel', 'fa-try', 'fa-turkish-lira', 'fa-usd', 'fa-won', 'fa-yen', 'fa-align-center', 'fa-align-justify', 'fa-align-left', 'fa-align-right', 'fa-bold', 'fa-chain', 'fa-chain-broken', 'fa-clipboard', 'fa-columns', 'fa-copy', 'fa-cut', 'fa-dedent', 'fa-eraser', 'fa-file', 'fa-file-o', 'fa-file-text', 'fa-file-text-o', 'fa-files-o', 'fa-floppy-o', 'fa-font', 'fa-header', 'fa-indent', 'fa-italic', 'fa-link', 'fa-list', 'fa-list-alt', 'fa-list-ol', 'fa-list-ul', 'fa-outdent', 'fa-paperclip', 'fa-paragraph', 'fa-paste', 'fa-repeat', 'fa-rotate-left', 'fa-rotate-right', 'fa-save', 'fa-scissors', 'fa-strikethrough', 'fa-subscript', 'fa-superscript', 'fa-table', 'fa-text-height', 'fa-text-width', 'fa-th', 'fa-th-large', 'fa-th-list', 'fa-underline', 'fa-undo', 'fa-unlink', 'fa-align-center', 'fa-align-justify', 'fa-align-left', 'fa-align-right', 'fa-bold', 'fa-chain', 'fa-chain-broken', 'fa-clipboard', 'fa-columns', 'fa-copy', 'fa-cut', 'fa-dedent', 'fa-eraser', 'fa-file', 'fa-file-o', 'fa-file-text', 'fa-file-text-o', 'fa-files-o', 'fa-floppy-o', 'fa-font', 'fa-header', 'fa-indent', 'fa-italic', 'fa-link', 'fa-list', 'fa-list-alt', 'fa-list-ol', 'fa-list-ul', 'fa-outdent', 'fa-paperclip', 'fa-paragraph', 'fa-paste', 'fa-repeat', 'fa-rotate-left', 'fa-rotate-right', 'fa-save', 'fa-scissors', 'fa-strikethrough', 'fa-subscript', 'fa-superscript', 'fa-table', 'fa-text-height', 'fa-text-width', 'fa-th', 'fa-th-large', 'fa-th-list', 'fa-underline', 'fa-undo', 'fa-unlink', 'fa-angle-double-down', 'fa-angle-double-left', 'fa-angle-double-right', 'fa-angle-double-up', 'fa-angle-down', 'fa-angle-left', 'fa-angle-right', 'fa-angle-up', 'fa-arrow-circle-down', 'fa-arrow-circle-left', 'fa-arrow-circle-o-down', 'fa-arrow-circle-o-left', 'fa-arrow-circle-o-right', 'fa-arrow-circle-o-up', 'fa-arrow-circle-right', 'fa-arrow-circle-up', 'fa-arrow-down', 'fa-arrow-left', 'fa-arrow-right', 'fa-arrow-up', 'fa-arrows', 'fa-arrows-alt', 'fa-arrows-h', 'fa-arrows-v', 'fa-caret-down', 'fa-caret-left', 'fa-caret-right', 'fa-caret-square-o-down', 'fa-caret-square-o-left', 'fa-caret-square-o-right', 'fa-caret-square-o-up', 'fa-caret-up', 'fa-chevron-circle-down', 'fa-chevron-circle-left', 'fa-chevron-circle-right', 'fa-chevron-circle-up', 'fa-chevron-down', 'fa-chevron-left', 'fa-chevron-right', 'fa-chevron-up', 'fa-hand-o-down', 'fa-hand-o-left', 'fa-hand-o-right', 'fa-hand-o-up', 'fa-long-arrow-down', 'fa-long-arrow-left', 'fa-long-arrow-right', 'fa-long-arrow-up', 'fa-toggle-down', 'fa-toggle-left', 'fa-toggle-right', 'fa-toggle-up', 'fa-arrows-alt', 'fa-backward', 'fa-compress', 'fa-eject', 'fa-expand', 'fa-fast-backward', 'fa-fast-forward', 'fa-forward', 'fa-pause', 'fa-play', 'fa-play-circle', 'fa-play-circle-o', 'fa-step-backward', 'fa-step-forward', 'fa-stop', 'fa-youtube-play']
//      });
//   }

   function validarCombos() {
      $('#cboTipoUsuario').attr('disabled', true);
      $('#btnBuscar').attr('disabled', true);
      $('#cboProyecto').on('change', function () {
         $('#btnBuscar').attr('disabled', true);
         var proyecto = $('#cboProyecto').val();
         if (proyecto === "") {
            $('#cboTipoUsuario').attr('disabled', true);
         } else {
            $('#cboTipoUsuario').attr('disabled', false);
         }
      });
      $('#cboTipoUsuario').on('change', function () {
         var tipo = $('#cboTipoUsuario').val();
         if (tipo === "") {
            $('#btnBuscar').attr('disabled', true);
         } else {
            $('#btnBuscar').attr('disabled', false);
         }
      });
   }

   function nuevoMenuTabla(codigo, apunta) {
      $('#btnNuevoMenu').on('click', function () {
         $('.tablaMenus').addClass('hide');
         formcrearMenu(codigo, apunta, 0, "");
      });
   }

   function nuevoMenuEditado(apunta, codigo) {
      $('#tblDetalle tbody').on('click', '.editar', function () {
         $('.tablaMenus').addClass('hide');
         var dataTabla = "";
         dataTabla = $("#tblDetalle").DataTable().row($(this).parents('tr')).data();
         formcrearMenu(codigo, apunta, 1, dataTabla);
      });
   }

   function rellenarFormulario(datos, jerarquia) {
      var tipo = datos.tipo;
      var url = datos.url;
      $('#editarNombre').val(datos.nombre);
      $('#editarIcono').val(datos.icono);
      $('#editarTipo').val(tipo);
      var txturl;
      if (tipo === 1 || jerarquia === 4) {
         txturl = url.slice(0, -4);
      } else {
         txturl = url;
      }
      $('#editarUrl').val(txturl);
   }

   function formcrearMenu(codigo, apunta, tipo, datos) {
      modified = false;
      switch (apunta) {
         case 1:
            tabla = "Título";
            break;
         case 2:
            tabla = "Módulo";
            break;
         case 3:
            tabla = "Categoría";
            break;
         case 4:
            tabla = "Subcategoría";
            break;
      }
      var formCrear = bootbox.dialog({
         title: `<b><i class='ace-icon fa fa-tags'></i> <span class=''>${tabla.toUpperCase()}</span></b>`,
         className: "btbxMenu",
         headerClass: "modal-bg-primary",
         size: "medium",
         message: `<form id="formCrearMenu" onsubmit="return false" autocomplete="off">
                                    <input type="hidden" id="codigoConsejo"></input>
                                    <div class='divCont row'>  
                                        <div class="frm col-md-6" id="formNombre">                                            
                                            <label style="font-size: small">
                                                Nombre: 
                                            </label>
                                            <span id="spanAterik" class="asterisk"> (*)</span>
                                            <input type="text" id="editarNombre" name="txtNombre" class="form-control" value="" placeholder="INGRESE NOMBRE DEL ${tabla.toUpperCase()}" style="text-transform:uppercase">                                            
                                        </div>
                                        <div class='frm col-md-6' id="formIcono">
                                            <label style="font-size: small">
                                                Icono: 
                                            </label>
                                            <span id="spanAterik" class="asterisk"> (*)</span>
                                            <input id="editarIcono" name="txtIcono" class="icp-opts form-control" type="text" value="" placeholder="INGRESE ICONO"/>
                                        </div>    
                                     <div class='divCont' id="formUrl">
                                        <div class="frm col-md-6" id="formTipo">                                            
                                            <label style="font-size: small">
                                                Tipo: 
                                            </label>
                                            <span id="spanAterik" class="asterisk"> (*)</span>
                                            <select id="editarTipo" name="cboTipo" class="form-control">
                                                <option value="">SELECCIONE TIPO</option>                                                
                                                <option value="2">Desplegable</option>
                                                <option value="1">Único</option>
                                            </select>
                                        </div>
                                        <div class="frm col-md-6"> 
                                            <label style="font-size: small">
                                                Url: 
                                            </label>
                                            <span id="spanAterik" class="asterisk"> (*)</span>
                                             <div class="input-group"  id="formUrlUnico">
                                                    <input type="text" id="editarUrl" name="txtUrl" class="form-control" value="" placeholder="INGRESE URL">  
                                                    <span class="input-group-addon"><div class="" style="color:#848484">.jsp</div></span>
                                            </div>                                                                                       
                                        </div>
                                        <div class='col-md-12 hide' id="formHide">
                                            &nbsp;
                                        </div>
                                    </div>                                    
                                    </div>                                    
                                        <div class="col-md-12 pull-right form-group">                                              
                                            <div class="text-right" style="font-size: small"> 
                                                <span class="text-danger"> (*)</span>  Campo obligatorio
                                            </div>
                                        </div> 
                                </form>`,
         buttons: {
            si: {
               label: "<i class='fa fa-check bigger-110'></i>&nbsp; Crear",
               className: "btn bg-primary border-primary-600 btn-xs buttonOk",
               callback: function () {
                  var validar = $("#formCrearMenu").validate({
                     rules: {
                        txtNombre: {required: true},
                        txtIcono: {required: true},
                        cboTipo: {required: true},
                        txtUrl: {required: true}
                     },
                     messages: {
                        txtNombre: {required: "<b>&times; Ingrese un Nombre</b>"},
                        txtIcono: {required: "<b>&times; Seleccione un Icono</b>"},
                        cboTipo: {required: "<b>&times; Seleccione un Tipo de Menú</b>"},
                        txtUrl: {required: "<b>&times; Ingrese una Url</b>"}
                     },
                     errorPlacement:
                             function (error, element) {
                                if (element.attr("id") === "editarUrl") {
                                   error.insertAfter("#formUrlUnico");
                                } else {
                                   error.insertAfter(element);
                                }
                             }
                  });
                  if (validar.form()) {
                     if (modified === false && tipo === 1) {
                        $('.btbxMenu').addClass('hide');
                        bootbox.dialog({
                           className: "dialogExtraSmall",
                           title: "<i class='ace-icon fa fa-exclamation-circle white'></i> <span class='white'>Advertencia</span>",
                           headerClass: "modal-bg-warning",
                           message: `Ya existe un ${tabla} con estas características`,
                           buttons: {
                              si: {
                                 label: "<i class='fa fa-check bigger-110'></i>&nbsp; Aceptar",
                                 className: "btn bg-orange border-orange-600 btn-xs",
                                 callback: function () {
                                    $('.btbxMenu').removeClass('hide');
                                 }
                              }
                           }
                        });
                        return false;
                     } else {
                        if (detalle === '0') {
                           crearMenu(apunta, codigo, proyecto, 0, );
                        } else {
                           crearMenu(apunta, codigo, detalle, 1, );
                        }
                     }
                  } else {
                     return false;
                  }
               }
            },
            no: {
               label: "<i class='fa fa-times bigger-110'></i>&nbsp; Cancelar",
               className: "btn bg-danger border-danger-600 btn-xs",
               callback: function () {
                  $('.tablaMenus').removeClass('hide');
               }
            }
         }
      });
      formCrear.init(function () {
         validCaracForm();
//         activarIconPicker();
         validarInput();
         validarFormulario(apunta);
         submitKey('formCrearMenu', '.buttonOk');
//         soloLetras('editarUrl');
         if (tipo === 1) {
            rellenarFormulario(datos, apunta);
         }
         if (datos.tipo === 2) {
            $('#editarTipo').change();
         }
         getChangesOnForm();
      });
   }

   function getChangesOnForm() {
      $('#formCrearMenu').change(function () {
         if (modified === false) {
            modified = true;
         }
      });
   }

   $('#btnNuevoTitulo').click(function () {
      var codigo = 0;
      var jerarquia = 0;
      var apunta = jerarquia + 1;
      var nombre = obtenerNombreTabla(apunta);
      crearFormTabla(codigo, apunta, nombre);
   });

   function crearMenu(jerarquia, codigo, param, tipo) {
      var nombre = obtenerNombreTabla(jerarquia);
      var tipoMenu = $('#editarTipo').val();
      var url = $('#editarUrl').val();
      var txturl;
      if (tipoMenu === "1" || jerarquia === 4) {
         txturl = url + '.jsp';
      } else {
         txturl = url;
      }
      var json = {
         nombre: $('#editarNombre').val(),
         icono: $('#editarIcono').val(),
         padre: codigo,
         tipoMenu: tipoMenu,
         url: txturl,
         proyecto: param,
         tipo: tipo,
         jerarquia: jerarquia
      };
      $.ajax({
         type: 'POST',
         url: "../servlet/MantenimientoMenuServlet?accion=nuevoMenu",
         dataType: 'JSON',
         data: {
            json: JSON.stringify(json)
         },
         success: function (data, textStatus, jqXHR) {
            if (data.status === true) {
               bootbox.dialog({
                  className: "dialogExtraSmall",
                  title: "<i class='ace-icon fa fa-tags white'></i> <span class='white'>Notificación</span>",
                  headerClass: "modal-bg-success",
                  message: `${data.message}`,
                  buttons: {
                     si: {
                        label: "<i class='fa fa-check bigger-110'></i>&nbsp; OK",
                        className: "btn bg-success border-success-600 btn-xs",
                        callback: function () {
                           bootbox.dialog({
                              className: "dialogExtraSmall",
                              headerClass: "modal-bg-primary",
                              title: "<i class='ace-icon fa fa-check-circle white'></i> <span class='white'>Conformidad</span>",
                              message: `¿Desea continuar registrando ${nombre}s?`,
                              buttons: {
                                 si: {
                                    label: "<i class='fa fa-check bigger-110'></i>&nbsp; Si",
                                    className: "btn bg-primary border-primary-600 btn-xs",
                                    callback: function () {
                                       $('.tablaMenus').removeClass('hide');
                                       $("#tblDetalle").DataTable().ajax.reload();
                                       recargar();
                                    }
                                 }, no: {
                                    label: "<i class='fa fa-times bigger-110'></i>&nbsp; No",
                                    className: "btn bg-danger border-danger-600 btn-xs",
                                    callback: function () {
                                       recargar();
                                       $('.bootbox-close-button').click();
                                    }
                                 }
                              }
                           });
                        }
                     }
                  }
               });
            } else {
               bootbox.dialog({
                  className: "dialogExtraSmall",
                  title: "<i class='ace-icon fa fa-exclamation-circle white'></i> <span class='white'>Advertencia</span>",
                  headerClass: "modal-bg-warning",
                  message: "Ha ocurrido un error",
                  buttons: {
                     si: {
                        label: "<i class='fa fa-check bigger-110'></i>&nbsp; Aceptar",
                        className: "btn bg-orange border-orange-600 btn-xs",
                        callback: function () {
                           $('.bootbox-close-button').click();
                        }
                     }
                  }
               });
            }
         }
      });
   }

   function eliminacion(json) {
      $.ajax({
         type: 'POST',
         url: "../servlet/MantenimientoMenuServlet?accion=eliminarDetalleMenu",
         dataType: 'JSON',
         data: {
            json: JSON.stringify(json)
         },
         success: function (data, textStatus, jqXHR) {
            if (data.status === true) {
               bootbox.dialog({
                  className: "dialogExtraSmall",
                  title: "<i class='ace-icon fa fa-tags white'></i> <span class='white'>Notificación</span>",
                  headerClass: "modal-bg-success",
                  message: "Menú correctamente eliminado",
                  buttons: {
                     si: {
                        label: "<i class='fa fa-check bigger-110'></i>&nbsp; Aceptar",
                        className: "btn bg-success border-success-600 btn-xs",
                        callback: function () {
                           recargar();
                        }
                     }
                  }
               });
            } else {
               bootbox.dialog({
                  className: "dialogExtraSmall",
                  title: "<i class='ace-icon fa fa-exclamation-circle white'></i> <span class='white'>Advertencia</span>",
                  headerClass: "modal-bg-warning",
                  message: "Ha ocurrido un error",
                  buttons: {
                     si: {
                        label: "<i class='fa fa-check bigger-110'></i>&nbsp; Aceptar",
                        className: "btn bg-orange border-orange-600 btn-xs",
                        callback: function () {
                        }
                     }
                  }
               });
            }
         }
      });
   }
   var jsonObjTitulo = [];
   var jsonObjModulo = [];
   var jsonObjCategoria = [];
   var jsonObjSubCategoria = [];
   function eliminarMenuDetalle() {
      $('#tblMenu tbody').on('click', '.eliminar', function () {
         contaDel = 0;
         var tdata = "";
         tdata = table.row($(this).parents('tr')).data();
         var configuracion = tdata["configuracion"];
         var jerarquia = tdata["jerarquia"];
         var codigo = tdata["codigo"];
         var json = {
            configuracion: configuracion,
            jerarquia: jerarquia,
            proyecto: proyecto,
            codigo: codigo,
            prodetail: detalle
         };
         $.ajax({
            type: 'POST',
            url: "../servlet/MantenimientoMenuServlet?accion=validarEliminarDetalle",
            dataType: 'JSON',
            data: {
               json: JSON.stringify(json)
            },
            success: function (data, textStatus, jqXHR) {
               if (data.status === true) {
                  bootbox.dialog({
                     className: "dialogExtraSmall",
                     headerClass: "modal-bg-primary",
                     title: "<i class='ace-icon fa fa-check-circle white'></i> <span class='white'>Conformidad</span>",
                     message: "¿Está seguro de eliminar este menu?",
                     buttons: {
                        si: {
                           label: "<i class='fa fa-check bigger-110'></i>&nbsp; Si",
                           className: "btn bg-primary border-primary-600 btn-xs",
                           callback: function () {
                              eliminacion(json);
                           }
                        }, no: {
                           label: "<i class='fa fa-times bigger-110'></i>&nbsp; No",
                           className: "btn bg-danger border-danger-600 btn-xs",
                           callback: function () {
                           }
                        }
                     }
                  });
               } else {
                  bootbox.dialog({
                     className: "dialogExtraSmall",
                     headerClass: "modal-bg-primary",
                     title: "<i class='ace-icon fa fa-check-circle white'></i> <span class='white'>Conformidad</span>",
                     message: `Este menú tiene dependecias, si continua estas serán eliminada también. ¿Desea continuar?`,
                     buttons: {
                        si: {
                           label: "<i class='fa fa-check bigger-110'></i>&nbsp; Si",
                           className: "btn bg-primary border-primary-600 btn-xs",
                           callback: function () {
                              mapeo(table.data(), jerarquia, codigo);
                              obj.push(tdata);
                              for (var i in obj) {
                                 var json = {
                                    configuracion: obj[i].configuracion,
                                    jerarquia: obj[i].jerarquia,
                                    proyecto: proyecto,
                                    codigo: obj[i].codigo
                                 };
                                 switch (obj[i].jerarquia) {
                                    case 1:
                                       jsonObjTitulo.push(json);
                                       break;
                                    case 2:
                                       jsonObjModulo.push(json);
                                       break;
                                    case 3:
                                       jsonObjCategoria.push(json);
                                       break;
                                    case 4:
                                       jsonObjSubCategoria.push(json);
                                       break;
                                    default:
                                       break;
                                 }
                              }
                              let jsonGeneral = {
                                 titulos: jsonObjTitulo,
                                 modulos: jsonObjModulo,
                                 categorias: jsonObjCategoria,
                                 subcategorias: jsonObjSubCategoria,
                                 vista: detalle
                              };
                              eliminarMenusAninados(jsonGeneral);
                           }
                        }, no: {
                           label: "<i class='fa fa-times bigger-110'></i>&nbsp; No",
                           className: "btn bg-danger border-danger-600 btn-xs",
                           callback: function () {
                           }
                        }
                     }
                  });
               }
            }
         });
      });
   }
   let obj = [];
   const mapeo = (data, jerarquia, codigo) => {
      for (var i = 0; i < data.length; i++) {
         var padre = data[i].padre;
         var jerar = data[i].jerarquia;
         if (padre === codigo && jerar === jerarquia + 1) {
            obj.unshift(data[i]);
            mapeo(data, data[i].jerarquia, data[i].codigo);
         }
      }
   };
   function eliminarMenusAninados(json) {
      $.ajax({
         type: 'POST',
         url: "../servlet/MantenimientoMenuServlet?accion=eliminarMenusAninado",
         dataType: 'JSON',
         data: {
            json: JSON.stringify(json)
         },
         success: function (data, textStatus, jqXHR) {
            if (data.status === true) {
               bootbox.dialog({
                  className: "dialogExtraSmall",
                  title: "<i class='ace-icon fa fa-tags white'></i> <span class='white'>Notificación</span>",
                  headerClass: "modal-bg-success",
                  message: "Menú correctamente eliminado",
                  buttons: {
                     si: {
                        label: "<i class='fa fa-check bigger-110'></i>&nbsp; Aceptar",
                        className: "btn bg-success border-success-600 btn-xs",
                        callback: function () {
                           recargar();
                        }
                     }
                  }
               });
            } else {
               bootbox.dialog({
                  className: "dialogExtraSmall",
                  title: "<i class='ace-icon fa fa-exclamation-circle white'></i> <span class='white'>Advertencia</span>",
                  headerClass: "modal-bg-warning",
                  message: `${data.message}`,
                  buttons: {
                     si: {
                        label: "<i class='fa fa-check bigger-110'></i>&nbsp; Aceptar",
                        className: "btn bg-orange border-orange-600 btn-xs",
                        callback: function () {
                        }
                     }
                  }
               });
            }
         }
      });
   }

   function cambiarOrdenArriba() {
      $('#tblMenu tbody').on('click', '.arriba', function () {
         var acuArr = 0;
         var tabla = {};
         tabla = table.row($(this).parents('tr')).data();
         var configuracionA = tabla["configuracion"];
         var jerarquia = tabla["jerarquia"];
         var conta = tabla["conta"];
         var real = conta - 1;
         var padre = tabla["padre"];
         var ordenA = tabla["orden"];
         let len = table.data().length;
         let getRow = (row) => table.row(row).data();
         for (let i = 0; i < len; i++) {
            let data = getRow(i);
            if (data.padre === padre && data.conta === real && data.jerarquia === jerarquia) {
               var configuracionB = data.configuracion;
               var ordenB = data.orden;
               var json = {
                  jerarquia: jerarquia,
                  configuracionA: configuracionA,
                  ordenA: ordenA,
                  configuracionB: configuracionB,
                  ordenB: ordenB
               };
               $.ajax({
                  type: 'POST',
                  url: "../servlet/MantenimientoMenuServlet?accion=cambiarOrden",
                  dataType: 'JSON',
                  data: {
                     json: JSON.stringify(json)
                  },
                  success: function (data, textStatus, jqXHR) {
                     if (data.status === true) {
                        refrescar();
                     } else {
                        bootbox.dialog({
                           className: "dialogExtraSmall",
                           title: "<i class='ace-icon fa fa-exclamation-circle white'></i> <span class='white'>Advertencia</span>",
                           headerClass: "modal-bg-warning",
                           message: "Ha ocurrido un error",
                           buttons: {
                              si: {
                                 label: "<i class='fa fa-check bigger-110'></i>&nbsp; Aceptar",
                                 className: "btn bg-orange border-orange-600 btn-xs",
                                 callback: function () {
                                 }
                              }
                           }
                        });
                     }
                  }
               });
            } else {
               acuArr++;
            }
         }
         if (len === acuArr) {
            bootbox.dialog({
               className: "dialogExtraSmall",
               title: "<i class='ace-icon fa fa-exclamation-circle white'></i> <span class='white'>Advertencia</span>",
               headerClass: "modal-bg-warning",
               message: "No puedes subir más",
               buttons: {
                  si: {
                     label: "<i class='fa fa-check bigger-110'></i>&nbsp; Aceptar",
                     className: "btn bg-orange border-orange-600 btn-xs",
                     callback: function () {
                     }
                  }
               }
            });
         }
      });
   }
   function cambiarOrdenAbajo() {
      $('#tblMenu tbody').on('click', '.abajo', function () {
         var tabla = {};
         var acuAba = 0;
         tabla = table.row($(this).parents('tr')).data();
         var configuracionA = tabla["configuracion"];
         var jerarquia = tabla["jerarquia"];
         var conta = tabla["conta"];
         var real = conta + 1;
         var padre = tabla["padre"];
         var ordenA = tabla["orden"];
         let len = table.data().length;
         let getRow = (row) => table.row(row).data();
         for (let i = 0; i < len; i++) {
            let data = getRow(i);
            if (data.padre === padre && data.conta === real && data.jerarquia === jerarquia) {
               var configuracionB = data.configuracion;
               var ordenB = data.orden;
               var json = {
                  jerarquia: jerarquia,
                  configuracionA: configuracionA,
                  ordenA: ordenA,
                  configuracionB: configuracionB,
                  ordenB: ordenB
               };
               $.ajax({
                  type: 'POST',
                  url: "../servlet/MantenimientoMenuServlet?accion=cambiarOrden",
                  dataType: 'JSON',
                  data: {
                     json: JSON.stringify(json)
                  },
                  success: function (data, textStatus, jqXHR) {
                     if (data.status === true) {
                        refrescar();
                     } else {
                        bootbox.dialog({
                           className: "dialogExtraSmall",
                           title: "<i class='ace-icon fa fa-exclamation-circle white'></i> <span class='white'>Advertencia</span>",
                           headerClass: "modal-bg-warning",
                           message: "Ha ocurrido un error",
                           buttons: {
                              si: {
                                 label: "<i class='fa fa-check bigger-110'></i>&nbsp; Aceptar",
                                 className: "btn bg-orange border-orange-600 btn-xs",
                                 callback: function () {
                                 }
                              }
                           }
                        });
                     }
                  }
               });
            } else {
               acuAba++;
            }
         }
         if (len === acuAba) {
            bootbox.dialog({
               className: "dialogExtraSmall",
               title: "<i class='ace-icon fa fa-exclamation-circle white'></i> <span class='white'>Advertencia</span>",
               headerClass: "modal-bg-warning",
               message: "No puedes bajar más",
               buttons: {
                  si: {
                     label: "<i class='fa fa-check bigger-110'></i>&nbsp; Aceptar",
                     className: "btn bg-orange border-orange-600 btn-xs",
                     callback: function () {
                     }
                  }
               }
            });
         }
      });
   }

   function obtenerNombreTabla(jerarquia) {
      var nombre;
      switch (jerarquia) {
         case 1:
            nombre = "Título";
            break;
         case 2:
            nombre = "Módulo";
            break;
         case 3:
            nombre = "Categoría";
            break;
         case 4:
            nombre = "Subcategoría";
            break;
      }
      return nombre;
   }

   function crearMenuExistente(jerarquia, tipo, proyecto, codigo, tipoMenu) {
      var json = {
         codigo: codigo,
         proyecto: proyecto,
         tipo: tipo,
         jerarquia: jerarquia
      };
      var nombre = obtenerNombreTabla(jerarquia);
      $.ajax({
         type: 'POST',
         url: "../servlet/MantenimientoMenuServlet?accion=nuevoMenuExistente",
         dataType: 'JSON',
         data: {
            json: JSON.stringify(json)
         },
         success: function (data, textStatus, jqXHR) {
            if (data.status === true) {
               bootbox.dialog({
                  className: "dialogExtraSmall",
                  title: "<i class='ace-icon fa fa-tags white'></i> <span class='white'>Notificación</span>",
                  headerClass: "modal-bg-success",
                  message: "Menú correctamente agregado",
                  buttons: {
                     si: {
                        label: "<i class='fa fa-check bigger-110'></i>&nbsp; Aceptar",
                        className: "btn bg-success border-success-600 btn-xs",
                        callback: function () {
                           bootbox.dialog({
                              className: "dialogExtraSmall",
                              headerClass: "modal-bg-primary",
                              title: "<i class='ace-icon fa fa-check-circle white'></i> <span class='white'>Conformidad</span>",
                              message: `¿Desea continuar registrando ${nombre}s?`,
                              buttons: {
                                 si: {
                                    label: "<i class='fa fa-check bigger-110'></i>&nbsp; Si",
                                    className: "btn bg-primary border-primary-600 btn-xs",
                                    callback: function () {
                                       $('.tablaMenus').removeClass('hide');
                                       $("#tblDetalle").DataTable().ajax.reload();
                                       recargar();
                                    }
                                 }, no: {
                                    label: "<i class='fa fa-times bigger-110'></i>&nbsp; No",
                                    className: "btn bg-danger border-danger-600 btn-xs",
                                    callback: function () {
                                       recargar();
                                       $('.bootbox-close-button').click();
                                    }
                                 }
                              }
                           });

                        }
                     }
                  }
               });
            } else {
               bootbox.dialog({
                  className: "dialogExtraSmall",
                  title: "<i class='ace-icon fa fa-exclamation-circle white'></i> <span class='white'>Advertencia</span>",
                  headerClass: "modal-bg-warning",
                  message: `${data.message}`,
                  buttons: {
                     si: {
                        label: "<i class='fa fa-check bigger-110'></i>&nbsp; Aceptar",
                        className: "btn bg-orange border-orange-600 btn-xs",
                        callback: function () {
                        }
                     }
                  }
               });
            }
         }
      });
   }

   function asignarDetalle() {
      $('#tblMenu tbody').on('click', '.crear', function () {
         var data = "";
         data = table.row($(this).parents('tr')).data();
         var codigo = data["codigo"];
         var jerarquia = data["jerarquia"];
         var apunta = jerarquia + 1;
         var tabla;
         switch (apunta) {
            case 1:
               tabla = "TÍTULO";
               break;
            case 2:
               tabla = "MÓDULO";
               break;
            case 3:
               tabla = "CATEGORIA";
               break;
            case 4:
               tabla = "SUBCATEGORIA";
               break;
         }
         crearFormTabla(codigo, apunta, tabla);
      });
   }

   function crearFormTabla(codigo, apunta, tabla) {
      var listarMenus = bootbox.dialog({
         title: `<span><i class='ace-icon fa fa-tags'></i> AGREGAR ${tabla.toUpperCase()}</span>`,
         headerClass: "modal-bg-primary",
         className: "tablaMenus",
         size: "large",
         message: `<div class="panel panel-primary">
                              <div class="panel-heading" style="padding: 8px 15px">
                                 <h6 class="panel-title" style="font-size: 15px; font-family: inherit"><i class="fa fa-list"></i>&nbsp; LISTADO DE ${tabla.toUpperCase()}S</h6>
                                 <div class="heading-elements">                                                                
                                     <button id="btnNuevoMenu"  type="button"  class="btn bg-slate-600 border-slate-800  btn-xs"><i class="glyphicon glyphicon-plus"></i>&nbsp; Nuevo ${capitalizeWords(tabla)}</button>
                                 </div>                        
                              </div>
                            <div class="table-responsive">
                                <table class="table table-responsive table-striped table-hover table-bordered" style ="width: 100%" id="tblDetalle">                                                 
                                    <thead>
                                        <tr>
                                            <th class="text-center">NOMBRE</th>
                                            <th class="text-center">ICONO</th>                                                     
                                            <th class="text-center">TIPO</th>                                                     
                                            <th class="text-center">URL</th>                                                     
                                            <th class="text-center">ACCIONES</th>                                                     
                                        </tr>
                                    </thead>
                                </table>
                            </div>
                        </div>`,
         buttons: {
            si: {
               label: "<i class='fa fa-times bigger-110'></i>&nbsp; Cerrar",
               className: "btn bg-danger border-danger-600 btn-xs",
               callback: function () {
                  recargar();
               }
            }
         }
      });
      listarMenus.init(function () {
         nuevoMenuTabla(codigo, apunta);
         datosCreacion.listarMenus(apunta, codigo);
         validarColumnas(apunta);
         $('#tblDetalle').on('draw.dt', function () {
            $('[data-toggle="tooltip"]').tooltip();
         });
         if (detalle === '0') {
            crearMenuExistenteTabla(apunta, 0, proyecto);
         } else {
            crearMenuExistenteTabla(apunta, 1, detalle);
         }
         nuevoMenuEditado(apunta, codigo);
      });
   }

   function crearMenuExistenteTabla(apunta, tipo, proyecto) {
      $('#tblDetalle tbody').on('click', '.crear', function () {
         $('.tablaMenus').addClass('hide');
         var data = "";
         data = $("#tblDetalle").DataTable().row($(this).parents('tr')).data();
         var codigo = data["codigo"];
         var tipoMenu = data["tipo"];
         crearMenuExistente(apunta, tipo, proyecto, codigo, tipoMenu);
      });
   }

   function validarColumnas(jerarquia) {
      var dt = $('#tblDetalle').DataTable();
      switch (jerarquia) {
         case 1:
            dt.column(2).visible(false);
            dt.column(3).visible(false);
            break;
         case 2:
            break;
         case 3:
            dt.column(1).visible(false);
            break;
         case 4:
            dt.column(1).visible(false);
            dt.column(2).visible(false);
            break;
      }
   }

   var datosCreacion = {listarMenus: function (jerarquia, padre) {
         var json = {
            "jerarquia": jerarquia,
            "padre": padre,
            "detalle": detalle,
            "proyecto": proyecto
         };
         $("#tblDetalle").DataTable({
            "language": {
               "lengthMenu": "Mostrar: _MENU_",
               "zeroRecords": "&nbsp;&nbsp;&nbsp; No se encontraron resultados",
               "info": "&nbsp;&nbsp;&nbsp; Mostrando del _START_ al _END_ de un total de _TOTAL_ Proyectos",
               "infoEmpty": "&nbsp;&nbsp;&nbsp; Mostrando 0 de 0 registros",
               "search": "Filtrar:",
               "loadingRecords": "Cargando...",
               "processing": '<span style="width:100%;"><img src="http://www.snacklocal.com/images/ajaxload.gif"></span>',
               "scrollY": false,
               "paginate": {
                  "first": "First",
                  "last": "Last",
                  "next": "Siguiente",
                  "previous": "Anterior"
               }
            },
            "ajax": {
               type: 'POST',
               "url": '../servlet/MantenimientoMenuServlet?accion=listarMenuDetalle',
               data: {
                  json: JSON.stringify(json)
               }
            },
            "bSort": false,
            "bFilter": false,
            "serverSide": true,
            "processing": true,
            "aaSorting": [],
            "ordering": false,
            "bLengthChange": false,
            "bInfo": true,
            "paging": true,
            "iDisplayLength": 10,
            "columnDefs": [
               {targets: 0, orderable: false, width: "20%"},
               {targets: 1, orderable: false, width: "10%", className: "text-center"},
               {targets: 2, orderable: false, width: "10%", className: "text-center"},
               {targets: 3, orderable: false, width: "20%"},
               {targets: 4, orderable: false, width: "7%", className: "text-center"}
            ],
            "columns": [
               {"data": "nombre"},
               {"data": "icono", "render": function (data, type, row) {
                     return `<a role="button" style="color: black;"><i class="fa ${data}" style="font-size: 19px"></i></a>`;
                  }
               },
               {"data": "tipo", "render": function (data, type, row) {
                     let retorno = "";
                     if (data === 1) {
                        retorno = "<span class='label bg-info-600' style='color: white'>ÚNICO</span>";
                     } else if (data === 2) {
                        retorno = '<span class="label bg-slate-600" style="color: white">DESPLEGABLE</span>';
                     }
                     return retorno;
                  }
               },
               {"data": "url"},
               {"data": "existencia", "render": function (data, type, row) {
                     let retorno = "";
                     if (data === 0) {
                        retorno = `<span data-toggle="tooltip" title="Duplicar" style="cursor: pointer">  <i class='editar icon  icon-copy4 text-slate-800' ></i> &nbsp;&nbsp; </span>
                                    <span data-toggle="tooltip" title="Usar" style="cursor: pointer">  <i class='crear icon  icon-checkmark4 text-success-800'></i></span>`;
                     } else {
                        retorno = `<span data-toggle="tooltip" title="Duplicar" style="cursor: pointer">  <i class='editar icon  icon-copy4 text-slate-800'></i> &nbsp;&nbsp; </span>`;
                     }
                     return retorno;
                  }
               }
            ]

         });
      }
   };


