var infowindow;
var map;
var geocoder;

function initialize()
{
    geocoder = new google.maps.Geocoder();

    var myOptions = {
      zoom: 6,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    map = new google.maps.Map($("map_canvas"), myOptions);
    codeAddress(pays);


    downloadUrl(websiteroot + "/partenaires-xml/" + id_categ_selected, function(data) {
    var markers = data.documentElement.getElementsByTagName("marker");

           for (var i = 0; i < markers.length ; i++)
           {
               if (markers[i].getAttribute("lat") != "" && markers[i].getAttribute("lng") != "") {
                   var latlng = new google.maps.LatLng(markers[i].getAttribute("lat"),  markers[i].getAttribute("lng"));
                   createMarker(markers[i], latlng,   websiteroot + "/partenaires_icons/" + picto );
               }
           }
    });
}

function createMarker(CustomMarker, latlng, image)
{
    var marker = null;
    if (image != websiteroot + "/partenaires_icons/")
          marker = new google.maps.Marker({position: latlng, map: map, icon: image});
    else
          marker = new google.maps.Marker({position: latlng, map: map});

     // sur le click d'un point sur la carte on ouvre l'InfoWindow correspondant
    google.maps.event.addListener(marker, "click", function() { openWindow(marker, CustomMarker); });

    // sur le click d'une fiche on ouvre l'InfoWindow sur la carte
    Event.observe('marker-'+CustomMarker.getAttribute("id"), 'click', function() { openWindow(marker, CustomMarker); });

    return marker;
}


function openWindow(marker, CustomMarker)
{
    if (infowindow)
          infowindow.close();

    var myContent = "<strong class='partenaire-infowindow'>"+CustomMarker.getAttribute("name")+"</strong>";

    if (CustomMarker.getAttribute("adresse") != "")
        myContent += "<br/><span class='partenaire-infowindow'>"+CustomMarker.getAttribute("adresse")+"</span>";

    myContent += '<p><a class="partenaire-infowindow" href="'+currentUrl+'/#marker-'+CustomMarker.getAttribute("id")+'">Voir la fiche</a></p>';

    infowindow = new google.maps.InfoWindow({content: myContent});
    infowindow.open(map, marker);
}

function codeAddress(address)
{
    if (geocoder) {
      geocoder.geocode( { 'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
          if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
            map.setCenter( results[0].geometry.location );
          } else {
            alert("No results found");
          }
        } else {
          alert("Geocode was not successful for the following reason: " + status);
        }
      });
    }
}