// JavaScript Document

var selectionColor = "rgb(0,255,252)";
//var selectAXLColor
//var mapHistory = new IHistory();
//var currentHistory = mapHistory.AXL.length -1;
var themeSite = null;
var myMap = new IMap;
var myService = new IService();
var myToc = new IToc();
myToc.map = myMap;
var resultsLayer;
var suggestLayer;
var mapLayer;
var infoLayer;
var topTable;
var toolBarLayer;
var settingsLayer;
var rubberBandLayer;
var showSideBarLayer;
var resultsOpenAndCloseImage;
var navContainerLayer;
var mailBufferLayer;
var bottomResultslayer
var linkLayer;
var loadingLayer;
var mainTableFrame
var subTableFrame
var legendLayer;
var sideMenuOpen = true;
//var myToolTips = new IToolTips() 
var myTheme = new ITheme();
//var myHyperLinks = new IHyperLink();
var myColorPicker = new IColorPicker();
	myColorPickerloadDiv = "colorPickerDiv";
var mailingResults; //access via pop up window...


//info about the page design
var mapWidth;
var mapHeight;
var resultsWidth; 
var resultsHeight; 
var legendHeight;

var zoom2PrintKey = null;
var zoom2Swiss = null

//queryString vars
var ENVELOPE = null;


//**************************************************
// Initial Lloading function to generate the map
//**************************************************
function startUp() {
	//getSearchFormContent('parcel','address');
	
	loadRequiredLayers();
	
	window.onresize= windowResize;
	screenMaximize();
	setMapHeight();
	generateSearchForm('parcelSearch','Address'); // default search view.
	designMainMapToolBar(false);
	getQueryString();
	loadActiveTab("Legend");

	loadService();

	loadMap();
	loadAllRenderers(); ///load all the renders into memory
	createLegend();
	buildZoom2List();
	buildZoom2Scale();
	positionSmallLayers();
	positionLoadLayer();
	getLayout();

	setTool(currentToolName);
	IActiveLayer.id= parcelAXLId;
	document.onmousemove=mousemove;	
}


function loadService()
{
	//size up the map area
	myService.server = server; 
	myService.service = service; 
	myService.getService();
}

 
//**************************************************
//  Get the service and Map for startup.
//**************************************************
function loadMap() {

		myMap.service = myService;
		myMap.fullextent = true;
		myMap.div = "mapContainer";
		myMap.maxScale = maxScale;
		
		
		//*******************
		//  GenCo FUNCTIONS
		//******************
		if (doComparison)
		{ 
			loadActiveTab("Results");
			doCompareSearch();
			myMap.getMap();
		}
		
		//zoom to printKey
		else if (zoom2PrintKey != null && zoom2Swiss != null)
		{
			zoomMap2PrintKey(zoom2PrintKey,zoom2Swiss,true);
		}
		
		//check to see if there is a getMap QueryString with envelope
		else if (ENVELOPE)
		{
			var envValues = new Array();
			envValues = ENVELOPE.split(":");
			var env = string2Envelope(envValues[0],envValues[1],envValues[2],envValues[3]);
			zoom2Envelope(env);
		}
		
		else if (themeSite != null)
		{
			startThemeList();
			//myTheme.themeMapLayers(themeSite)
			myTheme.activeTheme = themeSite;
			
			myMap.getMap();
			
			giveColor(document.getElementById(themeSite));
			//restoreColor(document.getElementById("County"))
			
			myToc.closeAllGroups();
			myToc.openSingleGroupByName(themeSite);
		}
		
		else
		{
			startThemeList();
			myMap.getMap();
		}		
}


function setMapHeight()
{

 var middleHeight = document.body.clientHeight - 110 - document.getElementById("endOfHeader").offsetTop;
	mapLayer.style.height = middleHeight + "px";
	resultsLayer.style.height = middleHeight - 20+ "px"
	legendLayer.style.height = middleHeight - 20+ "px"
	document.getElementById("searchLayer").style.height = middleHeight - 20+ "px"

}



//**************************************************
//function to Resize the components 
// also gets the same map but new size
//**************************************************
function windowResize() {
	positionSmallLayers();
}
	
