<?php
$this->registerJsFile('http://maps.google.com/maps/api/js?sensor=false',[
    'depends'=>'yii\web\YiiAsset',
    'position' => \yii\web\View::POS_END]);
//$this->registerJsFile('https://cdnjs.cloudflare.com/ajax/libs/jquery-scrollTo/1.4.14/jquery.scrollTo.js');

?>

<style>

    // #map-outer {height: 100%; padding: 20px; border: 2px solid #CCC; margin-bottom: 20px; background-color:#FFF;margin-left: 5px }
    #map-canvas { height: 763px;margin-left: 5px }
    @media all and (max-width: 991px) {

    }
    .map-overlay{
        background-color: whitesmoke;
        height: 100%;
        opacity: 0.64;
        position: absolute;
        text-align: center;
        width: 100%;
        z-index: 1;
    }  
    .img-cls{
        margin-bottom: auto;
        margin-right: 205px;
        margin-top: 219px;
        text-align: center;
        width: 100px;
    }
  
.skin-blue .sidebar > .sidebar-menu > li.active > a {
 
    background-color: #F0E68C !important;
    color: #222;
}

</style>


<!--      <div id="map-outer" class="col-md-12">-->
<div class="map-overlay" style="display: none">
    <image class="img-cls" src="<?php echo Yii::$app->request->baseUrl ?>/images/ajax_loader.gif"/>

</div>
<div id="map-canvas"></div>
<!--      </div> /map-outer -->




<!--<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-scrollTo/1.4.14/jquery.scrollTo.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-scrollTo/1.4.14/jquery.scrollTo.min.js"></script>
<script src="http://maps.google.com/maps/api/js?sensor=false"></script>-->



