/**
 * @file
 * Javascript functionality for component map simple.
 */

(function ($, Drupal, once) {

  'use strict';

  Drupal.componentMapSimple = Drupal.componentMapSimple || {};
  Drupal.behaviors.mapSimple = {
    attach: function (context, settings) {
      Drupal.componentMapSimple.init(context, settings);
    }
  }
  Drupal.componentMapSimple.init = function (context, settings) {
    const $map = $(once('accordionItems', '.component-builder.component-wrapper--type-map_simple', context));
    if ($map.length > 0) {
      const locations = JSON.parse(settings.components.map_simple.location);
      const $options = {
        "zoom": 8,
        "minZoom": 5,
        "maxZoom": 100,
        "scrollwheel": true,
        "mapTypeControl": true,
        "scaleControl": true,
        "streetViewControl": true,
        "zoomControl": true,
        "mapTypeId": "roadmap"
      };
      const map = new google.maps.Map(document.getElementById("map-simple"), $options);

      var bounds = new google.maps.LatLngBounds();
      var infowindow = new google.maps.InfoWindow();
      var i;
      for (i = 0; i < locations.length; i++) {
        var marker = new google.maps.Marker({
          position: new google.maps.LatLng(locations[i][1], locations[i][2]),
          map: map
        });

        bounds.extend(marker.position);

        google.maps.event.addListener(marker, 'click', (function (marker, i) {
          return function () {
            infowindow.setContent(locations[i][0]);
            infowindow.open(map, marker);
          }
        })(marker, i));
      }

      map.fitBounds(bounds);

      var listener = google.maps.event.addListener(map, "idle", function () {
        map.setZoom(10);
        google.maps.event.removeListener(listener);
      });
    }
  }

})(jQuery, Drupal, once);
