////////////////////////////////////////////

/** 
* Initialise les messages (d'erreur notamment) qui seront affichés à l'utilisateur
* @var string browser_support Incompatiblité de navigateur
* @var string show_on_map Afficher sur la carte
* @var string loading Chargement en cours
* @var string map Carte
* @access  private 
*/
function carteMessages(browser_support, show_on_map, loading, map)
{
    this.browser_support = browser_support;
    this.show_on_map = show_on_map;
    this.loading = loading;
    this.map = map;
}

////////////////////////////////////////////

/** 
* Contructeur
* @var string divCarte Le div où afficher la carte Google
* @var string external_object_name Le nom donné à la carte Google
* @var string messages Les messages initialisés plus haut
* @access  private 
*/
function cartographieGoogle(divCarte, external_object_name, messages)
	{
	// Les messages
	this.messages = messages;
	
	// Si le navigateur est compatble avec Google Maps
	if (GBrowserIsCompatible()) 
		{
		// Objet carte
		this.map = new GMap2(document.getElementById(divCarte));
		
		// Ajouter les menus de zoom et de déplacement
		this.map.addControl(new GLargeMapControl());
		//this.map.addControl(new GSmallMapControl());
		
		// Ajouter le menus permettant d'alternet le mode carte/satellite/les 2
		// this.map.addControl(new GMapTypeControl());
		
		// Ajouter la petite fenetre zoom en bas à droite
		this.map.addControl(new GOverviewMapControl());
		//this.map.addControl(new GScaleControl()) ;
		
		// Le tableau qui va contenir les références aux communes
		this.markers = Array();
		
		// La residence en cours
		this.residence = null;
		
		// Initialisation des variables
		this.xml_source = null;
		this.iframeInfo = null;
		this.xml_doc = null;
		
		// VARIABLES
		this.niveauZoom = 8;
		this.latitudeInitiale = 48.45;
		this.longitudeInitiale = 1.5;
		this.xml_source = "bdd/communes.xml";
		this.nomIframe = "divInformations";
		this.fichierCommune = "lister_communes.php";
		
		// L'objet carte
		this.external_object_name = external_object_name;
		} // FIN if (GBrowserIsCompatible())
	else 
		{
			// Si non compatible, on l'indique à l'utilisateur et on le renvoie sur une page d'erreur
		alert(this.messages.browser_support);
		window.location.replace("erreur.php");
		}
	} // FIN function cartographieGoogle(divCarte, external_object_name, messages)

////////////////////////////////////////////

/** 
* Création du texte Html qui sera affiché dans l'info Bulle et dans l'iframe d'information
* @var string infosCommune Le texte du fichier XML des communes
* Return du texte html
* @access  private 
*/
cartographieGoogle.prototype.creerHtmlInfosCommunes = function(infosCommune)
	{
	var html = "<table><tr><td>";
	
	var codePostal = infosCommune.getAttribute("codePostal");
	var commune = infosCommune.getAttribute("commune");
	
	html += "<b>"+commune+"</b> ("+codePostal+")";
	html += "</td></tr></table>";
	
	return html;
	} // FIN cartographieGoogle.prototype.creerHtmlInfosCommunes

////////////////////////////////////////////

/** 
* Constructeur d'icones
* Créer une icone à partir d'un ichier image png ou gif
* @var string imageUrl L'url de l'image
* Return Renvoie l'objet icone
* @access  private 
*/
cartographieGoogle.prototype.createIcon = function (imageUrl, iSize, shadowUrl, sSize, iconAnchor, bubbleAnchor)
	{
	var icon = new GIcon();
	
	// L'url de l'image utilisée pour l'icone
	icon.image = imageUrl;
	// Sa taille
	icon.iconSize = iSize;
	// icon.shadow = shadowUrl;
	// icon.shadowSize = sSize;
	
	// Gérer où placer l'icone selon le point de (latitude, longitude)
	// Le décalage (x,y) de l'icone
	icon.iconAnchor = iconAnchor;
	// Le décalage (x,y) de l'info bulle de l'icone
	icon.infoWindowAnchor = bubbleAnchor;
	
	return icon;
	}

////////////////////////////////////////////

