document.addEventListener('DOMContentLoaded', function(event) {
  window.blockSelectReadonly();

  window.info = document.querySelector('[data-info]').getAttribute('data-info');
  info = JSON.parse(info);

  language.add(info);
  language.load('sale/customer');

  var btnDesbloqueio = document.querySelector('.js-costumer-unlock');

  if(btnDesbloqueio){
    btnDesbloqueio.addEventListener('click', function unlockCustomer(e){
      e.preventDefault();
      var costumerLogin = this.getAttribute('data-customer-id');

      $.ajax({
        url: 'index.php?route=sale/customer/unlock&token='+ token +'&customer_id='+ costumerLogin,
        type: 'get',
        success: function(json) {
          window.location.reload();
        },error: function(json) {
          console.log(json);
        }
      });

    });
  }

  var btnAdd = document.getElementById('address-add');

  btnAdd.addEventListener('click', addAddress);

  function addAddress(e) {
    e.preventDefault();

    const valueConditionDefault = (address_row == 1) ? "value='" + address_row + "' checked='checked'" : "value=''";

    html = '<div class="col-xs-12 col-md-8">';
    html += ' <div class="content-box vtabs-content js-address">';
    html += '   <div class="row">';
    html += '     <div class="col-xs-12">';
    html += '       <div id="address-' + address_row + '" class="top-padding-medium flex middle-xs">';
    html +=
      '         <span class="count-shipping-address text-x-large text-dark right-padding-medium">Endereço de entrega </span>';
    html += '         <button type="button" class="btn btn-default btn-error btn-small padding-small js-remove-row">';
    html += '           <i class="fas fa-times"></i>';
    html += '         </button>';
    html += '       </div>';
    html += '     </div>';

    html += '<div id="tab-address-' + address_row + '" class="col-xs-12">';
    html += ' <div class="content-box background-white shadow-small padding-large">';
    html += '   <div class="row">';

    html += '      <div class="col-xs-12">';
    html += '        <div class="content-box">';
    html += '          <label class="checkbox checkbox-medium">';
    html +=
      '            <input class="checkbox-entry default-address" type="checkbox" name="address[' +
      address_row +
      '][default]" '+ valueConditionDefault + ' >';
    html +=
      '            <span class="checkbox-text">' + language.get('entry_default') + '</span>';
    html += '          </label>';
    html += '        </div>';
    html += '      </div>';

    html += '<div class="col-xs-12">';
    html += '  <div class="content-box">';
    html += '    <label class="field field-medium">';
    html += '      <span class="field-label required">' + language.get('entry_firstname') + '</span>';
    html +=
      '      <input type="text" class="field-entry"  name="address[' +
      address_row +
      '][firstname]" value="" maxlength="32" required>';
    html += '    </label>';
    html += '  </div>';
    html += '</div>';

    html += '<div class="col-xs-12">';
    html += '  <div class="content-box">';
    html += '    <label class="field field-medium">';
    html += '      <span class="field-label required">' + language.get('entry_lastname') + '</span>';
    html +=
      '      <input type="text" class="field-entry" name="address[' +
      address_row +
      '][lastname]" value="" maxlength="32" required>';
    html += '    </label>';
    html += '  </div>';
    html += '</div>';

    html += '<div class="col-xs-12 col-md-6">';
    html += '  <div class="content-box">';
    html += '    <div class="flex between-xs">';
    html += '      <label class="field field-medium">';
    html += '        <span class="field-label required">' + language.get('entry_postcode') + '';
    html += '          <span class="vertical-middle">';
    html +=
      '            <img class="js-postcode-loading hidden" src="../assets/img/loading-black.svg" width="14" height="14"/>';
    html += '          </span>';
    html +=
      '          <span class="text-primary text-small js-postcode-address cursor-pointer pull-right">Não sei meu cep</span>';
    html += '        </span>';
    html +=
      '        <input type="text" class="field-entry numeric mask-cep js-postcode-search" id="postcode" name="address[' +
      address_row +
      '][postcode]" value="" placeholder="' +
      language.get('text_postcode_placeholder') +
      '" />';
    html += '      </label>';
    html += '   </div>';
    html += '  </div>';
    html += '</div>';

    html += '<div class="col-xs-12 col-md-6">';
    html += '  <div class="content-box">';
    html += '    <label class="field field-medium">';
    html += '      <span class="field-label">Local</span>';
    html +=
      '      <input type="text" class="field-entry" name="address[' +
      address_row +
      '][apelido]" value="" placeholder="' +
      language.get('text_apelido_placeholder') +
      '" />';
    html += '    </label>';
    html += '  </div>';
    html += '</div>';

    html += '</div>';
    html += '<div class="row js-postcode-content hidden">';
    html += '<div class="col-xs-12">';
    html += '  <div class="content-box top-margin-medium">';
    html += '    <label class="field field-medium">';
    html += '      <span class="field-label required">' + language.get('entry_address_1') + '';
    html += '      </span>';
    html +=
      '        <input type="text" class="field-entry address_1" name="address[' +
      address_row +
      '][address_1]" value="" />';
    html +=
      '        <input type="hidden" name="address[' + address_row + '][tipo_logradouro]" class="tipo_logradouro">';
    html += '        <input type="hidden" name="address[' + address_row + '][logradouro]" class="logradouro">';
    html += '        <input type="hidden" name="address[' + address_row + '][city]" class="city">';
    html += '    </label>';
    html += '  </div>';
    html += '</div>';

    html += '<div class="col-xs-6">';
    html += '  <div class="content-box">';
    html += '    <label class="field field-medium">';
    html += '      <span class="field-label required">';
    html += '        Número';
    html += '      </span>';
    html +=
      '        <input type="text" class="field-entry mask-number numero" name="address[' +
      address_row +
      '][numero]" value="" placeholder="' +
      language.get('text_number_placeholder') +
      '" />';
    html += '    </label>';
    html += '  </div>';
    html += '</div>';

    html += '<div class="col-xs-6">';
    html += '  <div class="content-box">';
    html += '    <label class="field field-medium">';
    html += '      <span class="field-label">Complemento</span>';
    html +=
      '      <input type="text" class="field-entry" name="address[' +
      address_row +
      '][complemento]" value=""  placeholder="' +
      language.get('text_complemento_placeholder') +
      '" maxlength="60" />';
    html += '    </label>';
    html += '  </div>';
    html += '</div>';

    html += '<div class="col-xs-12">';
    html += '  <div class="content-box">';
    html += '    <label class="field field-medium">';
    html += '      <span class="field-label required"> ' + language.get('entry_address_2') + '</span>';
    html +=
      '      <input type="text" class="field-entry address_2" name="address[' +
      address_row +
      '][address_2]" value=""/>';
    html += '    </label>';
    html += '  </div>';
    html += '</div>';

    html += '<div class="col-xs-6">';
    html += '  <div class="content-box">';
    html += '    <label class="field field-medium">';
    html += '      <span class="field-label required">' + language.get('entry_zone') + '';
    html += '      </span>';
    html += '        <select name="address[' + address_row + '][zone_id]" class="field-entry zone_id js-city-search" >';
    for (const key in states) {
      if (states.hasOwnProperty(key)) {
        const state = states[key];
        html += '<option value="' + state.zone_id + '" >' + state.name + '</option>';
      }
    }
    html += '        </select>';
    html += '    </label>';
    html += '    <input type="hidden" name="address[' + address_row + '][country_id]" value="' + country_id + '">';
    html += '  </div>';
    html += '</div>';

    html += '<div class="col-xs-6">';
    html += '  <div class="content-box">';
    html += '    <label class="field field-medium">';
    html += '      <span class="field-label required">' + language.get('entry_city') + '';
    html += '      </span>';
    html +=
      '        <select  class="field-entry codigo-municipio codigo_municipio js-codigo-municipio" name="address[' +
      address_row +
      '][codigo_municipio]"></select>';
    html += '        </select>';
    html += '    </label>';
    html += '  </div>';
    html += '</div>';

    html += '   </div>';
    html += ' </div>';
    html += '</div>';

    html += '   </div>';
    html += ' </div>';
    html += '</div>';

    html = $(html)[0];

    removeAddress(html);

    html = $(html)[0];

    $('#address-tab').append(html);

    window.initPostcode(html);
    window.blockSelectReadonly();

    $("select[name='address[" + address_row + "][country_id]']").trigger('change');

    $('#address-' + address_row).trigger('click');

    maskAll();

    address_row++;
  }

  function removeAddress(context) {
    context = context || document;
    var remove = context.querySelectorAll('.js-remove-row');

    for (let i = 0; i < remove.length; i++) {
      remove[i].onclick = function(e) {
        e.preventDefault();

        var pai = this.parentNode.parentNode.parentNode.parentNode.parentNode;
        var isDefault = pai.querySelector('.default-address').checked;

        if (isDefault) {
          alert('Você não pode deletar o endereço padrão!');
          return;
        }

        pai.parentNode.removeChild(pai);
      };
    }
  }
  removeAddress();
});

