﻿// Archivo GMapsAPI.js

_mPreferMetric=true;

var map;
var Resultados;
var Index = 0;
var tabIndex = 0;
var AnimacionOn = false;
var FiltroOn = false;
var IconoObraNueva = "img/ObraNueva.png";
var IconoSegundaMano = "img/Segundamano.png";
var IconoSombra = "img/Sombra.png";
var Marcadores;
var presentacionDiv;
var marker1;
var marker2;
var label1;
var label2;
var dist=0;
var line;
var poly;

function createIcon (ObraNueva) {
  var icon = new GIcon();
  if (Boolean.parse(ObraNueva)) {
    icon.image = IconoObraNueva;
  }
  else { 
    icon.image = IconoSegundaMano;
  }
  icon.shadow = IconoSombra;
  icon.iconSize = new GSize(15, 23);
  icon.shadowSize = new GSize(25, 23);
  icon.iconAnchor = new GPoint(7, 23);
  icon.infoWindowAnchor = new GPoint(6, 1);
  return icon;
}         

function multiTabWith(Tabs){
    var width = 300;
    if (Tabs > 3){
        width = width + (Tabs - 3) * 85;
    }
    return width;
}

function createMarker(point, inmuebles, info, options) {
  var marker = new GMarker(point, options);
  GEvent.addListener(marker, "click", function() {
    marker.openInfoWindowTabsHtml(info, {maxWidth:multiTabWith(inmuebles)});    
  });
  return marker;
}

function displayResultadoBusqueda (numeroPuntos) {
    switch (numeroPuntos){
        case 0:
			    document.getElementById(Resultados).value = "Ningún inmueble con los parámetros indicados"
			    break;
        case 1:
  			    document.getElementById(Resultados).value = "Se ha localizado 1 inmueble con los parámetros indicados"
			    break;
        default:
   			    document.getElementById(Resultados).value = "Se han localizado " + numeroPuntos + " inmuebles con los parámetros indicados"
			    break;
    }
}

