/*
 * Dépendance avec jQuery v1.2.6 et/ou selon interoptabilité
 * variables définies par le serveur et présent au "niveau supérieur" càd dans la page HTML
 * var markerIcon // Icônes
 * var jobDataMap // objet JSON
 */

// Charge le composant "maps" V2 de google
//google.load("maps", "2");

// Variables Globales
var map;
var isMapInitialized = false;					// Définie si la carte a déjà été initialisé
var jobDataArray = (window.jobDataMap) ? jobDataMap : ''; 	// Objet contenant toutes les offres localisable
var markerIcon = (window.markerIcon) ? markerIcon : '';

var jobMarkerManager;
var multiJobMarkerMapBounds; 			//bound of map
var currentInfoWindowPageIndex = 0; 	//infowindow paging
var currentInfoWindowJobMarker; 		//infowindow paging
var MultiJobMapBoundsExtendRatio = .2; 	//ratio to extend bounds on map to ensure all markers fit

var mapIconSingle = new GIcon();
mapIconSingle.image = markerIcon.replace('{extension}', 'single');
mapIconSingle.shadow = markerIcon.replace('{extension}', 'shadow_s');
mapIconSingle.iconSize = new GSize(24, 24);
mapIconSingle.shadowSize = new GSize(24, 24);
mapIconSingle.iconAnchor = new GPoint(9, 34);
mapIconSingle.infoWindowAnchor = new GPoint(9, 2);
mapIconSingle.infoShadowAnchor = new GPoint(18, 25);

// Attends la fin du chargement de la page pour ajouter des méthodes aux fonctions de google
// Sinon les méthodes sont ajouté à des classes non existante
$(document).ready(function(){

	// Calcul automatiquement le centre de la carte et définie le zoom optimal pour voir tous les marqueurs
	GMap2.prototype.centerAndZoomOnBounds = function(bounds, maxZoomLevel, extendRatio) { 
		var zoomLevel = maxZoomLevel || 0;
		var ratio = extendRatio || 0;
		var largerBounds = bounds.extendByRatio(ratio); 
		var center_lat = (largerBounds.getNorthEast().lat() + largerBounds.getSouthWest().lat())/ 2.0; 
		var center_lng = (largerBounds.getNorthEast().lng() + largerBounds.getSouthWest().lng())/ 2.0; 
		 
		var boundsZoom = map.getBoundsZoomLevel(largerBounds);
		 
		//do not zoom in more then specificed zoom level
		var zoom =  boundsZoom <= zoomLevel ? boundsZoom : zoomLevel;
		map.setCenter(new GLatLng(center_lat, center_lng), zoom);
	}

	//pads existing GLatLngBounds by ratio to ensure all markers are visible
	GLatLngBounds.prototype.extendByRatio = function(ratio) {
		 // initialize bounds to be the same as original 
		 var largerBounds = new GLatLngBounds( this.getSouthWest(), this.getNorthEast() ); 
		 // get lat, lng of north east and south west 
		 var northEastLat = this.getNorthEast().lat(); 
		 var northEastLng = this.getNorthEast().lng(); 
		 var southWestLat = this.getSouthWest().lat(); 
		 var southWestLng = this.getSouthWest().lng(); 
		 var diffLat = northEastLat - southWestLat; 
		 var diffLng = northEastLng - southWestLng; 
		 // multiply with ratio 
		 northEastLat += diffLat * ratio; 
		 southWestLat -= diffLat * ratio; 
		 northEastLng += diffLng * ratio; 
		 southWestLng -= diffLng * ratio; 
		 // extend north east 
		 largerBounds.extend(new GLatLng(northEastLat, northEastLng)); 
		 // extend south west 
		 largerBounds.extend(new GLatLng(southWestLat, southWestLng)); 
		 return largerBounds;
	}
});

// @param 	mapContainer	HTMLDivElement
function initSingleGmap(mapContainerJQ,lat,lng){

	var mapContainer = mapContainerJQ.get()[0];
		
	// Si la carte est compatible avec le navigateur et si l'élement HTML et définie ou initialise la carte
	if (GBrowserIsCompatible() && mapContainer) {
	
		// Paramètre pour la carte
		map = new GMap2(mapContainer);	// instancie la carte
		map.addControl(new GSmallMapControl());		// ajoute un contrôle pour le zoom
		map.enableContinuousZoom();		 			// aténue l'effet lors du zoom
		map.enableDoubleClickZoom();				// autorise le double clic pour zoomer
		
		var point = new GLatLng(parseFloat(lat), parseFloat(lng));  
		map.setCenter(point, 9);		// centre la carte
		var marker = new GMarker(point, mapIconSingle);
		
		map.addOverlay(marker);
	}
	
	return map;
}

// réafiche la carte avec les valeurs comme pour la première visualisation
function ResetMapView() {
	map.centerAndZoomOnBounds(multiJobMarkerMapBounds, MultiJobMapInitialZoomLevel, MultiJobMapBoundsExtendRatio);	
	map.closeInfoWindow();
}

/*
 * Affiche un marqueur en lui passant comme paramètre une adresse
 */
function displayMarkerByAdress( map, info) {
	//alert(info.html);
	
	// Initialise le géocoder
	var geocoder = new google.maps.ClientGeocoder(); 
	
	// On indique au géocoder que par défault il doit chercher les adresse en France
	geocoder.setBaseCountryCode('fr');
	
	// Récupère un point en fonciton de l'adresse et affiche dans la foulée le marqueur
	geocoder.getLatLng(
		info.adresse,
		function (point) { // Récupère au passage  les données du point
			if (!point) {
				return false;
			} else {
				map.setCenter(point, 13);
				var marker = new google.maps.Marker(point);
				if(info.html != '') {
					GEvent.addListener(marker, "click", function() {
						marker.openInfoWindowHtml(info.html);
					});
				}
				map.addOverlay(marker);
				return true;
			}
		}
	);
}

/*
 * Affiche un marqueur en lui passant comme paramètres les coordonnées
 */
function displayMarkerByCoords( map, latitude, longitude, zoom) {
	var zoom = zoom || 13;
	point = new google.maps.LatLng(latitude, longitude);
	map.setCenter(point, zoom);
	var marker = new google.maps.Marker(point);
	map.addOverlay(marker);
	return true;
}

// Creates a marker whose info window displays the letter corresponding
// to the given index.
function createMarker(point, index, icon) {
	// Create a lettered icon for this point using our icon class
	var marker = new GMarker(point, icon);

	GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowTabsHtml(index);
	});
	return marker; 
}

// GUnload  on unload
$(window).unload( function() {
	GUnload();
} );