/** 
* Créer un objet sur la carte Google pour les communes
* Return Renvoie l'objet
* @access  private 
*/
cartographieGoogle.prototype.creerMarqueurCommune = function(point, icon, codeInsee, html)
	{
	// Gérer les icones
	var marker = new GMarker(point, icon);
	var self = this;
	
	// Gestion des évènements liés à cet objet
	// Sur le passage souris, affiche une Info Bulle
	GEvent.addListener(marker, "mouseover", function()
		{
		marker.openInfoWindowHtml(html);
		});
	
	// Lors du click, on affiche les résidences présentes sur cette commune
	GEvent.addListener(marker, "click", function()
		{
		self.afficherResidence(codeInsee);
		});

	// Si on a la (longitude,latitude) alors on affiche cette résidence sur la carte
	// et on ouvre une infobulle
	GEvent.addListener(marker, "allerA", function()
		{		
		if (point.y == '0')	
			{
			alert("Pas de localisation disponible");
			}
		else
			{
			marker.openInfoWindowHtml(html);
			self.allerAPosition(point.y, point.x, 12);
			}
		});

	return marker;
	} // FIN cartographieGoogle.prototype.creerMarqueurCommune = function(point, icon, codeInsee, html)

////////////////////////////////////////////

/** 
* Créer un objet sur la carte Google pour les résidences
* Return Renvoie l'objet
* @access  private 
*/
cartographieGoogle.prototype.creerResidence = function(point, icon, html)
	{
	// Gérer les icones
	var marker = new GMarker(point, icon);
	var self = this;

	// Gestion des évènements liés à cet objet
	// Sur le passage souris, affiche une Info Bulle
	GEvent.addListener(marker, "mouseover", function()
		{
		marker.openInfoWindowHtml(html);
		});

	// Si on a la (longitude,latitude) alors on affiche cette résidence sur la carte
	// et on ouvre une infobulle
	GEvent.addListener(marker, "allerA", function()
		{		
		if (point.y == '0')	
			{
			alert("Pas de localisation disponible");
			}
		else
			{
			marker.openInfoWindowHtml(html);
			self.allerAPosition(point.y, point.x, 15);
			}
		});
	return marker;
	} // FIN cartographieGoogle.prototype.creerResidence = function(point, icon, html)

////////////////////////////////////////////

/** 
* Ouvrir une info bulle sur un marker
* On appelle l'évènement mouseover du marker
* @access  private 
*/
cartographieGoogle.prototype.ouvrirInfoBulle = function(codeInsee)
	{
	if (this.markers[codeInsee]==undefined)
		{
		alert("Pas de logement disponible sur cette commune");
		}
	else
		{
		GEvent.trigger(this.markers[codeInsee], "allerA");
		}
	} // FIN cartographieGoogle.prototype.ouvrirInfoBulle = function(idBulle)

////////////////////////////////////////////

/** 
* Création du point à afficher sur la carte Google pour une résidence
* @access  private 
*/
cartographieGoogle.prototype.afficherPictoResidence = function(longitude, latitude, infosResidence)
	{
	// On enlève la résidence précédemment crée
	if (this.residence)
		{ this.map.removeOverlay(this.residence); }
	
	// Icone résidence
	var residenceIcone = this.createIcon("images/batiments.gif", new GSize(22, 22),
											"images/batiments.gif", new GSize(22, 22),
											new GPoint(20, 20), new GPoint(10, 1));
	
	// Le point à afficher
	var point = new GPoint(parseFloat(longitude), parseFloat(latitude));	
	
	residenceCree = this.creerResidence(point, residenceIcone, infosResidence);
	
	// Cette résidence est la résidence en cours
	this.residence = residenceCree;
	
	// On ajoute ce point à la carte Google
	this.map.addOverlay(residenceCree);
	
	// On affiche ce point sur la carte
	GEvent.trigger(residenceCree, "allerA");
	}

////////////////////////////////////////////

/** 
* On affiche la liste des résidences d'une commune dans l'iframe
* @access  private 
*/
cartographieGoogle.prototype.afficherResidence = function(codeInsee)
	{
	// On enlève la résidence précédemment crée
	if (this.residence)
		{ this.map.removeOverlay(this.residence); }

	this.iframeInfo.src = "lister_residences.php?codeInsee="+codeInsee;
	} // FIN cartographieGoogle.prototype.afficherResidence = function(codeInsee)

////////////////////////////////////////////

