// JavaScript Document

// JavaScript Document
var errorComoLlegarDireccion = "No se ha encontrado la localización geográfica de la dirección dada. Puede que la dirección sea demasiado nueva o incorrecta. ";
var errorComoLlegarParseo = "No se ha podido leer correctamente la dirección enviada. ";
var errorDesconocido = "Se ha producido un error desconocido al intentar generar la ruta. ";

var inicializado = false;
var cookieName = 'puntoPartidaComoLlegar';

function origenUsado()
{
	try {
		if ( myCookie = Cookie.read(cookieName) )
		{
			return myCookie;
		}
		else
		{
			return '';
		}
	}
	catch ( e )
	{
		return '';
	}
}

var mapacomol = null;
$(document).ready(function() {
	$.ajax({
	        url: "/cgi-bin/apsesp/municipios/datos_mun.php",
	        dataType: "xml",
	        encoding:"UTF-8",
	        success: xmlSuccess,
	        error: xmlError
	    });
	
	function xmlError( xhrInstance, message, optional ){
	    alert("No fue posible cargar las coordenadas del municipio.");
	}
	
	function xmlSuccess( data, status ){
		//Write your Parse XML Function
	    parseXML( data );
	}
	
	function parseXML( xml ){
	    // XML Tag identifying each item
	    var itemTag = "datos_municipio";
	    // XML Tag giving the latitude
	    var latTag = "latitud";
	    // XML Tag giving the longitude
	    var lngTag = "longitud";
		 // XML Tag giving the longitude
	    var nombreTag = "nombre";
		
		var lat, lng, nombre;

	    //Parse the XML
	    $( xml ).find( itemTag ).each(function(){
	        lat = $( this ).find( latTag ).text();
	        lng   = $( this ).find( lngTag ).text();
			nombre = $(this).find(nombreTag).text();
	    });
 
 		//creamos el mapa donde se ve el municipio de forma estática
        mapa = new GMap2($('#mapa_situacion').get(0),{size: new GSize (anchoMapaMunicipio,altoMapaMunicipio)});
		
		//variable para establecer el nivel de zoom
		if (window.zoomMapa)
		{
			zoomMapa = zoomMapa;
		}
		else { zoomMapa = 14};
				
		mapa.setCenter(new GLatLng(lat, lng), zoomMapa);
		mapa.addControl(new GSmallMapControl());
	    mapa.addControl(new GMapTypeControl());
		
		baseIcon = new GIcon();
		baseIcon.iconSize=new GSize(200,34);
		baseIcon.shadowSize=new GSize(220,34);
		baseIcon.iconAnchor=new GPoint(20,34);
		baseIcon.infoWindowAnchor=new GPoint(40,40);
	
		var icono = new GIcon(baseIcon);
	
		var html1 = '<div class="globo">';
		html1 = '<div id="globo-texto">';
		html1 += '<b>'+unescape(nombre)+'</b>';
		html1 += '</div>';
		html1 += '</div>';
		
		var elpunto = new GLatLng(lat,lng);
		
		marca = creaMarcaPunto(elpunto,html1,'');
		mapa.addOverlay(marca);

		//creamos el mapa donde se verá la ruta
		mapacomol = new GMap2($('#mapaComoLlegar').get(0),{size: new GSize (anchoMapaComoLlegar,altoMapaComoLlegar)});
		mapacomol.setCenter(new GLatLng(lat, lng), zoomMapa);
		mapacomol.addControl(new GSmallMapControl());
	    mapacomol.addControl(new GMapTypeControl());
		
	}
});

function comoLlegar(frm)
{   
	if(!inicializado && GBrowserIsCompatible())
	{
		inicializado = true;

		//var mapacomol = new GMap2($('#mapaComoLlegar').get(0));
		var indicacionesComoLlegar = $('#indicacionesComoLlegar').get(0);

		//mapacomol.addControl(new GSmallMapControl());
                //mapacomol.addControl(new GMapTypeControl());
		gestorComoLlegar = new GDirections(mapacomol, indicacionesComoLlegar);
		GEvent.addListener(gestorComoLlegar, "error", handleErrorsComoLlegar);
	}

	var	origen = frm.puntoPartida.value;
	//var myCookie = Cookie.write(cookieName, origen, {'path': '/'});

	var destino = frm.lugarDestino.value + "@" + frm.latitudDestino.value + ", " + frm.longitudDestino.value;
	
	gestorComoLlegar.load("from: " + origen + " to: " + destino, { "locale": frm.idioma.value });
	
	
	//esta linea muestra el contenedor del div del mapa si existe y queremos que esté oculto al mostrar la página
	//se le pone display none en las css y con esta línea se muestra al desplegarse la ruta

	$('#mapaComoLlegar').parent().css('display','block');
	
	$('#mapaComoLlegar').get(0).style.display = 'block';
	$('#introduccionComoLlegar').get(0).style.display = 'block';
	$('#indicacionesComoLlegar').get(0).style.display = 'block';

}

function creaMarcaPunto(punto,html1,icono) 
{
    var marc = new GMarker(punto);

	GEvent.addListener(marc, "click", function() 
	{
 		marc.openInfoWindowTabsHtml([new GInfoWindowTab("Situaci?n",html1)]);
  });
  return marc;
   
} 

function handleErrorsComoLlegar()
{
	$('#introduccionComoLlegar').get(0).style.display = 'none';
	$('#indicacionesComoLlegar').get(0).style.display = 'none';
	
	//Cookie.dispose(cookieName);
	
	if (gestorComoLlegar.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
	{
		alert(errorComoLlegarDireccion);
	}
	else if (gestorComoLlegar.getStatus().code == G_GEO_BAD_REQUEST) {
		alert(errorComoLlegarParseo);
	}
	else
	{
		alert(errorDesconocido);
	}
}
