// aimsCommon.js
var aimsCommonPresent=true;
jsPlace = "parent.MapFrame";

var queryTool = 0;
var legendImage="";
var modeBlurb = "Zoom In";

var chkUnits=false;
var legendTemp = false;
var ovIsVisible=true;

var showBuffer = false;

// character used by browser in decimals - either point or comma
var decimalChar = ((("theChar is" + (10/100)).indexOf("."))==-1) ? "," : ".";
//alert("Decimal character: " + decimalChar);

var theImagePath = "";
var theImageURLPath = "";
var theServiceName = "";

var theVersion = navigator.appVersion;
var theVersNum = parseFloat(theVersion);
var theBrowser = navigator.appName;
var noOverlay = true;  //must be true for now
//alert(browser + " - " + versNum + " - " + version);

//if ((theVersion.indexOf("MSIE 5")!=-1) || (theBrowser=="Netscape") || (theVersNum>=5))  noOverlay = false;

// when there is a mapservice to load, it proceeds from here
function startUp() {

	if (imsURL != "") {
		//alert(imsURL);
		iWidth = document.theImage.width;
		iHeight = document.theImage.height;
		if (imsURL!=imsOVURL) toggleOVVisible = false;
		getStartExtent();
	}
}

// get the starting extent
function getStartExtent() {
	if(parent.PostFrame.document.theForm != null) {
		var theString = '<?xml version="1.0" encoding="UTF-8"?>\n<ARCXML version="1.1">\n<REQUEST>\n<GET_SERVICE_INFO renderer="false" extensions="false" fields="false" />\n';
		theString = theString + '</REQUEST>\n</ARCXML>';
		var theReply="";
		if(getLimitExtent) {
			if(hasOVMap) {
				sendToServer(imsOVURL,theString,3);
			} else {
				sendToServer(imsURL,theString,3);
			}
		} else {
			XMLMode=3;
			//alert("No request sent for Limit Extent");
			processXML("No request for Limit Extent")
		}
	} else {
		parent.document.location.reload();
	}
}

// process the start extent and set up layers
function processStartExtent(theReply) {

	if (getStartingExtent) {
		getXYs(theReply);
		startLeft=left;
		startRight=right;
		startTop=top;
		startBottom=bottom;
	} else {
		left=startLeft;
		right=startRight;
		top=startTop;
		bottom=startBottom;
		xDistance = Math.abs(right-left);
		var sFactor = xDistance / iWidth
		mapScaleFactor = sFactor;

	}
	if (aimsLayersPresent) getLayers(theReply);
	if (aimsQueryPresent) {
		if (useStoredQuery) checkStoredQueries(theReply);
	} else {
		useStoredQuery=false;
	}
	 xDistance = Math.abs(right-left);
	 yDistance = Math.abs(top-bottom);
	 xHalf = xDistance/2;
	 yHalf = yDistance/2;
	 panX = xDistance * panFactor;
	 panY = yDistance * panFactor;
	 if (chkUnits) {
		 if (MapUnits=="DEGREES") {
		 	if ((right > 250) || (top > 150)) MapUnits="FEET";
			// alert(MapUnits);
		 }
		 chkUnits=false;
	 }
	 mouseX = 0;
	 mouseY = 0;
	 pixelX = xDistance/iWidth;
	 pixelY = yDistance/iHeight;
	 mapX = left;
	 mayY = top;
	 lastLeft = left;
	 lastRight = right;
	 lastTop = top;
	 lastBottom = bottom;
	 if (hasOVMap == false) {
		 fullLeft = limitLeft;
		 fullRight = limitRight;
		 fullTop = limitTop;
		 fullBottom = limitBottom;
		 fullWidth = Math.abs(fullRight - fullLeft);
		 fullHeight = Math.abs(fullTop - fullBottom);

	 }
	if (aimsLayersPresent) {
	 	if ((hasTOC) && (showTOC)) {
		 	parent.TOCFrame.document.location=appDir+"toc.htm";
		}
	}
	if (aimsGeocodePresent) {
		if (GCLayerCount==0) {
			if ((useGeocode) || (useReverseGeocode)) {
				useGeocode=false;
				useReverseGeocode=false;
			}
		}
	} else {
			useGeocode=false;
			useReverseGeocode=false;
	}

	if (parent.ToolFrame!=null) {
		//parent.mainmenu.document.location= appDir + "mainmenu.htm";
		parent.ToolFrame.document.location= appDir + "toolframe.html";
		//parent.MapDataFrame.document.location= appDir + "mapdatabar.htm";
	} else if (hasToolBarOnLayer) {
		// requires custom function getLayerListContent. . . example in layerlist.js in Hyperlink sample
		var content = getLayerListContent();
		if (isNav) {
			replaceLayerContent("theToolBar",content);
		} else {
			content = swapStuff(content,"\\'",sQuote);
			document.all.theToolBar.innerHTML = content;
		}

	}
	hideRetrieveData();
	if ((ovIsVisible) && (aimsDHTMLPresent)) {
		ovIsVisible = false;
		toggleOVMap();
	}
	if (enforceFullExtent) {
		writeBlankMapXML();
	} else {
		sendMapXML();
	}
}


