// Development (local)
/*var rootUrl = 'http://localhost/covfIMS/';
var server = 'http://localhost/covfIMS/webservices/';*/

// Staging (dev-web01)
var rootUrl = 'http://demo.timmons.com/covfIMS/';
var server = 'http://demo.timmons.com/covfIMS/webservices/';

//all
var rootUrl = './';
var server = './webservices/';

var user = new User();
var layerArray = new Array(); // Array of Layer objects
var mapArray = new Array(); // Array of Map objects
var mapArrayIndex;
var mapLoaded = false; //determines whether the map info has been returned

var sizing = false;
var arrPoints = new Array();
var moving;
var selectMode = 0; //0 - make new selection, 1 - add to/remove from selection (not yet implemented)
var pixelTolerance = 2; //pixel tolerance used for selecting by point
var zoomTolerance = 1000;//envelope size when zooming to a point
var prevState = 'ZOOMIN';//store the previous state so we can switch back if needed

var browser; // Browser
var map; // Map
var draw; // Draw
var toolTip; // FeatureToolTip
var queryBuilder; // QueryBuilder
var feature; // Feature
var spatialFilter; // SpatialFilter
var find; // Find

var x1;
var y1;
var x2;
var y2;

var lastResizeTick = 0;
var lastResizeTickDelay = 100;

//******************Zoom Slider******************************
var zs = new ZoomSlider();
zs.Mode = 1;//0 - Fixed Scale, 1 - Fixed Width. sets how the zoom slider bar works
zs.Orientation = 0;//0 - horizontal, 1 - vertical.
zs.WidthUnits = "MILES";

zs.ScaleArray[0] = 100;
zs.ScaleArray[1] = 200;
zs.ScaleArray[2] = 500;
zs.ScaleArray[3] = 1000;
zs.ScaleArray[4] = 2000;
zs.ScaleArray[5] = 5000;

zs.ScaleLabelArray = zs.ScaleArray;

/*zs.WidthArray[0] = 0.1;
zs.WidthArray[1] = 0.2;*/
zs.WidthArray[0] = 30;
zs.WidthArray[1] = 50;
zs.WidthArray[2] = 60;
zs.WidthArray[3] = 70;
zs.WidthArray[4] = 80;
zs.WidthArray[5] = 90;
zs.WidthArray[6] = 100;
zs.WidthArray[7] = 200;
zs.WidthArray[8] = 300;
zs.WidthArray[9] = 400;
zs.WidthArray[10] = 500;

zs.WidthLabelArray = zs.WidthArray;
//****************************************************

function delayResizeMap(){
	var now = new Date();
	lastResizeTick = now.valueOf();
	setTimeout("executeDelayResizeMap(" + lastResizeTick + ");",lastResizeTickDelay);
}

function executeDelayResizeMap(oldLastTick){
	if(oldLastTick == lastResizeTick){
		if(null != map){
			map.getMap('REFRESH', map.getMinX(), map.getMinY(), map.getMaxX(), map.getMaxY(), true);
		}
	}
}

function calcDistance(x1,y1,x2,y2)
{
	var dist;
	var thescale = (map.getMaxX() - map.getMinX()) / map.MapWidth;
	dist = Math.sqrt(Math.pow((thescale * (x2 - x1)),2) + Math.pow((thescale * (y2 - y1)),2));
 	return dist;
}
 
function calcArea(arr,x,y)
{
	var arrX = new Array();
	
	for( var z = 0; z < arr.length; z++ )
	{
		arrX.push(arr[z]);
	}
	
	if( x && y )
		arrX.push(x + "," + y);
	
	var area = 0;
	
	for( var i = 0; i < arrX.length; i++ )
	{
		if(i == arrX.length - 1)
			area += (arrX[i].split(',')[0] * arrX[0].split(',')[1] - arrX[0].split(',')[0] * arrX[i].split(',')[1]);
		else
			area += (arrX[i].split(',')[0] * arrX[i + 1].split(',')[1] - arrX[i + 1].split(',')[0] * arrX[i].split(',')[1]);
	}
	
	area = 0.5 * area; // in pixels
	
	//Convert Square Pixels to Square Map Units
	var unitsPerPixel = (map.getMaxX() - map.getMinX()) / map.MapWidth;
	area = area * Math.pow(unitsPerPixel,2);
	
	return Math.abs(area);//in map units
}

function resizeElements()
{
	/*
	divTabsTop = 129;
	divMapTop = 129;
	divMapLeft = 5;
	divTabsWidth = 340;
	*/
	
	divTabsTop = 150;
	divMapTop = 150;
	divMapLeft = 5;
	divTabsWidth = 410;
	
	divTools.style.width = document.body.clientWidth - 15;
	
	divMap.style.height = document.body.clientHeight - divMapTop - 63;
	divMap.style.width = document.body.clientWidth - divTabsWidth - 20;
	divTabs.style.left = parseInt(divMap.style.width) + 10;
	
	map.MapWidth = parseInt(divMap.style.width);
	map.MapHeight = parseInt(divMap.style.height);
	map.MapLeft = parseInt(divMapLeft);
	map.MapTop = parseInt(divMapTop);
	divMapImage.style.width = map.MapWidth;
	divMapImage.style.height = map.MapHeight;
	mapImage.style.width = map.MapWidth;
	mapImage.style.height = map.MapHeight;
	
	divZoomSlider.style.width = map.MapWidth;
	divZoomSlider.style.top = map.MapTop + map.MapHeight;
	footer.style.top = parseInt(divZoomSlider.style.top) + 70;
	
	divTabs.style.height = 45 + parseInt(divMap.style.height) + 12;
	
	divLayers.style.height = parseInt(divTabs.style.height) - 35;
	divLayersList.style.height = parseInt(divTabs.style.height) - 35 - 37;
	
	divInformation.style.height = parseInt(divTabs.style.height) - 35;
	divInformationList.style.height = parseInt(divTabs.style.height) - 35 - 60;
	divInformationMessage.style.height = parseInt(divTabs.style.height) - 35 - 60;
	
	divResults.style.height = parseInt(divTabs.style.height) - 35;
	divResultsList.style.height = parseInt(divTabs.style.height) - 35 - 60;
	divDetailsList.style.height = parseInt(divTabs.style.height) - 35 - 60;
	
	divSearch.style.height = parseInt(divTabs.style.height) - 35;
	divParcelSearchList.style.height = parseInt(divTabs.style.height) - 35 - 40;
	
	divLegend.style.height = parseInt(divTabs.style.height) - 35;
	
	draw.resizeElements();
}

