﻿/// <reference path="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js" />
/// <reference path="~/Common/HillsideUI.js" />
/// <reference path="~/MapSearchControl.aspx" />
/// <reference path="~/Common/HC-Utils.js" />

/*****************************************/
/* MAKE SURE HELPER FUNCTIONS ARE INIT'D */
if (typeof VELatLongRectangle.toCsv == "undefined") {
	VELatLong.prototype.toCsv = function (delimiter) { if (!delimiter) { delimiter = ","; } return this.Latitude + delimiter + this.Longitude; }
	VELatLongRectangle.prototype.toCsv = function (delimiter) { if (!delimiter) { delimiter = "|"; } return this.TopLeftLatLong.toCsv() + delimiter + this.BottomRightLatLong.toCsv(); }
} /*****************************************/


/* SelectedMarkers is used to track which listings should be used for driving directions */
var SelectedMarkers = new Array();
/* SelectedMarkerList is a line-break delimited list of selected indexes */
var SelectedMarkerList = "\n\n";


var MLSNumbers = "";
var resetSetMapView = false;
var isMapLoaded = false;
var points = new Array();
var pushpinShapes = new Array();
var listingsPerPage = 5;
var ListingPages = [];

var pointClusteringTracker = {};// new Hash();
var pointClusterPropertyInfo = {}; //new Hash();

var tempPoints = null;
var num = 0;
var firstPoint = null;
var areaBox;
var SelectedTopLeft;
var SelectedBottomRight;

var isMouseUp = true;

var btnMsgs = ["SAVE PROPERTY", "CENTER MAP", "DIRECTIONS", ""];

function buttonHover(iconImg) {
	iconImg.src = iconImg.src.replace("Small_Icon_", "");
}
function buttonOut(iconImg, markerIndex) {
	iconImg.src = iconImg.src.replace("_Tile_r", "_Tile_Small_Icon_r");
	$("#objButtonInfo_" + markerIndex).html("");
}
function setButtonInfo(MsgNumber, markerIndex) {
	$("#objButtonInfo_" + markerIndex).html(btnMsgs[MsgNumber]);
}
/******OBSOLETE*****
function openDetails(detailsUrl) {
var objPropertyWin;
if (window.screen.availWidth > 1100) {
objPropertyWin = window.open(detailsUrl, "_blank", "width=1100,height=768,top=5,left=5,scrollbars=yes,resizable=yes,toolbars=no,status=yes,menubar=no,location=no");
return;
} else if (window.screen.availWidth > 900) {
objPropertyWin = window.open(detailsUrl, "_blank", "width=920,height=768,top=5,left=5,scrollbars=yes,resizable=yes,toolbars=no,status=yes,menubar=no,location=no");
return;
} else {
objPropertyWin = window.open(detailsUrl, "_blank", "width=780,height=580,top=5,left=5,scrollbars=yes,resizable=yes,toolbars=no,status=yes,menubar=no,location=no");
return;
}
}
*/
function setTileColor(el, isHovering) {
	
}
function listingTile(ListingInfo) {
	// From <table> tag: onmouseover=\"showHoverInfoTile(" + ListingInfo.markerIndex + ")\" onmouseout=\"hideHoverInfoTile(" + ListingInfo.markerIndex + ")\"
	// From <img> tag: onmouseover=\"scaleImage(this)\"
	var infoTile_MouseOut = "setTileColor(this, false); if (VEMap._GetMapFromGUID(map.GUID).FireEvent('onmouseout'))return;VEHideVEShapeERO(false);"
	var infoTile_MouseOver = "setTileColor(this, true); if (VEMap._GetMapFromGUID(map.GUID).FireEvent('onmouseover'))return;VEShowVEShapeERO(objMarkers[" + ListingInfo.markerIndex + "].pushpin.guid,map.GUID);"

	return "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"190\" style=\"border-top: 1px solid #ADADAD;\" class=\"PropertyInfoTile\" onmouseover=\"" + infoTile_MouseOver + "; showHoverInfoTile(" + ListingInfo.markerIndex + ")\" onmouseout=\"" + infoTile_MouseOut + "; hideHoverInfoTile(" + ListingInfo.markerIndex + ")\">\n\
	<tr>\n\
		<td valign=\"top\" align=\"left\" class=\"AddrTD\" colspan=\"2\" nowrap>\n\
			<img alt=\"Zoom to Property\" title=\"Zoom to Property\" src=\"images/Zoom_16.png\" border=\"0\" style=\"cursor: pointer; width: 14px; height: 14px; display: inline;\" onclick=\"showTab(0); map.SetCenterAndZoom(new VELatLong(" + ListingInfo.lat + ", " + ListingInfo.lon + "), 15)\" />&#160;<a href=\"javascript:hillsideUI.mappingTools.showPropertyDetails('" + ListingInfo.ln + "', '" + ListingInfo.address + "')\" class=\"InfoTD\" title=\"" + ListingInfo.address + "\"><b>" + ListingInfo.address + "</b></a>\
		</td>\n\
	</tr>\n\
	<tr>\n\
		<td valign=\"top\" align=\"center\" width=\"80\">\n\
			<img class=\"PropertyImg\" onclick=\"hillsideUI.mappingTools.showPropertyDetails('" + ListingInfo.ln + "', '" + ListingInfo.address + "')\" style=\"cursor: pointer;\" src=\"GetPhoto.aspx?LN=" + ListingInfo.ln + "a&Board=" + CurrentAgent.Board.toString() + "&Size=Large\" width=\"80\" border=\"0\" alt=\"\" onerror=\"this.src='images/NoPhotoSmall.gif'\" />\
		</td>\n\
		<td valign=\"top\">\n\
			<table align=\"left\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"font-size: 11px; width: 122px; position: relative;\">\n\
				<tr><td class=\"InfoTD\" valign=\"top\" style=\"width: 122px; overflow: hidden;\" nowrap>" + ListingInfo.price + " <b>City:</b> " + ListingInfo.city + "<br /><b>Beds:</b> " + ListingInfo.beds + " <b>Baths:</b> " + ListingInfo.baths + "<br /><b>Sq. Feet:</b> " + ListingInfo.sqFt + "</td></tr>\n\
				<tr><td class=\"InfoTD\" style=\"width: 122px; overflow: hidden;\" nowrap>" + ListingInfo.bkr + "</td></tr>\n\
			</table>\n\
		</td>\n\
	</tr>\n\
</table>";
}
/* Old Listing Tile Code: 
function listingTile(ListingInfo) {
return "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"192\" style=\"border-top: 2px solid #000000;\">\n\
<tr>\n\
<td>\n\
<table align=\"left\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"24\">\n\
<tr><td><img src=\"images/Property_Tile_Small_Icon_r1_c1.png\" width=\"24\" height=\"23\" alt=\"\" onmouseover=\"buttonHover(this); setButtonInfo(0, " + ListingInfo.markerIndex + ")\" onmouseout=\"buttonOut(this, " + ListingInfo.markerIndex + ")\" class=\"iconBtn\" onclick=\"SaveListing('" + ListingInfo.ln + "')\" /></td></tr>\n\
<tr><td><img src=\"images/Property_Tile_Small_Icon_r2_c1.png\" width=\"24\" height=\"22\" alt=\"\" onmouseover=\"buttonHover(this); setButtonInfo(1, " + ListingInfo.markerIndex + ")\" onmouseout=\"buttonOut(this, " + ListingInfo.markerIndex + ")\" class=\"iconBtn\" onclick=\"map.SetCenterAndZoom(new VELatLong(" + ListingInfo.lat + ", " + ListingInfo.lon + "), 15)\" /></td></tr>\n\
<tr><td><img src=\"images/Property_Tile_Small_Icon_r3_c1.png\" width=\"24\" height=\"22\" alt=\"\" onmouseover=\"buttonHover(this); setButtonInfo(2, " + ListingInfo.markerIndex + ")\" onmouseout=\"buttonOut(this, " + ListingInfo.markerIndex + ")\" class=\"iconBtn\" onclick=\"startGetDirections('" + unescape(escape(ListingInfo.address.replace("\n", "")).replace("%0D", "")) + "', " + ListingInfo.lat + ", " + ListingInfo.lon + ")\" /></td></tr>\n\
</table>\n\
</td>\n\
<td>\n\
<table align=\"left\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"63\">\n\
<tr><td class=\"tdPhoto\"><div style=\"padding: 1px 1px 0px 2px; height: 48px; width: 60px; overflow: hidden;\"><img onclick=\"hillsideUI.mappingTools.showPropertyDetails('" + ListingInfo.ln + "', '" + ListingInfo.address + "')\" style=\"cursor: pointer;\" src=\"" + ListingInfo.pic + "\" width=\"52\" border=\"0\" alt=\"\" onerror=\"this.src='images/NoPhotoSmall.gif'\" /></div></td></tr>\n\
<tr><td class=\"tdBtnInfo\" valign=\"top\"><div class=\"divBtnInfo\" id=\"objButtonInfo_" + ListingInfo.markerIndex + "\"></div></td></tr>\n\
</table>\n\
</td>\n\
<td class=\"tdAddrRemarks\">\n\
<div style=\"padding: 1px 2px 0px 2px; height: 64px; overflow: hidden;\">\n\
<div style=\"width: 102px; overflow: hidden;\"><a href=\"javascript:hillsideUI.mappingTools.showPropertyDetails('" + ListingInfo.ln + "', '" + ListingInfo.address + "')\" class=\"aAddr\" title=\"" + ListingInfo.address + "\">" + ListingInfo.address + "</a></div>\n\
<div class=\"divRemarks\">" + ListingInfo.remarks.substring(0, (ListingInfo.remarks.length >= 55) ? 55 : ListingInfo.remarks.length - 1) + ((ListingInfo.remarks.length >= 55) ? "..." : "") + "</div>\n\
</div>\n\
</td>\n\
</tr>\n\
</table>";
}
*/

