
//*************** INTITIALISATION DE LA LISTE DES CARTES **********************

var listeMaps = Array();

//***************** FONCTIONS GOOGLE MAPS ***********************************

/**
 * Cette fonction créer un nouveau marqueur google map et le renvoie
 * lat, lng : les coordonnées du marqueur
 * info : le texte à afficher dans la bulle lors d'un clic.
 * Si info = null alors l'icone ne comportera pas de description
 * bounds
 * (optionnel) icon : une image pour redéfinir l'affichage du marqueur
 */
function createMarker( lat, lng, info, bounds, icon, label )
{

    var point = new GLatLng(lat, lng);
/*
    icon.iconAnchor = new GPoint(16, 16);
    icon.infoWindowAnchor = new GPoint(25, 7);
    opts = { 
        "icon": icon,
        "clickable": true,
        "labelText": label,
        "labelOffset": new GSize(-6, -10)
    };

    var marker = new LabeledMarker(point, opts);
*/
    var marker = new GMarker( point, {icon:icon} );

    if(info != null)
    {
        GEvent.addListener(marker, "click", function() {
            marker.openInfoWindowHtml(info);
        });
    }
    if (bounds != null)
    {
        bounds.extend(point);
    }
    return marker;      
}

/**
 * Cette fonction affiche une carte google maps dans un bloc
 * blockId : L'id du block dans lequel insérer la map
 * datas : Un tableau multidimensionnel contenant la liste des points
 * à afficher ainsi que leurs options. Exemple :
 *          data[i] = Array(
 *                      "latitude" => 33.3333
 *                      "longitude" => 22.22222
 *                      "icon" => "blue"
 *                      "contentobject_id" => 135
 *                  )
 * zoom : le niveau de zoom de la carte
 * center : le point sur lequel centrer la map Ex: Array(33.333, 22.2222)
 * display_info : booleen indiquant si on affiche ou non la description des
 * puces lorsque l'on clique dessus
 */
function displayMap(blockId, datas, zoom, center, display_info, itinerary){
    
    var map = new GMap2(document.getElementById(blockId));
    map.addControl(new GSmallMapControl());
    
    map.setCenter(new GLatLng(center[0],center[1]), zoom);
    var bounds = new GLatLngBounds();
    map.setMapType(G_NORMAL_MAP);

    var encodedPolygon = new GPolygon.fromEncoded({
      polylines: [{
          points: encodedPoints,
          levels: encodedLevel,
          color: pathColor
      }],
      fill: true,
      color: pathFillColor,
      outline: true
    } );
    map.addOverlay(encodedPolygon);
    if (zoom > 8 )
    {
       encodedPolygon.hide();
    }


    GEvent.addListener(map,"zoomend",function( oldLevel, newLevel ){
                       if (oldLevel < 9 && newLevel > 8 )
                       {
                           encodedPolygon.hide();
                       }
                       else if (oldLevel > 8 && newLevel < 9 )
                       {
                           encodedPolygon.show();
                       }
    });

    var index = 1;
    var markers = [];
    var mcOptions = { gridSize: 20, maxZoom: 15};
    
    for(i=0; i < datas.length; i++)
    {
        var data = datas[i];
        
        // On récupère la description de notre point
        var latitude = data["latitude"];
        var longitude = data["longitude"];
        var label = data["label"];
        var icon = eval( data["icon"] );
        var contentobject_id = data["contentobject_id"];
        var text = document.getElementById('location_' + contentobject_id).innerHTML;
        
        if(display_info == false)
        {
            text = null;
        }
        
        // On ajoute le point sur la carte
        var marker = createMarker( latitude, longitude, text, bounds, icon, label );
        markers.push( marker );
        
    }
    var markerCluster = new MarkerClusterer(map, markers, mcOptions);
    
    // Calcul de l'itinéraire
    if(itinerary){
        var locale = itinerary["locale"];
        var from = itinerary["from"];
        var Lat = itinerary["latitude"];
        var Long = itinerary["longitude"];
        
        var gdir = new GDirections(map, document.getElementById("directions"));
        
        GEvent.addListener(gdir, "error", handleErrors);
        GEvent.addListener(gdir, "addoverlay", handleAddOverlay);
        // On charge le point recherché
        
        var result = gdir.load("from: " + from + " to: " + Lat + "," + Long,	{ "locale": locale , "getSteps" : true});
    }
    
    // Pour week end gbnl : on cache le panneau de filtres par sequences quand on clic sur un picto google maps 
    var divSequenceFilterPanel = document.getElementById('gmap_sequence_filters');
    if(divSequenceFilterPanel){
    	GEvent.addListener(map, "infowindowopen", function(){
    		divSequenceFilterPanel.style.display = 'none';
    	});
    	
    	GEvent.addListener(map, "infowindowclose", function(){
    		divSequenceFilterPanel.style.display = 'block';
    	});
    }
    
    function handleAddOverlay(){
        // Si l'itineraire est valide, cette fonction est appelée
        // Suppression des anciens markers pour éviter d'en avoir 2 superposés
        markerCluster.clearMarkers();
    }
    
  	var secondTry = false;
    function handleErrors(){
        if(secondTry)
        {
            // Erreur dans l'adresse de l'itinéraire, affichage d'un message d'erreur
            var divDirections = document.getElementById('directions');
            divDirections.set('html', document.getElementById('gmap_error').get('html'));
        }
        else
        {
            gdir.load( "from: " + from + ", France to: " + Lat + "," + Long, { "locale": locale, "getSteps": true } );
            secondTry = true;
        }
    }
}


var gmapExistingOnload = null;

window.addEvent('domready',function() {
    if (GBrowserIsCompatible())
    {
        for(var j=0; j<listeMaps.length; j++)
        {
            var tab = listeMaps[j];
            if(tab[5])
                displayMap(tab[0], tab[1], tab[2], tab[3], tab[4], tab[5]);
            else
                displayMap(tab[0], tab[1], tab[2], tab[3], tab[4]);
        }
    }
});