function loadRequiredLayers()
{
	resultsOpenAndCloseImage = document.getElementById("resultsOpenAndCloseImage");
	legendLayer = document.getElementById("legendLayer");	
	rubberBandLayer = document.getElementById("rubberBandLayer");	
	resultsLayer = document.getElementById("resultsLayer");
	suggestLayer = document.getElementById("suggestLayer");
	mapLayer = document.getElementById("mapContainer");
	topTable = document.getElementById("topTable");
	infoLayer = document.getElementById("infoLayer");
	toolBarLayer = document.getElementById("toolBar");
	settingsLayer = document.getElementById("settingsLayer");
	showSideBarLayer = document.getElementById("showSideBarLayer");
	navContainerLayer = document.getElementById("navContainer");
	mainTableFrame = document.getElementById("mainTableFrame");
	subTableFrame = document.getElementById("subTableFrame");
	//bottmSideBarlayer = document.getElementById("bottmSideBarlayer");
	mailBufferLayer = document.getElementById("mailBufferLayer");
	loadingLayer = document.getElementById("loadingLayer");
	bottomResultslayer =document.getElementById("bottomResultslayer");
	linkLayer = document.getElementById("linkLayer");
}



//**************************************************
//function Design Layout for map components
//**************************************************
function getLayout() {
	mapWidth = parseInt(myMap.layer.offsetWidth);
	mapHeight = parseInt(myMap.layer.offsetHeight);
	resultsWidth = parseInt(resultsLayer.offsetWidth);
	resultsHeight = parseInt(resultsLayer.offsetHeight);
	//legendHeight = parseInt(legendLayer.offsetHeight);
}


function positionSmallLayers() {

	//position the side show and hide arrow
	showSideBarLayer.style.top = myMap.layer.offsetTop+ myMap.layer.offsetHeight  / 2 - (showSideBarLayer.offsetHeight)+ "px";
	showSideBarLayer.style.left = (myMap.layer.offsetLeft + 2)+"px";
	
	//position the zoom in and zoom out step buttons
	navContainerLayer.style.top = myMap.layer.offsetTop+myMap.layer.offsetHeight / 2 - (navContainerLayer.offsetHeight / 2) - 8 + "px";
	navContainerLayer.style.left = myMap.layer.offsetLeft+ 17+"px";
	
	//position the tool bar.
	toolBarLayer.style.top = myMap.layer.offsetTop + 5 + "px";
	toolBarLayer.style.left = (myMap.layer.offsetLeft + myMap.layer.offsetWidth) - toolBarLayer.offsetWidth - 5 + "px";
	
}


function resizeMapArea(isQuery) {
	//var resutlsWidth = parseInt(resultsLayer.style.width);
	
	if (isQuery) 
	{  
		if(resultsWidth > 0) { return; }
	}
	
	if (resultsWidth != 0) 
	{
		resultsLayer.style.width = "0px";
		legendLayer.style.width	 = "0px";
		//searchLayer.style.width	 = "0px";
		
		myMap.layer.style.width = subTableFrame.offsetWidth + "px";
		resultsWidth = parseInt(resultsLayer.offsetWidth);
		myMap.getMap();
		positionSmallLayers();
		resultsOpenAndCloseImage.src = "images/icons/sideOutArrow.gif";
		sideMenuOpen = false;
	}
	
	else {
		myMap.layer.style.width = mapWidth+ "px";
		resultsLayer.style.width = subTableFrame.offsetWidth - mapWidth+ "px"; 
		legendLayer.style.width = subTableFrame.offsetWidth - mapWidth+ "px"; 
		//searchLayer.style.width = subTableFrame.offsetWidth - mapWidth+ "px"; 
		
		resultsWidth = parseInt(resultsLayer.offsetWidth);
		myMap.getMap();
		positionSmallLayers()
		resultsOpenAndCloseImage.src = "images/icons/sideInArrow.gif";
		sideMenuOpen = true;
		}	
}



var myQuery = new IAttributeQuery();
//*************************************************************
// Performs a attribute Query agains the defined map
//*************************************************************
function doMainSearch(form,subName,Search) {
	
	//resizeMapArea(true)
	
	if (!sideMenuOpen)
	{
		resizeMapArea();
	}
	clearSuggest();
	searchObject = eval(Search);
	searchSubObject = searchObject.subSearch[subName];
	firstField = searchSubObject.firstField;
	secondField = searchSubObject.secondField;


	var whereClause = generateWhereForSearch(Search,subName);
	
	//Send the Query to the server
	
		myQuery.featureLimit = 25;
		myQuery.subFields = "#ALL#"; //subFields;						
		myQuery.layerId = searchObject.layerId;	
		myQuery.where = whereClause;
		myQuery.selectFeatures = true; 						
		myQuery.getQuery(myMap);
		
		loadSearchResults(myQuery.layerId)
}


