var iconsInUse = [];
//constructor
var MapController = function(container, centerSelector, dataSelector, options) {
  map = new google.maps.Map2(container);

  if (!options) options = {};

  this.dataSelector = dataSelector;
  this.map = map;
  this.markers = {};

  if (!options.simple) {
    map.addControl(new google.maps.LargeMapControl());
    var mapTypesControl = new GMapTypeControl();
    map.addControl(mapTypesControl);
  }

  if (options.moveend) {
    GEvent.addListener(map, "moveend", options.moveend);
  }
	
  this.setCenter(centerSelector);

  this.updateMapMarkers();
}


var iconPaths = {restaurant: '/images/markers/restaurant.png', 
		ski : '/images/markers/ski.png',
		park : '/images/markers/park.png',
		attraction : '/images/markers/attraction.png',
		martini : '/images/markers/martini.png',
		scuba : '/images/markers/scuba.png',
		shopping : '/images/markers/shopping.png',
		beach : '/images/markers/umbrella.png',
		travel_guide : '/images/markers/star.png',
		property :  '/images/markers/home.png'}

var iconLabels = {restaurant: 'Restaurant', 
		ski : 'Ski Area',
		park : 'Park / Nature Reserve',
		attraction : 'Attraction',
		martini : 'Bar / Nightclub',
		scuba : 'Snorkeling',
		shopping : 'Shopping Area',
		beach : 'Beach Area',
		travel_guide : 'Travel Guide',
		property :  'Property'}
		
MapController.icon = new GIcon();
MapController.icon.image = iconPaths['property'];
MapController.icon.iconSize = new GSize(21, 21);
MapController.icon.iconAnchor = new GPoint(1, 21);
// MapController.icon.image = '/images/marker.png';
// MapController.icon.shadow = '/images/marker_shadow.png';
// MapController.icon.iconSize = new GSize(37, 38);
// MapController.icon.shadowSize = new GSize(37, 38);
// MapController.icon.iconAnchor = new GPoint(8, 38);
MapController.icon.infoWindowAnchor = new GPoint(0, 8);

MapController.icon_blue = new GIcon(MapController.icon);
MapController.icon_blue.image = '/images/marker_blue.png';

MapController.icon_purple = new GIcon(MapController.icon);
MapController.icon_purple.image = '/images/marker_purple.png';

MapController.icon_restaurant = new GIcon(MapController.icon);
MapController.icon_restaurant.iconSize = new GSize(21, 21);
MapController.icon_restaurant.iconAnchor = new GPoint(1, 21);
MapController.icon_restaurant.image = iconPaths['restaurant'];

MapController.icon_ski = new GIcon(MapController.icon);
MapController.icon_ski.iconSize = new GSize(21, 21);
MapController.icon_ski.iconAnchor = new GPoint(1, 21);
MapController.icon_ski.image = iconPaths['ski'];

MapController.icon_park = new GIcon(MapController.icon);
MapController.icon_park.iconSize = new GSize(21, 21);
MapController.icon_park.iconAnchor = new GPoint(1, 21);
MapController.icon_park.image = iconPaths['park'];

MapController.icon_attraction = new GIcon(MapController.icon);
MapController.icon_attraction.iconSize = new GSize(21, 21);
MapController.icon_attraction.iconAnchor = new GPoint(1, 21);
MapController.icon_attraction.image = iconPaths['attraction'];

MapController.icon_martini = new GIcon(MapController.icon);
MapController.icon_martini.iconSize = new GSize(21, 21);
MapController.icon_martini.iconAnchor = new GPoint(1, 21);
MapController.icon_martini.image = iconPaths['martini'];

MapController.icon_scuba = new GIcon(MapController.icon);
MapController.icon_scuba.iconSize = new GSize(21, 21);
MapController.icon_scuba.iconAnchor = new GPoint(1, 21);
MapController.icon_scuba.image = iconPaths['scuba'];

MapController.icon_shopping = new GIcon(MapController.icon);
MapController.icon_shopping.iconSize = new GSize(21, 21);
MapController.icon_shopping.iconAnchor = new GPoint(1, 21);
MapController.icon_shopping.image = iconPaths['shopping'];

MapController.icon_beach = new GIcon(MapController.icon);
MapController.icon_beach.iconSize = new GSize(21, 21);
MapController.icon_beach.iconAnchor = new GPoint(1, 21);
MapController.icon_beach.image = iconPaths['beach'];

MapController.icon_travel_guide = new GIcon(MapController.icon);
MapController.icon_travel_guide.iconSize = new GSize(21, 21);
MapController.icon_travel_guide.iconAnchor = new GPoint(1, 21);
MapController.icon_travel_guide.image = iconPaths['travel_guide'];

