// aimsCustom.js
/*
*  JavaScript template file for ArcIMS HTML Viewer
*		dependent on aimsXML.js, ArcIMSparam.js, aimsCommon.js, aimsMap.js,
*		aimsLayers.js, aimsDHTML.js
*		aimsClick.js, aimsNavigation.js,
*/

// Global variables
	aimsCustomPresent=true;
	// Change these to send XML response to custom function.
	// Use numbers >= 1000 and match in useCustomFunction().
	// Defaults are defined in aimsXML.js and use standard functions.
	
	// xml response mode for selection
	selectXMLMode = 6;
	// xml response mode for identify
	identifyXMLMode = 7;
	// xml response mode for query
	queryXMLMode = 8;
	// xml response mode for find
	findXMLMode = 14;
	// xml response mode hyperlink
	hyperlinkXMLMode = 15;
	
	//
	// *** begin dsSelectByCircle code ***
	//
	var drawCircle=true;
	var drawBufferedFeatures=false;
	var buffX=0;
	var buffY=0;
	//
	// ***  end dsSelectByCircle code  ***
	//


var extractXMLMode=1111;
var imsExtractURL = imsURL + '&CustomService=Extract'

// Custom function for handling clicks 
// 		flow redirected here when
//		toolMode set to >=1000
function customMapTool(e) {
				if (toolMode == 1001) {
						// Insert code here.
						return false;
					
				}
				if (toolMode == 1002) {
				//
				// *** begin dsSelectByCircle code ***
				//
				// dsSelectByCircle tool in use
				//alert ("Buffer this point");
				if (checkIfActiveLayerAvailable()) {
					selectType=ActiveLayerType;
					getBufferedData=false;
					drawTargetLayer=false;
					showBuffer=false;
					drawBufferedFeatures=true;
					bufferPoint(e);
				}
				//
				// ***  end dsSelectByCircle code  ***
				//
       			}

}

// Send  XML response to custom function
//		flow  redirected here when
//		XMLMode >=1000
function useCustomFunction(theReply) {
	if (XMLMode==1001) {
		// Insert code here.
	} else if (XMLMode==1111) {
		parseExtractResponse(theReply);
	} else if (XMLMode==1002) {
		//
		// *** begin dsSelectByCircle code ***
		//
		// dsSelectByCircle tool in use
		customGetBufferAttributeData(theReply);
		//
		// ***  end dsSelectByCircle code  ***
		//
	} else {
		alert(msgList[55] + XMLMode + msgList[56]);
	}
	hideLayer("LoadData");
}

// Add custom stuff to Map XML request. . . between selection and geocode.
function addCustomToMap1(){
	var customString = "";
	/*
		customString += '<LAYER type="ACETATE" name="theMode">\n';
		customString += '<OBJECT units="PIXEL">\n<TEXT coord="5 ' + (iHeight-10) + '" label="This is a test">\n';
		customString += '<TEXTMARKERSYMBOL fontstyle="BOLD" fontsize="12" font="ARIAL" fontcolor="' + modeMapColor + '" ';
		customString += 'threed="TRUE" glowing="' + modeMapGlow + '" />\n</TEXT>\n</OBJECT>';
		customString += '\n</LAYER>\n';
	*/
	return customString;
}

// Add custom stuff to Map XML request. . . between clickpoints and copyright.
function addCustomToMap2(){
	if (buffX == 0 && buffY == 0) {
		return '';
	}

	var customString = "";
	//
	// *** begin dsSelectByCircle code ***
	//
	if (debugOn>3) alert ("[function addCustomToMap2]\ndrawCircle="+drawCircle+"\ndrawBufferedFeatures="+drawBufferedFeatures+"\ntoolMode="+toolMode);
	
	if (drawCircle && (toolMode == 1002 || toolMode < 4)) {
		customString += bufferDrawCircleAroundPt();
	}
	
	if (drawBufferedFeatures && (toolMode == 1002 || toolMode < 4)) {
		customString += bufferDrawSelected();
	}
	
	if (debugOn>3) alert ("[function addCustomToMap2]\n\n"+customString);
	//
	// ***  end dsSelectByCircle code  ***
	//
	return customString;
}