function getNextSearch(layerId,nextAmount)
{
	resultsLayer.innerHTML = '';
	myQuery.beginrecord = nextAmount;
	myQuery.getQuery(myMap);
	loadSearchResults(layerId);
	myQuery.beginrecord = 1; // reset the begin record since its public.
}


function loadSearchResults(layerId)
{
	var firstResult = '';
	var secondResult ='';
	var resultsHTML = '';
 
	//Alert if not results found when not suggesting.
	if (RESPONSE.RESULTS.length==0) {  alert("No Results Found!");  return; }
	else {	loadActiveTab("Results")  }
 
	//display all the results.
	for (i in RESPONSE.RESULTS)
	{
		
		var firstResult = RESPONSE.RESULTS[i].FIELDS[firstField];
		if (!firstResult)
		{
			firstResult = '[?]';
		}
		if(secondField)
		{
			var secondResult = RESPONSE.RESULTS[i].FIELDS[secondField];
			if (!secondResult) { secondResult = '[?]'; }
		}	
		var envelope = RESPONSE.RESULTS[i].ENVELOPE;
		
		//get the layer index in RESPONSE.LAYER to find the obectID
		layerIndex  = findLayerIndex(searchObject.layerId)
		objectIDFieldName =findObjectIdFieldName(layerIndex)	//getObjectId field name -99 TYPE
		objectId = RESPONSE.RESULTS[i].FIELDS[objectIDFieldName];
		
		results = firstResult + " " + secondResult;
		resultsHTML += designResultsTable(results,envelope,objectId,layerId);
	}
		resultsLayer.innerHTML = resultsHTML;
		
		
		//populate the additionalInfo Link with the LINK*!
		populateAdditionalInfo(layerId)
		
		
		//Grow and get Attributes if results is = 1
		if (RESPONSE.RESULTS.length == 1)
		{
			showAttributes(objectId,myQuery.layerId)
		}
	
	// add a link for the next results.	
	
	var bottomHTML ='<div align=center id="resultOptions" align="center" class="largeBlackFont"> ';
	var next25 = myQuery.beginrecord + 25;
	var previous25 = parseInt(myQuery.beginrecord) - 25;
	showLayer("bottomResultslayer");
	
	//check to see if the data is using the parcel table.
	// if so, allow to download mailing list.
	if (myQuery.layerId == parcelAXLId)
	{
		//bottomHTML +=' <a href="javascript: void(0);" onClick="getSearchMail('+layerId+',\'myQuery\');  return false;"><img src="'+iconPath+'/mailEnvelope.gif" border=0>Download </a> &nbsp;&nbsp;&nbsp;'
	}
	
	if (previous25 > 0)
	{
		bottomHTML +=' <a href="javascript: void(0);" onClick="getNextSearch('+layerId+','+previous25+');  return false;">Previous 25 </a> &nbsp;&nbsp;&nbsp;'
	}
	
	if (RESPONSE.COUNT == myQuery.featureLimit)
	{
		bottomHTML +=' <a href="javascript: void(0);" onClick="getNextSearch('+layerId+','+next25+');  return false;">Next 25</a> ';
	}
	bottomHTML +='</div>';
	bottomResultslayer.innerHTML = bottomHTML;
}



