$(window).on('load', function() {
  $('.qommon-map').each(function() {
     var $map_widget = $(this);
     var map_options = Object();
     var initial_zoom = parseInt($map_widget.data('initial_zoom'));
     if (! isNaN(initial_zoom)) {
       map_options.zoom = initial_zoom;
     } else {
       map_options.zoom = 13;
     }
     var max_zoom = parseInt($map_widget.data('max_zoom'));
     if (! isNaN(max_zoom)) {
       map_options.maxZoom = max_zoom;
     } else {
       map_options.maxZoom = 19;
     }
     var min_zoom = parseInt($map_widget.data('min_zoom'));
     if (! isNaN(min_zoom)) map_options.minZoom = min_zoom;
     map_options.zoomControl = false;
     var map_tile_urltemplate = $map_widget.data('tile-urltemplate');
     var map_attribution = $map_widget.data('map-attribution');
     if ($map_widget.data('max-bounds-lat1')) {
       map_options.maxBounds = L.latLngBounds(
               L.latLng($map_widget.data('max-bounds-lat1'), $map_widget.data('max-bounds-lng1')),
               L.latLng($map_widget.data('max-bounds-lat2'), $map_widget.data('max-bounds-lng2')));
     }
     if ($map_widget.data('readonly') && $map_widget.attr('id') != 'backoffice-map') {
       map_options.scrollWheelZoom = 'center';
       map_options.doubleClickZoom = 'center';
       map_options.maxBounds = null;
     }
     var map = L.map($(this).attr('id'), map_options);
     var map_controls_position = $('body').data('map-controls-position') || 'topleft';
     new L.Control.Zoom({
         position: map_controls_position,
         zoomInTitle: WCS_I18N.map_zoom_in,
         zoomOutTitle: WCS_I18N.map_zoom_out
     }).addTo(map);
     $map_widget[0].leaflet_map = map;
     var gps_control = new L.Control.Gps({
             position: map_controls_position,
             tooltipTitle: WCS_I18N.map_display_position
     });
     var hidden = $(this).prev();
     map.marker = null;
     var latlng;
     if ($map_widget.data('init-lat')) {
       latlng = [$map_widget.data('init-lat'), $map_widget.data('init-lng')]
       map.marker = L.marker(latlng);
       map.marker.addTo(map);
     } else if ($map_widget.data('def-lat')) {
       latlng = [$map_widget.data('def-lat'), $map_widget.data('def-lng')]
     } else {
       latlng = [50.84, 4.36];
     }
     map.setView(latlng, map_options.zoom);
     L.tileLayer(map_tile_urltemplate, {
             attribution: map_attribution,
             maxZoom: map_options.maxZoom
     }).addTo(map);
     if ($map_widget.data('readonly') && $map_widget.attr('id') != 'backoffice-map') {
       map.dragging.disable();
       map.boxZoom.disable();
       map.keyboard.disable();
     } else {
       map.addControl(gps_control);
     }
     if (! $map_widget.data('readonly')) {
       map.on('click', function(e) {
         $map_widget.trigger('set-geolocation', e.latlng);
       });
     }
     $map_widget.on('set-geolocation', function(e, coords, options) {
       if (map.marker === null) {
         map.marker = L.marker([0, 0]);
         map.marker.addTo(map);
       }
       map.marker.setLatLng(coords);
       hidden.val(coords.lat + ';' + coords.lng);
       if (!(typeof(options) != 'undefined' && options.trigger === false)) {
         hidden.trigger('change');
       }
       $(document).trigger('wcs:set-last-auto-save');
     });
     $map_widget.on('qommon:invalidate', function() {
       map.invalidateSize();
     });
     var is_preview = $('.form-preview').length == 1;
     position_prefil = $map_widget.parent().parent().data('geolocation') == 'position';
     if (! ($map_widget.data('readonly') || is_preview) && ($map_widget.data('init-with-geoloc') || position_prefil)) {
       $map_widget.addClass('waiting-for-geolocation');
       $map_widget.removeClass('geolocation-error');
       map.on('locationfound', function(e) {
         $map_widget.removeClass('waiting-for-geolocation');
         $map_widget.parent().parent().find('label').removeClass('activity');
         if (map_options.maxBounds && ! map_options.maxBounds.contains(e.latlng)) {
           /* ouf of bounds, keep map centered on default position */
           return;
         }
         if (map.marker === null) {
           hidden.val(e.latlng.lat + ';' + e.latlng.lng);
           hidden.trigger('change');
           map.setView(e.latlng, map_options.zoom);
           if (position_prefil) {
             map.setView(e.latlng, 16);
             $map_widget.trigger('set-geolocation', e.latlng);
           }
         }
       });
       map.on('locationerror', function(e) {
         $map_widget.removeClass('waiting-for-geolocation');
         $map_widget.addClass('geolocation-error');
         var message = WCS_I18N.geoloc_unknown_error;
         if (e.code == 1) message = WCS_I18N.geoloc_permission_denied;
         else if (e.code == 2) message = WCS_I18N.geoloc_position_unavailable;
         else if (e.code == 3) message = WCS_I18N.geoloc_timeout;
         $map_widget.parent().parent().find('label').removeClass('activity');
         $map_widget.parent().parent().find('.geoloc-error').remove();
         $map_widget.parent().parent().find('label').after('<span class="geoloc-error">' + message + '</span>');
       });
       gps_control.on('gps:located', function(e) {
         map.panTo(e.latlng);
         map.stopLocate();
         $map_widget.trigger('set-geolocation', e.latlng);
       });
       $map_widget.parent().parent().find('label').addClass('activity')
       gps_control.addLayer();
       map.locate({timeout: 10000, maximumAge: 300000, enableHighAccuracy: false});
     }

    $(document).on('backoffice-filter-change', function(event, listing_settings) {
      if ($('.leaflet-popup').length > 0 && listing_settings.auto == true) {
        /* disable autorefresh when a popup is open */
        return;
      }
      $('.qommon-map').each(function() {
         var base_url = $(this).data('geojson-url').split('?')[0];
         map.eachLayer(function(layer) {
           if (layer.feature && layer.feature.type == 'Feature') {
             map.removeLayer(layer);
           }
         });
         $.getJSON(base_url + '?' + listing_settings.qs, function(data) {
           var geo_json = L.geoJson(data, {
             onEachFeature: function(feature, layer) {
               if (feature.properties.display_fields.length > 0) {
                 var popup = '';
                 $.each(feature.properties.display_fields, function(index, field) {
                   var $popup_field = $('<div><p class="popup-field"><span class="field-label"></span><span class="field-value"></span></p></div>');
                   $popup_field.find('.field-label').text(field.label);
                   if (field.html_value) {
                     $popup_field.find('.field-value').html(field.html_value);
                   } else {
                     $popup_field.find('.field-value').text(field.value);
                   }
                   popup += $popup_field.html();
                 });
               } else {
                   var popup = '<p class="popup-field formdata-name">' + feature.properties.name + '</p>';
                   popup += '<p class="popup-field status-name">' + feature.properties.status_name + '</p>';
               }
               popup += '<p class="view-link"><a href="' + feature.properties.url + '">' + feature.properties.view_label + '</a></p>';
               layer.bindPopup(popup);
             },
             pointToLayer: function (feature, latlng) {
                 var markerStyles = "background-color: "+feature.properties.status_colour+";";
                 marker = L.divIcon({iconAnchor: [0, 24],
                                     popupAnchor: [5, -36],
                                     html: '<span style="' + markerStyles + '" />'});
                 m = L.marker(latlng, {icon: marker});
                 return m;
             }
           });
           map.fitBounds(geo_json.getBounds());
           geo_json.addTo(map);
         });
      });
    });
    if ($(this).data('geojson-url')) {
        $(document).trigger('backoffice-filter-change', {qs: $('form#listing-settings').serialize()});
    }
  });
  $(document).trigger('wcs:maps-ready');
});
