var tabMarqueurs = new Array();
var marqueur,loc;
function geolocate(carte){
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position) {
          var pos = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
            carte.setCenter(pos);
          var cord={lat:pos.lat(),long:pos.lng()};
            //marqueur.setMap(null);
            mark(carte,cord);
            marqueur.setAnimation(google.maps.Animation.BOUNCE)
        console.log(pos);
        }, function() {
          console.log("erreur");
        });
      } else {
          console.log("erreur");
      }
}

function drawWay(carte,myWay,color){
    var way = new google.maps.Polyline({
        path: myWay,
        geodesic: true,
        strokeColor: color,
        strokeOpacity: 0.75,
        strokeWeight: 2
      });
    way.setMap(carte);
    carte.setCenter(new google.maps.LatLng(myWay[parseInt(myWay.length/2)].lat,myWay[parseInt(myWay.length/2)].lng));
    carte.setZoom(17);
}

function clearWay(){
    way.setMap(null);   
}

function getDistanceBetweenMeAnd(b){
    var distanceKm = google.maps.geometry.spherical.computeDistanceBetween(marqueur.getPosition(), b);
    return distanceKm;
}

function marcheProche(carte){
    var min=getDistanceBetweenMeAnd(tabMarqueurs[0].getPosition());             
   for(var i=1;i<tabMarqueurs.length;i++){
        if(min>getDistanceBetweenMeAnd(tabMarqueurs[i].getPosition()))
            min=getDistanceBetweenMeAnd(tabMarqueurs[i].getPosition());
   }

    for(var i=0;i<tabMarqueurs.length;i++){
        if(getDistanceBetweenMeAnd(tabMarqueurs[i].getPosition())!=min)
            tabMarqueurs[i].setMap(null);
        else{
            var way=[
                {lat:tabMarqueurs[i].getPosition().lat(),lng:tabMarqueurs[i].getPosition().lng()},
                {lat:marqueur.getPosition().lat(),lng:marqueur.getPosition().lng()}
            ];
            $("#info").html("Any @ "+parseInt(min)+" m miala eto ny tsena akaiky indrindra");
            $("#info").show("linear");
            drawWay(carte,way,'#0CBCB7');
        }
    }
}

function getLocation(){
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position) {
          var db=new Database();
            db.configure();
            var w=new MyWay(db.open("smarkhelp6",2));
            w.creer(position.coords.latitude,position.coords.longitude);
        }, function() {
          console.log("erreur");
        });
        loc=setTimeout(getLocation,5000);
      } else {
        // Browser doesn't support Geolocation
          console.log("erreur");
      }
}

function initMap(id){
        var latlng = new google.maps.LatLng(-18.9083,47.5263);
        var options = {
            center: latlng,
            zoom: 16,
            mapTypeControl: false,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        var carte = new google.maps.Map(document.getElementById(id), options);
        var cord={lat:latlng.lat(),long:latlng.lng()};
    return carte;
}


function mark(carte,cord){
    marqueur = new google.maps.Marker({
        position: new google.maps.LatLng(cord.lat,cord.long),
        map: carte,
        title : "vous êtes ici",
        icon:"../img/autre.png"
    });
    
    google.maps.event.addListener(marqueur, 'click', function() {
        
    });
}

function removeAllMark(){
    for(var i=0;i<tabMarqueurs.length;i++){
        tabMarqueurs[i].setMap(null);
    }
}

function seeInMap(carte,lat,lng){
        var latlng = new google.maps.LatLng(lat,lng);
        var mtp=new google.maps.Marker({
                position: latlng,
                map: carte,
            });
        carte.setCenter(latlng);
        carte.setZoom(17);
}

function addLocationMark(carte,lat,lng,categorie){
    var latlng = new google.maps.LatLng(lat,lng);
    var info=categorie.split("#");
    var iconName=info[0]+".png";
    console.log("locaddd : "+lat+"#"+lng+">"+iconName);
    var contentString = '<div id="content">'+
      '<div id="siteNotice">'+
      '</div>'+
      '<h6 id="firstHeading" class="firstHeading">'+info[1]+'</h6>'+
      '<div id="bodyContent">'+
      '<p><b></b><b></b>' +info[0]+' - '+info[2]+
      '</p>'+
      '</div>'+
      '</div>';
    var infowindow = new google.maps.InfoWindow({
        content: contentString
      });
    var mtp=new google.maps.Marker({
            position: latlng,
            map: carte,
            icon:"../img/"+iconName
        });
    mtp.addListener('click',function(){
       infowindow.open(carte,mtp); 
    });
    tabMarqueurs.push(mtp);
}

function addMark(carte){
    //notez la présence de l'argument "event" entre les parenthèses de
    google.maps.event.addListener(carte, 'click', function(event) {
        tabMarqueurs.push(new google.maps.Marker({
            position: event.latLng,
            map: carte
        }));

    });
}

function getCord(carte,element){
    google.maps.event.addListener(carte, 'click', function(event) {
        element.val(event.latLng.lat()+"#"+event.latLng.lng());
        removeAllMark();
        addMark(carte);
    });
    return 
}