function miUnescape(htmlCodificado){
    var htmlResult = htmlCodificado;
    htmlResult = htmlResult.replace(/&quot;/gi, '"');
    htmlResult = htmlResult.replace(/&lt;/gi, "<");
    htmlResult = htmlResult.replace(/&gt;/gi, ">");
    htmlResult = htmlResult.replace(/&#47;/gi, "/");
    return htmlResult;   
}

function formatHint(ObraNueva, Segundamano){
    var hint = "";
    if (ObraNueva > 0){
        hint = ObraNueva + " inmuebles de obra nueva";
    }
    if (Segundamano > 0){
        if (hint != ""){
            hint = hint + " -- ";
        }
        hint = hint + Segundamano + " inmuebles de segunda mano";
    }
    return hint;       			       
}

function displayPuntos(URL) {
    Marcadores = new Array();
    map.clearOverlays();
    var Lat = 0;
    var Lng = 0;
    var point;
    var icon;
    var inmuebles;
    var infoTabs;
    var content;
    var hint;
    var point1;
    var point2;
    var radio;
    if (FiltroOn){
        point1 = marker1.getPoint();
        point2 = marker2.getPoint();
        radio = marker1.radio;
    }
	var request = GXmlHttp.create();
	request.open("GET", URL, true);
	request.onreadystatechange = function() {
		if (request.readyState == 4) {
			var xml = GXml.parse(request.responseText);
			var total = xml.documentElement.getElementsByTagName("total");
			var totalInmuebles = total[0].getAttribute("total");
			displayResultadoBusqueda (totalInmuebles);
			if (totalInmuebles > 0){
                var bounds = new GLatLngBounds;
    			var puntos = xml.documentElement.getElementsByTagName("punto");
	    		if (puntos.length > 0){
    			    for (var i = 0; i < puntos.length; i++){
    				    Lat = parseFloat(puntos[i].getAttribute("lat"));
	    			    Lng = parseFloat(puntos[i].getAttribute("lng"));
		    		    point = new GLatLng(Lat, Lng);
                        bounds.extend(point);
    			        totalInmuebles = puntos[i].getAttribute("noinm");  // Total de inmuebles en cada punto
    			        inmuebles = puntos[i].getElementsByTagName("inmueble");
                        infoTabs = new Array();
                        var ON = 0;
                        var SM = 0;
    			        for (var j = 0; j < inmuebles.length; j++){
    			            content = new GInfoWindowTab(j + 1, miUnescape(inmuebles[j].getAttribute("info")));
    			            infoTabs.push(content);
    			            if (Boolean.parse(inmuebles[j].getAttribute("onue"))){
    			                ON++;
    			            }
    			            else {
    			                SM++;
    			            }    			            
    			        }
     			        if (totalInmuebles == 1){
       			            icon = createIcon(inmuebles[0].getAttribute("onue"));
       			            hint = inmuebles[0].getAttribute("hint");
   			            }
   			            else{
   			                if (ON > SM){
           			            icon = createIcon("true");
           			        }
           			        else {
       			                icon = createIcon("false");
       			            }
       			            hint = formatHint(ON, SM);
   			            }
                        Marcador = createMarker(point, inmuebles.length, infoTabs, {title:hint,icon: icon});
                        Marcador.info = infoTabs;
                        Marcador.inmuebles = inmuebles.length;
                        Marcadores.push(Marcador);
            	        map.addOverlay(Marcador);
    			    }
			    }
                if (FiltroOn){
                    annadeRegla(point1, point2, radio, false);
                    pintaCirculo();
                    filtraPuntos();
                }
                else {
        		    map.setCenter(bounds.getCenter());
                    map.setZoom(map.getBoundsZoomLevel(bounds));
                }
			}
		}
	}
	request.send(null);
}

function comienzaAnimacion(){
    if (AnimacionOn == true) {
        AnimacionOn = false;
    }
    else
    {
        Index=0;
        AnimacionOn = true;
        window.setTimeout("Animacion();", 100);
    }
}

function Animacion(){
    var Timeout = 0;
    map.closeInfoWindow();  
    if ((Index < Marcadores.length) && (AnimacionOn == true)) {
        if (!Marcadores[Index].isHidden()){
            if (Marcadores[Index].inmuebles == 1){
                Marcadores[Index].openInfoWindowTabsHtml(Marcadores[Index].info, {maxWidth:multiTabWith(Marcadores[Index].inmuebles)});
                Index++;
            }
            else {
                Marcadores[Index].openInfoWindowTabsHtml(Marcadores[Index].info, {maxWidth:multiTabWith(Marcadores[Index].inmuebles),selectedTab:tabIndex});
                tabIndex++;
                if (tabIndex >= Marcadores[Index].inmuebles){
                    tabIndex = 0;
                    Index++;
                }
            }
            Timeout = 3000;
        }
        else {
            Index++;
        }
        window.setTimeout("Animacion();", Timeout); 
    }
    else {
        window.setTimeout("map.closeInfoWindow();", 30);  
        window.setTimeout("AnimacionOn = false;", 30);
        window.setTimeout("presentacionDiv.innerHTML = 'Ver fichas';", 30);
    }

}

function ponCentro (Latitud, Longitud, Zoom)
{
	var lat = parseFloat(Latitud);
	var lng = parseFloat(Longitud);
	var zoom = parseInt(Zoom);
    map.setCenter(new GLatLng(lat, lng), zoom);
}

function displayMapa (elementName, LatCentro, LngCentro, Zoom, controlesEspeciales)
{
	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById(elementName));
		map.addControl(new GLargeMapControl());
		map.addControl(new GMapTypeControl());
    	map.addControl(new GScaleControl());
        map.addControl(new GOverviewMapControl()); 
        new GKeyboardHandler(map);
        map.enableContinuousZoom();
        map.enableDoubleClickZoom();
        if (controlesEspeciales) {
            map.addControl(new ControlPresentacion());
            map.addControl(new ControlRegla());
        }
        ponCentro(LatCentro, LngCentro, Zoom);
	}
	else {
	  alert("Su explorador no es compatible con Google Maps. Actualice su explorador a la última versión disponible.");
	}
}

function loadBusqueda (elementName, URL, LatCentro, LngCentro, Zoom, ControlId)
{
	if (GBrowserIsCompatible()) {
	    Resultados = ControlId;
	    displayMapa(elementName, LatCentro, LngCentro, Zoom, true);
		displayPuntos(URL);
	}
}

function loadLocalizacion (elementName, Lat, Lng)
{
	if (GBrowserIsCompatible()) {
	    displayMapa(elementName, Lat, Lng, 13, false);
        var marker = new GMarker(new GLatLng(Lat, Lng));
        GEvent.addListener(marker, "click", function() {
            map.showMapBlowup(new GLatLng(Lat, Lng))
        });
        map.addOverlay(marker);
        map.showMapBlowup(new GLatLng(Lat, Lng));
	}
}

// -------------------------------------------------------------------------------------------------------------------------------------- //

/////////////////////// Ruler code by Esa