// Used so we can reset the pushpin's style
var lastHoveredMarkerIndex = -1;


var zoomedImgs = [];

/*
function scaleImage(img) {
	resetAllZoomedImgs();
	$(img)
		.css({ position: "absolute", zIndex: 100 })
		.animate({width: "120px"});
	Event.observe($(img), "mouseout", function () { resetImg(this) });
}
function resetImg(img) {
	img.morph("width: 65px; z-index: auto;", { queue: "end", duration: 0.25 });
}

function resetAllZoomedImgs() {
	var imgs = $$("img.PropertyImg");
	imgs.each(function (img) { try { if (img.style.width > 65) { $(img).morph("width: 65px; z-index: auto;", { duration: 0.25 }); } } catch (e) { } });
}
*/

function showHoverInfoTile(markerIndex) {
	/* Make sure we are on the map tab - not property details or charts */
	if (jQuery("#tabs").tabs().tabs('option', 'selected') != 0) {
		return "";
	}
	var myShape;
	myShape = objMarkers[markerIndex].pushpin;
	if (myShape) {
		/* Reset style of selected pin if "lastHoveredMarkerIndex" has a real value */
		if (lastHoveredMarkerIndex > -1) {
			var tempShape = objMarkers[lastHoveredMarkerIndex].pushpin;
			if (tempShape) { setPushpinHoverState(tempShape, false, markerIndex); lastHoveredMarkerIndex = -1; }
		}
		lastHoveredMarkerIndex = markerIndex;
		setPushpinHoverState(myShape, true, markerIndex);
		map.ShowInfoBox(myShape);
	}
}
function hideHoverInfoTile(markerIndex) {
	var myShape;
	myShape = objMarkers[markerIndex].pushpin;
	if (myShape) {
		/* Reset style of selected pin if "lastHoveredMarkerIndex" has a real value */
		if (lastHoveredMarkerIndex > -1) {
			var tempShape = objMarkers[lastHoveredMarkerIndex].pushpin;
			if (tempShape) { setPushpinHoverState(tempShape, false, markerIndex); lastHoveredMarkerIndex = -1; }
		}
		map.HideInfoBox(myShape);
	}
}

//<mapSettings idxImg="" lat="39.595591" lon="-104.769623733333" minLat="39.565933" minLon="-104.977515" maxLat="39.638226" maxLon="-104.680416" />
/* DEFINE LISTING CLASS/FUNCTION */
function listingInfo(markerIndex, address, ln, lat, lon, beds, baths, price, pic, remarks, link, unit, city, state, zip, bkr, listDate, sqFt) {
	// Set the local vars
	this.markerIndex = markerIndex;
	this.address = address;
	this.ln = ln;
	this.lat = lat;
	this.lon = lon;
	this.beds = beds;
	this.baths = baths;
	this.price = price;
	this.pic = pic;
	this.remarks = remarks;
	this.link = link;
	/* New Fields added by Dan L.: 2009-01-17
	Fields: Unit, City, State, Zip, Bkr, ListDate
	Indexs: 10, 11, 12, 13, 14, 15 */
	this.unit = unit;
	this.city = city;
	this.state = state;
	this.zip = zip;
	this.bkr = bkr;
	this.listDate = listDate;
	/* NEW FIELD: Added By: Dan L. 2009-04-01 
	Field: SqFt
	Index: 16 */
	this.sqFt = sqFt;

	this.pushpin = null;
	//this.GetListingTile = listingTile(this);





}

