var map = null;
var centreurl = null; 
var markerTmp = null;
var Offres = new Array();
var LaisonsCircuits = new Array();
var MoveMap;

//Recuperation des coordonnees et des infos
// setcenter = [0] ne pas centrer ; [1] centrer sur le dernier point de la liste (ou 1 seul point dans la liste) ; [2] centrer au milieu des points affichés
function PositionnePoints(param, setcenter, modecarto)
{
    MasqueCalquePDL();
    // nettoyage de la carte
//    map.clearOverlays();

    // creation nouveaux points
	var urlxml = "GetXMLGoogleMapV2.asp?" + param;
//alert(urlxml);

	GDownloadUrl(urlxml, function(data, responseCode)
	{
		var xml = GXml.parse(data);
		var autoZoom = xml.documentElement.getAttribute("autoZoom");
		var liaisons = xml.documentElement.getAttribute("liaisons");

		if (setcenter != 0 && xml.documentElement != null)
		{
			var infos = xml.documentElement.getElementsByTagName("markers");
			var val_maptype = eval(xml.documentElement.getAttribute("maptype"));
			var val_GLargeMapControl = xml.documentElement.getAttribute("GLargeMapControl");
			var val_GMapTypeControl = xml.documentElement.getAttribute("GMapTypeControl");
			var val_GOverviewMapControl = xml.documentElement.getAttribute("GOverviewMapControl");
			var val_GScaleControl = xml.documentElement.getAttribute("GScaleControl");
			var zoom = xml.documentElement.getAttribute("zoom");
			var centreX = xml.documentElement.getAttribute("centreX");
			var centreY = xml.documentElement.getAttribute("centreY");
			
			if (val_GLargeMapControl=="1")
				map.addControl(new GLargeMapControl());
		    
			if (val_GMapTypeControl=="1")
				map.addControl(new GMapTypeControl());
			
			if (val_GOverviewMapControl=="1")
			   // map.addControl(new GOverviewMapControl());
			
			if (val_GScaleControl=="1")
			    map.addControl(new GScaleControl());
		}	
		
		var bounds = new GLatLngBounds;

		var markers;

		if (xml.documentElement != null)
			markers = xml.documentElement.getElementsByTagName("marker");
		else
			markers = new Array();

		var mespoints = new Array(markers.length);

        if (setcenter!=0)
    		map.setCenter(new GLatLng(parseFloat(centreX.replace(',', '.')), parseFloat(centreY.replace(',', '.'))), parseInt(zoom), val_maptype);

        // spécifique circuits
		if (autoZoom && liaisons)
		{
		    map.disableDoubleClickZoom();
	        map.disableContinuousZoom();
		    map.disableScrollWheelZoom();
		}
		
        CalquePDL();
        // masquer les offres non nécessaires
        // puis ré-afficher les offres deja en mémoire
        for (var i = 0; i < Offres.length; i++)
        {
            if (Offres[i] != null)
            {
                Offres[i].hide();
//                Offres[i].closeInfoWindow();
            }
        }
        for (var i = 0; i < LaisonsCircuits.length; i++)
        {
            if (LaisonsCircuits[i] != null)
            {
                LaisonsCircuits[i].hide();
            }
        }
/*
alert(Offres.length);
alert(markers.length);
alert(mespoints.length);
*/
        // liaisons pour les circuits
        var idCircuit = "-1";
        
        // afficher les offres supplémentaires + mise en mémoire
		for (var i = 0; i < markers.length; i++)
        {
//if ("0112993" == markers[i].getAttribute("identifiant"))
//      debugger;
            if (Offres[parseInt(markers[i].getAttribute("identifiant"), 10)] == null)
            {
                picto = markers[i].getAttribute("picto");
                texte = markers[i].textContent;

                // Bug IE - il ne connait pas textContent
                if (!texte)
                {
                    texte = markers[i].xml;
                    if (texte) texte = texte.replace("]]>", "");
                }

                if (texte) texte = "<div class='infospoints'>" + texte + "<br/></div>";
		else texte = ""

                var point = null
                
//                if (markers[i].getAttribute("lat") == 0 && markers[i].getAttribute("lng") == 0)
//                    Geolocaliser(""/*markers[i].getAttribute("Ligne_adresse")*/, ""/*markers[i].getAttribute("Code_postal")*/, markers[i].getAttribute("Libelle_de_commune"), texte, 'France');
//                else
                {
                    point = new GLatLng(parseFloat(markers[i].getAttribute("lat")),  parseFloat(markers[i].getAttribute("lng")));

                    bounds.extend(point);
                    mespoints[i] = point;

                    // positonnement du point courant
                    var marker = createMarker(point, texte, picto, markers[i].getAttribute("LienDirect"));
                    map.addOverlay(marker);

                    // sauvegarde du marker
                    Offres[parseInt(markers[i].getAttribute("identifiant"), 10)] = marker;
                }
            }
            else
            {
		Offres[parseInt(markers[i].getAttribute("identifiant"), 10)].show();
                bounds.extend(Offres[parseInt(markers[i].getAttribute("identifiant"), 10)].getLatLng());
            }

            // Dessiner une ligne entre les points
            if (i > 0 && liaisons == "1" && idCircuit == markers[i].getAttribute("categorie"))
            {
                var polyline = new GPolyline([
                      new GPoint(Offres[parseInt(markers[i-1].getAttribute("identifiant"), 10)].getLatLng().lng(), 
                        Offres[parseInt(markers[i-1].getAttribute("identifiant"), 10)].getLatLng().lat()),
                      new GPoint(Offres[parseInt(markers[i].getAttribute("identifiant"), 10)].getLatLng().lng(), 
                        Offres[parseInt(markers[i].getAttribute("identifiant"), 10)].getLatLng().lat())
                      ],
                      "#5050F0", 4);
                map.addOverlay(polyline);
                LaisonsCircuits.push(polyline);
            }

            // liaisons pour les circuits
            idCircuit = markers[i].getAttribute("categorie");
        }

        // Dessiner une ligne avec le point de départ si boucle (défini avec le champ Libelle_de_commune dans la psu)
        if (markers.length > 2 && liaisons == "1" 
            && markers[0].getAttribute("categorie") == markers[markers.length - 1].getAttribute("categorie")
            && markers[markers.length - 1].getAttribute("Libelle_de_commune") == "1")
        {
            var polyline = new GPolyline([
                  new GPoint(Offres[parseInt(markers[markers.length - 1].getAttribute("identifiant"), 10)].getLatLng().lng(), 
                    Offres[parseInt(markers[markers.length - 1].getAttribute("identifiant"), 10)].getLatLng().lat()),
                  new GPoint(Offres[parseInt(markers[0].getAttribute("identifiant"), 10)].getLatLng().lng(), 
                    Offres[parseInt(markers[0].getAttribute("identifiant"), 10)].getLatLng().lat())
                  ],
                  "#5050F0", 4);
            map.addOverlay(polyline);
            LaisonsCircuits.push(polyline);
        } 

        //on determine le zoom en fonction des points a afficher
        if (autoZoom == "1" && markers.length > 1)
        {
            var newzoom = map.getBoundsZoomLevel(bounds);
            if (newzoom < map.getZoom())
                map.setZoom(newzoom);
        }

        //si plusieurs points recentrage
        if (setcenter == 2 && markers.length > 0)
        {
            var centre = bounds.getCenter();
            map.setCenter(centre);
        }

        for (var i = 0; i < Offres.length; i++)
        {
            if (Offres[i] != null && Offres[i].getIcon().image.indexOf("_On.") > 0)
            {
                // on remet au premier plan l'offre en cours
                map.removeOverlay(Offres[i]);
                map.addOverlay(Offres[i]);
                
                // on charge la carte et centre si necessaire sur le dernier point
                if (setcenter==1)
                    map.setCenter(Offres[i].getPoint());
            }
        }
        
        if (document.getElementById("chargementEnCours") != null)
            document.getElementById("chargementEnCours").style.display = "none";

        // recherche nouveaux points
        // si changement zoom ou deplacement
        if (modeCarto == "Offres" || modeCarto == "Geoloc" || modeCarto == "Incontournables" || modeCarto == "Circuits")
            MoveMap = GEvent.addListener(map, "moveend", Recalculer);
    }); 
}

