// aimsExtract.js
/*
*  JavaScript template file for ArcIMS HTML Viewer Extract Sample
*		dependent on aimsXML.js, ArcIMSparam.js, aimsCommon.js, aimsMap.js, aimsIdentify.js, aimsSelect.js, and aimsLayers.js
*		To be interactive, dependent also on aimsDHTML.js, aimsClick.js, and aimsNavigation.js
*
*		It is assumed that the Image MapService will have the appropriate paramaters set up in the axl file for extraction. . .
*		Add the following lines in the MapService axl file in one of the layers' definitions:
*      		<EXTENSION type="extract" >
*        		<EXTRACTPARAMS clip="true" >
*        		</EXTRACTPARAMS>
*     		</EXTENSION>
*
*		Only one <EXTENSION type="extract"> tag set is required for the Extract functionality to be enabled
*
*		The output directory and URL are defined in the mapservice configuration.
*
*		Only the layers visible within the current extent will be extracted.
*		The active layer can be further filtered by selection or query. 
*
*		Image layers cannot be extracted. Only feature-type layers can be extracted.
*
*/

aimsExtractPresent=true;

var ex_totLayers = 0;
var ex_xLayers = new Array();

// this variable added for Extract MapService
var extractURL = imsURL + "&CustomService=Extract";

//INIZIO - Baco Extract : GeDeONE 1.2.0.
var HaMaxScale= false;
//FINE - Baco Extract : GeDeONE 1.2.0.



// extract layers to download
	// overrides function in aimsCustom.js
function ex_extractIt() {
	hideLayer("measureBox");
	//alert("Extract function here");
	ex_totLayers = 0;
	var estr_lyr = ActiveLayerIndex;

	var Win1 = parent.TextFrame;
	var theFrame = "parent.MapFrame";
	if ((useExternalWindow) || (!useTextFrame)) {
		Win1 = window.open("","ExtractWindow","width=575,height=120,scrollbars=yes,resizable=yes");
		theFrame = "opener";
		if (parent.MapFrame!=null) theFrame = "opener.parent.MapFrame";
	} else {
		Win1 = parent.TextFrame;
		Win1.document.open();
	}
	Win1.document.open();
	Win1.document.writeln('<html><meta http-equiv="Content-Type" content="text/html; charset=' + charSet + '"><head><link rel="stylesheet" href="'+pagStile+'" type="text/css">');		
	Win1.document.writeln('<title>' + extractList[0] + '</title></head>');
   Win1.document.writeln('<body  LEFTMARGIN=10 TOPMARGIN=5 onload="window.focus()">');
	Win1.document.writeln('<FONT SIZE="-1"><b><center>' + extractList[1] + '</b></center><br>');
	Win1.document.writeln('<DIV ALIGN="center"><table width="50%" border="0" cellspacing="2" cellpadding="2" nowrap>');
	
	//INIZIO - Baco Extract : GeDeONE 1.2.0.          
	if (LayerMaxScale[estr_lyr]=='1.7976931348623157E308'){
		HaMaxScale=false;
	}else{
		HaMaxScale=true;
	}
	//FINE - Baco Extract : GeDeONE 1.2.0.
	
	if ((mapScaleFactor>=LayerMinScale[estr_lyr]) && (mapScaleFactor<=LayerMaxScale[estr_lyr])) {
	   if (LayerIsFeature[estr_lyr]) {
				if (LayerVisible[estr_lyr]) {
				   if (ExtractLayer[estr_lyr]){		
				      ex_xLayers[0]= ActiveLayerIndex;     
		            Win1.document.writeln('<form>');
			         Win1.document.writeln('<tr><td>');
                  Win1.document.writeln(LayerName[estr_lyr] + '<br>');
			         Win1.document.writeln('</td><td>');
			         Win1.document.writeln('<input type="button" class=background value="' + extractList[2] + '" onclick="' + theFrame + '.ex_extractTheLayers()">');			
			         Win1.document.writeln('</td></tr>');
			         Win1.document.writeln('</form>');
			      } else {
		            Win1.document.writeln('<tr><td>'+extractList[9]+'</font></td></tr>');
		         }		         
			   } else {
			      Win1.document.writeln('<tr><td>'+extractList[3]+'</font></td></tr>');
			   }
			} else {
			   Win1.document.writeln('<tr><td>'+extractList[10]+'</font></td></tr>');
			}
		} else {
		   Win1.document.writeln('<tr><td>'+extractList[4]+'</font></td></tr>');
		}
		
		Win1.document.writeln('<tr><td>'+extractList[5]+'</td><td>Xmin: ' + eLeft + ',<br>Xmax: ' + eRight + ',<br>Ymin: ' + eBottom + ',<br>Ymax: ' + eTop + '</td></tr>');
		Win1.document.writeln('</table>');
		Win1.document.writeln('</DIV>');
		Win1.document.writeln('</body></html>');
		Win1.document.close();	
}



