// JavaScript Document
var x; //used for setting the timmer on animated html
var htmlElement;
var mouseOverColor = '#B7D8ED';
var mouseOutColor = '#F7FBFB';

//***********************************************************************
// Function to convert a string of minx,miny,maxx,maxy to ENVELOPE Object
//***********************************************************************
// 	Syntax/Examples:
//	string2ResizedEnvelope(Envelope String:String , Zoom Out offset difference:Integer)
//	objEnvelope = string2ResizedEnvelope(minx,miny,maxx,maxy,100);
//***********************************************************************
function string2ResizedEnvelope(minx,miny,maxx,maxy,offset) {
	var tempEnv = new tempEnvelope()
		if (!offset) { offset = 100; }
	
		tempEnv.minx = minx - offset;
		tempEnv.miny = miny + offset;
		tempEnv.maxx = maxx + offset;
		tempEnv.maxy = maxy - offset;
		return tempEnv;
}


function string2Envelope(minx,miny,maxx,maxy) {
	var tempEnv = new tempEnvelope()
		tempEnv.minx = minx;
		tempEnv.miny = miny;
		tempEnv.maxx = maxx;
		tempEnv.maxy = maxy;
		return tempEnv;
}



function resizeEnvelope(env,offset) {
	var tempEnv = new tempEnvelope()
		if (!offset) { offset = 100; }
	
		tempEnv.minx = parseFloat(env.minx) - offset;
		tempEnv.miny = parseFloat(env.miny) + offset;
		tempEnv.maxx = parseFloat(env.maxx) + offset;
		tempEnv.maxy = parseFloat(env.maxy) - offset;
		return tempEnv;
}



function zoomOutEnvelopeOneStep(env,amount)
{
	var value = amount;
	var dx = parseFloat(env.maxx) - parseFloat(env.minx);
	var dy = parseFloat(env.maxy) - parseFloat(env.miny);

	var cx = (parseFloat(env.maxx) + parseFloat(env.minx))/2.0;
	var cy = (parseFloat(env.maxy) + parseFloat(env.miny))/2.0;

	var dx1 = 0.5 * value * dx;
	var dy1 = 0.5 * value * dy;

	var tempEnv = new IEnvelope();
		tempEnv.minx = cx - dx1;
		tempEnv.miny = cy - dy1;
		tempEnv.maxx = cx + dx1;
		tempEnv.maxy = cy + dy1;
		return tempEnv;	
}	

//***********************************************************************
//figure out the estimated envelope by looking for high a low values
// This function will calculate the new extent of a map based on May Envelopes.
// it returns an envelope. (1 only)
//***********************************************************************
function estimateEnvelope(arrayOfEnvelopes) {
	
	var eMaxx = 0;
	var eMaxy = 0;
	var eMinx = 0;
	var eMiny = 0;
	var MINX = '';
	var MAXX = '';
	var MINY = '';
	var MAXY = '';
	
	for (x in arrayOfEnvelopes) {
		var enc = arrayOfEnvelopes[x];
		
		if (x == 0) {
			var eMaxx = enc.maxx
			var eMaxy = enc.maxy
			var eMinx = enc.minx
			var eMiny = enc.miny		
		}
		
		
		MINX +=enc.minx +'\n';
		MAXX +=enc.maxx +'\n';
		MINY +=enc.miny +'\n';
		MAXY +=enc.maxy +'\n';
		
		
		if (eMaxx < parseFloat(enc.maxx)) { eMaxx = enc.maxx }
		if (eMaxy < parseFloat(enc.maxy)) { eMaxy = enc.maxy }
		if (eMinx > parseFloat(enc.minx)) { eMinx = enc.minx }
		if (eMiny > parseFloat(enc.miny)) { eMiny = enc.miny }
	}

	

	var estimatedEnv = new tempEnvelope()
		estimatedEnv.minx = eMinx;
		estimatedEnv.miny = eMiny;
		estimatedEnv.maxx = eMaxx;
		estimatedEnv.maxy = eMaxy;
		return estimatedEnv;	
		

		
}






function getQueryString()
{
//*********************************************************************
// Function to get the QueryString and return the values are variables
// http://mySite.com/coolIMS/default.htm?debug=true
//*********************************************************************
var search = location.search;
search = search.replace(/\?/,'');
var searchAttributes = search.split('&');

if (location.search != "")  {
	for(var num=0; num<searchAttributes.length; num++)
	{
		var items = searchAttributes[num].split('=');
		eval(""+items[0]+" = '"+items[1]+"';");
	}
}

}



//***********************************************************************
// Function(s) to animate a tables size ( ANIMATION DOWN)
//***********************************************************************
// 	Syntax/Examples:
//	
//	
//***********************************************************************

function growElement(type,elementNameArray,size) {
	clearTimeout(x); 
	
	//for (var i in elementNameArray) {
		var elementName = elementNameArray;
		if (type=="boost") { 
			size=parseInt(document.getElementById(elementName).offsetHeight) + 100;  
			x = setInterval("elementZoomDown(\'"+elementName+"\',"+size+")",3);
			}
			
		else if (type == "down") { x = setInterval("elementZoomDown(\'"+elementName+"\',"+size+")",3); } 
		else {	x = setInterval("elementZoomUp(\'"+elementName+"\',"+size+")",3);	}
	//}
}





function elementZoomDown(elementName,size) 
{
	
	var object = document.getElementById(elementName);
	if (object)
	{
		var elementHeight = object.offsetHeight;
		elementHeight = parseInt(elementHeight) + 30;
		object.style.height = elementHeight + "px";
	}
	
	//stop the grow
	if (elementHeight >= size) { 
		clearTimeout(x); 
		object.style.height = size + "px";
		return;
	}

}

function elementZoomUp(elementNameArray,size) {
		var elementName = elementNameArray;
		var object = document.getElementById(elementName);
		if (object)
		{
			var elementHeight = object.offsetHeight;
			elementHeight = parseInt(elementHeight) - 30;
		}
		
		
		//stop the grow
		if (elementHeight <= size) { 
			object.style.height = size + "px";
			clearTimeout(x);
			return;
		}
		else {
			object.style.height = elementHeight + "px";
		}

}


function positionColorPicker(colorPicker)
{
	var	divStyle = document.getElementById(colorPicker.loadDiv).style;
	divStyle.top = mouseY + "px";
	divStyle.left = mouseX + "px";
}

function findCssClassByName(className,cssTagIndex)
{
	var cssRule;
	var cssObj = null;
	if (ie4)
	{
		cssRule = document.styleSheets[cssTagIndex].rules
	}
	else
	{
		cssRule = document.styleSheets[cssTagIndex].cssRules;
	}
	
	for (var i in cssRule)
	{
		if (cssRule[i].selectorText == className)
		{
			cssObj = cssRule[i]
		}
		
	}
	
	if (cssObj == null) { alert ("cant find class name, example (.tables OR #tables are valid)"); }
	return cssObj;	
}


