var idMinX, idMinY, idMaxX, idMaxY;
var idCount = 0;
var selectedId = 1;


var selectXL = false;
var xLClickX = 0;
var xLClickY = 0;


function loadXL(){

	selectXL = true;
	//ActiveLayer = LayerID[ImageLayerIndex];
	setActiveLayer(LayerID[ImageLayerIndex])
	displayToc();

}



function identify(x1, y1){
	var idMins = convertPixelToMap(x1-(pixelTolerance/2), y1+(pixelTolerance/2));
	var idMaxs = convertPixelToMap(x1+(pixelTolerance/2), y1-(pixelTolerance/2));
	idMinX = idMins[0];
	idMinY = idMins[1];
	idMaxX = idMaxs[0];
	idMaxY = idMaxs[1];


     if (mapMode == 'ims')
     {
	   selectedId = 1;
	   //sendIdRequest(true); 
	   sendIdRequest(false); 
     } else if (mapMode == 'wms')
     {
       //GetFeatureInfoRequest(idMinX, idMinY);
       GetFeatureInfoRequest(x1, y1);
     }
	
}



function identifyXL(x1, y1){
	var idMins = convertPixelToMap(x1-(pixelTolerance/2), y1+(pixelTolerance/2));
	var idMaxs = convertPixelToMap(x1+(pixelTolerance/2), y1-(pixelTolerance/2));
	idMinX = idMins[0];
	idMinY = idMins[1];
	idMaxX = idMaxs[0];
	idMaxY = idMaxs[1];
	
 

	//selectedId = 1;
	//sendIdRequest(true); 
}


function convertPixelToMap(px, py){
	var dx = (maxx - minx)/mwidth;
    var drx = Math.round(dx*1000)/1000;
	var mx = parseFloat(minx) + (drx * px);
	var my = parseFloat(miny) + (dx * (mheight - py));
	var newpoint = new Array();
	newpoint[0] = mx;
	newpoint[1] = my;
	
	//alert(mx + "   " + my);
	
	xLClickX = mx;
	xLClickY = my;	
	
	//alert(selectXL);
	return newpoint;

}

function sendIdRequest(countOnly, beginRecord){
	var axl = getIdRequest(countOnly, beginRecord);
	var queryUrl = url + "&CustomService=Query";
	http = getHTTPObject();
	if ((http != null)) {
	    http.open("POST", queryUrl, true);
	    if (countOnly) http.onreadystatechange = parseResultForCount;
	    else http.onreadystatechange = parseResult;
	    isWorking = true;
	    showLayer('loading');
	    //alert(axl);
	    http.send(axl);
  	}

}

function getIdRequest(countOnly, beginRecord){
	var axl = '<?xml version="1.0" encoding="UTF-8"?>';

	axl += '<ARCXML version="1.1">\n<REQUEST>\n<GET_FEATURES geometry="false" outputmode="xml" checkesc ="true" ';
	if(countOnly) axl += 'envelope="false" skipfeatures="true">\n';
	else axl += 'envelope="true" skipfeatures="false" beginrecord="' +  beginRecord + '" featurelimit="1">\n'; 
	axl += '<LAYER id="' + ActiveLayer + '" />';
	axl += '<SPATIALQUERY  subfields="#ALL#" where="">';
	axl += '<SPATIALFILTER relation="area_intersection" >';
	axl += '<ENVELOPE maxy="' + idMaxY + '" maxx="' + idMaxX + '" miny="' + idMinY + '" minx="' + idMinX + '" />';
	axl += '</SPATIALFILTER>';
	axl += '</SPATIALQUERY>';
	axl += '</GET_FEATURES>';
	axl += '</REQUEST>';
	axl += '</ARCXML>';
	//alert("getIdRequest: " + axl);
	return axl;

}

function parseResultForCount(){
	if (http.readyState == 4) {
	    if (http.status == 200) {
	      var result = http.responseText;
	      //alert(result);
	      idCount = getCount(result); 
	      if(idCount != 0) sendIdRequest(false, 1);
	      else alert("No features found");
	     } else alert("Error retreiving data");
	     	          
       }  
}
function parseResult(){
	if (http.readyState == 4) {
	    if (http.status == 200) {
	      var result = http.responseText;
	      //alert(result);
	      processResult(result); 
	      
	     } else alert("Error retreiving data");
		          
       }  
}
function getCount(theReply){
    //alert("getCoun:  " + theReply);
	var theCount;
	var startpos = 0;
	var endpos = 0;
	var pos = theReply.indexOf("FEATURECOUNT");
	var pos1 = theReply.indexOf("count", pos + 12);
	if(pos1 != -1){
		pos1 += 7;
		var pos2 = theReply.indexOf("\"", pos1);
		theCount = parseFloat(theReply.substring(pos1,pos2));
	}
	else theCount=0;
	//alert(theCount);
	hideLayer('loading');
	return theCount;
}

/*
function processResult(theReply){

  //TODO : Use XML DOM parser instead to parse the response
  
  var selectedData = "";
  var endpos = 1;
  var pos = theReply.indexOf("<FIELDS ",endpos);
  if (pos!=-1) {
	var startpos = pos + 8;
	endpos = theReply.indexOf('" />',startpos);
	selectedData = theReply.substring(startpos,endpos);
  }

 if(selectedData != ""){
	var fValue1 = getFieldValues(selectedData);
        var fName1 = getFieldNames(selectedData);

	if (selectXL == true) {

		displayX(fName1, fValue1);
		selectXL = false;
	
	} else {

		displayIdResult(fName1, fValue1);
	
	}
 }
 
 hideLayer('loading');
         
}
*/

