var map = null;
var geoCoder = null;
var poly;
var inicio;
var fin;

var icono = new GIcon();
icono.image = "../archivos/googlemaps/marcador.png";
icono.shadow = "../archivos/googlemaps/sombra.png";
icono.iconSize = new GSize(32, 32);
icono.shadowSize = new GSize(46, 32);
icono.iconAnchor = new GPoint(15, 32);
icono.infoWindowAnchor = new GPoint(15, 1);

var latitud = 40.201070;
var longitud = 0.070130;

function carga() {
	if (GBrowserIsCompatible()) {
		if ( map == null ) {
			map = new GMap2($('mapa-google'));
			pos = new GLatLng(latitud, longitud);
			map.setCenter(pos, 11);
			map.addControl(new GSmallMapControl());
			map.setMapType(G_NORMAL_MAP);
		}
		if (map) {
			geoCoder = new GClientGeocoder();
			map.enableDoubleClickZoom();
			map.enableContinuousZoom();
			map.enableScrollWheelZoom();
			map.addControl(new GOverviewMapControl()); 
			refresh();
		}
	}
}

var geoXml = null;
var exml = null;
function refresh() {
	// Para un zoom automatico a todas las localizaciones quitar la opcion nozoom
	exml = new EGeoXml("exml", map, "../archivos/googlemaps/aerocas.kml?"+(Math.random()*10000) , {titlestyle:'class="bocadillo-titulo"',descstyle:'class="bocadillo-texto"',iwwidth:'auto',baseicon:icono,nozoom:true});
	exml.parse();
	return false;
}

var gDir = null;
function searchAddress(direccion) {
	geoCoder.getLatLng(direccion,
			function(ptoOrigen) {
				if (!ptoOrigen) {
					alert(direccion + ": No ha sido posible encontrar la localización.");
				} else {
					map.panTo(ptoOrigen);
					
					var ptoDestino = "Aeroport Castelló@"+latitud+","+longitud;

					var puntos = new Array();
					puntos.push(direccion+ '@' + ptoOrigen);
					puntos.push(ptoDestino);
					
					if(gDir) {
						gDir.clear();
					} else {
						gDir = new GDirections(map, $('panel-mapa'));
					}

					gDir.loadFromWaypoints(puntos,"{preserveViewport:true;getSteps=true}");
					GEvent.addListener(gDir,"load",function(){onGDirectionsLoad(gDir);});
					GEvent.addListener(gDir,"addoverlay",function(){onGDirectionsAddOverlay(gDir);});
				}
			}
	);
}

function onGDirectionsLoad(gDir) {
	poly = gDir.getPolyline();
	poly.color = '#171796';
	for(var i=0;i<gDir.getNumGeocodes();i++) {
		fin = gDir.getMarker(i);
	}
}

function onGDirectionsAddOverlay(gDir) {
	map.removeOverlay(fin);
}