/**
 * Module pour utiliser une carte google map
 * 	Ce script necessite que
 *		- l'api google soit chargée avant l'inclusion de celui-ci
 *		- le fichier des tranductions soit chargé
 *		- les variables suivantes soit déclarées
 *			- gm_icons_informations : Tableau associatif contenant les informations des icones
 *			- gm_map_name : le nom de l'objet contenant la map
 *			- gm_directions_name : le nom de l'objet contenant les directions
 *			- gm_lat_focus : la latitude du focus
 *			- gm_lon_focus : la longitude du focus
 *			- gm_zoom_focus : le zoom du focus
 *			- gm_markers : tableau associatif contenant la liste des latitudes, longitudes et type de marker à utiliser
 *
 *	exemple :
 *	<script type="text/javascript" src="http://maps.google.com/maps?file=api&v=2&key='.GOOGLE_MAP_KEY.'"></script>
 *	<script type="text/javascript" src="'.REP_LANGUES.$_SESSION['md_langue'].'/js_googlemap.js"></script>
 *	<script type="text/javascript" src="'.REP_SCRIPTS.'js/googlemap.js"></script>
 *	<script type="text/javascript">
 *		var gm_icon0 = new Array;
 *		gm_icon0["file"] = "media/images/carte/0.png";
 *		gm_icon0["largeur"] = 36;
 *		gm_icon0["hauteur"] = 28;
 *		gm_icon0["anchorX"] = 9;
 *		gm_icon0["anchorY"] = 27;
 *		var gm_icon1 = new Array;
 *		gm_icon1["file"] = "media/images/carte/1.png";
 *		gm_icon1["largeur"] = 36;
 *		gm_icon1["hauteur"] = 28;
 *		gm_icon1["anchorX"] = 9;
 *		gm_icon1["anchorY"] = 27;
 *		var gm_icons_informations = new Array
 *		gm_icons_informations["ico0"] = gm_icon0;
 *		gm_icons_informations["ico1"] = gm_icon1;
 * 		var gm_map_name = 'map';
 *		var gm_directions_name = 'directions';
 *		var gm_lat_focus = 'xxxx';
 *		var gm_lon_focus = 'yyyy';
 *		var gm_zoom_focus = z;
 *		var gm_m0 = new Array; gm_m0["lat"] = "xxxx"; gm_m0["lon"] = "yyyy"; gm_m0["type"] = "livree"; gm_m0["html"] = ""; gm_m0["open"] = false;
 *		var gm_m1 = new Array; gm_m1["lat"] = "xxxx"; gm_m1["lon"] = "yyyy"; gm_m1["type"] = "en_cours"; gm_m1["html"] = ""; gm_m1["open"] = true;
 *		var gm_m2 = new Array; gm_m2["lat"] = "xxxx"; gm_m2["lon"] = "yyyy"; gm_m2["type"] = "prevu"; gm_m2["html"] = ""; gm_m2["open"] = false;
 *		var gm_markers = new Array(gm_m0, gm_m1, gm_m2);
 *	</script>
 *
 * La construction de la carte se fait en appelant la fonction gm_makeMap();
 *
 * @author : Service Informatique
 * @version : 2008-02-12
 * @copyright : Monné-Decroix (service informatique)
 */