function showLoading()
{
	loading.style.left = (document.body.clientWidth/2 - parseInt(loading.style.width) /2 + document.body.scrollLeft)
	loading.style.top = (document.body.clientHeight/2 - parseInt(loading.style.height) /2 + document.body.scrollTop)
	loading.style.visibility = "visible";
}

function init()
{
	browser = new Browser();
	feature = new Feature();
	spatialFilter = new SpatialFilter();
	map = new Map();
	draw = new Draw(browser, "draw");
	draw.writeHtml();

	//draw.setState("ZOOMIN");
	draw.setState("PAN");
	resizeElements();
	
	find = new Find();
	
	// login the current user
	user.userLogin();
	
	// load query builder html
	queryBuilder = new QueryBuilder("divQueryBuilder");
	
	var layer = new Layer();
	layer.getSearchableLayers();
	
	// load layer list, which will call the first map once finished
	layer.loadLayerList();
	
	toolTip = new FeatureToolTip("divFeatureToolTip");
	toolTip.updateFeatureToolTipStatus();
	
	zs.createHTML();
}

function setActiveLayerNoClick(layerPosition)
{
	if( map.ActiveLayer )
		eval("lyr" + map.ActiveLayer).className = "layerNormal";
		
	eval("lyr" + layerPosition).className = "layerActive";
	map.ActiveLayer = layerPosition;
	for(var i = 0; i < activeLayerSelect.options.length; i++)
	{
		var ddlLayerPosition = activeLayerSelect.options[i].value;
		if(ddlLayerPosition == layerPosition)
		{
			activeLayerSelect.selectedIndex = i;
			break;
		}
	}
}

function setActiveLayer(layerPosition)
{
	if( browser.isInternetExplorer() )
	{
		if( event && event.srcElement.tagName == "INPUT" )
			return;
	}
		
	if( map.ActiveLayer )
		eval("lyr" + map.ActiveLayer).className = "layerNormal";
		
	eval("lyr" + layerPosition).className = "layerActive";
	map.ActiveLayer = layerPosition;
	for(var i = 0; i < activeLayerSelect.options.length; i++)
	{
		var ddlLayerPosition = activeLayerSelect.options[i].value;
		if(ddlLayerPosition == layerPosition)
		{
			activeLayerSelect.selectedIndex = i;
			break;
		}
	}
}

function getActiveLayerId()
{
	var layer;
	
	for( var i = 0; i < layerArray.length; i++ )
	{
		layer = layerArray[i];
		
		if( map.ActiveLayer == layer.LayerPosition )
			return layer.Name;
	}
}


function changeLayerVisible(layerName)
{
	// find layer in "layerArray" and set its visibility 
	// to the the opposite of its current setting
	var layer;
	
	for( var i = 0; i < layerArray.length; i++ )
	{
		layer = layerArray[i];
		
		if( layer.Name == layerName )
		{
			// found layer, change it's visibility setting
			if( layer.IsVisible )
				layer.IsVisible = false;
			else if( !layer.IsVisible )
				layer.IsVisible = true;
		}
	}
}

function updateVisibleLayers()
{
	showLoading();
	
	// send request to web service to get new map
	map.getMap(draw.state, map.getMinX(), map.getMinY(), map.getMaxX(), map.getMaxY(), false);
}

function getVisibleLayerString()
{
	// take "layerArray" and send request back to server for new list
	// of layers to be visible.  this list also includes spatial filters (aka, cloned layers)
	// ?layers=Elevation,true$Polygon,123,345,456,678
	// ?layers=Parcels,true$Buffer,OBJECTID,DIST,UNITS,TARGET_LAYER,ACTIVE_LAYER
	var layerString = "";
	var layer;
	
	for( var i = 0; i < layerArray.length; i++ )
	{
		layer = layerArray[i];
		layerString += layer.Name + "," + layer.IsVisible;
		
		if( layer.SpatialFilter != null )
		{
			var spatialFilter = layer.SpatialFilter;
			
			if( spatialFilter.Type != null )
			{
				if( spatialFilter.Type != "Buffer" )
					layerString += "$" + spatialFilter.Type + "," + spatialFilter.Points;
				else
					layerString += "$" + spatialFilter.Type + "," + spatialFilter.Buffer.ObjectId + "," + spatialFilter.Buffer.BufferUnits + "," + spatialFilter.Buffer.BufferDistance + "," + spatialFilter.Buffer.BufferTarget + "," + spatialFilter.Buffer.ActiveLayer;
			}
		}
		
		if(layer.isThemed)
		{
			layerString += "!" + layer.themeField1 + "*" + layer.themeField2 + "*" + layer.breaks;
		}
		
		layerString += "|";
	}
	
	// remove last pipe "|" from layerString
	layerString = layerString.substr(0, layerString.lastIndexOf('|'));
	return layerString;
}

function calcScale()
{
	var mapScale = (map.getMaxX() - map.getMinX()) / map.MapWidth * 96; //mapunits/inch
	
	switch(map.Units)
	{
		case 'METERS':
			mapScale = mapScale / 0.0254;
			break;
		
		case 'FEET':
			mapScale = mapScale / 0.0254 * 0.3048;
			break;
		
		case 'MILES':
			mapScale = mapScale / 0.0254 * 0.3048 / 5280;
			break;
	}
	
	map.Scale = mapScale;
}