iconStart=new GIcon(G_DEFAULT_ICON, "http://maps.google.com/mapfiles/dd-start.png");
iconDest=new GIcon(G_DEFAULT_ICON, "http://maps.google.com/mapfiles/dd-end.png");

function measure(){
    if (marker1 && marker2){
        line = [marker1.getPoint(),marker2.getPoint()];
        dist = marker1.getPoint().distanceFrom(marker2.getPoint());
        marker1.radio = dist;
        dist = dist.toFixed(0) + "m";
        if(parseInt(dist)>10000){
            dist=(parseInt(dist)/1000).toFixed(2) + "Km";
        }
        label1.setContents(dist);
        label1.setPoint(marker1.getPoint());
        label2.setContents(dist);
        label2.setPoint(marker2.getPoint());
        if (poly){
            map.removeOverlay(poly);
        }
        poly = new GPolyline(line,"#FF00FF", 2, 0.6)
        map.addOverlay(poly);
    }
}

function borraRegla(){
    map.removeOverlay(marker1.circulo);
    map.removeOverlay(marker1);
    map.removeOverlay(marker2);
    map.removeOverlay(poly);
    map.removeOverlay(label1);
    map.removeOverlay(label2);
    if (map.getInfoWindow().isHidden() == false){
        map.closeInfoWindow();
    }
    dist=0;
}

function pintaCirculo(){
	marker1.circulo = drawEarthCircle(marker1.getPoint(), marker1.radio, "#9999FF", 2, 6);
	map.addOverlay(marker1.circulo);
}

function borraCirculo(){
	map.removeOverlay(marker1.circulo);
}

function drawEarthCircle(center, radius, color, width, complexity) {
	var points = [];
	var radians = Math.PI / 180;
	var longitudeOffset = radius / (Math.cos(center.y * radians) * 111325);
	var latitudeOffset = radius / 111325;
	for (var i = 0; i < 360; i += complexity) {
		var point = new GPoint(center.x + (longitudeOffset * Math.cos(i * radians)), center.y + (latitudeOffset * Math.sin(i * radians)));
		points.push(point);
	}
	points.push(points[0]);         // close the circle
	var polyline = new GPolygon(points, color, width, 0.8, "#CCCCFF", 0.4);
	map.addOverlay(polyline);
	return polyline;
} 

function annadeRegla(point1, point2, radio, conAyuda){
    marker2 = new GMarker(point2,{draggable: true, icon:iconDest});
    map.addOverlay(marker2);
    marker2.enableDragging();
    //
    label2=new ELabel(point2, dist,"labelstyle",new GSize(5,25),100);
    map.addOverlay(label2);
    //
    marker1 = new GMarker(point1,{draggable: true, icon:iconStart, dragCrossMove: true});
    marker1.radio = radio;
    marker1.circulo = null;
    map.addOverlay(marker1);
    marker1.enableDragging();
    if (conAyuda){
        marker1.openInfoWindowHtml(
         "<ol style='font-size: 9pt; color: #3300cc; font-family: Arial; list-style-type: disc;'>" +
         "    <li>Se han creado dos marcadores: verde y rojo (este último está oculto por el primero)</li>" +
         "    <li>Centra el área de tu interés moviendo el marcador verde</li>" +
         "    <li>Define el radio del área de interés moviendo el marcador rojo</li>" +
         "    <li>Elige un nivel de zoom que te permita ver todo el área seleccionada</li>" +
         "    <li>Los inmuebles fuera del área seleccionada quedarán ocultos a la vista hasta " +
         "que muevas o cambies el área del filtro o lo desactives</li>" +
         "</ol>");
    }         
    //
    label1=new ELabel(point1, dist,"labelstyle",new GSize(5,25),100);
    map.addOverlay(label1);
    //
    GEvent.addListener(marker1, "drag", function(){measure();});
    GEvent.addListener(marker1, "dragstart", function(){
        if (map.getInfoWindow().isHidden() == false){
            map.closeInfoWindow();
        }
        borraCirculo();});
    GEvent.addListener(marker1, "dragend", function(){
        pintaCirculo();
        filtraPuntos();});
    GEvent.addListener(marker1, "dblclick", function(){clr();});
    GEvent.addListener(marker2, "drag", function(){measure();});
    GEvent.addListener(marker2, "dragstart", function(){borraCirculo();});
    GEvent.addListener(marker2, "dragend", function(){
        pintaCirculo();
        filtraPuntos();});
    GEvent.addListener(marker2, "dblclick", function(){clr();});
}

