

	
var area_displayed_categories = {};
var shapefile_selected = {};
var area_subcategories = {};

var areaLat = null;
var areaLng = null;
var areaZoom = null;


var chosenAreaLat = null;
var chosenAreaLng = null;
var chosenAreaZoom = null;
var areaShapeIds = null;

var showThematicView = false;
var thematicShapefileId = null;
var thematicLegend = null;
var lastThemeLoc = "";

var roundAmount = 100;
var areaFilterCountryCode = null;
var areaFilterZooms = null;

// numtries is optional, defaults to 4
function getAreaInfo(numtries, mycallback) {
	if (typeof(numtries)== 'undefined') numtries = 4;
	if (typeof(numtries)!= 'number') numtries = 0;
	if (numtries < 0) {
		if (typeof(mycallback)=='function')
			mycallback();
		return;
	}

	if (areaLat == null || areaLat != map.getCenter().lat() ||
			areaLng == null || areaLng != map.getCenter().lng() ||
			areaZoom == null || areaZoom != map.getZoom()) {
		areaLat = map.getCenter().lat();
		areaLng = map.getCenter().lng();
		areaZoom = map.getZoom();
	} else {
		if (typeof(mycallback)=='function')
			mycallback();
		return; // nothing to do ; what they see is current
	}

	var filterDiv = document.getElementById('area_subcatsCol1');
	filterDiv.innerHTML = t("Loading...");

	area_subcategories = {};

	var callback =
	{
		success: getAreaInfoSuccess,
		failure: getAreaInfoFailure,
		argument: [numtries-1, mycallback],
		timeout: 7000
	}
		
	var d = new Date();
	var transaction = YAHOO.util.Connect.asyncRequest('GET',
																										(htmlbase +
																										 (window.location.pathname.substring(htmlbase.length).match(/^[^/?]*/)[0])+'/getAreaInfo?'
																										 //+'noCache='+(Math.random()+''+(new Date()).getTime()) // dont ever cache results
																										 +'cache='+(d.getFullYear()+'-'+(d.getMonth()+1)+'-'+d.getDate()) // let it be cached for one full day
																										 +'&lat='+areaLat+'&lng='+areaLng+'&zoom='+areaZoom+"&json=1"),
					callback);
}

var getAreaInfoFailure = function(o){
	//document.getElementById('loadingDiv').style.display='none';
	var numtries = 0;
	try {
		numtries = o.argument[0];
	} catch(e) {}
	if (typeof numtries == 'number' && numtries > 0) {
		getAreaInfo(numtries-1);
	} else {
		var filterDiv = document.getElementById('area_subcatsCol1');
		filterDiv.innerHTML = t("An error has occured. The filter could not load.");
	}
	//window.setMessage( window.serverAddr, "ERROR");
}

var availAreaFilter = null;
var getAreaInfoSuccess = function (o) {

	// updates smallShapeInfo, shapefile_id_names
//try {
	//alert(o.responseText);
	if (!areaFilterZooms) checkZoom = true;
	availAreaFilter = eval("("+o.responseText+")");
	areaFilterCountryCode = availAreaFilter.countryCode;
	areaFilterZooms = [];
	try {
		for (var i in availAreaFilter.zooms) {
			areaFilterZooms.push({zoom:i, shapefileid:availAreaFilter.zooms[i]});
		}
		areaFilterZooms.push({zoom:0});
	} catch(e) {}
	availAreaFilter = availAreaFilter.Shapefile;
	markHiddenShapefileIds();
	showAvailFilters();
	if (checkZoom)
		thematicChangedZooms(false); //if we're setting up the page from a page load, check the currently viewed shapefile id to make sure it isnt one that should be hidden right now based on the zoom level
	
//} catch (e) {alert('erro:'+e.message + " " + e.name);}
	
	if (o.argument.length > 1) {
		var callback = o.argument[1];
		if (typeof(callback)=='function')
		callback();
	}
}

