<div id="products" data-products>
    <h1 class="h4 main-panel-title">{'discountProduct'|translate}</h1>
    <div class="row bottom-space">
        <div class="col-md-3">
            <input type="text" data-autocomplete-search="pricelevels_products" autocomplete="off" class="form-control input-sm autocomplete-control" name="addProduct" placeholder="{'addProduct'|translate}">
        </div>

        <div class="col-md-3 col-md-offset-6">
            <input type="text" class="form-control input-sm" placeholder="Filtrujte.." data-filter />
        </div>
    </div>

    <div class="panel-group panel-group-lists" id="sets">
        <div class="panel-heading" style="padding-bottom:4px">
            <div class="row">
                <div class="col-md-5">
                    <small><strong>{'product'|translate}</strong></small>
                </div>
                <div class="col-md-1 col-md-offset-1 text-right">
                    <small><strong>{'set'|translate}</strong></small>
                </div>
                <div class="col-md-1 col-md-offset-2 text-right">
                    <small><strong>{'value'|translate}</strong></small>
                </div>
                <div class="col-md-1 col-md-offset-1">
                    <small><strong>{'action'|translate}</strong></small>
                </div>
            </div>
        </div>

        <div data-autocomplete-items="pricelevels_products">

            <script id="multiselectAutocomplete_pricelevels_products" type="text/x-dot-template">
                {literal}
                    {{~it.items :item :index}}
                    <div class="panel panel-body autocomplete-results" data-form-item="{{=item.id}}" style="display:none">
                        <div class="row" style="display: flex;align-items: center">
                            <div class="col-md-1">
                                {{? item.image}}
                                <img src="{{=item.image.src}}" alt="{{=item.image.descr}}">
                                {{?}}
                            </div>

                            <div class="col-md-6">
                                <input type="hidden" class="form-control input-sm" name="data[products][{{? item.index }}-{{=item.index}}{{??}}{{=index + 1}}{{?}}][id_product]"
                                       value="{{=item.id}}">
                                <p class="product-title">
                                    <a href="javascript:nw('product', '{{=item.id}}')" data-product-title="">{{=item.title}}</a><br>
                                    <small>Kód: {{=item.code}} | Skladem: {{=item.in_store}} ks</small></p>
                            </div>

                            <div class="col-md-2">
                                <select name="data[products][{{? item.index }}-{{=item.index}}{{??}}{{=index + 1}}{{?}}][unit]" class="selecter perc-price">
                                    <option value="perc" {{? item.unit && item.unit=='perc'}}selected{{?}}>{/literal}{'discountIn'|translate}{literal} %</option>
                                    <option value="price" {{? item.unit && item.unit=='price'}}selected{{?}}>{/literal}{'discountIn'|translate} {$dbcfg.currency}{literal}</option>
                                    <option value="final_price" {{? item.unit && item.unit=='final_price'}}selected{{?}}>{/literal}{'finalPrice'|translate}{literal}</option>
                                </select>
                            </div>

                            <div class="col-md-3">
                                <div class="{{? item.unit && item.unit!='perc'}}input-group{{?}}">
                                    <input type="text" class="form-control input-sm price" name="data[products][{{? item.index }}-{{=item.index}}{{??}}{{=index + 1}}{{?}}][discount]" value="{{? item.discount}}{{=item.discount}}{{?}}">
                                    <div class="input-group-btn vat-changer" style="display:none;">
                                        {/literal}
                                            <a class="btn btn-primary dropdown-toggle btn-sm" data-toggle="dropdown">
                                                <span>{if $body.data.priceWithVat}{'with'|translate:'vat'}{else}{'without'|translate:'vat'}{/if} {'vat'|translate:'vat'}</span>
                                                <span class="caret"></span>
                                            </a>
                                            <ul class="dropdown-menu">
                                                <li><a data-value="1">{'withTax'|translate:'choice'}</a></li>
                                                <li><a data-value="0">{'withoutTax'|translate:'choice'}</a></li>
                                            </ul>
                                        {literal}

                                        <input type="hidden" name="data[products][{{? item.index }}-{{=item.index}}{{??}}{{=index + 1}}{{?}}][priceWithVat]" class="priceWithVat" value="{/literal}{if $body.data.priceWithVat}1{else}0{/if}{literal}">
                                        <input type="hidden" name="data[products][{{? item.index }}-{{=item.index}}{{??}}{{=index + 1}}{{?}}][priceVat]" class="priceVat" value="{{=item.vat}}">
                                    </div>
                                </div>
                            </div>

                            <div class="col-md-1">
                                <a class="btn-sm btn btn-danger" data-form-delete>
                                    <input class="hidden" type="checkbox" name="data[products][{{? item.index }}-{{=item.index}}{{??}}{{=index + 1}}{{?}}][delete]"/>
                                    <span class="glyphicon glyphicon-remove"></span>
                                </a>
                            </div>
                        </div>
                    </div>
                    {{~}}
                {/literal}
            </script>
        </div>
        <script type="application/javascript">
            $('[data-autocomplete-search="pricelevels_products"]')
                .multiSelectAutoComplete({
                    append: false,
                    formTemplate: '#multiselectAutocomplete_pricelevels_products',
                    formWrapper: 'pricelevels_products',
                    afterSelect: function (e, $item) {
                        var selector = $('[data-autocomplete-items="pricelevels_products"]');
                        styleFormInputs(selector);
                    }
                }).multiSelectAutoComplete('addItems', {$body.price_levels_products|json_encode nofilter});
        </script>
    </div>