var gm_map;
function gm_makeMap(useControl){
	if(useControl == 'undefined' || useControl == null){
		useControl = true;
	}

	if (GBrowserIsCompatible()) { 
		// Display the map, with some controls and set the initial location
		gm_map = new GMap2(document.getElementById(gm_map_name));
		gm_map.disableDoubleClickZoom();
		if(useControl){
			gm_map.addControl(new GLargeMapControl());				// le controle de position et le zoom
			gm_map.addControl(new GMenuMapTypeControl(true,false));	// Le type de map (plan, photo, relief)
			//gm_map.addControl(new GScaleControl());					// L'echelle de la carte
		}
		gm_map.setCenter(new GLatLng(gm_lat_focus,gm_lon_focus), gm_zoom_focus);
		
		// On crée les markers si il y en a
		for(var i = 0; i < gm_markers.length; i++){
			if(gm_markers[i]['lat'] != 0 && gm_markers[i]['lon'] != 0){
				var point = new GLatLng(gm_markers[i]['lat'],gm_markers[i]['lon']);
				var marker = gm_createMarker(point, gm_markers[i]['html'], gm_markers[i]['type']);
				gm_map.addOverlay(marker);
				
				// On affiche la bulle si on le demande
				if(gm_markers[i]['open'] == true){
					marker.openInfoWindowHtml(markers_htmls[i]);
				}
			} else {
				//gm_showAddress(gm_markers[i]['address'], gm_markers[i]['html'], gm_markers[i]['type']);
			}
		}
		
		// Lance les events pour la direction
		gm_makeDirections();
	} else {
		// display a warning if the browser was not compatible
		alert("Sorry, the Google Maps API is not compatible with this browser");
	}
}
function gm_zoomMap(lat,lon,zoom){
	gm_lat_focus = lat;
	gm_lon_focus = lon;
	gm_map.setCenter(new GLatLng(gm_lat_focus,gm_lon_focus), zoom);
}
function gm_setSatellite() {
	gm_map.setMapType(G_SATELLITE_MAP);
}
function gm_setPlan() {
	gm_map.setMapType(G_NORMAL_MAP);
}
function gm_setZoom(num) {
	gm_map.setZoom(num);
}
function gm_center(){
	gm_map.setCenter(new GLatLng(gm_lat_focus,gm_lon_focus), gm_zoom_focus);
}
function gm_getZoom(){
	return gm_map.getZoom();
}
	
///// CIRCLE /////
var gm_circle;
var gm_circleDrawed = false;
function gm_drawCircle(radius, color, width, opacity, fillColor, fillOpacity){   
	var R = 6371; // earth's mean radius in km
	var lat = (gm_lat_focus * Math.PI) / 180; //rad
	var lon = (gm_lon_focus * Math.PI) / 180; //rad
	var d = parseFloat(radius)/R;  // d = angular distance covered on earth's surface
   
	var points = new Array();
	for (x = 0; x <= 360; x++){ 
		var latitude = 0;
		var longitude = 0;
		brng = x * Math.PI / 180; //rad
		latitude = Math.asin(Math.sin(lat)*Math.cos(d) + Math.cos(lat)*Math.sin(d)*Math.cos(brng));
		longitude = ((lon + Math.atan2(Math.sin(brng)*Math.sin(d)*Math.cos(lat), Math.cos(d)-Math.sin(lat)*Math.sin(latitude))) * 180) / Math.PI;
		latitude = (latitude * 180) / Math.PI;
	  
		var P = new GLatLng(latitude,longitude);
		points.push(P);
	}
   
	gm_circle = new GPolygon(points, color, width, opacity, fillColor, fillOpacity)
	gm_map.addOverlay(gm_circle);
	gm_circleDrawed = true;
}
function gm_removeCircle(){
	if(gm_circleDrawed){
		gm_map.removeOverlay(gm_circle);
	}
}
function gm_displayCircle(km, color, width, opacity, fillColor, fillOpacity){
	km = parseInt(km);
	gm_removeCircle();
	if(km > 0){
		gm_drawCircle(km, color, width, opacity, fillColor, fillOpacity);
	}
}
//////////////////
  
///// MARKER /////
var markers_i = 0;
var markers_save = [];
var markers_htmls = [];
var markers_to_htmls = [];
var markers_from_htmls = [];