function parseRGB(rgb)
{
	var firstSplit = rgb.split("\(");
	var secondSplit = firstSplit[1].split("\)");
	var newRGB = secondSplit[0];
	//alert(newRGB);
	return newRGB;
}




function setSelectColor()
{
	rubberBandLayer.style.backgroundColor=document.getElementById("colorSelection").style.backgroundColor;	
}
//*************************************************************
// Build SetActive Layer List
//*************************************************************
var activeLayerList;


function showActiveLayerList(showColorPicker)
{

	var activeLayerHTML =''
	activeLayerHTML  ='<table cellspacing="1" cellpadding="0" class="settingsFont" border=0><tr><td> &nbsp;Select Active Layer:  ';
	activeLayerHTML +='<select class="settingsForms" style="font-size:13px" id="activeLayerList" name="select" onChange="setActiveLayer(this.value)">';
	activeLayerHTML +='</select>';
	activeLayerHTML +='</td>';
	
	if (showColorPicker)
	{
		activeLayerHTML +='<td>&nbsp;&nbsp;&nbsp;Selection Color: &nbsp;</td>';
		activeLayerHTML +='<td><table border="0" cellspacing="0" cellpadding="0" style="border:1px #000000 solid; background:'+selectionColor+'"><tr ><td id="colorSelection" width="10" height="10" style="cursor:pointer;" onClick=" myColorPicker.load(this); positionColorPicker(myColorPicker);"></td></tr></table></td>';
	}
	
	activeLayerHTML +='</tr></table>';
	
	settingsLayer.innerHTML = activeLayerHTML;
	
	activeLayerList = document.getElementById("activeLayerList");
	var layerList =RESPONSE.LAYER;	
	var layerNames = new Array(); // used for sorting.
	//var layerObjects = new Array(); // holds the new objects.
	
	for(var i in layerList) 
	{
		layerNames.push(layerList[i].name);	
		//layerObjects.push(layerList[i]);
	}
	
	var bgListColor = "#FFF";
	for (var x in layerNames.sort())
	{
		var i = findLayerIndexByName(layerNames[x])
		
		optionText = layerList[i].name;
		optionText= cleanInValidChars(optionText) //Clean up and & symb.
		optionValue = layerList[i].id	
		
		activeLayerList.options[x]=new Option(optionText, optionValue, false, false)
		
		
		odd = parseInt(x) % 2;
		if (odd ==1) { bgListColor = "#F3F3ED"; }
		else { bgListColor = "#FFF" }
		
		activeLayerList.options[x].style.background = bgListColor;
		
		//set the selected value. (IE 6 issue with the Option Object, had to be done old school)
		if (optionValue == parseInt(IActiveLayer.id))
		{  
			activeLayerList.options.selectedIndex =x
		}
		
		if (!IActiveLayer.id == null)
		{
			
			setActiveLayer(layerList[i].id)
		}
	}
	
	
	
	
	
}



function setActiveLayer(layerId) {

	var layerList =RESPONSE.LAYER;
	
	//find the id and set as active layer
	for(var i in layerList)
	{
		if (layerList[i].id == layerId)
		{
			IActiveLayer.displayName = layerList[i].name;
			IActiveLayer.id = layerList[i].id;
			IActiveLayer.type = layerList[i].type;
			IActiveLayer.visible = layerList[i].visible;
		}
	}
}


//*************************************************************
// Builts a Results Table, returns a HTML Table.
//*************************************************************
function buildResultsTable(objectId,layerId) {
	
	var useAliasNames = false;
	var resultsTable;
	var className;
	var counter = 0;
	var aliasArray = new Array();
	var aliasAssArray = new Array();
	var tempAliasSplit;
	var useFieldNameFilter = false;
	var filterArray = new Array();
	
	
	//build filter info.
	//has it be defined?
	if (aliasNames[layerId]) { useAliasNames = true; }
	
	if(useAliasNames) 
	{
		aliasArray = aliasNames[layerId].split(aliasSeparator);
		for (var x in aliasArray)
		{
			tempAliasSplit = aliasArray[x].split(":");
			aliasAssArray[tempAliasSplit[0]] = tempAliasSplit[1];
		}
	}
		

	//check to see if this field should be visiable or not.
	if (visibleNames[layerId]) { useFieldNameFilter = true; }
	
	
	//take the filtered names and put them into an array.
	if (useFieldNameFilter)
	{
		filterArray = visibleNames[layerId].split(visibleSeparator)
	}

	
	resultsTable  = '<table id="attributeTable'+objectId+'"  width="100%" border="0" cellspacing="0" cellpadding="0">\n';
	
	
	for (var i in RESPONSE.RESULTS) {
	
	//get the layer index in RESPONSE.LAYER to find the obectID
	layerIndex  = findLayerIndex(layerId)
	//getObjectId field name -99 TYPE
	objectIDFieldName =findObjectIdFieldName(layerIndex)
	
	var objId = RESPONSE.RESULTS[i].FIELDS[objectIDFieldName];
	if (objectId == objId) 
	{	
		counter = 0;
		
		//Loop through the found object and get its values/field names
		for (var y in RESPONSE.RESULTS[i].FIELDS) {
			
		var showThisField = false;	
		fieldName =y;
		
		//convert the SDE names to normal
		fieldName = convertSDEName(fieldName)
		fieldValue =RESPONSE.RESULTS[i].FIELDS[y]
		
	
		//loop through the fieldNameFilter and find if true.
		for (var m in filterArray)
		{
			if (filterArray[m] == fieldName)
			{
				showThisField = true;
			}
		}
	
	
		//give the field name an alias name
		if(useAliasNames && aliasAssArray[fieldName]) 
		{
			fieldName = aliasAssArray[fieldName];
		}
		
		
	if (showThisField || !visibleNames[layerId])
	{
			counter++;
			odd = counter % 2;
			if (odd ==1) { className = "attributeOddRows"; }
			else { className = "attributeEvenRows" }
			
			/*
			var hyperLinkOpen = '';
			var hyperLinkClose = '';
			
			
			//OnCor Function - HyperLink Print Key;
			if (fieldName == parcelPrintKeyField && layerId== parcelAXLId)
			{ 
				hyperLinkOpen = '<a href="javascript: void(0);" OnClick="setPrintKeySessionVar(\''+fieldValue+'\'); return false;" title="Review This Parcels Real Property Information">';
				hyperLinkClose = '</a>';
			}
			*/
			
			
			resultsTable += '<tr class="'+className+'">\n';
			resultsTable += '<td>'+ fieldName +': </td>\n';
			//resultsTable += '<td>'+hyperLinkOpen+ fieldValue +hyperLinkClose+'</td>\n';
			resultsTable += '<td>'+fieldValue+'</td>\n';
			resultsTable += '</tr>\n';
	}
		
		}
	}
	}
	resultsTable += '</table>\n';

	
	return resultsTable;
}