// calque qui entoure la région pdl
var _calquePDL100 = null;
var _calquePDL50 = null;

function importanceOrder(marker,b)
{
    return 1;
}
function EnDessous(marker,b)
{
    return -100000000;
}

function MasqueCalquePDL()
{
    if (_calquePDL100 != null && !_calquePDL100.isHidden())
        _calquePDL100.hide();
    if (_calquePDL50 != null && !_calquePDL50.isHidden())
        _calquePDL50.hide();
}

function CalquePDL()
{
    var zoomTmp = map.getZoom();

    if (zoomTmp == 8)
    {
        if (_calquePDL100 == null)
        {
            var icon = new GIcon();
	        icon.image = "design/PDL_50.png";
            icon.iconSize = new GSize(697, 690);
            icon.iconAnchor = new GPoint(400, 400);
            
            _calquePDL100 = new GMarker(new GLatLng(47.22329888685773, -0.5657958984375), {icon: icon, clickable: false, draggable: false, zIndexProcess:EnDessous});
            GEvent.addListener(_calquePDL100, "dragend", function () { alert(_calquePDL100.getPoint().lat() + ", " + _calquePDL100.getPoint().lng()); });

            map.addOverlay(_calquePDL100);
        }
        else
        {
            _calquePDL100.show();
        }
	}
    else if (zoomTmp == 7)
    {
        if (_calquePDL50 == null)
        {
            var icon = new GIcon();
	        icon.image = "design/PDL_100.png";
            icon.iconSize = new GSize(379, 375);
            icon.iconAnchor = new GPoint(200, 200);
            _calquePDL50 = new GMarker(new GLatLng(47.33137715779824, -0.72509765625), {icon: icon, clickable: false, draggable: false, zIndexProcess:EnDessous});
            GEvent.addListener(_calquePDL50, "dragend", function () { alert(_calquePDL50.getPoint().lat() + ", " + _calquePDL50.getPoint().lng()); });

            map.addOverlay(_calquePDL50);
        }
        else
        {
            _calquePDL50.show();
        }
	}
}

