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 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 ThemesIconsTemplate = '<div class="bubble-images">{{0}}</div>';
var ThemesImgTemplate = '<img src="{{0}}" alt="">';
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;
var firstLoad = true;
var openSelectedOffer = false;

var textualZoomControl = null;
var customMoveControl = null;
var startZoom = 2;

function InitializeMap()
{
  if (GBrowserIsCompatible()) 
  {
      map = new GMap2(document.getElementById("map_canvas"));
      map.setCenter(new GLatLng(55.60516610936823, 12.998800277709961), startZoom);
      
      textualZoomControl = new TextualZoomControl(map, isIE6);
      customMoveControl = new CustomMoveControl(map, isIE6);
      map.addControl(textualZoomControl);
      map.addControl(customMoveControl);
      map.addControl(new GScaleControl());

      textualZoomControl.moveZoomDot(parseInt(startZoom));

	    GEvent.addListener(map, "dragend", viewPointChanged);
	    GEvent.addListener(map, "zoomend", LoadMapPoints, false);
	    LoadMapPoints();
  }
}

function viewPointChanged() {
  var currentZoom = map.getZoom();
  if (currentZoom > 2) {
    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();
        var params = "SwLat=" + southWest.lat() + "&SwLng=" + southWest.lng() + "&NeLat=" + northEast.lat() + "&NeLng=" + northEast.lng() + "&Zoom=" + map.getZoom();
        params += getCountryParams();
        params += getCityParams();
        params += getOffersParams();
        xmlRequest.send(params);
    }
    catch (e)
    { alert(e.message); }
}

function ProcessReqChange()
{
  if (xmlRequest.readyState == 4 && xmlRequest.status == 200) {
    var points = eval(xmlRequest.responseText);

    if (points == null) {
      alert("Error loading Map Points!");
      return;
    }

    map.clearOverlays();
    markersArray = [];

    var point;
    var marker;
    for (i = 0; i < points.length; i++) {
      point = points[i];
      marker = CreateMarker(point);
      markersArray[point.PageID] = marker;
      map.addOverlay(marker);
    }

    if (openSelectedOffer) {
      openSelectedOffer = false;
      openSelectedOfferPopup(selectedOffer);
    }

    if (firstLoad && selectedOffer != 0) 
    {
      firstLoad = false;
      setSelectedOfferCenter(selectedOffer);
    }
  }
}

function CreateMarker(mapPoint)
{
  var customIcon = new GIcon();
  var mapIcon = icon_default;
  
  customIcon.image = mapIcon;
  customIcon.shadow = null;
  customIcon.iconSize = new GSize(32, 38);
  customIcon.shadowSize = new GSize(0, 0);
  //customIcon.iconAnchor = new GPoint(8, 16);
  customIcon.iconAnchor = new GPoint(16, 33);
  customIcon.infoWindowAnchor = new GPoint(16, 16);
    
  var point = new GLatLng(mapPoint.Latitude, mapPoint.Longitude);
  var marker = new GMarker(point, { icon: customIcon, title: mapPoint.Title });
  marker.id = mapPoint.PageID;
  marker.text = mapPoint.Text;
  marker.zoom = mapPoint.Zoom;
  marker.themes = mapPoint.Themes;
  GEvent.addListener(marker, "click", function () {
    OpenMarkerPopup(marker.getLatLng(), marker.text, marker.themes, true);
    loadItemInfo(marker.id);
  });
  return marker;
}

function OpenMarkerPopup(latlng, text, themes, markerMode) {
    CloseMarkerPopup();

    var themesHTML = GetThemesIconsHTML(themes);
    var html = CustomOverlayTemplate.replace("{{0}}", themesHTML + 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 GetThemesIconsHTML(themes) 
{
  var iconsHTML = '';

  if (isset(themes) && themes != '') {
    var themesArr = themes.split('|');
    var imgsHTML = '';
    var iconURL = '';
    for (var i = 0; i < themesArr.length; i++) {
      iconURL = getTypeImageURL(themesArr[i]);
      if (iconURL != '') {
        imgsHTML += ThemesImgTemplate.replace("{{0}}", iconURL);
      }
    }
  }

  if (imgsHTML != '') {
    iconsHTML = ThemesIconsTemplate.replace("{{0}}", imgsHTML);
  }

  return iconsHTML;
}

function CloseMarkerPopup() {
  if (InfoOverlay !== null) {
    map.removeOverlay(InfoOverlay);
    clearItemInfo();
  }
}
