/**
 * google maps API code
 * Sagan Bolliger, 28 June 2011
 */

Map = new function() {
	this.drawMap = function() {
		
		var initialPosition = null;
		
		// get a marker for initial centering
		// but what if there are no markers?
		$.each(markers,function(id,marker) {
			initialPosition = marker['position'];
			return false;
		});
		
		if(initialPosition == null)
			return false;
		
		if(!needs_redraw)
			return true;
		needs_redraw = false;
		
		$('#map-lightbox').hide();
		
		var myOptions = {
		  zoom: 8,
		  center: initialPosition, 
		  mapTypeId: google.maps.MapTypeId.ROADMAP
		}
		
		map = new google.maps.Map(document.getElementById("map"), myOptions);
		
		var bounds = new google.maps.LatLngBounds();
		
		var counter = 0;
		
		$.each(markers,function(id,marker) {

			google.maps.event.addListener(marker, 'click', function() {

				map.setCenter(marker['position']);
				map.panBy(0,-120); /* half of height of map lightbox */

				Map.showInfoWindow(id)

			});

			bounds.extend(marker['position']);
			counter++;

		});
		
		Map.filterMarkers(Property.getActiveIds());
		
		if(counter >= 2)
			map.fitBounds(bounds);
		
		google.maps.event.addListener(map,'click',function() {
			$('#map-lightbox').hide();
		})
		
		return true;
		
	};
	this.addMarker = function(id,title,latitude,longitude) {
		
		var marker = new google.maps.Marker({
			position: new google.maps.LatLng(latitude,longitude),
			title: title
		});
		
		markers[id] = marker;
		
		needs_redraw = true;
	};
	this.clearMarkers = function() {
		$.each(markers,function(i,marker) {
			marker.setMap(null);
		});
		markers = {};
		
		needs_redraw = true;
	};
	this.showInfoWindow = function(id) {
		
		$('#map-lightbox').remove();
		
		$.get('/item/campaign/' + Property.getCampaignIdForProperty(id) + '/view/map-item',function(rt) {
			var tmpl = $(rt);
			
			Property.populateFieldsForItem(tmpl,id);
			$('.map-view.view').append(tmpl);
			
//			alert($('#map-lightbox').length)
			
			$('#map-lightbox').show();
			$('#map-lightbox .additional-dates-popup').hide();
		});		
	}
	this.filterMarkers = function(activeIds) {
		if(needs_redraw)
			return; // no use filtering if needs redraw
		
		$.each(markers,function(id,marker) {
			if($.inArray(id,activeIds) != -1) {
				if(marker.getMap() != map)
					marker.setMap(map);
			} else if(marker.getMap() != null)
				marker.setMap(null);
		});
	}

	var map = {};
	var markers = {};
	var needs_redraw = true;
}


