// Chargement des API
google.load('maps' , '2');
google.load('search' , '1');

var map;					// objet carte
var gdir;					// objet GDirection pour itineraire
var geocoder = null;		// objet Geocoder pour geocodage adresse
var programmeLat;			// latitude du programme
var programmeLng;			// longitude du programme
var bvLat;					// latitude du bureau de vente
var bvLng;					// longitude du bureau de vente
var useBV;					// Centrer sur le BV
var programmePoint;			// point du programme (GLatLng)
var bvPoint;				// point du BV (GLatLng)
var searcher;				// objet LocalSearcher
var searchControl;			// objet SearchControl

var services = [];			// liste des serices

// Initialisation des outils de geolocalisation
function initialize() {

	// Si le navigateur est compatible
	if (GBrowserIsCompatible()) {

		// Initialisations communes
		geoInit();
		
		// Carte
		map = new GMap2(document.getElementById("map"));
		
		// Controlleurs
    	var customUI = map.getDefaultUI();
    	customUI.maptypes.satellite = false;
    	customUI.maptypes.hybrid = false;
    	customUI.maptypes.physical = false;
    	customUI.controls.maptypecontrol = false;
    	customUI.controls.menumaptypecontrol = false;
    	map.setUI(customUI);

		// Placement du programme sur la carte
		programmePoint = new GLatLng(programmeLat,programmeLng);
		var marker = new GMarker(programmePoint,{
			title: 'Programme neuf',
			icon: programmeOnIcon
		});
		map.addOverlay(marker);
		
		// Placement du BV sur la carte
		if(bvLat && bvLng) {
			bvPoint = new GLatLng(bvLat,bvLng);
			var marker = new GMarker(bvPoint,{
				title: 'Bureau de vente',
				icon: bvOnIcon
			});
			map.addOverlay(marker);
		}

		map.setCenter(useBV ? bvPoint : programmePoint, 15);

		// Searcher
		searchControl = new google.search.SearchControl();
		searcher = new google.search.LocalSearch();
		searcher.setCenterPoint(map);
		searcher.setResultSetSize(google.search.Search.LARGE_RESULTSET);
		var options = new google.search.SearcherOptions();
		options.setExpandMode(google.search.SearchControl.EXPAND_MODE_OPEN);
		searchControl.addSearcher(searcher , options);
		searchControl.draw(document.getElementById("searchControl"));

		/*
		 * Geolocalisation de l'addresse du programme
		 * Inutile normallement ...
		geocoder = new GClientGeocoder();
		geocoder.getLatLng(
    		"Chemin Marteltal 67140 Gertwiller", function(point) {
				if (!point) {
					alert(address + " not found");
				} else {
					currentPoint = point;
					map.setCenter(point, 15);
					var marker = new GMarker(point,{
						title: 'Programme neuf',
						icon: programmeOnIcon
					});
					map.addOverlay(marker);
				}
			}
		);
		*/

		// Itineraires
		gdir = new GDirections(map, document.getElementById("textDirection"));
		GEvent.addListener(gdir, "load", onGDirectionsLoad);
		GEvent.addListener(gdir, "error", handleErrors);
	}
}
    
function setDirections(fromAddress, toAddress, locale) {
	gdir.load("from: " + fromAddress + " to: " + toAddress, {"locale": locale});
}

function handleErrors(){
	if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
		alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + gdir.getStatus().code);
	else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
		alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code);
	else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
		alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);
	else if (gdir.getStatus().code == G_GEO_BAD_KEY)
		alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);
	else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
		alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);
	else alert("An unknown error occurred.");
}

function onGDirectionsLoad(){
	$('#textDirectionContainer').addClass('itineraire');
}

function getDirection(){
	var from = document.getElementById('fromDirection').value;
	var to = document.getElementById('toDirectionGPS').value;
	
	if(from == "" || to == "")
		alert("merci de saisir un lieu de départ et d'arrivée");
	else
		setDirections(from, to, 'fr_FR');

	return false;
}

function searchService(service,strService,del) {

	if(del) {
		for(i in services[service]) {
			map.removeOverlay(services[service][i]);
		}
		services[service] = [];
	}

	else if(services[services]) {
		for(i in services[service])
			map.addOverlay(services[service][i]);
	}
	
	else {
		searchControl.setSearchCompleteCallback(searcher , function() {
			completeSearch(service);
		});
		strServices = strService.split(',');
		for(i in strServices)
			searchControl.execute(strServices[i]);
	}
}

function completeSearch(service) {

	var results = searcher.results;
	var icon = baseServiceIcon;
	if(!services[service])
		services[service] = [];

	switch(service) {
		case 'transport':
			icon = transportIcon;
			break;
		case 'ecole':
			icon = ecoleIcon;
			break;
		case 'garderie':
			icon = garderieIcon;
			break;
		case 'sortie':
			icon = sortieIcon;
			break;
		case 'sport':
			icon = sportIcon;
			break;
		case 'commerce':
			icon = commerceIcon;
			break;
	}
	
	for (var i = 0; i < results.length; i++) {
		var result = results[i];
		var markerLatLng = new google.maps.LatLng(parseFloat(result.lat), parseFloat(result.lng));
		var marker = new google.maps.Marker(markerLatLng,{title:'', icon:icon});
		marker.bindInfoWindow(result.html.cloneNode(true));
		result.marker = marker;
		map.addOverlay(marker); // add the marker to the map
		services[service].push(marker);
	}

	/*
	var center = searcher.resultViewport.center;
	// Calculate what the zoom level should be
	var ne = new google.maps.LatLng(searcher.resultViewport.ne.lat, searcher.resultViewport.ne.lng);
	var sw = new google.maps.LatLng(searcher.resultViewport.sw.lat, searcher.resultViewport.sw.lng);
	var bounds = new google.maps.LatLngBounds(sw, ne);
	var zoom = map.getBoundsZoomLevel(bounds, new google.maps.Size(350, 350));
	map.setCenter(new google.maps.LatLng(parseFloat(center.lat), parseFloat(center.lng)), zoom);*/
}

$(document).ready(function() {
	initialize();
});