/* Note: 2008-04-19 *** Somewhat obsolete, or bloated, now we only need to know the center lat & lon */
function mapSettings(idxImg, lat, lon, minLat, minLon, maxLat, maxLon, isPolygonValid) {
	this.idxImg = idxImg;
	this.lat = lat;
	this.lon = lon;
	this.minLat = minLat;
	this.minLon = minLon;
	this.maxLat = maxLat;
	this.maxLon = maxLon;
	this.isPolygonValid = isPolygonValid;
}


function AddPushpin(ID, Lat, Long, IconURL, Title, Notes, Link) {
	var shape = new VEShape(VEShapeType.Pushpin, new VELatLong(Lat, Long));

	//Set the icon
	//shape.SetCustomIcon(IconURL);
	/*
	var myIcon = new VECustomIconSpecification();

	myIcon.Image = IconURL;
	myIcon.TextContent = (pushpinShapes.length + 1);
	myIcon.TextSize = 5;
	myIcon.TextBold = true;
	*/
	//Set the info box
	shape.SetTitle(Title);
	shape.SetDescription(Notes);
	//shape.SetCustomIcon(myIcon);
	// OBSOLETE: shape.SetCustomIcon("<div class=\"PinIcon\" style=\"text-decoration: none;\">" + (pushpinShapes.length + 1) + "</div>");
	shape.SetCustomIcon("<img src=\"images/Pushpin-20x30.png\" width='20' height='30' alt='' />");
	/*** ADD CUSTOM ATTRIBUTE(S) ***/
	shape.markerIndex = ID;

	pushpinShapes[pushpinShapes.length] = shape;

	//Add the shape the the map
	map.AddShape(shape);

	return shape;
}

/* Quick Add PushPin */
function AddPin(LatLong, Title, Notes, IconURL) {
	var shape = new VEShape(VEShapeType.Pushpin, LatLong);

	//Set the icon
	if (IconURL) { shape.SetCustomIcon(IconURL); }

	//Set the info box
	if (Title) { shape.SetTitle(Title); }
	if (Notes) { shape.SetDescription(Notes); }

	//Add the shape the the map
	map.AddShape(shape);
}

function ShapeInfo(e) {
	if (e.elementID != null) {
		shape = map.GetShapeByID(e.elementID);

		//Respond to ctrl-click event (toggle polygon icon visibility).
		//Note that pushpin shapes ignore ShowIcon and HideIcon.
		if (e.ctrlKey == 1) shape.HideIcon();
		else shape.ShowIcon();

		//Display information for the selected shape.
		var info = "";
		info += "ID (event object): " + e.elementID + "<br />";
		info += "ID (GetID method): " + shape.GetID() + "<br />";
		info += "Type: " + shape.GetType() + "<br />";
		info += "Title: " + shape.GetTitle() + "<br />";
		icon = shape.GetCustomIcon();
		info += "Icon: " + icon + "<br />";

		//Note that the Icon Anchor value for pushpin shapes is always
		//the latitude and longitude of the pin itself.
		info += "Icon Anchor: " + shape.GetIconAnchor() + "<br />";
		//$('DebugLabel').innerHTML = info;
	} else {
		//$('DebugLabel').innerHTML = "e.elementID is null!";
	}
}

/* Old Code!
function AddPushpin(ID, Lat, Long, IconURL, Title, Notes, Link) {
//Create a pushpin and add it to the map
var pushpin = new VEPushpin(ID, new VELatLong(Lat, Long), IconURL, Title, Notes);
map.AddPushpin(pushpin);
}
*/

function checkBirdseye() {
	//Change the map style to Birdseye
	if (map.IsBirdseyeAvailable()) {
		map.SetMapStyle(VEMapStyle.Birdseye);
	} else {
		//Change the map style to Raod (Other Options: VEMapStyle.Road, VEMapStyle.Aerial, VEMapStyle.Hybrid, VEMapStyle.Oblique, and VEMapStyle.Birdseye)
		map.SetMapStyle(VEMapStyle.Road);
	}
}

/* Returns a VEFindResult Object */
function GeoCode(Address, City, State, Zip) {
	var nextPage = false;
	try {
		map.Find(null, Address + ", " + City + ", " + State + " " + Zip, 1,
			fnCallback);
	} catch (err) {
		alert(err.source + ": " + err.message);
	}
}

function fnCallback(findResults) {
	try {
		/* The Find Method returns a collection of VEFindResult Objects - http://dev.live.com/virtualearth/sdk/Ref/HTML/T_Namespace_VEFindResult.htm */
		if (findResults.length > 0) {
			/* return the first result */
			return findResults[0];
		}
	} catch (err) {
		alert(err.source + ": " + err.message);
	}
}

