//******************************************************************************************************************
//
// USGS Download Extract File Creation 
// Created By:  Jennifer Ming
// Installation:
//   01.  Copy USGS_DL_Rect.js into the javascript directory of the HTML Viewer
//
//   02.  Add the following line to MapFrame.htm 
//	  <script type="text/javascript" language="JavaScript" src="javascript/USGS_DL_Rect.js"></script>
//
//   03.  Copy the selection.htm file into the main HTML viewer directory 
//        (IE: same directory mapframe.htm is in...)
//
//   04.  Copy the select_rect_1.gif and select_rect_2.gif into the usgs_images folder.
//
//   05.  Add the following lines to USGS_Toolbar.js: MakeUSGSToolbar()      
//	  if (parent.MapFrame.useDownloadRect)  { miscCount++; }
//
//   06.  Add the following lines to USGS_Toolbar.js: MakeUSGSToolbar()       
//	  if (parent.MapFrame.useDownloadRect) {
//
//        	if (parent.MapFrame.modeName == "Download Rectangle") {
//          	  LocalString += WriteButton( MakeButton2( "usgs_images/select_rect_2.gif", 'Select by rectangle', "downloadrect", 'parent.MapFrame.modeName=\'Download Rectangle\'; parent.MapFrame.downloadRectangle();', "status=\' Select by rectangle\';", "", true ) );
//        	} else {
//          	  LocalString += WriteButton( MakeButton2( "usgs_images/select_rect_1.gif", 'Select by rectangle', "downloadrect", 'parent.MapFrame.modeName=\'Download Rectangle\'; parent.MapFrame.downloadRectangle();', "status=\' Select by rectangle\';", "", true ) );
//        	}
//          	  buttonCol++;
//          	  LocalString += Table_Structure(buttonCol,miscCount);
//	  }
//
//    07. Add the following lines to aimsClick.js: clickFunction() - Make the additions near the top of the
//        function, before the switch statement and after the 'if block' for measureBox
//
//    	  if ( (toolName!="downloadrect") && (toolName!="fullextent") ) {
//        	hideLayer("xBoxTop");
//        	hideLayer("xBoxLeft");
//       	hideLayer("xBoxRight");
//       	hideLayer("xBoxBottom");
//	
//       	xTop = eTop;
//        	xBottom = eBottom;
//        	xRight = eRight;
//        	xLeft = eLeft;
//    	  }
//
//    08. Add the following lines to USGS_DL_Single.js, USGS_DL_Mult.js,USGS_Elevation_Service.js, USGS_Gazetter_Service.js and USGS_USNG_Service.js.      
//        In USGS_Elevation_Service.js:setElevationTool() make the additions near the top of the
//            function after the 'if block' for measureBox.  
//        In USGS_Gazateer_Service.js:getGazateer() make the additions at the top of the function
//        In USGS_USNG_Service.js:setusngTool() make the additions near the top of the
//            function after the 'if block' for measureBox.  
//
//        	hideLayer("xBoxTop");
//        	hideLayer("xBoxLeft");
//       	hideLayer("xBoxRight");
//       	hideLayer("xBoxBottom");
//
//
//   09.  Add the following lines to aimsClick.js: chkMouseUp(e)
//	  if ((toolMode == 1204) && (xBox)) {
//			//alert("aimsClick : toolmode : " + modeBlurb);
//			stopSelectExBox(e);
//	  }	
//
//   10.  Add the following lines to aimsClick.js:MapTool()
//				case 1204:
//			                //alert("aimsClick : case 1204 : " + modeBlurb);
//					//Download Rect
//					startSelectExBox(e);
//					return false;
//					break; 
//
//    11.  Remove these lines in file MapFrame.htm: 
//
//              <script type="text/javascript" language="JavaScript" src="javascript/aimsCustom.js"></script>
//              <script type="text/javascript" language="JavaScript" src="javascript/aimsClick.js"></script>
//		<script type="text/javascript" language="JavaScript" src="javascript/aimsNavigation.js"></script>
//   
//    12.  Add the following lines into MapFrame.htm
//
//              <script type="text/javascript" language="JavaScript" src="javascript/aimsCustom.js"></script>
//              <script type="text/javascript" language="JavaScript" src="javascript/aimsClick.js"></script>
//		<script type="text/javascript" language="JavaScript" src="javascript/aimsNavigation.js"></script>             
//    13.  Add the following lines to MapFrame.htm after // set zoom box color
//
//                //  xBox selection box
//                content = '<img name="xImageTop" src="images/pixel.gif" width=1 height=1 alt="Top extent of order box">';
//                createLayer("xBoxTop",0,0,sWidth,sHeight,false,content);
//                content = '<img name="xImageLeft" src="images/pixel.gif" width=1 height=1 alt="Left extent of zoom box">';
//                createLayer("xBoxLeft",0,0,sWidth,sHeight,false,content);
//                content = '<img name="xImageRight" src="images/pixel.gif" width=1 height=1 alt="Right extent of zoom box">';
//                createLayer("xBoxRight",0,0,sWidth,sHeight,false,content);
//                content = '<img name="xImageBottom" src="images/pixel.gif" width=1 height=1 alt="Bottom extent of zoom box">';
//                createLayer("xBoxBottom",0,0,sWidth,sHeight,false,content);
//                
//                // set xBox box color
//                setLayerBackgroundColor("xBoxTop", xBoxColor);
//                setLayerBackgroundColor("xBoxLeft", xBoxColor);
//                setLayerBackgroundColor("xBoxRight", xBoxColor);
//                setLayerBackgroundColor("xBoxBottom", xBoxColor);
//
//    14.  Change the following line to aimsNavigation.js: mouseStuff()
//         if ((zooming) || (selectBox)) { to if ((zooming) || (selectBox) || (xBox)) {
//
//    15.  Add the following lines to aimsNavigation.js: setClip()
//        if (xBox) {
//            if ((x1 != x2) && (y1 != y2)) {
//                xboxIt(zleft,ztop,zright,zbottom);
//            }
//        } else {
//                ... ------old line: if ((x1 != x2) && (y1 != y2)) {boxIt(zleft,ztop,zright,zbottom); }
//        }
//
//
//    16. Add the following lines into ArcIMSparam.js
//	//var reqMachineURL = 'http://edcw2w036.cr.usgs.gov/';  //for production
//	var reqMachineURL = 'http://edcw2w064.cr.usgs.gov/';    
//******************************************************************************************************************
//
// useDownloadRect determines if the toolbar should show this button or not.
var useDownloadRect=true;
var xBoxColor = '#00FF00'; //green color
var xBox=false;