//*************************************************************
// Function for starting suggest [ BETA ]
//*************************************************************
function suggest(element,lid) {
	positionSuggestDiv(element)
	htmlElement = document.getElementById(element);
	usersValue = htmlElement.value;
	
	/*
	//test if the user is on the 3rd char.. we cant send  every time.
	
	isModThree = usersValue.length-1 % 3;
	if (isModThree != 1) { return; }
	*/
	
	var suggestHTML = '';
	//check for any value
	if (usersValue =="") { clearSuggest(); return; }
	
	//Clear the layers HTML
	suggestLayer.innerHTML = "";
	
	//Define the query
	var where = 'UPPER('+element+') LIKE \'' + usersValue + '%\'';
	where = cleanWhereClause(where)
	//Send the Sugest Query to the server
	var suggestQuery = new IAttributeQuery();
		suggestQuery.featureLimit = 5;
		suggestQuery.subFields = element;						
		suggestQuery.layerId = lid;	
		suggestQuery.where = where;
		suggestQuery.selectFeatures = true; 						
		suggestQuery.getQuery(myMap);
	
if (RESPONSE.RESULTS.length ==0) { clearSuggest(); return; }
	//Get all the results from the XML objects
	for (i in RESPONSE.RESULTS) {
		var streetName = RESPONSE.RESULTS[i].FIELDS[element];
		var envelope = RESPONSE.RESULTS[i].ENVELOPE;
		
		//get the layer index in RESPONSE.LAYER to find the obectID
		layerIndex  = findLayerIndex(lid)
		//getObjectId field name -99 TYPE
		objectIDFieldName =findObjectIdFieldName(layerIndex)
		
		var objectId = RESPONSE.RESULTS[i].FIELDS[objectIDFieldName];
		var results = streetName;
		
		//Add information to the suggest Layer
suggestHTML += '<div id="suggestMouseOut"  onmouseover="this.id=\'suggestMouseOver\'" onmouseout="this.id=\'suggestMouseOut\'"> &bull; <a href="javascript: void(0);" onClick="addSuggest2Input(\''+results+'\'); return false;"> '+ results +'</div></a>\n'; 
		
	}
	
	suggestLayer.innerHTML = suggestHTML;
	if (RESPONSE.RESULTS.length >0) {	showSuggest();	} 
	else  { clearSuggest(); }
	
}



function showSuggest() {
	suggestLayer.style.visibility = "visible";	
}

function clearSuggest() {
	suggestLayer.style.visibility = "hidden";	
}

function addSuggest2Input(value) {
		htmlElement.value = value;
		suggestLayer.style.visibility = "hidden";
		document.getElementById("pQuery").onclick;
}


function positionSuggestDiv(element) {
	inputElement = document.getElementById(element);
	var oNode = inputElement;
    var iLeft = 0;

    while(oNode.tagName != "BODY") {
        iLeft += oNode.offsetLeft;
        oNode = oNode.offsetParent;
    }

	var oNode = inputElement;
    var iTop = 0;

    while(oNode.tagName != "BODY") {
        iTop += oNode.offsetTop;
        oNode = oNode.offsetParent;
    }
	
	suggestLayer.style.left = iLeft -5 + "px";
	suggestLayer.style.top = iTop + inputElement.offsetHeight-3+"px";
	suggestLayer.style.width = inputElement.offsetWidth -13 + "px";
}



//*************************************************************
// Functions to dynamically build the search forms.
// Based off of ISearch Objects
//*************************************************************
function generateSearchForm(Search,SubSearch) {
	
	//clearS suggest if open;
	clearSuggest();
	
	//Define.
	newSearch = eval(Search);
	searchLayerId = newSearch.layerId;
	var searchDiv = document.getElementById("searchDiv");
	searchDiv.innerHTML = '';
	var suggestHTML = '';
	var formHTML ='';
	var subSearchHTML =''
	
	//Rename object properties for ease;
	thisSubSearch = newSearch.subSearch[SubSearch];
	firstField = thisSubSearch.firstField;
	firstFieldTitle = thisSubSearch.firstFieldTitle;
	firstFieldLength = thisSubSearch.firstFieldLength;
	firstFieldSuggest = thisSubSearch.firstFieldSuggest;
	secondField = thisSubSearch.secondField;
	secondFieldTitle = thisSubSearch.secondFieldTitle;
	secondFieldLength = thisSubSearch.secondFieldLength;
	secondFieldSuggest = thisSubSearch.secondFieldSuggest; 
	
	
	
	formHTML +='<table  width="263" border="0" cellspacing="0" cellpadding="4" class="searchTable">';
	
	
	//generate the First Field
	formHTML +='<tr>\n';
	formHTML +='<td width="63" class="largeBlackFont">';
	formHTML +=firstFieldTitle;
	formHTML +='</td>\n';
	formHTML +='<td width="200">\n';
	
	//determin if suggest is allowed.
	if (firstFieldSuggest) { suggestHTML = 'onkeyup="suggest(this.id,'+searchLayerId+')"'; }

	//form focus code.
	var	formFocus = ' onfocus="changeColor(this,true)" onBlur="changeColor(this,false)" ';

	//Generate HTML for Form
	formHTML +='<input id="'+firstField+'" name="'+firstField+'" type="text" size="'+firstFieldLength+'"'+ formFocus+' class="textboxes"'+ suggestHTML+ '/>';
	formHTML +='</td></tr>\n';
	
	//Check if,  and generate the second Field. 
	if (secondField) {
		
		if (secondFieldSuggest) { 
			suggestHTML = 'onkeyup="suggest(this.id,'+searchLayerId+')"';
		 } else { suggestHTML = ''; }
		
		
		
		formHTML +='<tr>\n';
		formHTML +='<td width="63" class="largeBlackFont">';
		formHTML +=secondFieldTitle;
		formHTML +='</td>\n';
		formHTML +='<td width="200">\n';
		formHTML +=' <input id="'+secondField+'" name="'+secondField+'" type="text"'+ formFocus+' size="'+secondFieldLength+'" class="textboxes"' +suggestHTML+ '/>';
		formHTML +='</td></tr>\n';
	}
	
	
	formHTML +='<tr>\n';
	formHTML +='<td width="96">&nbsp;</td>\n';
	formHTML +='<td width="158">\n';
	formHTML +='<input type="submit" id="pQuery" value="Search" class="textboxes"' + formFocus +' onClick="doMainSearch(this.form,\''+SubSearch+'\',\''+Search+'\'); return false;"  />';
	formHTML +='</td></tr>\n';
	
	//Generate SubSearch HyperLinks
	subSearchArray = newSearch.subSearch
	
	
	
	
	//subSearchHTML +='<table border="0" cellspacing="3" cellpadding="0"><tr>';
	var subSearchCount =0;
	
	//subSearchHTML +='<br><div id="subMenuTabs">';         
	
	for (p in subSearchArray) {
		subSearchCount++;
		if (subSearchCount >1) { spacer = "|"; } 
		else { spacer = ""; }
		subSearchHTML += spacer +' <a href="javascript: void(0);" onClick="generateSearchForm(\''+Search+'\',\''+p+'\'); return false;"><span class="blackLinks">'+ p +'<\a></span>\n';
	}	
	          
              
	//subSearchHTML +='</div>\n';
	document.getElementById("subSearchArea").innerHTML =subSearchHTML;
	
	formHTML +='</table>\n';
	
	searchDiv.innerHTML += formHTML;
}	




