////////////////////////////////
// GOOGLE MAPS
////////////////////////////////

// Include configuration constants
//var script = document.createElement("script");
//script.type = "text/javascript";
//script.src = "maps_config.js";
//document.getElementsByTagName('head').item(0).appendChild(script);

// Global variables
var nightMapType;
var map;
var KmlOverlay;
var latInicial, lngInicial, zoomInicial;
var infoWindow;

// Load Google Maps script asynchronously

function loadGoogleMapsScript(platInicial, plngInicial, pzoomInicial)
{
    if (typeof(platInicial) != 'undefined')
    {
        // llamado con parámetros
        latInicial  = platInicial;
        lngInicial  = plngInicial;
        zoomInicial = pzoomInicial;
    }
    else
    {
        // load llamado sin parámetros: default position
        CalculateHeightWidth();
        if (frameWidth > 1500)
            zoomInicial  = ZOOMINICIAL+2;
        else if (frameWidth > 900)
            zoomInicial  = ZOOMINICIAL+1;
        else zoomInicial = ZOOMINICIAL;
    
        latInicial = LATINICIAL;
        lngInicial = LNGINICIAL;
    }

    // Load Google Maps V3 library
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.src = "http://maps.google.com/maps/api/js?v=3&sensor=true&libraries=panoramio&callback=initialize";
    document.body.appendChild(script);
    
    // Load jOverviewMapControl library
    if (OVERVIEWMAPCONTROL)
    {
        var script = document.createElement("script");
        script.type = "text/javascript";
        script.src = "jOverviewMapControlV3.js";
        document.body.appendChild(script);
    }
}
//window.onload = loadGoogleMapsScript;

// Simulate higher image details by zooming in the map tiles
function zoomchanged()
{
    var zoom = map.getZoom();

    var last = nightMapType.tileSize.height;

    // 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);
        nightMapType.tileSize.height = 256 * power;
        nightMapType.tileSize.width  = 256 * power;
    }
    else
    {
        nightMapType.tileSize.height = 256;
        nightMapType.tileSize.width  = 256;
    }

    if (last != nightMapType.tileSize.height)
    {
        //map.checkResize();
        google.maps.event.trigger(map, 'resize');
        map.setZoom(zoom);
        map.setCenter(map.getCenter());
    }
}

// focus the map into the screen
function maximizeMap()
{
    document.getElementById('menumap').scrollIntoView();
}

function centerMapInCurrentLocation()
{
    // if the browser supports the W3C geolocation API, get the current position
    if (navigator.geolocation)
    {
        if (map)
        navigator.geolocation.getCurrentPosition(

            // if this was successful, get the latitude and longitude
            function (position)
            {
            	map.setCenter(new google.maps.LatLng(position.coords.latitude, position.coords.longitude));
            },
            
            // if there was an error, show the error message
            function (error)
            {
                alert('It is not possible to obtain the current location.');
            }
        );
        // var watchId = navigator.geolocation.watchPosition(success, error, { enableHighAccuracy:true });
        // navigator.geolocation.clearWatch(watchId);
    }
    else alert('Sorry, your browser does not support the W3C geolocation API. Update it in order to use this functionality.');
}

var currentHeight = 0;
var currentWidth  = 0;
function resizeMapDiv()
{
    CalculateHeightWidth();
    
    if ( (frameHeight != currentHeight) || (frameWidth != currentWidth) )
    {
        currentHeight = frameHeight;
        currentWidth  = frameWidth;
        
        document.getElementById("map_canvas").style.height = (frameHeight - document.getElementById("menumap").offsetHeight)+"px";

        if (map)
        {
            var zoom   = map.getZoom();
            var center = map.getCenter()

            //map.checkResize();
            google.maps.event.trigger(map, 'resize');
            map.setZoom(zoom);
            map.setCenter(center);
        }

        document.getElementById("map_canvas").style.background = MAPCANVASBGCOLOR;
    }
}

// Positive modulo

Number.prototype.mod = function(n) {
    return ((this%n)+n)%n;
}

// main

