////////////////////////////////
// GOOGLE MAPS
////////////////////////////////

var MAXZOOM = 13;

// Global variables
var map;
//var KmlOverlay;
var exml;

var frameHeight, frameWidth;
function CalculateHeightWidth()
{
    if (self.innerWidth)
    {
        frameHeight = self.innerHeight;
        frameWidth  = self.innerWidth;
    }
    else if (document.documentElement && document.documentElement.clientWidth)
    {
        frameHeight = document.documentElement.clientHeight;
        frameWidth  = document.documentElement.clientWidth;
    }
    else if (document.body)
    {
        frameHeight = document.body.clientHeight;
        frameWidth  = document.body.clientWidth;
    }
}

var actualHeight = 0;
var actualWidth  = 0;
function resizeMapDiv()
{
    CalculateHeightWidth();

    if ( (frameHeight != actualHeight) || (frameWidth != actualWidth) )
    {
        actualHeight = frameHeight;
        actualWidth  = frameWidth;

        document.getElementById("map").style.height = (frameHeight-40)+"px";
        document.getElementById("map").style.width  = (frameWidth -40)+"px";
        document.getElementById("menumap").style.width  = (frameWidth -40)+"px";

        if (map)
        {
            var zoom   = map.getZoom();
            var center = map.getCenter()
            map.checkResize();
            map.setCenter(center, zoom);
        }

        document.getElementById("map").style.background = "#CCB557";
    }
}

function load(latInicial, lngInicial, zoomInicial)
{
    if (typeof(latInicial) == 'undefined')
    {
        // load llamado sin parámetros: default position
        CalculateHeightWidth();
        if (frameWidth > 900)
            zoomInicial  = 13;
        else zoomInicial = 12;

        latInicial   = 40.422644;
        lngInicial   = -3.702908;
    }

    if (GBrowserIsCompatible())
    {
        // Create the map
        map = new GMap2(document.getElementById("map"));
        map.addControl(new GLargeMapControl());
        map.addControl(new GMapTypeControl());

        // Add a scale control with white text
        var scale = new GScaleControl();
        map.addControl(scale)
        //scale.fpsLbl.style.color    = '#ffffff';
        //scale.metricLbl.style.color = '#ffffff';

        map.setCenter (new GLatLng(latInicial, lngInicial), zoomInicial);
        map.enableContinuousZoom();
        map.enableDoubleClickZoom();

        // Add a minimap
        var minimap=new GOverviewMapControl(new GSize(200, 150));
        map.addControl(minimap);
        minimap.hide();

        // Add the kml overlay: it will refresh each minute
        KmlOverlay = new GGeoXml("http://www.salirdetapas.com/salirdetapas.kmz");
        //KmlOverlay = new GGeoXml("http://www.salirdetapas.com/salirdetapas.kml");
        map.addOverlay(KmlOverlay);
        //exml = new EGeoXml("exml", map, "salirdetapas.kml?aaa", {iwwidth:356,descstyle:"background-color: #CCB557",nozoom:true});
        //exml.parse();

        // Create the show/hide markers control
        function ShowHideMarkers() {}
        ShowHideMarkers.prototype = new GControl();

        ShowHideMarkers.visible=true;
        ShowHideMarkers.prototype.initialize = function(map)
        {
          var container = document.createElement("div");
          ShowHideMarkers.container = container;

          this.setButtonStyle_(container);
          container.appendChild(document.createTextNode("Oculta resultados"));
          GEvent.addDomListener(container, "click", function()
          {
            if (this.visible == true)
            {
              //map.removeOverlay(KmlOverlay);
              this.visible = false;
              ShowHideMarkers.container.innerHTML = "Muestra resultados";
            }
            else
            {
              //map.addOverlay(KmlOverlay);
              this.visible = true;
              ShowHideMarkers.container.innerHTML = "Oculta resultados";
            }
          });

          map.getContainer().appendChild(container);
          return container;
        }

        ShowHideMarkers.prototype.getDefaultPosition = function()
        {
          return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(7, 7));
        }

        ShowHideMarkers.prototype.setButtonStyle_ = function(button)
        {
          button.style.border          = "1px solid black";
          button.style.backgroundColor = "white";
          button.style.color           = "#000000";
          button.style.cursor          = "pointer";

          button.style.width           = "92px";
          button.style.marginLeft      = "72px";

          button.style.font            = "small Arial";
          //button.style.fontWeight      = "bold";
          button.style.textAlign       = "center";
        }

        map.addControl(new ShowHideMarkers());

        GEvent.addListener(map,"click",function(overlay,latlng)
        {
            if (latlng)
            {
                // the code to be performed when map is clicked

                // create an HTML DOM form element
                var inputForm=document.createElement("form");
                inputForm.setAttribute("action","");
                inputForm.onsubmit=function(){storeMarker(map); return false;};


                //put currently clicked point's lat and long in temp variables
                var lat=latlng.lat();
                var lng=latlng.lng();

                //the form
                inputForm.innerHTML='<fieldset style="size:150px;">'
                +'<legend>Comparte bares conocidos!</legend>'
                +'<div class="black">¿Conoces algún bar de tapeo<br/>que no esté dado de alta?<br/><a href=\"manageitem.php?action=new&lat='+ lat +'&lon='+ lng +'\" target="_blank">añádelo!</a></div>';

                map.openInfoWindow(latlng,inputForm);
            }
        });

        // We start the function that will monitor resizes (because of IE's bug).
        resizeMapDiv();
        setInterval(resizeMapDiv, 1000);
    }
}

