var map = null;
var geocoder = null;
var khand = null;
var _mode = 'd';  // can be d, dm, dgs

function load() 
{
    if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("map"));
        viewFromCookie();
        map.addControl(new GSmallMapControl());
        map.addControl(new GMapTypeControl());
        GEvent.addListener(map, "click", 
                           function(marker, point) {
                               reportPointCoords(point);
                           });
        // Don't need to add zoomend (moveend called after a zoom)
        GEvent.addListener(map, "moveend", 
                           function() {
                               viewToCookie();
                           });
        geocoder = new GClientGeocoder();
        geocoder.setBaseCountryCode("ES");

        khand = new GKeyboardHandler(map);

        var dt = $('#datepicker').val();
        if (!dt) {
            var t = new Date();
            var m = t.getMonth()+1;
            var d = t.getDate();
            var y = t.getFullYear();
            $('#datepicker').val(y + '-' + m + '-' + d);
        }
    }
}

function dec2sexa(num) 
{
    var r = Math.floor(num);
    if (num < 0) { r = r + 1; }
    return [r, Math.abs(num - r) * 60];
}

function reportPointCoords(point) 
{
   if (point) {
        var lt = point.lat();
        var ltgm = dec2sexa(lt);
        var ltms = dec2sexa(ltgm[1]);

        var ln = point.lng();
        var lngm = dec2sexa(ln);
        var lnms = dec2sexa(lngm[1]);

        // One second is around 30m, so for a precision of at least 1m
        // we need 0.03 s, 0.0005 m, or 9.2e-6 dg.

        map.openInfoWindowHtml(point,
                               "<font color='blue'>lat, long</font><br/>" +
                               "<font size='-1'>grados:</font> " +
                               "<br/>" + lt.toPrecision(8) + ", " +
                               ln.toPrecision(8) + "<br/>" +
                               "<font size='-1'>grados minutos:</font> " +
                               "<br/>" + ltgm[0] + " " +
                               ltgm[1].toPrecision(6) + ", " +
                               lngm[0] + " " +
                               lngm[1].toPrecision(6) + "<br/>" +
                              "<font size='-1'>grados minutos segundos:</font>"
                               + "<br/>" + ltgm[0] + " " + ltms[0] + " " +
                               ltms[1].toPrecision(5) + ", " +
                               lngm[0] + " " + lnms[0] + " " +
                               lnms[1].toPrecision(5) + "<br/>"
                              );
    }
}


function findAddress(address, then) 
{
    if (geocoder) {
        geocoder.getLatLng(address,
                           function(point) {
                               if (!point) {
                                   alert("No hemos encontrado " + address);
                               } else {
                                   then(point, address);
                               }
                           });
    }
    else { alert("Tu navegador no es compatible con Google Maps. " +
                 "Deberķas considerar usar firefox."); }
}

function showPlace(where) 
{
    if (map) {
        findAddress(where,
                   function(point) {
                       map.setCenter(point);
                       reportPointCoords(point);
                   });
    }
    else { alert("Tu navegador no es compatible con Google Maps. " +
                 "Deberķas considerar usar firefox!."); }
}

function viewToCookie() 
{
    var nextyear = new Date();
    nextyear.setFullYear(nextyear.getFullYear() + 1);
    var expire = '; expires=' + nextyear.toGMTString();

    var center = map.getCenter();
    var zoom = map.getZoom();
    document.cookie = 'lat=' + escape(center.lat()) + expire;
    document.cookie = 'long=' + escape(center.lng()) + expire;
    document.cookie = 'zoom=' + escape(zoom) + expire;
    document.cookie = 'mode=' + _mode + expire;
}

function cookieField(fname) 
{
    var cookies = document.cookie;
    var pos = cookies.indexOf(fname + '=');
    if (pos != -1) {
        var start = pos + fname.length + 1;
        var end = cookies.indexOf(';', start);
        if (end == -1) end = cookies.length;
        var val = cookies.substring(start, end);
        return (unescape(val));
    }
}

function viewFromCookie() 
{
    var lat = cookieField("lat");
    var lng = cookieField("long");
    var zoom = cookieField("zoom");
    _mode = cookieField("mode");
    if (!_mode) { _mode = 'd'; }

    if (lat && lng && zoom) {
        map.setCenter(new GLatLng(parseFloat(lat), parseFloat(lng)), 
                      parseInt(zoom));
    }
    else {
        viewWholeSpain();
    }
}

function viewWholeSpain() 
{
    map.setCenter(new GLatLng(39.75, -3.25), 6);
}