function ex_writeExtractXML() {
   var Coordinate =LayerExtent[ActiveLayerIndex]; 
   
   pos = Coordinate.indexOf("|");
   var xmin=(Coordinate).substr(0,pos);
   Coordinate=Coordinate.substr(pos+1,Coordinate.length);
 
   pos = Coordinate.indexOf("|");
   ymin=(Coordinate).substr(0,pos);
   Coordinate=Coordinate.substr(pos+1,Coordinate.length);
   
   pos = Coordinate.indexOf("|");
   xmax=(Coordinate).substr(0,pos);
   Coordinate=Coordinate.substr(pos+1,Coordinate.length);
  
   pos = Coordinate.indexOf("|");   
   ymax=Coordinate.substr(pos+1,Coordinate.length);
   		
	var eString = '<ARCXML version="1.1">\n';
	eString += '<REQUEST>\n<GET_EXTRACT>\n<PROPERTIES>\n';

//INIZIO - Baco Extract : GeDeONE 1.2.0. 
//eString += '<ENVELOPE minx="' + xmin + '" miny="' + ymin +'" maxx="' + xmax + '" maxy="' + ymax + '" />\n';
if (HaMaxScale==false){
	//alert('Senza max scale');
	eString += '<ENVELOPE minx="' + xmin + '" miny="' + ymin +'" maxx="' + xmax + '" maxy="' + ymax + '" />\n';
}else{
	//alert('con max scale');
 	eString += '<ENVELOPE minx="' + forceComma(eLeft) + '" miny="' + forceComma(eBottom) +'" maxx="' + forceComma(eRight) + '" maxy="' + forceComma(eTop) + '" />\n';
}

//FINE - Baco Extract : GeDeONE 1.2.0. 		
	
	eString += '<IMAGESIZE height="' + iHeight + '" width="' + iWidth + '" />\n';
	eString += '<LAYERLIST>\n';
	
	for (var j=0;j<LayerID.length;j++) {
		eString += '<LAYERDEF id="' + LayerID[j] + '" ';
		var k=-1;
		for (var m=0;m<ex_xLayers.length;m++) {
			if (parseInt(ex_xLayers[m])==j) k=j;
		}
		if (k>-1) {
			eString += 'visible="true"';
			if (k==ActiveLayerIndex) {
				var addString = ex_addSelectToExtractRequest();
				if (addString!="") {
					eString += '>\n' + addString + '</LAYERDEF>\n';
				} else {
					eString += '/>\n';
				}
			} else {
				eString += '/>\n';
			} 
		} else {
			eString += 'visible="false"/>\n';
		}
	}
	eString += '</LAYERLIST>\n';
	eString += '</PROPERTIES>\n</GET_EXTRACT>\n</REQUEST>\n';
	eString += '</ARCXML>\n';
	return eString;
}

function ex_extractTheLayers() {
	showRetrieveData();
	var theString = ex_writeExtractXML();
	
	ex_sendExtractRequest(theString, 4001);
}

