//Zoom por defecto
var zoom = 5;
var zoomM = 13;
var zoomN = 15;
var lat = 40.396764;
var lng = -3.713379;

//Funcion Load que carga el mapa por defecto
function load() {
      if (GBrowserIsCompatible()) {
        var map = new GMap2(document.getElementById("mapa"));
        map.setCenter(new GLatLng(lat, lng), zoom);
      }
}

//Funcion Load que carga el mapa por defecto
function loadAll() {

      if (GBrowserIsCompatible()) {
		
		var latlng = new GLatLng(parseFloat(lat), parseFloat(lng));
		map = new GMap2(document.getElementById("mapa"));
		map.setCenter(latlng, zoom);
		
		var request = GXmlHttp.create();
		request.open('GET', 'http://www.todoterrenos.biz/anuncios/sacar-direcciones-anuncios.php', true);
		request.onreadystatechange = function() {
			
			var xmlDoc = request.responseXML;
			var markers = xmlDoc.getElementsByTagName("marker");
			
			for (var i=0;i<markers.length;i++){
				
				var dir = markers[i].getAttribute("dir");
				var tit = markers[i].getAttribute("ti");
				
				html = "<p></p><p><b>" + tit +"</b></p>";
				localizar(dir, map, tit);

			}
		}
		request.send(null);
		
		map.addControl(new GLargeMapControl());
		map.addControl(new GMapTypeControl());
	}
}

function localizar(dir, map, tit) {

      //Creamos cliente Geocoder
      var geo = new GClientGeocoder(); 
 
      //Creamos un array con errores
      var reasons=[];
      reasons[G_GEO_SUCCESS]            = "Success";
      reasons[G_GEO_MISSING_ADDRESS]    = "Missing Address: The address was either missing or had no value.";
      reasons[G_GEO_UNKNOWN_ADDRESS]    = "Unknown Address:  No corresponding geographic location could be found for the specified address.";
      reasons[G_GEO_UNAVAILABLE_ADDRESS]= "Unavailable Address:  The geocode for the given address cannot be returned due to legal or contractual reasons.";
      reasons[G_GEO_BAD_KEY]            = "Bad Key: The API key is either invalid or does not match the domain for which it was given";
      reasons[G_GEO_TOO_MANY_QUERIES]   = "Too Many Queries: The daily geocoding quota for this site has been exceeded.";
      reasons[G_GEO_SERVER_ERROR]       = "Server error: The geocoding request could not be successfully processed.";
      
        
        // ====== Perform the Geocoding ======        
        geo.getLocations(dir, function (result) { 
            // Si hay exito
            if (result.Status.code == G_GEO_SUCCESS) { 
      
              //Centramos el mapa en el primer resultado
              var p = result.Placemark[0].Point.coordinates;
              //map.setCenter(new GLatLng(p[1],p[0]),zoom);
		
			   //Aņadimos un marcador al mapa
			   var marker = crearMarcador(1, new GLatLng(p[1],p[0]), tit);
			   map.addOverlay(marker);
		
          }
            // Si las cosas se ponen chungas
            else {
              var reason="Code "+result.Status.code;
              if (reasons[result.Status.code]) {
                reason = reasons[result.Status.code]
              } 
              alert('Could not find "'+search+ '" ' + reason);
            }
          }
        );
}

function crearMarcador(tipo, latlng, html) {
	//var icon = new GIcon();
	//img = 'http://www.todoterrenos.biz/img/dgt.gif';
	//icon.image = img;
	//icon.iconSize = new GSize(50, 50);
	//icon.iconAnchor = new GPoint(25, 50);
	//icon.infoWindowAnchor = new GPoint(25,25);
	var marker = new GMarker(latlng); //, icon);
	GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml(html); } 
	);
	return marker;
}