function loadMapMarkers() {
	objMapDropArr = new Array();
	var marker;
	var point;
	var endDate;
	var endTime;
	var lastPropertyRowIndex = 0;
	var mapSettingsRowIndex = 0;

	/* Clear ListingPages Array */
	ListingPages = new Array();
	ListingPages = [];
	MLSNumbers = "";
	objDate = new Date();
	startTime = objDate.getTime();

	// Initialize/Clear the map & listing list info
	// Temp: addSchoolMarkers();

	//GEvent.addListener(map, "moveend", function() {mapMoved();});
	//Load property data into the objMarkers array
	if (!objMarkers || objMarkers.length < 1) {
		objMarkers = new Array();
		map.DeleteAllShapes();
		areaBox = null;
		/* Try re-add AreaBox to map 
		if (areaBox) {
		areaBox.SetFillColor(new VEColor(170, 150, 150, 0.25));
		map.AppShape(areaBox);
		}*/

		// Set the default mapSettingsRowIndex
		mapSettingsRowIndex = strRows.length - 1;
		// Check the last 2 rows - as there may be a trailing linebreak
		// Note: The value (strRows.length - 1) equals the LAST row's index because ".length" is a 1-based value
		/*
		if (strRows[strRows.length - 1].indexOf("|") < 0 && strRows[strRows.length - 2].indexOf("|") > -1) {mapSettingsRowIndex = 2;}
		if (strRows[strRows.length - 1].indexOf("|") > 0) {mapSettingsRowIndex = 1;}
		*/
		// The lastPropertyRowIndex is "one up" from the map settings
		lastPropertyRowIndex = mapSettingsRowIndex - 1;

		// Load the settings - FROM THE mapSettings ROW
		strFields = strRows[mapSettingsRowIndex].split("|");

		// Check if we have a result coming back. (at all)
		if (strRows.length < 2) {
			alert("No results found. Please check your search criteria and try again.");
		}
		if (!strFields || strFields.length < 1) {
			strFields = "<img border=\"0\" src=\"images/idx.gif\" alt=\"IDX Logo\" />|39.4|-104.09|39.29|-104.22|39.44|-103.92|true"
		}
		//alert("strFields[0]: " + strFields[0] + "\nstrFields.length: " + strFields.length);
		try {
			//alert("strRows[" + mapSettingsRowIndex + "]: " + strRows[mapSettingsRowIndex]);
			objMapSettings = new mapSettings(strFields[0], strFields[1], strFields[2], strFields[3], strFields[4], strFields[5], strFields[6], strFields[7]);
			//map.SetCenter(new VELatLong(objMapSettings.lat, objMapSettings.lon));
		} catch (ex) {
			if (isDebug) { eval("debugger"); }
			// Do Nothing!
		}
		if (strFields.length > 1 && !objMapSettings.isPolygonValid) {
			// Show a warning
			var s = "The area/shape you created could not be fully interpreted by the Mapping Engine. Necessary adjustments were automatically made.";
			var polyMsg = hillsideUI.showWarningPopup("Polygon Search Area Message", s);
			//setTimeout(
		}
		// Add 1 to the index to get the item count
		listingCount = lastPropertyRowIndex + 1;

		// Initialize the 1st page's string
		ListingPages[0] = "";

		var pageCounter = 0;
		var tempCount = 0.0;
		for (var i = 0; i <= lastPropertyRowIndex; i++) {
			strFields = strRows[i].replace("\r", "").split("|");
			/*try {*/
			if (strFields.length > 8) {
				averageLat += parseFloat(strFields[0]);
				averageLon += parseFloat(strFields[1]);

				/* Added By: Dan L. on 2007-09-11 */
				points[i] = new VELatLong(parseFloat(strFields[0]), parseFloat(strFields[1]));
				strFields[9] = strFields[9].replace(String.fromCharCode(13), "").replace(String.fromCharCode(10), "");
				strFields[16] = strFields[16].replace(String.fromCharCode(13), "").replace(String.fromCharCode(10), "");
				objMarkers[i] = new listingInfo(i, strFields[9], strFields[2], parseFloat(strFields[0]), parseFloat(strFields[1]), strFields[3], strFields[4], strFields[5], strFields[7], strFields[8], strFields[6], strFields[10], strFields[11], strFields[12], strFields[13], strFields[14], strFields[15], strFields[16]);
				if (pageCounter > (listingsPerPage - 1)) {
					/* Add Closing DIV tag */
					//ListingPages[ListingPages.length] += "\n</div>";
					/* Add New Page */
					ListingPages[ListingPages.length] = "";
					/* Reset Listing/Page Counter to 0 */
					pageCounter = 0;
				}
				/* Add Beginning DIV tag */
				//if (ListingPages[ListingPages.length - 1].length < 1) { ListingPages[ListingPages.length - 1] = "<div id=\"ListingPage" + (ListingPages.length - 1) + "\" style=\"display: none;\">\n"; }
				ListingPages[ListingPages.length - 1] += listingTile(objMarkers[i]) + "\n";
				pageCounter++;
				tempCount += 1;
			}
			/*} catch (ex) {
			debugger;
			//alert("Error: " + ex.toString());
			}*/
		}

		averageLat = (averageLat / tempCount);
		averageLon = (averageLon / tempCount);

		// NB: objMarkers will be reset below - based on the current page
		strRows = null;
		strFields = null;
	}

	if (resetSetMapView || !isMapLoaded) {
		resetSetMapView = false;
		// Set the map view to the same points used by the shape.
		map.SetMapView(points);
		if (map.GetZoomLevel() < 8) {
			consoleLog("Error: Cannot auto-zoom (from: " + map.GetZoomLevel() + ")! Try center on first 2 listings - then zoom.");
			map.SetMapView([points[0], points[1]]);
			map.SetZoomLevel(12);
		}
		// Call map.ZoomIn(); to get a more condensed view of the properties
		//map.ZoomIn();
	}

	/* Re-initialize Hash objects */
	pointClusteringTracker = null;
	pointClusteringTracker = {}; // new Hash();
	pointClusterPropertyInfo = null;
	pointClusterPropertyInfo = {}; // new Hash();



	var tempPushpin;
	var tempKey = "";
	var propertyIndexAndShapeArray = [];
	if (objMarkers && objMarkers.length) {
		for (var intMarkersPosition = 0; intMarkersPosition < objMarkers.length; intMarkersPosition++) {
			tempPushpin = AddMarker(intMarkersPosition, objMarkers[intMarkersPosition].address, objMarkers[intMarkersPosition].ln, parseFloat(objMarkers[intMarkersPosition].lat), parseFloat(objMarkers[intMarkersPosition].lon), objMarkers[intMarkersPosition].beds, objMarkers[intMarkersPosition].baths, objMarkers[intMarkersPosition].price, objMarkers[intMarkersPosition].pic, objMarkers[intMarkersPosition].remarks, objMarkers[intMarkersPosition].link);
			objMarkers[intMarkersPosition].pushpin = tempPushpin;










			/* 
			Add the listing's lat & lon to a keyed hash containing references to the VEShape & the objMarkers array index # 
			*/
			try {
				tempKey = objMarkers[intMarkersPosition].lat + "," + objMarkers[intMarkersPosition].lon;















				if (pointClusteringTracker[tempKey.toString()]) {//Point is to be added (at the exact same spot) 
					// Add Shape & Marker Index references to collection
					propertyIndexAndShapeArray = pointClusteringTracker[tempKey.toString()];
					propertyIndexAndShapeArray.push({ MarkersPosition: intMarkersPosition, Shape: tempPushpin });
					// Set the new propertyIndexAndShapeArray
					pointClusteringTracker[tempKey.toString()] = propertyIndexAndShapeArray;
				} else {
					// Create object for new propertyIndexAndShapeArray to initialize for pointClusteringTracker
					propertyIndexAndShapeArray = [{ MarkersPosition: intMarkersPosition, Shape: tempPushpin}];
					pointClusteringTracker[tempKey] = propertyIndexAndShapeArray;
				}
			} catch (e) { window.status = "Error Tracking Cluster Points: " + e.toString(); }

			try {
				objMapDropArr[intMarkersPosition] = new DirectionList(intMarkersPosition, objMarkers[intMarkersPosition].address, objMarkers[intMarkersPosition].lon, objMarkers[intMarkersPosition].lat);
			} catch (e) { window.status = "Error Tracking Cluster Points: " + e.toString(); }
		}
	} else {
		/*
		if (isDebug) {debugger; alert("No Pushpin Data Could Be Loaded!");}
		alert("Error: Could not load results!");
		*/
	}
	markers = null;
	strRows = null;

	// Call processPointClusteringTracker()
	// TEMPORARILY DISABLED (2009-04-09) - needs to work with the mouse-hover info tiles: processPointClusteringTracker();


	// Make sure we only initialize the map, etc. one time
	isMapLoaded = false;

	endDate = new Date();
	endTime = endDate.getTime();

	// Run time +5000ms
	// Run time with out adding overlays +4700ms
	if (isDebug) {
		//window.document.title = "(Load Time: " + (endTime - startTime) + "ms)";
		//window.status = "(Load Time: " + (endTime - startTime) + "ms)";
	}
}











