/**
 * @file
 * Javascript for service location presets menu.
 */

(function ($, Drupal, drupalSettings) {
  'use strict';

  Drupal.behaviors.uw_ct_service_location_autofill = {
    attach: function (context, drupalSettings) {
      var location_select = $('select#edit-location-presets-select');
      location_select.change(function () {
        // Get chosen location.
        var location = drupalSettings.uwCtService[location_select.val()];
        // Do nothing when re-selecting the initial value.
        if (!location) {
          return;
        }

        // Set coordinates and re-center map.
        $('input#edit-field-uw-service-location-coord-0-value-lat').val(location.latitude);
        $('input#edit-field-uw-service-location-coord-0-value-lon').val(location.longitude).change();

        // Set the country if it has changed.
        var select_country = $('#edit-field-uw-service-location-0 select.country');
        if (select_country.val() !== location.country_code) {
          select_country.val(location.country_code).change();
        }

        // Update the address fields.
        var address_fields = {
          location_name_and_code: 'input.organization',
          address: 'input.address-line1',
          city: 'input.locality',
          postal_code: 'input.postal-code',
          province_code: 'select.administrative-area',
        };
        // Give time for the progress throbber to appear. Fields are updated by
        // Ajax following any change in the country.
        setTimeout(function () {
          var counter = 0;
          // Repeat until the progress throbber disappears and the address field
          // appears. Update the address and clearInterval() to stop repeating.
          var checkExist = setInterval(function () {
            // Stop repeating after 10 seconds if Ajax gets stuck.
            counter++;
            if (counter > 50) {
              clearInterval(checkExist);
            }
            else if (!$('.ajax-progress-throbber').length && $('#edit-field-uw-service-location-0 input.organization').length) {
              clearInterval(checkExist);
              for (var key in address_fields) {
                var element = $('#edit-field-uw-service-location-0 ' + address_fields[key]);
                if (element.val() !== location[key]) {
                  element.val(location[key]).change();
                }
              }
            }
          }, 200);
        }, 500);
      });
    }
  }

})(jQuery, Drupal, drupalSettings);