// A Google map library

// Convert a decimal degree value to degress, minutes and seconds
function decToDMS(dec) {
    var deg = Math.floor(dec);
    dec = (dec - deg) * 60;
    var min = Math.floor(dec);
    var sec = (dec - min) * 60;
    sec = Math.round(100 * sec) / 100;	// round to 1/100th precision
    return deg + "° " + min + "′ " + sec + "″";
}

// Convert latitude and longitude to a HTML string
function LatLngToHtml(lat, lng) {
    lat = decToDMS(Math.abs(lat)) + (lat < 0 ? ' S' : ' N');
    lng = decToDMS(Math.abs(lng)) + (lng < 0 ? ' W' : ' E');
    return lat + ', ' + lng;
}

// Create a marker at the given point with the given label
function GMcreateMarker(point, label) {
    var marker = new GMarker(point);
    GEvent.addListener(marker, "click", function() {
        marker.openInfoWindowHtml(label);
    });
    return marker;
}

// Initialize a map and return it
function GMinit(mapid) {
    var div = document.getElementById(mapid);
    if (!div) {
        alert("Map region not found");
        return null;
    }

    if (!GBrowserIsCompatible()) {
        div.innerHTML = '<p>Sorry, your browser is not compatible with Google Maps.</p>';
        return null;
    }

    var map = new GMap2(div);

    if (parseInt(div.style.height) >= 350) {
        map.addControl(new GOverviewMapControl());
        map.addControl(new GLargeMapControl());
        map.addControl(new GScaleControl());
    }
    else
        map.addControl(new GSmallMapControl());
    map.addControl(new GMapTypeControl());
    // map.enableDoubleClickZoom();
    map.setCenter(new GLatLng(47.2, 7.5), 8);

    // Allow to click anywhere and display the clicked point's coordinates
    GEvent.addListener(map, 'click', function(obj, point) {
        map.lastPoint = point;  // Keep a copy for the main page
        if (point)
            this.openInfoWindowHtml(point, LatLngToHtml(point.lat(), point.lng()));
    });

    // Add a new member function that creates labeled markers
    map.addMarkerOverlay = function(lat, lng, label) {
        var point = new GLatLng(lat, lng);
        this.addOverlay(GMcreateMarker(point, label));
        return point;
    }

    // Register the cleanup function
    window.onunload = GUnload;

    return map;
}