function changeColor(obj,inTextBox) {
	if (inTextBox) {
	obj.className = "textboxesFocus";
	}
	else {
		obj.className = "textboxes";
	}
}	
	
//*************************************************************
//Function to generat the WHERE clause for Searches.
//*************************************************************
function generateWhereForSearch(searchObject,subs) {
	
	searchObject = eval(searchObject);
	
	//Rename object properties for ease;
	thisSearchObject = searchObject.subSearch[subs];
	firstField = thisSubSearch.firstField;
	firstFieldLength = thisSubSearch.firstFieldLength;
	secondField = thisSubSearch.secondField;
	secondFieldLength = thisSubSearch.secondFieldLength;

	var firstWhere, secondWhere;
	var firstText, secondText;
	var finalWhere = '';
	var addAnd = '';

	//Get the form elements.
	firstText = document.getElementById(firstField).value;
	
	if (firstText != "") {
	firstWhere =  'UPPER('+firstField+') LIKE \'' + firstText + '%\'';
	finalWhere = firstWhere;
	}
	
	if (secondField) {
	secondText = document.getElementById(secondField).value;
	if (secondText != "") {
		secondWhere =  'UPPER('+secondField+') LIKE \'' + secondText + '%\'';
		finalWhere = secondWhere;
		}
	}
	
	if (firstText && secondText)  { 
		finalWhere = firstWhere + ' AND '+ secondWhere;
		
		finalWhere = cleanWhereClause(finalWhere)
		return(finalWhere)
	 } else{ 
	 	finalWhere = cleanWhereClause(finalWhere)
	 	return finalWhere; 
		}
}




function mousemove(e) {
	if (ie4) {  
		mouseX=event.clientX + document.body.scrollLeft; 
		mouseY=event.clientY + document.body.scrollTop
		}
	else  { mouseX=e.pageX; mouseY=e.pageY}	
	

}