// request a list of available Image MapServices
function startMap() {

	showRetrieveData();
	if (aimsGenericPresent) {
		var theText = "<GETCLIENTSERVICES/>";
		sendToServer(catURL,theText,5);
	} else {
		startUp();
	}
}

// get the Map Image width
function getMapWidth () {
	var mapFrameWidth = thePageWin.innerWidth;
	if (mapFrameWidth == null) {
		mapFrameWidth = thePageDoc.body.clientWidth;
	}
	return mapFrameWidth;
}

 //get the Map Image height
function getMapHeight () {
	var mapFrameHeight = thePageWin.innerHeight;
	if (mapFrameHeight == null) {
		mapFrameHeight = thePageDoc.body.clientHeight;
	}
	return mapFrameHeight;
}

function checkCurrentExtent() {
	var msg = "Current Extent:\nLeft: " + left + "\nBottom: " + bottom + "\nRight: " + right + "\nTop: " + top;
	var ratio1 = xDistance/fullWidth;
	msg += "\n\nRatio to Full Extent: " + ratio1;
	alert(msg);
}

// write out ModeFrame page
function writeModeFrame(currentMode) {
	parent.ModeFrame.document.location= appDir + "ModeFrame.htm";
}

// write out Mode on dynamic layer
function writeModeLayers(currentMode) {
	var content = '<font face="' + modeLayerFont + '"color="' +  modeLayerShadowColor + '"size=' + modeLayerSize + '><b>' + currentMode + '</b></font>';
	replaceLayerContent("theMode1",content);
	content = '<font face="' + modeLayerFont + '"color="' +  modeLayerColor + '"size=' + modeLayerSize + '><b>' + currentMode + '</b></font>';
	replaceLayerContent("theMode2",content);

}

// swap out double quotes for single
function swapQuotes2(inText) {
	var doubleQuote = dQuote;
	var singleQuote = "'";
	var preTemp = "";
	var posTemp = "";
	var nextPos = 0;
	var ePos = inText.length;
	var pos=9;
	while (pos != -1) {
		pos = inText.indexOf(dQuote);
		if (pos!=-1) {
			nextPos=pos+1;
			preTemp = inText.substring(0,pos);
			posTemp = inText.substring(nextPos,ePos);
			inText = preTemp + sQuote + posTemp;
		}
	}
	return inText;
}