// Add custom stuff to Map XML request. . . under modeOnMap.
function addCustomToMap3(){
	var customString = "";
		/*
		customString += '<LAYER type="ACETATE" name="theMode">\n';
		customString += '<OBJECT units="PIXEL">\n<TEXT coord="5 ' + (iHeight-10) + '" label="This is a test">\n';
		customString += '<TEXTMARKERSYMBOL fontstyle="BOLD" fontsize="12" font="ARIAL" fontcolor="' + modeMapColor + '" ';
		customString += 'threed="TRUE" glowing="' + modeMapGlow + '" />\n</TEXT>\n</OBJECT>';
		customString += '\n</LAYER>\n';
		alert(customString);
		*/
	return customString;
}

// Add custom stuff to Map XML request. . . on top of everything.
function addCustomToMap4(){
	var customString = "";
	
	return customString;
}

// Extract layers to download.
function extractIt() {
	hideLayer("measureBox");
	//alert(msgList[51]);
	alert("PLEASE DON'T DO ANY OPERATIONS After clicking OK! Please wait till 'Retrieving Data' bar gone(<1 minute).  The download link will be shown in the below window.");
    showRetrieveData();
if (checkIfActiveLayerAvailable()) {
   sendExtractRequest();
  }

}


function sendExtractRequest(){
 var extractAXL="";
 //extractAXL += '<?xml version="1.0" encoding="UTF-8"?>\n';
 extractAXL += '<ARCXML version="1.1">\n';
 extractAXL += '<REQUEST>\n';
 extractAXL += ' <GET_EXTRACT>\n';
 extractAXL += '   <PROPERTIES>\n';
 extractAXL += '     <ENVELOPE minx="' + forceComma(eLeft) + '" miny="' + forceComma(eBottom) + '" maxx="' + forceComma(eRight) + '" maxy="' + forceComma(eTop) + '" />\n';
 extractAXL += '       <LAYERLIST>\n';
 extractAXL += '         <LAYERDEF id="' + ActiveLayer + '" visible="true" />\n';
 extractAXL += '       </LAYERLIST>\n';
 extractAXL += '   </PROPERTIES>\n';
 extractAXL += ' </GET_EXTRACT>\n';
 extractAXL += '</REQUEST>\n';
 extractAXL += '</ARCXML>\n';

sendToServer(imsExtractURL, extractAXL ,extractXMLMode);
}


function parseExtractResponse(theResponse){

  var extractURL = getURL(theResponse);
  //alert("The extracted shapefile is located in: " + extractURL);
  if(extractURL!="")
	parent.TextFrame.document.open();
	parent.TextFrame.document.writeln('<html><meta http-equiv="Content-Type" content="text/html; charset=' + charSet + '"><head>');
	//parent.TextFrame.document.writeln('<title>' "Download the shapefile" '</title>');
	parent.TextFrame.document.writeln('</head>');
	parent.TextFrame.document.writeln('<body BGCOLOR="White" TEXT="Black" LEFTMARGIN=0 TOPMARGIN=0>');
	parent.TextFrame.document.writeln('<FONT FACE="Arial" size="-1">');
	parent.TextFrame.document.writeln('<a href="' + extractURL + '">Click here to download the shapefile</A>');
	parent.TextFrame.document.writeln('</FONT>');
	parent.TextFrame.document.writeln('</body></html>');
	parent.TextFrame.document.close()
}



//******************************************************************************
// dsSelectByCircle:
// add custom map click controls here
//******************************************************************************
function customClick(toolName) {
	if (hasLayer("measureBox")) hideLayer("measureBox");
	
	switch(toolName) {
		// select sections by buffering a point
		case "select_circle":
			if (debugOn>3) alert("[function customClick]\n\nselect_circle called...");
			panning=false;
			zooming=false;
			selectBufferClicked=true;
			// select mode - requires aimsSelect.js
			if (canQuery) {
				setCursor("theTop", "crosshair");
				
				toolMode = 1002;
				queryTool=0;
				clickCount=0;
				selectCount = 0;
				//parent.TextFrame.document.location= appDir + "selectByCircle.htm";
				parent.showInDialog(appDir + "selectByCircle.htm");				
				modeName = "Select By Circle";
			} else {
				alert("Cannot query Service\nIdentify, Select, and Query functions are disabled.");
			}
			showGeocode=false;
			showBuffer=false;
			break;

	default:
		alert(msgList[51]);
	}
	if (useModeFrame) writeModeFrame(modeName);
}
//------------------------------------------------------------------------------


