document.getElementById('body').onload = function(){
	
	/* Fonction de recentrage des svgOverlay dont le zéro est en haut à gauche
		alors qu'on le veut au milieu */
	// --------------------------------------------------------------------------
	function centrerSVG(latitudeLongitudeCentre,extension) {
		coinHautGaucheX = latitudeLongitudeCentre[0]+extension[0]/2
		coinHautGaucheY = latitudeLongitudeCentre[1]-extension[1]/2
		coinHautGauche = [coinHautGaucheX,coinHautGaucheY];
		coinBasDroiteX = latitudeLongitudeCentre[0]-extension[0]/2;
		coinBasDroiteY = latitudeLongitudeCentre[1]+extension[1]/2;
		coinBasDroite = [ coinBasDroiteX, coinBasDroiteY];
		return [[coinHautGaucheX,coinHautGaucheY],[coinBasDroiteX,coinBasDroiteY]];
	}
	// --------------------------------------------------------------------------
	
	// Déclaration des variables
	// --------------------------------------------------------------------------

	var centrePacifiqueSud = [-24.3763, -128.3184];
	var extensionPacifiqueSud = [50,50];
	var centrePacifiqueNord = [35, -180];
	var extensionPacifiqueNord = [100,100];
	var centreZero = [0, 0];
	var extensionZero = [90, 90];

	// La carte centrée et zoomée 
	// --------------------------------------------------------------------------
	// --------------------------------------------------------------------------
	var map = L.map('map', {
		center: [-7, -100],
		zoom: 2
	});//.setView([0, 0], 2);
	
   // Déclaration des fonds	
	var baselayers = {
		osm:L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
			maxZoom: 19,
			attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'			
		}),
		stamen:L.tileLayer('https://stamen-tiles-{s}.a.ssl.fastly.net/watercolor/{z}/{x}/{y}.jpg', {
    		maxZoom: 19,
    		attribution: 'Map tiles by <a href="https://stamen.com">Stamen Design</a>, under CC BY 4.0. Data by <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>, under <a href="http://creativecommons.org/licenses/by/4.0">CC BY SA</a>.'
		})
	};
	// Ajout du fond par défaut
	baselayers.stamen.addTo(map);
	// Ajout du menu de changement de fonds
	L.control.layers(baselayers, null, {position: 'topright', collapsed : false }).addTo(map);	

	// --------------------------------------------------------------------------
	// Définition des marqueurs
	var marker1 = L.marker([-42.5,69]).addTo(map)
    .bindPopup("La gyre de l'océan indien.")
    .openPopup();   
   
   // --------------------------------------------------------------------------
   // Définition des cercles 
   var rayon = 3000000   
	// Un cercle orange, remplis vert transparent -------------------------------
	var cercle1 = L.circle([-45, -130], rayon, {
	 color: 'black',
	 fill: 'true',
	 fillColor: '#101010',
	 fillOpacity: 0.2,
	}).addTo(map)
	.bindTooltip("Gyre du Pacifique Sud", 
    {
        permanent: true, 
        direction: 'left',
        offset: [0,0]
    });
	
	// --------------------------------------------------------------------------
	// Définition des polygones
	// Un polygone
