//funcion para  crear un menu cuenta con multiples opciones
  //$("ul.list-menubo").sortable();
$('.dd').nestable({ /* config options */ });
  function toObject(element,order=0)
  {
      var result = [];
      // make sure we're using jquery elements
      var $element = $(element);
      var $children = $element.children('li');
      $children.each(function(index)
      {
          var $this = $(this);
          var item = {};
          item.title = '';

          var $label = $this.find('div.info-menu');
          item.title = $label.find('input[name*="name[]"]').val();
          item.slug = $label.find('input[name*="url[]"]').val();
          item.icon = $label.find('input[name*="ico[]"]').val();


          var $grandchild = $this.children('ol').first();

          item.order = order+1;
          if ($grandchild.length > 0) {
            item.children = toObject($grandchild);
          }
          result.push(item);
      
      });

      return result;
  }



function CreateSubmit(i){
    var o = toObject( $('ol.config-menu'));
    var json = JSON.stringify(o);

    $(i).find('button').attr('disabled','disabled');
    var target = $(i).attr('data-content');
    $.ajaxSetup({
      headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
    $.ajax({
      url:$(i).attr('action'),
      type:'POST',    
      data:{menu:json,action:'fullsave'},
      beforeSend: function( xhr ) {
        $('.'+target).block({ 
            message: '<i class="icon-spinner2 spinner"></i>',
            overlayCSS: {
                backgroundColor: '#fff',
                opacity: 0.8,
                cursor: 'wait',
                'box-shadow': '0 0 0 1px #ddd'
            },
            css: {
                border: 0,
                padding: 0,
                backgroundColor: 'none'
            }
        });    
      }
    })
    .done(function(data) {
      $(i).find('button').removeAttr('disabled');
      $('.'+target).unblock();
      if(jQuery.isEmptyObject(data.error)){
        if (data.animation == 'up') {
          $('html, body').animate({scrollTop:0}, '300');
          $('.response-data').removeClass('alert alert-danger').addClass('alert alert-success').html(data.success).fadeIn(100);
        }else if (data.animation=='reload') {
          swal({
            title: data.success,
            text: "Haz click en el boton para recargar y ver los cambios",
            icon: "success",
            button: {
              text: "Recargar",
              closeModal: false,
            },
          })
          .then((willDelete) => {
            if (willDelete) {
              location.reload();
            }
          });
        }
      }else{
      }
    })
    .fail(function() {
      console.log("error");
    })
    .always(function(data) {

    });

}
//\FIN de createMenu function

// funcion para enviar formularios  en el modulo templates
function UpdateSubmit(i){
  $.ajaxSetup({
    headers: {
          'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
      }
  });
  $.ajax({
    url:$(i).attr('action'),
    type:'PATCH',    
    data:$(i).serialize(),
    beforeSend: function( xhr ) {

    }
  })
  .done(function(data) {
    if(jQuery.isEmptyObject(data.error)){
      if (data.animation == 'up') {
        $('html, body').animate({scrollTop:0}, '300');
        $('.response-data').removeClass('alert alert-danger').addClass('alert alert-success').html(data.success).fadeIn(100);
      }else if (data.animation=='reload') {
        swal({
          title: "Excelente sub menu creado y actualizado",
          text: "Haz click en el boton para recargar y ver los cambios",
          icon: "success",
          button: {
            text: "Recargar",
            closeModal: false,
          },
        })
        .then((willDelete) => {
          if (willDelete) {
            location.reload();
          }
        });
      }
    }else{
      $('.response-data').removeClass('alert alert-success').addClass('alert alert-danger').html(data.error).fadeIn(100);
    }
  })
  .fail(function() {
    console.log("error");
  })
  .always(function(data) {

  });
}
//\FIN de template function

/* Funcion global para eliminar un registro*/
function deleteSubmit(i){
  var id = $(i).attr('data-id');
  swal({
  title: "Estas seguro ?",
  text: "Vas a eliminar el registro seleccionado",
  icon: "warning",
  buttons: true,
  dangerMode: true,
  closeModal: false,
})
.then((willDelete) => {
  if (willDelete) {
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
    $.ajax({
         type:'DELETE',
         url:$(i).attr('data-url'),
         success:function(data){
            if(jQuery.isEmptyObject(data.error)){
              $('.menu-'+id).fadeOut(200).remove();
              $('.itemr-'+id).remove();
              $('.linkadd-'+id).remove();
               swal({
                title: data.success,
                text: "Haz click en el boton para recargar y ver los cambios",
                icon: "success",
                button: {
                  text: "Recargar",
                  closeModal: false,
                },
              })
              .then((willDelete) => {
                if (willDelete) {
                  location.reload();
                }
              });
            }else{
              alert(data);
            }
          },
          error: function(jqXHR, textStatus, errorThrown) 
          { 
            
          }
      });

  } else {
    swal("No hubo actualizaciones...");
  }
});

}
let count =0;
$(document).on("click",".additems",function( event ) { 
   count++;
   var d = new Date();
   var n = d.getTime();
   let id = ($(this).data('id')) ? $(this).data('id') : n;
   if ($('.option-'+id).next('ol').html() !== undefined) {
      $('.option-'+id).next('ol').append(`
         <li class="menu-list menu-${id}${count} menu-js${id}${count} dd-item">
              <div class="dd-handle dd3-handle p-0 m-0">
      
              </div>
                <div href="#" class="dd3-content configmenus-${id}${count}">
                  <i class=" icon-configs"></i>
                  
                  <span class="rename-${id}${count}">
                      Nuevo item !!
                  </span>

                <span class="config" style="float: right;">
                  <a href="#" class="additems" data-id="${id}${count}">Add</a>

                  <a href="#" class="item-menu" data-id="${id}${count}">
                    <i class="open-ico icon-arrow-down32"></i>
                  </a>
                </span>
                </div>
              <div class="info-menu option-${id}${count}">
                    <input type="hidden" name="order[]" value="">
                    <input type="hidden" name="idupdate[]" value="">
                  <div class="form-group">
                      <input type="text" name="name[]"  data-id="${id}${count}" onkeyup="rename(this); return false" class="form-control form-cont" placeholder="Nombre del menu">
                    </div>
                    <div class="form-group">
                      <input type="text" name="url[]" class="form-control form-cont" placeholder="Url a la que dirige">
                    </div>
                    <div class="form-group">
                      <input type="text" name="ico[]"  data-tipe="${id}${count}" onkeyup="rename(this); return false" class="form-control  form-cont" placeholder="Iconos">
                    </div>

                    <div class="row">
                    <div class="col-6"><a href="#" data-id="${id}${count}" class="btn btn-danger btn-sm deleteitems" ><i class="icon-trash"></i></a></div>
                  </div>
              
                </div>
            </li>
        `);
    }else{
      $('.option-'+id).after(`<ol class="content-ul${id} list-menubo dd-list"><li class="menu-list menu-${id}${count} menu-js${id}${count} dd-item">
                <div class="dd-handle dd3-handle p-0 m-0">
        
                </div>
                <div href="#" class="dd3-content configmenus-${id}${count}">
                  <i class=" icon-configs${id}${count}"></i>
                  
                  <span class="rename-${id}${count}">
                    Nuevo item !!
                  </span>


                <span class="config" style="float: right;">
                  <a href="#" class="additems"  data-id="${id}${count}">Add</a>

                  <a href="#" class="item-menu" data-id="${id}${count}">
                    <i class="open-ico icon-arrow-down32"></i>
                  </a>
                </span>
                </div>
              <div class="info-menu option-${id}${count}">
                    <input type="hidden" name="order[]" value="">
                    <input type="hidden" name="idupdate[]" value="">
                  <div class="form-group">
                      <input type="text" name="name[]"  data-id="${id}${count}" onkeyup="rename(this); return false" class="form-control form-cont" placeholder="Nombre del menu">
                    </div>
                    <div class="form-group">
                      <input type="text" name="url[]" class="form-control form-cont" placeholder="Url a la que dirige">
                    </div>
                    <div class="form-group">
                      <input type="text" name="ico[]"  data-tipe="${id}${count}" onkeyup="rename(this); return false" class="form-control  form-cont" placeholder="Iconos">
                    </div>

                    <div class="row">
                    <div class="col-6"><a href="#" data-id="${id}${count}"  class="btn btn-danger btn-sm deleteitems"><i class="icon-trash"></i></a></div>
                  </div>
              
                </div>
            </li>
  </ol>`);
    }
    event.preventDefault();
});
$(document).on("click",".addnewitems",function( event ) { 
   count++;
   var d = new Date();
   var n = d.getTime();
   let id = n;
   if ($('ol.config-menu').length > 0 )  {
      $('ol.config-menu').prepend(`
          <li class="menu-list menu-${id}${count} menu-js${id}${count} dd-item">
                <div class="dd-handle dd3-handle p-0 m-0">
        
                </div>
                <div href="#" class="dd3-content configmenus-${id}${count}">
                  <i class=" icon-configs"></i>
                  
                  <span class="rename-${id}${count}">
                      Nuevo item !!
                  </span>

                <span class="config" style="float: right;">
                  <a href="#" class="additems" data-id="${id}${count}">Add</a>

                  <a href="#" class="item-menu" data-id="${id}${count}">
                    <i class="open-ico icon-arrow-down32"></i>
                  </a>
                </span>
                </div>
              <div class="info-menu option-${id}${count}">
                    <input type="hidden" name="order[]" value="">
                    <input type="hidden" name="idupdate[]" value="">
                  <div class="form-group">
                      <input type="text" name="name[]"  data-id="${id}${count}" onkeyup="rename(this); return false" class="form-control form-cont" placeholder="Nombre del menu">
                    </div>
                    <div class="form-group">
                      <input type="text" name="url[]" class="form-control form-cont" placeholder="Url a la que dirige">
                    </div>
                    <div class="form-group">
                      <input type="text" name="ico[]"  data-tipe="${id}${count}" onkeyup="rename(this); return false" class="form-control  form-cont" placeholder="Iconos">
                    </div>

                    <div class="row">
                    <div class="col-6"><a href="#" data-id="${id}${count}" class="btn btn-danger btn-sm deleteitems" ><i class="icon-trash"></i></a></div>
                  </div>
              
                </div>
          </li>
        `);
    }
    event.preventDefault();
});

$(document).on("click",".deleteitems",function( event ) { 
  $(`.menu-js${$(this).data('id')}`).remove();
  event.preventDefault();
});
/*FIN\ Funcion global para eliminar un registro*/

//funciones para  agregar  nuevos elementos  de menu, eliminar y modificar dichos elementos-------
//----------------------------------------------------------------------------------------------


function rename(i){
  if ($(i).attr('data-tipe')) {
    var tipe = $(i).attr('data-tipe');
    $('.icon-configs'+tipe).remove();
    $('.icons-rename'+tipe).remove();
    $('.configmenus-'+tipe).prepend('<i class="'+$(i).val()+' icons-rename'+tipe+'"></i>')
  }else{
    var id = $(i).attr('data-id');
    var name = $(i).val();
    $('.rename-'+id).html(name);
  }
}
//----------------------------------------------------------------------------------------------
//------------------\Fin de la funciones para el manejo de menus elementos----------------------
//----------------------------------------------------------------------------------------------