//  Variables to control the color of the rubberbanding selection box.  
//  If any of these values change, make the same changes in RequestSummary.jsp
var maxOrderMB = 1500; 

//for distributed download
var MBperSqDeg = 65;  // This is the initial value. The value should be changed when default products are changed. 
var featIDArray = new Array();

function downloadRectangle() {


	    panning=false;
	    zooming=false;
	    selectBox=false;
            showCONUSfootprints = false;
            showALASKAfootprints = false;

            parent.MapFrame.featIDArray.length = 0;
            
		// select mode - requires aimsSelect.js
                //alert("in here");
		if (canQuery) {
			toolMode = 1204;              //aimsClick.js maptool()
			queryTool=0;
			clickCount=0;
			showBuffer=false;
			if (isIE)	{
				document.all.theTop.style.cursor = "crosshair";
				theCursor = document.all.theTop.style.cursor;
			}

			modeBlurb = "Extract Box";
		} else {
			alert(msgList[46]);
		}
		//alert("Loading text.htm into Textframe");
		showGeocode=false;
		if (useTextFrame) parent.TextFrame.document.location= appDir + "selection.htm";
		hideLayer("measureBox");

}


// start select extract box display
function startSelectExBox(e) {

	        //alert("aimsSelect : startSelectExBox1 : " + mouseX);
		moveLayer("theMap",hspc,vspc);
		getImageXY(e);
		// keep it within the MapImage
		if ((mouseX<iWidth) && (mouseY<iHeight)) {
		//alert("aimsSelect : startSelectExBox2 : " + xBox);
			if (xBox) {
				stopSelectExBox(e);
			} else {
				//alert("aimsSelect : startSelectExBox3 : " + xBox);
                                
                                //xBoxColor = '#00FF00';
				x1=mouseX;
				y1=mouseY;
				x2=x1+1;
				y2=y1+1;
				zleft=x1;
				ztop=y1;
				zbottom=y1;
				zright=x1;

				//parent.MapFrame.document.modeBlurb = "Area: " + vta;
				//selectBlurb=vta;

				xboxIt(x1,y1,x2,y2);
				//var vty=y2-y1;
				//var vtx=x2-x1;
				//var vta=vtx * vty;
				//if (vta>30.0) {
				//   Alert("Over 30 : " + vta);
				//}

				/*
				clipLayer("xBoxTop",x1,y1,x2,y2);
				clipLayer("xBoxLeft",x1,y1,x2,y2);
				clipLayer("xBoxRight",x1,y1,x2,y2);
				clipLayer("xBoxBottom",x1,y1,x2,y2);
				*/
				xBox=true;

				//if (isNav4) {
					showLayer("xBoxTop");
					showLayer("xBoxLeft");
					showLayer("xBoxRight");
					showLayer("xBoxBottom");
				//} else {
				//	showLayer("xBox");
				//}
			}
			highlightedOne="";
		}
		return false;


}