function getThematicLinkedShapefileIdStatuses(zoom, shapefileId) {
	var shapefileIdToKeep = null;
	var shapefileIdsToLose = {};
	var z;
	if (typeof(zoom)!='undefined')
		z = zoom;
	else
		z = map.getZoom();
	if (areaFilterZooms.length>1) {
		for (i=0; i < areaFilterZooms.length; i++) {
			if (z <= areaFilterZooms[i].zoom && z > areaFilterZooms[i+1].zoom) {
				shapefileIdToKeep = areaFilterZooms[i].shapefileid;
			} else {
				shapefileIdsToLose[areaFilterZooms[i].shapefileid] = true;
			}
		}
	}

	var nonlinked = -1;
	if (typeof(shapefileId)!='undefined') {
		if (shapefileId != shapefileIdToKeep && !shapefileIdsToLose[shapefileId]) {
			nonlinked = shapefileId;
		}
	}
	return {keep:shapefileIdToKeep, lose:shapefileIdsToLose, nonlinked:nonlinked};
}

function markHiddenShapefileIds() {
	if (areaFilterZooms.length) {
		var statuses = getThematicLinkedShapefileIdStatuses();

		var k = 0;
		try {
			while (true) {
				var t = availAreaFilter[k];
				if (statuses.lose[t['@attrs'].shapefileid]) {
					t.hidden = true;
				} else {
					t.hidden = false;
				}
				k++;
			}
		} catch(e) {}
	}
}

/*
 * Natural Sort algorithm for Javascript
 *  Version 0.2
 * Author: Jim Palmer (based on chunking idea from Dave Koelle)
 * Released under MIT license.
 * from : http://www.overset.com/2008/09/01/javascript-natural-sort-algorithm/
 */
function naturalSort (a, b) {
	// setup temp-scope variables for comparison evauluation
	var x = a.toString().toLowerCase() || '', y = b.toString().toLowerCase() || '',
		nC = String.fromCharCode(0),
		xN = x.replace(/([-]{0,1}[0-9.]{1,})/g, nC + '$1' + nC).split(nC),
		yN = y.replace(/([-]{0,1}[0-9.]{1,})/g, nC + '$1' + nC).split(nC),
		xD = (new Date(x)).getTime(), yD = (new Date(y)).getTime();
	// natural sorting of dates
	if ( xD && yD && xD < yD )
		return -1;
	else if ( xD && yD && xD > yD )
		return 1;
	// natural sorting through split numeric strings and default strings
	for ( var cLoc=0, numS = Math.max( xN.length, yN.length ); cLoc < numS; cLoc++ )
		if ( ( parseFloat( xN[cLoc] ) || xN[cLoc] ) < ( parseFloat( yN[cLoc] ) || yN[cLoc] ) )
			return -1;
		else if ( ( parseFloat( xN[cLoc] ) || xN[cLoc] ) > ( parseFloat( yN[cLoc] ) || yN[cLoc] ) )
			return 1;
	return 0;
}