function initialize()
{
    var mapTypeIdsArray = [null, google.maps.MapTypeId.ROADMAP, google.maps.MapTypeId.SATELLITE, google.maps.MapTypeId.HYBRID, google.maps.MapTypeId.TERRAIN];
    var mapTypeId = google.maps.MapTypeId.ROADMAP;
    
    // Night map layer
    if (SHOWNIGHTMAP)
    {
        nightMapType = new google.maps.ImageMapType({
            getTileUrl: function(coord, zoom) {
                // We'll always use the deeper layer available (MAXZOOM)
                if ( (zoom > MAXZOOM) && (zoom <= MAXFAKEZOOM) )
                zoom = MAXZOOM;

                var zfactor = Math.pow(2, zoom);

                return "nightmaps/level" + zoom + "/map_" + zoom + "_" + (coord.x.mod(zfactor)) + "_" + (coord.y.mod(zfactor)) + ".gif";
            },
            tileSize: new google.maps.Size(256, 256),
            isPng: false,
            alt: "Show night map",
            name: "Night",
            maxZoom: MAXCITYZOOM
        });
        mapTypeIdsArray[0] = 'night';
        mapTypeId = 'night';
    }
    
    // OpenStreetMap layer
    if (SHOWOPENSTREETMAP)
    {
        var osmMapType = new google.maps.ImageMapType({
	        getTileUrl: function(coord, zoom) {
		        return "http://tile.openstreetmap.org/" + zoom + "/" + coord.x + "/" + coord.y + ".png";
	        },
	        tileSize: new google.maps.Size(256, 256),
	        isPng: true,
	        alt: "OpenStreetMap",
	        name: "OpenStreet",
	        maxZoom: 19
        });
        mapTypeIdsArray.push('OpenStreetMap');
    }

    // Create the map
    var mapOptions = { minZoom: 1, zoom: zoomInicial, center: new google.maps.LatLng(latInicial, lngInicial), 
                       scaleControl: true, mapTypeId: mapTypeId, mapTypeControlOptions: { mapTypeIds: mapTypeIdsArray } };
    map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
    
    // Now attach the night map type to the map's registry
    if (SHOWNIGHTMAP)
    {
        map.mapTypes.set('night', nightMapType);
        map.setMapTypeId('night');
    }
    
    if (SHOWOPENSTREETMAP)
	    map.mapTypes.set('OpenStreetMap', osmMapType);

    if (SHOWNIGHTMAP)
    {
        //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 copyrightNode = document.createElement('div');
        copyrightNode.id = 'copyright-control';
        copyrightNode.style.fontSize = '11px';
        copyrightNode.style.color = 'white';
        copyrightNode.style.fontFamily = 'Arial, sans-serif';
        copyrightNode.style.margin = '0 2px 2px 0';
        copyrightNode.style.whitespace = 'nowrap';
        copyrightNode.innerHTML = '2007 Jose Manuel G&oacute;mez - Imagery &copy; 2000 NASA\'s Visible Earth - ';
        copyrightNode.index = 0;
        map.controls[google.maps.ControlPosition.BOTTOM_RIGHT].push(copyrightNode);
    }
    
    // Panoramio Layer
    var panoramioLayer = new google.maps.panoramio.PanoramioLayer();
    panoramioLayer.setTag(PANORAMIOTAGS);
    //panoramioLayer.setMap(map);

    // Set white text to the scale control
    ////scale.fpsLbl.style.color    = '#ffffff';
    ////scale.metricLbl.style.color = '#ffffff';

    // Add a minimap (external library)
    if (OVERVIEWMAPCONTROL)
    {
        var overview = new window.jeremy.jOverviewMapControl(map);
        overview.show();
    }

    // Modify the behaviour of the zoom for the night map
    if (SHOWNIGHTMAP)
        google.maps.event.addListener(map, "zoom_changed", function() {zoomchanged();}); // track the user zooming.

    // Add the kml overlay: it will refresh each minute
    KmlOverlay = new google.maps.KmlLayer(KMZLOCATION + "?" + (new Date()).getTime(), { map:map, preserveViewport:true, suppressInfoWindows:false });
    //KmlOverlay.setMap(map);

    // Create the "show/hide markers" control
    AddShowHideButton(HIDEMARKERS, SHOWMARKERS, KmlOverlay, true);
    AddShowHideButton(HIDEPANORAMIO, SHOWPANORAMIO, panoramioLayer, false);

    // the info window to be shown when map is clicked
    infoWindow = new google.maps.InfoWindow();
    google.maps.event.addListener(map, 'click', function(event)
    {   
        // 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=event.latLng.lat();
        var lng=event.latLng.lng();

        //the form
        inputForm.innerHTML = '<fieldset style="size:150px;"><legend>'+INFOWINDOWCLICKLEGEND+'</legend>' +
                              INFOWINDOWCLICKMSG+'<a href=\"manageitem.php?action=new&lat='+ lat +'&lon='+ lng +'\" target="_blank">'+INFOWINDOWCLICKUPLOAD+'</a>';
        
        infoWindow.setContent(inputForm);
        infoWindow.setPosition(event.latLng);
        infoWindow.open(map);
    });

    // We start the function that will monitor resizes (because of IE's bug).
    resizeMapDiv();
    if (SHOWNIGHTMAP) zoomchanged();
    setInterval(resizeMapDiv, 1000);
}