$(document).ready(function($) {
  function exibeContent() {
    $(
      '.pessoa_' +
        $('#juridica, #fisica')
          .filter(':checked')
          .attr('id')
    )
      .prop('disable', false)
      .show();
    $(
      '.pessoa_' +
        $('#juridica, #fisica')
          .filter(':not(:checked)')
          .attr('id')
    )
      .hide()
      .find('#cpf, #rg, #cnpj, #razao_social, #inscricao_estadual')
      .prop('disable', true)
      .val('');
  }

  exibeContent();

  $('#juridica, #fisica').on('change', function() {
    exibeContent();
  });

  $('.btn-email-ml').on('click', function(event) {
    event.preventDefault();

    $.ajax({
      url: 'index.php?route=module/mercadolivre/mercadolivre/sendEmail&token=' + token + '',
      type: 'get',
      data: 'email_ml=' + $("input[name='email_ml']").val() + '&customer_id=' + costumerId + '',
      dataType: 'json',
      beforeSend: function() {
        $('.btn-email-ml').addClass('btn-loading');
        $('.btn-email-ml').attr('disabled', true);
      },
      complete: function() {
        $('.btn-email-ml').removeClass('btn-loading');
        $('.btn-email-ml').attr('disabled', false);
      },
      success: function(json) {
        $('.error, .success, .warning').remove();
        $('.field-entry-error').removeClass();

        if (json['error']) {
          $.each(json['error'], function(key, value) {
            $("input[name='" + key + "']")
              .addClass('field-entry-error')
              .after('<span class="error">' + value + '</span>');
          });

          if (json['error']['connect']) {
            $('.btn-email-ml').after('<span class="warning">' + json['error']['connect'] + '</span>');
          }

          $('.btn-email-ml')
            .removeClass('btn-primary')
            .addClass('btn-error');
        }

        if (json['success']) {
          $('.btn-email-ml')
            .removeClass('btn-primary btn-error')
            .addClass('btn-success');
          $('.btn-email-ml').after('<span class="success">' + json['success'] + '</span>');
        }
      },
    });
  });

  $('#history .pagination a').live('click', function() {
    $('#history').load(this.href);

    return false;
  });

  $('#history').load('index.php?route=sale/customer/history&token=' + token + '&customer_id=' + costumerId + '');

  $('#button-history').bind('click', function() {
    $.ajax({
      url: 'index.php?route=sale/customer/history&token=' + token + '&customer_id=' + costumerId + '',
      type: 'post',
      dataType: 'html',
      data: 'comment=' + encodeURIComponent($("#tab-history textarea[name='comment']").val()),
      beforeSend: function() {
        $('.success, .warning').remove();
        $('#button-history').attr('disabled', true);
        $('#button-history').addClass('btn-loading');
      },
      complete: function() {
        $('#button-history').attr('disabled', false);
        $('#button-history').removeClass('btn-loading');
        $("#tab-history textarea[name='comment']").val('');
      },
      success: function(html) {
        $('#history').html(html);

        $("#tab-history input[name='comment']").val('');
      },
    });
  });

  $('#transaction .pagination a').live('click', function() {
    $('#transaction').load(this.href);

    return false;
  });

  $('#transaction').load(
    'index.php?route=sale/customer/transaction&token=' + token + '&customer_id=' + costumerId + ''
  );

  $('#button-transaction').bind('click', function() {
    $.ajax({
      url: 'index.php?route=sale/customer/transaction&token=' + token + '&customer_id=' + costumerId + '',
      type: 'post',
      dataType: 'html',
      data:
        'description=' +
        encodeURIComponent($("#tab-transaction input[name='description']").val()) +
        '&amount=' +
        encodeURIComponent($("#tab-transaction input[name='amount']").val()),
      beforeSend: function() {
        $('.success, .warning').remove();
        $('#button-transaction').attr('disabled', true);
        $('#transaction').before(
          '<div class="attention"><img src="../assets/img/loading-black.svg" alt="" /> ' + textWait + '</div>'
        );
      },
      complete: function() {
        $('#button-transaction').attr('disabled', false);
        $('.attention').remove();
      },
      success: function(html) {
        $('#transaction').html(html);

        $("#tab-transaction input[name='amount']").val('');
        $("#tab-transaction input[name='description']").val('');
      },
    });
  });

  $('#reward .pagination a').live('click', function() {
    $('#reward').load(this.href);

    return false;
  });

  $('.js-main-form').on('click', '.js-add-ban-ip', function() {
    var $this = $(this);
    var ip = $this.data('ip');
    console.log(token);
    console.log(ip);

    $.ajax({
      url: 'index.php?route=sale/customer/addbanip&token=' + token + '',
      type: 'post',
      dataType: 'json',
      data: 'ip=' + encodeURIComponent(ip),
      beforeSend: function() {
        $('.success, .warning').remove();

        $('.box').before(
          '<div class="attention"><img src="../assets/img/loading-black.svg" alt="" /> ' + textWait + '</div>'
        );
      },
      complete: function() {},
      success: function(json) {
        console.log(json);

        $('.attention').remove();

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

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

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

          $('.success').fadeIn('slow');

          $this.replaceWith(
            '<button type="button" data-ip="' +
              ip +
              '" class="btn-default btn-outline btn-medium js-remove-ban-ip"><span>' +
              language.get('text_remove_ban_ip') +
              '</span></button>'
          );
        }
      },
    });
  });

  $('.js-main-form').on('click', '.js-remove-ban-ip', function() {
    var $this = $(this);
    var ip = $this.data('ip');
    console.log(token);
    console.log(ip);

    $.ajax({
      url: 'index.php?route=sale/customer/removebanip&token=' + token + '',
      type: 'post',
      dataType: 'json',
      data: 'ip=' + encodeURIComponent(ip),
      beforeSend: function() {
        $('.success, .warning').remove();

        $('.box').before(
          '<div class="attention"><img src="../assets/img/loading-black.svg" alt="" /> ' + textWait + '</div>'
        );
      },
      success: function(json) {
        $('.attention').remove();

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

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

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

          $('.success').fadeIn('slow');

          $this.replaceWith(
            '<button type="button" data-ip="' +
              ip +
              '" class="btn-default btn-outline btn-medium js-add-ban-ip"><span>' +
              language.get('text_add_ban_ip') +
              '</span></button>'
          );
        }
      },
    });
  });

  $('.colorbox').fancybox({
    prevEffect: 'none',
    nextEffect: 'none',
    closeBtn: true,
    nextClick: true,
  });

  $('.htabs a').tabs();
  $('.vtabs a').tabs();
});
