{get_sellers assign='dealers'}
{$body['dealers'] = $dealers}
<div class="row seller-map-wrapper">
   <div class="col-xl-12 col-xs-12">
      <div class="sellers-map-outer">
         <div id="map-sellers" class="map-sellers map-inactive" data-map-sellers></div>
         <div class="search-box seller-search-box" id="vyhledat-prodejce" data-search-box>
            <form action="" method="post" class="seller-search-form">
               <h3><i class="fc icons_location"></i>{t}Vyhledat prodejnu{/t}</h3>
               <div class="seller-search-form-inner">
                  <div class="form-wrap">
                     <input id="id_longitude" name="longitude" type="hidden">
                     <input id="id_latitude" name="latitude" type="hidden">
                     <input id="id_page" name="page" type="hidden" value="">
                     <input type="text" class="form-control" value="{$form.address.value|default:""}" name="address" id="id_long_address"
                            placeholder="{t}Zadej město{/t}" autocomplete="off">
                     <button class="btn-gps" value="Podle aktuální pozice" title="{t}Moje poloha{/t}" data-btn-gps>
                        {t}Aktuální poloha{/t}<i class="fc icons_gsp_locator"></i>
                     </button>
                  </div>
                  <button type="button" id="id_find" class="btn btn-primary">{t}Vyhledat{/t}</button>
               </div>
               <a href="" data-search-box-close class="search-box-close">{t}Zavřít{/t}<span class="fc icons_close"></span></a>
            </form>
         </div>
         <div class="search-box-active search-box-empty" id="change-location" data-search-box-active>
            <p><i class="fc icons_gps"></i><span data-current-address></span></p>
            <a class="change-city" onclick="changeState('search');">{t}Změnit město{/t}</a>
         </div>

         <div class="seller-box seller-box-empty" data-seller-box>
            <div data-seller-box-content></div>
         </div>
      </div>
   </div>
</div>