/*
function clusterPointInfo(lat, lon, description, propertyIndexes) { 
	/ * Define new object called clusterPointInfo * /
	this.Lat = lat;
	this.Lon = lon;
	// Temp Title should never be displayed because it's only for displaying "clustered" icons
	this.Title = "1 property found at this location.";
	this.Shape = null;
	/ * Description is an accumulating msg for the popup info box/tile ... should be in the format like:
	4. 123 Elm St.
	17. 987 Main St.
	41. 6 E. Walnut St. * /
	this.Description = description;
	this.PropertyIndexes = propertyIndexes;
	this.getKey = function () { return (this.Lat + "," + this.Lon); }
}
function addPropInfoToClusterPointTracker(markerIndex) {
	var tempKey = objMarkers[markerIndex].lat + "," + objMarkers[markerIndex].lon;
	// note: clusterInfo is a clusterPointInfo type
	var clusterInfo = pointClusterPropertyInfo[tempKey];
	if (!clusterInfo) {
		// Create new clusterPointInfo
		clusterInfo = new clusterPointInfo(objMarkers[markerIndex].lat, objMarkers[markerIndex].lon, "<a href=\"javascript:hillsideUI.mappingTools.showPropertyDetails('" + objMarkers[markerIndex].ln + "', '" + objMarkers[markerIndex].address + "')\" class=\"aAddr\" title=\"" + objMarkers[markerIndex].address + "\">#" + (markerIndex + 1) + ": " + objMarkers[markerIndex].address + "</a><br />\n", [markerIndex]);
	} else {
		clusterInfo.Description += "<a href=\"javascript:hillsideUI.mappingTools.showPropertyDetails('" + objMarkers[markerIndex].ln + "', '" + objMarkers[markerIndex].address + "')\" class=\"aAddr\" title=\"" + objMarkers[markerIndex].address + "\">#" + (markerIndex + 1) + ": " + objMarkers[markerIndex].address + "</a><br />\n";
		clusterInfo.PropertyIndexes.push(markerIndex);
		clusterInfo.Title = clusterInfo.PropertyIndexes.length + " properties found at this location.";
	}
	pointClusterPropertyInfo.set(tempKey, clusterInfo);
	return clusterInfo;
}

function processPointClusteringTracker() {
	try {
		pointClusteringTracker.each(function (pair) {
			// alert(pair.key + ' = "' + pair.value + '"');
			if (pair.value.length > 1) {
				// Cluster matching points! - Now, Iterate thru prop info Array
				pair.value.each(function (indexAndShape, arrayIndex) {
					addPropInfoToClusterPointTracker(indexAndShape.MarkersPosition);
					// Delete overlapped/overlapping pushpin so we dont have to worry about it later
					map.DeleteShape(indexAndShape.Shape);
				});
				// Add Cluster Pushpin
				var clusterInfo = pointClusterPropertyInfo[pair.key];
				var pin;
				if (!clusterInfo) {
					alert("Error: Could not find value for key: pointClusterPropertyInfo.get(" + pair.key + ")");
				} else {
					pin = polygonGetPushpin(new VELatLong(clusterInfo.Lat, clusterInfo.Lon), clusterInfo.Description, { title: clusterInfo.Title, description: clusterInfo.Description });
					pin.SetCustomIcon("<div class=\"PinIconMulti\" style=\"text-decoration: none;\">&#160;</div>");
					clusterInfo.Shape = pin;
					map.AddShape(pin);
				}
			}
		});
	} catch (e) { window.status = "Error Tracking Cluster Points: " + e.toString(); }
}*/


/* Old Code: function GetMarker(point, addToListingList, currentMarkerIndex, addr, ln, lat, lon, beds, baths, price, pic, remarks, link) */
function AddMarker(currentMarkerIndex, addr, ln, lat, lon, beds, baths, price, pic, remarks, link) {
	MLSNumbers += ln + ",";
	/* Override value for link (for VO only) */
	// CRITICAL: Disable for HomeCards and other non-VO code: link = "";
	var notes = "<div style='width: 240px;'>";
	if (pic && pic.length > 0) {
		notes += "<a class=\"PhotoLink\" onmousedown=\"hillsideUI.mappingTools.showPropertyDetails('" + ln + "', '" + addr + "')\"><img src=\"" + pic + "\" alt=\"Photo For " + addr + "\" width=\"100\" style=\"border: 0px;\" /></a><br />";
	}
	notes += "<b><a class=\"ListingLink\" onmousedown=\"hillsideUI.mappingTools.showPropertyDetails('" + ln + "', '" + addr + "')\">" + addr + "</a></b>" +
		"<br /><b>MLS #:</b> " + ln +
		"<br /><b>Beds:</b> " + beds +
		"&#160;<b>Baths:</b>&#160;" + baths +
		"<br /><b>Price:</b>&#160;" + price + "<br />" +
		"<b>Remarks:</b>&#160;" + remarks + "<br />" +
		"" + IDXImagePath;
	var strIconURL = "images/home_green_32.png";

	notes += "</div>";
	return AddPushpin(currentMarkerIndex, lat, lon, strIconURL/*Was: null*/, addr, notes, link);

}

function DeleteAreaBox() {
	/* set cursor to default pointer "hand" icon */
	$("mymapcontroldiv").childNodes[0].style.cursor = "";

	hideMapLoadingProgress();
	hillsideUI.mappingTools.setDrawingButtonsState(false);

	if (isPolygonSupported) {
		// For polygon support
		polygonPoints = new Array();
		polygonTempPoints = null;
		selectedPolygonWKT = "";
		if (selectedAreaLayer) { selectedAreaLayer.DeleteAllShapes(); }
		try {
			map.DeletePolygon('tempPolygon');
		} catch (err) {
		}

		//Moved to the start drawing function: polygonPoints = new Array();
		map.DetachEvent('onclick', polygonMapClick);
		//map.DetachEvent('oncontextmenu', polygonMapContextMenu);
		map.DetachEvent('onmousemove', polygonMapMouseMove);
		map.vemapcontrol.EnableGeoCommunity(false);
	}

	$("#info").html("");
	/* set cursor to cross-hair */
	//$("mymapcontroldiv").style.cursor = "crosshair";
	if (areaBox) {
		/* Remove shape from map and null the var - then reset the firstPoint var for first-use */
		map.DeleteShape(areaBox);
		areaBox = null;
		firstPoint = null;
	}

	try {
		map.DetachEvent('onmousedown', mapClick);
		map.DetachEvent('onmousemove', mapMouseMove);
	} catch (err) {
		/* Do Nothing */
	}
}