</div>
<script type="application/javascript">
    initForm({
        selector:'[data-products]',
        beforeAdd: function(callback) {
            var $item = callback();
            return false;
        }
    });

   $('[data-autocomplete-items="pricelevels_products"]').on('click', '.vat-changer li a', function (e) {
       var row = $(this).closest('.row');
       row.find(".dropdown-toggle span:first").html($(this).text());
       var value = $(this).data("value"),
           oldValue = row.find('.priceWithVat').val();

       row.find('.priceWithVat').val(value);
       if(oldValue != value) {
           var vat = Number(row.find(".priceVat").val()),
               $price = row.find(".price"),
               $value = new BigNumber($price.val());

           switch(value) {
               case 1:
                   $price.val($value.times((100 + vat) / 100).round(4));
                   break;
               case 0:
                   $price.val($value.times(100).dividedBy(100 + vat).round(4));
                   break;
           }
       }
   }).on('change', '.perc-price', function () {
       if ($(this).val() === 'perc') {
           $(this).closest('.row').find('.vat-changer').hide().parent().removeClass('input-group');
       }else if ($(this).val() === 'price' || $(this).val() === 'final_price') {
           $(this).closest('.row').find('.vat-changer').show().parent().addClass('input-group');
       }
   }).find('.perc-price').change();

   jQuery.expr[':'].Contains = function(a,i,m){
      return (a.textContent || a.innerText || "").toUpperCase().indexOf(m[3].toUpperCase())>=0;
   };

   domUtils = {
      activeTimers: {  },
      resetTimer: function (id, timeout, callback)
      {
         var timers = domUtils.activeTimers,
            timer = timers[id];
         if (timer)
            clearTimeout(timer);

         timers[id] = setTimeout(function ()
         {
            delete timers[id];
            callback();
         }, timeout);
      }
   };

   $('[data-filter]').on('keyup change', searchItems);

   var list = $('[data-form-item]');

   function searchItems() {
      var filter = $('[data-filter]').val();
      domUtils.resetTimer('products-search', 200, function() {
         if (filter) {
            list.show();
            list.find("[data-product-title]:not(:Contains("+ filter +"))").parents('[data-form-item]').hide();
         } else {
            list.show();
         }

         $('#sets').trigger('changed');
      });
   }
</script>