function processResult(theReply)  {
 	  var fValue1 =new Array();
      var fName1 =new Array();
      var xmlDoc;
      //alert("processResult: " + theReply);
      // Check for illegal " characters in att values
      var re = new RegExp('[0-9]\"\"', "");
      if (theReply.match(re) != null);
      {
          theReply = theReply.replace(/([0-9])\"\"/g, "$1\"");
      }
      

      if(document.implementation && document.implementation.createDocument) { 
      	// MOZILLA 
       	 xmlDoc = document.implementation.createDocument("", "", null);
      	 xmlDoc.async="false";
         xmlDoc.loadXML(theReply);
      } else if (window.ActiveXObject){
      	 //IE
      	  xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
	      xmlDoc.async="false";
	      xmlDoc.loadXML(theReply);
      }
 
    var flds = xmlDoc.getElementsByTagName("FIELD");
    var flen = flds.length;
    for (var i = 0; i < flen; i++) {
       //var nm = flds[i].item(0).getAttribute("name");
       //var vl = flds[i].item(0).getAttribute("value");
       var nm = flds.item(i).getAttribute("name");
       var vl = flds.item(i).getAttribute("value");
       fName1[i] = nm;
       fValue1[i] = vl;
    }
    
    hideLayer('loading');
 
	if (selectXL == true) {
		displayX(fName1, fValue1);
		selectXL = false;
	} else {
		displayIdResult(fName1, fValue1);
	}
 }
 
 
// 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;";
		fValue1[f] = v[1];
	}
	return fValue1;
}




function displayX(fName1, fValue1){

 	//alert(fValue1[ImageNameFieldOrder]);
 	
 	
 	
 	//xLClickX
 	//loadLookingGlass(fValue1[ImageNameFieldOrder]);
 	
 	
  	//loadLookingGlass(fValue1[ImageNameFieldOrder], xLClickX, xLClickY);
 
}




function displayIdResult(fName1, fValue1){
 var idContent =  "<table class='idTitleBarClass'>";
 idContent += "<tr onmousedown='startMove(event, \"IdResult\")'>";
 idContent += "<td width='95%'><font class='idTitleClass'>Identify Results</font></td>";
 idContent += "<td align='right' width='5%'> <img onmousedown='hideLayer(\"IdResult\");' src='images/close.gif'></td>";
 idContent += "</tr>";
 idContent += "</table>";
 
 idContent += "<table width='100%' cellspacing='5' cellpadding='5'>";
 idContent += "<tr>";
 //idContent += "<table width='100%' cellspacing='5' cellpadding='5'>";
 idContent += "<td class='idNonTitleClass'>Identify Layer : " + LayerName[ActiveLayerIndex] + "<br> Total Count : " + idCount;
 idContent += "</td>";
 idContent += "</tr>";
 
 idContent += "<tr> <td>";
 idContent += "<table border='1' cellpadding='0' cellspacing='2' width='100%'>";
 idContent += "<tr valign='top'>";
 idContent += "<td width='20%'>";
 idContent += "<table border='0' width='100%'>";
 idContent += "<tr class='headerRow'>";
 idContent += "<td>Record Num</td>";
 idContent += "</tr>";
 idContent += "</table>";
 idContent += "<div style='overflow:auto;height:295px;border-width:1px;'>";
 idContent += "<table width='100%' cellpadding='0' cellspacing='0'>";
 for (var i=1;i<=idCount;i++){
 	idContent += " <tr>";
 	idContent += "<td align='middle'>";
 	if(i==selectedId) idContent += "<span class='selectedIdClass'> " + i + "</span>";
 	else {
 		idContent += "<a href='#' onclick='setSelectedId(" + i + ");sendIdRequest(false," + i + " );return false;' style='color:black;font-size:12px;font-family:Arial, Verdana, Helvetica, sans-serif;'>";
 		idContent += "<font class='unselectedIdClass'>" + i + "</font></a>";
 	}
 idContent += "</td></tr>";
 }
 idContent += "</table>"; 
 idContent += "</div>";

 idContent += "</td>";
 idContent += "<td>";
 
 idContent += "<div style='overflow:auto;height:310px;border-width:1px;'>";
 idContent += "<table width='100%' cellpadding='0' cellspacing='0'>";
 idContent += "<tr>";
 idContent += "<td>";
 idContent += "<table cellspadding='0' cellspacing='2' width='100%'>";
 idContent += "<tr>";
 idContent += "<td class='headerRow'><b>Field</b></td><td class='headerRow'><b>Value</b></td>";
 idContent += "</tr>";
 for (var ii=0;ii<fValue1.length;ii++){

 	var evenOdd;
 	if((ii%2) == 0) evenOdd = "evenRow";

 	else evenOdd = "oddRow";

 	idContent += "<tr valign='top'>";
 	idContent += "<td class='" + evenOdd + "'><b>" + fName1[ii] + "</b></td><td class='" + evenOdd + "'>" + fValue1[ii] + "</td>";
 	idContent += "</tr>";
 }
 idContent += "</table>";
 idContent += "</td>";
 idContent += "</tr>";
 idContent += "</table>";
 idContent += "</div>";
 idContent += "</td>";
 idContent += "</tr>";
 idContent += "</table>";
 idContent +="</td>";
 idContent += "</tr>";
 idContent += "<tr>";
 idContent += "<td align='right'><input value='Close' onmousedown='hideLayer(\"IdResult\");' type='button' id='CloseButton' name='CloseButton'></td>";
 idContent += "</tr>";
 idContent += "</table>";
 updateContent('IdResult', idContent);
 showLayer('IdResult');
}

function setSelectedId(indx){
	selectedId = indx;
}