/** 
* Lecture du fichier XML des communes
* @access  private 
*/
cartographieGoogle.prototype.chargerFichierCommunes = function()
	{
	// Vérifier si ok
	if (this.xml_source != null) 
		{
		// Fool the async callback
		var self = this;
		var request = GXmlHttp.create();
		
		// Ouvrir le fichier
		request.open("GET", this.xml_source, true);
		
		// Parse le fichier
		request.onreadystatechange = function() 
			{
			if (request.readyState == 4) 
				{
				// Traitement du fichier
				self.listerCommunes(request.responseXML);
				}
			}
		request.send(null);
		} // FIN if (this.xml_source != null) 
	else 
		{
		return false;
		} // FIN else
	} // FIN cartographieGoogle.prototype.chargerFichierCommunes = function()

///////////////////////////////////////////////

/** 
* On traite le fichier XML des communes afin de créer les points sur la carte Google
* @access  private 
*/
cartographieGoogle.prototype.listerCommunes = function(xml_doc)
	{
	// Icone 
	var communeIcone = this.createIcon("images/communes.gif", new GSize(22, 22),
										"images/communes.gif", new GSize(22, 22),
										new GPoint(10, 27), new GPoint(10, 1));
	
	// Parse le XML
	var markers = xml_doc.documentElement.getElementsByTagName("marker");
	
	// Pour chaque commune
	for (var i = 0; i < markers.length; i++) 
		{
		var codeInsee = markers[i].getAttribute("codeInsee");		
		var point = new GPoint( parseFloat(markers[i].getAttribute("lng")), parseFloat(markers[i].getAttribute("lat")));						
		
		// Les infos à afficher dans l'infobulle et dans l'iframe
		var html = this.creerHtmlInfosCommunes(markers[i]);
		
		// Le lien pour afficher les résidences de cette commune
		html += "<a href=\"javascript:" + this.external_object_name +".afficherResidence('" + codeInsee + "');\">Afficher les residences</a>";		
		
		marker = this.creerMarqueurCommune(point, communeIcone, codeInsee, html);
		
		// On ajoute cette commune à la liste des communes
		this.markers[codeInsee] = marker;
		
		// On ajoute ce point à la carte Google
		this.map.addOverlay(marker);
		} // FIN for (var i = 0; i < markers.length; i++)
	} // FIN cartographieGoogle.prototype.listerCommunes = function(xml_doc)

//////////////////////////////////////

/** 
* Initialisation et création de la carte Google
* @access  private 
*/
cartographieGoogle.prototype.redraw = function()
	{
	// On vide le tablea des communes
	
	for (i = 0;i < this.markers.length;i++) 
		{
		this.map.removeOverlay(this.markers[i]);
		}

	// On vide la résidence courante
	if (this.residence)
		{ this.map.removeOverlay(this.residence); }

	// Affecte le fichier XML
	this.setXmlSourceUrl(this.xml_source);
	
	// Affecte l'iframe où seront affichées les informations
  this.setIframeInfos(this.nomIframe);	

	// Centre la carte sur ce point
	// Ex: sur Chartres
  this.setInitialPosition();
	
  //this.setMapType(G_MAP_TYPE);

	// Lecture du fichier XML des communes
	this.chargerFichierCommunes();	

	/*
	var bounds2 = new GLatLngBounds(
				new GLatLng(50, 1.5),
				new GLatLng(46.28, -0.59)
		); */
/*
	var bounds = this.map.getBounds();
	var southWest = bounds.getSouthWest();
	var northEast = bounds.getNorthEast();
	var lngDelta = (northEast.lng() - southWest.lng()) / 4;
	var latDelta = (northEast.lat() - southWest.lat()) / 4;
	
	var bounds2 = new GLatLngBounds(
			new GLatLng(southWest.lat() + latDelta, southWest.lng() + lngDelta),
			new GLatLng(northEast.lat() - latDelta, northEast.lng() - lngDelta));
*/
	/*var bounds2 = new GLatLngBounds(
				new GLatLng(southWest.lat(), southWest.lng()),
				new GLatLng(northEast.lat(), northEast.lng())
		);*/


	//this.map.addOverlay(new ImageOpac(bounds2, "images/eureetloir.png"));

	} // FIN cartographieGoogle.prototype.redraw = function()

////////////////////////////////////////////

/** 
* Affectation du div où seront affichées les infos
* @access  private 
*/
cartographieGoogle.prototype.setAssocesInfoList = function(divInfos)
{
    this.divInfos = document.getElementById(divInfos);
}

////////////////////////////////////////////

/** 
* Affectation de l'iframe où seront affichées les infos
* @access  private 
*/
cartographieGoogle.prototype.setIframeInfos = function(iframeInfos)
	{
	this.iframeInfo = document.getElementById? document.getElementById(iframeInfos): document.all? document.all[iframeInfos]: null;
	}