function swapQuotes(inText) {
	inText = inText.replace(/"/g, "'");
	return inText;
}

// convert hexidecimal rgb number to delimited decimal rgb
function convertHexToDec(hexColor) {
	var pos = hexColor.indexOf(",");
	var decString = hexColor;
	if (pos==-1) {
		pos = hexColor.indexOf("#");
		if (pos!=-1) {
			hexColor = hexColor.substring((pos + 1),(pos + 7));
		}
		//alert(hexColor);
		var redHex = hexColor.substring(0,2);
		var greenHex = hexColor.substring(2,4);
		var blueHex = hexColor.substring(4,6);
		decString = parseInt(redHex,16) + "," + parseInt(greenHex,16) + "," + parseInt(blueHex,16);

	}
	//alert(decString);
	return decString;

}
function swapStuff(oldString, oldStuff, newStuff) {
	oldString = oldString.replace(eval("/" + oldStuff + "/gi;"), newStuff);
	return oldString;
}
// disables error checking
function clearError() {
	return true;
}

// reset error checking to default
function resetError() {
	return false;
}


function reloadApp() {
	if (isNav) {
		document.location = "default.htm";
	}
}

// clear out leading spaces in field value list
function clearLeadingSpace(inText) {
	var pos=9;
	while (pos != -1) {
		pos = inText.indexOf('=" ');
		if (pos!=-1) {
			var lastpos = inText.length;
			var midend = pos + 2;
			var midstart = pos + 3;
			var leftSide = inText.substring(0,midend);
			var rightSide = inText.substring(midstart,lastpos);
			inText = leftSide + rightSide;
		}
	}
	return inText;
}

// replace < and > in string with « and » to allow display in html page
function untag(inputString) {
	var outString = inputString.replace(/</g,"«");
	outString = outString.replace(/>/g, "»");
	return outString;
}

// replace single quotes with double single quotes
//	set up interior single qoutes and apostrophes for queries
function fixSingleQuotes(inputString) {
	var outString = inputString.replace(/'/g, "''");
	return outString;
}


function PoistaHipsut(inputString) {
	var outString = inputString.replace(/"/g, "");
	return outString;
}

function Muunnavalilyonti(inputString) {
        //var outString = inputString.replace(/ /g, "&#160");
        //muutettu 25.5.2003 by Jani
        var outString = inputString.replace(/ /g, "&#32");
        return outString;
}

function Muunnablanko(inputString) {
	//var outString = inputString.replace(/&#160/g, " ");
        //muutettu 25.5.2003 by Jani
        var outString = inputString.replace(/&#32/g, " ");
	return outString;
}


// parse out record data from XML stream
function parseRecordString(theReply, startpos) {
	var inData = "";
	var pos = theReply.indexOf("<FIELDS ",startpos);
	if (pos!=-1) {
		startpos = pos + 8;
		xmlEndPos = theReply.indexOf('" />',startpos);
		inData = theReply.substring(startpos,xmlEndPos);
	}
	return inData;
}

// get a list of field names from the returned record
function getFieldNames(recordString) {
	var theStuff = new String(recordString);
	var theList = theStuff.split('" ');
	var fName1 = new Array();
	for (var f=0;f<theList.length;f++) {
		var v = theList[f].split('="');
		fName1[f] = v[0];
	}
	return fName1;

}

// get a list field values from the returned record
function getFieldValues(recordString) {
	var theStuff = new String(recordString);
	var theList = theStuff.split('" ');
	var fValue1 = new Array();
	for (var f=0;f<theList.length;f++) {
		var v = theList[f].split('="');
		if ((v[1]=="") || (v[1]==null)) v[1] = "&nbsp;";
		if (v[0]==LayerShapeField[ActiveLayerIndex]) v[1]="[" + ActiveLayerType + "]";
		fValue1[f] = v[1];
	}
	return fValue1;

}

// just get the field value from the lists of fieldnames and fieldvalues
function getIdValue(fieldNameArray, fieldValueArray) {
	var theValue = 0;
	for (var f=0;f<fieldNameArray.length;f++) {
		if (fieldNameArray[f]==LayerIDField[ActiveLayerIndex]) {
			theValue = fieldValueArray[f];
		}
	}
	return theValue;

}

// just get the interior string from the theReply between preString and postString
//		starting from startpos
function justGetValue(theReply,preString,postString,startpos) {
	var theValue = "";
	var pos = theReply.indexOf(preString,startpos);
	if (pos!=-1) {
		pos = pos + preString.length;
		var endpos = theReply.indexOf(postString,(pos));
		if (endpos!=-1) {
			theValue = theReply.substring(pos,endpos);
			xmlEndPos = endpos;
		}
	}
	return theValue;
}

// get one field value from theReply starting from startpos
function justGetFieldValue(theReply,theField,startpos) {
	var preString = theField + '="';
	var returnString = justGetValue(theReply, preString, dQuote, startpos);
	return returnString;
}

// get the number of features returned in xml response
function justGetFeatureCount(theReply) {
	var theCount = 0;
	var pos = theReply.indexOf("<FEATURECOUNT");
	if(pos!=-1) {
		var theValue = justGetValue(theReply,'count="',dQuote,pos);
		theCount = parseInt(theValue);
	}
	return theCount;
}

// get the number of features returned in xml response
function justGetHasMoreValue(theReply) {
        //alert(theReply);
	var theHasMoreValue = "";
	var pos = theReply.indexOf("<FEATURECOUNT");
	if (pos!=-1) {
		theHasMoreValue = justGetValue(theReply,'hasmore="',dQuote,pos);
	}
	return theHasMoreValue;
}


// get all the field values and return a list
function getAllFieldValues(theReply,theField,recCount) {
	var vList = new Array();
	xmlEndPos = 0;
	for (var i=0;i<recCount;i++) {
		vList[i] = parseFloat(justGetFieldValue(theReply,theField,xmlEndPos));
	}
	return vList;
}

// reset order to numeric
function numberorder(a,b) { return a - b; }

// replace common HTML entitys with the characters they represent
function parseEntity(oldString) {
	oldString = swapStuff(oldString,"&apos;","'");
	oldString = swapStuff(oldString,"&divide;","/");
	oldString = swapStuff(oldString,"&ge;",">=");
	oldString = swapStuff(oldString,"&gt;",">");
	oldString = swapStuff(oldString,"&le;","<=");
	oldString = swapStuff(oldString,"&lt;","<");
	oldString = swapStuff(oldString,"&ne;","<>");
	oldString = swapStuff(oldString,"&quot;",'"');
	oldString = swapStuff(oldString,"&amp;","&");
	//alert(oldString);

	return oldString;
}

// replace the five problem characters for the server's XML parser
function makeXMLsafe(oldString) {
	oldString = swapStuff(oldString,"'","&apos;");
	oldString = swapStuff(oldString,">","&gt;");
	oldString = swapStuff(oldString,"<","&lt;");
	oldString = swapStuff(oldString,'"',"&quot;");
	return oldString;
}

// replace +  in string with space to allow parsing of unescaped xml response
function replacePlus(inText) {
	var pos=9;
	while (pos != -1) {
		pos = inText.indexOf('+');
		if (pos!=-1) {
			var lastpos = inText.length;
			var midend = pos;
			var midstart = pos + 1;
			var leftSide = inText.substring(0,midend);
			var rightSide = inText.substring(midstart,lastpos);
			inText = leftSide + " " + rightSide;
		}
	}
	return inText;
}

// get the substring between beforeString and afterString, starting at startpos
// 		must be found before limitpos (0 for no limit)
// 		caseSensitive = true or false
function getInsideString(inString,beforeString,afterString,startpos,limitpos,caseSensitive) {
	var returnString = "";
	var ucInString = inString;
	var ucBefore = beforeString;
	var ucAfter = afterString;
	if (limitpos==0) limitpos = inString.length;
	if (!caseSensitive) {
		ucInString = inString.toUpperCase();
		ucBefore = beforeString.toUpperCase();
		ucAfter = afterString.toUpperCase();
	}
	pos = ucInString.indexOf(ucBefore,startpos);
	//alert(startpos);
	if ((pos != -1) && (pos<limitpos)) {
		pos = pos + ucBefore.length;
		var endpos = ucInString.indexOf(ucAfter,pos);
		returnString = inString.substring(pos,endpos);
	}

	return returnString;
}

function ConvertSpecialCharacters(inStr) {
  inStr = swapStuff(inStr," ","%20");
  inStr = swapStuff(inStr,"Ä","%c4");
  inStr = swapStuff(inStr,"Å","%c5");
  inStr = swapStuff(inStr,"Ö","%d6");
  inStr = swapStuff(inStr,"ä","%e4");
  inStr = swapStuff(inStr,"å","%e5");
  inStr = swapStuff(inStr,"ö","%f6");
  return inStr;
}