// placement un point sur la carto + layer sur clic
function createMarker(point, texte, picto, lienDirect)
{
    var icon = new GIcon();

	if (picto == "")
	    icon.image = "design/Gmap_standard.png";
	else
	    icon.image = "design/" + picto;

	icon.iconSize = new GSize(23, 34);
	icon.iconAnchor = new GPoint(10, 33);
	icon.infoWindowAnchor = new GPoint(15, 12);

    var marker;
    
    if (modeCarto == "BackOffice")
        marker = new GMarker(point, {draggable: true, zIndexProcess:importanceOrder});
    else if (lienDirect != "")
    {
        marker = new GMarker(point, {icon: icon, zIndexProcess:importanceOrder});
        GEvent.addListener(marker, "click", function() { parent.location.href=lienDirect; });
    }
    else
    {
        marker = new GMarker(point, {icon: icon, zIndexProcess:importanceOrder});
        GEvent.addListener(marker, "click", function() {marker.openInfoWindowHtml(texte, {maxWidth:240}); });
    }

    return marker;
}  

// placer un seul point
function PlacerPoint(point, titre)
{
    if (markerTmp != null)
    {
        map.removeOverlay(markerTmp);
    }

    markerTmp = createMarker(point, titre, "Gmap_recherche.png")

    map.addOverlay(markerTmp);
    if (modeCarto != "BackOffice")
        markerTmp.openInfoWindowHtml(titre, {maxWidth:140});
    map.setCenter(point);

    // sur le début du déplacement, on ferme l'info-bulle
        GEvent.addListener(markerTmp, "dragstart", function() { map.closeInfoWindow(); });
    // sur la fin du déplacement, on récupère les coordonnées
    GEvent.addListener(markerTmp, "dragend", function() { RenseignerCoordonnees(markerTmp.getPoint().lat().toString().replace('.', ','), markerTmp.getPoint().lng().toString().replace('.', ',')); });
	
    if (modeCarto == "BackOffice")
        RenseignerCoordonnees(point.lat().toString().replace('.', ','), point.lng().toString().replace('.', ','));
    else
    {
		Recalculer();
    }
}

