function loadStates(selectZone, contryId, zone_id) {
  selectZone.load('index.php?route=localisation/geo_zone/zone&token=' + token + '&country_id=' + contryId + '&zone_id=' + zone_id);
}

function initLoadStates(context) {
  var
    selectCountries = context.find('.select-country');

  selectCountries.change(function () {
    var
      selectZone = $(this).closest('.row').find('.select-zone'),
      contryId = $(this).val();

    zone_id = (typeof selectZone.data('zoneid') !== 'undefined') ? selectZone.data('zoneid') : zoneDefault;

    loadStates(selectZone, contryId, zone_id);
  });

  loadStatesInitial(selectCountries);
}

function loadStatesInitial(selectCountries) {
  selectCountries.each(function () {
    $(this).trigger('change');
  });
}

initLoadStates($('body'));

function addGeoZone() {
  var html = '';

  html += '<div class="col-xs-12 zone-row">';
  html += '<div class="content-box background-white padding-large bottom-margin-small shadow-small" id="zone-to-geo-zone-row' + zone_to_geo_zone_row + '">';
  html += '<div class="row">';
  html += '<div class="col-xs">';
  html += '<label class="field field-medium">';
  html += '<span class="field-label">' + entrycountry + '</span>';
  html += '<select class="field-entry select-country" name="zone_to_geo_zone[' + zone_to_geo_zone_row + '][country_id]" id="country' + zone_to_geo_zone_row + '">';
  for (const key in countries) {
    if (countries.hasOwnProperty(key)) {
      const country = countries[key];
      html += '<option value="' + country.country_id + '" ' + (countryDefault == country.country_id ? 'selected' : '') + '>' + country.name + '</option>';
    }
  }
  html += '</select>';
  html += '</label>';
  html += '</div>';
  html += '<div class="col-xs">';
  html += '<label class="field field-medium">';
  html += '<span class="field-label">' + entryZone + '</span>';
  html += '<select class="field-entry select-zone" name="zone_to_geo_zone[' + zone_to_geo_zone_row + '][zone_id]" id="zone' + zone_to_geo_zone_row + '">';
  html += '</select>';
  html += '</label>';
  html += '</div>';
  html += '<div class="col-xs-width-auto">';
  html += '<button type="button" class="btn-default btn-medium-square js-remove-row top-margin-medium btn-error btn-remove-row">';
  html += '<i class="fas fa-times"></i>';
  html += '</button>';
  html += '</div>';
  html += '</div>';
  html += '</div>';
  html += '</div>';

  html = $(html);

  initLoadStates(html);
  initRemoveButton(html);

  $('#zone-to-geo-zone').append(html);

  zone_to_geo_zone_row++;
}

var btnAddZoneRow = document.getElementById('add_zone');

btnAddZoneRow.onclick = addGeoZone;

function initRemoveButton(context) {
  context = context || $('body');

  var btnRemoveRow = context.find('.btn-remove-row');

  btnRemoveRow.click(function (e) {
    e.preventDefault();
    $(this)
      .closest('.zone-row')
      .remove();
  });
}
initRemoveButton();