/*	var polygon1 = L.polygon([
	    [61, -95],
	    [61, 4.3],
	    [7, 4.3],
	    [7, -95]
		],{color: "green"}).addTo(map);      
*/   
   // --------------------------------------------------------------------------
   // Définition des polylines
   var latlngs1 = [
    [0, -80],
    [0, 80]
	];

	var polyline = L.polyline(latlngs1, {color: 'green'}).addTo(map)
	.bindTooltip("Équateur : latitude 0°", 
    {
        permanent: true, 
        direction: 'right',
        offset: [60,0]
    });
	
   // --------------------------------------------------------------------------
	// Définition des overlays svg
	// La gyre de l'océan Indien  
	var coin20_0 = L.latLng(0, 23);
	var coin0_20 = L.latLng(-65, 115);
	var bounds1 = L.latLngBounds(coin20_0, coin0_20);   
   
   // Définition des calques (overlay)        
	var svgElement = document.createElementNS("http://www.w3.org/2000/svg", "svg");
	svgElement.setAttribute('xmlns', "http://www.w3.org/2000/svg");
	svgElement.setAttribute('viewBox', "0 0 100 100");
	svgElement.innerHTML = '<ellipse transform="rotate(-40 50 60)" cx="50" cy="60" rx="45" ry="30" stroke="black" stroke-opacity="1" fill-opacity="50%"/>';
	//svgElementBounds = centrerSVG(centreZero,extensionZero);
	//svgElementBounds = [map.layerPointToLatLng([0,0]),map.layerPointToLatLng([30,30])];
	var forme = L.svgOverlay(svgElement, bounds1);
	forme.addTo(map);
	
	// La gyre de l'Atlantique Sud
	var coin20_0 = L.latLng(0, -65);
	var coin0_20 = L.latLng(-70, 18);
	var bounds1 = L.latLngBounds(coin20_0, coin0_20);   
   
   // Définition des calques (overlay)        
	var svgElement = document.createElementNS("http://www.w3.org/2000/svg", "svg");
	svgElement.setAttribute('xmlns', "http://www.w3.org/2000/svg");
	svgElement.setAttribute('viewBox', "0 0 100 100");
	svgElement.innerHTML = '<path d="M 85,15 C 100,40 85,85 15,85 C 0,85 50,-55 85,15" stroke="black" stroke-opacity="1" fill-opacity="0%"/>\
	<image xlink:href="images/Mollweide_Cycle.gif" x="30" y="20" height="50" width="50" />';
	//svgElementBounds = centrerSVG(centreZero,extensionZero);
	//svgElementBounds = [map.layerPointToLatLng([0,0]),map.layerPointToLatLng([30,30])];
	var forme = L.svgOverlay(svgElement, bounds1);
	forme.addTo(map);
	
	// --------------------------------------------------------------------------
	// Définition des images overlay
	
	var imageUrl = 'images/North_Pacific_Gyre.png';
	var errorOverlayUrl = 'https://cdn-icons-png.flaticon.com/512/110/110686.png';
	var altText = 'Wikipedia : https://commons.wikimedia.org/wiki/File:North_Pacific_Gyre.png';
	var latLngBounds = L.latLngBounds([[66.6, -254.5], [-15.5, -105.2]]);

	var imageOverlay = L.imageOverlay(imageUrl, latLngBounds, {
    opacity: 1,
    errorOverlayUrl: errorOverlayUrl,
    alt: altText,
    interactive: true
	}).addTo(map)
	.bindTooltip("Gyre du Pacifique Nord", 
    {
        permanent: true, 
        direction: 'right',
        offset: [0,0]
    });
    
    // -------------------------------------------------------------------------
    // Définition des vidéos overlay
    // Attention, pour remplir latLngBound, il faut mettre à fill la propriété
    // css object-fit de la balise video.
    
    var videoUrls = [
    'images/GyreAtlantiqueNordPetitPetit.mp4'
	 ];
	 var errorOverlayUrl = 'https://cdn-icons-png.flaticon.com/512/110/110686.png';
	 var latLngBounds = L.latLngBounds([[57, -100], [3.5, 13]]);

    var videoOverlay = L.videoOverlay(videoUrls, latLngBounds, {
     opacity: 0.6,
     errorOverlayUrl: errorOverlayUrl,
     interactive: true,
     autoplay: true,
     muted: true,
     playsInline: true,
     keepAspectRatio: false
	}).addTo(map);
	
	// --------------------------------------------------------------------------
	// Définition de la légende
	function getColor(d) {
    return d === 'Océaniques'  ? "#5bc6da" :
           d === 'Terrestres'  ? "#e5c7a9" :
           d === 'Polaires' ? "#dadcd2" :
           d === 'Désertiques' ? "#e2ddcf" :
                 "#cd9474";
   }
	var legend = L.control({position: 'bottomleft'});
   legend.onAdd = function (map) {
   var div = L.DomUtil.create('div', 'info legend');
   labels = ['<strong>Surfaces</strong>'],
    categories = ['Océaniques','Terrestres','Polaires','Désertiques','Autres'];
   for (var i = 0; i < categories.length; i++) {
     div.innerHTML += 
     labels.push('<span style="display:inline-block;width:10px;height:10px;border-radius:5px;background:'+getColor(categories[i])+';"></span> '+categories[i]);
   }
   div.innerHTML = labels.join('<br>');
   return div;
   };
   legend.addTo(map);
   
   // --------------------------------------------------------------------------
   // Définition d'un grand cercle avec le plugin Leaflet.greatCircle permettant
   // des grand cercles correctement définis dans la projection de Mercator.
   var grandcercle = new L.greatCircle([-30, 110], {radius: 7000000});
	grandcercle.addTo(map);

	
onMapClick = function(e){
  popup = L.popup()
  popup.setLatLng(e.latlng)
  lepoint = map.latLngToLayerPoint(e.latlng);
  popup.setContent("Position : "+e.latlng+" et "+lepoint)
  popup.openOn(map);
  //console.log("Coordinate: #{e.latlng}")
  }

map.on('click', onMapClick)

};