//*************************************************************
// Function to design the results table
//*************************************************************
function designResultsTable(result,ev,objectId,layerId) {
	var tableWidth =resultsLayer.offsetWidth - 50 + "px";
	var envelopeString = ev.minx+','+ev.miny+','+ev.maxx+','+ev.maxy;
	var attributeDivName = "attributes"+objectId;
	
	//Get the enter of the result so Pictometry work.
	var pictoXY = getMapCentroid(ev);
	
	content ='<table border="0" width="'+tableWidth+'" id="resultsTable'+objectId+'" class="resultsTable" align=center ';
	content +='style= cellspacing="0" cellpadding="1">\n';
	content +='<tr>\n';
	content +='<td>\n';
	content +='<span  align="left" class="largeGrayBoldFont">';
	content +=' &bull; ';
	content += result +'<span>\n';
	
	content +='</td>\n';
	content +='</tr>\n';
	content +='<tr>\n';
	content +='<td>\n';
	
	content +='<table class="mediumBlackFont" width="'+tableWidth+'" border="0" cellspacing="0" cellpadding="0">\n';
	content +='<tr>';
	
	//content +='<td>';
	//content +='<img src="'+iconPath+'/closeX.gif" onClick="hideLayer(\'legendLayer\');" style="cursor:pointer">';
	//content +='</td>';	
	content +='<td>\n';
	content +='<a href="javascript: void(0);" onClick="zoom2Selected('+ envelopeString +',\'myMap\'); return false;">Zoom</a></td>\n';
	
	content +='<td><a href="javascript: void(0);" onClick="showAttributes('+objectId+','+layerId+'); return false;">Attributes</a>\n';
	
	content += '</td>\n';
	//**********************************************
	//Pictometry Link
	//content += '<td><a href="javascript: void(0);" onClick="doOnCorPicto(\''+pictoXY+'\'); return false;">Pictometry<a/></td>\n';
	//**********************************************
	
	//&swis=180200&sbl=0840730001040000
	//**********************************************
	//Pro Server Link
	//content += '<td><a href="javascript: void(0);" onClick="loadOARS('+objectId+','+layerId+'); return false;">Additional Info<a/></td>\n';
	//**********************************************
	
	
	//Additional Information Link (ASP.NET Pages)
	content += '<td><div id="additionalInfo'+objectId+'"></div></td>\n';
	
	content += '<td>';
	content += '<a href="javascript: void(0);" onClick="showReport(\''+layerId+'\','+objectId+');">\n'; 
	content += '<img src="'+iconPath+'/report.gif" border=0 title="Display Report"></a>\n';
	content += '</td>';
	
	
	content += '<td>';
	//content += '<a href="javascript: void(0);" onClick="selectPolygon(\''+layerId+'\','+objectId+','+envelopeString+'); startMail('+objectId+','+layerId+'); return false;">\n'; 
	//content += '<img src="'+iconPath+'/mailEnvelope.gif" border=0 title="Create A Mailing List Around This Parcel"></a>\n';
	content += '</td><td>';
	content += '<a href="javascript: void(0);" onClick="showMiniMapLayer(\'miniMapLayerBoundary'+objectId+'\','+ envelopeString +','+objectId+',\''+layerId+'\'); return false;">';
	content += '<img src="'+iconPath+'/popOutMap.gif" border=0 title="Show A Small Map Of This Area In Floating Window"></a></td>\n';
	content += '</tr>\n';
	content += '</table>\n';
	
	content +='</td>\n';
	content +='</tr>\n';
	
	//create a span tag for minimze and maximize images.
	var upDownSpan 	= '<div id="upDownSpan'+objectId+'" align="right" style="visibility:hidden;">';
		upDownSpan += '</div>';

	//Show the attribute Information
	content +='<tr >\n';
	content +='<td valign="top" id="'+objectId+'" style="height:0px;">\n';
	
	content +='<div id="'+attributeDivName+'" style="width: 100%; height: 1px; overflow: auto;">\n';
	content +='</div>';
	content +=upDownSpan;
	content +='</tr></td></table>\n';
	
	miniMapName  = 'miniMapLayer'+objectId;
	
	return content;
}

//*************************************************************
// Function to zoom to selected
//*************************************************************
function zoom2Selected(minx,miny,maxx,maxy,map) {
	map = eval(map);
	
	tempEnv = string2ResizedEnvelope(minx,miny,maxx,maxy,500);
	map.envelope = tempEnv;
	map.fullextent = false;
	
	//Calulate the center of the object and add an acetate layer to it
	var coords = getMapCentroid(tempEnv);
	var myColor = "219,89,89";
	addPointAcetateXMLToMap(coords,myColor,16,map,true);
	map.getMap();
}