//clean any invalid characters
function cleanWhereClause(oldString) {
	oldString = oldString.toUpperCase();
	oldString = oldString.replace(/&/g, "&amp;");
	oldString = oldString.replace(/'/g, "&apos;");
	oldString = oldString.replace(/>/g, "&gt;");
	oldString = oldString.replace(/</g, "&lt;");
	oldString = oldString.replace(/"/g, "&quot;");
	return oldString;
}

//*************************************************************
//Functions to drag a item on screen. 
//*************************************************************
var isMoving = false;
var idx, idy;
var idLayer;

function startMove(divId,e) {
	
	idLayer = document.getElementById(divId);
	isMoving = true;
	idx = mouseX - idLayer.offsetLeft;
	idy = mouseY - idLayer.offsetTop;
	document.onmousemove = updateMove;
	document.onmouseup = stopMove;
	
}

function updateMove(e) {
	if(!isMoving || (idLayer == null)) return;
	
	mousemove(e);

	idLayer.style.left = mouseX - idx + "px";
	idLayer.style.top = mouseY - idy + "px";
	idLayer.style.border ="1px dashed";
	//idLayer.style.filter ="alpha(opacity=75)";
	idLayer.style.opacity = "0.75";
	
	if (idLayer.offsetLeft < 0)
		idLayer.style.left = 0;
	if (idLayer.offsetTop < 0)
		idLayer.style.top = 0;

	document.onselectstart = function(){return false}
}

function stopMove() {
	//continue the program to track X and Y
	document.onmousemove =mousemove;
	
	if(!isMoving || (idLayer == null)) return;
	
	idLeft = idLayer.offsetLeft;
	idTop = idLayer.offsetTop;
	idLayer.style.border = "1px solid";
//	idLayer.style.filter ="alpha(opacity=100)";
	idLayer.style.opacity = "1";
	
	isMoving = false;
	//idLayer = null;

	document.onselectstart = function(){return true}
	
}



//***********************************************************************
//FUNCTION FOR CONTROLING THE ZOOM MENU BAR
//***********************************************************************

var zoomIsMoving = false;
var zoomidx, zoomidy;
var zoomLayer;

function startZoomMove(e, divId) {
	zoomLayer = document.getElementById(divId);
	zoomIsMoving = true;
	mousemove(e);
	zoomidx = mouseX - zoomLayer.offsetLeft;
	zoomidy = mouseY - zoomLayer.offsetTop;
	
	document.onmousemove = updateZoomMove;
	document.onmouseup = stopZoomMove;
}

function updateZoomMove(e) {
	if(!zoomIsMoving || (zoomLayer == null)) return;
	
	mousemove(e);

	//zoomLayer.style.left = mouseX - zoomidx + "px";
	zoomLayer.style.top = mouseY - zoomidy + "px";
	if (zoomLayer.offsetLeft < 0)
		zoomLayer.style.left = 0;
	if (zoomLayer.offsetTop < 0)
		zoomLayer.style.top = 0;
	document.onselectstart = function(){return false}
}

function stopZoomMove() {
	//continue the program to track X and Y
	document.onmousemove =mousemove;
	
	if(!zoomIsMoving || (zoomLayer == null)) return;
	
	idLeft = zoomLayer.offsetLeft;
	idTop = zoomLayer.offsetTop;

	
	zoomIsMoving = false;
	zoomLayer = null;
	document.onselectstart = function(){return true}

}






//***********************************************************************
// Function(s) to animate a tables size ( ANIMATION SIDE)
//***********************************************************************
// 	Syntax/Examples:
//	growSlideElement([up]|[down],elementName,width,height)
//	
//***********************************************************************
var widthDone = false;
var heightDone = false;
var q;

function growSlideElement(type,elementName,width,height) {
	
	clearTimeout(q); 
	widthDone = false;
	heightDone = false;
 	
	//reset to 0 if needed.
	if (type=='out') {
	elm = document.getElementById(elementName);
	elm.style.width = "0px";
	elm.style.height = "0px";
	}
	
	if (type == "out") { q = setInterval("elementSlideZoomOut(\'"+elementName+"\',"+width+","+height+")",5); } 
	else {	q = setInterval("elementSlideZoomBack(\'"+elementName+"\')",5);	}
}


function elementSlideZoomOut(elementName,width,height) 
{
	object = document.getElementById(elementName);
	object.style.visibility = "visible";
	//Height Info
	if (!heightDone) {
	var elementHeight = object.offsetHeight;
	elementHeight = parseInt(elementHeight) + 30;
	object.style.height = elementHeight + "px";
	}
	
	//Width Info
	if (!widthDone) {
	var elementWidth = object.offsetWidth;
	elementWidth = parseInt(elementWidth) + 30;
	object.style.width = elementWidth + "px";
	}
	
	//stop the grow
	if (elementHeight >= height) {  
		heightDone = true; 
		object.style.height = height + "px";
		}
	if (elementWidth >= width) {  
		widthDone = true; 
		object.style.width = width + "px";
		}
	if (heightDone && widthDone) {
	//alert(object.style.height)
		clearTimeout(q); 
		}
}



function elementSlideZoomBack(elementName) 
{
	object = document.getElementById(elementName);
	
	//Height Info
	if (!heightDone) {
	//alert(object.style.height);
	var elementHeight = object.offsetHeight;
	elementHeight = parseInt(elementHeight) - 10;
	if (elementHeight < 0) {elementHeight =0; }
	object.style.height = elementHeight + "px";
	}
	
	//Width Info
	if (!widthDone) {
	var elementWidth = object.offsetWidth;
	elementWidth = parseInt(elementWidth) - 30;
	if (elementWidth < 0) {elementWidth =0; }
	object.style.width = elementWidth + "px";
	}
	
	//stop the grow
	if (elementHeight <= 0) { 
		heightDone = true; 
		alert('here');
		object.style.height = 0 + "px";
		}
	if (elementWidth <= 0) {  
		widthDone = true; 
		object.style.width = 0 + "px";
		}
	if (heightDone && widthDone) {
	//alert(object.style.height)
		clearTimeout(q); 
		object.style.visibility = "hidden";
		}
}





//***********************************************************************
// Function to add content to the settings Layer.
//***********************************************************************
function addContentToSettingsLayer(content) {
	settingsLayer.innerHTML = content;
	
}

//***********************************************************************
//function to convert Zoom out coodrdinates.
//***********************************************************************
function convertZoomOut(env) {

	var ratio;
	var newRangX, newRangY;
	var xCenter, yCenter;
	
	absX = Math.abs(env.minx - env.maxx);
	absY = Math.abs(env.miny - env.maxy);
	
	extX = myMap.envelope.maxx - myMap.envelope.minx; // width
	extY = myMap.envelope.maxy - myMap.envelope.miny; // height
	
	// make ratio	
	if (absX > absY) { 	ratio = absX / extX;  } 
	else {  ratio = absY / extY;  }
		
	newRangX = extX / ratio;
	newRangY = extY / ratio;
	
	//calculate X center of drawn box
	if (env.minx < env.maxx) { xCenter = env.minx + (absX / 2) }
	else {  xCenter = env.maxx + (absX / 2) } 
	
	//calculate Y center of drawn box
	if (env.miny < env.maxy) { yCenter = env.miny + (absY / 2) }
	else {  yCenter = env.maxy + (absY / 2) }
	
	zoomOutCoords = new Object()
	zoomOutCoords.minx = xCenter - (newRangX / 2);
	zoomOutCoords.maxx = xCenter + (newRangX / 2);
	zoomOutCoords.miny = yCenter - (newRangY / 2);
	zoomOutCoords.maxy = yCenter + (newRangY / 2);

	zoom2Envelope(zoomOutCoords)
	
}




//***********************************************************************
// Function to get a map after zoom in using a rubber Band.
//***********************************************************************

function zoom2Envelope(envelope) {
	myMap.envelope = envelope;
	myMap.fullextent = false;
	myMap.getMap();
}
	

function zoomMap2PrintKey(pk,swiss,selectPk)
{
	var myPrinKeyQuery = new IAttributeQuery();
	myPrinKeyQuery.featureLimit = 1;
	myPrinKeyQuery.subFields = "#ALL#"; //subFields;						
	myPrinKeyQuery.layerId = parcelAXLId;	
	
	var swissWhere = "";
	if (swiss != "")
	{
		swissWhere = ' AND '+parcelSwissField+'=&apos;'+swiss+'&apos;';
	}
	if (useHardCodeSwisCode==true)
	{
		if (swiss == hardCodeSwisCode)
		{
			swissWhere = "";
		}
	}

	
	myPrinKeyQuery.where = parcelPrintKeyField +' = &apos;'+pk+'&apos;'+swissWhere;
	myPrinKeyQuery.getQuery(myMap);

	var env = RESPONSE.RESULTS[0].ENVELOPE
	
	//myMap.envelope = resizeEnvelope(env,900)
	myMap.envelope = zoomOutEnvelopeOneStep(env,1.33);
		
	if (selectPk)
	{
		var pkZoomRend = new IPolygonRenderer() 
			pkZoomRend.usefill = false;
			pkZoomRend.fillcolor = "12,222,1";
			pkZoomRend.filltype = "solid";
			pkZoomRend.filltransparency = "0";
			pkZoomRend.boundarycolor ="127, 255, 255";
			pkZoomRend.boundarywidth = 3;
			pkZoomRend.boundarytype = "solid"; 
			
			
			
		var pkZoomSelection = new IQuerySelection() 
			pkZoomSelection.layerId = parcelAXLId;
			pkZoomSelection.where = parcelPrintKeyField +' = &apos;'+pk+'&apos;';
			pkZoomSelection.selectionProperties = pkZoomRend	
			
			myMap.querySelection = pkZoomSelection;
	}
		myMap.fullextent = false;
		myMap.getMap();
		
		
		
	
}






//*************************************************************
// Performs a spatial POINT query on the map (like Identify)
//*************************************************************
function doPointQuery() {

	var myPoint = new IPoint()
		myPoint.x = IMouse.coordX;
		myPoint.y = IMouse.coordY
		
	var myPointQuery = new IPointQuery()		
		myPointQuery.map = myMap;
		myPointQuery.subFields = "#ALL#"
		myPointQuery.layerId = IActiveLayer.id;				
		myPointQuery.point = myPoint;					
		myPointQuery.getQuery(myMap);
		
		getPointQuery(myPointQuery.layerId,myPointQuery.beginrecord,true)
}



//*************************************************************
// Performs a spatial POINT query on PARCEL LAYER
//*************************************************************
function doParcelId() {

	var myPoint = new IPoint()
		myPoint.x = IMouse.coordX;
		myPoint.y = IMouse.coordY
		
	var myPointQuery = new IPointQuery()		
		myPointQuery.map = myMap;
		myPointQuery.subFields = "#ALL#"
		myPointQuery.layerId = parcelAXLId				
		myPointQuery.point = myPoint;					
		myPointQuery.getQuery(myMap);
		
		getPointQuery(myPointQuery.layerId,myPointQuery.beginrecord,true)
}

function getPointQuery(layerId,startingNumber,isPoint) {
	
	//Alert if not results found when not suggesting.
	if (RESPONSE.RESULTS.length==0) { alert("No Result(s) Found!"); return;}
	else {	loadActiveTab("Results"	)}
	
	//open side menu if not already open
	if (!sideMenuOpen) { resizeMapArea()	}
	var resultsHTML = '';;
	//display all the results.
	for (i in RESPONSE.RESULTS) {
		var firstResult = "Result #" + (parseInt(startingNumber)+parseInt(i));
		var envelope = RESPONSE.RESULTS[i].ENVELOPE;
		
		//get the layer index in RESPONSE.LAYER to find the obectID
		layerIndex  = findLayerIndex(layerId)
		//getObjectId field name -99 TYPE
		objectIDFieldName =findObjectIdFieldName(layerIndex)
		
		var objectId = RESPONSE.RESULTS[i].FIELDS[objectIDFieldName];
		var results = firstResult;
		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,layerId)
		}
				
	
		
	// add a link for the next results.	
	
	
	
	var bottomHTML ='<div align=center id="pointOptions" align="center" class="largeBlackFont"> ';
	var next25 = mySelectQuery.beginrecord + 25;
	var previous25 = parseInt(mySelectQuery.beginrecord) - 25;
	showLayer("bottomResultslayer")
	
	//check to see if the data is using the parcel table.
	// if so, allow to download mailing list.
	if (!isPoint)
	{
		if (layerId == parcelAXLId)
		{
			//bottomHTML +=' <a href="javascript: void(0);" onClick="getSearchMail('+layerId+',\'mySelectQuery\');  return false;"><img src="'+iconPath+'/mailEnvelope.gif" border=0>Download</a> &nbsp;&nbsp;'
		}
		
		if (previous25 > 0)
		{
			bottomHTML +='<a href="javascript: void(0);" onClick="getNextPoint('+layerId+','+previous25+');  return false;">Previous 25</a> &nbsp;&nbsp;'
		}
		
		if (RESPONSE.COUNT == mySelectQuery.featureLimit)
		{
			bottomHTML +='<a href="javascript: void(0);" onClick="getNextPoint('+layerId+','+next25+');  return false;">Next 25</a>';
		}
		bottomHTML +='</div>'
			
		bottomResultslayer.innerHTML = bottomHTML;
	}
	else 
	{
		bottomResultslayer.innerHTML = "";
	}


}



function populateAdditionalInfo(layerId)
{
	
	if (layerId == parcelAXLId)
	{
	
		for ( var i in RESPONSE.RESULTS)
		{
			//get the layer index in RESPONSE.LAYER to find the obectID
			layerIndex  = findLayerIndex(layerId)
			//getObjectId field name -99 TYPE
			objectIDFieldName =findObjectIdFieldName(layerIndex)
			var objectId = RESPONSE.RESULTS[i].FIELDS[objectIDFieldName];
			
			var printKey =RESPONSE.RESULTS[i].FIELDS[parcelPrintKeyField];
			var sbl = RESPONSE.RESULTS[i].FIELDS[parcelSBLField];
			
			var addInfoDiv = document.getElementById("additionalInfo"+objectId);
			//addInfoDiv.innerHTML = '<a href="'+additionalInfoURL+'?id=0&key='+printKey+'&sbl='+sbl+'"  target="_blank"> Additional Info </a>';
		}
	
	}

	
}








//*************************************************************
//Create a Div on the page dynamically
//*************************************************************
function createDiv(name,top,left,width,height) {

	var newDiv = document.createElement(name);
	newDiv.id = name;
	newDiv.style.position = "absolute";
	newDiv.style.visibility = "visible";
	newDiv.style.width =  width +"px";
	newDiv.style.height =  height +"px";
	newDiv.style.top = top +"px";
	newDiv.style.left = left + "px";
	newDiv.style.zIndex = 100;
	document.body.appendChild(newDiv);
}

function makeMiniMapBorderNice(divName) {
	div = document.getElementById(divName)
	div.style.background = "#FFF";
	
}




//Get the center of an envelope.
function getScreenCentroid(map) {

	var minx= parseInt(map.layer.offsetLeft);	//"609396.917728694" 
	var maxx= minx + map.layer.offsetWidth;	//"609434.746539193" 
	var maxy= map.layer.offsetTop;	//"1085050.61415221"
	var miny= maxy + map.layer.offsetHeight;	//"1085020.85757915" 
	
	var left = maxx - minx;
	var top = maxy - miny;
	
	var centerX = parseFloat(minx) + (left / 2);
	var centerY = parseFloat(miny) + (top / 2);
	
	var coords = centerX + " " + centerY;
	return coords
}





//Get the center of an envelope.
function getMapCentroid(env) {

	var minx= parseFloat(env.minx);	//"609396.917728694" 
	var miny= parseFloat(env.miny);	//"1085020.85757915" 
	var maxx= parseFloat(env.maxx);	//"609434.746539193" 
	var maxy= parseFloat(env.maxy);	//"1085050.61415221"
	
	var left = maxx - minx;
	var top = maxy - miny;
	
	var centerX = parseFloat(minx) + (left / 2);
	var centerY = parseFloat(miny) + (top / 2);
	
	var coords = centerX + " " + centerY;
	return coords
}



//get the screen X from a coordinate of X
function getScreenX(xCoord,map){
	
  xminx=parseFloat(map.envelope.minx);
  xmaxx=parseFloat(map.envelope.maxx);
  var xfac = (map.width/(xmaxx-xminx));
  x=xfac*(xCoord-xminx);
  
  return  parseInt(x);
}



//get the screen Y from a coordinate of Y
function getScreenY(yCoord,map){
	yminy=parseFloat(map.envelope.miny + 200);
	ymaxy=parseFloat(map.envelope.maxy + 200);
	var yfac = (map.height/(ymaxy-yminy));
	var y=map.height-(yfac*(yCoord-yminy));
	return  parseInt(y);
}






//Pictometry integration. (NIW ONLY!!!! - ensure client is using NIW)
var PicmapX;
var PicmapY;
var pictoX;
var pictoY;

//*********************************************************************
// Function to get the QueryString and return the values are variables
//*********************************************************************
function doPicto(centroid)
{

	if (centroid) {
		var pictoXYArray = centroid.split(' ');
		pictoX = pictoXYArray[0];
		pictoY = pictoXYArray[1];
	}
	else {
		pictoX = parseFloat(IMouse.coordX);
		pictoY = parseFloat(IMouse.coordY)		
	}
	
	
	if (pictoX && pictoY) {
	var xx = pictoX;
	var yy = pictoY;

	//Pictometry REQUIRES THESE 2 variables so it knows the X and Y
	//NIW does the coordinate conversion. if not using NIW, Code will bee to convert (not yet implemented)
	PicmapX = parseFloat(xx)
	PicmapY = parseFloat(yy);


	winImageList = open(pictometryURL,"PictImageListWindow");
	winImageList.focus();
	}
	else { alert("Missing query string params, pictoX or pictoY") }

	// Test Coordinates for Ontario County
	// X: 633179.1715389386
	// Y: 1053088.2569454442
}



//***************************************************************
//	function to convert an SDE.PATH to a single attribute Name
//***************************************************************
function convertSDEName(sdeFieldName) {
     var lastPoint = sdeFieldName.lastIndexOf('.')
 
     //retrun original if nothing . found.
     if (lastPoint == -1) { 
      return sdeFieldName; 
     } else {
      var newString = sdeFieldName.substr(lastPoint+1,sdeFieldName.length);
      return  newString;
     }
}


//***************************************************************
//	Find Layer ID index number in RESPONSE.LAYER[]
//***************************************************************
function findLayerIndex(layerId) {
	var myLayerIndex = ''; 
	
	for (x in RESPONSE.LAYER) 
	{
		if (layerId == RESPONSE.LAYER[x].id)
		{
			myLayerIndex = x;
		}
	}
	if(myLayerIndex == '') { alert("Cant find Layer ID" + layerId) }
	
	return myLayerIndex;
}


//***************************************************************
//	Find Layer index  in RESPONSE.LAYER[]
//***************************************************************
function findLayerIndexByName(name) {
	var myLayerIndex = ''; 
	
	for (x in RESPONSE.LAYER) 
	{
		if (name == RESPONSE.LAYER[x].name)
		{
			myLayerIndex = x;
		}
	}
	if(myLayerIndex == '') { alert("Cant find Layer Name" + name) }
	
	return myLayerIndex;
}


//***************************************************************
// 	Function to find the object ID fieldName
// 	returns the object Id Feild Name [  OBJECTID  _ID_ ]
//***************************************************************
function findObjectIdFieldName(layerIndex) {
	var myObjectIdField = ''; 
	var layerFields = RESPONSE.LAYER[layerIndex].FCLASS.FIELD

	for (x in layerFields) 
	{
		if (layerFields[x].type == "-99")
		{
			myObjectIdField =layerFields[x].name
		}
	}
	if(myObjectIdField == '') { alert("Cant find Layer Index " + layerIndex + " for ObjectID FieldName") }
		
	return myObjectIdField;
}


//***************************************************************
//Maximize the window to 100% of the users screen
//***************************************************************
function screenMaximize()
{
	moveTo(0,0);
	window.resizeTo(screen.availWidth+4,screen.availHeight+4)
}

//*******************************************************
// SHOW , HIDE, KILL & POSITION (xy) LAYERS
//*******************************************************
function showLayer(name) {
	
	 layerz = document.getElementById(name);
	if (layerz) 
	layerz.style.visibility = "visible";
}

function hideLayer(name) {
	layerz = document.getElementById(name);
	if (layerz)
	layerz.style.visibility = "hidden";
}

function killLayer(name) {
	
	name = document.getElementById(name)
	if (name)
	document.body.removeChild(name);
	
}

function blockLayer(name) {
	layerz = document.getElementById(name);
	layerz.style.display = "block";
}

function unBlockLayer(name) {
	layerz = document.getElementById(name);
	layerz.style.display = "none";
}

function positionLayer(e) {
	layerz.style.top = mouseY + "px";
	layerz.style.left = mouseX + "px";
}



//*******************************************************
//Select a plygon object on the map
//*******************************************************
function selectPolygon(layerId,objectId,minx,miny,maxx,maxy) {

	//get the object ID
	//get the layer index in RESPONSE.LAYER to find the obectID
	var layerIndex  = findLayerIndex(layerId)
	var objectIDFieldName =findObjectIdFieldName(layerIndex)	//getObjectId field name -99 TYPE


var envelopeString = minx+','+miny+','+maxx+','+maxy;
var selectionEnvelope = new tempEnvelope();
var selectionEnvelope = string2ResizedEnvelope(minx,miny,maxx,maxy,1500);

myPlygonRender = new IPolygonRenderer() 
	myPlygonRender.usefill = false;
	myPlygonRender.fillcolor = "91,182,220";
	myPlygonRender.filltype = "solid";
	myPlygonRender.filltransparency = "0";
	myPlygonRender.boundarycolor ="127, 255, 255";
	myPlygonRender.boundarywidth = 2;
	myPlygonRender.boundarytype = "solid"; //"solid | dash | dot | dash_dot | dash_dot_dot"  [solid]

myPolygonQuerySelection = new IQuerySelection() 
	myPolygonQuerySelection.layerId = layerId;
	myPolygonQuerySelection.where = objectIDFieldName+'='+objectId;
	myPolygonQuerySelection.selectionProperties = myPlygonRender
	
	
	myMap.querySelection = myPolygonQuerySelection;
	myMap.fullextent = false;
	myMap.envelope = selectionEnvelope;
	myMap.getMap();
}



//*******************************************************
//Zoom To an area,. feature etc.... new IZoomTo
//*******************************************************

function buildZoom2List() {
	
	if (myZoomTo.useZoomTo)
	{
	
	var listValue;
	var totalInList = 0;
	var zoomSelectMenu = document.getElementById("areaZoomList");
	
	
	var myBuildZoom2Query = new  IAttributeQuery() 
		myBuildZoom2Query.featureLimit = 80;		
		myBuildZoom2Query.beginrecord = 1;		
		myBuildZoom2Query.subFields = myZoomTo.fieldName;				
		myBuildZoom2Query.layerId = myZoomTo.layerId	;			
		myBuildZoom2Query.where = myZoomTo.fieldName +' LIKE \'%%\'';		
		myBuildZoom2Query.useResults2 = true;
		myBuildZoom2Query.getQuery();
	
	
		var zoomListSortArray = new Array();
	
		for (var i in RESPONSE.RESULTS2) {
			 zoomListSortArray[i] = RESPONSE.RESULTS2[i].FIELDS[myZoomTo.fieldName];

		}
		zoomListSortArray.sort()
		for (var i in zoomListSortArray) {
			var listValue = zoomListSortArray[i];

			var optionText = listValue;
			var optionValue = listValue
			 zoomSelectMenu.options[i]=new Option(optionText, optionValue, false, false)
			 totalInList++;
		}

		 zoomSelectMenu.options[totalInList]=new Option("-- Select --", "", false, true)
	}
	else { document.getElementById("zoomTo").style.display = "none"; }
}


function zoom2Area(iZoomTo) {

var myZoom2Query = new  IAttributeQuery() 
	myZoom2Query.featureLimit = 1;		
	myZoom2Query.beginrecord = 1;		
	myZoom2Query.subFields = "#SHAPE#";				
	myZoom2Query.layerId = iZoomTo.layerId	;			
	myZoom2Query.where = iZoomTo.fieldName +'=\''+iZoomTo.fieldValue+'\'';	
	myZoom2Query.useResults2 = true;
	myZoom2Query.getQuery();
	
	
	myMap.envelope = RESPONSE.RESULTS2[0].ENVELOPE
	myMap.fullextent = false;
	myMap.getMap();
	
	
}

function doZoomTo(value) {
	if (value == '') { return; }
	myZoomTo.fieldValue = value;
	zoom2Area(myZoomTo)
}



// Date formatting functions from http://www.web-source.net/web_development/javascript_date.htm
// Copyright 2002 Bontrager Connection, LLC
function getCalendarDate()
{
   var months = new Array(13);
   months[0]  = "January";
   months[1]  = "February";
   months[2]  = "March";
   months[3]  = "April";
   months[4]  = "May";
   months[5]  = "June";
   months[6]  = "July";
   months[7]  = "August";
   months[8]  = "September";
   months[9]  = "October";
   months[10] = "November";
   months[11] = "December";
   var now         = new Date();
   var monthnumber = now.getMonth();
   var monthname   = months[monthnumber];
   var monthday    = now.getDate();
   var year        = now.getYear();
   if(year < 2000) { year = year + 1900; }
   var dateString = monthname +
                    ' ' +
                    monthday +
                    ', ' +
                    year;
   return dateString;
} // function getCalendarDate()

function getClockTime()
{
   var now    = new Date();
   var hour   = now.getHours();
   var minute = now.getMinutes();
   var second = now.getSeconds();
   var ap = "AM";
   if (hour   > 11) { ap = "PM";             }
   if (hour   > 12) { hour = hour - 12;      }
   if (hour   == 0) { hour = 12;             }
   if (hour   < 10) { hour   = "0" + hour;   }
   if (minute < 10) { minute = "0" + minute; }
   if (second < 10) { second = "0" + second; }
   var timeString = hour +
                    ':' +
                    minute +
                    ':' +
                    second +
                    " " +
                    ap;
   return timeString;
} // function getClockTime()


//clean any invalid characters
function cleanInValidChars(oldString) {
	var oldString = oldString.replace(/&amp;/g, "&");
	return oldString;	
}



//----------------------------------------
// Zoom to scale functions
//----------------------------------------

//function to populate the zoom 2 scale menu.

function buildZoom2Scale()
{
	var zMenu = document.getElementById("zoom2ScaleMenu");

	for (var i =0; i<= zoom2ScaleArray.length - 1; i++)
	{
	var zVal = zoom2ScaleArray[i]
	zMenu.options[i]=new Option("1 : "+ zVal,zVal, false, false)
	}
	 zMenu.options[zoom2ScaleArray.length]=new Option("-- Select --", "", false, true)

}

function doZoom2Scale(value) 
{
	//remove the comma incase the user thinks they have to have one.
	var value = value.replace(/\,/g, ""); 
	
	//Check to see if it is a number.
	if (isNaN(value)) {	alert("Please check your entry. An invalid character value was entered."); return false;	}
	
	//sent to the function to do the work
	processZoom2Scale(value,myMap);
}


function processZoom2Scale(value,map) 
{
   	var msize;
	var env = map.envelope;
  	var eRight 	=  parseInt(env.maxx);
  	var eTop 	=  parseInt(env.maxy);

	var xDistance =  parseFloat(env.maxx) -  parseFloat(env.minx);
	var yDistance =  parseFloat(env.maxy) -  parseFloat(env.miny);
   
	if ( map.height < map.width) {
	  msize = map.height
	} else {
	  msize = map.width
	} 
	var midX = eRight - (xDistance / 2);
	var midY = eTop   - (yDistance / 2);
	var mscale= (value * ((msize/96)/12)) * .5;
	
	myMap.envelope.minx 	= ((midX) - (mscale));
	myMap.envelope.maxx 	= ((midX) + (mscale));
	myMap.envelope.miny 	= ((midY) - (mscale));
	myMap.envelope.maxy 	= ((midY) + (mscale));

	myMap.fullextent = false;
	myMap.getMap();
}


//-------------------------------------------
// MAP SELECTION
//-------------------------------------------
var mySelectQuery = new IPointQuery()

function mapSelect(env)
{	
		mySelectQuery.map = myMap;
		mySelectQuery.featureLimit = 25;
		mySelectQuery.subFields = "#ALL#"
		mySelectQuery.layerId = IActiveLayer.id;				
		mySelectQuery.envelope = env;	
		mySelectQuery.useResults2 = false;
		mySelectQuery.getQuery(myMap);
		
		getPointQuery(IActiveLayer.id,mySelectQuery.beginrecord)
		getSelectionImage(env,IActiveLayer.id)
}



function getSelectionImage(Zenv,layerId) {
	var selectionPoly = new IPolygonRenderer() ;
		selectionPoly.usefill = true;
		selectionPoly.fillcolor = parseRGB(selectionColor) //"77, 203, 219" //;
		selectionPoly.filltype = "solid";
		selectionPoly.filltransparency = 0.0;
		selectionPoly.boundarycolor = parseRGB(selectionColor)//"2, 102, 211" //"255,255,255";
		selectionPoly.boundarywidth = 2;
		selectionPoly.boundarytype = "solid"; //"solid | dash | dot | dash_dot | dash_dot_dot"  [solid]

 	var mySS = new  ISpatialSelection()
		mySS.layerId =layerId; 
		mySS.selectionEnvelope =Zenv;
		mySS.selectionProperties = selectionPoly;

		myMap.spatialSelection = mySS;
		myMap.getMap();
}

function getNextPoint(layerId,nextAmount)
{
	resultsLayer.innerHTML = '';
	mySelectQuery.beginrecord = nextAmount;
	mySelectQuery.getQuery(myMap);
	getPointQuery(layerId,nextAmount);
	mySelectQuery.beginrecord = 1; // reset the begin record since its public.
}




function positionLoadLayer()
{
	var centerOfMap = getScreenCentroid(myMap)
	var loadingCentroid = centerOfMap.split(" ");
	loadingLayer.style.top  = loadingCentroid[1]  -(loadingLayer.offsetHeight / 2)+"px";
	loadingLayer.style.left = loadingCentroid[0]-  (loadingLayer.offsetWidth / 2)+ "px";
}


function startHyperSelection(toolName)
{
	var sentence = "&nbsp;&nbsp;Need Help finding an area associated with a file? ";
	settingsLayer.innerHTML = sentence+'<input type="button" value="Select All Areas In Current View" OnClick="myHyperLinks.selectAllHyperLinks(\''+toolName+'\')">';	
}

/*
var mapHistory = new IHistory();
mapHistory.axl[0] = "a"
mapHistory.axl[1] = "b"
mapHistory.axl[2] = "c"
mapHistory.axl[3] = "d"
mapHistory.axl[4] = "e"
mapHistory.axl[5] = "f"
function historyManager(axl)
{
		
	//mapHistory.axl.pop(10);
	//alert(mapHistory.axl.length);
	mapHistory.axl.shift();
	for (var i in mapHistory.axl)
	{	
		//alert(mapHistory.axl[i] + " " +i);
	}
	
	
}
*/


