var map;
var centrar_mapa = true;
var geocoder = null;
var resultados;
var paso;

var hibridoLayers;
var mapaLayers;
var mapaMapType;
var hibridoMapType;
var latitudInicial;
var longitudInicial;
var latitudLongitudPropia = null;

function load(latitud, longitud, region) {
    latitudInicial = latitud;
    longitudInicial = longitud;

    mostrarPaso1Mapa();

    if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("map"));
        map.addControl(new GSmallMapControl());
        map.setCenter(new GLatLng(latitud, longitud), 13);

        map.addControl (new GMapTypeControl());

        geocoder = new GClientGeocoder();
        geocoder.setBaseCountryCode(region);

		var latlng = new GPoint (latitud,longitud);
		var marker = new GMarker(latlng);
		map.addOverlay(marker);

        GEvent.addListener(map, "click", function(overlay, latlng) {
            if ((paso == 3) || (paso==1) ) {
				if (latlng){
					marker.setPoint(latlng);
					latitudLongitudPropia = latlng;
	               	mostrarPaso3Mapa();
                    mostrarContenidoPaso3(latlng, "Mi ubicacion", -1);
					if (paso==1)
						paso=3;
				}
			}
			opener.document.publicacion.coordenada_x.value = latlng.lat();
			opener.document.publicacion.coordenada_y.value = latlng.lng();
        });
    }
}

function loadForView(latitud, longitud, titulo, mensaje) {

   if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("map"));
        map.setCenter(new GLatLng(latitud, longitud), 16);
        map.addControl (new GMapTypeControl());
		map.addControl(new GSmallMapControl());

		function createMarker(point, titulo) {
			var marker = new GMarker(point);
			GEvent.addListener(marker, 'click', function() {
					marker.openInfoWindowHtml("<span style='font-weight: bold; font-size: 8pt; font-family: verdana;'>" + titulo + "</span><br><br><span style='font-size: 8pt; font-family: verdana;'>"+ mensaje + "<br></span>", {maxWidth: 70, maxHeight: 90});
			});
			return marker;
		}


		var point = new GPoint (longitud,latitud);
		var marker = createMarker (point, titulo);
		map.addOverlay(marker);

    }
}


function loadBusqueda(latitud, longitud, arr_x, arr_y, arr_t, arr_u, arr_m, arr_r) {
   		if (GBrowserIsCompatible()) {
        	map = new GMap2(document.getElementById("map"));
     		map.setCenter(new GLatLng(latitud, longitud), 10);
      		map.addControl (new GMapTypeControl());
			map.addControl(new GSmallMapControl());


			var iconoMarca = new GIcon(G_DEFAULT_ICON);
			var tamanoIcono = new GSize(17,17);
			iconoMarca.iconSize = tamanoIcono;
			//iconoMarca.shadow = "img/sombra-bandera2.png";
			//var tamanoSombra = new GSize(22,18);
			//iconoMarca.shadowSize = tamanoSombra;
			iconoMarca.iconAnchor = new GPoint(11, 16);


			function createMarker(point,titulo,url,mensaje) {
				var marker = new GMarker(point,iconoMarca);
				GEvent.addListener(marker, 'click', function() {

				marker.openInfoWindowHtml("<span style='font-weight: bold; font-size: 8pt; font-family: verdana'>" + titulo + "</span><br><span style='font-size: 8pt; font-family: verdana'>"+mensaje+"<br><a target='_blank' href='http://" + url + "'>Ir al mensaje " + url + "</a></span>");
			});
			return marker;
			}


			for(var q=0;q<arr_x.length;q++){
			switch(arr_r[q]){
				case "Inmuebles":
						iconoMarca.image = "img/inmueble.png";
				break;

				case "Autos":
						iconoMarca.image = "img/auto.png";
					break;

				case "Negocios":
						iconoMarca.image = "img/negocios.png";
					break;
			}
			var point = new GPoint (arr_y[q],arr_x[q]);
			var marker = createMarker (point, arr_t[q], arr_u[q], arr_m[q]);
			map.addOverlay(marker);
		}
    }
}

function addListener (element, event, listener, bubble) {
    if (element.addEventListener) {
        if (typeof(bubble) == "undefined") bubble = false;
        element.addEventListener (event, listener, bubble);
    } else if (this.attachEvent) {
        element.attachEvent ("on" + event, listener);
    }
}

//addListener(this, "load", function() { load(-32.8898744, -68.8447914); });
addListener(this, "unload", function () { GUnload(); });



var req;
var latitudSeleccionada;
var longitudSeleccionada;
var latitudesPosibles = new Array();
var longitudesPosibles = new Array();