function checkVisScale()
{
	try
	{
		var chk;
		var layer;
		
		for(var i = 0; i < layerArray.length; i++)
		{
			layer = layerArray[i];
			var layerChk = document.getElementById("chk" + layer.LayerPosition);
			
			// check for "blank" values
			if( (parseFloat(layer.MinScale) == -1.0 || parseFloat(layer.MinScale) <= parseFloat(map.Scale)) 
			&& (parseFloat(layer.MaxScale) == -1.0 || parseFloat(layer.MaxScale) >= parseFloat(map.Scale)) )
			{
				// enable
				layerChk.disabled = false;
			}
			else
			{
				// set chk to disabled
				layerChk.disabled = true;
			}
		}
	}
	catch(e) {}
}

function collapseLayerGroup(group)
{
	var tbody = document.getElementById(group);
	var img = document.getElementById(group + "img");
	
	if( img.src.indexOf('minus') != -1 )
		img.src = "images/plus.gif";
	else
		img.src = "images/minus.gif";
		
	if( tbody.style.display == 'none')
	{
		if( !browser.isInternetExplorer() )
			tbody.style.display = 'table-row-group';
		else
			tbody.style.display = 'block';
	}
	else
		tbody.style.display = 'none';
}

// command: SELECTRECT, SELECTLINE, SELECTPOLY
function spatialSelect(command, points, isZoomTo)
{
	//clear current spatial filters, if necessary
	if( selectMode == 0 )
		draw.clearSelection(false);

	// "clone" active layer (add to SpatialFilter array of layer object in layerArray)
	if( map.ActiveLayer != "" )
	{
		var layer;
		
		for( var i = 0; i < layerArray.length; i++ )
		{
			layer = layerArray[i];
			
			if( layer.LayerPosition == map.ActiveLayer )
			{
				// set that spatial filter object's "type" and "points"
				spatialFilter = new SpatialFilter();
				spatialFilter.Points = "";
				
				// parse out points array, convert to map units, store in string using ',' to delim
				for( var x = 0; x < points.length; x++ )
				{
					var strx = points[x].split(',')[0];
					var stry = points[x].split(',')[1];
					
					if( isZoomTo )
						spatialFilter.Points += strx + "," + stry + ",";
					else
						spatialFilter.Points += convertMapPoints(strx, stry);
				}
				
				spatialFilter.Points = spatialFilter.Points.substr(0, spatialFilter.Points.lastIndexOf(','));
				
				if( command == "SELECTRECT" )
					spatialFilter.Type = "Polygon";
				else if( command == "SELECTLINE" )
					spatialFilter.Type = "Line";
				else if( command == "SELECTPOLY" )
					spatialFilter.Type = "Polygon";
					
				layer.SpatialFilter = spatialFilter;
				break;
			}
		}
		
		// send request for spatial filter data
		spatialFilter.getSpatialFilterResults();
		
		// send request to server using map.getMap() call
		map.getMap(draw.state, map.getMinX(), map.getMinY(), map.getMaxX(), map.getMaxY(), true);
	}
}

function collapseFeatureData(featureID, fieldsLength)
{
	var img = document.getElementById(featureID + "img");
	var tbody = document.getElementById(featureID + "tbody");

	if( img.src.indexOf('minus') != -1 )
		img.src = "images/plus.gif";
	else
		img.src = "images/minus.gif";
	
	if( tbody.style.display == 'none' || tbody.style.display == '')
	{	
		if( !browser.isInternetExplorer() )
			tbody.style.display = 'table-row-group';
		else
			tbody.style.display = 'block';
	}
	else
		tbody.style.display = 'none';
}

function convertMapPoints(x, y)
{
	x = (map.getMinX() * 1) + (x * (map.getMaxX() - map.getMinX())/map.MapWidth);
	y = map.getMaxY() - (y * (map.getMaxY() - map.getMinY())/map.MapHeight);
	
	return x + "," + y + ",";
}

function activateTab(tabID)
{	
	for( var i = 0; i < tblTabs.getElementsByTagName("td").length; i++ )
	{
		id = tblTabs.getElementsByTagName("td")[i].id;
		divid = id.replace("tab","div");
		
		if( id == tabID )
		{
			eval(id).className = "tabActive";
			eval(divid).style.display = "block";
		}
		else
		{
			eval(id).className = "tabNormal";
			eval(divid).style.display = "none";
		}
	}
}

function zoomToScale(scale)
{
	dx = map.getMaxX() - map.getMinX();
	dy = map.getMaxY() - map.getMinY();
	centerX = map.getMaxX() - dx / 2;
	centerY = map.getMaxY() - dy / 2;
	
	scale = scale / map.Scale;
	
	dx = dx * scale / 2;
	dy = dy * scale / 2;
	
	map.getMap("ZOOMIN", (centerX - dx), (centerY - dy), (centerX + parseFloat(dx)), (centerY + parseFloat(dy)), true)
}

function convertDistanceUnits(inputDistance, inputUnits, outputUnits)
{
	var outputDistance;
	
	//Convert everything to METERS
	switch(inputUnits)
	{
		case "METERS":
			outputDistance = inputDistance;
			break;
		case "FEET":
			outputDistance = inputDistance * 0.3048;
			break;
		case "MILES":
			outputDistance = inputDistance * 5280 * 0.3048;
			break;
		case "INCHES":
			outputDistance = inputDistance / 12 * 0.3048;
			break;		
	}
	
	//Convert METERS to OUTPUT UNITS
	switch(outputUnits)
	{
		case "METERS":
			outputDistance = outputDistance;
			break;
		case "FEET":
			outputDistance = outputDistance / 0.3048;
			break;
		case "MILES":
			outputDistance = outputDistance / 0.3048 / 5280;
			break;
		case "INCHES":
			outputDistance = outputDistance / 0.3048 * 12;
			break;	
	}
	
	return outputDistance;
}

