// JavaScript Document
var map;
var current_info = null;
var markers = new Array();
var infowindows = new Array();

function display_marker(id){
	for(var i = 0; i < markers.length; i++){
		if (markers[i].agency_id == id) {
			if( current_info ) {
				current_info.close();
			}
			current_info = infowindows[i];
			current_info.open(map, markers[i]);
			break;
		}
	}
}

function attach_info(marker, text){

	var infowindow = new google.maps.InfoWindow(
		{
			content: text
		}
	);

	infowindows.push(infowindow);

	google.maps.event.addListener(marker, 'click',
		function()
		{
			if( current_info ) {
				current_info.close();
			}
			current_info = infowindow;
			infowindow.open(map, marker);
		}
		);
}

function load_map(agencies){

	// Création de la carte
	var options = {
		zoom: agencies['zoom'],
		center: new google.maps.LatLng(agencies['latitude'], agencies['longitude']),
		mapTypeId: google.maps.MapTypeId.ROADMAP,
		navigationControl: false
	};


	map = new google.maps.Map(
		$("map_canvas"),
		options
		);

	// Ajout des marker
	for (var index in agencies) {

		if (agencies[index] instanceof Object) {

			var agency = agencies[index];

			var marker = new google.maps.Marker(
			{
				position: new google.maps.LatLng(agency.latitude, agency.longitude),
				map: map,
				title:agency.title
			}
			);

			attach_info(marker, agency.info);

			markers.push(marker);

		}
	}

}

function initialize_map() {

	// Récupérer les données pour afficher les agences
	new Ajax.Request('get_agencies_map_data.php', {
		method: 'get',
		onComplete: function(requester){
			load_map(eval('(' + requester.responseText + ')'));
		}
	});

}

function position_and_zoom(latitude, longitude, zoom) {
	map.panTo(new google.maps.LatLng(latitude, longitude));
	map.setZoom(zoom);
}