//******************************************************************************
// dsSelectByCircle:
// buffer a point
//******************************************************************************
function bufferPoint(e) {
	clearMapParams();
	
	bufferTargetLayerIndex = ActiveLayerIndex;
	bufferTargetLayer = LayerName[bufferTargetLayerIndex];
	//showMarker(mouseX,mouseY,1);
	var theX = mouseX;
	var theY = mouseY;
	getMapXY(theX,theY);
	buffX = mapX;
	buffY = mapY;
	var theString = '<ARCXML version="1.1">\n<REQUEST>\n';
	theString += '<GET_FEATURES outputmode="xml" envelope="true" geometry="false" checkesc="true" featurelimit="500" beginrecord="1">\n';
	theString += '<LAYER id="' + ActiveLayer + '" ftype="' + ActiveLayerType + '" />\n';
	if (debugOn>2) alert ("[function bufferPoint]\n\nActiveLayerID="+LayerID[ActiveLayerIndex]+"\nbufferTargetLayerID="+LayerID[bufferTargetLayerIndex]);
	theString += '<SPATIALQUERY subfields="' + selectFields + '" >\n';
	theString += '<SPATIALFILTER relation="area_intersection">\n';
	theString += '<BUFFER distance="'+bufferDistance+'" smoothedges="2" bufferunits="MILES" />\n';
	theString += '<MULTIPOINT>';
	theString += '<POINT x="'+buffX+'" y="'+buffY+'" />';
	theString += '</MULTIPOINT>\n';
	theString += '</SPATIALFILTER>\n';
	theString += '</SPATIALQUERY>\n';
	theString += '</GET_FEATURES>\n';
	theString += '</REQUEST>\n';
	theString += '</ARCXML>';
	if (debugOn>2) alert("[function bufferPoint]\ntheString="+theString);
	
	sendToServer(imsQueryURL,theString,1002);
}	//end of function bufferPoint
//------------------------------------------------------------------------------


//******************************************************************************
// dsSelectByCircle:
// parse XML response for selected features
//******************************************************************************
function customGetBufferAttributeData(theReply) {
	var docObject = parent.MapFrame;
	var docName = "parent.MapFrame";
	if (!useTextFrame) docName = "opener.parent.MapFrame";
	var Win1;
	setLayerFields(ActiveLayerIndex);
	var str = '<html><meta http-equiv="Content-Type" content="text/html; charset=' + docObject.charSet + '"><head><title>' + docObject.titleList[7] + '</title></head>';
	str += '<body bgcolor="' + docObject.textFrameBackColor + '" text="' + docObject.textFrameTextColor + '" link="' + docObject.textFrameLinkColor + '" vlink="' + docObject.textFrameFormColor + '" LEFTMARGIN=0 onload="window.focus()" onunload="' + docName + '.focusOnData=false">';

	str += writeOutDataPage(theReply,ActiveLayerIndex,docObject,docName,Win1);
	
	str += '</body></html>';
	if (useTextFrame) {
		Win1 = parent.TextFrame;
		Win1.document.open();

	} else {
		Win1 = open("","DataWindow","width=575,height=250,scrollbars=yes,resizable=yes");
		extWin = Win1;
		focusOnData = true;

	}
	Win1.document.writeln(str);
	Win1.document.close();
	hideRetrieveData();
}

//function customGetBufferAttributeData(theReply) {
//	setLayerFields(ActiveLayerIndex);
//	var url = appDir + "displayBufferAttributeData.htm";
//	if (useTextFrame) {
//		parent.TextFrame.document.location = url;
//	} else {
//		var Win1 = open(url,"DataWindow","width=575,height=250,scrollbars=yes,resizable=yes");
//		extWin = Win1;
//		focusOnData = true;
//	}
//	sendMapXML();
//}		// end of function customGetBufferAttributeData
//------------------------------------------------------------------------------


