{extends "index.tpl"}

{block "css-entry" append}
   {encore_entry_link_tags entry='htmlpage'}
{/block}

{block "js-dynamic-load"}
   <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyALWHnTYGbIvtTTB8EMiT9wZP3sLMTw-lI&libraries=places&language=cs"></script>
   <script src="/web/bundles/seller/js/markerwithlabel.js"></script>
   <script src="/web/bundles/seller/js/jquery.geocomplete.js"></script>
   <script src="/common/static/wpj/wpj.serializer.js"></script>
   <script src="https://unpkg.com/@googlemaps/markerclustererplus/dist/index.min.js"></script>
{/block}

{block "infopanel"}{/block}

{block "main"}
   <main class="main sellers-main">

      <div class="container">
         <div class="row">
            <div class="col-xl-10 col-xl-offset-1 col-xs-12">
               <div class="sellers-header">
                  <div class="sellers-title">
                     <h6>{t}Navštiv naše{/t}</h6>
                     <h1>{$view->getTitle()}</h1>
                  </div>
                  {if $body.types|count > 1}
                     <div class="sellers-tabs">
                        {foreach $body.types as $type}
                            <a href="" class="sellers-nav-link active" data-tab-opener="#sellers-map-wrapper">{$type}</a>
                        {/foreach}
                     </div>
                  {/if}

                  {if $body.types|count > 1}
                     <form action="{path('shop_seller_seller_list')}" method="post" data-sellers-filter class="sellers-filter">
                        {foreach $body.types as $key => $type}
                            <label class="custom-control custom-checkbox">
                              <input type="checkbox" name="type[]" value="{$key}" class="custom-control-input" checked>
                              <span class="custom-control-indicator"></span>
                              <span class="custom-control-text">
                                 {$type}
                                 <i class="tooltip tooltip-{$key}"></i>
                              </span>
                            </label>
                        {/foreach}
                     </form>
                  {/if}
               </div>
            </div>
         </div>
      </div>

      <div class="sellers-tab-content active" id="sellers-map-wrapper">
         <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">
                  <h5 class="fc icons_gps">{t}Vyhledat prodejnu{/t}</h5>
                  <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_gps_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="fc icons_close search-box-close"></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>

      {block "online-sellers"}{/block}
   </main>

   <div data-sellers-filter-container></div>
{/block}

<script>
    {block onready}
    $('body').on('click', '[data-tab-opener]', function(e){
       const $target = $(this).data('tab-opener');

       $('.sellers-tab-content').removeClass('active');
       $('.sellers-nav-link').removeClass('active');
       $($target).addClass('active');
       $(this).addClass('active');

       return false;
    });

    $('body').on('change', '[data-sellers-filter] input', function (e) {
       var data = $('[data-sellers-filter]').serialize();
       $('[data-sellers-filter-container]').load("{path('shop_seller_seller_list')}", data, function() {

       });
    });

    /**
     * Vyhledávání, geocomplete
     */

    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,
        $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}
    {$dealer.id}:[
        [
            {$dealer.x},
            {$dealer.y}
        ],
        "{$dealer.type}",
        "{path('shop_seller_seller_listdetail', ['id_seller' => $dealer.id])}",
    ],
    {/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 MarkerWithLabel({
                position: location,
                title: "{t}Zadané místo hledání{/t}",
                map: dealer_map,
                icon:{
                    url: '/templates/images/map_marker_here.png'
                }
            });
        }

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


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

        var marker = new MarkerWithLabel({
            position: pos,
            labelContent: "<i class='fc icons_plus'></i>",
            labelAnchor: new google.maps.Point(20, 42),
            labelClass: "sellers-map-label sellers-map-label-" + params.type,
            labelInBackground: false,
            icon: '',
            dimClass: "sellers-map-label sellers-map-label-" + params.type,
            detailUrl: params.detailUrl,
            map: dealer_map
        });

        marker.index = index;

       google.maps.event.addListener(marker, 'mouseover', function() {
          marker.set('labelClass', marker.dimClass + ' hover');
       });
       google.maps.event.addListener(marker, 'mouseout', function() {
          marker.set('labelClass', marker.dimClass);
       });

        google.maps.event.addListener(marker, "click",  function () {
           $sellerBoxContent.load(marker.detailUrl, { }, function () {
              $sellerBox.removeClass('seller-box-empty');

              if($(window).width() < 992) {
                 $('html, body').animate({
                    scrollTop: $sellerBox.offset().top - 100
                 }, 600);
              }
            });
        });

       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(dealer_map, allMarkers, {
          styles: [{
             height: 80,
             url: "/templates/images/marker_clusterer.png",
             width: 80
          }]
       });
    };


    /**
     * 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
        }
    });

    // 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}
    {/block}
</script>

{block "js-entry" append}
   {encore_entry_script_tags entry='htmlpage'}
{/block}
