var idMinX, idMinY, idMaxX, idMaxY;
var idCount = 0;
var selectedId = 1;
var queryStartRecord=1;
var recSave=1;
var cList = new Array();
var curRec=0;

function identify(x1, y1){
	//offset for message div position
	x1 = x1 + mapleft;
	y1 = y1 + maptop;
	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;
	queryStartRecord=1;
	sendIdRequest(true); 
}

function convertPixelToMap(px, py){
	var dx = (maxx - minx)/mwidth;
	var mx = minx + (dx * px);
	var my = miny + (dx * (mheight - py));
	var newpoint = new Array();
	newpoint[0] = mx;
	newpoint[1] = my;
	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;
	    showLayer('loading');
	    //alert(axl);
	    http.send(axl);
  	}

}

function getIdRequest(countOnly, beginRecord){
	var axl = '<?xml version="1.0" encoding="UTF-8"?>\n';
	axl += '<ARCXML version="1.1">\n<REQUEST>\n<GET_FEATURES geometry="false" outputmode="xml" checkesc ="true" ';
	if(countOnly) axl += 'envelope="false" skipfeatures="true" featurelimit="'+maxFeat+'">\n';
	else axl += 'envelope="true" skipfeatures="false" beginrecord="' +  beginRecord + '" featurelimit="'+maxFeat+'">\n'; 
	axl += '<LAYER id="0" />\n';
	if (crimelist != "") {
		axl += '<SPATIALQUERY where="' + crimelist + '" subfields="' + selectFields + '">\n';
	} else {	//PREVENT ID OF INCIDENTS THAT ARE NOT PART OF A VALID QUERY
		axl += '<SPATIALQUERY where="CATEGORY=&apos;DONOTSHOWTHESE&apos;" subfields="' + selectFields + '">\n';
	}
	axl += '<SPATIALFILTER relation="area_intersection" >\n';
	axl += '<ENVELOPE maxy="' + idMaxY + '" maxx="' + idMaxX + '" miny="' + idMinY + '" minx="' + idMinX + '" />\n';
	axl += '</SPATIALFILTER>\n';
	axl += '</SPATIALQUERY>\n';
	axl += '</GET_FEATURES>\n';
	axl += '</REQUEST>\n';
	axl += '</ARCXML>';
//alert(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;
	      processResult(result); 
	      
	     } else alert("Error retreiving data");
		          
       }  
}

function getCount(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 fValue1 = "";
  var selectedData = "";
  var endpos = 1;
  var pos;
  var startpos;
  for (var f=0;f<idCount;f++) {
  	pos = theReply.indexOf("<FIELDS ",endpos);
  	if (pos!=-1) {
		startpos = pos + 8;
		endpos = theReply.indexOf('" />',startpos);
		selectedData = theReply.substring(startpos,endpos);
  	}
	cList[f] = selectedData;
  }

  dispNextVal(1);
  hideLayer('loading');               
}


// get a list of field names from the returned record
function getIdFieldNames(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('="');

		//use an alias name for the field names
		switch(v[0]) {
			case "ODT1":
				v[0] = "DATE";
				break;
			case "PLCOD_DESC":
				v[0] = "LOCATION";
				break;
			case "CASEN":
				v[0] = "CASE";
				break;
			case "OFFDESC1":
				v[0] = "PRIMARY OFFENSE";
				break;
			case "TYPE_DESC":
				v[0] = "CHARGE";
				break;
		}

		fName1[f] = v[0];
	}
	return fName1;
}

