var map;
var openMarker = null;
var bubble;
var numIcons = [];
var markers = [];
var markersData = [];
var imgSrc = "images/";

var mapLat;
var mapLong;
var mapZoom;
var mapType;

/*==========================
   Different Map types:
   Default = hybrid
   1 = Physical
   2 = Satellite Only
   3 = Regular map
========================== */

function loadListingMap(isLocalHome) {

      if (GBrowserIsCompatible()) {

    // create the map
    map = new GMap2(document.getElementById("mapCanvas"));

    //map.setCenter(new GLatLng(mapLat,mapLong), mapZoom);
    mapBounds = new GLatLngBounds(new GLatLng(southExtremum, westExtremum), new GLatLng(northExtremum, eastExtremum))
    map.setCenter(mapBounds.getCenter(), map.getBoundsZoomLevel(mapBounds));

    $("#body").append("<div id='bubble'></div>");

    map.addControl(new GSmallZoomControl3D());

    //Set up type of Map.
    if (mapType == 1)
     map.setMapType(G_PHYSICAL_MAP);
    else if (mapType == 2)
     map.setMapType(G_SATELLITE_MAP);
    else if (mapType == 3)
            map.setMapType(G_NORMAL_MAP);
    else
                  map.setMapType(G_HYBRID_MAP);

            map.disableScrollWheelZoom();

            bubble = new mapBubble(map);
            loadMarkers(isLocalHome);
      } // if gbrowser compatible end
}

// A function to load the listings into markers
function loadMarkers(isLocalHome) {
      var totalMarkers = sponsoredAds.length +  unsponsoredAds.length;
      var imgCount = 1;

      loadAds(sponsoredAds, imgSrc + "orange.png", isLocalHome, true);
      loadAds(unsponsoredAds, imgSrc + "blue.png", isLocalHome, false);

      //when the map is clicked if marker
      GEvent.addListener(map, "click", function(point) {
            if (!point) {
                  bubble.hide();
                  resetOpenMarkerIco();
            }
      });

      //when the map is moved
      GEvent.addListener(map, "move", function() {
            bubble.hide();
            resetOpenMarkerIco();
      });
}

function loadAds(ads, icon, isLocalHome, isSponsored) {
      var y = numIcons.length;
      for (i = 0; i < ads.length; i++, y++) {
            var ad = ads[i];
            numIcons[y] = new GIcon(G_DEFAULT_ICON);
            numIcons[y].image = icon;
            numIcons[y].iconSize = new GSize(20, 26);
            numIcons[y].shadowSize = new GSize(0, 0);
            markers[y] = createMarker(new GLatLng(ad.latitude, ad.longitude), ad.html, numIcons[y], isLocalHome, isSponsored);
            markersData[y] = ad.html;
            map.addOverlay(markers[y]);
      }
}

//A function to create the marker and set up the event window
function createMarker(point, html, icontype, isLocalHome, isSponsored) {
      var marker = new GMarker(point, icontype);
      marker.isOpen = false;

      //Behavior of Markers
      GEvent.addListener(marker, "click", function() {
						//elementTracker._trackEvent('Map','Marker Click');      	
            selectMarkerIco(marker,html);
      });

      return marker;
}

//A function to change icon to the selected marker icon
function selectMarkerIco(marker,html) {

      marker.isOpen = !marker.isOpen;
      if (marker.isOpen){
            bubble.openOnMarker(marker,html);
            resetOpenMarkerIco();
            openMarker = marker;
            marker.setImage(imgSrc + "green.png");
      }     else {
            bubble.hide();
            resetOpenMarkerIco();
      }
}

//A function to reset the marker's icon back to its orginal
function resetOpenMarkerIco() {
      if (openMarker != null)
            openMarker.setImage(openMarker.getIcon().image);
}

function mapBubble(map,anchor) {
      // parameters
      this.map = map;
      this.anchor=anchor;

      this.div = document.createElement("div"); this.div.display = "none";
      this.div.className = "mapHtml";


      var bubbleContainerDiv = document.getElementById("bubble");

      //Remove previous appended "bubble" Info.
      if (bubbleContainerDiv.childNodes.length == 1 ) {
            bubbleContainerDiv.removeChild(bubbleContainerDiv.childNodes[0]);
      }
      bubbleContainerDiv.appendChild(this.div);
      bubbleContainerDiv.style.display ='none';
}


mapBubble.prototype.openOnMap = function(point, html) {
      this.point = point;
      this.div.innerHTML = html;

      // pixel relative to map world
      var p = this.map.fromLatLngToDivPixel(point);

      // map world relative to map container
      var dragObject = this.map.getPane(G_MAP_MAP_PANE).parentNode;
      var x = p.x + parseInt(dragObject.style.left);
      var y = p.y + parseInt(dragObject.style.top);

      // offset by the where the map is relative to its placement in the page.
      x += this.map.getContainer().offsetLeft + 14;
      y += this.map.getContainer().offsetTop - 160;

      //Above and to the left of the button
      var repositionX = x - 260;
      var repositionY = y + 10;


      //Compensate if bubble falls of the top or left side of the screen.
      if (repositionX > 0)
            x = repositionX;

      if (y < 100)
            y = repositionY;

      // Apply those values
      var bubbleContainerDiv = document.getElementById("bubble");
      bubbleContainerDiv.style.left = x+"px";
      bubbleContainerDiv.style.top = y+"px";

      // make it visible
      this.show();
}

mapBubble.prototype.openOnMarker = function(marker,html) {
      var vx = marker.getIcon().iconAnchor.x - marker.getIcon().infoWindowAnchor.x;
      var vy = marker.getIcon().iconAnchor.y - marker.getIcon().infoWindowAnchor.y;
      this.openOnMap(marker.getPoint(), html, new GPoint(vx,vy));
}

mapBubble.prototype.show = function() {
      $("#bubble").fadeIn();
}

mapBubble.prototype.hide = function() {
      $("#bubble").fadeOut();
}