//*************************************************************
// Function to show the attributes in results pane.
//*************************************************************
function showAttributes(objectId,layerId) {
	
	attributeLayer = document.getElementById(objectId);
	attributeSpanName = "attributes" + objectId;
	resultsSpan = document.getElementById(attributeSpanName);
	upDownSpanName = "upDownSpan"+objectId;
	upDownSpan = document.getElementById(upDownSpanName);
	resultsTable = document.getElementById("resultsTable"+objectId);
	var resultHeight = 300;

	var upDownHTML ='';
	upDownHTML += '<a href="javascript: void(0);" onClick="growElement(\'up\','+objectId+',1); growElement(\'up\',\''+attributeSpanName+'\',1); hideLayer(\''+upDownSpanName+'\'); return false;">\n';
	upDownHTML += '<img src="'+iconPath+'/minusNode.gif" border=0 title="Minimize"></a>&nbsp;&nbsp;';
	upDownHTML += '<a href="javascript: void(0);" onClick="growElement(\'boost\','+objectId+'); growElement(\'boost\',\''+attributeSpanName+'\'); return false;">';
	upDownHTML += '<img src="'+iconPath+'/plusNode.gif" border=0 title="Boost Size"></a>&nbsp;&nbsp;';
	upDownSpan.innerHTML = upDownHTML;
	upDownSpan.style.visibility ='visible';
	
	//check to see if the user has looked at the attributes yet.
	if (resultsSpan.innerHTML.length <= 1) {
		var results = ''; 
		
		var attributeTable = buildResultsTable(objectId,layerId);
		resultsSpan.innerHTML = attributeTable;
		resultsTable.className = "resultsTableViewed";
	}
	
	var attributeTableName = document.getElementById('attributeTable'+objectId);
	var attributeTableHeight = attributeTableName.offsetHeight;
	
	//grow the attributeDiv (span) to the size required unless bugger than 300px
	if (attributeTableHeight < resultHeight) { resultHeight = parseInt(attributeTableHeight) + 10 }
	
	//grow
	growElement("down",objectId,resultHeight);
	growElement("down",attributeSpanName,resultHeight);
	//resultsTable.scrollIntoView(true); // kind cool scrool2view method.

}


//*************************************************************
// Function to show a mini map of the selected in div
//*************************************************************

var mouseX;
var mouseY;
var layerz;
var borderLayer;
var show = false;
ie4 = (document.all)? true:false
var miniMap = new IMap();

function showMiniMapLayer(name,minx,miny,maxx,maxy,objectId,layerId) {

	tempEnv = string2ResizedEnvelope(minx,miny,maxx,maxy,100);
	
	//get the object ID
	//get the layer index in RESPONSE.LAYER to find the obectID
	layerIndex  = findLayerIndex(layerId);
	objectIDFieldName =findObjectIdFieldName(layerIndex);	//getObjectId field name -99 TYPE

	//set point proerties.
	var miniPointRenderer = new IPointRenderer();
		miniPointRenderer.transparency = 1.0;
		miniPointRenderer.color = "236,65,65";
		miniPointRenderer.type = "cross";
		miniPointRenderer.width = 18;
		miniPointRenderer.outline = miniPointRenderer.color;
	
	//create the point
	var miniPointSelection = new IPointSelection();
		miniPointSelection.layerId =layerId;
		miniPointSelection.where = objectIDFieldName+"="+objectId;
		miniPointSelection.selectionProperties = miniPointRenderer;
	
	miniMapName = "miniMapLayer"+objectId;
	
	miniMap.service = myService;
	miniMap.envelope = tempEnv;
	miniMap.fullextent = false;
	miniMap.isMiniMap = true;
	miniMap.showScaleBar = false;
	miniMap.div = miniMapName;
	miniMap.layerName = "miniMapLayerInsideLayer"+objectId;
	miniMap.imageName = "miniMapImage" +objectId +layerId;
	
	//miniMap.pointSelection = miniPointSelection //apply a point on the map via XMl
	
	//Create the Div for the mini Map.
	var mmName = miniMap.div;
	
	isDivAlready = document.getElementById(mmName);
	if (isDivAlready)  { killLayer(mmName); }
	
	createDiv(miniMap.div,mouseY,mouseX,150,150);
	miniMapBorder = document.getElementById(miniMap.div);
	miniMapBorder.className = "miniMapClass";
	miniMapBorder.onmousedown= function() { startMove(mmName); }
	
	var closeLink  = '<span class="mediumBlackFont">';
		closeLink +='<center>&nbsp;&nbsp;[ <a href="javascript: void(0);" onClick="killLayer(\''+miniMapName+'\'); return false;">close</a> ]</center></span>';	 
	
	miniMapBorder.innerHTML = closeLink;
	
	//Calulate the center of the object and add an acetate layer to it
	var coords = getMapCentroid(tempEnv);
	var myColor = "219,89,89";
	addPointAcetateXMLToMap(coords,myColor,12,miniMap);

	//Get the mini Map.
	miniMap.getMap();
	
	miniMapBorder.style.padding = "5px 15px 20px 15px"
	miniMapBorder.style.cursor = "move";

}

