$(document).ready(function(){
	var localizador_marcado = "0";

	$('body').unload(function() {
		GUnload();
	});

	initialize();

	$('.localizador').each(function() {
		var tmp = $(this).attr('id');
		var ic = $(this).attr('class');
		ic = ic.split(" ")[1];
		var posn = new GLatLng($("#lat_"+tmp).val(),$("#lon_"+tmp).val());
		var marker = createMarker(posn,tmp,"icon_"+ic);
		markers[tmp] = marker;
		map.addOverlay(marker);
	});

	$('.localizador').bind('click',function() {
		gdir.clear();
		$('.localizador').css('font-weight','normal');
		$(this).css('font-weight','bold');
		var tmp = $(this).attr('id');
		localizador_marcado = tmp;
		showAddress(tmp);
		return false;
	});

	$('#calcRuta').bind('click',function() {
		if (localizador_marcado == "0") {
			$('#routedetails').html("Elige una localización para calcular la ruta.");
		} else {
			$('#routedetails').empty();
			setDirections($('#fromAddress').val(),$('#pos_'+localizador_marcado).val());
		}
		return false;
	});
});

var map = null;
var gdir;
var markers = new Array();
var baseIcon = null;
var geocoder = null;
//var addressMarker;
var Lat = 42.416894;
var Lng = -3.693295;
var Alt = 5;

function createMarker(point,tmp,id) {
	var letteredIcon = new GIcon(baseIcon);
	letteredIcon.image = $("#"+id).attr("src");

	// Set up our GMarkerOptions object
	markerOptions = { icon:letteredIcon };
	var marker = new GMarker(point, markerOptions);
	marker.bindInfoWindowHtml($("#info_"+tmp).html());
	return marker;
}

function showAddress(address) {
	map.setCenter(markers[address].getLatLng(), 14);
	markers[address].openInfoWindowHtml($("#info_"+address).html());
}

function initialize() {
	if (GBrowserIsCompatible()) { 
		map = new GMap2(document.getElementById("mapbox_localizador"));
		map.setMapType(G_HYBRID_MAP);
		map.enableContinuousZoom();
		// Centra el mapa en unas coordenadas determinadas 
		//con un nivel de zoom (15)
		map.setCenter(new GLatLng(Lat,Lng), Alt);
		// Define los controles que se veran sobre el mapa
		map.addControl(new GLargeMapControl());
		var mapControl = new GMapTypeControl();
		map.addControl(mapControl);
		geocoder = new GClientGeocoder();
		// Create a base icon for all of our markers that specifies the
		// shadow, icon dimensions, etc.
		baseIcon = new GIcon(G_DEFAULT_ICON);
		baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
		baseIcon.iconSize = new GSize(20, 34);
		baseIcon.shadowSize = new GSize(37, 34);
		baseIcon.iconAnchor = new GPoint(9, 34);
		baseIcon.infoWindowAnchor = new GPoint(9, 2);

		//Asociamos el div 'directions' a las direcciones que 
		//devolverá Google Maps
		gdir = new GDirections(map, document.getElementById("routedetails"));
		//Listener para los errores que se produzcan cuando procese la petición
		GEvent.addListener(gdir, "error", handleErrors);
		GEvent.addListener(gdir, "addoverlay", onGDirectionsOk);
		GEvent.addListener(gdir, "load", onGDirectionsLoad);
	}
}

//Función encargada de calcular la ruta con el API de Maps
function setDirections(fromAddress, toAddress) {
	var opt = {}
	//opt.locale = "es";
	if ($("#rutaPie").attr('checked'))
		opt.travelMode = G_TRAVEL_MODE_WALKING;
	gdir.load("from: " + fromAddress + " to: " + toAddress, opt);
	//Como es de suponer la opción locale:es hace que la ruta que  
	//nos escriba esté en español.
}

//Manejo de errores
function handleErrors(){
	if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
		$('#routedetails').html('No se puede calcular la ruta desde la dirección indicada, compruebe que está bien escrita o esta no sea ambigua.');
	else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
		$('#routedetails').html('Error desconocido.');
	else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
		$('#routedetails').html('No se ha introducido una dirección de inicio.');
	else if (gdir.getStatus().code == G_GEO_BAD_KEY)
		$('#routedetails').html('Clave usada por el mapa no valida o no corresponde con el dominio desde el que se usa.');
	else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
		$('#routedetails').html('La dirección no puede ser parseada.');
	else
		$('#routedetails').html('Ha ocurrido un error');
}

function onGDirectionsOk(){
	//$(document).scrollTo($('#ver_todo'),1000);
}
	
function onGDirectionsLoad(){
}

