if (window.addEventListener)
    window.addEventListener("load", InitializeMap, false);
else if (document.addEventListener)
    document.addEventListener("load", InitializeMap, false);
else if (window.attachEvent)
    window.attachEvent("onload", InitializeMap);

var map, cluster, markersArray = [], xmlRequest;
var CustomOverlayTemplate = '<div class="bubble"><div class="bubble-body"><div class="bubble-content"><a class="close-btn" href="javascript:CloseMarkerPopup()">Close</a><div class="bubble-pointer">{{0}}</div></div></div><div class="bubble-bottom">&nbsp;</div></div>';
var InfoOverlay = null;
var CUSTOM_OVERLAY_SHIFT_X = -14;
var CUSTOM_OVERLAY_SHIFT_Y = 107;
var CUSTOM_OVERLAY_CLUSTER_SHIFT_X = -16;
var CUSTOM_OVERLAY_CLUSTER_SHIFT_Y = 122;

function InitializeMap()
{
    if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("map_canvas"));
        map.setCenter(new GLatLng(55.60516610936823, 12.998800277709961), 2);
        map.addControl(new GMapTypeControl(), new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(7, 7)));
	    map.addControl(new GLargeMapControl(), new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(7, 28)));
	    GEvent.addListener(map, "dragend", LoadMapPoints);
	    GEvent.addListener(map, "zoomend", LoadMapPoints);
        LoadMapPoints();
    }
}

function LoadMapPoints()
{
    xmlRequest = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
    if (xmlRequest == null)
    {
        alert("Your browser does not support this map.");
        return;
    }

    xmlRequest.onreadystatechange = ProcessReqChange;
    xmlRequest.open("post", "/GoogleMapPoints.aspx", true);
    xmlRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

    try
    {
        var bounds = map.getBounds();
        var southWest = bounds.getSouthWest();
        var northEast = bounds.getNorthEast();
        xmlRequest.send("SwLat=" + southWest.lat() + "&SwLng=" + southWest.lng() + "&NeLat=" + northEast.lat() + "&NeLng=" + northEast.lng() + "&Zoom=" + map.getZoom());
    }
    catch (e)
    { alert(e.message); }
}

function ProcessReqChange()
{
    if (xmlRequest.readyState != 4 || xmlRequest.status != 200)
        return;
    
    var points = eval(xmlRequest.responseText);
    
    if (points == null)
    {
        alert("Error loading Map Points!");
        return;
    }
    else if (points.length == 0)
        return;
    
    map.clearOverlays();
    markersArray = [];
    
    for(i = 0; i < points.length; i++)
    {
        var point = points[i];
        markersArray.push(CreateMarker(point));
    }
    
    cluster = new ClusterMarker(map, { markers:markersArray, clusterMarkerTitle:"Klik for at se info om %count lokationer", clusterMarkerClick:Cluster_Click });
    cluster.refresh(true);
}

function Cluster_Click(args)
{
    cluster.defaultClickAction = function()
        {
	        map.setCenter(args.clusterMarker.getLatLng(), map.getBoundsZoomLevel(args.clusterMarker.clusterGroupBounds))
	        delete cluster.defaultClickAction;
        }
    var text = "";
    text += "<a href=\"javascript:void(0)\" onclick=\"cluster.defaultClickAction();\">Zoom</a> ind for at vise disse lokationer:<br/><br/>";
    for (i = 0; i < args.clusteredMarkers.length; i++)
    {
        text += args.clusteredMarkers[i].getTitle() + "<br/>";
    }
    
    OpenMarkerPopup(args.clusterMarker.getLatLng(), text, false);
}

function CreateMarker(mapPoint)
{
    var customIcon = new GIcon();
    customIcon.image = "http://maps.google.com/mapfiles/arrow.png";
    customIcon.shadow = null;
    customIcon.iconSize = new GSize(32, 32);
    customIcon.shadowSize = new GSize(0, 0);
    customIcon.iconAnchor = new GPoint(8, 16);
    customIcon.infoWindowAnchor = new GPoint(16, 16);
    
    var point = new GLatLng(mapPoint.Latitude, mapPoint.Longitude);
    var marker = new GMarker(point, { icon:customIcon, title:mapPoint.Title });
    GEvent.addListener(marker, "click", function() {
        OpenMarkerPopup(marker.getLatLng(), mapPoint.Text, true);
    });
    return marker;
}

function OpenMarkerPopup(latlng, text, markerMode) {
    if (InfoOverlay !== null) {
        CloseMarkerPopup();
    }

    var html = CustomOverlayTemplate.replace("{{0}}", text);
    if (markerMode) {
        InfoOverlay = new MarkerCustomOverlay(latlng, html, CUSTOM_OVERLAY_SHIFT_X, CUSTOM_OVERLAY_SHIFT_Y);
    }
    else {
        InfoOverlay = new MarkerCustomOverlay(latlng, html, CUSTOM_OVERLAY_CLUSTER_SHIFT_X, CUSTOM_OVERLAY_CLUSTER_SHIFT_Y);
    }
    
    map.addOverlay(InfoOverlay);
}

function CloseMarkerPopup() {
    map.removeOverlay(InfoOverlay);
}

function MarkerCustomOverlay(point, html, shiftLeft, shiftTop) {
    this.point_ = point;
    this.html_ = html;
    this.shiftTop_ = 0;
    this.shiftLeft_ = 0;

    if (typeof (shiftTop) != 'undefined') {
        this.shiftTop_ = shiftTop;
    }

    if (typeof (shiftLeft) != 'undefined') {
        this.shiftLeft_ = shiftLeft;
    }

    this.index = 0;
}

MarkerCustomOverlay.prototype = new GOverlay();

MarkerCustomOverlay.prototype.initialize = function(map) {
    var div = document.createElement("div");
    div.style.position = "absolute";
    div.innerHTML = this.html_;

    map.getPane(G_MAP_FLOAT_PANE).appendChild(div);

    this.map_ = map;
    this.div_ = div;
}

MarkerCustomOverlay.prototype.remove = function() {
    this.div_.parentNode.removeChild(this.div_);
}

MarkerCustomOverlay.prototype.copy = function() {
    return new MarkerCustomOverlay(this.point_, this.html_);
}

MarkerCustomOverlay.prototype.redraw = function(force) {
    if (!force) return;

    var pointPixels = this.map_.fromLatLngToDivPixel(this.point_);

    this.div_.style.left = (pointPixels.x - this.shiftLeft_) + "px";
    this.div_.style.top = (pointPixels.y - this.shiftTop_) + "px";
}

MarkerCustomOverlay.prototype.setShiftValues = function(x, y) {
    if (typeof (x) != 'undefined') {
        this.shiftLeft_ = x;
    }

    if (typeof (y) != 'undefined') {
        this.shiftTop_ = y;
    }
}