// JavaScript Document
// MAPAS Y COORDENADAS OBTENIDAS POR IRLANDA EN RED SL  - GRUPO MUNDO EN RED - PROHIBIDO REPRODUCIR SIN AUTORIZACION ESTE SCRIPT. //
// UNA COPIA DE LAS PRINCIPALES FUNCIONES DE ESTE SCRIPT Y UNO DE EJEMPLO HAN SIDO REGISTRADAS EN SUS DERECHOS DE PROPIEDAD INTELECTUAL EN 2009 EN LA OFICINA DE PATENTES Y MARCAS DE MADRID, Paseo de la Castellana, 75 - 28046 MADRID //
// LA REPRODUCCIÓN TOTAL Y PARCIAL DE ESTE SCRIPT POR PARTE DE EMPRESAS DE LA COMPETENCIA DIRECTA, SERÁ DENUNCIADA SIN REMISIÓN POR SUS DERECHOS DE PROPIEDAD INTELECTUAL, ENFRENTANDOSE A UNA ELEVADA COMPENSACIÓN ECONOMICA //
// ESTE SCRIPT HA SIDO DESARROLLADO POR EL PROPIO EQUIPO DE DESARROLLO DE GRUPO MUNDO EN RED, UTILIZANDO EL API DE GOOGLE, DE USO LIBRE Y GRATUITO. A LAS EMPRESAS DE LA COMPETENCIA LES ROGAMOS QUE SE DESARROLLEN USTEDES SUS PROPIOS SCRIPTS //

    //<![CDATA[

    function load() {
      if (GBrowserIsCompatible()) {
        var map = new GMap2(document.getElementById("map"));
        map.setCenter(new GLatLng(35.898715,14.487593), 14);
	    map.addControl(new GMapTypeControl());
        map.addControl(new GLargeMapControl());
        map.addControl(new GScaleControl());
		map.enableDoubleClickZoom();
		map.enableScrollWheelZoom();
		map.enableContinuousZoom();
		map.getContainer().style.overflow="hidden";
        map.addControl(new GOverviewMapControl());	
		map.setMapType(G_HYBRID_MAP);
		
		// Creamos el "MEC" marker icon
		var mecIcon = new GIcon();
		
		//GIcon mecIcon = new GIcon();
		mecIcon.image = "http://www.becasmec.info/images/mec.png";
		mecIcon.shadow = "http://www.becasmec.info/images/mec-sombra.png";
		mecIcon.iconSize = new GSize(48, 50);
		mecIcon.shadowSize = new GSize(48, 50);
		mecIcon.iconAnchor = new GPoint(15, 49);
		mecIcon.infoWindowAnchor = new GPoint(17, 35);
		markerOptions = { icon:mecIcon };
		
		/*GMarkerOptions mOpts = new GMarkerOptions();
		mOpts.icon = mecIcon;
		
		GMarker marker = new GMarker(latlng, mOpts);
		GMap1.addGMarker(marker);*/
		
		//Funcion de texto de escuelas MEC
		function addtag(point, address) {
        var marker = new GMarker(point, markerOptions);
        GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml(address); } );
        return marker;
        }
		
		// inicio pruebas de api google
		
		// crea el buscador y lo añade al mapa
		map.enableDoubleClickZoom();
		map.enableScrollWheelZoom();
		var lsc = new google.maps.LocalSearch(); 
		map.addControl(new google.maps.LocalSearch(), new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(140,20)))	
		
		// fin pruebas de api google
		
		// MALTA
		
		// SKYLARK
		var point = new GLatLng(35.898715,14.487593);
        var address = '<b>SKYLARK </b><br/><i>Oferta de Curso de Ingl&eacute;s - BECA MEC - Malta</i><br /><a href="http://www.becasmec.info/detalles/13/malta/skylark-malta" title="CURSO DE INGLES MEC EN MSIDA - MALTA">CURSO DE INGLES MEC EN MSIDA - MALTA</a>';
		var marker = addtag(point, address);
		map.addOverlay(marker);
		

      }
    }
	
    var map;
    var gdir;
    var geocoder = null; // ?
    var addressMarker;   // ?


    function initialize() {
      if (GBrowserIsCompatible()) {      
        map = new GMap2(document.getElementById("map_canvas"));
		map.addControl(new GMapTypeControl());
        map.addControl(new GLargeMapControl());
        map.addControl(new GScaleControl());
		map.enableDoubleClickZoom();
		map.enableScrollWheelZoom();
		map.enableContinuousZoom();
        gdir = new GDirections(map, document.getElementById("directions"));
        GEvent.addListener(gdir, "load", onGDirectionsLoad);
        GEvent.addListener(gdir, "error", handleErrors);
        GEvent.addListener(gdir, "addoverlay", onGDirectionsAddOverlay); // added to trigger marker swap
		map.setCenter(new GLatLng(0,0),0);	//Inital setCenter()  added. Esa.

        setDirections("Roma, Italia", "Sicilia, Italia", "es_ES");
      }
    }
    
    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("Estimado becario del MEC, google no reconoce esta direcci&oacute;n para dibujar el recorrido, pudiendo ser que la direcci&oacute;n es muy nueva. No dejes de probar en esta p&aacute;gina para calcular e imprimir tus recorridos por la zona, a tu alojamiento etc. aunque contrates tu curso en otro sitio, usa esta p&aacute;gina con toda libertad.\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_UNAVAILABLE_ADDRESS)  <--- Doc bug... this is either not defined, or Doc is wrong
	//     alert("The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.\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(){ 
      // Use this function to access information about the latest load() results.
	}
	  
	  
///////////////////////////////////////////////////////////////////////
// The add-on code for draggable markers
// Esa 2008
//
	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});
		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');
		  });
		}
// End of draggable markers code
// Esa 2008
///////////////////////////////////////////////////////////////////////
	}	
	
    //]]>