var add1 = null;
var add2 = null;
var add3 = null;

function GeolocaliserZoom(Adresse, CP, Ville, Titre, Pays, zoom)
{
	Geolocaliser(Adresse, CP, Ville, Titre, Pays);
	map.setZoom(zoom);
}

function Geolocaliser(Adresse, CP, Ville, Titre, Pays)
{
    var geocoder = new GClientGeocoder();

    function showAddress(Adresse, CP, Ville, Pays) {
      add1=Adresse + ", " + CP + ", " + Ville;
      geocoder.getLatLng(
        add1,
        function(point)
        {
            if (!point)
            {
                 if (Ville == "")
                 {
                     if (modeCarto == "BackOffice")
                     {
                         alert("Impossible de localiser automatiquement l'adresse saisie.\n\nVous pouvez positionner manuellement l'icone sur la carte.");
                         PlacerPoint(new GLatLng(parseFloat(latDefaut.replace(',', '.')), parseFloat(lngDefaut.replace(',', '.'))), Titre);
                     }
                     else
                     {
                        alert ("Impossible de geolocaliser : " + modeCarto + " " + idPoint + " (" + add1 + ")");
                        
                        if (document.getElementById("chargementEnCours") != null)
                            document.getElementById("chargementEnCours").style.display = "none";
                     }
                 }
                 else
                 {
                     add2=Ville;
                     geocoder.getLatLng(
                         add2,
                         function(point)
                         {
                             if (!point)
                             {
								 if (modeCarto == "BackOffice")
								 {
									 alert("Impossible de localiser automatiquement l'adresse saisie.\n\nVous pouvez positionner manuellement l'icone sur la carte.");
									 PlacerPoint(new GLatLng(parseFloat(latDefaut.replace(',', '.')), parseFloat(lngDefaut.replace(',', '.'))), Titre);
								 }
								 else
								 {
									alert ("Impossible de geolocaliser : " + modeCarto + " " + idPoint + " (" + add2 + ")");
                                    
                                    if (document.getElementById("chargementEnCours") != null)
                                        document.getElementById("chargementEnCours").style.display = "none";
								 }
                             }
                             else
                                 PlacerPoint(point, Titre);
                         }
                    );
                }
            }
            else
                PlacerPoint(point, Titre);
         }
       );
    }

    showAddress(Adresse, CP, Ville, Pays)
}

function ChargerGMaps()
{
    // charger google maps
    if (GBrowserIsCompatible())
    {
	    map = new GMap2(document.getElementById("map"));

        if (modeCarto == "BackOffice" || (adressePoint != "" && nomPoint != ""))
        {
            GEvent.addListener(map, "load", function()
            {
                if (latPoint != "" && lngPoint != "" && latPoint != "0" && lngPoint != "0")
                {
                    PlacerPoint(new GLatLng(parseFloat(latPoint.replace(',', '.')), parseFloat(lngPoint.replace(',', '.'))), nomPoint);
                }
                else if (adressePoint + cpPoint + villePoint + nomPoint)
                {
                    Geolocaliser(adressePoint, cpPoint, villePoint, nomPoint, paysPoint);
                }
            });

    	    PositionnePoints(paramCarto, 1, modeCarto);
        }
	else
	{
            // configure gmaps
            map.enableDoubleClickZoom();
	    map.enableContinuousZoom();
	    map.enableScrollWheelZoom();

    	    PositionnePoints(paramCarto, 2, modeCarto);
	}
/*	    
        if (modeCarto == "BackOffice")
    	    PositionnePoints(paramCarto, 1, modeCarto);
    	else
    	    PositionnePoints(paramCarto, 2, modeCarto);
*/
    }

    //Geolocaliser();
}

function addEvent(elm, evType, fn, useCapture)
{
    if(elm.addEventListener)
    {
        elm.addEventListener(evType, fn, useCapture);
        return true;
    }
    else if (elm.attachEvent)
    {
        var r = elm.attachEvent('on' + evType, fn);
        return r;
    }
    else
    {
        elm['on' + evType] = fn;
    }
}

addEvent(window, 'load', ChargerGMaps, false)
addEvent(window, 'unload', GUnload, false)

