/**
*	GOOGLE MAP CLASS
*
*	Classe de gestion des "Google Map" - nécéssite prototype
*
*	par Lisaraël, 18 avril 2007
*/
// ==========================================================================================

/* 
* Contructeur: GMapAPI()
*
*	@params:	
*		- mapDiv: id de l'élément qui va recevoir la map 		(string)
*		- startLat: latitude de départ 						(float)
*		- startLong: longitude de départ 						(float)
*		- startZoom: niveau de zoom de départ					(float)
*		- controlType: type des contrôles de la map				(enum of string: "full", "small", "switchOnly", "none" - default = "full")
*/
function GMapAPI(mapDiv, startLat, startLong, startZoom, controlType, tools) 
{
	// déclaration des variables
	this.map;
	this.indicator = "http://www.napyfab.com/ajax-indicators/images/live_com_loading.gif";
	this.markersInViewport = new Array(); // futur tableau qui contiendra tous les marqueurs du viewport
	
	// vérification de la compatibilité du browser avant la création de l'objet
	if ( !GBrowserIsCompatible() ) 
	{
		alert("Attention !\n\nVotre navigateur n'est pas compatible avec Google Map.");
		return false;
	}
	// création de l'objet
	this.map = new GMap2( $(mapDiv) );
	// centrage de la map sur le point défini
	this.map.setCenter(new GLatLng(startLat, startLong), startZoom);
	this.map.enableDoubleClickZoom();
	// définition des contrôles
	if( typeof(controlType) == "undefined" ) controlType = "full";
	switch(controlType) {
		case "full":
			this.map.addControl( new GLargeMapControl() );
			this.map.addControl( new GMapTypeControl() );
			break;
		case "small":
			this.map.addControl( new GSmallMapControl() );
			this.map.addControl( new GMapTypeControl() );
			break;
		case "switchOnly":
			this.map.addControl( new GMapTypeControl() );
			break;
	}
	// création d'un objet geocoder, nommé localise
	this.localise = new GClientGeocoder();
	
	// activation des bulles d'alert sur un onclick sur la map
	if(tools) {
		GEvent.addListener(this.map, "click", function(overlay, point) {
			alert("Coordonnées du point :\n\nLatitude : "+(Math.round(point.x * 10000)/10000)+"\nLongitude : "+(Math.round(point.y * 100)/100));
		});	
	}
} // GMapAPI

// création d'un objet icône de marqueur
GMapAPI.prototype.createIcon = function(iconObj, shadowObj) 
{
	var icon = new GIcon();
		icon.image = iconObj.url;
		icon.shadow = (!shadowObj) ? "" : shadowObj.url; 
		icon.iconSize = new GSize(iconObj.w, iconObj.h);
		if( icon.shadow != "" ) icon.shadowSize = new GSize(shadowObj.w, shadowObj.h);
		icon.iconAnchor = new GPoint(iconObj.cX, iconObj.cY);
		icon.infoWindowAnchor = new GPoint(12, 4);
		
	return icon;
} // createIcon

// création d'un marqueur
GMapAPI.prototype.createMarker = function(obj)
{
	// vérification de la présence d'une icône, sinon récupération de l'icône par défaut
	iconRef = ( typeof(obj.icon) == "undefined" || !obj.icon ) ? this.G_DEFAULT_ICON : obj.icon;
	// création du marqueur
	var marker = new GMarker(new GLatLng(obj.latitude, obj.longitude), {title:obj.name, icon:iconRef, draggable:obj.drag } );
	// création de la bulle d'info au click si demandé, avec récupération de contenu par ajax ou directement dans la page
	if( typeof(obj.info) == "string" ) {
		GEvent.addListener(marker, "click", function() {
			marker.openInfoWindowHtml( $(obj.info).innerHTML );
		});	
	} else if( typeof(obj.info) == "object" && typeof(obj.info.url) == "string" ) 
	{
		objectRef = this;
		GEvent.addListener(marker, "click", function() {
			marker.openInfoWindowHtml( '<div style="text-align: center"><br /><img alt="" src="../Knauff/'+objectRef.indicator+'" /><br />chargement des infos...</div>' );
			var params = (obj.info.params != "") ? obj.info.params : "";
			new Ajax.Request(obj.info.url, {
							 		method: "post",
									// parameters: obj.info.params, 
									onComplete: function(req) {
										var content = (req.responseText == "") ? '<div style="text-align: center"><br /><strong>Erreur: impossible de charger les infos.</strong></div>' : req.responseText;
										marker.openInfoWindowHtml(content);
									}
							 });
		});	
	}
	
	// ajout à la carte
	this.map.addOverlay(marker);
	
	this.markersInViewport.push(marker);
	
	return marker;
} // createMarker

// chargement de plusieurs marqueurs
GMapAPI.prototype.loadMarkers = function(markersObj) 
{
	var tempObj = this;
	$A(markersObj).each(
		function(elt) {
			elt = tempObj.createMarker(elt);
		}					
	);
} // loadMarkers

// gestion de la reconnaissance d'un point depuis une adresse textuelle donnée
GMapAPI.prototype.showAddress = function(address, windowInfo, extendMap, iconObj) 
{
	var tempObj = this;
	this.localise.getLatLng(address, function(point) {
		if (!point) {
			alert("L'adresse \""+address+"\" \nne semble pas exister.");
		} else {
			var marker = new GMarker(point, {title: address, icon: iconObj});
			tempObj.map.addOverlay(marker);
			tempObj.markersInViewport.push(marker);
			if(extendMap) 
			{
				var actualMapBounds = tempObj.map.getBounds();
				if( !actualMapBounds.contains(point) ) {
					tempObj.extendViewport(actualMapBounds);	
				}
			} else {
				tempObj.map.setCenter(point, 13);	
			}
			if(windowInfo) marker.openInfoWindowHtml(address);
		}
	} );
} // showAddress

// étends le viewport pour qu'il contienne tous les marqueurs posés sur la carte
GMapAPI.prototype.extendViewport = function(actualMapBounds) 
{
	var minLat = this.markersInViewport.min(function(elt) { return elt.getPoint().lat(); } );
	var maxLat = this.markersInViewport.max(function(elt) { return elt.getPoint().lat(); } );
	var minLng = this.markersInViewport.min(function(elt) { return elt.getPoint().lng(); } );
	var maxLng = this.markersInViewport.max(function(elt) { return elt.getPoint().lng(); } );
	var newMapBounds = new GLatLngBounds(new GLatLng(minLat, minLng), new GLatLng(maxLat, maxLng));
	var oldZoomLevel = this.map.getBoundsZoomLevel(actualMapBounds);
	var newZoomLevel = this.map.getBoundsZoomLevel(newMapBounds);
	this.map.setCenter( newMapBounds.getCenter(), newZoomLevel-1 );
} // extendViewport