// stop select Extract box display..... select
function stopSelectExBox(e) {
	//alert("aimsSelect : stopSelectExBox : " + mouseX);
	xBox=false;
	/*
	var tempLeft=lastLeft;
	var tempRight=lastRight;
	var tempTop=lastTop;
	var tempBottom=lastBottom;
	*/
	//if (isNav4) {
		//hideLayer("xBoxTop");
		//hideLayer("xBoxLeft");
		//hideLayer("xBoxRight");
		//hideLayer("xBoxBottom");
	//} else {
	//	showLayer("xBox");
	//}
	// /*
	if ((zright <zleft+2) && (zbottom < ztop+2)) {
		
		//getMapXY(mouseX-pixelTolerance,mouseY-pixelTolerance);
		getMapXY(mouseX,mouseY);
		searchTolerance = (xDistance/iWidth) * pixelTolerance;
		tempLeft = mapX-searchTolerance;
		tempTop = mapY-searchTolerance;
		tempRight = mapX+searchTolerance;
		tempBottom = mapY+searchTolerance;
		
		//select(e);
	} else {
	// */	
		pixelX = xDistance / iWidth;
		var theY = iHeight - ztop;
		pixelY = yDistance / iHeight;
		tempTop = pixelY * theY + eBottom;
		tempRight = pixelX * zright + eLeft;
		tempLeft = pixelX * zleft + eLeft;
		theY = iHeight - zbottom;
		pixelY = yDistance / iHeight;
		tempBottom = pixelY * theY + eBottom;
	}
		window.scrollTo(0,0);


		// We want to send along the list of layers to download....
		var theLayers = "&PL=";
		theLayers = theLayers + parent.MapFrame.getDownloadLayerList();
		//alert("theLayers" + theLayers);

		/*
		if (parent.MapFrame.Download_SRC_Layer_Checked[101]) theLayers = theLayers + "NED,";
		if (parent.MapFrame.Download_SRC_Layer_Checked[102]) theLayers = theLayers + "NEDHR,";
		if (parent.MapFrame.Download_SRC_Layer_Checked[103]) theLayers = theLayers + "SRTM,";
		if (parent.MapFrame.Download_SRC_Layer_Checked[104]) theLayers = theLayers + "SRTM90M,";
		if (parent.MapFrame.Download_SRC_Layer_Checked[201]) theLayers = theLayers + "NLCD,";
		if (parent.MapFrame.Download_SRC_Layer_Checked[202]) theLayers = theLayers + "MOD0,";
		if (parent.MapFrame.Download_SRC_Layer_Checked[203]) theLayers = theLayers + "MOD1,";
		if (parent.MapFrame.Download_SRC_Layer_Checked[204]) theLayers = theLayers + "MOD2,";
		if (parent.MapFrame.Download_SRC_Layer_Checked[205]) theLayers = theLayers + "MOD3,";
		if (parent.MapFrame.Download_SRC_Layer_Checked[206]) theLayers = theLayers + "MOD4,";
		if (parent.MapFrame.Download_SRC_Layer_Checked[207]) theLayers = theLayers + "MOD5,";
		if (parent.MapFrame.Download_SRC_Layer_Checked[208]) theLayers = theLayers + "MOD6,";
		if (parent.MapFrame.Download_SRC_Layer_Checked[301]) theLayers = theLayers + "OCHIP,";
		if (parent.MapFrame.Download_SRC_Layer_Checked[401]) theLayers = theLayers + "VECBTSR,";
		*/

		// If nothing is selected, don't send the request summary page any product list.  It will assume all porducts selected.
		if (theLayers == "&PL=") theLayers = "";
		

                selectEnvelope='maxy="' + tempTop + '" maxx="' + tempRight + '" miny="' + tempBottom + '" minx="' + tempLeft + '"';
                //alert("maxy=" + tempTop + " maxx=" + tempRight + " miny=" + tempBottom + " minx=" + tempLeft);
                xTop = tempTop;
                xRight = tempRight;
                xBottom = tempBottom;
                xLeft = tempLeft;
		var vy = tempTop - tempBottom;
		var vx = tempRight - tempLeft;
		var va = vx * vy;
	        //alert("aimsSelect : stopSelectExBox : Extract box done  [Area = " + va + "]");


		var vy2=Math.abs(tempTop-tempBottom);
		var vx2=Math.abs(tempRight-tempLeft);
		var va2=vx2*vy2;
                var randNum = Math.round( Math.random() * 2000 );
                var windowName = "winName" + randNum;
                
		if ((va2 * MBperSqDeg) > maxOrderMB) {
		/*
		   var mediaOK = confirm("The area selected exceeds the maximum downloadable area. Click OK to place a Media order, or Cancel to go back to map.");
		   if (mediaOK) {
		      var summaryURL= parent.MapFrame.reqMachineURL + "Website/distreq/waiting.jsp?areaList=" + xTop + "," + xBottom + "," + xRight + "," + xLeft + theLayers;
		      //alert("aimsSelect : stopSelectExBox : Extract box done  [Area = " + va2 + "]");
                      window.open(summaryURL, windowName, "height=600,width=800,scrollbars,resizable,location, menubar,status,toolbar");
		   }
		*/
		alert("The area selected exceeds the maximum downloadable area. Click OK to select a smaller downloadable area.");

		} else {

		      var summaryURL= parent.MapFrame.reqMachineURL + "Website/distreq/RequestSummary.jsp?AL=" + xTop + "," + xBottom + "," + xRight + "," + xLeft + theLayers + "&DB=true";

		      //alert("aimsSelect : stopSelectExBox : Extract box done  [Area = " + va2 + "]");
                      window.open(summaryURL, windowName, "height=600,width=800,scrollbars,resizable,location, menubar,status,toolbar");
		}

		//alert("URL: " + summaryURL);

                return true;




	//queryStartRecord=1;
	//var theString = writeGetFeatures2(tempLeft,tempBottom,tempRight,tempTop);
	//selectEnvelope='maxy="' + forceComma(tempTop) + '" maxx="' + forceComma(tempRight) + '" miny="' + forceComma(tempBottom) + '" minx="' + forceComma(tempLeft) + '"';
	//drawSelectBoundary=true;
	//showBuffer=false;
	//selectionMode=2;
	////if (useTextFrame) parent.TextFrame.document.location = "text.htm";
	//sendToServer(imsQueryURL,theString,selectXMLMode);


}