// A function to create the marker and set up the event window
// Dont try to unroll this function. It has to be here for the function closure
// Each instance of the function preserves the contends of a different instance
// of the "marker" and "html" variables which will be needed later when the event triggers.    
function gm_createMarker(point, html, ico) {
	// Create icon
	//var Icon = new GIcon(G_DEFAULT_ICON, gm_icons_informations[ico]['file']);
	var Icon = new GIcon();
    Icon.image = gm_icons_informations[ico]['file'];
    Icon.iconSize = new GSize(gm_icons_informations[ico]['largeur'], gm_icons_informations[ico]['hauteur']); 
    Icon.iconAnchor = new GPoint(gm_icons_informations[ico]['anchorX'], gm_icons_informations[ico]['anchorY']);
    Icon.infoWindowAnchor = new GPoint(gm_icons_informations[ico]['anchorX'], gm_icons_informations[ico]['anchorY']);
	
	// Create marker
	var marker = new GMarker(point, Icon);
	
	// The info window version with the "to here" form open
	markers_to_htmls[markers_i] = html+'<table cellspacing="0">'+
		'<tr>'+
		'<td><hr><b>'+txt_gm_to_here+'</b> - <a href="javascript:gm_fromhere('+markers_i+')">'+txt_gm_from_here+'</a></td>'+
		'</tr>'+
		'<tr>'+
		'<td><form action="javascript:gm_getDirections()">'+txt_gm_start_address+'&nbsp;'+
		'<input type="text" size="30" maxlength="100" name="saddr" id="saddr" value="" style="font:10px Verdana;" />&nbsp;'+
		'<input value="Ok" type="submit" style="font:10px Verdana;">'+
		'<input type="hidden" id="daddr" value="'+name+"@"+ point.lat()+','+point.lng()+'"/></td>'+
		'</tr>'+
		'</table>';

	// The info window version with the "to here" form open
	markers_from_htmls[markers_i] = html+'<table cellspacing="0">'+
		'<tr>'+
		'<td><hr><a href="javascript:gm_tohere('+markers_i+')">'+txt_gm_to_here+'</a> - <b>'+txt_gm_from_here+'</b></td>'+
		'</tr>'+
		'<tr>'+
		'<td><form action="javascript:gm_getDirections()">'+txt_gm_end_address+'&nbsp;'+
		'<input type="text" size="30" maxlength="100" name="daddr" id="daddr" value="" style="font:10px Verdana;" />&nbsp;'+
		'<input value="Ok" type="submit" style="font:10px Verdana;">'+
		'<input type="hidden" id="saddr" value="'+name+"@"+ point.lat()+','+point.lng()+'"/></td>'+
		'</tr>'+
		'</table>';

	// The inactive version of the direction info
	html = html+'<table cellspacing="0">'+
		'<tr>'+
		'<td><hr><a href="javascript:gm_tohere('+markers_i+')">'+txt_gm_to_here+'</a> - <a href="javascript:gm_fromhere('+markers_i+')">'+txt_gm_from_here+'</a></td>'+
		'</tr>'+
		'</table>';
	
	markers_htmls[markers_i] = html;
	
	GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml(html);
		
		var pt = marker.getLatLng();
		gm_lat_focus = pt.lat();
		gm_lon_focus = pt.lng();
	});
	
	// save the info we need to use later for the side_bar
	markers_save[markers_i] = new Array;
	markers_save[markers_i]['obj'] = marker;
	markers_save[markers_i]['type'] = ico;
	//markers_save[markers_i] = marker;
  
	markers_i++;
	
	return marker;
}

function gm_showHideMarkerByType(type, action){
	if(action == 'undefined' || action == null){
		action = 'show';
	}

	for(var i = 0; i < markers_save.length; i++){
		if(markers_save[i]['type'] == type){
			if(action == 'show'){
				markers_save[i]['obj'].show();
			} else {
				if(action == 'hide'){
					markers_save[i]['obj'].hide();
				}
			}
		}
	}
}
//////////////////
	
///// DIRECTIONS /////
var gm_dir
function gm_makeDirections(){
	// === create a GDirections Object ===
	gm_dir = new GDirections(gm_map, document.getElementById(gm_directions_name));
	
	// === catch Directions errors ===
	GEvent.addListener(gm_dir, "error", function() {
		var code = gm_dir.getStatus().code;
		var reason="Code "+code;
		if (reasons[code]) {
			reason = reasons[code]
		} 
	
		alert(txt_gm_address_error+', '+reason);
	});
}

// request the directions
function gm_getDirections() {
	var saddr = document.getElementById("saddr").value
	var daddr = document.getElementById("daddr").value
	gm_dir.load("from: "+saddr+" to: "+daddr);
}

// functions that open the directions forms
function gm_tohere(i) {
	markers_save[i]['obj'].openInfoWindowHtml(markers_to_htmls[i]);
	//markers_save[i].openInfoWindowHtml(markers_to_htmls[i]);
}
function gm_fromhere(i) {
	markers_save[i]['obj'].openInfoWindowHtml(markers_from_htmls[i]);
	//markers_save[i].openInfoWindowHtml(markers_from_htmls[i]);
}
/////////////////////

///// GEOCODER /////
var gm_geocoder = new GClientGeocoder();
function gm_showAddress(address, html, type) {
	gm_geocoder.getLatLng(address,
		function(point, html, type) {
			if(point){
				var marker = gm_createMarker(point, html, type)
				gm_map.addOverlay(marker);
			}
		}
	);
}
////////////////////