<script type="text/javascript">
   wpj.onReady.push(function () {
      var $longAddress = $("#id_long_address");

      $longAddress.geocomplete({
         country: "cz",
         blur: false,
      }).bind("geocode:result", function (event, result) {
         findDealers(result.geometry.location);
      });

      $longAddress.geocomplete({ country: "cz", blur: false, }).bind("geocode:result", function (event, result) {
            findDealers(result.geometry.location);
         });

      $("#id_find").click(function(){
         if ($longAddress.val()){
            $longAddress.trigger("geocode");
         }
      });

      $longAddress.click(function() {
         if($(this).val("{t}Nelze získat pozici{/t}")) {
            $(this).val("");
         }
      });

      var $geo = $('[data-btn-gps]');
      if ("geolocation" in navigator) {

         $geo.click(function () {
            navigator.geolocation.getCurrentPosition(function(position) {
               // Success
               $longAddress.val('{t}ve vašem okolí{/t}');
               var latitude = position.coords.latitude;
               var longitude = position.coords.longitude;
               findDealers(new google.maps.LatLng(latitude, longitude));
            }, function () {
               // Error
               $longAddress.val("{t}Nelze získat pozici{/t}");
            }, { enableHighAccuracy: true, timeout: 60000, maximumAge: 600000 });

            $longAddress.val('{t}Vyhledávám pozici ...{/t}');

            return false;
         });

      }

      /**
       * Mapa a prodejci
       */

      var dealer_map,
         markerCluster,
         info_window,
         $searchBox = $('[data-search-box]'),
         $searchBoxActive = $('[data-search-box-active]'),
         $currentAddress = $('[data-current-address]'),
         $sellerBox = $('[data-seller-box]'),
         $sellerBoxContent = $('[data-seller-box-content]'),
         $map = $('[data-map-sellers]'),
         allMarkers = [],
         markers = {
            {foreach $body.dealers as $dealer}
            {if ($ctrl.active_language == 'cs' and $dealer.country == 'CZ') or ($ctrl.active_language == 'sk' and $dealer.country == 'SK')}
            {$dealer.id}:[
               [
                  {$dealer.x},
                  {$dealer.y}
               ],
               "{$dealer.title}",
               "{$dealer.street}{if $dealer.number} {$dealer.number}{/if}",
               "{$dealer.city}, {$dealer.psc}",
               "{path('shop_seller_seller_detail', ['id_seller' => $dealer.id])}",
            ],
            {/if}
            {/foreach}
            0:0};

      window.changeState = function(state) {
         switch(state)
         {
            case "search":
               $longAddress.val('');
               $searchBoxActive.addClass('search-box-empty');
               $map.addClass('map-inactive');
               $searchBox.removeClass('search-box-hidden');
               $sellerBox.addClass('seller-box-empty');
               break;

            case "results-loaded":
               $searchBoxActive.removeClass('search-box-empty');
               $currentAddress.html($longAddress.val());
               $map.removeClass('map-inactive');
               $searchBox.addClass('search-box-hidden');
               break;
         }
      };

      $('body').on('click', '[data-close-seller-box]', function (e) {
         $sellerBox.addClass('seller-box-empty');
         return false;
      }).on('click', '[data-search-box-close]', function (e) {
         changeState('results-loaded');
         return false;
      });

      var hereMarker = null;

      // po vyhledání prodejce - nastavení středu mapy na vyhledané souřadnice,
      // nastavení bodu aktuální pozice
      // zavolání loadování dealer-boxu
      function findDealers(location, skipHistory)
      {
         dealer_map.setCenter(location);
         dealer_map.setZoom(10);

         $searchBox.find('#id_longitude').val(location.lng());
         $searchBox.find('#id_latitude').val(location.lat());

         if (!hereMarker)
         {
            hereMarker = new google.maps.Marker({
               position: location,
               title: "{t}Zadané místo hledání{/t}",
               map: map,
               icon:{
                  url: '{static_url url="/templates/images/map_marker_here.png"}'
               }
            });
         }

         hereMarker.setPosition(location);
         changeState('results-loaded');
      }

      function openWindow()
      {
         var marker = this;
         var info = markers[marker.index];
         var params = {
            title: info[1],
            link: "<a href='"+ info[4] +"' class='btn-link'>{t}Detail prodejny{/t}</a>",
            street: info[2],
            city: info[3],
            {if $body.type == 'reservation'}
            availability: info[5],
            {/if}
         };

         info_window.setContent(
            "<div id='map_info' class='seller-map-info'><h5>" + params.title + "</h5>"
            {if $body.type == 'reservation'}
            + "<p>" + params.availability + "</p>"
            {/if}
            + "<p>" + params.street + "<br>" + params.city +"</p>"
            + params.link + "</div>"
         );

         info_window.open(map, marker);
      }

      function addMarker(index, params) {
         var pos = new google.maps.LatLng(params.pos[0],params.pos[1]);

         var marker = new google.maps.Marker({
            position: pos,
            // title: params.title,
            icon: '{static_url url="/templates/images/map-marker-seller.png"}',
            map: map
         });

         marker.index = index;

         google.maps.event.addListener(marker, "click", openWindow);

         allMarkers.push(marker);
      }

      function cleanMarkers()
      {
         for (var index in allMarkers) {
            allMarkers[index].setMap(null);
         }

         try{
            markerCluster.clearMarkers();
         }catch(e){

         }

         allMarkers = [];
      }

      window.processMarkers = function(markersNew){
         var marker;
         for(var index in markersNew)
         {
            marker = markersNew[index];
            if (!marker)
               continue;

            addMarker(index, { pos: marker[0], type: marker[1], detailUrl: marker[2] });
         }

         // Add a marker clusterer to manage the markers.
         markerCluster = new MarkerClusterer(map, allMarkers, {
            styles: [{
               height: 58,
               url: '{static_url url="/templates/images/marker-clusterer.png"}',
               width: 58
            }]
         });
      };


      /**
       * Načtení default mapy
       */
      var center = new google.maps.LatLng(49.85, 15.5);

      var zoomLevel = 7,
         isDraggable = true;

      if ( $(window).width() > 900 ) {
         zoomLevel = 8; // oddálení mapy při měnších rozlišeních
      }

      var map = dealer_map = new google.maps.Map(document.getElementById("map-sellers"), {
         center: center,
         zoom: zoomLevel,
         draggable: isDraggable,
         scrollwheel: isDraggable,
         streetViewControlOptions: {
            position: google.maps.ControlPosition.LEFT_BOTTOM
         },
         zoomControlOptions: {
            position: google.maps.ControlPosition.LEFT_BOTTOM
         }
      });

      info_window = new google.maps.InfoWindow({
         content: ""
      });

      // Create placeholder control to make some space
      var centerControlDiv = $('<div>').css({
         height: $('#vyhledat-prodejce').outerHeight(true),
         width: '100%',
         'pointer-events': 'none'
      })[0];
      centerControlDiv.index = 1;
      map.controls[google.maps.ControlPosition.TOP_CENTER].push(centerControlDiv);

      processMarkers(markers);

      {if $form.address.value}
      $("#id_long_address").trigger("geocode");
      {/if}

   });

</script>