function showAvailFilters() {
	area_displayed_categories = {};
	area_subcategories = {};
	shapefile_selected = {};

	var ihtml = [];
	if (availAreaFilter) {
		ihtml.push("<div class='areaFilterSectionHeading'>"+t("Apply New Filter:")+" </div>");
		var sortedFilters = [];
		for (var i = 0; ; i++) {
			if (typeof(availAreaFilter[i])=='undefined') {
				break;
			}
			sortedFilters.push(availAreaFilter[i]);
		}
		sortedFilters.sort(function (a,b) {
			return naturalSort(a['@attrs']['title'], b['@attrs']['title']);
		});
		for (var i = 0; i<sortedFilters.length; i++) {
			if (typeof(sortedFilters[i])=='undefined') {
				break;
			}
			var shpf = sortedFilters[i];
			if (typeof(shpf.hidden)!='hidden' && shpf.hidden) {
				continue;
			}
			var shpf_id = shpf['@attrs']['shapefileid'];
			var shpf_title = shpf['@attrs']['title'];
			shapefile_id_names[shpf_id] = shpf_title;
			var onclick = ' onclick="toggleOneMainCategory('+shpf_id+', \'area_\');" ';
			ihtml.push("<div class='crimeGroup'>");
			ihtml.push("	<div class='crimeTypeMain' id='area_category_main_"+shpf_id+"' "+onclick+" >");
			ihtml.push("		"+shpf_title);
			ihtml.push("	</div><!-- end class=crimeTypeMain -->");
			area_displayed_categories[shpf_id] = {};
			area_subcategories[shpf_id] = {};
			shapefile_selected[shpf_id] = false;
			if (!showThematicView) {
				var shps = shpf['Shape'];
				var sortedShps = [];
				for (var k = 0; ; k++) {
					if (typeof(shps[k]) == 'undefined')
						break;
					sortedShps.push(shps[k]);
				}
				sortedShps.sort(function (a,b) {
					return naturalSort(a['#text'], b['#text']);
				});
				for (var k = 0; k<sortedShps.length; k++) {
					if (typeof(sortedShps[k]) == 'undefined')
						break;
					var shp = sortedShps[k];
					var shp_id = shp['@attrs']['shapeid'];
					var shp_title = shp['#text'];
					if (typeof(smallShapeInfo[shpf_id])!='object')
						smallShapeInfo[shpf_id] = {};
					if (typeof(smallShapeInfo[shpf_id][shp_id])!='object')
						smallShapeInfo[shpf_id][shp_id] = {};
					smallShapeInfo[shpf_id][shp_id].name = shp_title;
					smallShapeInfo[shpf_id][shp_id].centroid = shp['@attrs']['centroid'];
					onclick = ' onclick="toggleOneSubCategory('+shpf_id+','+shp_id+', \'area_\');" ';
					ihtml.push("	<div class='crimeTypeSub' id='area_category_sub_"+shpf_id+"_"+shp_id+"' "+onclick+" >");
					ihtml.push("		"+shp_title);
					ihtml.push("	</div>");
					area_subcategories[shpf_id][shp_id] = shp['#text'];
				}
			}
			ihtml.push("</div><!-- end class=crimeGroup -->");
		}
	}
	if (ihtml.length == 0) {
		ihtml.push(t("No Areas were found near the map center."));
	}
	var filterDiv = document.getElementById('area_subcatsCol1');
	filterDiv.innerHTML = ihtml.join("\n");
}


function placeNamesOfCurrentAreaIds() {
	var div = document.getElementById('areaFilterCurrent');
	if (!div) return;
	var ihtml = [];
	var ids = null;
	if (showThematicView) {
		if (thematicShapefileId)
			ids = [thematicShapefileId];
	} else {
		ids = areaShapeIds;
		if (typeof(ids)=='string') {
			ids = areaShapeIds.split(',');
		}
	}
	if (ids && ids.length > 0 && (areaShapeIds!='' || showThematicView)) {
		ihtml.push("<div class='areaFilterSectionHeading'>"+t("Current Filter:")+" </div>");
		ihtml.push("<div class='crimeGroupNoAction' >");
		var shapefileid = null;
		var someFilters = false;
		for (var i in ids) {
			if (!showThematicView && !String(ids[i]).match(/^\d+_\d+$/))
				continue;
			if (shapefileid == null) { // we assume for now that they can only select one shapefile. this will have to change if/when we allow them to select more than one shapefile
				shapefileid = showThematicView ? ids[i] : getShapefileId(ids[i]); //shapeToShapefileMap[ids[i]];
				ihtml.push("<div class='crimeTypeMainNoAction'>"+shapefile_id_names[shapefileid]+"</div>");
			}
			if (!showThematicView) {
				var shapeid = getShapeId(ids[i]); //shapeToShapefileMap[ids[i]];
				ihtml.push("<div class='crimeTypeSubNoAction' style='padding-left:10px;'>"+smallShapeInfo[shapefileid][shapeid].name+"</div>");
			}
			someFilters = true;
		}
		if (!someFilters) {
			ihtml.push("<div class='crimeTypeMainNoAction'>"+t('[None]')+"</div>");
		}
		ihtml.push("</div>");
	}
	
	div.innerHTML = ihtml.join("\n");
}