function DrawPolygon() {
	try {
		/* Show the MAP tab */
		jQuery("#tabs").tabs('select', 0);

		// Reset the city selection to <ALL> (we may need to disable this)
		$("#City option:eq(0)").attr('selected', true);

	} catch (e) { /* DO NOTHING */ }



	// For polygon support
	polygonPoints = new Array();
	polygonTempPoints = null;
	selectedPolygonWKT = "";
	if (selectedAreaLayer) { selectedAreaLayer.DeleteAllShapes(); }

	isMouseUp = true;
	hideMapLoadingProgress();
	map.ClearDirections;
	map.DeleteRoute();
	if (!$("#City option:selected").length == 0) {
		$("#City option:eq(0)").attr('selected', true);
	}
	$('#DirectionsResult').html("");

	hillsideUI.mappingTools.setDrawingButtonsState(true);

	$("#info").html("Click on the map to add a starting point.");
	/* set cursor to cross-hair */
	$("#mymapcontroldiv").children().css({cursor: "crosshair"});
	if (areaBox) {
		/* Remove shape from map and null the var - then reset the firstPoint var for first-use */
		map.DeleteShape(areaBox);
	}
	areaBox = null;
	firstPoint = null;

	// IMPORTANT: isPolygonSupported is defined at the top of this script!!!
	if (isPolygonSupported) {
		/********** Polygon drawing Enabled **********/
		/********** Polygon drawing Enabled **********/
		/********** Polygon drawing Enabled **********/
		if (!HidePolygonInstructions) {
			var infoPopup = hillsideUI.showWarningPopup("<i>Mapping Tip</i>", "<ul><li>Click anywhere on the map to begin drawing.</li><li>Then click on <b>at least 2 more</b> locations.</li><li>Click the STAR (your starting point) when you are done drawing to complete your area.</li></ul>");
			var popupButtons = infoPopup.find("button");
			if (popupButtons.length > 0) { popupButtons.first().click(function (e) { ListingLinksCallBack.Callback("HidePolygonInstructions"); }); }
		}
		//setTimeout("$('" + infoPopup.identify() + "').hide()", 7500);

		// Make sure the map auto-zooms to the results
		resetSetMapView = true;
		map.AttachEvent('onclick', polygonMapClick);
		//map.AttachEvent('oncontextmenu', mapContextMenu);
		map.AttachEvent('onmousemove', polygonMapMouseMove);
		map.vemapcontrol.EnableGeoCommunity(true);
		try {
			map.DeletePolygon('tempPolygon');
		} catch (err) {
		}
	} else {
		/********** RECTANGLE drawing Enabled **********/
		/********** RECTANGLE drawing Enabled **********/
		/********** RECTANGLE drawing Enabled **********/
		try {
			map.DetachEvent('onmousedown', mapClick);
			map.DetachEvent('onmousemove', mapMouseMove);
			map.DetachEvent('onstartpan', mapStartPan);
		} catch (err) {
			/* Do Nothing */
		}
		map.AttachEvent('onmousedown', mapClick);
		map.AttachEvent('onmouseup', mapMouseUp);
		map.AttachEvent('onmousemove', mapMouseMove);
		map.AttachEvent('onstartpan', mapStartPan);
	}

}

function mapMouseUp(e) {
	isMouseUp = true;
	// Adjust the "2" below to make the 
	if (moveCount > 2) {
		mapClick(e);
	}
	moveCount = 0;
}

function mapStartPan(e) {
	if ($("#StartButton").is(":visible") == false) {
		return true;
	}
}

//Used to track # of move events fired while the mouse is down
var moveCount = 0;


function mapClick(e) {
	isMouseUp = false;
	//consoleLog(e);
	var pixel = new VEPixel(e.mapX, e.mapY);
	if (!firstPoint) {
		firstPoint = map.PixelToLatLong(pixel);
		$("#info").html("Now, click on the map to finish drawing.");
		if ($("#StartButton").is(':visible') == false) {
			return true;
		}
	} else if (firstPoint) {
		var lastPoint = map.PixelToLatLong(pixel);
		map.DetachEvent('onmousedown', mapClick);
		map.DetachEvent('onmousemove', mapMouseMove);
		/* set cursor to default pointer "hand" icon */
		$("#mymapcontroldiv").children().css({ cursor: "" });
		
		/* Set Top-left and Bottom-right coords */
		//42.293564192170074x-109.51171875000003   37.09023980307206x-102.216796875
		//$("coords").innerHTML = 
		SelectedTopLeft = new VELatLong(((firstPoint.Latitude < lastPoint.Latitude) ? firstPoint.Latitude : lastPoint.Latitude), ((firstPoint.Longitude > lastPoint.Longitude) ? firstPoint.Longitude : lastPoint.Longitude));
		SelectedBottomRight = new VELatLong(((firstPoint.Latitude > lastPoint.Latitude) ? firstPoint.Latitude : lastPoint.Latitude), ((firstPoint.Longitude < lastPoint.Longitude) ? firstPoint.Longitude : lastPoint.Longitude));
		/*
		var TopLeftPin = new VEShape(VEShapeType.Pushpin, SelectedTopLeft);
		TopLeftPin.SetTitle(SelectedTopLeft.Latitude + 'x' + SelectedTopLeft.Longitude);
		map.AddShape(TopLeftPin);
		var BottomRightPin = new VEShape(VEShapeType.Pushpin, SelectedBottomRight);
		BottomRightPin.SetTitle(SelectedBottomRight.Latitude + 'x' + SelectedBottomRight.Longitude);
		map.AddShape(BottomRightPin);
		*/
		//(firstPoint.Latitude + "x" + firstPoint.Longitude) + " &#160; " + (lastPoint.Latitude + "x" + lastPoint.Longitude)
		$("#info").html("Finished drawing area.");

		hillsideUI.mappingTools.setDrawingButtonsState(false);

		doSearch();
		return true;
	}
}

function mapMouseMove(e) {
	/* Increment the move evt counter */
	if (!isMouseUp) { moveCount++; }

	if (firstPoint) {
		var pixel;
		var cornerPoint;

		if (e.mapX && e.mapY) {
			pixel = new VEPixel(e.mapX, e.mapY);
			cornerPoint = map.PixelToLatLong(pixel);
		}

		if (cornerPoint) {
			tempPoints = getRectPoints(cornerPoint);
		} else {
			tempPoints = null;
		}
		if (cornerPoint && tempPoints) {

			if (!areaBox) {
				areaBox = new VEShape(VEShapeType.Polygon, tempPoints);
				areaBox.HideIcon();
				areaBox.SetFillColor(new VEColor(170, 150, 150, 0.45));
				areaBox.SetLineColor(new VEColor(170, 150, 150, 1.0));
				areaBox.SetLineWidth(2);

				map.AddShape(areaBox);
			} else {
				areaBox.SetPoints(tempPoints);
			}
		} //if (cornerPoint && tempPoints) {
	} //if (firstPoint) {
}