//custom axl to be on an accetate layer.
function addPointAcetateXMLToMap(coords,color,width,map,temp) {
	
var axlXML = '<LAYER type="acetate" name="POINT MARKER" visible="true">\n';
	axlXML +='<OBJECT units="database">\n';
	axlXML +='<POINT coords="'+coords+'">\n';
	axlXML += '<SIMPLEMARKERSYMBOL tansparency="0.5" color="'+color+'" type="acetate" width="'+width+'" overlap="true" outline="0,0,0" antialiasing="true" />\n';
	axlXML +='</POINT>\n';
	axlXML +='</OBJECT>\n';
	axlXML += '</LAYER>\n';
	
	if (temp)	{
		map.tempXML = axlXML;
	} else	{	
		map.appendXML = axlXML;
	}
}

//*******************************************************
//Start the mail notifivation process
//*******************************************************
var tempBufLayerId;
var tempBufObjectId;

function startMail(objectId,layerId) {
	
	var mapScreenCenter = getScreenCentroid(myMap);
	var mapXYcentroid = mapScreenCenter.split(' ');
	
	mailBufferLayer.style.top = mapXYcentroid[1] + "px";
	mailBufferLayer.style.left = mapXYcentroid[0] + "px";
	showLayer('mailBufferLayer');
	myMailMerge.objectId = objectId;
	tempBufLayerId = layerId;
	tempBufObjectId = objectId;
}


function doImageBuffer() {
	
	var bufferDistance = document.getElementById("bufferDistance").value;
	if (parseFloat(bufferDistance) >= 0) 
	{ 
		bufferMail(myMap,bufferDistance,'feet');
	}
	else {	alert("Invalid Number");  }	
}


function bufferMail(map,distance,units) {
		
		//get the object ID
		//get the layer index in RESPONSE.LAYER to find the obectID
		layerIndex  = findLayerIndex(tempBufLayerId);
		objectIDFieldName =findObjectIdFieldName(layerIndex);	//getObjectId field name -99 TYPE
		
		
	var myImageBuffer = new IBuffer();
		myImageBuffer.bufferLayerId = tempBufLayerId;
		myImageBuffer.distance = distance;
		myImageBuffer.units = "feet";
		
		myImageBuffer.where =objectIDFieldName+'='+myMailMerge.objectId;
		myMap.imageBuffer = myImageBuffer;
		myMap.getMap();
}


function downloadBuffer()
{
	var myBufferQuery = new IBufferQuery();
	var bufferDistance = document.getElementById("bufferDistance").value;

	//get the object ID
	//get the layer index in RESPONSE.LAYER to find the obectID
	layerIndex  = findLayerIndex(tempBufLayerId);
	objectIDFieldName =findObjectIdFieldName(layerIndex);	//getObjectId field name -99 TYPE

if (parseFloat(bufferDistance) >= 0) { 	}
	else {	alert("Invalid Number"); return; }	

	myBufferQuery.featureLimit = 2000;		//integer
	myBufferQuery.beginrecord = 1;		//integer
	myBufferQuery.units = "feet";
	myBufferQuery.layerId = tempBufLayerId ;				//integer
	myBufferQuery.targetLayerId= myMailMerge.layerId;
	myBufferQuery.subFields = myMailMerge.fields;			//string (seperate by space)
	myBufferQuery.where = objectIDFieldName+'= '+tempBufObjectId;
	myBufferQuery.distance = bufferDistance;
	
	//use a new object to hold temp Results.
	myBufferQuery.useResults2 = true;
	
	//Get the attributes.
	myBufferQuery.getBufferAttributes(myMap);

	formatMail();
}

function getSearchMail(id,refQueryObj)
{
	refObj = eval(refQueryObj);
	var mySearchedMail = refObj
		mySearchedMail.featureLimit = 2000;
		mySearchedMail.beginrecord = 1;
		mySearchedMail.useResults2 = true;
		mySearchedMail.subFields = myMailMerge.fields;
		mySearchedMail.getQuery(myMap);
		formatMail()
}