<script>
<?php $this->registerJs("
// delay between geocode requests - at the time of writing, 100 miliseconds seems to work well
var delay = 100;
var lastmarker=0;
var markers = [];
var lastid = 0;
var lastblue = 0;



// ====== Create map objects ======
    var infowindow = new google.maps.InfoWindow();
    var latlng = new google.maps.LatLng(-34.397, 150.644);
    var mapOptions = {
        zoom: 8,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    var geo = new google.maps.Geocoder();
    var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
    var bounds = new google.maps.LatLngBounds();

// ====== Geocoding ======

    $('#list').on('click', 'li', function (event) {
        company=$(this).find('b').text();
        id=$(this).find('p').text();
        address=$(this).find('span').text();
           $('li').removeClass('active');
            $('#li_'+id).addClass('active');
   
        getbluemarker(id,address,company);
    });

   function DeleteMarker(id) {
        //Find and remove the marker from the Array
     
    
        for (var i = 0; i < markers.length; i++) {
             //  console.log(markers);
            if (markers[i].id === id) {
               //  console.log(id);
                //Remove the marker from Map                  
                //markers[i].setMap(null);
                markers[i].setIcon('http://maps.google.com/mapfiles/ms/icons/red-dot.png');
              //  markers[i].setMap('icon'=>'http://maps.google.com/mapfiles/ms/icons/blue-dot.png');
 
                //Remove the marker from array.
             //   markers.splice(i, 1);
                return;
            }
        }
    }
    



    function getbluemarker(id,address,company) {
         
        if(lastblue!==id){
            if(lastblue!==0){
               DeleteMarker(lastblue);
           }

           $('#list').scrollTo('#li_'+id,{duration:'slow', offsetTop : '50'});
//                       $('section,ul').animate({
//                          // $('#demo-stage').scrollTo($chScrollPositions[next]);
//                 //   scrollTop: ($("#li_"+id).position().top)
//                  //  scrollTop: 1700
//                }, "slow");
               
         //  console.log( $("#li_34").offset().top);

            // $("#li_"+id).show();
//            if(lastid!==0){
//               DeleteMarker(lastid);
//           }
           for (var i = 0; i < markers.length; i++) {
            if (markers[i].id == id) {
                //Remove the marker from Map                  
                //markers[i].setMap(null);
                markers[i].setIcon('http://maps.google.com/mapfiles/ms/icons/yellow-dot.png');
                markers[i].setZIndex(100);
                map.setZoom(10);
                map.panTo(markers[i].getPosition());
                infowindow.setContent('<b>'+company+'</b><br/>'+address);
                infowindow.open(map, markers[i]);
                
              //  markers[i].setMap('icon'=>'http://maps.google.com/mapfiles/ms/icons/blue-dot.png');
 
                //Remove the marker from array.
                //markers.splice(i, 1);
                 lastblue=id;
                return;
            }
        }
       
                // find the marker by given id
              //  marker.setMap(null);
            
//        geo.geocode({'address': address}, function (results, status) {
//            if (status == google.maps.GeocoderStatus.OK) {
//                map.setCenter(results[0].geometry.location);
//                p = results[0].geometry.location;
//                var lat = p.lat();
//                var lng = p.lng();
//                var marker = new google.maps.Marker({
//                    id:id,
//                    title: address,
//                    zoom: map.setZoom(10),
//                    map: map,
//                    position: new google.maps.LatLng(lat, lng),
//                    icon: "http://maps.google.com/mapfiles/ms/icons/green-dot.png",
//                    zIndex: Math.round(latlng.lat() * -100000) << 5
//                });
//               
//                google.maps.event.addListener(marker, 'click', function () {
//                    infowindow.setContent(company);
//                    infowindow.open(map, marker);
//                });
//                infowindow.setContent(company);
//                infowindow.open(map, marker);
//                markers.push(marker);
//                lastid=id;
//                
//            } 
//            
//        else {
//                alert("Geocode was not successful for the following reason: " + status);
//            }
//            
//        });

}
//        google.maps.event.addListener(marker, 'click', function () {
//            infowindow.setContent(address);
//            infowindow.open(map, marker);
//        });

        // bounds.extend(marker.position);
  //  }

}



    function getAddress(search,company,id, next) {

        geo.geocode({address: search}, function (results, status)
        {
            // If that was successful
            if (status == google.maps.GeocoderStatus.OK) {
                map.setCenter(results[0].geometry.location);
                // Lets assume that the first marker is the one we want
                var p = results[0].geometry.location;
                var lat = p.lat();
                var lng = p.lng();
                // Output the data
                // var msg = 'address="' + search + '" lat=' + lat + ' lng=' + lng + '(delay=' + delay + 'ms)<br>';
                var msg = '<li id=li_'+id+'><a href="javascript:void(0)"> <b>'+company+'</b><br/><span>' + search + '</span><p style="display:none">'+id+'</p></a></li>';
                document.getElementById("list").innerHTML += msg;
                // Create a marker
                createMarker(search,company,id, lat, lng);
            }
            // ====== Decode the error status ======
            else {
                // === if we were sending the requests to fast, try this one again and increase the delay
                if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
                    nextAddress--;
                    delay++;
                } else {
                    var reason = "Code " + status;
                    var msg = 'address="' + search + '" error=' + reason + '(delay=' + delay + 'ms)<br>';
                    //  document.getElementById("messages").innerHTML += msg;
                }
            }
            next();
        }
        );
    }

// ======= Function to create a marker
    function createMarker(add,company, id,lat, lng) {
       // var contentString = company;
        var marker = new google.maps.Marker({
            position: new google.maps.LatLng(lat, lng),
            map: map,
            id:id,
            icon: "http://maps.google.com/mapfiles/ms/icons/red-dot.png"
                    // zIndex: Math.round(latlng.lat() * -100000) << 5
        });
              markers.push(marker);
               
        google.maps.event.addListener(marker, 'click', function () {
              map.panTo(marker.getPosition());
            $("li").removeClass('active');
            $("#li_"+id).addClass('active');
            getbluemarker(id,add,company);
//            if(lastid!==0){
//            DeleteMarker(lastid);
//        }
//            marker.setIcon('http://maps.google.com/mapfiles/ms/icons/yellow-dot.png');
//            lastid=id;
//            infowindow.setContent(contentString);
//            infowindow.open(map, marker);
        });

        bounds.extend(marker.position);

    }

// ======= An array of locations that we want to Geocode ========
    var addresses = <?php echo $locations; ?>;



// ======= Global variable to remind us what to do next
    var nextAddress = 0;

// ======= Function to call the next Geocode operation when the reply comes back

    function theNext() {

        $(".wrapper").addClass('map-overlay');
        $(".map-overlay").show();
      
       // if (nextAddress < addresses.length) {
       if (nextAddress < 5) {
            
            setTimeout('getAddress("' + addresses[nextAddress]['address'] + '","' + addresses[nextAddress]['company'] + '","' + addresses[nextAddress]['id'] + '",theNext)', delay);
            nextAddress++;
        } else {
            // We're done. Show map bounds
            map.fitBounds(bounds);
           
            $(".wrapper").removeClass('map-overlay');
             $(".map-overlay").hide();
        }
    }

// ======= Call that function for the first time =======
    theNext();

");



