﻿var map;
var gdir;
var geocoder = null; 
var puntoCircuitos;






function crearMarcador (punto, nombre, texto, color) {

  	  var icono = new GIcon();
	  icono.image = "http://labs.google.com/ridefinder/images/mm_20_" + color + ".png";
	  icono.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
	  icono.iconSize = new GSize(12, 20);
	  icono.shadowSize = new GSize(22, 20);
	  icono.iconAnchor = new GPoint(6, 20);
	  icono.infoWindowAnchor = new GPoint(5, 1);

  	  var marcador = new GMarker(punto, icono);

  	  GEvent.addListener(marcador, "click", function() {
  	    marcador.openInfoWindowHtml("<div><address><strong>MotorLand Aragon</strong><br />Ctra TE-V-7033, km 1<br />Apdo de correos 174<br/>44600 Alcañiz, Teruel (Spain)</address>Coord. GPS: N 41&deg; 4\' 17,69&quot; - E -0&deg; 11\' 15,43&quot;<br />Tel: 978 835 548<br />Fax: 978 835 549<br />Web: <a href=\"http://www.motorlandaragon.com\">www.motorlandaragon.com</a></div>");
  	  });

  	  return marcador;
	}

window.onload = function load() {
	cargarValores();
	  abrirMenu(7); 
      if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("slideMapa"));
		gdir = new GDirections(map, document.getElementById("indicaciones"));
		GEvent.addListener(gdir, "load", onGDirectionsLoad);
        GEvent.addListener(gdir, "error", handleErrors);
        GEvent.addListener(gdir, "addoverlay", onGDirectionsAddOverlay); 
		map.addControl(new GSmallMapControl());
		map.addControl(new GMapTypeControl());
        map.setCenter(new GLatLng(41.071587,-0.187626), 11, G_HYBRID_MAP);
		//map.enableScrollWheelZoom(); 
		
		
		//creo los puntos de los límites de la imagen
		var x1 = new GLatLng(41.06927,-0.21782);
		var x2 = new GLatLng(41.0881,-0.1763);
		//defino los límites donde voy a colocar la imagen
		var limites_imagen = new GLatLngBounds(x1, x2);
		//Creo un ground overlay
		var imagen = new GGroundOverlay("http://web.desarrollando.net/cma2008/images/imagenmapa.jpg", limites_imagen);
		//coloco la imagen o ground overlay en el mapa
		map.addOverlay(imagen); 

		

		var icon = new GIcon();
		icon.image = "http://labs.google.com/ridefinder/images/mm_20_red.png";
		icon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
		icon.iconSize = new GSize(12, 20);
		icon.shadowSize = new GSize(22, 20);
		icon.iconAnchor = new GPoint(6, 20);
		icon.infoWindowAnchor = new GPoint(5, 1);
		
		puntoCircuitos = crearMarcador(new GLatLng(41.071587,-0.187626), 'Motorland Aragón', 'Circuitos', 'yellow');
		
		map.addOverlay(puntoCircuitos);
			

  	}
}

function obtenerIndicaciones(idioma){
		
		var direccion = document.getElementById('direccion');
		
		var error = false;
		if(((!error && direccion.value == "") || (!error && direccion.value == "Indique el punto de partida…")) || (!error && direccion.value == "Type in your starting point…")){
			alert("Por favor, indique el punto de partida");
			error = true;
		}
		if (!error){
			if (getRadioValue('destino') == 'motorland'){
				setDirections(direccion.value, '41.071587,-0.187626', idioma)
			}else{
				setDirections(direccion.value, '41.050618,-0.131106', idioma)	
			}			
			map.removeOverlay(puntoCircuitos);
			//map.removeOverlay(puntoOficinas);
		    map.closeInfoWindow();
			map.setMapType(G_NORMAL_MAP);
			var mapa = document.getElementById('slideMapa');
			var direcciones = document.getElementById('indicaciones');
			direcciones.style.display = 'block';	
			var columna = document.getElementById('restoColumna');
			columna.style.display = 'none';			
		}
	}

function setDirections(fromAddress, toAddress, locale) {
		
     gdir.load("from: " + fromAddress + " to: " + toAddress,
                { "locale": locale , "getSteps":true});
    }

    function handleErrors(){
	   if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
	     alert("La dirección solicitada no se ha podido localizar. Por favor, verifique los datos introducidos y vuelva a intentarlo." );
	   else alert("Ha ocurrido un error al procesar su solicitud. Vuelva a intentarlo más tarde.");	  
	   		    //map.openInfoWindow();
			var direcciones = document.getElementById('indicaciones');
			direcciones.style.display = 'none';		
			var columna = document.getElementById('restoColumna');
			columna.style.display = 'block';	
			map.addOverlay(puntoInicial);
		    map.openInfoWindowHtml(new GLatLng(41.071587,-0.187626),"<p><font color='#0041ad'><strong><font size='3' face='Arial, Helvetica, sans-serif'>La Ciudad del <br/>Motor de Aragón</font></strong></font></p>");
			map.setCenter(new GLatLng(41.071587,-0.187626), 13, G_HYBRID_MAP);
	}
	
	function onGDirectionsLoad(){ 
      // Use this function to access information about the latest load() results.
	}

	var newMarkers = [];
	var latLngs = [];
	var icons = [];
	
	// Note the 'addoverlay' GEvent listener added inside initialize() function

	function onGDirectionsAddOverlay(){ 
	// Remove the draggable markers from previous function call.
	for (var i=0; i<newMarkers.length; i++) 
	{map.removeOverlay(newMarkers[i]);
	}

	// Loop through the markers and create draggable copies
	for (var i=0; i<=gdir.getNumRoutes(); i++) 
		{
		var originalMarker = gdir.getMarker(i);
		latLngs[i] = originalMarker.getLatLng();
		icons[i] = originalMarker.getIcon();
		newMarkers[i] = new GMarker(latLngs[i],{icon:icons[i], draggable:true, title:''});
		map.addOverlay(newMarkers[i]);

		// Get the new waypoints from the newMarkers array and call loadFromWaypoints by dragend
		GEvent.addListener(newMarkers[i], "dragend", function()
		  {
		var points = [];
		for (var i=0; i<newMarkers.length; i++) 
			{
		points[i]= newMarkers[i].getLatLng();
			}
		gdir.loadFromWaypoints(points);
		  });

		//Bind 'click' event to original hidden marker
		copyClick(newMarkers[i],originalMarker);
		
		// hide or remove the original marker
		//originalMarker.hide();
		map.removeOverlay(originalMarker);
		}
		
		function copyClick(newMarker,oldMarker){
		GEvent.addListener(newMarker, 'click', function()
		  {GEvent.trigger(oldMarker,'click');
		  });
		}
		
		
	}
	
function getRadioValue(RadioName)
{
	var colRadio = document.getElementsByName(RadioName);
	for (var i = 0; i < colRadio.length; i++)
	{
		if (colRadio[i].checked)
			{ 
			return colRadio[i].value; 
			}
	}
	return null;
}

function limpiarCuadro(){
	var direccion = document.getElementById('direccion');
	if ((direccion.value == 'Indique el punto de partida…') || (direccion.value == 'Type in your starting point…'))
	{
		direccion.value = ''}
	}