//MapController functional declaration
new function() {
  //global settings

  //private methods
  function createMarker(geoNode) {
    var $geoNode = $(geoNode);
    var title = $geoNode.find('.title').text();
    var entityUrl = $geoNode.find('a.link').attr('href');
    //pack some data into the marker title
    var packedTitle = ['packed_title', title, entityUrl].join('|');
    var icon = MapController.icon;
    if(($geoNode.is('.bar') || $geoNode.is('.jazz') || $geoNode.is('.gay') || $geoNode.is('.country') || $geoNode.is('.nightlife') || $geoNode.is('.dance'))){
			icon = MapController.icon_martini;
			addIconInUse('martini');
		} else if(($geoNode.is('.snorkeling') || $geoNode.is('.scuba') || $geoNode.is('.coral') || $geoNode.is('.underwater'))){
			icon = MapController.icon_scuba;
			addIconInUse('scuba');
		} else if(($geoNode.is('.theme') || $geoNode.is('.park') || $geoNode.is('.botanical') || $geoNode.is('.garden') || $geoNode.is('.nature') || $geoNode.is('.national') || $geoNode.is('.state'))){
			icon = MapController.icon_park;
			addIconInUse('park');
		} else if(($geoNode.is('.ski') || $geoNode.is('.snowboarder') || $geoNode.is('.downhill') || $geoNode.is('.cross'))){
			icon = MapController.icon_ski;
			addIconInUse('ski');
		} else if(($geoNode.is('.shopping') || $geoNode.is('.flea') || $geoNode.is('.street'))){
			icon = MapController.icon_shopping;
			addIconInUse('shopping');
		} else if(($geoNode.is('.bay') || $geoNode.is('.beach'))){
			icon = MapController.icon_beach;
			addIconInUse('beach');
		} else if(($geoNode.is('.restaurant'))){
			icon = MapController.icon_restaurant;
			addIconInUse('restaurant')
		} else if(($geoNode.is('.destination'))){
			icon = MapController.icon_travel_guide;
			addIconInUse('travel_guide');
		} else if(($geoNode.is('.attraction'))){
			icon = MapController.icon_attraction;
			addIconInUse('attraction');
		}	else if(($geoNode.is('.property'))){
			addIconInUse('property');
		}
    return new google.maps.Marker(getLatLng(geoNode), {icon: icon, title: packedTitle});
    //var propertyId = popupId.split('_')[popupId.split('_').length - 1];
    //GEvent.addListener(marker, 'click', function(){document.write($('#google_map').html());});
  };

	function addIconInUse(str){
		if(iconsInUse.indexOf(str) == -1){
			iconsInUse.push(str)
		}
	}

  function getLatLng(geoNode) {
    return new google.maps.LatLng($(geoNode).find('.latitude').text(), $(geoNode).find('.longitude').text());
  };

  function getId(geoNode) {
    return $(geoNode).attr('id');
  }


  //public methods
  MapController.prototype = {

    DEFAULT_ZOOM: 12,

    updateMapMarkers: function() {
      if (!this.dataSelector) return;

      var currentMarkers = {};
      var self = this;

      //add new markers
      var $data = $(this.dataSelector);
      var geos;
      if ($data.is('.geo'))
        geos = $data;
      else
        geos = $data.find('.geo');
				
      geos.each(function() {
        var id = getId(this);

        var marker = self.markers[id];

        if (!marker) {
          marker = createMarker(this);
          self.addMarker(id, marker);
        }

        currentMarkers[id] = marker;
      });

      //remove unused markers
      $.each(this.markers, function(id, val) {
        if (!currentMarkers[id]) {
          self.removeMarker(id, val);
        }
      });
			

			
      //setup popups
      var markers = $('#google_map *[title^="packed_title"]');
      //remove the packed information from the title
			var sale_or_rental = $('#property_search_type').val()
      markers.each(function() {
                        var $this = $(this);
                        var packedTitleArray = $this.attr('title').split('|');
												var markerType = packedTitleArray[2].split('/')[1]
												var height
												if(markerType == 'destinations' || markerType == 'attractions'){
													height = '265px'
													$this.attr('rel', packedTitleArray[2]);
													$this.attr('title', packedTitleArray[1]);
												} else {
													height = '540px'
													$this.attr('rel', packedTitleArray[2]+'?'+sale_or_rental+'=1');
													$this.attr('title', packedTitleArray[1]);
												}
												$this.popups({activation: 'hover', width: height, cluetipClass : 'marker-popup ' + markerType});
                      })
			if($('#marker_legend').length > 0){
				// update the map legend
				$('#marker_legend').html('')
				$.each(iconsInUse, function(index, icon){
					div = $('<div>')
					div.append('<img src="'+iconPaths[icon]+'" />')
					div.append('<div class="label">'+iconLabels[icon]+'</div>')
					$('#marker_legend').append(div)
				})
			}
              
    },

    addMarker: function(id, marker) {
      this.map.addOverlay(marker);
      this.markers[id] = marker;
    },

    removeMarker: function(id, marker) {
      this.map.removeOverlay(marker);
      delete this.markers[id];
    },

    setCenter: function(geoNode) {
      var zoom = parseInt($(geoNode).find('.zoom').text()) || this.DEFAULT_ZOOM;
      map.setCenter(getLatLng(geoNode), zoom);
    },

    getGMap: function(){ return map; }

  }

}();

jQuery.fn.extend({
  mapController: function(centerSelector, dataSelector, options) {
    var mapController = jQuery.data(this[0], 'mapController')
    if (!mapController) {
      mapController = jQuery.data(this[0], 'mapController', new MapController(this[0], centerSelector, dataSelector, options));
    }
    return mapController;
  }
});

$(document).unload(GUnload);