var map;
var directions;
var wayPoints = new Array();

function createMap(id, controls, lat, lng, zoom){
	if (GBrowserIsCompatible()) {
	   	divMap = document.getElementById(id);
	   	map = new GMap2(divMap);
	   	for(i=0; i < controls.length; i++){
     		var aux = "map.addControl(new "+controls[i]+"())";
     		eval(aux);
     	}
     	map.setCenter(new GLatLng(lat,lng), zoom);
	}
}

function createDirections(id){
	if (GBrowserIsCompatible()) {
	   	divDir = document.getElementById(id);
		directions = new GDirections(map, divDir);
	
		GEvent.addListener(directions, "error", handleErrors);
	}
}

function createMarker(lat,lng,type,info,icon){
	var point = new GLatLng(lat,lng);
	createMarkerPoint(point,type,info,icon);
}

function createMarkerPoint(point,type,info,icon){
	
	if(icon == null) var marker = new GMarker(point);
	else var marker = new GMarker(point, icon);
	
	map.addOverlay(marker);
	
	if (type == 'base'){
		marker.openInfoWindowHtml(info);
		GEvent.addListener(marker, "click", function() {
    		marker.openInfoWindowHtml(info);
  		});
	}else{
		marker.openInfoWindowTabsHtml(info);
		GEvent.addListener(marker, "click", function() {
  			marker.openInfoWindowTabsHtml(info);
		});
	}
}

function showAddress(address,zoom) {
	var geocoder = new GClientGeocoder();
	map.clearOverlays();
	geocoder.getLatLng(
		address,
		function(point) {
			if (!point) {
		   	alert("No se ha encontrado '"+address+"'" );
		  	} else {
		   	map.setCenter(point, zoom);
		   	createMarkerPoint(point,'base',address);
/*
		      var marker = new GMarker(point);
		      map.addOverlay(marker);
		      marker.openInfoWindowHtml(address);
*/		      
		 	}
		}
	);
}

function addWayPoint(point){
	wayPoints[wayPoints.length] = point;
	if(wayPoints.length > 1){
		directions.loadFromWaypoints(wayPoints);
	}
}

function deleteWayPoint(index){
	if(index >= 0){
		for (i=index+1; i<wayPoints.length; i++){
			wayPoints[i-1] = wayPoints[i];
		}
		wayPoints.length = wayPoints.length -1;
		if(wayPoints.length > 1){
			directions.loadFromWaypoints(wayPoints);
		}else{
			directions.clear();
		}
	}
}

function handleErrors(){
	if (directions.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
    	alert("No se ha encontrado la dirección especificada. Puede ser que la dirección sea relativamente nueva o errónea.");
	else if (directions.getStatus().code == G_GEO_SERVER_ERROR)
    	alert("No se ha podido procesar la dirección solicitada.");
   
	else if (directions.getStatus().code == G_GEO_MISSING_QUERY)
    	alert("No se ha indicado dirección.");

//   else if (directions.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: " + directions.getStatus().code);
     
	else if (directions.getStatus().code == G_GEO_BAD_KEY)
    	alert("La clave indicada es errónea.");

	else if (directions.getStatus().code == G_GEO_BAD_REQUEST)
    	alert("No se ha podido procesar la dirección solicitada.");
    
	else alert("Se ha producido un error.");
   
}

function addPoint(sPoints, sRoute){
    if(sPoints != null && sPoints.selectedIndex == -1){
        alert("Debe seleccionar un punto de ineterés.");
        sPoints.focus();
	}else{
		var point = new Option(sPoints.options[sPoints.selectedIndex].text, sPoints.options[sPoints.selectedIndex].value);
		sRoute.options[sRoute.options.length] = point;
		addWayPoint(sPoints.options[sPoints.selectedIndex].value);
	}	
}

function deletePoint(sRoute,iAddress){
    if(sRoute != null && sRoute.selectedIndex == -1){
        alert("Debe seleccionar un punto de ineterés.");
        sRoute.focus();
	}else{
		if(iAddress.disabled && sRoute.selectedIndex == 0){
			iAddress.disabled = false;
		}
		deleteWayPoint(sRoute.selectedIndex);
		sRoute.options[sRoute.selectedIndex] = null;
	}	
}

function addAddress(iAddress, sRoute){
	if(iAddress.value == ''){
        alert("Debe indicar la dirección de origen.");
        iAddress.focus();
	}else if(iAddress.disabled){
        alert("Ya está incluida la dirección de origen.");
	}else{
		//add address to route in first position
		var aux = wayPoints.length;
		for(i=aux; i>0; i--){
			wayPoints[i] = wayPoints[i-1];
			sRoute.options[i] = new Option(sRoute.options[i-1].text,sRoute.options[i-1].value);
		}
		wayPoints[0] = iAddress.value;
		iAddress.disabled = true;
		
		//add address to route select
		var point = new Option(iAddress.value, iAddress.value);
		sRoute.options[0] = point;
		
		//refresh route information
		if(wayPoints.length > 1){
			directions.loadFromWaypoints(wayPoints);
		}
	}
}