////////////////////////////////////////////

/** 
* Affectation du div d'initialisation
* @access  private 
*/
cartographieGoogle.prototype.setAssocesInit = function(divInit)
{
    this.divInit = document.getElementById(divInit);
}

////////////////////////////////////////////

/** 
* Permet de réinitialiser la carto pour afficher ce qu'on voit 
* quand on arrive la première fois sur la carte
* @access  private 
*/
cartographieGoogle.prototype.revenirAccueil = function()
	{
	var self = this;
	
	// Supprime la résidence courante de la carte
	if (this.residence)
		{ this.map.removeOverlay(this.residence); }
	this.residence = null;
	
	// On affecte à l'iframe le fichier lister_commune
	this.iframeInfo.src = this.fichierCommune;
	
	// On réinitialise la carto
	self.setInitialPosition();
	}

////////////////////////////////////////////

/** 
* Permet de réinitialiser la carto pour afficher Chartres 
* et son agglomération
* @access  private 
*/
cartographieGoogle.prototype.allerAChartres = function()
	{
	var self = this;
	
	// Supprime la résidence courante de la carte
	if (this.residence)
		{ this.map.removeOverlay(this.residence); }
	this.residence = null;
	
	// On affecte à l'iframe le fichier lister_commune
	this.iframeInfo.src = this.fichierCommune;

	// On réinitialise la carto
	self.allerAPosition(this.latitudeInitiale,this.longitudeInitiale, 12);
	}

////////////////////////////////////////////

/** 
* Permet de centrer la carto sur le point d'initialisation
* @access  private 
*/
cartographieGoogle.prototype.setInitialPosition = function()
	{
	this.map.setCenter(new GLatLng(this.latitudeInitiale,this.longitudeInitiale), this.niveauZoom);
	}

////////////////////////////////////////////

/** 
* Permet de centrer la carto sur un point dont les coordonnées sont passés en argument
* @access  private 
*/
cartographieGoogle.prototype.allerAPosition = function(lat, lng, zoom)
	{
	this.map.setCenter(new GLatLng(lat,lng), zoom);
	}

////////////////////////////////////////////

cartographieGoogle.prototype.setMapType = function(map_type)
	{
	this.map.setMapType(map_type);
	}

////////////////////////////////////////////

cartographieGoogle.prototype.setXmlSourceUrl = function(xml_source)
	{
	this.xml_source = xml_source;
	}

////////////////////////////////////////////
////////////////////////////////////////////




function ImageOpac(bounds, imgsrc) {
  this.bounds_ = bounds;
  this.imgsrc_ = imgsrc;
}
ImageOpac.prototype = new GOverlay();

// Creates the DIV representing this rectangle.
ImageOpac.prototype.initialize = function(map) {
  // Create the DIV representing our rectangle
  var div = document.createElement("img");
  div.setAttribute("src", this.imgsrc_);
  div.style.position = "absolute";
  
  // Our rectangle is flat against the map, so we add our selves to the
  // MAP_PANE pane, which is at the same z-index as the map itself (i.e.,
  // below the marker shadows)
 map.getPane(G_MAP_MAP_PANE).appendChild(div);

  this.map_ = map;
  this.div_ = div;
}

// Remove the main DIV from the map pane
ImageOpac.prototype.remove = function() {
  this.div_.parentNode.removeChild(this.div_);
}

// Copy our data to a new Rectangle
ImageOpac.prototype.copy = function() {
  return new Rectangle(this.bounds_, this.imgsrc_);
}

// Redraw the rectangle based on the current projection and zoom level
ImageOpac.prototype.redraw = function(force) {
  // We only need to redraw if the coordinate system has changed
  if (!force) return;

  // Calculate the DIV coordinates of two opposite corners of our bounds to
  // get the size and position of our rectangle
  var c1 = this.map_.fromLatLngToDivPixel(this.bounds_.getSouthWest());
  var c2 = this.map_.fromLatLngToDivPixel(this.bounds_.getNorthEast());

  // Now position our DIV based on the DIV coordinates of our bounds
  this.div_.style.width = Math.abs(c2.x - c1.x) + "px";
  this.div_.style.height = Math.abs(c2.y - c1.y) + "px";
  this.div_.style.left = Math.min(c2.x, c1.x) + "px";
  this.div_.style.top = Math.min(c2.y, c1.y) + "px";
}