function displayResultadoFiltro (numeroPuntos){
    var Result = document.getElementById(Resultados).value;
    switch(numeroPuntos){
        case 0:
            Result = Result + ". Ninguno en el área seleccionada";
            break;
        default:
   	        Result = Result + ". " + numeroPuntos + " en el área seleccionada";
   	        break;
    } 
    document.getElementById(Resultados).value = Result;
}

function filtraPuntos(){
    var marker;
    var j = 0;
	for (var i = 0; i < Marcadores.length; i++) {
	    marker = Marcadores[i];
	    if (marker1.getPoint().distanceFrom(marker.getPoint()) > marker1.radio){
	        if (!marker.isHidden()){
	            marker.hide();
	        }
	    }
	    else
	    {
	        if (marker.isHidden()){
                marker.show();
            }
            j++;
	    }
	}
	displayResultadoBusqueda(Marcadores.length);
    if (Marcadores.length != 0){
        displayResultadoFiltro (j)
	}
}

function quitaFiltroPuntos(){
	for (var i = 0; i < Marcadores.length; i++) {
        Marcadores[i].show();
	}
	displayResultadoBusqueda(Marcadores.length);
}

///Geo

var geocoder = new GClientGeocoder();

function showAddress(address){
    geocoder.getLatLng(address,function(point){
        if(!point){
            alert(address + " not found");
        }
        else
        {
            map.panTo(point);
        }
    })
}

function direct(){
    var saddr = document.getElementById("saddr").value;
    var daddr = document.getElementById("daddr").value;
    var txt = 'http://maps.google.com/?saddr=' + saddr +'&daddr=' + daddr;
    return txt;
}

// -------------------------------------------------------------------------------------------------------------------------------- //

    function ControlPresentacion() {
    }
    
    ControlPresentacion.prototype = new GControl();

    ControlPresentacion.prototype.initialize = function(map) {
      var container = document.createElement("div");

      presentacionDiv = document.createElement("div");
      this.setButtonStyle_(presentacionDiv);
      container.appendChild(presentacionDiv);
      presentacionDiv.appendChild(document.createTextNode("Ver fichas"));
      GEvent.addDomListener(presentacionDiv, "click", function() {
        comienzaAnimacion();
        if (AnimacionOn == true){
            presentacionDiv.innerHTML = "Parar fichas";
        }
        else
        {
            presentacionDiv.innerHTML = "Ver fichas";
        }
      });

      map.getContainer().appendChild(container);
      return container;
    }

    ControlPresentacion.prototype.getDefaultPosition = function() {
       return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(350, 7));
    }

    // Sets the proper CSS for the given button element.
    ControlPresentacion.prototype.setButtonStyle_ = function(button) {
      button.style.color = "black";
      button.style.backgroundColor = "white";
      button.style.font = "small Arial";
      button.style.fontSize = "12px";
      button.style.fontWeight = "bold";
      button.style.border = "1px solid black";
      button.style.padding = "1px";
      button.style.marginBottom = "2px";
      button.style.textAlign = "center";
      button.style.width = "80px"; 
      button.style.cursor = "pointer";
      button.style.position = "absolute";
    }

    function ControlRegla() {
    }
    
    ControlRegla.prototype = new GControl();

    ControlRegla.prototype.initialize = function(map) {
      var container = document.createElement("div");
      var ReglaDiv = document.createElement("div");
      this.setButtonStyle_(ReglaDiv);
      container.appendChild(ReglaDiv);
      ReglaDiv.appendChild(document.createTextNode("Filtrar zona"));
      GEvent.addDomListener(ReglaDiv, "click", function() {
        if (FiltroOn == true){
            quitaFiltroPuntos();
            ReglaDiv.innerHTML = "Filtrar zona";
            FiltroOn = false;
            borraRegla();
        }
        else
        {
            ReglaDiv.innerHTML = "Ver todos";
            FiltroOn = true;
            annadeRegla(map.getCenter(),map.getCenter(), 0, true);
        }
      });

      map.getContainer().appendChild(container);
      return container;
    }

    ControlRegla.prototype.getDefaultPosition = function() {
       return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(438, 7));
    }

    // Sets the proper CSS for the given button element.
    ControlRegla.prototype.setButtonStyle_ = function(button) {
      button.type = "button";
      button.style.color = "black";
      button.style.backgroundColor = "white";
      button.style.font = "small Arial";
      button.style.fontSize = "12px";
      button.style.fontWeight = "bold";
      button.style.border = "1px solid black";
      button.style.padding = "1px";
      button.style.marginBottom = "2px";
      button.style.textAlign = "center";
      button.style.width = "80px"; 
      button.style.cursor = "pointer";
      button.style.position = "absolute";
    }