function convertAreaUnits(inputArea, inputUnits, outputUnits)
{
	var outputArea;
	
	//Convert everything to SQUARE METERS
	switch(inputUnits)
	{
		case "METERS":
			outputArea = inputArea;
			break;
		case "FEET":
			outputArea = inputArea * Math.pow(0.3048,2);
			break;
		case "MILES":
			outputArea = inputArea * Math.pow(5280,2) * Math.pow(0.3048,2);
			break;
		case "INCHES":
			outputArea = inputArea / Math.pow(12,2) * Math.pow(0.3048,2);
			break;
		case "ACRES":
			outputArea = inputArea / 0.000247105 ;
			break;
	}
	
	//Convert SQUARE METERS to OUTPUT UNITS
	switch(outputUnits)
	{
		case "METERS":
			outputArea = outputArea;
			break;
		case "FEET":
			outputArea = outputArea / Math.pow(0.3048,2);
			break;
		case "MILES":
			outputArea = outputArea / Math.pow(0.3048,2) / Math.pow(5280,2);
			break;
		case "INCHES":
			outputArea = outputArea / Math.pow(0.3048,2) * Math.pow(12,2);
			break;
		case "ACRES":
			outputArea = outputArea * 0.000247105 ;
			break;	
	}
	
	return outputArea;
}

function getGeocode(address, crossStreet, county)
{
	
}

function processIdentify()
{
	var objectIds = new Array();
	showLoading();
	
	if(feature.XmlReqIdentify.readyState == 4)
	{
		if(feature.XmlReqIdentify.status == 200)
		{
			// parse response and place data into html table
			var infoTable = document.getElementById("divResultsList");
			infoTable.innerHTML = "";
			document.getElementById("subTabResultsList").innerHTML = "Identify Results";
			
			var response = feature.XmlReqIdentify.responseXML.documentElement;
			var features = response.getElementsByTagName('FEATURES');
			var className = "";
			var html = "<table width=\"100%\" cellspacing=\"0\" cellpadding=\"2\" style=\"margin-top:5px;\">";
			
			// get request specific top level values (layer, layerHyperlink, response feature count, hasMore features)
			var layer = features[0].attributes.getNamedItem('layer').nodeValue;
			var layerHyperlink = features[0].attributes.getNamedItem('hyperlink').nodeValue;
			var count = features[0].attributes.getNamedItem('count').nodeValue;
			var hasMore = features[0].attributes.getNamedItem('hasmore').nodeValue;
	
			if( count == 0 )
			{
				spnResultsInfo.innerHTML = "No Result Found";
			}
			else
			{
				if( count == 1 )
					spnResultsInfo.innerHTML = "1 Result Found";
				else
					spnResultsInfo.innerHTML = count + " Results Found";
			
				// looks at FEATURES elements
				for( var i = 0; i < features.length; i++ )
				{
					// looks at FEATURE elements
					for( var x = 0; x < features[i].childNodes.length; x++ )
					{
						if( features[i].childNodes[x].nodeName == 'FEATURE' )
						{
							var gpin = "";
							var minx = "", miny = "", maxx = "", maxy = "";
							
							// get feature specific top level values (uniqueName, uniqueValue, primaryDisplay)
							var uniqueName = features[i].childNodes[x].attributes.getNamedItem('uniquename').nodeValue;
							var uniqueValue = features[i].childNodes[x].attributes.getNamedItem('uniquevalue').nodeValue;
							var pdisplay = features[i].childNodes[x].attributes.getNamedItem('pdisplay').nodeValue;
							
							if( uniqueValue != "" )
								objectIds.push(uniqueValue);
							
							// get envelope information
							for( var y = 0; y < features[i].childNodes[x].childNodes.length; y++ )
							{
								if( features[i].childNodes[x].childNodes[y].nodeName == 'ENVELOPE' )
								{
									minx = features[i].childNodes[x].childNodes[y].attributes.getNamedItem('minx').nodeValue;
									miny = features[i].childNodes[x].childNodes[y].attributes.getNamedItem('miny').nodeValue;
									maxx = features[i].childNodes[x].childNodes[y].attributes.getNamedItem('maxx').nodeValue;
									maxy = features[i].childNodes[x].childNodes[y].attributes.getNamedItem('maxy').nodeValue;
									
									// setup primary display field in HTML
									html += "<tr class=\"fieldPrimary\">";
									
									if( pdisplay != '' )
										html += "<td>" + layer + ": " + pdisplay + "</td>";
									else
										html += "<td>" + layer + ": " + uniqueValue + "</td>";
									
									html += "<td align=\"right\">";
									
									// check for Parcel layer and add getAdjoiningFeatures link to OBJECTID
									if( layer == 'Tax Parcels' )
										html += "<img class=\"featureImage\" src=\"images/adjoiners.gif\" onmousedown=\"spatialFilter.getAdjoiningFeatures('" + uniqueValue + "', 'feet', 1, 'Tax Parcels', 'Tax Parcels');\" alt=\"Get Adjoining Parcels\" />";
								
									html += "<img class=\"featureImage\" src=\"images/feature_zoom_to.gif\" onmousedown=\"map.zoomToFeature('" + minx + "', '" + miny + "', '" + maxx + "', '" + maxy + "');\" alt=\"Zoom to Feature\" />";
									//html += "<img src=\"images/feature_report.gif\" alt=\"Feature Details\" onmousedown=\"feature.getFeatureDetails('" + layer + "','" + uniqueValue + "');\"/>";
									//html += "<img class=\"featureImage\" src=\"images/buffer.gif\" alt=\"Buffer Select\" onmousedown=\"document.getElementById('trInformationInfo').style.display='none';document.getElementById('divBuffer').style.display='block';document.getElementById('divInformationList').style.display='none';document.getElementById('divInformationMessage').style.display='none';\" />";
									html += "</td></tr>";
										
								}
								else if( features[i].childNodes[x].childNodes[y].nodeName == 'FIELDGROUP' )
								{
									var fieldGroupName = features[i].childNodes[x].childNodes[y].attributes.getNamedItem('name').value;
									var fieldGroupHyperlink = features[i].childNodes[x].childNodes[y].attributes.getNamedItem('hyperlink').value;
									
									// looks at FIELD elements
									for( var z = 0; z < features[i].childNodes[x].childNodes[y].childNodes.length; z++ )
									{
										if( features[i].childNodes[x].childNodes[y].childNodes[z].nodeName == 'FIELD' )
										{
											var fieldName = features[i].childNodes[x].childNodes[y].childNodes[z].attributes.getNamedItem('name').value;
											var fieldAlias = features[i].childNodes[x].childNodes[y].childNodes[z].attributes.getNamedItem('alias').value;
											var fieldNameHyperlink = features[i].childNodes[x].childNodes[y].childNodes[z].attributes.getNamedItem('namehyperlink').value;
											var fieldValue = features[i].childNodes[x].childNodes[y].childNodes[z].attributes.getNamedItem('value').value;
											var fieldValueHyperlink = features[i].childNodes[x].childNodes[y].childNodes[z].attributes.getNamedItem('valuehyperlink').value;
											
											// add each field to the HTML
											className = (z % 2 == 1)?"Odd":"Even";
											html += "<tr>";
											
											// add field name (alias)
											if( fieldNameHyperlink != "" )
											{
												html += "<td class=\"field" + className + "\">";
												html += "<a class=\"fieldLink\" href=\"" + fieldNameHyperlink + "\" target=\"_new\">";
												html += fieldAlias + "</a></td>";
											}
											else
												html += "<td class=\"field" + className + "\">" + fieldAlias + "</td>";
											
											// add field value
											if( fieldValue != null )
											{
												// check for hyperlink!
												if( fieldValueHyperlink != "" )
												{
													html += "<td class=\"field" + className + "\">";
													html += "<a class=\"fieldLink\" href=\"" + fieldValueHyperlink + "\" target=\"_new\">";
													html += fieldValue + "</a></td>";
												}
												else
													html += "<td class=\"fieldValue" + className + "\">" + fieldValue + "</a></td>";
											}
											else
												html += "<td></td></tr>";
										}
									}
								}
							}
						}
					}
				}
				
				html += "</table>";
				infoTable.innerHTML = html;
			}
			if(objectIds.length > 0)
			{
				var spanHtml = "<br/><span class=\"trInfo\" style=\"font-size:11px\">Export data to Excel </span><a href=\"feature_csv.aspx?objectId=";
				for( var n in objectIds)
				{
					spanHtml += objectIds[n] + ",";
				}

				spanHtml += "&layer=" + layer + "&reportType=Short Report&userGroupName=" + user.userGroupName + "\" target=\"_new\" border=\"0\"><img src=\"images/excel.gif\" alt=\"Export to Excel\" border=\"0\" /></a>";
				spnResultsInfo.innerHTML += spanHtml;
			}			
			
			
			//activateTab("tabInformation");
			//trInformationInfo.style.display = 'block';
			//divInformationMessage.style.display = 'none';
			//divInformationList.style.display = 'block';
			//divTheme.style.display = 'none';
			//subTabInformationMessage.className = 'subTabNormal';
			//subTabInformationList.className = 'subTabActive';
			//subTabThemeMap.className = 'subTabNormal';
			document.getElementById('loading').style.visibility = 'hidden';
			
			activateTab("tabResults");
			trResultsInfo.style.display='block';
			trDetailsInfo.style.display='none';
			divResultsList.style.display='block';
			divDetailsList.style.display='none';
			subTabResultsList.className='subTabActive';
			subTabDetailsList.className='subTabNormal';
			
			if( hasMore == 'True' )
				alert("This search returned more than the number of features allowed.  Please refine your search for more detailed results.");
		}
	}
}

