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

var addresses = "";
function setlocations(loc){
     addresses=loc;
    theNext();
   
    
}

   function DeleteMarker(id) {
        for (var i = 0; i < markers.length; i++) {
            if (markers[i].id === id) {
                markers[i].setIcon('http://maps.google.com/mapfiles/ms/icons/red-dot.png');
                return;
            }
        }
    }
    
    
      
//    function serachloc(){
//        search=$("#search-q").val();
//        console.log(search);
//              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();
//                map.panTo(results[0].geometry.location);      
//            }
//        
//        });
//    
//    }
    



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

           $('#list').scrollTo('#li_'+id,{duration:'slow', offsetTop : '50'});
           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(10000);
                map.setZoom(10);
                map.panTo(markers[i].getPosition());
                infowindow.setContent('<b>'+company+'</b><br/>'+address);
                infowindow.open(map, markers[i]);
                 lastblue=id;
                return;
            }
        }

}


}



    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 ========
  



// ======= 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() {
       // console.log(addresses);
        $(".wrapper").addClass('map-overlay');
        $(".map-overlay").show();
      
        if (nextAddress < addresses.length) {
     //  if (nextAddress < 3) {
            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 =======

$("#search-q").on('keyup', function() {
   // address_json=JSON.stringify(addresses)
    var search = this.value.toLowerCase();
    var result = $.grep(addresses, function(el) {
       
         return el.address.toLowerCase().indexOf(search)> -1;
        //return el.keyword.toLowerCase().indexOf(search) > -1;
    });
   // console.log(result);
   
    log(result,search);

});

function log(rows,search) {
    var str = '';
    $.each(rows, function(i, row) {
        //console.log(row['id']);
            //str+ = '<li id=li_'+row['id']+'><a href="javascript:void(0)"> <b>'+row['company']+'</b><br/><span>' + row['address'] + '</span><p style="display:none">'+row['id']+'</p></a></li>';
          str+='<li id=li_'+row['id']+'><a href="javascript:void(0)"><b>'+row['company']+'</b><br/><span>' + row['address'] +'</span><p style="display:none">'+row['id']+'</p></a></li>';
         
       // console.log(row['address']);
       // str += JSON.stringify(row) + '<br>';
        //str += row + '<br>';
    });
    if(search!=""){
    searchplace(search);
}else{
    map.fitBounds(bounds);
}
    $('#list').html(str);
     // console.log(str);
   
}   

function searchplace(search){
               
              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();
                map.setZoom(10);      
                map.panTo(results[0].geometry.location);      
            }
        
        });
}
