//funcion para  crear un menu cuenta con multiples opciones

function CreateSubmit(i){

    $(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:$(i).serialize(),
      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...");
  }
});

}
/*FIN\ Funcion global para eliminar un registro*/

//funciones para  agregar  nuevos elementos  de menu, eliminar y modificar dichos elementos-------
//----------------------------------------------------------------------------------------------
$(function() {
  $(document).on("click",".addnewmenu",function( event ) { 
      if ($(this).hasClass('fadeOut')) {
          $('.additem').fadeIn(100);
          $(this).removeClass('fadeOut').addClass('fadeIn').html('Cerrar creacion de menu');
      }else{
          $('.additem').fadeOut(100);
          $(this).removeClass('fadeIn').addClass('fadeOut').html('Agregar nuevo menu');
      }
    event.preventDefault();
  });
  var count =0;
  var sub = 0;
  $(document).on("click",".additem",function( event ) {  
    count++;
    var id = ($(this).attr('data-id')) ? $(this).attr('data-id') : count; 
    if ($('.items-form-'+id+count).length > 0) {
      count +=1;
    }  
    var parent = $(this).attr('data-parent');
    var order = $(this).attr('data-order');
    var url = $(this).attr('data-url');
    $('.itemr-'+id).append('<div class="items-form-'+id+count+' menu-js mt-2"><div class="alert alert-info response-'+id+count+'">Agregar nuevo menu</div>'+
      '<a href="#" class="item-menu" data-id="'+id+count+'" >'+
        '<div href="#" class="alert-config configmenus-'+id+count+'">'+
          '<i class="icon-home4 icon-configs'+id+count+'"></i>'+
          ' <span class="rename-'+id+count+'"> NEW item'+
          '</span>'+
        '<span class="config" style="float: right;">'+
          '<i class="open-ico icon-arrow-down32"></i>'+
        '</span>'+
        '</div>'+
      '</a>'+
    '<div class="info-menu option-'+id+count+'">'+
      '<div class="resp-">'+
      '</div>'+
          '<input type="hidden" name="addnewmenu[]" value="1"> '+

          '<input type="hidden" name="jsmenu['+id+count+'][jsparent]" value="'+parent+'"> '+
          '<input type="hidden" name="jsmenu['+id+count+'][jsorder]" value="'+order+'"> '+
          '<div class="form-group">'+
            '<input type="text" name="jsmenu['+id+count+'][jsname]" value="" placeholder="Nombre del menu" data-id="'+id+count+'" onkeyup="rename(this); return false" class="form-control form-cont" required="">'+
          '</div>'+
          '<div class="form-group">'+
            '<input type="text" name="jsmenu['+id+count+'][jsurl]" value=""  placeholder="Url a la que dirige" class="form-control form-cont" required="">'+
          '</div>'+
          '<div class="form-group">'+
            '<input type="text" name="jsmenu['+id+count+'][jsico]" value=""   placeholder="Iconos" data-tipe="'+id+count+'" onkeyup="rename(this); return false" class="form-control  form-cont">'+
          '</div>'+
          '<div class="col-12 text-center">'+
        '</div>'+
      '</div>'+
      '<ul> <li><a href="#" data-nivel="2"  class="addsubitem" data-id="'+id+count+'">+ ADD New sub menu</a><div class="items-'+id+count+'"></div></li></ul>'+
    '<div class="row mt-2"><div class="col-4"><a href="#" class="minus btn btn-danger btn-sm" data-tipe="general" data-id="'+id+count+'"><i class="icon-trash"></i></a></div><div class="col-8 "></li>'+'</div></div></div>');
    event.preventDefault();
  });

  $(document).on("click",".addsubitem",function( event ) {  

      sub++;
      var id = $(this).attr('data-id');
      if ($('.sub-js-'+id+sub).length > 0) {
        sub +=1;
      }  
      var arrays = ''; 
      if($(this).attr("data-nivel")){
        var nivel = $(this).attr("data-nivel");
        if (nivel == '3') {
          var enlaza = 'itemsub-'+id;
          var sectionsub = '';
          var parent = $(this).attr("data-parent");
          var count = $(this).attr("data-count");
          var inputs = parent;
          arrays = '['+count+'][sub]['+sub+']';
        }else if (nivel == '2') {
          var enlaza = 'items-'+id;
          var sectionsub = '<ul> <li><a href="#" data-nivel="3" class="addsubitem" data-parent="'+id+'" data-id="'+id+sub+'" data-count="'+sub+'">+ ADD New sub menu</a><div class="itemsub-'+id+sub+'"></div></li></ul>';
          var inputs = id;
          arrays = '['+sub+']';
        }
      }
      $('.'+enlaza).append('<li class="menu-list sub-js-'+id+sub+'">'+
      '<a href="#" class="item-menu" data-id="'+id+sub+'" >'+
        '<div href="#" class="alert-config configmenus-'+id+sub+'"">'+
          '<i class="icon-home4 icon-configs'+id+sub+'"></i>'+
          ' <span class="rename-'+id+sub+'"> NEW item'+
           
          '</span>'+
        '<span class="config" style="float: right;">'+
          '<i class="open-ico icon-arrow-down32"></i>'+
        '</span>'+
        '</div>'+
      '</a>'+
    '<div class="info-menu option-'+id+sub+'">'+
      '<div class="resp-">'+
      '</div>'+
          '<input type="hidden" name="id[]" value="'+inputs+'">'+
          '<input type="hidden" name="suboptionadd[]" value="1">'+
          '<div class="form-group">'+
            '<input type="text" name="jsmenu['+inputs+'][submenu]'+arrays+'[snombre]" data-id="'+id+sub+'"  placeholder="Nombre del menu" onkeyup="rename(this); return false" value="" class="form-control form-cont" required="">'+
          '</div>'+
          '<div class="form-group">'+
            '<input type="text" name="jsmenu['+inputs+'][submenu]'+arrays+'[surl]" value="" class="form-control form-cont" placeholder="Url a la que dirige" required="">'+
          '</div>'+
          '<div class="form-group">'+
            '<input type="text" name="jsmenu['+inputs+'][submenu]'+arrays+'[sico]"  placeholder="Iconos" data-tipe="'+id+sub+'" onkeyup="rename(this); return false"  value="" class="form-control  form-cont">'+
          '</div>'+
          '<div class="col-12 text-center">'+
        '</div>'+
      '<div class="row"><div class="col-12 "><a href="#" class="minus btn btn-danger btn-sm mt-2" data-tipe="sub-js" data-id="'+id+sub+'"><i class="icon-trash"></i></a></div></div></div>'+
      sectionsub+
    '</li>');
      event.preventDefault();
  });

  $(document).on("click",".updatesubitem",function( event ) {  

      sub++;
      var id = $(this).attr('data-id');
      if ($('.sub-js-'+id+sub).length > 0) {
        sub +=1;
      }  
      var arrays = ''; 
      var options = '';
      if($(this).attr("data-nivel")){
        var nivel = $(this).attr("data-nivel");
        if (nivel == '3') {
          var enlaza = 'fitemsub-'+id;
          var sectionsub = '';
          var inputs = id;
          arrays = '[sub]['+sub+']'; 
          options = 'full';
        }else if (nivel == '2') {
          var enlaza = 'fitems-'+id;
          var sectionsub = '<ul> <li><a href="#" data-nivel="3" class="updatesubitem" data-id="'+id+sub+'">+ ADD New sub menu</a><div class="fitemsub-'+id+sub+'"></div></li></ul>';
          var inputs = id+sub;
        }
      }
      $('.btn-elements'+id).html('Guardar '+sub+'  elementos');
      $('.'+enlaza).append('<li class="menu-list sub-js-'+id+sub+'">'+
      '<a href="#" class="item-menu" data-id="'+id+sub+'" >'+
        '<div href="#" class="alert-config  configmenus-'+id+sub+'">'+
          '<i class="icon-home4 icon-configs'+id+sub+'"></i>'+
          ' <span class="rename-'+id+sub+'"> NEW item'+
           
          '</span>'+
        '<span class="config" style="float: right;">'+
          '<i class="open-ico icon-arrow-down32"></i>'+
        '</span>'+
        '</div>'+
      '</a>'+
    '<div class="info-menu option-'+id+sub+'">'+
      '<div class="resp-">'+
      '</div>'+
          '<input type="hidden" name="sub['+inputs+']'+arrays+'[id]" value="'+id+'">'+
          '<input type="hidden" name="suboptionupdate[]" value="1">'+
          '<input type="hidden" name="sub['+inputs+']'+arrays+'[nivel]" value="'+nivel+'">'+
          '<div class="form-group">'+
            '<input type="text" name="sub['+inputs+']'+arrays+'[snombre]" data-id="'+id+sub+'" placeholder="Nombre del menu" onkeyup="rename(this); return false" value="" class="form-control form-cont" required="">'+
          '</div>'+
          '<div class="form-group">'+
            '<input type="text" name="sub['+inputs+']'+arrays+'[surl]" value=""  placeholder="Url a la que dirige" class="form-control form-cont" required="">'+
          '</div>'+
          '<div class="form-group">'+
            '<input type="text" name="sub['+inputs+']'+arrays+'[sico]" data-tipe="'+id+sub+'" placeholder="Iconos" onkeyup="rename(this); return false" value="" class="form-control  form-cont">'+
          '</div>'+
          '<div class="col-12 text-center">'+
        '</div>'+
      '<div class="row"><div class="col-12 "><a href="#" class="minus btn btn-danger btn-sm mt-2" data-tipe="sub-js" data-id="'+id+sub+'"><i class="icon-trash"></i></a></div></div></div>'+
      sectionsub+
    '</li>');

      event.preventDefault();
  });
  $(document).on("click",".minus",function( event ) {  
    var id = $(this).attr('data-id');
    var tipe = $(this).attr('data-tipe');
    if (tipe == 'general') {
      $('.items-form-'+id).remove();
      count -= 1;
    }else if (tipe == 'sub-js') {
      $('.sub-js-'+id).remove();
      sub -= 1;
    }
    event.preventDefault();
  });
});

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----------------------
//----------------------------------------------------------------------------------------------

