$(document).ready(function() {


  var token = $('body').data('token');

  $('select[name="to"]').bind('change', function(event) {
    $('#mail .to').hide();

    if(event.target.value == 'customer_group' || event.target.value == 'customer_all' || event.target.value == 'newsletter'){
      document.querySelector('#store_id').children[0].innerHTML = 'Marketing'
    }else{
      document.querySelector('#store_id').children[0].innerHTML = 'Padrão'
    }

    $(
      '#mail #to-' +
        $(this)
          .attr('value')
          .replace('_', '-')
    ).show();
  });

  $('select[name="to"]').trigger('change');

  $.widget('custom.catcomplete', $.ui.autocomplete, {
    _renderMenu: function(ul, items) {
      var self = this,
        currentCategory = '';

      $.each(items, function(index, item) {
        if (item.category != currentCategory) {
          ul.append('<li class="ui-autocomplete-category">' + item.category + '</li>');

          currentCategory = item.category;
        }

        self._renderItem(ul, item);
      });
    },
  });

  $('input[name="customers"], input[name="products"]').on('focus', function() {
    var type = $(this)
        .attr('name')
        .replace(/[s]$/, ''),
      $this = $(this),
      route = type == 'customer' ? 'sale/' + type : 'catalog/' + type,
      url = 'index.php?route=' + route + '/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 {
                  category: item.customer_group,
                  label: item.name,
                  value: item[type + '_id'],
                };
              })
            );
          },
        });
      },
      select: function(event, ui) {
        var $scrollbox = $this.closest('.field').next('.scrollbox');
        var $item = $scrollbox.find('#' + type + ui.item.value).remove();

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

        $scrollbox.append(
          '<div id="' +
            type +
            ui.item.value +
            '" class="scrollbox-item flex between-xs middle-xs vertical-padding-small"><span class="text-small text-dark text-ellipsis" style="width:80%;">' +
            ui.item.label +
            '</span><i class="fas fa-trash text-small right-margin-small text-gray padding-x-small"></i><input type="hidden" name="'+
            type +'[]" value="' +
            ui.item.value +
            '" /></div>'
        );
        return false;
      },
      focus: function(event, ui) {
        return false;
      },
    });
  });

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

  $('.js-btn-csv').on('click', function(event) {
    event.preventDefault();
    $.ajax({
      url: 'index.php?route=sale/contact/gerarCsv&token=' + token,
      type: 'get',
      data: $('select, input, textarea'),
      dataType: 'json',
      beforeSend: function() {
        $('.js-btn-csv').addClass('btn-loading');
        $('.js-btn-csv').attr('disabled', true);
      },
      complete: function() {
        $('.js-btn-csv').removeClass('btn-loading');
        $('.js-btn-csv').attr('disabled', false);
      },
      success: function(json) {
        $('.warning, .success').remove();

        if (json['error']) {
          $('.box').before('<div class="warning full-width">' + json['error'] + '</div>');
        }

        if (json['success']) {
          window.location = 'index.php?route=sale/contact/downloadCsv&token=' + token;
          $('.box').before('<div class="success full-width">' + json['success'] + '</div>');
        }

        setInterval(function() {
          $('.warning, .success').fadeOut();
        }, 5000);
      },
    });
  });

  window.CKEDITOR.replace('message', {
    filebrowserBrowseUrl: 'index.php?route=common/filemanager&token=' + token,
    filebrowserImageBrowseUrl: 'index.php?route=common/filemanager&token=' + token,
    filebrowserFlashBrowseUrl: 'index.php?route=common/filemanager&token=' + token,
    filebrowserUploadUrl: 'index.php?route=common/filemanager&token=' + token,
    filebrowserImageUploadUrl: 'index.php?route=common/filemanager/sendFilesCkeditor&token=' + token,
    filebrowserFlashUploadUrl: 'index.php?route=common/filemanager&token=' + token,
  });

  $('.js-variables').each(function () {
    $(this).on('click', function () {
      var element = CKEDITOR.dom.element.createFromHtml('<span contenteditable="false">{{ ' + $(this).data('variableName') + ' }}</span>' );
      CKEDITOR.instances.message.insertElement(element);
    });
  });

  $('#button-send').click(function() {
    $('textarea[name="message"]').val(CKEDITOR.instances.message.getData());
    send();
  });

  function send(json = 'index.php?route=sale/contact/send&token=' + token,){

    $.ajax({
      url: json,
      type: 'post',
      data: $('select, input, textarea'),
      dataType: 'json',
      beforeSend: function() {
        $('#button-send').attr('disabled', true);
        $('#button-send').addClass('btn-loading');
      },
      complete: function() {
        $('#button-send').attr('disabled', false);
        $('#button-send').removeClass('btn-loading');
        $('.wait').remove();
      },
      success: function(json) {
        $('.success, .warning, .error').remove();

        if (json['error']) {
          if (json['error']['warning']) {
            $('.box').before('<div class="warning full-width" style="display: none;">' + json['error']['warning'] + '</div>');

            $('.warning').fadeIn('slow');
          }

          if (json['error']['subject']) {
            $("input[name='subject']").after('<span class="error">' + json['error']['subject'] + '</span>');
          }

          if (json['error']['message']) {
            $("textarea[name='message']")
              .parent()
              .append('<span class="error">' + json['error']['message'] + '</span>');
          }
        }

        if (json['next']) {
          if (json['success']) {
            $('.box').before('<div class="success full-width">' + json['success'] + '</div>');
            send(json['next']);
          }
        } else {
          if (json['success']) {
            $('.box').before('<div class="success full-width" style="display: none;">' + json['success'] + '</div>');
            $('.success').fadeIn('slow');
          }
        }
      },
    })
  }
});