function processFeatureDetail()
{
	var objectIds = new Array();
	showLoading();
	
	if(feature.XmlReqDetails.readyState == 4)
	{
		if(feature.XmlReqDetails.status == 200)
		{
			
			// parse response and place data into html table
			var detailsTable = document.getElementById("divDetailsList");
			detailsTable.innerHTML = "";

			
			var response = feature.XmlReqDetails.responseXML.documentElement;
			var features = response.getElementsByTagName('FEATURES');
			var className = "";
			var html = "<table width=\"100%\" cellspacing=\"0\" cellpadding=\"2\" style=\"margin-top:5px;\">";
			
			// get request specific top level values (layer, layerHyperlink, response feature count, hasMore features)
			var layer = features[0].attributes.getNamedItem('layer').value;
			var layerHyperlink = features[0].attributes.getNamedItem('hyperlink').value;
			var count = features[0].attributes.getNamedItem('count').value;
			var hasMore = features[0].attributes.getNamedItem('hasmore').value;
			
			spnDetailsInfo.innerHTML = "Data Details";
			
			// looks at FEATURES elements
			for( var i = 0; i < features.length; i++ )
			{
				// looks at FEATURE elements
				for( var x = 0; x < features[i].childNodes.length; x++ )
				{
					if( features[i].childNodes[x].nodeName == 'FEATURE' )
					{
						var gpin = "";
						var minx = "", miny = "", maxx = "", maxy = "";
						
						// get feature specific top level values (uniqueName, uniqueValue, primaryDisplay)
						var uniqueName = features[i].childNodes[x].attributes.getNamedItem('uniquename').value;
						var uniqueValue = features[i].childNodes[x].attributes.getNamedItem('uniquevalue').value;
						var pdisplay = features[i].childNodes[x].attributes.getNamedItem('pdisplay').value;
						
						objectIds.push(uniqueValue);
						
						for( var y = 0; y < features[i].childNodes[x].childNodes.length; y++ )
						{
							if( features[i].childNodes[x].childNodes[y].nodeName == 'ENVELOPE' )
							{
								// get envelope information
								minx = features[i].childNodes[x].childNodes[y].attributes.getNamedItem('minx').value;
								miny = features[i].childNodes[x].childNodes[y].attributes.getNamedItem('miny').value;
								maxx = features[i].childNodes[x].childNodes[y].attributes.getNamedItem('maxx').value;
								maxy = features[i].childNodes[x].childNodes[y].attributes.getNamedItem('maxy').value;
						
								// setup primary display field in HTML
								html += "<tr class=\"fieldPrimary\">";
								
								if( pdisplay != '' )
									html += "<td>" + layer + ": " + pdisplay + "</td>";
								else
									html += "<td>" + layer + ": " + uniqueValue + "</td>";
									
								html += "<td align=\"right\">";
									
								// check for Parcel layer and add getAdjoiningFeatures link to OBJECTID
								if( layer == 'Tax Parcels' )
									html += "<img class=\"featureImage\" src=\"images/adjoiners.gif\" onmousedown=\"spatialFilter.getAdjoiningFeatures('" + uniqueValue + "', 'feet', 1, 'Tax Parcels', 'Tax Parcels');\" alt=\"Get Adjoining Parcels\" />";
									
								html += "<img class=\"featureImage\" src=\"images/feature_zoom_to.gif\" onmousedown=\"map.zoomToFeature('" + minx + "', '" + miny + "', '" + maxx + "', '" + maxy + "');\" alt=\"Zoom to Feature\" />";
								html += "</td></tr>";
							}
							else if( features[i].childNodes[x].childNodes[y].nodeName == 'FIELDGROUP' )
							{
								var fieldGroupName = features[i].childNodes[x].childNodes[y].attributes.getNamedItem('name').value;
								var fieldGroupHyperlink = features[i].childNodes[x].childNodes[y].attributes.getNamedItem('hyperlink').value;
								
								if( fieldGroupHyperlink != null && fieldGroupHyperlink != '' )
									html += "<tr><td colspan=\"2\" class=\"fieldGroupHeading\"><a href=\"" + fieldGroupHyperlink + "\" target=\"_new\">" + fieldGroupName + "</a></td></tr>";
								else
									html += "<tr><td colspan=\"2\" class=\"fieldGroupHeading\">" + fieldGroupName + "</td></tr>";
								
								// looks at FIELD elements
								for( var z = 0; z < features[i].childNodes[x].childNodes[y].childNodes.length; z++ )
								{
									if( features[i].childNodes[x].childNodes[y].childNodes[z].nodeName == 'FIELD' )
									{
										var fieldName = features[i].childNodes[x].childNodes[y].childNodes[z].attributes.getNamedItem('name').value;
										var fieldAlias = features[i].childNodes[x].childNodes[y].childNodes[z].attributes.getNamedItem('alias').value;
										var fieldNameHyperlink = features[i].childNodes[x].childNodes[y].childNodes[z].attributes.getNamedItem('namehyperlink').value;
										var fieldValue = features[i].childNodes[x].childNodes[y].childNodes[z].attributes.getNamedItem('value').value;
										var fieldValueHyperlink = features[i].childNodes[x].childNodes[y].childNodes[z].attributes.getNamedItem('valuehyperlink').value;
										
										// add each field to the HTML
										className = (z % 2 == 1)?"Odd":"Even";
										html += "<tr>";
										
										// add field name (alias)
										if( fieldNameHyperlink != "" )
										{
											html += "<td class=\"field" + className + "\">";
											html += "<a class=\"fieldLink\" href=\"" + fieldNameHyperlink + "\" target=\"_new\">";
											html += fieldAlias + "</a></td>";
										}
										else
											html += "<td class=\"field" + className + "\">" + fieldAlias + "</td>";
										
										// add field value
										if( fieldValue != null )
										{
											// check for hyperlink!
											if( fieldValueHyperlink != "" )
											{
												html += "<td class=\"fieldValue" + className + "\">";
												html += "<a class=\"fieldLink\" href=\"" + fieldValueHyperlink + "\" target=\"_new\">";
												html += fieldValue + "</a></td>";
											}
											else
												html += "<td class=\"fieldValue" + className + "\">" + fieldValue + "</a></td>";
										}
										else
											html += "<td></td>";
									}
								}
							}
						}
					}
				}
			}
			
			html += "</tr></table>";
			detailsTable.innerHTML = html;
		}
		
		if(objectIds.length > 0)
		{
			var spanHtml = "<br/><span class=\"trInfo\" style=\"font-size:11px\">Export feature data to Excel </span><a href=\"feature_csv.aspx?objectId=";
			for( var n in objectIds)
			{
				spanHtml += objectIds[n] + ",";
			}

			spanHtml += "&layer=" + layer + "&reportType=Short Report&userGroupName=" + user.userGroupName + "\" target=\"_new\" border=\"0\"><img src=\"images/excel.gif\" alt=\"Export to Excel\" border=\"0\" /></a>";
			spnDetailsInfo.innerHTML += spanHtml;
		}			
							
		activateTab("tabResults");
		trResultsInfo.style.display='none';
		trDetailsInfo.style.display='block';
		divResultsList.style.display='none';
		divDetailsList.style.display='block';
		subTabResultsList.className='subTabNormal';
		subTabDetailsList.className='subTabActive';
		document.getElementById('loading').style.visibility = 'hidden';
			
		if( hasMore == 'True' )
			alert("This search returned more than the number of features allowed.  Please refine your search for more detailed results.");
	}
}

