<link type="text/css" rel="stylesheet" href="/libraries/selectize/css/selectize.css">
<link type="text/css" rel="stylesheet" href="/libraries/selectize/css/selectize.default.css">
<script type="text/javascript" src="/libraries/selectize/js/standalone/selectize.js"></script>
<script type="text/javascript">
  (function($) {
    if (!$) return;

    $(function() {
      $('#set_products_id').selectize({
        maxItems: 999,
        plugins: ['remove_button']
      });

      var $form = $('#shop-product-set-edit');
      if ($form.length) {
        var origSerialize = $form.data('origSerialize');
        if (!origSerialize) {
          $form.on('submit', function(e) {
            e.preventDefault();
          });
        }

        $form.find('[data-action="save"]').off('click.productSetSave').on('click.productSetSave', function(e) {
          e.preventDefault();

          var formData = $form.serializeArray();

          var selectedProducts = $('#set_products_id').val();
          if (selectedProducts && selectedProducts.length) {
            for (var i = 0; i < selectedProducts.length; i++) {
              formData.push({ name: 'set_products_id[]', value: selectedProducts[i] });
            }
          }

          var actionUrl = $(this).data('url') || $form.attr('action');
          var backUrl = $(this).data('back-url') || '/admin/shop_product_sets/list/';

          $.ajax({
            url: actionUrl,
            type: 'POST',
            data: formData,
            dataType: 'json',
            success: function(response) {
              if (response.success || response.status === 'ok') {
                var msg = response.message || response.msg || 'Zapisano.';
                $('<div class="alert alert-success">' + msg + '</div>').insertBefore($form).delay(2000).fadeOut();

                if (response.id && !$form.find('input[name="id"]').val()) {
                  $form.find('input[name="id"]').val(response.id);
                }
              } else {
                var errorMsg = (response.errors && response.errors.general) || response.msg || 'Wystapil blad.';
                $('<div class="alert alert-danger">' + errorMsg + '</div>').insertBefore($form).delay(3000).fadeOut();
              }
            },
            error: function() {
              $('<div class="alert alert-danger">Blad komunikacji z serwerem.</div>').insertBefore($form).delay(3000).fadeOut();
            }
          });
        });
      }
    });
  })(window.jQuery);
</script>