function buscarDirecciones(localidad) {
    geocoder.setViewport(map.getBounds());

    var calle = document.getElementById("calle").value;
    var altura = document.getElementById("altura").value;

    geocoder.getLocations(calle + " " + altura + ", " + localidad, mostrarResultadosBusquedaDirecciones);

    mostrarPaso2Mapa();
}

function mostrarResultadosBusquedaDirecciones(response) {
    if (!response || response.Status.code != 200) {
        // No trajo nada
    } else {
        var divResultados = document.getElementById("divResultados");

        var itemsResultado = divResultados.getElementsByTagName("div");
        for (var i = (itemsResultado.length - 1); i >= 0 ; i--) {
            divResultados.removeChild(itemsResultado[i]);
        }

        var divTitulo = document.createElement("div");
        divTitulo.setAttribute("class", "resultados");
        divTitulo.appendChild(document.createTextNode("Selecciona el domicilio (clic sobre el mapa para indicar una ubicacion propia)"));

        divResultados.appendChild(divTitulo);

        resultados = new Array();
        for (var i = 0; i < response.Placemark.length; i++) {
            try {
                var divResultado = document.createElement("div");
                divResultado.setAttribute("class", "resultados");

                var link = document.createElement("a");
                link.setAttribute("id", "link_" + i);
                if (link.addEventListener) {
                    link.addEventListener("click", mostrarPlaceMark, false);
                } else {
                    link.attachEvent("onclick", mostrarPlaceMark);
                }
                link.setAttribute("style", "cursor: pointer;");
                link.setAttribute("href", "#0");
                link.appendChild(
                    document.createTextNode(
                        (i + 1) + " - " + response.Placemark[i].address));
                divResultado.appendChild(link);

//				var xx = response.Placemark[i].Point.coordinates[1];
//				var yy = response.Placemark[i].Point.coordinates[0];

                divResultados.appendChild(divResultado);
				map.clearOverlays();
				var punto = new GLatLng (response.Placemark[i].Point.coordinates[1], response.Placemark[i].Point.coordinates[0]);
				var marcador = new GMarker(punto);
				map.addOverlay(marcador);

				resultados[i] = response.Placemark[i];
            } catch (err) {
                alert(err);
            }
        }
		//permite el uso de click para elegir ubicacion
		GEvent.addListener(map, "click", function(overlay, punto) {
			if (punto)
				marcador.setPoint(punto);

				var place = resultados[0];
				opener.document.publicacion.coordenada_x.value = punto.lat();
				opener.document.publicacion.coordenada_y.value = punto.lng();
			}
		);
    }
}

function mostrarPlaceMark(evt) {
    latitudLongitudPropia = null;

    var indice = null;

    if (document.all) {
        indice = evt.srcElement.id.substring(evt.srcElement.id.indexOf("_") + 1);
    } else {
        indice = this.id.substring(this.id.indexOf("_") + 1);
    }

    var place = resultados[indice];

	opener.document.publicacion.coordenada_x.value = place.Point.coordinates[1];
	opener.document.publicacion.coordenada_y.value = place.Point.coordinates[0];

    mostrarPaso3Mapa();

	mostrarContenidoPaso3(
        new GLatLng(
            place.Point.coordinates[1],
            place.Point.coordinates[0]),
        place.address,
        indice);
}