//******************************************************************************
// dsSelectByCircle:
// draw circle around search point at buffer distance
//******************************************************************************
function bufferDrawCircleAroundPt(){
	if (debugOn>3) alert("[function bufferDrawCircleAroundPt]\nbufferDistance="+bufferDistance+"\nbuffX="+buffX+"\nbuffY="+buffY);

	var theCoords="";
	var increment=0.0;
	firstTime=true;
	//distance = bufferDistance * 5280; // for 1 mile = 5280 ft
	distance = bufferDistance * 1609.344;  // for 1 mile = 1609.344 meters


	x = buffX;
	y = buffY;
	while (increment<=350.0) {
		var x1 = x + (distance * Math.cos(increment*Math.PI/180));
		var y1 = y + (distance * Math.sin(increment*Math.PI/180));
		theCoords=theCoords+String(x1)+" ";
		theCoords=theCoords+String(y1)+";";
		if (firstTime) {
			firstString=theCoords;
			firstTime=false;
		}
		increment=increment+10;
	}
	var lastString = firstString.substring(0,firstString.length - 1)
	//alert(lastString);
	theCoords=theCoords+lastString;

	// ArcXML to draw circle object
	var theString = '<LAYER type="ACETATE" id="selRadiusCircle" name="Circle">\n';
	theString += '<OBJECT units="database">\n';
	theString += '<POLYGON coords="'+theCoords+'">\n';
	theString += '<SIMPLEPOLYGONSYMBOL fillcolor="100,100,100" filltype="solid" transparency="0.5" boundarycolor="255,255,255" />\n';
	theString += '</POLYGON>\n';
	theString += '</OBJECT>\n';
	theString += '</LAYER>\n';
	// ArcXML to draw point object in center of circle
	theString += '<LAYER type="ACETATE" id="ptInCircle" name="PointInCircle">\n';
	theString +='<OBJECT units="database">\n';
	theString += '<POINT coords="'+x+' '+y+'">\n';
	theString += '<SIMPLEMARKERSYMBOL color="255,0,0" outline="255,0,0" type="cross" transparency="1.0" width="5" />\n';
	theString += '</POINT>\n';
	theString += '</OBJECT>\n';
	theString += '</LAYER>\n';

	if (debugOn>3) alert("[function bufferDrawCircleAroundPt]\ntheString="+theString);
	return theString;
}		// end of function bufferDrawCircleAroundPt
//------------------------------------------------------------------------------


//******************************************************************************
// dsSelectByCircle:
// draw buffered features
//******************************************************************************
function bufferDrawSelected() {
	
	//alert ("[function bufferDrawSelected]\n\nActiveLayerIndex="+ActiveLayerIndex+"\nselectType="+selectType);
	var theString = '<LAYER type="featureclass" name="theBufferedFeatures" visible="true" >\n';
	theString += '<DATASET fromlayer="' + LayerID[ActiveLayerIndex] + '" />\n'
	theString += '<SPATIALQUERY>\n';
	theString += '<SPATIALFILTER relation="area_intersection" >\n';
	theString += '<BUFFER distance="' + bufferDistance + '" smoothedges="' + bufferSmoothEdges + '" bufferunits="' + ScaleBarUnits + '" />\n';
	theString += '<MULTIPOINT><POINT x="' + buffX + '" y="' + buffY + '" /></MULTIPOINT>\n';
	theString += '</SPATIALFILTER>\n';
	theString += '</SPATIALQUERY>\n';
	theString += '<SIMPLERENDERER>\n';
	if (selectType=="point") {
		theString += '<SIMPLEMARKERSYMBOL color="' + selectColor + '" type="Circle" width="10" />\n';
	} else if (selectType=="line") {
		theString +=' <SIMPLELINESYMBOL type="solid" color="' + selectColor + '" width="3" />\n';
	} else {
		theString += '<SIMPLEPOLYGONSYMBOL fillcolor="' + selectColor + '" filltype="solid" transparency="' + forceComma(transparentLevel) + '" boundary="off" />\n';
	}
	theString += '</SIMPLERENDERER>\n';
	theString += '</LAYER>\n';
	return theString;
}		// end of function bufferDrawSelected
//------------------------------------------------------------------------------
