window.addEventListener('load', function () {
  $('.btn-remove').on('click', function (e) {
    e.preventDefault();
    const itemId = $(this).data('id');
    const cityName = $(this).data('city-name');

    $modal = $('#remove-geofence-area-city-settings-modal');
    $modal.find('h4.modal-title').text(`Removing city settings for: ${cityName}`);
    $modal.find('#removeBtn').data('id', itemId);
  });

  $('#removeBtn').on('click', function (e) {
    e.preventDefault();
    const itemId = $(this).data('id');
    window.__api__.remove(`/geofence_area_city_settings/${itemId}/delete`, itemId);
  });

  $('.btn-search').on('click', function(e) {
    e.preventDefault();
    const form = $('.search-form');
    const data = form.serializeArray().reduce((result, item) => {
      result[item.name] = item.value;
      return result;
    }, {});
    const lat = data.lat;
    const lng = data.lng;
    const radius = data.radius;

    if (!( (lat && lng && radius) || (!lat && !lng && !radius) )) {
      if (!lat) {
        $('input[name="lat"]').parent('.form-group').addClass('has-error');
        $('input[name="lat"]').siblings('.invalid-feedback').text('This field is required.');
      } else {
        $('input[name="lat"]').parent('.form-group').removeClass('has-error');
        $('input[name="lat"]').siblings('.invalid-feedback').text('');
      }
      if (!lng) {
        $('input[name="lng"]').parent('.form-group').addClass('has-error');
        $('input[name="lng"]').siblings('.invalid-feedback').text('This field is required.');
      }else {
        $('input[name="lng"]').parent('.form-group').removeClass('has-error');
        $('input[name="lng"]').siblings('.invalid-feedback').text('');
      }
      if (!radius) {
        $('input[name="radius"]').parent('.form-group').addClass('has-error');
        $('input[name="radius"]').siblings('.invalid-feedback').text('This field is required.');
      } else {
        $('input[name="radius"]').parent('.form-group').removeClass('has-error');
        $('input[name="radius"]').siblings('.invalid-feedback').text('');
      }
      return;
    }

    form.submit();
  })

  $('#search, #export').on('click', function(e) {
    $(this).closest('form')
      .attr('action', $(this).data('action'))
      .submit();
  })
});