function processShortReport()
{
	var objectIds = new Array();
		
	if( spatialFilter.XmlReqFilter.readyState == 4 )
	{
		if( spatialFilter.XmlReqFilter.status == 200 )
		{
			// parse response and place data into html table
			var resultTable = document.getElementById("divResultsList");
			resultTable.innerHTML = "";
			document.getElementById("subTabResultsList").innerHTML = "Selection Results";
			var response = spatialFilter.XmlReqFilter.responseXML.documentElement;
			var features = response.getElementsByTagName('FEATURES');
			var featureID = "";
			var html = "";
			
			// get request specific top level values (layer, layerHyperlink, response feature count, hasMore features)
			var layer = features[0].attributes.getNamedItem('layer').value;
			var layerHyperlink = features[0].attributes.getNamedItem('hyperlink').value;
			var count = features[0].attributes.getNamedItem('count').value;
			var hasMore = features[0].attributes.getNamedItem('hasmore').value;
			
			if( count == 0 )
				spnResultsInfo.innerHTML = "No Results Found";
			else if( count == 1 )
				spnResultsInfo.innerHTML = "1 Result Found";
			else
				spnResultsInfo.innerHTML = count + " Results Found";
			
			// looks at FEATURES elements
			for( var i = 0; i < features.length; i++ )
			{
				// looks at FEATURE elements
				for( var x = 0; x < features[i].childNodes.length; x++ )
				{
					if( features[i].childNodes[x].nodeName == 'FEATURE' )
					{
						var fieldCount = 0;
						var minx = "", miny = "", maxx = "", maxy = "";
							
						// get feature specific top level values (uniqueName, uniqueValue, primaryDisplay)
						var uniqueName = features[i].childNodes[x].attributes.getNamedItem('uniquename').value;
						var uniqueValue = features[i].childNodes[x].attributes.getNamedItem('uniquevalue').value;
						var pdisplay = features[i].childNodes[x].attributes.getNamedItem('pdisplay').value;
						
						objectIds.push(uniqueValue);
						
						// for parcels, need to add 1 to this value
						var totalFieldsInFeature = features[i].childNodes[x].attributes.getNamedItem('fields').value;
						
						for( var y = 0; y < features[i].childNodes[x].childNodes.length; y++ )
						{
							if( features[i].childNodes[x].childNodes[y].nodeName == 'ENVELOPE' )
							{
								// get envelope information
								minx = features[i].childNodes[x].childNodes[y].attributes.getNamedItem('minx').value;
								miny = features[i].childNodes[x].childNodes[y].attributes.getNamedItem('miny').value;
								maxx = features[i].childNodes[x].childNodes[y].attributes.getNamedItem('maxx').value;
								maxy = features[i].childNodes[x].childNodes[y].attributes.getNamedItem('maxy').value;
								
								// setup primary display field in HTML
								featureID = "feature" + x;
								className = "fieldPrimary";
								
								
								html = "<table style=\"width: 100%; padding: 5px 0px 0px 0px;\" id=\"tblSearchResults" + featureID +"\" cellspacing=\"0\" cellpadding=\"2\" style=\"margin-top:5px;\">";
								html += "<tr id=\"" + featureID + "\" class=\"" + className + "\">";
								html += "<td><img id=\"" + featureID + "img\" class=\"collapseImage\" src=\"images/plus.gif\" onmousedown=\"collapseFeatureData('" + featureID + "'," + totalFieldsInFeature + ");\" />";
								
								if( pdisplay != '' )
									html += layer + ": " + pdisplay + "</td>";
								else
									html += layer + ": " + uniqueValue + "</td>";
								
								html += "<td align=\"right\">";
								
								if( layer == 'Tax Parcels' )
									html += "<img class=\"featureImage\" src=\"images/adjoiners.gif\" onmousedown=\"spatialFilter.getAdjoiningFeatures('" + uniqueValue + "', 'feet', 1, 'Tax Parcels', 'Tax Parcels');\" alt=\"Get Adjoining Parcels\" />";
								
								html += "<img class=\"featureImage\" src=\"images/feature_zoom_to.gif\" onmousedown=\"map.zoomToFeature('" + minx + "', '" + miny + "', '" + maxx + "', '" + maxy + "');\" alt=\"Zoom to Feature\" />";
							//	html += "<img class=\"featureImage\" src=\"images/feature_report.gif\" alt=\"Feature Details\" onmousedown=\"feature.getFeatureDetails('" + layer + "','" + uniqueValue + "');\"/>";
							//	html += "<img class=\"featureImage\" src=\"images/buffer.gif\" alt=\"Buffer Select\" onmousedown=\"activateTab('tabInformation');document.getElementById('trInformationInfo').style.display='none';document.getElementById('divBuffer').style.display='block';document.getElementById('divInformationList').style.display='none';document.getElementById('divInformationMessage').style.display='none';document.getElementById('divResultsList').style.display='none';\" />";
							//	html += "<a href=\"feature_csv.aspx?objectId=" + uniqueValue + "&layer=" + layer + "&reportType=Short Report&userGroupName=" + user.userGroupName + "\" target=\"_new\" border=\"0\"><img class=\"featureImage\" src=\"images/excel.gif\" alt=\"Export to Excel\" border=\"0\" /></a>";			
								html += "</td></tr>";
							}
							else if( features[i].childNodes[x].childNodes[y].nodeName == 'FIELDGROUP' )
							{
								var fieldGroupName = features[i].childNodes[x].childNodes[y].attributes.getNamedItem('name').value;
								var fieldGroupHyperlink = features[i].childNodes[x].childNodes[y].attributes.getNamedItem('hyperlink').value; 
								
								// looks at FIELD elements
								html += "<tbody id=\"" + featureID + "tbody\" style=\"display:none;\">";
								for( var z = 0; z < features[i].childNodes[x].childNodes[y].childNodes.length; z++ )
								{
									if( features[i].childNodes[x].childNodes[y].childNodes[z].nodeName == 'FIELD' )
									{
										var fieldName = features[i].childNodes[x].childNodes[y].childNodes[z].attributes.getNamedItem('name').value;
										var fieldAlias = features[i].childNodes[x].childNodes[y].childNodes[z].attributes.getNamedItem('alias').value;
										var fieldNameHyperlink = features[i].childNodes[x].childNodes[y].childNodes[z].attributes.getNamedItem('namehyperlink').value;
										var fieldValue = features[i].childNodes[x].childNodes[y].childNodes[z].attributes.getNamedItem('value').value;
										var fieldValueHyperlink = features[i].childNodes[x].childNodes[y].childNodes[z].attributes.getNamedItem('valuehyperlink').value;
										
										// add each field to the HTML
										className = (fieldCount % 2 == 1)?"Odd":"Even";
										featureID = "feature" + x + "field" + fieldCount;

										html += "<tr>";
										
										// add field name (alias)
										if( fieldNameHyperlink != "" )
										{
											html += "<td class=\"field" + className + "\">";
											html += "<a class=\"fieldLink\" href=\"" + fieldNameHyperlink + "\" target=\"_new\">";
											html += fieldAlias + "</a></td>";
										}
										else
											html += "<td class=\"field" + className + "\">" + fieldAlias + "</td>";
										
										// add field value
										if( fieldValue != null )
										{
											// check for hyperlink!
											if( fieldValueHyperlink != "" )
											{
												html += "<td class=\"fieldValue" + className + "\">";
												html += "<a class=\"fieldLink\" href=\"" + fieldValueHyperlink + "\" target=\"_new\">";
												html += fieldValue + "</a></td>";
											}
											else
												html += "<td class=\"fieldValue" + className + "\">" + fieldValue + "</td>";
										}
										else
											html += "<td></td>";
										
										fieldCount++;
									}
								}
							}
						}
						
						html += "</tbody></tr></table>";
						resultTable.innerHTML += html;
						
					}
				}
			}
			
			if(objectIds.length > 0)
			{
				var spanHtml = "<br/><span class=\"trInfo\" style=\"font-size:11px\">Export feature data to Excel </span><a href=\"feature_csv.aspx?objectId=";
				for( var n in objectIds)
				{
					spanHtml += objectIds[n] + ",";
				}

				spanHtml += "&layer=" + layer + "&reportType=Short Report&userGroupName=" + user.userGroupName + "\" target=\"_new\" border=\"0\"><img src=\"images/excel.gif\" alt=\"Export to Excel\" border=\"0\" /></a>";
				spnResultsInfo.innerHTML += spanHtml;
			}			
			
			activateTab("tabResults");
			trResultsInfo.style.display='block';
			trDetailsInfo.style.display='none';
			divResultsList.style.display='block';
			divDetailsList.style.display='none';
			subTabResultsList.className='subTabActive';
			subTabDetailsList.className='subTabNormal';
			document.getElementById('loading').style.visibility = 'hidden';
			
			// disable loading div
			loading.style.visibility = "hidden";
			
			if( hasMore == 'True' )
		
				alert("This search returned more than the number of features allowed.  Please refine your search for more detailed results.");
		}
	}
}