function getRectPoints(cornerLatLon) {
	var boxCoords =
		[firstPoint,
		new VELatLong(cornerLatLon.Latitude, firstPoint.Longitude),
		cornerLatLon,
		new VELatLong(firstPoint.Latitude, cornerLatLon.Longitude)];
	return boxCoords;
}

function StopDrawing() {
	/* set cursor to default pointer "hand" icon */
	$("#mymapcontroldiv").children().css({ cursor: "" });
	if (isPolygonSupported) { polygonFinishDrawing(); }
	hillsideUI.mappingTools.setDrawingButtonsState(false);
}

//Set DirectionList values to be used to access values throughout
function DirectionList(currindex, address, lon, lat) {
	this.currindex = currindex;
	this.address = address;
	this.lon = lon;
	this.lat = lat;
	this.listMapDir = function () {

	}

}

function trimChar(value, trimChar) {
	var len = value.length
	var begin = 0, end = len - 1;
	while (value.charAt(begin) == trimChar && begin < len) {
		begin++;
	}
	while (value.charAt(end) == trimChar && begin < end) {
		end--;
	}
	return value.substring(begin, end + 1);
}

function loadMapState(stateData) {
	if (stateData.length < 1) {return false; }
	
	var needsToDrawPolygon = false;
	var fields = stateData.split("&");
	var tempPriceRange = [];
	var includePointsInMapView = [];

	for (var i = 0; i < fields.length; i++) {
		var keyValue = fields[i].split("=");
		keyValue[1] = unescape(keyValue[1]);
		if (keyValue[0].toLowerCase() == "bounds") {
			var t = keyValue[1].split("|");
			var p1 = t[0].split(","), p2 = t[1].split(",");
			includePointsInMapView = [new VELatLong(p1[0], p1[1]), new VELatLong(p2[0], p2[1])];
			consoleLog(includePointsInMapView);
			map.SetMapView(includePointsInMapView);
		} 
		if (keyValue[0].toLowerCase() == "poly") {
			if (keyValue[1].length > 8) {
				polygonPoints = [];
				var polyPoints = keyValue[1].split("|");
				/* pull out the LatLon pairs and add them to the polygonPoints array */
				$A(polyPoints).each(function (tempVal) { tempVal = tempVal.split(","); if (tempVal.length >= 2 && !isNaN(tempVal[1])) polygonPoints.push(new VELatLong(tempVal[0], tempVal[1])); });
				needsToDrawPolygon = true;
			}
		}
		// Set the search form values!
		if (keyValue[0].toLowerCase() == "city") { $("City").value = unescape(keyValue[1]); }
		if (keyValue[0].toLowerCase() == "proptype") { $("PropType").value = unescape(keyValue[1]); }
		if (keyValue[0].toLowerCase() == "pricefrom") { tempPriceRange[0] = unescape(keyValue[1]); }
		if (keyValue[0].toLowerCase() == "priceto") { tempPriceRange[1] = unescape(keyValue[1]); }
		if (keyValue[0].toLowerCase() == "minbeds") { jQuery("#bedsSlider").slider("value", keyValue[1]); }
		if (keyValue[0].toLowerCase() == "minbaths") { jQuery("#bathsSlider").slider("value", keyValue[1]); }
		if (keyValue[0].toLowerCase() == "sort") { $("SortResults").value = unescape(keyValue[1]); }
	}

	jQuery("#priceSlider").slider("values", tempPriceRange);

	/* After importing the polygonPoints and the form values, load the polygon to the map */
	if (needsToDrawPolygon) {
		polygonFinishDrawing();
		map.SetMapView(includePointsInMapView);
	}

} //loadMapState()

function getCurrentMapState() {
	var currentState = [];
	// Get current map area bounds
	currentState.push("Bounds=" + escape(map.GetMapView().toCsv()) );


	// Get the polygon if there is one (and it's valid - i.e. first and last item are the same)
	if (polygonPoints.length >= 3 && (polygonPoints[0].toCsv() == polygonPoints[polygonPoints.length - 1].toCsv())) {
		consoleLog("DEBUG: polygonPoints ARE Valid!");
		var strPoly = "";
		$A(polygonPoints).each(function (a) { strPoly += roundFloat(a.Latitude, 5) + "," + roundFloat(a.Longitude, 5) + "|" });
		strPoly = trimChar(strPoly, "|");
		// ADD THE SHAPE TO THE STATE
		currentState.push("Poly=" + escape(strPoly));
	} else {
		consoleLog("DEBUG: polygonPoints IS NOT valid! Len: " + polygonPoints.length);

	}

	/** Return the QS-compatible state data string **/
	return currentState.join("&") + getSearchParamsQS();
}

function roundFloat(float1, decimalPlaces1) {
	try {
		var multiplier = Math.pow(10, decimalPlaces1);
		return Math.round(float1 * multiplier) / multiplier;
	} catch (e) {
		/* return original value - !!! */
		consoleLog(e);
		return float1;
	}
}

function showMapStateLink() {
	var stateUrl = self.location.toString();
	if (stateUrl.indexOf("#") > -1) { stateUrl = stateUrl.substring(0, stateUrl.indexOf("#")); }
	stateUrl = stateUrl + "#" + getCurrentMapState();
	jQuery("#MapStateLink").val(stateUrl)
	jQuery(".MapStateLinkViewer").css("display", "");
	jQuery("#MapStateLink").select();
}

function hideMapStateLinkViewer() {
	jQuery(".MapStateLinkViewer").css("display", "none");
}

/*************** POLYGON DRAWING SUPPORT FUNCTIONS ***************/
/*************** POLYGON DRAWING SUPPORT FUNCTIONS ***************/
/*************** POLYGON DRAWING SUPPORT FUNCTIONS ***************/
/*************** POLYGON DRAWING SUPPORT FUNCTIONS ***************/
/*************** POLYGON DRAWING SUPPORT FUNCTIONS ***************/
/*************** POLYGON DRAWING SUPPORT FUNCTIONS ***************/
/*************** POLYGON DRAWING SUPPORT FUNCTIONS ***************/
/*************** POLYGON DRAWING SUPPORT FUNCTIONS ***************/

/* Define Layers For Points */
var selectedAreaLayer;

var resultsLayer;

var polygonPoints = new Array();
var polygonTempPoints = null;
var tempPolygon;

var finishID;
var finishPushpinBtn;

var selectedPolygonWKT = "";