function ex_addSelectToExtractRequest() {
	var selString = "";
	var sFactor = (eRight-eLeft) / iWidth
	if ((sFactor>=LayerMinScale[ActiveLayerIndex]) && (sFactor<=LayerMaxScale[ActiveLayerIndex]) && (LayerVisible[ActiveLayerIndex]==1)) {
		if (selectCount>0) {
			if (selectionMode==1) {
				selString +='<SPATIALQUERY  where="' + setQueryString + '"';
				if (useLimitExtent) {
					// keep this within the limitExtent
					
					selString +='>\n<SPATIALFILTER relation="area_intersection">\n';
					selString +='<ENVELOPE maxx="' + forceComma(limitRight) + '" maxy="' + forceComma(limitTop) + '" minx="' + forceComma(limitLeft) + '" miny="' + forceComma(limitBottom) + '" />\n';
					selString +='</SPATIALFILTER>\n';
					selString +='</SPATIALQUERY>\n';
				} else {
				selString +='/>\n';
				}
			
			} else {
				selString +='<SPATIALQUERY>\n';
				selString +='<SPATIALFILTER relation="area_intersection" >\n';
				if (selectionMode==2) {
					selString +='<ENVELOPE ' + selectEnvelope + ' />\n';
				} else {
					if ((shapeSelectBuffer) && (shapeBufferDistance>0)) {
					//if (shapeBufferDistance>0) {
						// do a buffer around the shape before selecting
						var smoothEdge = shapeBufferDistance  * 0.01;
						selString += '<BUFFER distance="' + forceComma(shapeBufferDistance) + '" ';
						//selString += 'smoothedges="' + smoothEdge + '"';
						selString += ' bufferunits="' + ScaleBarUnits + '"';
						selString += ' />\n';
					}
					if (clickType==2) {
						selString +='<POLYLINE>\n<PATH>\n';
					} else if (clickType==3) {
						selString +='<POLYGON>\n<RING>\n';
					} else {
						selString +='<MULTIPOINT>\n';
					}
					if (clickType==1) {
						selString +='<POINT x="' + forceComma(clickPointX[clickCount-1]) + '" y="' + forceComma(clickPointY[clickCount-1]) + '" />\n';
					} else {
						for (var i=0;i<clickCount;i++) {
							selString +='<POINT x="' + forceComma(clickPointX[i]) + '" y="' + forceComma(clickPointY[i]) + '" />\n'; 
						}
					}
					if (clickType==3) {
						//selString +='<POINT x="' + clickPointX[0] + '" y="' + clickPointY[0] + '" />\n';
						selString +='</RING>\n</POLYGON>\n';
					} else if (clickType==2) {
						selString +='</PATH>\n</POLYLINE>\n';
					} else {
						selString +='</MULTIPOINT>\n';
					}
				}
				selString +='</SPATIALFILTER>\n';
				///*
				if (useLimitExtent) {
					// keep this within the limitExtent
					selString +='<SPATIALFILTER relation="area_intersection">\n';
					selString +='<ENVELOPE maxx="' + forceComma(limitRight) + '" maxy="' + forceComma(limitTop) + '" minx="' + forceComma(limitLeft) + '" miny="' + forceComma(limitBottom) + '" />\n';
					selString +='</SPATIALFILTER>\n';
				} 
				//*/
				selString +='</SPATIALQUERY>\n';
			}
		}
		//Inizio MultiSelect :  MUS
		else{
			if (parent.MapFrame.highlightedOne!=''){
				selString +='<QUERY where="';
				selString +=highlightedOne;
				selString +='"/>';
			}
		}
		//File MultiSelect 
	}
	return selString;
}

function ex_showExtractURL(theReply) {
	hideRetrieveData();	
	var Win1 = parent.TextFrame;
	var theFrame = "parent.MapFrame";
	if ((useExternalWindow) || (!useTextFrame)) {
		Win1 = window.open("","ExtractWindow","width=575,height=120,scrollbars=yes,resizable=yes");
		theFrame = "opener";
		if (parent.MapFrame!=null) theFrame = "opener.parent.MapFrame";
	} else {
		Win1 = parent.TextFrame;
		Win1.document.open();
	}
	Win1.document.open();
	Win1.document.writeln('<html><meta http-equiv="Content-Type" content="text/html; charset=' + charSet + '"><head>');
	Win1.document.writeln('<link rel="stylesheet" href="'+pagStile+'" type="text/css"><title>' + extractList[0] + '</title></head>');
	Win1.document.writeln('<body LEFTMARGIN=10 TOPMARGIN=5 onload="window.focus()">');
	Win1.document.writeln('<form><FONT SIZE="-1"><center><b>');
	var pos = theReply.indexOf("OUTPUT");
	var theURL = "";
	if (pos != -1) {
		Win1.document.writeln(extractList[6] + '&nbsp;&nbsp;&nbsp;&nbsp;');
		theURL = getInsideString(theReply,'url="',dQuote,pos,0,false);
		Win1.document.writeln('<a href="' + theURL + '">' + extractList[7] + '</A>');
	} else {
		Win1.document.writeln(extractList[8]);
	}
	Win1.document.writeln('</b></center></font></form></body></html>');
	Win1.document.close();
	
	
}

// send custom XML request. . . set up custom response handler
function ex_sendExtractRequest(XMLRequest, theType) {
	var theFunction = "parent.MapFrame.ex_processExtractXML";
	var theForm = parent.PostFrame.document.forms[0];
	theForm.JavaScriptFunction.value = theFunction;	
	sendToServer(extractURL,XMLRequest,theType)
}

function ex_processExtractXML(theReplyIn) {
	theReplyIn = replacePlus(theReplyIn);
	var theReply = unescape(theReplyIn);
	okToSend = true;
	if (debugOn>2) alert(msgList[13] + theReply);
	var theError = getXMLErrorMessage(theReply);
	if (XMLMode == 4001) {
		//alert("XMLMode=4001\n" + theReply);
		ex_showExtractURL(theReply);
	
	}
	if (XMLMode == 4002) {
		alert("XMLMode=4002");
	
	}
}
