<style type="text/css">
  .layout-tree-toggle {
    width: 18px;
    height: 18px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    border: 0;
    background: transparent;
    padding: 0;
    margin-right: 6px;
    color: #666;
    cursor: move;
  }
</style>
<script type="text/javascript" src="/libraries/jquery-nested-sortable/jquery.mjs.nestedSortable.js"></script>
<script type="text/javascript">
  $(document).ready(function() {
    function saveProductsOrder() {
      var products = $('ol.sortable').nestedSortable('toArray', { startDepthCount: 0 });

      $.ajax({
        type: 'POST',
        cache: false,
        url: '/admin/shop_category/save_products_order/',
        data: {
          category_id: <?= (int)$this->category_id; ?>,
          products: products
        },
        beforeSend: function() {
          $.prompt('Trwa zapisywanie...', { title: 'Proszę czekać' });
        },
        success: function(data) {
          $('.jqibox').remove();
          var response = jQuery.parseJSON(data);

          if (response.status === 'error')
            create_error(response.msg);
        }
      });
    }

    $('ol.sortable').nestedSortable({
      forcePlaceholderSize: true,
      handle: 'div',
      helper: 'clone',
      items: 'li',
      opacity: .6,
      placeholder: 'placeholder',
      revert: 250,
      tabSize: 25,
      tolerance: 'pointer',
      toleranceElement: '> div',
      maxLevels: 1,
      isTree: true,
      expandOnHover: 700,
      stop: function() {
        saveProductsOrder();
      }
    });
  });
</script>