function polygonMapClick(e) {
	/*** Check For Right-button click ***/
	if (e.rightMouseButton) {
		polygonFinishDrawing(); //polygonMapContextMenu(e);
	} else {
		if (polygonPoints.length < 1) {
			// FIRST POINT
			//"<div class=\"PinIcon\" style=\"text-decoration: none;\" onclick=\"alert('Clicked on: " + (pushpinShapes.length + 1) + "')\">" + (pushpinShapes.length + 1) + "</div>"
			finishPushpinBtn = polygonGetPushpin(polygonGetLatLongFromEvent(e), "", { icon: "<div class=\"\" style=\"text-decoration: none;\" onclick=\"polygonFinishDrawing()\"><img src=\"images/StarWithoutBorder.png\" onmouseover=\"this.src='images/StarWithBorder.png'\" onmouseout=\"this.src='images/StarWithoutBorder.png'\" border=0 style=\"width: 24px; height: 22px;\" /></div>" });
			finishPushpinBtn.SetDescription("");
			finishPushpinBtn.SetTitle("Click the STAR when you are done drawing to complete your area.");
			//finishPushpinBtn.ShowDetailOnMouseOver = false; // turn off the default, roll your own
			selectedAreaLayer.AddShape(finishPushpinBtn);
			finishID = finishPushpinBtn.GetID();
			/*
			map.ShowInfoBox(finishPushpinBtn);
			setTimeout("hideInfoBox('" + finishID + "')", 6000);
			*/
		}
		polygonPoints.push(polygonGetLatLongFromEvent(e));
		if (polygonPoints.length <= 3) { map.ShowInfoBox(finishPushpinBtn); }
	}
}

function hideInfoBox(shapeID) {
	var shape = map.GetShapeByID(finishID);
	if (shape) {
		map.HideInfoBox(shape);
		return shape;
	}
}

function polygonFinishDrawing() {
	if (polygonPoints.length > 0 && polygonPoints.length <= 2) {
		// Show warning message & reset the variable
		hillsideUI.showErrorPopup("Invalid Area", "Please draw another area/shape with <b>at least</b> 3 or more points.");
		polygonPoints = [];
		// Get rid of the "STAR" pushpin
		if (selectedAreaLayer && finishPushpinBtn) { selectedAreaLayer.DeleteShape(finishPushpinBtn); }
		$("#info").html("Invalid Area: Please try again.");
	} else {
		// *** MS Maps require polygons have the same start and end points!!!
		if (polygonPoints[0].toCsv() != polygonPoints[polygonPoints.length - 1].toCsv()) {
			polygonPoints.push(polygonPoints[0]);
			// We have a valid polygon
		}
	}

	/* set cursor to default pointer "hand" icon */
	$("#mymapcontroldiv").children().css({ cursor: "" });

	if (polygonPoints.length > 2) {
		var polygon = new VEShape(VEShapeType.Polygon, polygonPoints);
		polygon.HideIcon();
		polygon.SetFillColor(new VEColor(0, 102, 255, 0.30));
		polygon.SetLineColor(new VEColor(0, 255, 255, 0.65));
		polygon.SetLineWidth(2);

		selectedAreaLayer.DeleteAllShapes();
		selectedAreaLayer.AddShape(polygon);

		polygonId = polygon.GetID();

		/* Make sure we reset the button state */
		hillsideUI.mappingTools.setDrawingButtonsState(false);

		/* Process the polygonPoints & send 'em to the server */
		try { polygonProcessPoints(); } catch (error) { alert("Error Identifying Selected Area: " + error.toString()); }
	}

	try {
		map.DeletePolygon('tempPolygon');
	} catch (error) { /* Do Nothing */ }

	//Moved to the start drawing function: polygonPoints = new Array();
	map.DetachEvent('onclick', polygonMapClick);
	//map.DetachEvent('oncontextmenu', polygonMapContextMenu);
	map.DetachEvent('onmousemove', polygonMapMouseMove);
	map.vemapcontrol.EnableGeoCommunity(false);

	if (polygonPoints.length > 2) {
		// Run the search automatically
		doSearch();
	}
}

function polygonMapMouseMove(e) {
	if (e.leftMouseButton == true) {
		// user is clicking and dragging	
		
	}
	polygonTempPoints = polygonPoints.slice(0, polygonPoints.length);
	polygonTempPoints.push(polygonGetLatLongFromEvent(e));

	try {
		map.DeletePolygon('tempPolygon');
	} catch (err) {
	}

	var polygon = new VEPolygon('tempPolygon', polygonTempPoints);
	polygon.SetFillColor(new VEColor(0, 148, 255, 0.65));
	polygon.SetOutlineColor(new VEColor(170, 150, 150, 1.0));
	polygon.SetOutlineWidth(2);
	map.AddPolygon(polygon);
}
function polygonGetLatLongFromEvent(e) {
	var x = e.mapX;
	var y = e.mapY;
	var pixel = new VEPixel(x, y);
	return map.PixelToLatLong(pixel);
}

function polygonProcessPoints() {
	// Set the selectedPolygonWKT value to be passed in search query function ( doSearch() )!
	selectedPolygonWKT = polygonGetPolyPointsWKT();
}

function polygonGetPolyPointsWKT() {
	var myShape = map.GetShapeByID(polygonId);
	if (myShape) {
		var p1 = myShape.GetPoints();
		var shapeLatLonList = new Array();
		p1.reverse()
		for (var i = 0; i < p1.length; i++) {
			shapeLatLonList.push(p1[i].Longitude + " " + p1[i].Latitude);
			//polygonAddPushpin(p1[i], "#" + i);
		}
		//shapeLatLonList.push(shapeLatLonList[0]);
		return trimChar(trimChar(trimChar(trimChar(shapeLatLonList.join(", "), " "), ","), " "), ",");
	} else {
		return "";
	}
}

/*** TEST CODE ***/
/* pushpinOptions = {icon:"images/StarWithBorder.png", title:"Hello World", description:"My desc"} */
function polygonGetPushpin(point, caption, pushpinOptions) {
	var shape = new VEShape(VEShapeType.Pushpin, point);
	//shape.SetTitle("Title: " + point.toString());

	if (caption && caption.length > 1) { shape.SetDescription(caption); }

	if (pushpinOptions) {
		if (pushpinOptions.icon) { shape.SetCustomIcon(pushpinOptions.icon); }
		if (pushpinOptions.title) { shape.SetTitle(pushpinOptions.title); }
		if (pushpinOptions.description) { shape.SetDescription(pushpinOptions.description); }
	}
	return shape;
}
function polygonAddPushpin(point, caption, pushpinOptions) {
	var shape = polygonGetPushpin(point, caption, pushpinOptions);
	map.AddShape(shape);
}

//TODO: function showWarning(msg) { }


