$(document).ready(function () {
  var token = $('body').data('token');
  
  inputQuantityVisibility();
  
  $('input[name="product"], input[name="product_grid"], input[name="category"]').on('focus', function () {
    var
      type = $(this).attr('name').replace('_grid', ''),
      $this = $(this),
      grid = $this.data('grid'),
      url = (grid) ? 'index.php?route=catalog/product/autocompletegrid' : 'index.php?route=catalog/' + type + '/autocomplete';


    $this.autocomplete({
      delay: 500,
      source: function (request, response) {
        $.ajax({
          url: url + '&token=' + token + '&filter_name=' + encodeURIComponent(request.term),
          dataType: 'json',
          success: function (json) {
            response($.map(json, function (item) {
              return {
                label: item.name,
                value: item[type + '_id'],
              }
            }));
          }
        });
      },
      select: function (event, ui) {
        var $scrollbox = $this.closest('.field').next('.scrollbox');
        var $item = $scrollbox.find('#coupon-' + type + ui.item.value);

        if ($item && $item.length) return false;

        $scrollbox.append('<div id="coupon-' + type + ui.item.value + '" class="scrollbox-item flex between-xs"><span class="text-small text-gray">' + ui.item.label + '</span><i class="fas fa-trash-alt text-small right-margin-small text-error"></i><input type="hidden" name="coupon_' + $this.attr('name') + '[]" value="' + ui.item.value + '" /></div>');
        
        inputQuantityVisibility();
        
        return false;
      },
      focus: function (event, ui) {
        return false;
      }
    });

  });

  $('.fa-trash-alt').live('click', function () {
    $(this).parent().remove();
    inputQuantityVisibility();
  });

  $("#date-start, #date-end").datepicker({
    changeMonth: true,
    changeYear: true,

    /* COMECO - Tradução DataPicker - por Henrique R. Pohl */

    closeText: 'Fechar',
    prevText: '&#x3c;Anterior',
    nextText: 'Pr&oacute;ximo&#x3e;',
    currentText: 'Hoje',
    monthNames: ['Janeiro', 'Fevereiro', 'Mar&ccedil;o', 'Abril', 'Maio', 'Junho',
      'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro'],
    monthNamesShort: ['Jan', 'Fev', 'Mar', 'Abr', 'Mai', 'Jun',
      'Jul', 'Ago', 'Set', 'Out', 'Nov', 'Dez'],
    dayNames: ['Domingo', 'Segunda-feira', 'Ter&ccedil;a-feira', 'Quarta-feira',
      'Quinta-feira', 'Sexta-feira', 'Sabado'],
    dayNamesShort: ['Dom', 'Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'Sab'],
    dayNamesMin: ['Dom', 'Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'Sab'],
    weekHeader: 'Sm',
    firstDay: 0,
    isRTL: false,
    showMonthAfterYear: false,
    yearSuffix: '',

    /* FIM - Tradução DataPicker - por Henrique R. Pohl */

    dateFormat: "dd/mm/yy",
    minDate: 0,
    onSelect: function (date) {
      $('#validade').datepicker({
        changeMonth: true,
        changeYear: true,

        /* COMECO - Tradução DataPicker - por Henrique R. Pohl */

        closeText: 'Fechar',
        prevText: '&#x3c;Anterior',
        nextText: 'Pr&oacute;ximo&#x3e;',
        currentText: 'Hoje',
        monthNames: ['Janeiro', 'Fevereiro', 'Mar&ccedil;o', 'Abril', 'Maio', 'Junho',
          'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro'],
        monthNamesShort: ['Jan', 'Fev', 'Mar', 'Abr', 'Mai', 'Jun',
          'Jul', 'Ago', 'Set', 'Out', 'Nov', 'Dez'],
        dayNames: ['Domingo', 'Segunda-feira', 'Ter&ccedil;a-feira', 'Quarta-feira',
          'Quinta-feira', 'Sexta-feira', 'Sabado'],
        dayNamesShort: ['Dom', 'Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'Sab'],
        dayNamesMin: ['Dom', 'Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'Sab'],
        weekHeader: 'Sm',
        firstDay: 0,
        isRTL: false,
        showMonthAfterYear: false,
        yearSuffix: '',

        /* FIM - Tradução DataPicker - por Henrique R. Pohl */

        dateFormat: "dd/mm/yy"
      });

    }
  });

  $('#history').load('index.php?route=sale/coupon/history&token=' + token + '&coupon_id=' + coupon + '&pageHistory=' + pageHistory);

  typeDiscount();
});

let quantityProductValue = ''

function inputQuantityVisibility(){
  let quantity_product = document.querySelector('#quantity_product');
  let quantity_grade = document.querySelector('#quantity_grade');
  let quantity_department = document.querySelector('#quantity_department');

  if(document.querySelector('#coupon-product').children.length == 0){
    quantity_product.classList.add('hidden');
    quantity_product.querySelector('input').value = '';
  }else{
    quantity_product.classList.remove('hidden')
  }

  if(document.querySelector('#coupon-grid-produt').children.length == 0){
    quantity_grade.classList.add('hidden');
    quantity_grade.querySelector('input').value = '';
  }else{
    quantity_grade.classList.remove('hidden')
  }

  if(document.querySelector('#coupon-department').children.length == 0){
    quantity_department.classList.add('hidden');
    quantity_department.querySelector('input').value = '';
  }else{
    quantity_department.classList.remove('hidden')
  }
}

function showInfo(event){
  const tooltipProductInfo = document.querySelector('#tooltip_product_info');
  const tooltipGradeInfo = document.querySelector('#tooltip_grade_info');
  const tooltipDepartmentInfo = document.querySelector('#tooltip_department_info');
  
  switch(event.target.id){
    case 'quantity_product_info': 
      tooltipProductInfo.classList.remove('hidden')  
      break;
    case 'quantity_grade_info':
      tooltipGradeInfo.classList.remove('hidden')
      break;
    case 'quantity_department_info': 
      tooltipDepartmentInfo.classList.remove('hidden')
      break
  }
}

function hiddenInfo(event){
  const tooltipProductInfo = document.querySelector('#tooltip_product_info');
  const tooltipGradeInfo = document.querySelector('#tooltip_grade_info');
  const tooltipDepartmentInfo = document.querySelector('#tooltip_department_info');

  switch(event.target.id){
    case 'quantity_product_info': 
      tooltipProductInfo.classList.add('hidden')  
      break;
    case 'quantity_grade_info':
      tooltipGradeInfo.classList.add('hidden')
      break;
    case 'quantity_department_info': 
      tooltipDepartmentInfo.classList.add('hidden')
      break
  }
}

function typeDiscount() {
  var typeDiscount = document.querySelector('.js-type-discount');
  typeDiscount.addEventListener('change', function() {
    var textDiscount = document.querySelector('.js-discount');
    if (typeDiscount.value === 'P') {
      textDiscount.textContent = 'Desconto: (%)';
    } else {
      textDiscount.textContent = 'Desconto: (R$)';
    }
  });
}

function onlyNumer(input) {
  input.value = input.value.replace(/\D/g, '')
}