function mostrarContenidoPaso3(latLong, address, indice) {
    var divDomicilioSeleccionado = document.getElementById("divDomicilioSeleccionado");

    map.setCenter(latLong,16);

    var itemsResultado = divDomicilioSeleccionado.getElementsByTagName("div");
    for (var i = (itemsResultado.length - 1); i >= 0 ; i--) {
        divDomicilioSeleccionado.removeChild(itemsResultado[i]);
    }

    var divTitulo = document.createElement("div");
    divTitulo.setAttribute("class", "resultados");
    divTitulo.appendChild(document.createTextNode("Se creara el mapa con el siguiente domicilio:"));

    divDomicilioSeleccionado.appendChild(divTitulo);


    var divDomicilio = document.createElement("div");
    divDomicilio.setAttribute("class", "resultados");
    var strongDomicilio = document.createElement("strong");
    strongDomicilio.appendChild(document.createTextNode(address));
    divDomicilio.appendChild(strongDomicilio);

    divDomicilioSeleccionado.appendChild(divDomicilio);

    var divCorrecto = document.createElement("div");
    divCorrecto.setAttribute("class", "resultados");
    var hCorrecto = document.createElement("h");
    hCorrecto.appendChild(document.createTextNode("es correcto?"));
    divCorrecto.appendChild(hCorrecto);

    divDomicilioSeleccionado.appendChild(divCorrecto);


    var divSiCorrecto = document.createElement("div");
    divSiCorrecto.setAttribute("class", "boton-mapas");
    divSiCorrecto.className = "boton-mapas";
    var linkSiCorrecto = document.createElement("a");
    if (indice != -1) {
        linkSiCorrecto.setAttribute("id", "linkSiCorrecto_" + indice);
    }
    if (linkSiCorrecto.addEventListener) {
        linkSiCorrecto.addEventListener("click", confirmarMapa, false);
    } else {
        linkSiCorrecto.attachEvent("onclick", confirmarMapa);
    }
    linkSiCorrecto.setAttribute("style", "cursor: pointer;");
    linkSiCorrecto.setAttribute("href", "#0");
    linkSiCorrecto.appendChild(document.createTextNode("SI"));
    divSiCorrecto.appendChild(linkSiCorrecto);

    divDomicilioSeleccionado.appendChild(divSiCorrecto);


    var divNoCorrecto = document.createElement("div");
    divNoCorrecto.setAttribute("class", "boton-mapas");
    divNoCorrecto.className = "boton-mapas";
    var linkNoCorrecto = document.createElement("a");
    //linkNoCorrecto.setAttribute("id", "linkNoCorrecto_" + indice);
    if (linkNoCorrecto.addEventListener) {
        linkNoCorrecto.addEventListener("click", volverAResultadosMapa, false);
    } else {
        linkNoCorrecto.attachEvent("onclick", volverAResultadosMapa);
    }
    linkNoCorrecto.setAttribute("style", "cursor: pointer;");
    linkNoCorrecto.setAttribute("href", "#0");
    linkNoCorrecto.appendChild(document.createTextNode("NO"));
    divNoCorrecto.appendChild(linkNoCorrecto);

    divDomicilioSeleccionado.appendChild(divNoCorrecto);
}

function volverAResultadosMapa() {
    mostrarPaso2Mapa();
}

function confirmarMapa(evt) {
    mostrarPaso4Mapa();

    if (latitudLongitudPropia == null) {
        var indice = null;

        if (document.all) {
            indice = evt.srcElement.id.substring(evt.srcElement.id.indexOf("_") + 1);
        } else {
            indice = this.id.substring(this.id.indexOf("_") + 1);
        }

        var place = resultados[indice];

        indicarCoordenadas(place.Point.coordinates[1], place.Point.coordinates[0]);
    } else {
        indicarCoordenadas(latitudLongitudPropia.lat(), latitudLongitudPropia.lng());
    }
}

function cerrarMapas() {


	opener.document.getElementById('linkNewMap').style.display='none';
	opener.document.getElementById('textLoadedMap').style.display='block';

	window.close();

	return false;

}
function indicarCoordenadas(latitud, longitud) {
    var url = "/coordinates?lattitude=" + latitud + "&longitude=" + longitud;

    if (typeof XMLHttpRequest != "undefined") {
        req = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        req = new ActiveXObject("Microsoft.XMLHTTP");
    }

    req.open("GET", url, true);
    req.onreadystatechange = callbackIndicarCoordenadas;
    req.send(null);
}

function callbackIndicarCoordenadas() {
    // No es necesario hacer nada
}

function mostrarPaso1Mapa() {
    paso = 1;


    document.getElementById("divPasoFinalMapa").style["display"] = "none";
    document.getElementById("divResultados").style["display"] = "none";
    document.getElementById("divDomicilioSeleccionado").style["display"] = "none";

    document.getElementById("divPasosInicialesMapa").style["display"] = "block";
    document.getElementById("imagenPublicidadMapas").style["display"] = "block";
}

function mostrarPaso2Mapa() {
    paso = 2;


    document.getElementById("divPasoFinalMapa").style["display"] = "none";
    document.getElementById("imagenPublicidadMapas").style["display"] = "none";
    document.getElementById("divDomicilioSeleccionado").style["display"] = "none";

    document.getElementById("divPasosInicialesMapa").style["display"] = "block";
    document.getElementById("divResultados").style["display"] = "block";
}

function mostrarPaso3Mapa() {
    paso = 3;

    document.getElementById("divPasoFinalMapa").style["display"] = "none";
    document.getElementById("imagenPublicidadMapas").style["display"] = "none";
    document.getElementById("divResultados").style["display"] = "none";

    document.getElementById("divPasosInicialesMapa").style["display"] = "block";
    document.getElementById("divDomicilioSeleccionado").style["display"] = "block";
}

function mostrarPaso4Mapa() {
    paso = 4;

    document.getElementById("divPasosInicialesMapa").style["display"] = "none";
    document.getElementById("imagenPublicidadMapas").style["display"] = "none";
    document.getElementById("divResultados").style["display"] = "none";
    document.getElementById("divDomicilioSeleccionado").style["display"] = "none";

    document.getElementById("divPasoFinalMapa").style["display"] = "block";
}