function fillFieldList(layerName, elementToFill)
{	

	var dropDown = document.getElementById(elementToFill);
	
	clearFieldList(elementToFill);
	
	var layer = new Layer();
	var fieldOptions = layer.getThemedFields(layerName);
	
	if( !browser.isInternetExplorer() )
		dropDown.add( new Option("","",false,false),null );
	
	for( var i = 0; i < fieldOptions.length; i++ )
	{
		if( !browser.isInternetExplorer() )
			dropDown.add(fieldOptions[i],null);
		else
			dropDown.options[ i + 1 ] = fieldOptions[i];
	}
}

function clearFieldList(ddlToClear)
{
	var dropDown = document.getElementById(ddlToClear);
	
	while( dropDown.length > 0 )
	{
		dropDown.remove(0);
	}

}

function addTheme(layerName, field1, field2, layerBreaks)
{
	var layer;
	
	for( var i = 0; i < layerArray.length; i++ )
	{
		layer = layerArray[i];
		layer.IsVisible = false;
		document.getElementById("chk" + layer.LayerPosition).checked = false;
		
		if( layer.Name == layerName )
		{
			//alert("!!");
			//layer.isVisible = true;
			layer.isThemed = true;
			layer.themeField1 = field1;
			layer.themeField2 = field2;
			layer.breaks = layerBreaks;
			//document.getElementById("chk" + layer.LayerPosition).checked = false;
			
		}
		document.getElementById("clearThemes").style.display = "block";
	}
}

function clearThemes(refresh)
{
	var layer;
	
	for( var i = 0; i < layerArray.length; i++ )
	{
		layer = layerArray[i];
		layer.IsVisible = true;
		document.getElementById("chk" + layer.LayerPosition).checked = true;
		if(layer.isThemed)
			layer.isThemed = false;
	}
	
	document.getElementById("clearThemes").style.display = "none";
	if(refresh == true)
		map.getMap("REFRESH", 0, 0, 0, 0, true);
}

function clearSearch()
{

	var table = document.getElementById("tblFindFeature");
	var rows = table.getElementsByTagName("tr");
	
	for( var i = 0; i < rows.length - 1; i++ )
	{
		var cells = rows[i].getElementsByTagName("td");
		var nameCell = cells[0];
		var rowValue = document.getElementById("findLayer" + i);
		rowValue.value = "";
		
		if(document.getElementById("findLayer" + i + "_max") != null)
		{
			var rowValueMax = document.getElementById("findLayer" + i + "_max").value = "";
			//document.getElementById("findLayer" + i + "_max").value = "";
		}
	}
}