// get a list field values from the returned record
function getIdFieldValues(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 displayIdResult(fName1, fValue1){
 	var idContent =  "<table class='idbody'>";
	var cFld=-1;
	idContent += "<tr>";
	idContent += "<td>Located "+idCount+" incidents during the "+timer.toLowerCase()+" prior to <b>"+lastDate+"</b>.</td>";
	idContent += "</tr>";
	idContent += "</table>";
	idContent += "<table class='msgtable'>";
 	idContent += "<tr valign='top'>";
	for (var ii=0;ii<fName1.length;ii++){
		if (fName1[ii]=="CATEGORY") cFld=ii;
 		idContent += "<td class=idth><b>" + fName1[ii] + "<b></td>";
	}
 	idContent += "</tr>";



	for (var f=0;f<idCount;f++) {
		fValue1 = getIdFieldValues(cList[f]);
		idContent += "<tr valign='top'>";
		for (var ii=0;ii<fValue1.length;ii++){
			if (ii==cFld) {
 				idContent += "<td class=idth>" + fValue1[ii] + "&nbsp;<img src='" + getSymbol(fValue1[ii]) + "' style='vertical-align: middle;' alt='" + fValue1[ii] +"'></td>";
			} else {
 				idContent += "<td class=idth>" + fValue1[ii] + "</td>";
			}
		}
 		idContent += "</tr>";
	}



	idContent += "</table>";
	updateContent('msg2', idContent);
}

function dispNextVal(abc) {
  curRec=abc;
  abc = abc - 1;	//adjust for array
  if(cList[abc] != ""){
	var fValue1 = getIdFieldValues(cList[abc]);
        var fName1 = getIdFieldNames(cList[abc]);
	displayIdResult(fName1, fValue1);
  }
}


function displayIdResultXXXX(fName1, fValue1){
 	var idContent =  "<table class='idbody'>";
	var cFld=-1;
	idContent += "<tr>";
	idContent += "<td>Located "+idCount+" incidents during the "+timer.toLowerCase()+" prior to <b>"+lastDate+"</b>.</td>";
	idContent += "</tr>";
	idContent += "</table>";
	idContent += "<table class='msgtable'>";
 	idContent += "<tr valign='top'>";
	for (var ii=0;ii<fName1.length;ii++){
		if (fName1[ii]=="CATEGORY") cFld=ii;
 		idContent += "<td class=idth><b>" + fName1[ii] + "<b></td>";
	}
 	idContent += "</tr>";
	idContent += "<tr valign='top'>";
	for (var ii=0;ii<fValue1.length;ii++){
		if (ii==cFld) {
 			idContent += "<td class=idth>" + fValue1[ii] + "&nbsp;<img src='" + getSymbol(fValue1[ii]) + "' style='vertical-align: middle;' alt='" + fValue1[ii] +"'></td>";
		} else {
 			idContent += "<td class=idth>" + fValue1[ii] + "</td>";
		}
	}
 	idContent += "</tr>";
	if (idCount>1) {
 		idContent += "<tr><td>";
		for (var f=1;f<=idCount;f++) {
			if (f==curRec) {
 				idContent += "&nbsp;&nbsp;<a href=# onclick='dispNextVal(" + f + ");'>[" + f + "]</a>";
			}else{
				idContent += "&nbsp;&nbsp;<a href=# onclick='dispNextVal(" + f + ");'>" + f + "</a>";
			}
		}
 		idContent += "</td></tr>";
	}
	idContent += "</table>";
	updateContent('msg2', idContent);
}

function setSelectedId(indx){
	selectedId = indx;
}

function getSymbol(ctype) {
	//return a symbol to place on the message div
	var img;
	switch (ctype) {
		case "Arson":
			img = "images/arson.gif";
			break;
		case "Assaults":
			img = "images/battery.gif";
			break;
		case "Auto Theft":
			img = "images/autotheft.gif";
			break;
		case "Commercial Burglary":
			img = "images/burglary.gif";
			break;
		case "DUI":
			img = "images/dui.gif";
			break;
		case "Drugs or Narcotics":
			img = "images/drugs.gif";
			break;
		case "Drunk in Public":
			img = "images/drunk.gif";
			break;
		case "Grand Theft":
			img = "images/grandtheft.gif";
			break;
		case "Hate Crimes":
			img = "images/hatecrimes.gif";
			break;
		case "Petty Theft":
			img = "images/pettytheft.gif";
			break;
		case "Residential Burglary":
			img = "images/trespass.gif";
			break;
		case "Robbery":
			img = "images/robbery.gif";
			break;
		case "Vandalism":
			img = "images/vandalism.gif";
			break;
		case "Vehicle Burglary":
			img = "images/vehicleburglary.gif";
			break;
		case "Weapons":
			img = "images/weapons.gif";
	}
	return img;
}