var openingBubble = false;
var pinMarkers = Array();

function removeAllPins(gmap) {
	jQuery.each(pinMarkers, function() {
		gmap.removeOverlay(this);
	});
	pinMarkers = Array();
}

function addPin(latlng, number, guid) {
	var icon = new GIcon(baseIcon);
	icon.image = "http://www.google.com/mapfiles/marker.png";
	var marker = new GMarker(latlng, icon);
	marker.guid = guid;
	
	GEvent.addListener(marker, "click", function() {
		openingBubble = true;
		jQuery.get("/search/property-popup.cfm?guiPropertySummaryID=" + marker.guid, function(message) {
			marker.openInfoWindowHtml(message);
		});
	});
	map.addOverlay(marker);
	pinMarkers.push(marker);
}

function addAddressBlob(addr, city, guid, idx) {
	var blob = "";
	blob += "<div class='map-address'>";
	if (idx == 1) {
		blob += "<div class='idx'>IDX</div>";
	}
	blob += "<a href='/search/property.cfm?guiPropertySummaryID=" + guid + "'>" + addr + "<br/>" + city + "</a>"
	blob += "</div>";
	jQuery("#address-results").append(blob);
}

function fetchResults()
{
	if (openingBubble) { //Make sure not to close bubble right after we opened it
		openingBubble = false;
		return false;
	}
	var bounds = map.getBounds();
	var southWest = bounds.getSouthWest();
	var northEast = bounds.getNorthEast();
	
	jQuery("#searching").show();
	
	jQuery.ajax({
		type: "POST",
		url: "/cfc/MapSearch.cfc",
		cache: false,
		data: "method=RunSearch" +
			"&polygons=" + jQuery("#polygons").val() +
			"&pricemin=" + jQuery("#pricemin").val() +
			"&pricemax=" + jQuery("#pricemax").val() +
			"&proptype=" + jQuery("#proptype").val() +
			"&bedsmin=" + jQuery("#bedsmin").val() +
			"&bathsmin=" + jQuery("#bathsmin").val() +
			"&latMin=" + southWest.lat() +
			"&latMax=" + northEast.lat() +
			"&lngMin=" + southWest.lng() +
			"&lngMax=" + northEast.lng(),
		dataType: "xml",
		success: function(xml) {
			//map.clearOverlays();
			removeAllPins(map);
			jQuery("#address-results").html("");
			
			jQuery("#searching").hide();
			
			jQuery(xml).find('property').each(function() {
				var guid = jQuery(this).find("guid").text();
				var lat = jQuery(this).find("lat").text();
				var lng = jQuery(this).find("lng").text();
				var pin = jQuery(this).find("pin").text();
				var addr = jQuery(this).find("address").text();
				var city = jQuery(this).find("city").text();
				var idx = jQuery(this).find("idx").text();
				
				addPin(new GLatLng(lat, lng), pin, guid);
				addAddressBlob(addr, city, guid, idx);
			});
			
			jQuery(".map-address").each(function(i) {
				var moTO;
				jQuery(this).bind("mouseover", function() {
					moTO = setTimeout('GEvent.trigger(pinMarkers['+i+'], "click");', 250);
				});
				jQuery(this).bind("mouseout", function() {
					clearTimeout(moTO);
				});
			});
		},
		error: function(htpx, er) {
			//alert(er);
			jQuery("#searching").hide();
		}
	});
}