function roundNumber(floatnum, dec)
{
    return Math.round(floatnum*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 = BASEURL;
    }
    
    top.location.href = ("mailto:?subject="+SENDLOCATIONBYEMAILSUBJECT+"&body="+SENDLOCATIONBYEMAILBODY+"%0D%0A%0D%0A" + url + "%0D%0A%0D%0A%0D%0A"+SENDLOCATIONBYEMAILSALUTE);
}

var geo = null;
//var marker, infoWindow;
//function removeMarker(marker)
//{
//    marker.infoWindow.close();
//    marker.setMap(null);
//}

function showAddress()
{
    var address = document.getElementById("search").value;
    if (address && address.trim) address = address.trim(); // trim space if browser supports
    if (address.length <= 1) return;
    
    if (geo == null) geo = new google.maps.Geocoder();

    geo.geocode({address: address},
        function(response, status)
        {
            if (status != google.maps.GeocoderStatus.OK)
            {
                alert(address + " not found");
            }
            else
            {
                var lat      = response[0].geometry.location.lat();
                var lng      = response[0].geometry.location.lng();
                var point    = response[0].geometry.location;
                var html     = response[0].formatted_address;
                var fullhtml = "<span class='black'>" +
//                             "<br/>" +
                               "<strong>" + html + "</strong><br />lat = " + lat + " long = " + lng + "<br />&nbsp;<br/>" + INFOWINDOWCLICKMSG +
                               "<a href=\"manageitem.php?action=new&lat="+ lat +"&lon="+ lng +"\">" + INFOWINDOWCLICKUPLOAD + "</a>" +
//                             "<br />&nbsp;<br/><a href=\"javascript:removeMarker(this);\">remove marker</a><br/>&nbsp;" +
                               "</span>";
                
                map.setCenter(point);
                map.setZoom(MAXZOOM);

                var marker = new google.maps.Marker();
                marker.setPosition(point);
                marker.setMap(map);
                marker.fullhtml = fullhtml;
                
                var infoWindow = new google.maps.InfoWindow(); 
                infoWindow.setContent(fullhtml);
                infoWindow.open(map, marker);
                infoWindow.marker = marker;
                marker.infoWindow = infoWindow;

                google.maps.event.addDomListener(marker, "click", function() { this.infoWindow.setContent(this.fullhtml); this.infoWindow.open(map, this); });
            }
        }
    );
}

function GoToDetailedMapByListBox(box)
{
    if ( (box.selectedIndex == 0) || (!map) ) return;
    
    var locationInfo = DETAILEDLOCATIONS[box.options[box.selectedIndex].text];
    
    map.setCenter(new google.maps.LatLng(locationInfo[0], locationInfo[1]));
    map.setZoom(locationInfo[2]);
}

function AddShowHideButton(textOn, textOff, overlay, enabled)
{
    var showHideNode = document.createElement('DIV');
    showHideNode.innerHTML = enabled ? textOn : textOff;
    showHideNode.className = 'GM-button';
    showHideNode.index     = 1;
    map.controls[google.maps.ControlPosition.TOP_LEFT].push(showHideNode);
        
    google.maps.event.addDomListener(showHideNode, 'click', function() // Setup the click event listener
    {
        if (showHideNode.visible == true)
        {
          //map.removeOverlay(KmlOverlay);
          showHideNode.visible = false;
          showHideNode.innerHTML = textOff;
          overlay.setMap(null);
        }
        else
        {
          //map.addOverlay(KmlOverlay);
          showHideNode.visible = true;
          showHideNode.innerHTML = textOn;
          overlay.setMap(map);
        }
    });

    // Change the style when the user mousedowns
    google.maps.event.addDomListener(showHideNode, 'mousedown', function() {
      showHideNode.className = 'GM-button-selected';
    });

    // Change the style back when the user mouseups
    google.maps.event.addDomListener(showHideNode, 'mouseup', function() {
      showHideNode.className = 'GM-button';
    });
}

