
{% if search_latitude is defined and search_latitude is not empty %}
    {% set user_lat = search_latitude %}
    {% set user_lng = search_longitude %}
    {% set zoom = 12 %}
    {% set center_lat = user_lat %}
    {% set center_lng = user_lng %}
{% elseif app.user.latitude is defined and app.user.latitude is not empty %}
    {% set user_lat = app.user.latitude %}
    {% set user_lng = app.user.longitude %}
    {% set zoom = 12 %}
    {% set center_lat = user_lat %}
    {% set center_lng = user_lng %}
{% else %}
    {% set user_lat = false %}
    {% set user_lng = false %}
    {% set zoom = 6 %}
    {% set center_lat = google_maps_default_lat %}
    {% set center_lng = google_maps_default_lng %}
{% endif %}

<script src="https://maps.googleapis.com/maps/api/js?key={{ google_maps_id }}"></script>
<script>    
    var map, centerMap, mapOptions, markerYou;
    var display_marker_you = {{ user_lat is not empty ? 'true' : 'false' }};
    var enable_bounds = {{ user_lat is not empty ? 'true' : 'false' }};
    var markers = [];
    var map_markers = [];
    
    var mapInfoWindow = new google.maps.InfoWindow({
            content : "...",
    });

    function mappee_initialize() {
        var gm_styles = '';

        centerMap = new google.maps.LatLng({{ center_lat }},{{ center_lng }});
        
        mapOptions = {
            zoom: {{ zoom }},
            minZoom: 6,
            maxZoom: 18,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            // The latitude and longitude to center the map (always required)
            center: centerMap,
            disableDefaultUI: true
        };

        map = new google.maps.Map(document.getElementById('gmap-{{ module.id }}'),
            mapOptions);

        //mappee_setMarkers(map, markers);
        jQuery('.module-{{ module.id }} .submit-search').trigger('click');
    }

    function mappee_setMarkers(map, markers) {

        mappee_clearMarkers();
        
        if (enable_bounds) {
            var bounds = new google.maps.LatLngBounds();
            
            bounds.extend(map.getCenter()); // Include position of user
        }
        
        // Add markers to the map
        for (var i = 0; i < markers.length; i++) {
            var marker = markers[i];

            map_markers[i] = new google.maps.Marker({
                position: marker.position,
                map: map,
                icon: marker.icon,
                title: marker.title,
                zIndex: i,
                indexMarker: marker.indexMarker,
                target: marker.target,
                distance: marker.distance
            });
            
            if (enable_bounds) {
                if (i <= 5) { // First 6 items
                    if (map_markers[i].distance >= 0 && map_markers[i].distance < 500) { // Fix : Only distance 0 < 500km
                        //extend the bounds to include each marker's position
                        bounds.extend(map_markers[i].position);
                    }
                }
            }
            
            google.maps.event.addListener(map_markers[i], 'click', function() {                   
                // for (var j = 0; j < markers.length; j++) {
                //     markers[j].marker.setIcon('{{ path('map_pee_marker', { 'type' : 'green' }) }}?id='+(markers[j].marker.indexMarker)); // default icon
                //     markers[j].marker.setZIndex(j);
                // }
                
                // this.setIcon('{{ path('map_pee_marker', { 'type' : 'green-border' }) }}?id='+this.indexMarker+'&tcr=175&tcg=196&tcb=16'); // active icon
                // this.setZIndex(100);
                
                map.panTo(this.position); // Center progressive
                var zoom = map.getZoom();
                
                if (zoom < 10) {
                    map.setZoom(16);    
                }
                
                //mapInfoWindow.setContent(this.html);
                //mapInfoWindow.open(map, this);
                
                //var selector = $('#' + this.target + ' button.select-ope');
                var selector = $('#' + this.target + ' .learn_more a');
                selector.trigger('click');
            });
        }

        if (display_marker_you) {
            markerYou = new google.maps.Marker({
                position: centerMap,
                map: map,
                title: '',
                icon: '{{ path('map_pee_marker', { 'type' : 'dark' }) }}',  // user icon
            });
        }
        
        if (enable_bounds) {    
            bounds.extend(markerYou.position);
        
            //now fit the map to the newly inclusive bounds
            map.fitBounds(bounds, 100);
        }
    }

    function mappee_clearMarkers() {
        for (var i = 0; i < map_markers.length; i++) {
            map_markers[i].setMap(null);
        }  

        map_markers = [];

        if (typeof markerYou !== 'undefined' && markerYou !== null) {
            markerYou.setMap(null);
            markerYou = null;
        }
    }

    {# @NOTE Load by main.js #}
    {# google.maps.event.addDomListener(window, 'load', mappee_initialize); #}

    var mappee_max_pee_applications_per_user = {{ max_pee_applications_per_user }};
    var mappee_max_pee_limit_remaining = {{ max_pee_applications_per_user }};

    var mappee_txt_registration = "{{ 'sentence.module.mappee.list.checkbox.operation.label'|trans({}, 'sentence')|raw }}";
    var mappee_txt_waiting_list = "{{ 'sentence.module.mappee.list.checkbox.operation.waiting_list'|trans({}, 'sentence')|raw }}";
    var mappee_txt_checked = '{{ 'sentence.module.mappee.list.checkbox.operation.checked'|trans({}, 'sentence')|raw }}';
    var mappee_txt_date_identical = '{{ 'sentence.module.mappee.list.checkbox.operation.date_identical'|trans({}, 'sentence')|raw }}';
    var mappee_txt_fenced = '{{ 'sentence.module.mappee.list.checkbox.operation.fenced'|trans({}, 'sentence')|raw }}';
    
    var mappee_txt_error_limit_reached = '{{ 'notice.operationPee.registration.limit.reached'|trans( { '%limit%' : max_pee_applications_per_user }, 'notice')|raw }}';
    var mappee_txt_error_date_identical = '{{ 'notice.operationPee.registration.date_identical'|trans( { '%mail%' : cgenial_mail_pee_registration }, 'notice')|raw }}';
    var mappee_txt_error_fenced = '{{ 'notice.operationPee.registration.fenced'|trans( { '%mail%' : cgenial_mail_pee_registration }, 'notice')|raw }}';

    var mappee_marker_link = '{{ path('map_pee_marker', { 'type' : 'green' }) }}';
    var mappee_marker_link_active = '{{ path('map_pee_marker', { 'type' : 'green-border' }) }}?&tcr=175&tcg=196&tcb=16';

    var mappee_ajax_get_content = '{{ path('module_mappee_get_operations', { 'id' : module.id }) }}';
    var mappee_ajax_content_wrapper = 'mappee-content-{{ module.id }}';

    {% if user_lat is empty %} 
        var user_position;
        jQuery(function(){
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(
                    function(pos) {
                        
                        jQuery('.module-{{ module.id }} .cgenial-loader').fadeIn('fast');
                        
                        user_position = new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude); 
                        
                        if (typeof google === 'object' && typeof google.maps === 'object' && typeof map === 'object') {
                            map.panTo(user_position);
                        }
                        
                        jQuery('#operations-search-form-{{ module.id }} input[name="search_latitude"]').val(pos.coords.latitude);
                        jQuery('#operations-search-form-{{ module.id }} input[name="search_longitude"]').val(pos.coords.longitude);

                        jQuery('.module-mappee .submit-search').trigger('click');
                        //jQuery('.module-{{ module.id }} .cgenial-loader').fadeOut('fast');
                    }, 
                    function() {
                        
                    },
                    {
                        enableHighAccuracy: true,
                        timeout: 1000,
                        maximumAge: 0
                    }
                );
            } 
        });
    {% endif %}
</script>

{% if module.params.title is not empty and module.params.title_tag is not empty %}
    <{{ module.params.title_tag|striptags }} class="module-title text-center">
        {{ module.params.title|striptags }}
    </{{ module.params.title_tag|striptags }}>
{% endif %}

{% for msg in app.session.flashbag.get('mappee_error') %}
<div class="container">
    {% if loop.first %}
        <div class="alert alert-danger">
    {% endif %}

    <div class="notice">{{ msg|stripslashes|nl2br|raw }}</div>

    {% if loop.last %}
        </div>
    {% endif %}
</div>
{% endfor %}

<div class="container">
    <p class="text-center">{{ 'sentence.module.mappee.notice.intro'|trans({}, 'sentence')|raw }}</p>
</div>

{{ include('Front/Render/Module/MapPee/_form.html.twig') }}
<div id="gmap-{{ module.id }}" class="gmap"></div>
<div id="mappee-content-{{ module.id }}" class="mappee-content"></div>
<div id="loader-{{ module.id }}" class="cgenial-loader mappee-loader">
    <img src="{{ asset('front/images/ajax-loader.gif') }}" alt="Chargement en cours..." />
</div>