<html xmlns:f="http://typo3.org/ns/TYPO3/CMS/Fluid/ViewHelpers"
      xmlns:map="http://typo3.org/ns/WSR/Myttaddressmap/ViewHelpers"
      data-namespace-typo3-fluid="true">
<f:layout name="Default"/>
<f:section name="main">
    <div class="ajaxSearch">
        <f:comment>
            <f:debug>{_all}</f:debug>
        </f:comment>
        <div id="Lvar" style="display: none;">{Lvar}</div>
        <f:if condition="{settings.googleBrowserApiKey} > ''">
            <f:then>
                <script type="text/javascript" src="https://maps.google.com/maps/api/js?v=3&libraries=places&key={settings.googleBrowserApiKey}"></script>
            </f:then>
            <f:else>
                <div class="typo3-message message-warning">Please insert a Google maps browser API key with the constant editor first!</div>
                <script type="text/javascript" src="https://maps.google.com/maps/api/js?v=3&libraries=places"></script>
            </f:else>
        </f:if>
        <div id="flashMessages">
            <f:flashMessages/>
        </div>
        <f:render partial="FormErrors" arguments="{object:location}"/>
        <f:comment>
            <!--Container für Karte direkt als HTML-CE einbinden-->
            <div id="mapContainer" style="width: 100%;">
                <div id="map">MAP</div>
            </div>
        </f:comment>
        <f:render partial="AjaxSearchForm" arguments="{object:location}"/>
        <div id="ajaxResult"></div>
        <!-- get the map javascript -->
        <f:format.raw>
            <map:mapJS locations="{locations}" city="{location.storename}" settings="{settings}"/>
        </f:format.raw>
        <script>
            var marker;
            var maxPage = Math.ceil({locationsCount}
            /{settings.resultLimit});

            function scrollto(element) {
                $('html, body').animate({scrollTop: ($(element).offset().top)}, 'slow');
            };


            // Googles autocomplete
            var input = document.getElementById('tx_myttaddressmap_city');
            var options = {
                types: ['(regions)'],
                componentRestrictions: {country: ['de', 'at']}
            };
            autocomplete = new google.maps.places.Autocomplete(input, options);

            google.maps.event.addListener(autocomplete, 'place_changed', function () {
                //    show_submit_data(data);
//		geocodeByClient();
            });


            const countryInput = $('#tx_myttaddressmap_country');
            const addressInput = $('#tx_myttaddressmap_city');
            const cordLatInput = $('#tx_myttaddressmap_lat');
            const cordLonInput = $('#tx_myttaddressmap_lon');
            var radiusInput = $('input[type="radio"]:checked');
            const pageInput = $('#tx_myttaddressmap_page');


            $('input[type="radio"]').on('change',(evt) => {
                radiusInput = $(evt.currentTarget);
                geocodeByClient();
            });

            addressInput.on('focus',()=>{ addressInput.val('')});


            function geocodeByClient() {
                var id = <f:format.raw>{id}</f:format.raw>;

                var country = countryInput.val();
                var address = addressInput.val();

                // $("input[name='tx_myttaddressmap_categories']:checked").each(function() {
                //     categories.push($(this).val());
                // });

                var ajaxRequestUrl = "index.php?eID=myttaddressmap&id=" + id,
                    requestParameter = {
                        tx_myttaddressmap_ajax: {
                            controller: 'Ajax',
                            action: 'ajaxEid',
                            address: address,
                            country: country,

                            lat: cordLatInput.val(),
                            lon: cordLonInput.val(),
                            radius: radiusInput.val(),
                            page: pageInput.val(),
                            language: $('#tx_myttaddressmap_language').val(),
                            categories: [],

                            b: location.href
                        }
                    };

                mapBounds = new google.maps.LatLngBounds();

                $.post(ajaxRequestUrl, requestParameter, function (data) {
                    $('#ajaxResult').html(data);

                    // var page = parseInt(pageInput.val());
                    // if(page != -1)	{
                    //     if (page + 1 < maxPage) {
                    //         var n = page + 1;
                    //         pageInput.val(n);
                    //         // $('#tx_myttaddressmap_more').css('display', 'block');
                    //     } else {
                    //         // $('#tx_myttaddressmap_more').css('display', 'none');
                    //     }
                    // }
                    initMarkerEvents();

                    if (marker.length <= 1)
                        map.setZoom(12);

                });

                return false;

            }

            function openInfoWindow(i) {
                infoWindow[i].open(map, marker[i]);
            }

            function closeInfoWindows(elem)
            {
                for(var x in infoWindow)
                {
                    if(x != elem) infoWindow[x].close()
                }
            }

            function initMarkerEvents()
            {
                console.log("gotMarkers");

                // google.maps.event.addListener(marker, 'click', function(elem) {
                //   console.log(elem)
                //   console.log(this)
                //     openInfoWindow()
                //
                // });
                 for(var x in marker)
                 {
                    addEventlistener(x);
                }

            }


            function addEventlistener(elem){
                console.log("added Listener:",elem)

                google.maps.event.addListener(marker[elem],'click',function()
                {
                    console.log("clickd marker",elem)
                    closeInfoWindows(elem)
                })
            }



            $(function () {





                // show all locations when page is loaded
                // if this is activated then a radial search is done
                // otherwise the locations of the country are shown
                addressInput.val('Naila, Deutschland');

                // if you want manually set the search radius comment the following line and
                // set the text field tx_myttaddressmap_radius to another class, not hidden!
                radiusInput.val('20000');

                // $('#tx_myttaddressmap_page').val('-1'); //  shows all locations in the map without result list
                pageInput.val('0'); //  shows all locations in the map with result list


                // if you don't want to show POI's at page onload comment the following line
                geocodeByClient();

                // addressInput.val('');

                // do the ajax-call on click
                $("#ajaxSearchButton").click(function (evt) {
                    $('#tx_myttaddressmap_page').val(0);
                    geocodeByClient();
                    evt.preventDefault();
                });

            });
        </script>
        <script type="text/javascript">
            load();


            // panning for mobile devices


            google.maps.event.addListener(map, "click",function(event) {
            //map.setZoom(9);
            // map.setCenter(event.latLng);
                console.log(1);
                for(var x in infoWindow)
                {
                    infoWindow[x].close()
                }
            });
        </script>
        <!-- the startingpoint marker -->
        <f:comment>
            render partial="Location/Startingpoint" arguments="{startingPoint:startingPoint}"
        </f:comment>
        <script type="text/javascript">
            $(document).ready(function () {
                $('#flashMessages').fadeIn(2000);

            });

            <!-- responsive map -->
            function resizeMap() {
                var mapContainerWidth = $('#mapContainer').width();
                var mapContainerHeight = $('#mapContainer').height();
                $('#map').width(mapContainerWidth - 30);
                $('#map').height(mapContainerWidth / 4 * 3);
                google.maps.event.trigger($('#map'), 'resize');
                //console.log(mapContainerWidth);
                if (marker.length > 0) map.fitBounds(mapBounds);
            }

            $(window).resize(resizeMap);
            resizeMap();
            map.setOptions({
                scrollwheel: false,
                navigationControl: false,
                panControl: false,
                mapTypeControl: false,
                scaleControl: true,
                draggable: true,
                streetViewControl: false,
                zoomControlOptions: {
                    style: google.maps.ZoomControlStyle.LARGE,
                    position: google.maps.ControlPosition.RIGHT_CENTER
                }
            })
        </script>
    </div>
</f:section>
</html>
