/****************************** map_global.js */

var STR_HOME = 'home';

/**
 * Instance de la map googlemap
 *
 * @var GMap2
 */
var map;

/**
 * Instance du geocoder, utilisé pour faire la traduction entre adresse et coordonnées géographiques
 *
 * @var GClientGeocoder
 */
var geocoder;

/**
 * Liste des points sur la carte
 *
 * @var Array
 * 	- GLatLng coordonnees
 *  - Gmarker marker
 */
var points_ = new Array;

/**
 * Instance de GDirections pour les itinéraires
 * 
 * @var GDirections
 */
var gdir;

/**
 * Coordonnées du point au moment du clic droit sur la map
 * 
 * @var GLatLng
 */
var coordonneesClic;

/**
 * Préfixe utilisé pour les marqueurs de prod
 * 
 * @var string
 */
var prefix='prod_';

/**
 * Elément dans lequel l'itinéraire textuel doit être affiché
 * 
 * @var string
 */
var pGDirections='text_itineraire';

/**
 * Charge le code de Googlemaps et appelle la fonction callback une fois chargé
 * 
 * @param callback
 * @return
 */
function loadMaps(callback) {
	google.load("maps", "2", {"callback" : callback });
};






/************************* map_init.js */

/**
 * Initialise la carte de google maps
 * 
 * @param opts
 *		-int width
 *		-int height
 *		-function fGdirection fonction appellée lorsque l'itinéraire est prêt
 *		-Object center {
 *			latitude,
 *			longitude,
 *			zoom
 *		}
 * @return void
 */
function map_initialize( opts ) {
	opts = opts || {};
	var fGdirection = opts.fGdirection || null;
	var width =  opts.width || 775;
	var height = opts.height || Math.floor(width/1.61);
	var center = opts.center || {};
	var latitude = center.latitude || 47.341571;
	var longitude = center.longitude || 0.514233;
	var zoom = center.zoom || 13;
	
	setMapSize( {
		width: width,
		height: height
	} );
	if( GBrowserIsCompatible() ) {
		map = new GMap2(document.getElementById( "map_canvas" ) );
		setMapControls();
		map.setCenter(new GLatLng(latitude, longitude), zoom);
		
		;//Création de l'instance GDirections pour les itinéraires
		/*if( fGdirection ) {
			gdir = new GDirections(map, window.top.document.getElementById(pGDirections));
			GEvent.addListener(gdir, "addoverlay", fGdirection);
		}*/
	}
};

/**
 * Initialise les contrôles utilisateur de la map
 * 
 * @return
 */
function setMapControls() {
	var uiOptions = map.getDefaultUI();
	uiOptions.zoom.scrollwheel = false;
	map.setUI(uiOptions);
};










/************************ map_function.js */


/**
 * Retourne la largeur de la map
 * 
 * @param idElem ( par défaut: map_canvas )
 * @return int
 */
function getMapWidth( idElem ) {
	idElem = idElem || 'map_canvas';
	var strwidth = $('#'+idElem).css('height');
	return( parseInt( strwidth.substr( 0, strwidth.length - 2 ) ) );
};

/**
 * Retourne la hauteur de la map
 * 
 * @param idElem ( par défaut: map_canvas )
 * @return int
 */
function getMapHeight( idElem ) {
	idElem = idElem || 'map_canvas';
	var strwidth = $('#'+idElem).css('height');
	return( parseInt( strwidth.substr( 0, strwidth.length - 2 ) ) );
};

/**
 * Définit la taille de la carte
 * 
 * @param size
 * 		-height: hauteur en px
 * 		-width: largeur en px
 * 		-idMap: identifiant HTML de la map
 * @return void
 */
function setMapSize( size ) {
	size = size || {};
	var idMap = size.idMap || 'map_canvas';
	var height = size.height || getMapHeight(idMap);
	var width = size.width || getMapWidth(idMap);
	$('#'+idMap).css( 'width', width );
	$('#'+idMap).css( 'height', height );
};

/**
 * Retourne un marker de couleur hexColor. hexColor est une chaîne de la forme "RRGGBB"
 *
 * @param GLatLng coodonnees
 * @param Object opts:
 * 	-GMarkerOptions	GOptionMarker
 *	-event:			Evénement lié à l'affichage de l'info bulle
 *	-html: 			Le contenu de la bulle lors du clic( par défaut: "" )
 *
 * @use
 * @return GMarker
 */
function createMarker( coordonnees, opts ) {
	opts = opts || {};
	var html = opts.html || "";
	var event = opts.event || null;
	var optsMarker = opts.GMarkerOptions || null;
	
	var marker = new GMarker( coordonnees, optsMarker );
	
	if( event == 'click' ) {
		marker.bindInfoWindowHtml( html );
	} else if( event !== null ) {
		GEvent.addListener( marker, event, function() {
			map.openInfoWindowHtml( coordonnees, html );
		} );
	}
	
	
	
	return marker;
};