// getShapefileIds is optional
function getSelectedAreaIds(shapefileIds) {
	var ids = [];
	if (typeof(shapefileIds) != 'undefined' && shapefileIds) {
		for (var i in shapefile_selected) {
			if (shapefile_selected[i])
				ids.push(i);
		}
	} else {
		for (var i in area_displayed_categories) {
			for (var j in area_displayed_categories[i]) {
				if (area_displayed_categories[i][j]) {
					ids.push(i+'_'+j);
				}
			}
		}
	}
	return ids.join(',');
}



var areaFilterStateOpen = 0;
function setupAreaPanTrigger() {
	GEvent.addListener(map, "dragstart", function() {
			if (areaFilterStateOpen) {
				o = toggleTypes('area');
				if (o=='on')
					toggleTypes('area');
				areaFilterStateOpen = 0;
			}
		});
	GEvent.addListener(map, "dragend", function() {
			if (areaFilterStateOpen) {
				getAreaInfo();
			}
		});
}


	var curSelected = null;

	function loadAreaFilterTiles() {
		var lat = parseFloat(chosenAreaLat);
		var lng = parseFloat(chosenAreaLng);

		var zoom = map.getZoom();
		if (chosenAreaZoom != null)
			zoom = parseInt(chosenAreaZoom);
		map.setCenter(new GLatLng(lat, lng), zoom);
		window.chosenShapefileId = getShapefileId(areaShapeIds.split(',')[0]);//shapeToShapefileMap[areaShapeIds.split(',')[0]];
		
		initAFTileOverlay(map);
	}

	function getShapefileId(shapeid) {
		return shapeid.match(/^\d+/)[0]; 
	}
	function getShapeId(shapeid) {
		return shapeid.match(/_(\d+)/)[1]; 
	}

	function loadShapefilePreview(index) {
		var lat = parseFloat(shpinfo[index].centerlat);
		var lng = parseFloat(shpinfo[index].centerlng);
		var zoom = parseInt(shpinfo[index].zoom);

		if (curSelected!==null) {
			var old = document.getElementById('shpfile_index_'+curSelected);
			old.className = old.className.replace(/\s*shapefileSelected\s*/,'');
		}
		var ele = document.getElementById('shpfile_index_'+index);
		if (!ele.className.match(/shapefileSelected/)) {
			ele.className = ele.className + ' shapefileSelected';
		}
		curSelected = index;

		map.setCenter(new GLatLng(lat, lng), zoom+1);
		
		
		initTileOverlay(map, index);
	}

	var defaultShapefileIndex = null;
	function createMGMap(){
		if (GBrowserIsCompatible() ) { 
			
			map = new GMap2(document.getElementById("map"));
					
			map.setCenter(new GLatLng(38.89,-77.037),4);
			map.setMapType(G_SATELLITE_MAP); // G_HYBRID_MAP or G_NORMAL_MAP
			map.addControl(new GLargeMapControl());
			map.addControl(new GMapTypeControl());

				//map.setCenter(new GLatLng(shpinfo[k].centerlat*1, shpinfo[k].centerlng*1), shpinfo[k].zoom*1);

			if (typeof(defaultShapefileIndex)=='string') {
				defaultShapefileIndex = parseInt(defaultShapefileIndex);
			}
			if (defaultShapefileIndex === null && typeof(shpinfo)==='object') {
				defaultShapefileIndex = 0;
				for (var i = 0; i < shpinfo.length; i++) { 
					if (shpinfo[i].is_default) {
						defaultShapefileIndex = 0;
					}
				}
			}
		
			if (chosenAreaLat && chosenAreaLng) {
				loadAreaFilterTiles();
			} else if (typeof(defaultShapefileIndex)=='number' && !isNaN(defaultShapefileIndex)) {
				loadShapefilePreview(defaultShapefileIndex);
			} else {
				i = defaultShapefileIndex;
				map.setCenter(new GLatLng(parseFloat(shpinfo[i].centerlat),
						parseFloat(shpinfo[i].centerlng)),
						parseInt(shpinfo[i].zoom));
			}
			if (typeof(doSetupAreaPanTrigger) != 'undefined' && doSetupAreaPanTrigger) {
				setupAreaPanTrigger();
			}
		}
	}

	function initTileOverlay(map, index) {
		if (map.tileLayer)
			map.removeOverlay(map.tileLayer);
		var tilelayer = new GTileLayer(new GCopyrightCollection(''), 5, 14);
		tilelayer.getTileUrl = function(tile, zoom) {
			var url =  "http"+PE_Shapefile_BASE_URL+"bin/renderCRpreview.php?api_key="+PE_Shapefile_API_KEY
					+"&type="+shpinfo[index].shape_type.toUpperCase()
					+"&f="+shpinfo[index].ga_file_name
					+"&z="+zoom
					+"&label_field="+shpinfo[index].chosen_field_number
					+"&ul_x="+shpinfo[index].br_ul_long
					+"&ul_y="+shpinfo[index].br_ul_lat
					+"&lr_x="+shpinfo[index].br_lr_long
					+"&lr_y="+shpinfo[index].br_lr_lat
					+"&x="+tile.x
					+"&y="+tile.y
					+"&m=0"
					+"&h=3"
					+"&w=geoamp"
					+"&border_alpha=220"
					+"&splash_meters=0"
					+"&all_borders=1"
					+"&border_width=2"
					+"&show_labels=1"
					+"&layer_type=thematic"
					;
			//alert(url);
			return url;
		}   
		tilelayer.isPng = function() {return true;}
		tilelayer.getOpacity = function() {return 1;}
		map.tileLayer = new GTileLayerOverlay(tilelayer);
		map.addOverlay(map.tileLayer);
	}

	var initAFTileOverlay__status = null;
	function initAFTileOverlay(map) {
		if (map.tileLayer)
			map.removeOverlay(map.tileLayer);
		var doThematic = getDoThematic();
		var tilelayer = new GTileLayer(new GCopyrightCollection(''), 5, 14);
		tilelayer.getTileUrl = function(tile, zoom) {
			var sfid = "";
			if (doThematic) {
				sfid = thematicShapefileId;
				if (areaFilterZooms) {
					if (!initAFTileOverlay__status ||
								(initAFTileOverlay__status.zoom != zoom && initAFTileOverlay__status.nonlinked == -1) || // thematic with linked shapefile ids
								(initAFTileOverlay__status.nonlinked != -1 && initAFTileOverlay__status.nonlinked!=sfid)) { // thematic with NONlinked shapefile ids
						initAFTileOverlay__status = getThematicLinkedShapefileIdStatuses(zoom, sfid);
						initAFTileOverlay__status.zoom = zoom;
					}
					if (sfid != initAFTileOverlay__status.nonlinked && sfid != initAFTileOverlay__status.keep) {
						return '';
					}
				} else {
					return '';
				}
			} else {
				sfid = window.chosenShapefileId;
			}
			if (sfid+""=="") {
				return '';
			}
			var url = "http"+PE_Shapefile_TILES+"serveTiles?"+PE_Shapefile_API_KEY+"+"+(doThematic?PE_Shapefile_API_KEY+'_'+PE_Shapefile_THEMATIC_LAYER_NAME:PE_Shapefile_LAYER_NAME)+"[SRC_FILEID="+sfid+"]"+(!doThematic && areaShapeIds && areaShapeIds.length ? "["+areaShapeIds+"]" : '')+"&0&+"+tile.x+"+"+tile.y+"+"+zoom + (doThematic ? '+'+thematicLegend.legend_session_id+'+'+PE_Shapefile_THEMATIC_LAYER_STYLE: '');
			return url;
		}
		tilelayer.isPng = function() {return true;}
		tilelayer.getOpacity = function() {return 1;}
		map.tileLayer = new GTileLayerOverlay(tilelayer);
		map.addOverlay(map.tileLayer);
	}


	function setMapCenterForAreaIds() {
		var ids = areaShapeIds;
		if (typeof(ids)=='string') {
			ids = ids.split(',');
		}
    var minLat = 90;
    var maxLat = -90;
    var minLng = 180;
    var maxLng = -180;
		var inIt = false;

		if (ids && ids.length > 0 && areaShapeIds!='') {
			for (var i in ids) {
				if (!String(ids[i]).match(/^\d+_\d+$/))
					continue;
				
				inIt = true;
				var shpf_id = getShapefileId(ids[i]);
				var shp_id = getShapeId(ids[i]);
				var centroid = smallShapeInfo[shpf_id][shp_id].centroid;
				var centroidArr = centroid.split(',');
				if (centroidArr && centroidArr.length == 2 || centroidArr.length == 3) {
					var lat = centroidArr[0];
					var lng = centroidArr[1];
					var radius = centroidArr[2];
					
					var leftSide = getDestPoint(lat, lng, 180+90, radius);
					var rightSide = getDestPoint(lat, lng, 90, radius);
					var topSide = getDestPoint(lat, lng, 0, radius);
					var bottomSide = getDestPoint(lat, lng, 180, radius);
					//map.addOverlay(new GMarker(new GLatLng(bottomSide.lat(),leftSide.lng())));
					//map.addOverlay(new GMarker(new GLatLng(topSide.lat(), rightSide.lng())));
					//alert('addedone');
				
					minLat = Math.min(bottomSide.lat(), minLat);
					maxLat = Math.max(topSide.lat(), maxLat);
					minLng = Math.min(leftSide.lng(), minLng);
					maxLng = Math.max(rightSide.lng(), maxLng);
				}
			}
			//alert(minLat + ',' + minLng + ': :' + maxLat + ',' + maxLng);
			//map.addOverlay(new GMarker(new GLatLng(minLat, minLng)));
			//map.addOverlay(new GMarker(new GLatLng(maxLat, maxLng)));
			
			if (inIt) {
				centerLat = (maxLat - minLat)/2 + minLat;
				centerLng = (maxLng - minLng)/2 + minLng;
				newctr = new GLatLng(centerLat, centerLng);
				map.setCenter(newctr, 1 + map.getBoundsZoomLevel(new GLatLngBounds(
																		new GLatLng(minLat, minLng),
																		new GLatLng(maxLat, maxLng))));
				//map.addOverlay(new GMarker(newctr));
			}
		}
	}

	Number.prototype.toRad = function() {  // convert degrees to radians
		return this * Math.PI / 180;
	}

	Number.prototype.toDeg = function() {  // convert radians to degrees (signed)
		return this * 180 / Math.PI;
	}

	Number.prototype.toBrng = function() {  // convert radians to degrees (as bearing: 0...360)
		return (this.toDeg()+360) % 360;
	}

	/*
	 * calculate destination point given start point, initial bearing (deg) and distance in mi
	 *   see http://www.movable-type.co.uk/scripts/latlong.html
	 */
	function getDestPoint(lat, lon, brng, d) {
		var R = 3963; // earth's mean radius in mi
		var lat1 = Number(lat).toRad(), lon1 = Number(lon).toRad();
		brng = Number(brng).toRad();

		var lat2 = Math.asin( Math.sin(lat1)*Math.cos(d/R) + 
													Math.cos(lat1)*Math.sin(d/R)*Math.cos(brng) );
		var lon2 = lon1 + Math.atan2(Math.sin(brng)*Math.sin(d/R)*Math.cos(lat1), 
																 Math.cos(d/R)-Math.sin(lat1)*Math.sin(lat2));
		//lon2 = (lon2+Math.PI)%(2*Math.PI) - Math.PI;  // normalise to -180...+180 // instantiation of GLatLng takes care of this for us

		if (isNaN(lat2) || isNaN(lon2)) return null;
		return new GLatLng(lat2.toDeg(), lon2.toDeg());
	}

	function setSessionAreaShapeIds() {
		var s = document.getElementById("setSessionAreaShapeIdsScript");
		if (s) {
			s.parentNode.removeChild(s);
		}

		var s = document.createElement("script");
		s.id = "setSessionAreaShapeIdsScript";
		s.type = 'text/javascript';
		s.src = "/map/setAreaShapeIds?ids="+areaShapeIds+"&nocache="+(new Date()).valueOf();

		var headTag = document.getElementsByTagName('head')[0];
		headTag.appendChild(s);
	}

	function deselectAllAreas() {
		var ids = getSelectedAreaIds();
		if (ids && ids.length > 0) {
			var firstId = ids.split(',')[0].split('_')[0];
			toggleOneMainCategory(firstId, 'area_');
		}
		shapefile_selected = {};
		areaShapeIds = '';
		window.chosenShapefileId = '';
		placeNamesOfCurrentAreaIds();
		initAFTileOverlay(map);
	}


	function toggleThematicView(checkbox) {
		showThematicView = checkbox.checked;
		showAvailFilters();
	}

	function getDoThematic() {
		var doThematic = false;
		try {
			doThematic = showThematicView && thematicShapefileId && thematicLegend && thematicLegend.legend_session_id;
		} catch(e){}
		return doThematic;
	}

	function readyInterfaceForThematicView() {
		var doThematic = getDoThematic();
		document.getElementById("resultsTabs").style.display = (doThematic ? 'none':'block');
		document.getElementById("searchCriteria").style.display = (doThematic ? 'none':'block');
		document.getElementById("searchResults").style.display = (doThematic ? 'none':'block');
		var legend = document.getElementById("thematicLegend");
		legend.style.display = (doThematic ? 'block':'none');
		if (doThematic && lastThemeLoc != getThemeLocation())
			legend.innerHTML = t("Loading...");
	}

	function getLegendReady() {
		if (!areaFilterZooms) {
			getAreaInfo(4, actuallyGetLegendReady);
		} else {
			actuallyGetLegendReady();
		}
	}

	function actuallyGetLegendReady() {
		if (!showThematicView || !thematicShapefileId) {
			thematicShapefileId = null;
			lastThemeLoc = "";
			
			thematicLegend = null;
			initAFTileOverlay(map);
			return;
		}


		var s = document.createElement('SCRIPT');
		lastThemeLoc = getThemeLocation();
		s.src = lastThemeLoc;
		
		document.body.appendChild(s);

	}

	function getThemeLocation() {
		var loc = [];
		loc.push("/map/getCrimeCountsByShapefile?thematic_shapefile_id="+thematicShapefileId+'&');
		loc.push(getCrimeTypeFiltersInString(displayed_categories));
		loc.push('dayrange='+document.getElementById('dayrange').value+"&");
		loc.push('custom_date_start='+document.getElementById('startdate').value+"&");
		loc.push('custom_date_end='+document.getElementById('enddate').value+"&");
		loc.push('countryCode='+areaFilterCountryCode+'&');
		loc.push('callback=setupLegend');
		return loc.join('');
	}

	function setupLegend(legend, calculations, padding, type) {
		map.closeInfoWindow();
		thematicLegend = legend;
		readyInterfaceForThematicView();
		if (!legend || legend.status != "Success")
			return;
		thematicLegend.calculations = calculations;
		thematicLegend.padding = padding;
		thematicLegend.type = type;
		thematicLegend.zooms = areaFilterZooms;
		
		var html = [];
		html.push("<h3>Legend</h3>");
		if (type=='population') {
			html.push("Number of Incidents per 1000 People");
		} else if (type=='area') {
			html.push("Number of Incidents per square mile");
		} else {
			html.push("Total Number of Incidents");
		}
		for (var i = 0; i < thematicLegend.colors.length; i++) {
			var c = thematicLegend.colors[i].substring(0, 6);
			html.push("<div class='thematicLegendItem'>");
			html.push("<div style='background-color:#"+c+";' class='thematicLegendColor'></div>");
			var bottom = null;
			var top = null;
			var bottomCalc = 0;
			var topCalc = 0;
			try { bottomCalc = calculations[i]; } catch (e) {}
			try { topCalc = calculations[i+1]; } catch (e) {}

			/* // for integers
			if (i == 0) {
				bottom = Math.floor(bottomCalc);
			} else if (i == thematicLegend.colors.length-1) {
				top = Math.ceil(topCalc);
			}
			if (!bottom) {
				if (Math.round(bottomCalc)==bottomCalc) {
					bottom = bottomCalc;
				} else {
					bottom = Math.ceil(bottomCalc);
				}
			}
			if (!top) {
				if (Math.round(topCalc)==topCalc) {
					top = topCalc - 1;
				} else {
					top = Math.floor(topCalc);
				}
			} //*/

			bottom = Math.round((bottomCalc/padding)*roundAmount)/roundAmount; // round to two decimal places
			top = Math.round((topCalc/padding)*roundAmount)/roundAmount;


			html.push(bottom+(top>bottom?"&ndash;"+top:'')+" incidents");
			html.push("</div>");
			if (!calculations) {
				break;
			}
		}
		document.getElementById('thematicLegend').innerHTML = html.join('');


		initAFTileOverlay(map);
	}
	
	var thematic_callbackIfNoResults = null;
	function getShapeIdFromLatLng(lat, lng, callbackIfNoResults) {
		thematic_callbackIfNoResults = callbackIfNoResults;
		var s = document.createElement('SCRIPT');
		s.src = 'http'+PE_Shapefile_BASE_URL+'bin/getShapeInfo.php?api_key='+PE_Shapefile_API_KEY+'&layer='+PE_Shapefile_API_KEY+'_'+PE_Shapefile_THEMATIC_LAYER_NAME+'&lat='+lat+'&lng='+lng+'&rule[0][name]=SRC_FILEID&rule[0][value]='+thematicShapefileId+'&json=1&callback=getInfoWindowHtmlForShape';
		document.body.appendChild(s);
	}

	var thematic_lastSelectedShapeId = null;
	function getInfoWindowHtmlForShape(shapedata) {
		if (shapedata == null || shapedata.length == 0) {
			thematic_lastSelectedShapeId = null;
			try {
				thematic_callbackIfNoResults();
			} catch (e) {}
			thematic_callbackIfNoResults = null;
			return;
		}
		var shapeId = shapedata[0].UNIQUE_ROW;
		if (thematic_lastSelectedShapeId == shapeId && map.getInfoWindow() && !map.getInfoWindow().isHidden()) return;
		thematic_lastSelectedShapeId = shapeId;
		var centroid = shapedata[0].centroid.split(',');
		var html = [];
		var num = 0;
		try {
			num = thematicLegend.data[shapeId];
			num = num/thematicLegend.padding;
		} catch(e) {}
		
		if (parseInt(num)!=num) {
			num = Math.round(num*roundAmount)/roundAmount;
		}
		html.push('<div style="font-size:120%;">'+shapedata[0].NAME+'</div>');
		html.push('<div>'+num+' crime'+(num==1?'':'s')+'</div>');
		var opts = {};
		opts.noCloseOnClick = true;
		map.openInfoWindowHtml(new GLatLng(parseFloat(centroid[0]), parseFloat(centroid[1])), html.join(''), opts);
	}

	function thematicChangedZooms(doMore) {
		if (typeof(doMore)=='undefined') {
			doMore = true;
		}
		var statuses = getThematicLinkedShapefileIdStatuses(map.getZoom(), thematicShapefileId);
		if (statuses.keep == thematicShapefileId || statuses.nonlinked == thematicShapefileId) {
			return;
		} else { // we need to change the shapefile they are viewing based on zoom level
			thematicShapefileId = statuses.keep;
			map.closeInfoWindow();
			if (doMore) {
				getDataForNewFilter();
				placeNamesOfCurrentAreaIds();
			}
		}
	}