function roundNumber(float, dec)
{
    return Math.round(float*Math.pow(10,dec))/Math.pow(10,dec)
}

function getUrlLatLngZ(baseurl)
{
    if (map)
    {
        var center = map.getCenter();
        var lat    = roundNumber(center.lat(), 6);
        var lng    = roundNumber(center.lng(), 6);
        var zoom   = map.getZoom();

        return baseurl + "?lat=" + lat + "&lng=" + lng + "&z=" + zoom;
    }
    else return baseurl;
}

function sendLocationByEmail(local, baseurl)
{
    var url;
    if (local == true)
    {
        url = getUrlLatLngZ(baseurl).replace(/&/g,"%26");
    }
    else
    {
        url = "http://www.salirdetapas.com";
    }

    top.location.href = ("mailto:?subject=Página web interesante: Listado de bares y principales tapas que sirven&body=Hey!%0D%0A%0D%0ATienes que ver esta página web. Listado de bares y tapas que sirven, utilizando la interfaz de Google Maps!%0D%0A%0D%0A" + url + "%0D%0A%0D%0A%0D%0AUn saludo!");
}

var geo = null;
var marker;
function showAddress()
{
    var address = document.getElementById("search").value;
    if (geo == null) geo = new GClientGeocoder();

    geo.getLocations(address,
        function(result)
        {
            if (result.Status.code != G_GEO_SUCCESS)
            {
                alert(address + " not found");
            }
            else
            {
                var lat      = result.Placemark[0].Point.coordinates[1];
                var lng      = result.Placemark[0].Point.coordinates[0];
                var point    = new GLatLng(lat, lng);
                var html     = result.Placemark[0].address;
                var fullhtml = "<div class='black'><strong>" + html + "</strong>" +
                               "<br />lat = " + lat + " long = " + lng +
                               "<br />&nbsp;<br/>¿Conoces algún bar de tapeo<br/>que no esté dado de alta?<br/><a href=\"manageitem.php?action=new&lat='+ lat +'&lon='+ lng +'\" target=\"_blank\">añádelo!</a></span>" +
                               "<br />&nbsp;<br/><a href=\"javascript:map.closeInfoWindow();map.removeOverlay(marker);\">remove marker</a></div>";

                map.setCenter(point, MAXZOOM);
                marker = new GMarker(point);
                GEvent.addListener(marker, "click", function() { marker = this; marker.openInfoWindowHtml(fullhtml); });
                map.addOverlay(marker);
                marker.openInfoWindowHtml(fullhtml);
            }
        }
    );
}

function GoToDetailedMap(text)
{
    if (text == "Madrid")
        map.setCenter(new GLatLng(40.424082, -3.695269), 13);
    else if (text == "Barcelona")
        map.setCenter(new GLatLng(41.387917,  2.169919), 13);
    else if (text == "Salamanca")
        map.setCenter(new GLatLng(40.964972, -5.663047), 14);
    else if (text == "Granada")
        map.setCenter(new GLatLng(37.176487, -3.597929), 14);
    else if (text == "Zaragoza")
        map.setCenter(new GLatLng(41.656288, -0.876606), 14);
    else if (text == "Murcia")
        map.setCenter(new GLatLng(37.983375, -1.129897), 14);
    else if (text == "Malaga")
        map.setCenter(new GLatLng(36.719674, -4.420036), 14);
    else if (text == "Alicante")
        map.setCenter(new GLatLng(38.346041, -0.484756), 14);
}

function GoToDetailedMapByListBox(box)
{
    if (box.selectedIndex == 0) return;

    GoToDetailedMap(box.options[box.selectedIndex].text);
}
