////////////////////////////////
// GOOGLE MAPS
////////////////////////////////

// Constants
var MAXZOOM     = 7;  // Max coverage of the entire world
var MAXFAKEZOOM = 7;  // Max artificial zoom
var MAXCITYZOOM = 11; // Max level of detailed cities

// Global variables
var mapanocturno;
var map;
var KmlOverlay;

function NightGetTileUrl(a, b)
{
    // We'll always use the deeper layer available (MAXZOOM)
    if ( (b > MAXZOOM) && (b <= MAXFAKEZOOM) )
        b = MAXZOOM;

    return "nightmaps/level" + b + "/map_" + b + "_" + (a.x) + "_" + (a.y) + ".gif";
}

function zoomed()
{
    var zoom = map.getZoom();
    var last = mapanocturno.Hc;

    // When zoom > MAXZOOM we resize the tiles so that they fill what the 2^zoomDiff tiles were suppose to draw
    if ( (zoom > MAXZOOM) && (zoom <= MAXFAKEZOOM) )
    {
        var power = Math.pow(2,zoom-MAXZOOM);
        mapanocturno.Ic = 256 * power;
        //mapanocturno.tileSize = 256 * power;
    }
    else
    {
        mapanocturno.Ic = 256;
        //mapanocturno.tileSize = 256;
    }

    if (last != mapanocturno.Hc)
    {
        map.checkResize();
        map.setCenter(map.getCenter(), zoom);
    }
}

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;
//var exml;
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 = "#111744";
    }
}

function load(latInicial, lngInicial, zoomInicial)
{
    if (typeof(latInicial) == 'undefined')
    {
        // load llamado sin parámetros: default position
        CalculateHeightWidth();
        if (frameWidth > 900)
            zoomInicial  = 2;
        else zoomInicial = 1;
    
        latInicial   = 17;
        lngInicial   = -3.42;
    }            

    if (GBrowserIsCompatible())
    {
        // Create the new layer
        var copyright = new GCopyright(1000, new GLatLngBounds(new GLatLng(-90, -180), new GLatLng(90, 180)), 0, "<span class='white'>&copy; 2000 NASA's Visible Earth</span>");
        var copyrightCollection = new GCopyrightCollection("<span class='white'>2007 Jose Manuel G&oacute;mez - Imagery</span>");
        copyrightCollection.addCopyright(copyright);

        var tilelayers = [new GTileLayer(copyrightCollection , 0, MAXCITYZOOM)];
        tilelayers[0].getTileUrl = NightGetTileUrl;

        mapanocturno = new GMapType(tilelayers, new GMercatorProjection(MAXCITYZOOM+1), "Night", {errorMessage:"No data available", alt:"Show night imagery"});

        // 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();
        map.addMapType(mapanocturno);
        map.setMapType(mapanocturno);

        // Add a minimap
        var minimap=new GOverviewMapControl(new GSize(200, 150));
        map.addControl(minimap);
        minimap.hide();

        // Modify the behaviour of the zoom
        GEvent.addListener(map, "zoomend", function() {zoomed();}); // track the user zooming.

        // Add the kml overlay: it will refresh each minute
        KmlOverlay = new GGeoXml("http://www.nightearth.com/nightearth.kmz");
        //KmlOverlay = new GGeoXml("http://www.nightearth.com/nightearth.kml");
        map.addOverlay(KmlOverlay);
        //exml = new EGeoXml("exml", map, "nightearth.kml?aaa", {iwwidth:356,descstyle:"background-color: #000000"});
        //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("Hide Markers"));
          GEvent.addDomListener(container, "click", function()
          {
            if (this.visible == true)
            {
              map.removeOverlay(KmlOverlay);
              this.visible = false;
              ShowHideMarkers.container.innerHTML = "Show Markers";
            }
            else
            {
              map.addOverlay(KmlOverlay);
              this.visible = true;
              ShowHideMarkers.container.innerHTML = "Hide Markers";
            }
          });
        
          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>Share your images!</legend>'
                +'Do you have a beautiful night photo<br/>you want to share with your friends or<br/>with the world? <a href=\"manageitem.php?action=new&lat='+ lat +'&lon='+ lng +'\" target="_blank">upload it!</a>';
                
                map.openInfoWindow(latlng,inputForm);
            }
        });

        // We start the function that will monitor resizes (because of IE's bug).
        resizeMapDiv();
        zoomed();
        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.nightearth.com";
    }
    
    top.location.href = ("mailto:?subject=Interesting web site: Night satellite images with Google Maps interface!&body=Hey!%0D%0A%0D%0AYou need to see this web. Night satellite photos of the world, with Google Maps interface!%0D%0A%0D%0A" + url + "%0D%0A%0D%0A%0D%0ARegards!");
}

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 = "<span class='black'><strong>" + html + "</strong>" +
                               "<br />lat = " + lat + " long = " + lng +
                               "<br />&nbsp;<br/>Do you have a beautiful night photo<br/>you want to share with your friends or<br/>with the world? <a href=\"manageitem.php?action=new&lat="+ lat +"&lon="+ lng +"\">upload it!</a></span>" +
                               "<br />&nbsp;<br/><a href=\"javascript:map.closeInfoWindow();map.removeOverlay(marker);\">remove marker</a></span>";
                
                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 == "Buenos Aires")
        map.setCenter(new GLatLng(-34.63, -58.48), 11);
    else if (text == "Chicago")
        map.setCenter(new GLatLng(41.85, -87.65), 11);
    else if (text == "Los Angeles")
        map.setCenter(new GLatLng(33.85, -118.15), 11);
}

function GoToDetailedMapByListBox(box)
{
    if (box.selectedIndex == 0) return;
    
    GoToDetailedMap(box.options[box.selectedIndex].text);
}