function formatMail()
{
//put the results into a public var so asp.net can access it later
	var mailResults = new Array();
	var mailHeaders = '';
	var mailFields = new Array();
		mailFields = myMailMerge.fields.split(" ");

	mailingResults = '';	//clear area
		
	//what will the delimitor be fopr all the mail parts.	
	
	var fieldNameIndex;
	
	for (i in RESPONSE.RESULTS2)
	{
		
		//get the results.
		mailResults[i] ='';
		for (d in RESPONSE.RESULTS2[i].FIELDS)
		{
			//place the value into a sorted part of the array.
			mailValue = RESPONSE.RESULTS2[i].FIELDS[d];		
			mailValue = mailValue.replace(/\,/g, " "); //remove any commas
			mailResults[i] += mailValue + mailSeperator;
		}
		
	
	}
	
	//get the headers.
	for (d in RESPONSE.RESULTS2[RESPONSE.RESULTS2.length-1].FIELDS)
	{
		d  = convertSDEName(d);
		mailHeaders +=	d + mailSeperator;
	}
	mailHeaders = mailHeaders.substr(0,mailHeaders.length-1)
	if (myMailMerge.state != "")
		mailHeaders +=",STATE";
		else
		mailHeaders +="";
		
	
	var sortedMailResults = '';
	// add into public var
	var tempResults = '';
	for (a in mailResults)
	{
		//trim the last "separator" off the end.
		mailResults[a] = mailResults[a].substr(0,mailResults[a].length-1)
		
		//append to the textare now!
		if (mailResults[a].length > 1)  //make sure there is a value.
		{
			if (myMailMerge.state != "")
				tempResults += mailResults[a] +mailSeperator+myMailMerge.state+ "\n";
			else
				tempResults += mailResults[a] +"\n";
		}
	}
	
	window.open(mailMergeFilePath+"/downloadClick.aspx","mailDownloadPage", "height=500,width=800,status=yes,toolbar=no,menubar=yes,location=no,scrollbars =yes");
	
	mailingResults += mailHeaders + "\n";
	mailingResults += tempResults;	
}



function loadActiveTab(tabName)
{
	swapTab(tabName);
	var activeTitle = document.getElementById("activeTitle");
	//var bottmLayer = document.getElementById("bottmSideBarlayer");
	switch (tabName)
	{
		case "Legend":
		{
			var layerName = "legendLayer";
			hideTabLayers(layerName);
			blockLayer(layerName);
			//activeTitle.innerHTML = "";
			unBlockLayer("bottomSearchlayer");
			unBlockLayer("bottomResultslayer");
			blockLayer("bottomLegendlayer");
			break;
		}
		
		case "Results":
		{
			var layerName = "resultsLayer";
			hideTabLayers(layerName);
			blockLayer(layerName);
			unBlockLayer("bottomSearchlayer");
			unBlockLayer("bottomLegendlayer");
			blockLayer("bottomResultslayer")
			
			d = document.getElementById(layerName);
			if (d.innerHTML == "") {    d.innerHTML = "<center>Currently No Results. </center>" }
			
			break;	
		}
		
		case "Search":
		{
			var layerName = "searchLayer";
			hideTabLayers(layerName);
			blockLayer(layerName);
			unBlockLayer("bottomResultslayer");
			unBlockLayer("bottomLegendlayer");
			blockLayer("bottomSearchlayer");
			break;	
		}
	}
}

function hideTabLayers(except)
{	
	var layersToHide = new Array();
		layersToHide[0] = "legendLayer";
		layersToHide[1] = "resultsLayer";
		layersToHide[2] = "searchLayer";

	for (var i in layersToHide)
	{
		unBlockLayer(layersToHide[i]);
	}
}



//Loads the tabe with the current CSS to make it look active to the user.
function swapTab(tabName) {
	var sideTabs = document.getElementsByName("sideTabs");
	
	for (var i=0; i <= sideTabs.length-1; i++)
	{
		if (sideTabs[i].id == "current") {
			sideTabs[i].id = "";
		}
	}
	
	for (var i=0; i <= sideTabs.length-1; i++)
	{
		if (sideTabs[i].title == tabName) {
			sideTabs[i].id = "current";
		}
	}
}



//******************************************************
//create the legend HTML
//******************************************************
function createLegend()
{
	myToc.cssClass 			= "largeBlackFont";
	myToc.plusNodeImage 	= iconPath + "/plusNode.gif";
	myToc.minusNodeImage 	= iconPath + "/minusNode.gif";
	myToc.childNodeImage	= iconPath + "/childNode.gif";
	myToc.endChildNodeImage = iconPath + "/endChildNode.gif";
	myToc.noNode			= iconPath +"/noNode.gif";
	
	buildLegend();

	myToc.drawLegend("legendLayer");

	myToc.drawLegendUpdateButton("bottomLegendlayer");
	
}