/**
 * Affiche la carte de telle façon que tous les points soient visibles. Si aucun point n'est affiché
 * la carte se centre sur La France avec un zoom de 5.
 * 
 * @param Object opts
 * 		-GLatLng center: centre de la carte par défaut ( le centre de la France )
 *		-distanceMax: distance maximale d'un point par rapport au centre qui doit être affiché en km par défaut( aucune valeur )
 *		-zoomMax: zoom maximal ( par défaut: 15 )
 *		-zoomRelatif: augmentation ou diminution du zoom par rapport à celui qui est trouvé
 */
function centerMap( opts ) {
		
	opts = opts || {};
	var center = opts.center || null;
	var dst = opts.distanceMax || null;
	var zoomMax = opts.zoomMax || 15;
	var zoomRelatif = opts.zoomRelatif || 0;
	var p = opts.points || points_;
	
	var north, south, east, west;
	if( center ) {
		north = center.lat();
		south = center.lat();
		east = center.lng();
		west = center.lng();
	}
	
	var nbPointsVisibles = 0;
	for( var i in p ) {
		nbPointsVisibles++;
		if( !center ) {
			center = new GLatLng( p[i].coordonnees.lat(), p[i].coordonnees.lng() );
			north = south = center.lat();
			east = west = center.lng();
		}
		if( dst ) {
			if( distance( center, p[i].coordonnees ) > dst ) {
				continue;
			}
		}
		south = Math.min( p[i].coordonnees.lat(), south );
		north = Math.max( p[i].coordonnees.lat(), north );
		west = Math.min( p[i].coordonnees.lng(), west );
		east = Math.max( p[i].coordonnees.lng(), east );
	}
	
	if( nbPointsVisibles == 0 ) {
		map.setCenter( new GLatLng( 46.6494, 2.28515 ), 5 ); 
		return;
	}
	
	
	map.setCenter( new GLatLng( (north+south)/2, (east+west)/2 ), Math.min( 
		map.getBoundsZoomLevel ( 
			new GLatLngBounds ( 
				new GLatLng( south, west ),
				new GLatLng( north, east )
			) 
		) + zoomRelatif,
		zoomMax
	) );
	
};

/**
 * Retourne la distance à vol d'oiseau entre 2 points géographiques A et B.
 * 
 * @param GLatLng A
 * @param GLatLng B
 * return float
 */
function distance( A, B ) {
	var latA = A.latRadians();
	var lonA = A.lngRadians();
	var latB = B.latRadians();
	var lonB = B.lngRadians();
	return( 6378 * ( 
		(Math.PI)/2 - Math.asin( 
			Math.sin( latB ) * Math.sin( latA ) +
			Math.cos( lonB - lonA ) * Math.cos( latB ) * Math.cos( latA )
		)
	) );
};


/****************************** map_adresse.js */


/**
* Retourne l'adresse du client depuis la zone de texte ou null si aucune valeur n'est trouvée
* @param opts:
* 		- id: identifiant DOM de l'élément aresse (par défaut: txt_search)
* 
* @return string|null
*/
function getAdresse( opts ) {
	var options = opts || {};
	var id_adresse = options.id || 'txt_search';
	var adresse = $('#'+id_adresse).val();
	if( !adresse )
		return null;
	return adresse;
};


/**   
 * Remplit le champs de formulaire avec opts.
 * 
 * @param opts:
 * 		- id: identifiant DOM de l'élément aresse (par défaut: input_adresse)
 * 
 * @return void
 */
function setAdresse( opts ) {
	var options = opts || {};
	var id = opts.id || 'input_adresse';
	var adresse = opts.adresse || '';
	$('#'+id).val(adresse);
};


var itineraire = {
/*;*/ /* GPolyline poly */
	poly: null,
/*;*/ /* String dest */
	dest: null,
/*;*/ /* String panel */
	panel: pGDirections,
/*; GRoute route */
	route: null,
	
/*;*/ /**
	  * Charge l'itinéraire depuis le marker home jusqu à destination
	  */
	to: function(destination) {
		this.clear();
		this.dest = destination;
		gdir.load( "from: "+points_[STR_HOME].coordonnees.lat()+","+points_[STR_HOME].coordonnees.lng()+" to: "+destination, {
			locale: 'fr'
		} );
	},
	
/*;*/ /**
	  * Retrace l'itinéraire si le point de départ à changé d'emplacement
	  */
	refresh: function() {
		if( this.dest != null )
			this.to(this.dest);
	},
	
/*;*/ /**
	  * Efface le tracé de l'itinéraire
	  */
	clear: function() {
		if(this.poly !== null ) {
			map.removeOverlay(this.poly);
			this.poly = null;
		}
	}
};



































