/*
-- Petite classe pour simplifier l'utilisation de la Google Map
-- Compatible avec le Framework PHP
-- Author : Julien POUILLARD
*/

var GoogleMapAPI = new Class({

	followUrl:false,
	markers: [],
	directions:null,

	/* Crée la Google Map */
	create: function(config)
	{
		var mapSize = new GSize(400, 400);

		for(id in config)
		{
			switch(id)
			{
				case 'name': this.name = config[id];
				case 'size': mapSize = new GSize(config[id]['width'], config[id]['height']);
			}
		}

		var mapOptions = {size:mapSize/*, googleBarOptions:{onSearchCompleteCallback:function(p1) {dump(p1.results[0]);}}*/};

		if(GBrowserIsCompatible())
		{
			if(this.checkMap())
			{
				this.map = new GMap2(document.getElementById(this.name), mapOptions);
				document.onunload = function() { GUnload(); };
				this.map.setCenter(new GLatLng(1, 1))
			}
			else alert("Element "+this.name+" manquant.");
		}
		else alert('Votre navigateur ne peut pas afficher la carte.');
	},

	/* Ajoute un marker sur la map */
	createMarker: function(marker)
	{
		if(typeof this.markers[marker['company_id']] != 'undefined') return false;

		if(marker['lat'] == 0 || marker['lon'] == 0)
		{
			//this.setLatLng(marker);
			return false;
		}

		var point = new GLatLng(marker['lat'], marker['lon']);

		var gmarker = null;
		if(marker['icon'] == 0) gmarker = new GMarker(point);
		else gmarker = new GMarker(point, {'icon':icons[marker['icon']]});

		if(this.followUrl && marker['url'] !== false)
		{
			GEvent.addListener(gmarker, 'click', function() { document.location = marker['url']; });
		}
		else if(isArray(marker['html'])) { GEvent.addListener(gmarker, 'click', function() { gmarker.openInfoWindowTabsHtml(marker['html']); }); }
		else { GEvent.addListener(gmarker, 'click', function() { var options = {maxWidth:300}; gmarker.openInfoWindowHtml(marker['html'], options); }); }

		this.map.addOverlay(gmarker);
		this.markers[marker['company_id']] = gmarker;
	},

	/* Construit un marker à partir d'un objet JSON */
	makeMarker: function(config)
	{
		var marker = [];
		marker['company_id'] = typeof config.company_id == 'undefined' ? 0 : config.company_id;
		marker['address'] = typeof config.address == 'undefined' ? 'FR' : config.address;
		marker['html'] = typeof config.html == 'undefined' ? '<div></div>' : config.html;
		marker['icon'] = typeof config.icon == 'undefined' ? 0 : config.icon;
		marker['lat'] = typeof config.lat == 'undefined' ? 0 : config.lat;
		marker['lon'] = typeof config.lon == 'undefined' ? 0 : config.lon;
		marker['url'] = typeof config.url == 'undefined' ? false : config.url;
		return marker;
	},

	setLatLng: function (marker)
	{
		var myRequest = new Request.JSON({
			method: 'post', 
			url: 'ajax.php'
			});
		var req = 'module=geocoder&id='+marker['company_id'];
		myRequest.send(req);
	},

	/* Affiche le marker au centre de la map */
	setCenter: function(marker, zoom, maptype)
	{
		var center = new GLatLng(marker['lat'], marker['lon']);
		this.map.setCenter(center, zoom, maptype);
		this.map.savePosition();
	},

	/* Affiche un marker à partir de son address */
	createMarkerByAddress: function(marker, ind)
	{
		/*var geocoder = new GClientGeocoder();
		geocoder.getLatLng(marker['address'], function (coord)
		{
			if(coord)
			{
				marker['lat'] = coord.lat();
				marker['lon'] = coord.lng();
				if(marker['lat'] != 0 && marker['lon'] != 0)
				{
					this.createMarker(marker);
				}
			}
		});*/
	},

	/* Règle l'affichage de façon à ce que tous les markers soit visible */
	focusMap: function()
	{
		var max = this.markers.length;
		var min_lng, max_lng, min_lat, max_lat;
		var first = true;

		if(max == 0) return false;

		for(id in this.markers)
		{
			// On ne regarde que les markers (on exclue tout autre object)
			if(typeof this.markers[id] == 'object' && !isNaN(id.toInt()))
			{
				var coords = this.markers[id].getLatLng();
				if(first)
				{
					min_lng = coords.lng();
					max_lng = coords.lng();
					min_lat = coords.lat();
					max_lat = coords.lat();
					first = false;
				}
				else
				{
					if(coords.lng() < min_lng) min_lng = coords.lng();
					if(coords.lng() > max_lng) max_lng = coords.lng();
					if(coords.lat() < min_lat) min_lat = coords.lat();
					if(coords.lat() > max_lat) max_lat = coords.lat();
				}
			}
		}

		/*if(min_lng < 0 && max_lng < 0)
		{
			var bds = new GLatLngBounds(
				new GLatLng(max_lat, max_lng),
				new GLatLng(min_lat, min_lng) 
				);
		}
		else
		{*/
			var bds = new GLatLngBounds(
				new GLatLng(min_lat, min_lng), 
				new GLatLng(max_lat, max_lng)
				);
		//}

		this.map.setCenter(bds.getCenter(), this.map.getBoundsZoomLevel(bds));
		this.map.savePosition();
	},

	/* Affiche le marker au centre de la map */
	focusMarker: function(marker_id)
	{
		if(typeof this.markers[marker_id] != 'undefined')
		{
			this.map.panTo(this.markers[marker_id].getLatLng());
		}
	},

	makeDirection: function(query, element)
	{
		if(this.directions === null) this.directions = new GDirections(this.map, element);
		else this.directions.clear();
		this.directions.load(query,{"locale": "fr"});
	},

	/* Vérifie que la map est bien présente */
	checkMap: function()
	{
		var check = true;
		if(document.getElementById(this.name) == 'undefined' || document.getElementById(this.name) == null) check = false;
		return check;
	},

	clear: function()
	{
		this.markers = [];
		this.map.clearOverlays();
	}
});

function isArray(a) {return isObject(a) && a.constructor == Array;}
function isObject(a) {return (a && typeof a == 'object') || isFunction(a);}
function isFunction(a) {return typeof a == 'function';}