var printTitle = '';
//******************************************************
//create the print page
//******************************************************
function showPrintLayout()
{
	
var printWindow = open(appPath+'/printPage.htm', "PrintPageWindow", "width=700, height=800, toolbar=yes, location=yes, directories=yes, status=yes, menubar=yes, scrollbars=yes, copyhistory=yes, resizable=yes ");
	printWindow.focus();
		
	printTitle = document.getElementById("printTitleTextBox").value;
}



function loadPrint(dialogBoxName)
{
	showLayer(dialogBoxName);
	
	var printTitleTextBox = document.getElementById("printTitleTextBox");
		printTitleTextBox.value = countyName;
		printTitleTextBox.focus();
	
	var printBox = document.getElementById(dialogBoxName);
		putInLowerLeft(printBox);
}




function putInLowerLeft(obj)
{
	obj.style.top = myMap.layer.offsetTop + myMap.layer.offsetHeight - obj.offsetHeight - 5 + "px";
	obj.style.left = myMap.layer.offsetLeft + myMap.layer.offsetWidth - obj.offsetWidth - 5 + "px";	
}


function startThemeList()
{
	buildThemes();
}


function getLinkURL()
{
	var url = new Array();
	var loc = document.location.toString();
	url = loc.split("?");
	url[0] +="?ENVELOPE="+myMap.envelope.minx +":"+myMap.envelope.miny +":"+myMap.envelope.maxx +":"+myMap.envelope.maxy;
	return url[0];
}


function mailLink()
{
	var url = getLinkURL();
	document.location="mailto:?Subject=Map Link&body=Below is a link to the map I was viewing.%0d%0d" + url;	
}


var convertCodes = new Array();
convertCodes.push(4326);
convertCodes.push(32618);

function getLatLong()
{
	for (i in convertCodes)
	{
	var code= convertCodes[i];
	var project = new IProject();
		project.from = coordSystem;
		project.to = code;
		project.points = IMouse.coordX+' '+IMouse.coordY;
		project.getProject(showProjectedCoords);
	}
		var x = addCommasAndRound(IMouse.coordX,2);
		var y = addCommasAndRound(IMouse.coordY,2);
		document.getElementById("latCoord").innerHTML = "Calculating...";
		document.getElementById("longCoord").innerHTML = "";
		document.getElementById("UTMXCoord").innerHTML = "Calculating...";;
		document.getElementById("UTMYCoord").innerHTML = "";
		document.getElementById("SPXCoord").innerHTML = x;
		document.getElementById("SPYCoord").innerHTML =y;
		positionCoordinateConvertLayer();
}

function showProjectedCoords(coords,code)
{
	var XY = coords.split(" ");
	if (code == 4326)
	{	
		var x = addCommasAndRound( XY[0],6);
		var y = addCommasAndRound( XY[1],6);
		document.getElementById("latCoord").innerHTML = x;
		document.getElementById("longCoord").innerHTML = y;
	}
	if (code == 32618)
	{
		var x = addCommasAndRound(XY[0],2);
		var y = addCommasAndRound(XY[1],2);
		document.getElementById("UTMXCoord").innerHTML = x;
		document.getElementById("UTMYCoord").innerHTML = y;
	}
}

function clearCoordinateConvertLayer()
{
	document.getElementById("UTMXCoord").innerHTML = "";
	document.getElementById("UTMYCoord").innerHTML = "";
	document.getElementById("latCoord").innerHTML = "";
	document.getElementById("longCoord").innerHTML = "";
	document.getElementById("SPXCoord").innerHTML = "";
	document.getElementById("SPYCoord").innerHTML ="";
}


function positionCoordinateConvertLayer()
{
	var coordConvertLayer = document.getElementById("coordConvertLayer");
	if (coordConvertLayer.style.visibility != "visible");
	{
		showLayer("coordConvertLayer");

		coordConvertLayer.style.top = myMap.layer.offsetTop + 5+ "px";
		coordConvertLayer.style.left = myMap.layer.offsetLeft + myMap.layer.offsetWidth - coordConvertLayer.offsetWidth - 5 + "px";
	}
}

//Function to get the report showing the attributes
function showReport(layerID, objectID)
{
	var url = 'report.htm?QSlayerID='+layerID+'&QSobjectID='+objectID;
	var u = window.open(url)
}