function xboxIt(theLeft,theTop,theRight,theBottom) {
		if (!isNav4) {
			theTop = theTop + vspc;
			theBottom = theBottom + vspc;
			theLeft = theLeft + hspc;
			theRight = theRight + vspc;
		}
		//alert("L: " + theLeft);
		//alert("T: " + theTop);
		//alert("R: " + theRight);
		//alert("B: " + theBottom);

		pixelX = xDistance / iWidth;
		var theY = iHeight - ztop;
		pixelY = yDistance / iHeight;
		tTop = pixelY * theY + eBottom;
		tRight = pixelX * zright + eLeft;
		tLeft = pixelX * zleft + eLeft;
		theY = iHeight - zbottom;
		pixelY = yDistance / iHeight;
		tBottom = pixelY * theY + eBottom;

		var vy=Math.abs(tTop-tBottom);
		var vx=Math.abs(tRight-tLeft);
		var va=vx*vy;

		if ((va * MBperSqDeg) > maxOrderMB) {
		   xBoxColor='#FF0000';
		} else {
		   xBoxColor='#00FF00';
		}
                setLayerBackgroundColor("xBoxTop", xBoxColor);
                setLayerBackgroundColor("xBoxLeft", xBoxColor);
                setLayerBackgroundColor("xBoxRight", xBoxColor);
                setLayerBackgroundColor("xBoxBottom", xBoxColor);
		clipLayer("xBoxTop",theLeft,theTop,theRight,theTop+ovBoxSize);
		clipLayer("xBoxLeft",theLeft,theTop,theLeft+ovBoxSize,theBottom);
		clipLayer("xBoxRight",theRight-ovBoxSize,theTop,theRight,theBottom);
		clipLayer("xBoxBottom",theLeft,theBottom-ovBoxSize,theRight,theBottom);	
		showLayer("xBoxTop");
		showLayer("xBoxLeft");
		showLayer("xBoxRight");
		showLayer("xBoxBottom");
}