//var cqField_Mode3 = "WEQL.EQLPARCELS.PROP_STREET";
var cqField_Mode3 = "WEQL.EQLPARCELS.PROP_STREET";
var cqField_Mode4 = "WEQL.EQLPARCELS.OWNER_STREET";
var cqParcelLimit = 200; 
var cqPropSheetLayerId = 0;
var pollingID = 6;
var minxI,minyI,maxxI,maxyI;
var theenvelope = new Array();
var numResults = 0;
var electionsResults = new Array();
var decimalChar = ((("theChar is" + (10/100)).indexOf("."))==-1) ? "," : ".";
var theElecResultsArr = new Array();
var munis = "";
var addAcetate = false;
var glbURL;
var theMunis;
var cvtCount;
var cvtURL;
var GCLayerId = 5;
var GCid = "NAME"; 
var maxGeocodeCandidates = 1;
var minGeocodeScore = 45;
var glbPin;
var geoXmin;
var geoYmin;
var geoXmax;
var geoYmax;
var useGeocode = false;
var tryParcel = false;
var firstGoRound = false;
var geoAddress;
var isMultiSearchYN = 0;


//when ready to show the reports change showTheReport to true and change the elecFolder to whatever either Sophie or Derek tells you in the most current elections report folder name
var showTheReport = false;
var elecFolder = "aug2008";

function getInitialMap(){
	getMap("");
}


function getServiceInfo(){
	var axl = '<?xml version="1.0" encoding="UTF-8"?><ARCXML version="1.1">\n<REQUEST>\n<GET_SERVICE_INFO renderer="false" extensions="false" fields="false" />\n</REQUEST>\n</ARCXML>\n';
	http = getHTTPObject();
	//if ((http != null) && (!isWorking)) {
	if ((http != null)) {

	    http.open("POST", url, true);
	    http.onreadystatechange = parseLayers;
	    isWorking = true;
	    showLayer('loading');
	    http.send(axl);
  }
}


function parseLayers(){
  if (http.readyState == 4) {
  
   if (http.status == 200) {

      var result = http.responseText;
      //alert(result);
      getLayers(result); 
      getInitialMap();
   } else alert("Error retreiving data");
          
  }  
  
 }
function fixedZoomIn(){
	if (!addAcetate){
		addAcetate = true;
	}
    growEnvelope(0.75);
    var env = '<ENVELOPE minx="' + minx + '" miny="' + miny +'" maxx="' + maxx +'" maxy="' + maxy + '" />';
	getMap(env);
	
}

function fixedZoomOut(){
	if (!addAcetate){
		addAcetate = true;
	}
	growEnvelope(1.25);
	var env = '<ENVELOPE minx="' + minx + '" miny="' + miny +'" maxx="' + maxx +'" maxy="' + maxy + '" />';
	getMap(env);
	
}
function zoom(left, bottom, right, top){
     if(activeTool == "zoomin") getExtentForZoomIn(left, bottom, right, top);
     else getExtentForZoomOut(left, bottom, right, top);	
     var env = '<ENVELOPE minx="' + minx + '" miny="' + miny +'" maxx="' + maxx +'" maxy="' + maxy + '" />';
     getMap(env);	

}
function pan(ix, iy){
	var dx = (maxx - minx)/mwidth;
	var mx = dx*ix;
	var my = dx*iy;
	minx += mx;
	maxx += mx;
	miny += my;
	maxy += my;
	var env = '<ENVELOPE minx="' + minx + '" miny="' + miny +'" maxx="' + maxx +'" maxy="' + maxy + '" />';
     	getMap(env);
}
function panDirection(dir){
	if (!addAcetate){
		addAcetate = true;
	}
	shift(dir);
	var env = '<ENVELOPE minx="' + minx + '" miny="' + miny +'" maxx="' + maxx +'" maxy="' + maxy + '" />';
     	getMap(env);
}

function shift(dir){
	var dx = maxx - minx;
	var dy = maxy - miny;
		
	switch(dir) {
		//NORTH
		case "north":
			miny += 0.3*dy;
			maxy += 0.3*dy;
		break;
		//south
		case "south":
			miny -= 0.3*dy;
			maxy -= 0.3*dy;
		break;
		//east
		case "east":
			minx += 0.3*dx;
			maxx += 0.3*dx;
		break;
		//west
		case "west":
			minx -= 0.3*dx;
			maxx -= 0.3*dx;
		break;
		//northeast
		case "ne":
			miny += 0.3*dy;
			maxy += 0.3*dy;
			minx += 0.3*dx;
			maxx += 0.3*dx;
		break;
		//northwest
		case "nw":
			miny += 0.3*dy;
			maxy += 0.3*dy;
			minx -= 0.3*dx;
			maxx -= 0.3*dx;
		break;
		//southeast
		case "se":
			miny -= 0.3*dy;
			maxy -= 0.3*dy;
			minx += 0.3*dx;
			maxx += 0.3*dx;
		break;
		//southwest
		case "sw":
			miny -= 0.3*dy;
			maxy -= 0.3*dy;
			minx -= 0.3*dx;
			maxx -= 0.3*dx;
		break
		
	}
}

function getExtentForZoomIn(left, bottom, right, top){
	var LLPoint = getMapXY(left, bottom);
	minx = LLPoint[0];
	miny = LLPoint[1];
	var URPoint = getMapXY(right, top);
	maxx = URPoint[0];
	maxy = URPoint[1];
	

}


function getExtentForZoomOut(left, bottom, right, top){
		var xDiff= maxx-minx;
		var yDiff= maxy-miny;

		var pwidth = right-left;
		var pheight = top-bottom;
		var xRatio = mwidth / pwidth;
		var yRatio = mheight / pheight;
		var xAdd = xRatio * xDiff / 2;
		var yAdd = yRatio * yDiff / 2;
		minx =  minx - xAdd;
		maxx = maxx + xAdd;
		miny = miny - yAdd;
		maxy = maxy + yAdd;
		

}

function getMapXY(xIn,yIn) {
	var newValues = new Array();

	var mouseX = xIn;
	var pixelX = (maxx-minx) / mwidth;
	var newX = pixelX * mouseX + minx;
	var mouseY = mheight - yIn;
	var pixelY = (maxy-miny) / mheight;
	var newY = (pixelY * mouseY) + miny;
	newValues[0] = newX;

	newValues[1] = newY;
	return newValues; 
}

function growEnvelope(value){
	var dx = maxx - minx;
	var dy = maxy - miny;

	var cx = (maxx + minx)/2.0;
	var cy = (maxy + miny)/2.0;

	var dx1 = 0.5 * value * dx;
	var dy1 = 0.5 * value * dy;

	minx = cx - dx1;
	miny = cy - dy1;
	maxx = cx + dx1;
	maxy = cy + dy1;
}

function getMapWithCurrentExtent(){
	var env = '<ENVELOPE minx="' + minx + '" miny="' + miny +'" maxx="' + maxx +'" maxy="' + maxy + '" />';
	getMap(env);
}

function getMap(envelope) {
  http = getHTTPObject();
  if ((http != null)) {
    var axl = getMapRequest(envelope);
    http.open("POST", url, true);
    http.onreadystatechange = printResponse;
     //alert("sending :" + axl);
    showLayer('loading');
    http.send(axl);
  }
}

function getMapRequest(envelope){
	var axl = '<?xml version="1.0" encoding="UTF-8"?>';
	axl += '<ARCXML version="1.1">';
	axl += ' <REQUEST>';
	axl += '    <GET_IMAGE>';
	axl +=  '    <PROPERTIES>';
	axl += envelope;
	axl += '<IMAGESIZE height="' + mheight + '" width="' + mwidth + '" />';
	axl += '<LAYERLIST >\n';
	for (var i=0;i<layerCount;i++) {
		if (LayerVisible[i]==1) {
			axl += '<LAYERDEF id="' + LayerID[i] + '" visible="true" />\n';
		}else {
			axl += '<LAYERDEF id="' + LayerID[i] + '" visible="false" />\n';
		}
	}
	
	axl += '</LAYERLIST>\n';
	axl += ' </PROPERTIES>';
	if (addAcetate){
		
		 axl += '<LAYER type="acetate" name="acetate1" id="acetate1">';
      axl += '<OBJECT units="database">';
         axl += '<TEXT coords="' +theenvelope[0] + ' '+theenvelope[1] +'" label="'+theElecResultsArr[9]+'" >';
            axl += '<TEXTMARKERSYMBOL glowing="255,255,0" interval="3" fontstyle="bold" halignment="center" overlap="false" font="Arial" fontcolor="0,0,0" fontsize="12" valignment="top" />';
         axl += '</TEXT>';
      axl += '</OBJECT>';
    axl += '</LAYER>';
	
	 axl += '<LAYER type="acetate" name="acetate" id="acetate">';
      axl += '<OBJECT units="database">';
         axl += '<POINT coords="' +theenvelope[0] + ' '+theenvelope[1] +'" >';
            axl += '<SIMPLEMARKERSYMBOL color="255,255,0" type="star" width="16" outline="0,0,0" />';
         axl += '</POINT>';
      axl += '</OBJECT>';
    axl += '</LAYER>';
	
	}
	axl += '    </GET_IMAGE> </REQUEST></ARCXML>';
	
	return axl;
}

//need to define loadXML function for non IE browser which do not have loadXML implemented
//we use loadXML (can't use load method) to load ArcXML response because the response from ArcIMS is in plain text format   

if(!isIE){
	Document.prototype.loadXML = function (s) {
      
	   	// parse the string to a new doc   
	   	var doc2 = (new DOMParser()).parseFromString(s, "text/xml");
      
	   	// remove all initial children
	   	while (this.hasChildNodes())
	   	   this.removeChild(this.lastChild);
         
	   	// insert and import nodes
	   	for (var i = 0; i < doc2.childNodes.length; i++) {
	   	   this.appendChild(this.importNode(doc2.childNodes[i], true));
	   	}
       };
}



function printResponse(){

if (http.readyState == 4) {
    if (http.status == 200) {

      isWorking = false;
      var result = http.responseText;
      
	//var result = http.responseXML;  //fails
	//alert(result);

	var xmlDoc;
	
      if(document.implementation && document.implementation.createDocument) { 
      	// MOZILLA 
       	 xmlDoc = document.implementation.createDocument("", "", null);
      	 xmlDoc.async="false";
         xmlDoc.loadXML(result);
      } else if (window.ActiveXObject){
      	 //IE
      	  xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
	  
	  xmlDoc.async="false";
	  xmlDoc.loadXML(result);
       }
	//  alert(xmlDoc.getElementsByTagName("OUTPUT").item(0).getAttribute("url"));
	var theURL = xmlDoc.getElementsByTagName("OUTPUT").item(0).getAttribute("url");
	 document.getElementById('theImage').src = theURL;
	 glbURL = theURL;
	 var env = xmlDoc.getElementsByTagName("ENVELOPE").item(0);
	  minx = parseFloat(env.getAttribute("minx"));
	  miny = parseFloat(env.getAttribute("miny"));
	  maxx = parseFloat(env.getAttribute("maxx"));
	  maxy = parseFloat(env.getAttribute("maxy"));
	  //alert(minx +","+ miny +","+ maxx+","+maxy);

	//alert(result + " received");
	// parseEnvelope(result, 0);
	// var theURL = getURL(result);
	//document.getElementById('theImage').src = theURL;
	hideLayer('loading');
    }else alert("Error retreiving data");
     
  } 
}

function getURL(theReply) {
	var theURL = "";
	var startpos = 0;
	var endpos = 0;

	var pos = theReply.indexOf("OUTPUT");
	var pos1 = theReply.indexOf("url", pos);
	pos1 += 5;
	var pos2 = theReply.indexOf("\"", pos1);
	theURL = theReply.substring(pos1,pos2);


	return theURL;

}

function parseEnvelope(theString, startpos) {
	theString = theString.toUpperCase();
	var tempString = "";
	var dQuote="\"";
	var pos = theString.indexOf("ENVELOPE",startpos);
	if (pos!=-1) {
		pos = pos + 8;
		startpos = theString.indexOf("MINX=",pos);
		startpos += 6;
		var endpos = theString.indexOf(dQuote,startpos);
		tempString = theString.substring(startpos,endpos);
		minx = parseFloat(tempString);
		startpos = theString.indexOf("MINY=",pos);
		startpos += 6;
		endpos = theString.indexOf(dQuote,startpos);
		tempString = theString.substring(startpos,endpos);
		miny = parseFloat(tempString);
		startpos = theString.indexOf("MAXX=",pos);
		startpos += 6;
		endpos = theString.indexOf(dQuote,startpos);
		tempString = theString.substring(startpos,endpos);
		maxx = parseFloat(tempString);
		startpos = theString.indexOf("MAXY=",pos);
		startpos += 6;
		endpos = theString.indexOf(dQuote,startpos);
		tempString = theString.substring(startpos,endpos);
		maxy = parseFloat(tempString);

	}

}

function passTheSearch(passString,i){
	isMultiSearchYN = i;
	if (i == 2){
		cqParcelLimit = 1; 
	}
	var thePin = passString.substring(1,2);
		var pin;
		if (thePin == "+"){
			var pin1 = passString.substring(0,1);
			var pin2 = passString.substring(2,16);
			pin = pin1 + " " + pin2;
			
		}else{
			pin = passString;
			glbPin = pin;
		}
		var axl = cqBuildQuery_Address(pin,i);
	  //alert(axl);
		var queryUrl = url + "&CustomService=Query";
		//alert(queryUrl);
		http = getHTTPObject();
		http.open("POST", queryUrl, true);
   		http.onreadystatechange = printElection;
		isWorking = true;
   		http.send(axl);
		showLayer("loadingData");
	cqParcelLimit = 200; 
	firstGoRound = true;
	
}

function cqBuildQuery_Address(s,i) {

    fieldName = cqField_Mode3;
	fieldName2 = cqField_Mode4;
	theValue = s;//cqWin.document.queryform.parcelbyaddress.value;
	
		theValue = theValue.toUpperCase();
		if (i != 1){
			fieldName = "WEQL.EQLPARCELS.PIN";
			//fieldName = "WEQL.A2_County_Parcels_Com.PIN";
		}
		
		queryString = '( ' + fieldName + ' LIKE \'%' + theValue + '%\')';
		
	   //queryString = '( ' + fieldName + ' LIKE \'%' + theValue + '%\' or ' + fieldName2 + ' LIKE \'%' + theValue + '%\')';
		
	    var theString = '<?xml version="1.0" encoding="UTF-8"?>';
		theString += '<ARCXML version="1.1">\n<REQUEST>\n<GET_FEATURES featurelimit="' + cqParcelLimit + '" outputmode="xml" geometry="false" envelope="true">';
		theString += '<LAYER id="' + cqPropSheetLayerId + '" />';
		if (i == 99){
			theString += '<SPATIALQUERY subfields ="#ALL# "   where="" >';
		}else{
		theString += '<SPATIALQUERY subfields ="#ALL# "   where="' + queryString + '" >';
		}
		theString += '<SPATIALFILTER relation="area_intersection">';
		if (i == 99){
			theString += '<ENVELOPE minx="' + geoXmin + '" maxx="' + geoXmax + '" maxy="' + geoYmax + '" miny="' + geoYmin + '" />';
		}else{
     	theString += '<ENVELOPE minx="' + initialXmin + '" maxx="' + initialXmax + '" maxy="' + initialYmax + '" miny="' + initialYmin + '" />';
		}
		theString += '</SPATIALFILTER>';
        theString += '</SPATIALQUERY>';
		
		theString += '</GET_FEATURES>';
		theString += '</REQUEST>';
		theString += '</ARCXML>';
		
		return theString;
		
		
}

function printElection(){
	if (http.readyState == 4) {
    if (http.status == 200) {

      isWorking = false;
	  
      var result = http.responseText;
      //alert(result);
	  var idCount = getCount(result);
	  if (idCount == 0)
	  {
		  if (tryParcel){
			  //alert("Sorry.  We are having trouble locating this address.  If you are a City of Ann Arbor resident please try http://www.a2gov.org/voter/address.asp to find your voting information.");
		var wi = (screen.width - 200)/2;
		var he = (screen.height - 100)/2;
		//window.open("http://gisweb.ewashtenaw.org/website/elections/disclaimer.htm","GeocodeWindow","width=575,height=120,left="+wi+",top="+he+"scrollbars=yes,resizable=no,status=no");
		showLayer("errorData");
		tryParcel = false;
		hideLayer("loadingData");
		return;  
		  }else{
		  getGeocode();
		  return;
		  }
		  /*
		alert("No matches found.  If you live within the City of Ann Arbor you can go to http://www.a2gov.org/voter/address.asp to find your voting information.");
		hideLayer("loadingData");
		return;  
		*/
	  }
	  if (idCount > 1){
		processResult2(result,idCount);
		
         //alert(xmlDoc);
		displayMulti(idCount);
		return;
	  }
	  
	  //alert(result);
	  
	  theenvelope = getEnvelopeXYs(result,0);
	  //alert(envelope[0]);
	  //alert(envelope[0] + " " + envelope[1] + " " + envelope[2] + " " + envelope[3]);
	  if (useGeocode){
	  idMinX = geoXmin;
	  idMinY = geoYmin ;
	  idMaxX = geoXmax ;
	  idMaxY = geoYmax ;
	  }else{
	  idMinX = (theenvelope[2] + theenvelope[0])/2 - .01 ;
	  idMinY = (theenvelope[3] + theenvelope[1])/2 - .01 ;
	  idMaxX = (theenvelope[2] + theenvelope[0])/2 + .01 ;
	  idMaxY = (theenvelope[3] + theenvelope[1])/2 + .01 ;
	  }
	  //alert(idMinX + " " + idMinY + " " + idMaxX + " " + idMaxY);
	  processResult(result,99);
	  if (isMultiSearchYN != 2){
	  if (firstGoRound){
	  var checkTheStreet = checkStreet(prop_street,glbPin);
	  if (!checkTheStreet){
		  getGeocode();
		  return;
	  }
	  }
	  }
	  isMultiSearchYN = 0;
	  
	  //alert(juris);
	 //for (var i = 0;i < drillIDs.length;i++){
		  
		 //old ActiveLayer = drillIDs[i];
		 ActiveLayer = drillIDs[numResults];
	    var axl = getIdRequest(false, 1);
		var queryUrl = url + "&CustomService=Query";
		
		http = getHTTPObject();
		http.open("POST", queryUrl, true);
		//numResults = i;
		
   		http.onreadystatechange = makeResults;
		isWorking = true;
   		http.send(axl);
		//showLayer("loadingData");
	  //}
    }else alert("Error retreiving data");
     
  } 
}

function checkStreet(eqlStreet,userStreet){
	var eS = eqlStreet.split(" ");
	var uS = userStreet.split(" ");
	var theReturn;
	//alert(eS[1].toUpperCase() + " " + uS[1].toUpperCase());
	if ((eS[1].toUpperCase() != uS[1].toUpperCase())||(eS[0] != uS[0])){
		theReturn = false;
		
	}else{
		theReturn = true;
	}
	return theReturn;
	
}

function capWords(str){
	
	if (str == "&nbsp;"){
		
		theMunis = "Ann Arbor City";
		return;
	}else{
	str = str.toLowerCase();
   var words = str.split(" "); 
   for (var i=0 ; i < words.length ; i++){ 
      var testwd = words[i]; 
      var firLet = testwd.substr(0,1); 
      var rest = testwd.substr(1, testwd.length -1) 
	  if(words[i] != "of"){
      words[i] = firLet.toUpperCase() + rest 
	  }
   } 
   theMunis = words.join(" "); 
	}
} 


function getCVT(){
	var cvtFieldName = "WGIS.LUG_OFFICIALS_GEOGRAPHY.CVT_DESCRIPTION";
	
	var cvtLayerId = 66;
	capWords(municipality);
	//theValue = municipality.toUpperCase();
		
		
		queryString = '' + cvtFieldName + ' = \'' + theMunis + '\'';
	   //queryString = '( ' + fieldName + ' LIKE \'%' + theValue + '%\' or ' + fieldName2 + ' LIKE \'%' + theValue + '%\')';
		
	    var theString = '<?xml version="1.0" encoding="UTF-8"?>';
		theString += '<ARCXML version="1.1">\n<REQUEST>\n<GET_FEATURES featurelimit="' + cqParcelLimit + '" outputmode="xml" geometry="false" envelope="true">';
		theString += '<LAYER id="' + cvtLayerId + '" />';
		
		theString += '<SPATIALQUERY subfields ="#SHAPE# WGIS.LUG_OFFICIALS_GEOGRAPHY.NAME WGIS.LUG_OFFICIALS_GEOGRAPHY.TITLE "   where="' + queryString + '" />';
		//theString += '<SPATIALFILTER relation="area_intersection">';
     	//theString += '<ENVELOPE minx="' + initialXmin + '" maxx="' + initialXmax + '" maxy="' + initialYmax + '" miny="' + initialYmin + '" />';
     	//theString += '</SPATIALFILTER>';
        //theString += '</SPATIALQUERY>';
		
		theString += '</GET_FEATURES>';
		theString += '</REQUEST>';
		theString += '</ARCXML>';
		
		var queryUrl = url + "&CustomService=Query";
		
		http = getHTTPObject();
		http.open("POST", queryUrl, true);
		//numResults = i;
		
   		http.onreadystatechange = doCVT;
		isWorking = true;
   		http.send(theString);
	
	
}

function doCVT(){
	if (http.readyState == 4) {
    if (http.status == 200) {
		
		isWorking = false;
      var result = http.responseText;
      //alert(result);
	  cvtCount = getCount(result);
		//alert(result);
		processResult3(result,cvtCount);
		
		getPoll();
		
		
	}
	}
	
}

function getGeocode(){
	 var axl = writeGeocodeXML(glbPin);
		var geoUrl = url + "&CustomService=Geocode";
		
		http = getHTTPObject();
		http.open("POST", geoUrl, true);
		//numResults = i;
		
   		http.onreadystatechange = showGeocode;
		isWorking = true;
   		http.send(axl);
		useGeocode = true;
	
}

function showGeocode(){
	if (http.readyState == 4) {
    	if (http.status == 200) {
			
			isWorking = false;
			var result = http.responseText;
			//alert(result);
			var pos = result.indexOf("<GCCOUNT count=");
	var lpos = 0;
	var startpos = pos + 16;
	var startpos2=0;
	var dQuote = "\"";
	var endpos = result.indexOf(dQuote,startpos);
	var fString = result.substring(startpos,endpos);
	var GCpointCount=parseInt(fString);
	if (GCpointCount == 0){
		//alert("Sorry.  We are having trouble locating this address.  If you are a City of Ann Arbor resident please try http://www.a2gov.org/voter/address.asp to find your voting information.");
		var wi = (screen.width - 200)/2;
		var he = (screen.height - 100)/2;
		//window.open("http://gisweb.ewashtenaw.org/website/elections/disclaimer.htm","GeocodeWindow","width=575,height=120,left="+wi+",top="+he+"scrollbars=yes,resizable=no,status=no");
		showLayer("errorData");
		hideLayer("loadingData");
		return; 
		
	}else{
		startpos2 = result.indexOf('name="SCORE"',lpos);
		startpos = result.indexOf("FIELDVALUE valuestring=",startpos2);
		startpos = startpos + 24;
		endpos = result.indexOf(dQuote,startpos);
		startpos2 = result.indexOf('name="ADDRESSFOUND"',lpos);
		startpos = result.indexOf("FIELDVALUE valuestring=",startpos2);
		startpos = startpos + 24;
		endpos = result.indexOf(dQuote,startpos);
		geoAddress = result.substring(startpos,endpos);
		startpos2 = result.indexOf('name="SHAPEFIELD"',lpos);
		startpos = result.indexOf("<POINT x=",startpos2);
		startpos += 10;
		endpos = result.indexOf(dQuote,startpos);
		tempX = result.substring(startpos,endpos);
		startpos = result.indexOf("y=",endpos);
		startpos = startpos + 3;
		endpos = result.indexOf(dQuote,startpos);
		tempY = result.substring(startpos,endpos);
		//alert(tempX + " " + tempY);
		geoXmin = tempX - .01;
		geoYmin = tempY - .01;
		geoXmax = tempX + .01;
		geoYmax = tempY + .01;
		
		var axl = cqBuildQuery_Address(" ",99);
	//alert(axl);
		var queryUrl = url + "&CustomService=Query";
		
		http = getHTTPObject();
		http.open("POST", queryUrl, true);
   		http.onreadystatechange = printElection;
		isWorking = true;
   		http.send(axl);
		tryParcel = true;
		firstGoRound = false;
		
	}
			
		}
	}
	
}

function writeGeocodeXML(GCvalue) {
	var theString = '<ARCXML version="1.1">\n<REQUEST>\n<GET_GEOCODE maxcandidates="' + maxGeocodeCandidates + '" minscore="' + minGeocodeScore + '">\n';
	theString += '<LAYER id="' + GCLayerId + '" />';
	theString += '<ADDRESS>\n';
	theString += '<GCTAG id="STREET" value="' + GCvalue + '"/>\n';
	theString += '<GCTAG id="CROSSSTREET" value=""/>\n';
	theString += '</ADDRESS>\n</GET_GEOCODE>\n</REQUEST>\n</ARCXML>\n';
	//alert(theString);
	
	return theString;
	
}

function setDecimalString(numberString) {
	if (numberString.indexOf(",")!=-1) forceCommaInRequest[activeMapServiceIndex] = true;
	if (decimalChar==".") {
		numberString = numberString.replace(/,/g, ".");
	} else {
		numberString = numberString.replace(/./g, ",");
	}
	return numberString;
}


function getEnvelopeXYs(theString, startpos) {
	var theEnvelope = new Array();
	//forceCommaInRequest[activeMapServiceIndex] = false;
	theString = theString.toUpperCase();
	var dQuote="\"";
	var tempString = "";
	var pos = theString.indexOf("ENVELOPE",startpos);
	if (pos!=-1) {
		pos = pos + 8;
		startpos = theString.indexOf("MINX=",pos);
		startpos += 6;
		var endpos = theString.indexOf(dQuote,startpos);
		tempString = theString.substring(startpos,endpos);
		theEnvelope[0] = parseFloat(setDecimalString(tempString)); 
		startpos = theString.indexOf("MINY=",pos);
		startpos += 6;
		endpos = theString.indexOf(dQuote,startpos);
		tempString = theString.substring(startpos,endpos);
		theEnvelope[1] = parseFloat(setDecimalString(tempString)); 
		startpos = theString.indexOf("MAXX=",pos);
		startpos += 6;
		endpos = theString.indexOf(dQuote,startpos);
		tempString = theString.substring(startpos,endpos);
		theEnvelope[2] = parseFloat(setDecimalString(tempString)); 
		startpos = theString.indexOf("MAXY=",pos);
		startpos += 6;
		endpos = theString.indexOf(dQuote,startpos);
		tempString = theString.substring(startpos,endpos);
		theEnvelope[3] = parseFloat(setDecimalString(tempString)); 
		xmlEndPos = endpos;
	}
	return theEnvelope;

}

function makeResults(){
	
	if (http.readyState == 4) {
    	if (http.status == 200) {
			
			isWorking = false;
			var result = http.responseText;
			//alert(result);
			
			processResult(result,numResults)
			//if (numResults >= 5){
			//alert(theElecResultsArr[24]);
			    //if(theElecResultsArr[24] = ""){
			    
			        //showClerkInfo();
			        //return;
			    //}
			//}
			if (numResults == 7){
				
				/*for (var s = 0;s < theElecResultsArr.length;s++){
					alert(theElecResultsArr[s]);
					
				}*/
				getCVT();
				//getPoll();
				
				numResults = 0;
				return;
			}else{
				numResults++;
				 ActiveLayer = drillIDs[numResults];
				 //alert("drillIDs : "+drillIDs[numResults]);
	    		var axl = getIdRequest(false, 1);
				var queryUrl = url + "&CustomService=Query";
		
				http = getHTTPObject();
				http.open("POST", queryUrl, true);
				//numResults = i;
		
   				http.onreadystatechange = makeResults;
				isWorking = true;
   				http.send(axl);
				
				
				
				
			}
			
			
			
		}
	}
	
	
}

function showClerkInfo(){

var obj = document.getElementById('completeElecResults');
var theString = " ";
	theString += "<P>Please contact the County Clerk to find more information on your polling location.<br>Phone: 734-222-6730 Fax: 734-222-6528</p>";
obj.innerHTML = theString;
hideLayer("loadingData");
showLayer("resultReturn");
hideLayer('loading');
	
	

hideLayer('theImage');
hideLayer('toolbar');
var obj2 = document.getElementById('pollingText');
var obj3 = document.getElementById('printText');
	var obj4 = document.getElementById('pollingDirections');	
	var obj5 = document.getElementById('toolbar');	
	obj2.innerHTML = "&nbsp;";
	obj3.innerHTML = "";
	obj4.innerHTML = "";
	//obj5.innerHTML = "";
	obj5.style.visibility = "hidden";
	//document.getElementById('theImage').src = "images/pixel.gif";
	//document.getElementById('mapArea').innerHTML = "<img src=images/pixel.gif height=200 width=150>";
}

function displayMulti(i){
	
	var obj = document.getElementById('completeElecResults');
	var theString = " ";
	theString += "<P><b>Your query returned multiple results, please choose one address from below to continue:</b><br>";
	for (var s = 0;s < i;s++){
		var thePin = multiResults[s+""+0].substring(1,2);
		var pin;
		if (thePin == " "){
			var pin1 = multiResults[s+""+0].substring(0,1);
			var pin2 = multiResults[s+""+0].substring(2,16);
			pin = pin1 + "+" + pin2;
			
		}else{
			pin = multiResults[s+""+0];
		}
		if (window.ActiveXObject){
			//alert("here");
			 //pin = "'" + multiResults[s+""+0] + "'"; 
			 pin = "'" + pin + "'";
			theString += "Address: <a href=javaScript:multiS("+pin+");>"+multiResults[s+""+2]+ " " +multiResults[s+""+1]+"</a><br>";
		}else{
		 //pin = '&apos;' +multiResults[s+""+0] + '&apos';
		pin = '&apos;' + pin + '&apos;';
		theString += "Address: <a href=javaScript:multiS("+pin+");>"+multiResults[s+""+2]+ " " +multiResults[s+""+1]+"</a><br>";
		}
		//+ " " +multiResults[s,0]+
		
	}
	obj.innerHTML = theString;
	hideLayer("loadingData");
	showLayer("resultReturn");
}

function displayElecResults(){
//if (glbPollNum == 0){
//    showClerkInfo();
    
//}else{

	var obj = document.getElementById('completeElecResults');
	var obj2 = document.getElementById('pollingText');
	var obj3 = document.getElementById('printText');
	var obj4 = document.getElementById('pollingDirections');
	var theString = " ";
	theString += "<P><b>Your Voting Information:</b><br>";
	theString += "Click <a href=https://services2.sos.state.mi.us/mivote/ target=_blank>here</a> to see whether you are registered to vote.<br><br>";
	//if (theMunis == "Ann Arbor City"){
		//theString += "City of Ann Arbor address locations are estimated; please confirm your polling location at this <a href=http://www2.a2gov.org/Mypropertyinformation/address.asp target=_blank>site</a><br><br>";
		theString += "<font color=\"red\">If you feel you have recieved incorrect information please try searching again.  </font>If you are an Ann Arbor City resident you can confirm your polling location at <a href=http://www2.a2gov.org/Mypropertyinformation/address.asp target=_blank>this site</a><br><br>";
	//}
	if(glbPollNum == 0){
		theString += "<b>Please contact the County Clerk to find more information on your polling location.<br>Phone: 734-222-6730</b><br><br>";
	}else{
	theString +="<b>Polling Information for:</b> ";
		if (tryParcel){
			theString += geoAddress.toUpperCase();
		}else{
			theString += prop_street;
		}
	
	theString += ", "+theMunis+"<br><br>";
	}
	if (theElecResultsArr[1] != "&nbsp;"){
		theString += "<b>Ward:</b> "+theElecResultsArr[1]+"<br>";	
	}
	theString += "<b>Precinct:</b> "+theElecResultsArr[0]+"<br>";	
	theString += "<b>Polling Place:</b> "+theElecResultsArr[10]+"<br>";	
	theString += "<b>Polling Address:</b> "+theElecResultsArr[9]+"<br>";	
	theString += "<b>School District:</b> "+theElecResultsArr[11]+"<br>";
	if (theElecResultsArr[22] != "No Library District"){
		theString += "<b>Library District:</b> "+theElecResultsArr[22]+"<br>";
	}
	theString += "<b>Community College District:</b> "+theElecResultsArr[17]+"<br><br>";
	theString += "<b>Current Elected Officials:</b> <br>";
	theString += "<b>County Commissioner District:</b> "+theElecResultsArr[7]+" - <a href=http://www.ewashtenaw.org/government/boc/members/district_"+theElecResultsArr[7]+" target=_blank>"+theElecResultsArr[6]+"</a> - ("+theElecResultsArr[8]+")<br>";// - <a href=mailto:"+theElecResultsArr[8]+">"+theElecResultsArr[8]+"</a><br><br>";	
	theString += "<b>State House of Rep District:</b> "+theElecResultsArr[3]+" - <a href="+theElecResultsArr[15]+" target=_blank>"+theElecResultsArr[2]+"</a> - ("+theElecResultsArr[13]+")<br>";	
	theString += "<b>State Senate District:</b> "+theElecResultsArr[5]+" - <a href="+theElecResultsArr[16]+" target=_blank>"+theElecResultsArr[4]+"</a> - ("+theElecResultsArr[14]+")<br>";	
	theString += "<b>US House District:</b> "+theElecResultsArr[19]+" - <a href="+theElecResultsArr[20]+" target=_blank>"+theElecResultsArr[18]+"</a> - ("+theElecResultsArr[21]+")<br>";	
	theString += "<b>US Senators: </b><a href=http://levin.senate.gov/ target=_blank>Carl Levin</a> (D) And <a href=http://stabenow.senate.gov/ target=_blank>Debbie Stabenow</a> (D)<br><br>";
	theString += "<b>Municipality: </b><a href="+cvtURL+" target=_blank>"+theMunis+"</a><br>";
//	theString += "<b>Current Local Officials:</b><br>";
//	theString += getPrimary();
//	theString += getSecondary();
//	theString += getTertiary();
//	theString += getWard1();
//	theString += getWard2();
//	theString += getWard3();
//	theString += getWard4();
//	theString += getWard5();
//	theString += getTrustee();
//	theString += getConstable();
//	theString += getRest();
	theString += "<br><br>";
	
	if (showTheReport){
		theString += "<a href=http://electionresults.ewashtenaw.org/"+elecFolder+"/sampleprecinctreport"+theElecResultsArr[12]+".html target=_blank>See Your Ballot</a>";
	}
	else{
	    theString += "<a href=https://services2.sos.state.mi.us/mivote/ target=_blank>Click here to view your ballot on the State's web site</a>";
	    //theString += "<a href=SampleBallots.pdf target=_blank>To View Sample Presidential Primary Ballots, Click Here</a>";
	}
//	
	obj.innerHTML = theString;
	obj2.innerHTML = "<p><B>Your Polling Location:</b></p>";
	obj3.innerHTML = "<a href=print.htm?print target=_blank>Print My Info</a>";
	var pL = theElecResultsArr[9].split(" "); 
	var thePl = "";
   for (var i=0 ; i < pL.length ; i++){ 
     thePl = thePl + pL[i] + "+"; 
	 
   } 
	obj4.innerHTML = "<a href=http://maps.google.com/maps?f=d&hl=en&q="+thePl+""+theElecResultsArr[23]+" target=_blank>Get Directions to Your Polling Place</a>";
	
	hideLayer("loadingData");
	showLayer("resultReturn");
	/*for (var c=0;c<cvtCount;c++){
		cvtResults[c+""+0] = " ";
		cvtResults[c+""+1] = " ";
	}*/
	
}
//}
function getPrimary(){
	var theString = "";
	for (var c=0;c<cvtCount;c++){
		if ((cvtResults[c+""+1] == "President")||(cvtResults[c+""+1] == "Supervisor")||(cvtResults[c+""+1] == "Mayor")||(cvtResults[c+""+1] == "Village President")){
		theString += ""+cvtResults[c+""+0]+" - "+cvtResults[c+""+1]+"<br>";
		}
	}
	
	return theString;
}

function getSecondary(){
	var theString = "";
	for (var c=0;c<cvtCount;c++){
		if ((cvtResults[c+""+1] == "President Pro Tem")||(cvtResults[c+""+1] == "Clerk")||(cvtResults[c+""+1] == "Mayor Pro-Tem")||(cvtResults[c+""+1] == "Village President Pro Tem")){
		theString += ""+cvtResults[c+""+0]+" - "+cvtResults[c+""+1]+"<br>";
		}
	}
	return theString;
	
}

function getTertiary(){
	var theString = "";
	for (var c=0;c<cvtCount;c++){
		if (cvtResults[c+""+1] == "Treasurer"){
		theString += ""+cvtResults[c+""+0]+" - "+cvtResults[c+""+1]+"<br>";
		}
	}
	return theString;
	
}
function getWard1(){
	var theString = "";
	
	for (var c=0;c<cvtCount;c++){
		var words = cvtResults[c+""+1].split(" ");
		if (words[3] == "1"){
		theString += ""+cvtResults[c+""+0]+" - "+cvtResults[c+""+1]+"<br>";
		}
	}
	return theString;
	
}
function getWard2(){
	var theString = "";
	
	for (var c=0;c<cvtCount;c++){
		var words = cvtResults[c+""+1].split(" ");
		if (words[3] == "2"){
		theString += ""+cvtResults[c+""+0]+" - "+cvtResults[c+""+1]+"<br>";
		}
	}
	return theString;
	
}
function getWard3(){
	var theString = "";
	
	for (var c=0;c<cvtCount;c++){
		var words = cvtResults[c+""+1].split(" ");
		if (words[3] == "3"){
		theString += ""+cvtResults[c+""+0]+" - "+cvtResults[c+""+1]+"<br>";
		}
	}
	return theString;
	
}
function getWard4(){
	var theString = "";
	
	for (var c=0;c<cvtCount;c++){
		var words = cvtResults[c+""+1].split(" ");
		if (words[3] == "4"){
		theString += ""+cvtResults[c+""+0]+" - "+cvtResults[c+""+1]+"<br>";
		}
	}
	return theString;
	
}function getWard5(){
	var theString = "";
	
	for (var c=0;c<cvtCount;c++){
		var words = cvtResults[c+""+1].split(" ");
		if (words[3] == "5"){
		theString += ""+cvtResults[c+""+0]+" - "+cvtResults[c+""+1]+"<br>";
		}
	}
	return theString;
	
}

function getTrustee(){
	var theString = "";
	
	for (var c=0;c<cvtCount;c++){
		var words = cvtResults[c+""+1].split(" ");
		if (cvtResults[c+""+1] == "Trustee"){
		theString += ""+cvtResults[c+""+0]+" - "+cvtResults[c+""+1]+"<br>";
		}
	}
	return theString;
	
}

function getConstable(){
	var theString = "";
	
	for (var c=0;c<cvtCount;c++){
		var words = cvtResults[c+""+1].split(" ");
		if (cvtResults[c+""+1] == "Constable"){
		theString += ""+cvtResults[c+""+0]+" - "+cvtResults[c+""+1]+"<br>";
		}
	}
	return theString;
	
}

function getRest(){
	var theString = "";
	
	for (var c=0;c<cvtCount;c++){
		var words = cvtResults[c+""+1].split(" ");
		//if ((cvtResults[c+""+1] == "Trustee")||(cvtResults[c+""+1] == "Constable")||(cvtResults[c+""+1] == "Council Member") ||(words[0] == "Park")/*||(words[2] != "Ward")*/){
		if ((cvtResults[c+""+1] == "Council Member") ||(words[0] == "Park")/*||(words[2] != "Ward")*/){
		theString += ""+cvtResults[c+""+0]+" - "+cvtResults[c+""+1]+"<br>";
		}
	}
	return theString;
	
}
function getPoll(){
	
	switch(juris){
		case "&nbsp;":
		munis = "Ann Arbor City";
		cvtURL = "http://www.a2gov.org/";
		break;
		
		case "09":
		munis = "Ann Arbor City";
		cvtURL = "http://www.a2gov.org/";
		break;
		
		case "11":
		munis = "Ypsilanti City";
		cvtURL = "http://www.city-ypsilanti.org";
		break;
		
		case "18":
		munis = "Saline City";
		cvtURL = "http://www.ci.saline.mi.us";
		break;
		
		case "06":
		munis = "Chelsea City";
		cvtURL = "http://www.city-chelsea.org";

		break;
		
		case "19":
		munis = "Milan City";
		cvtURL = "http://www.ci.milan.mi.us";
		break;
	
		case "A":
		munis = "Salem Twp."	
		cvtURL = "http://www.salem-mi.org";
		break;
		
		case "B":
		munis = "Northfield Twp.";	
		cvtURL = "http://www.twp-northfield.org";
		break;
		
		case "C":
		munis = "Webster Twp.";	
		cvtURL = "http://www.twp.webster.mi.us";
		break;
		
		case "D":
		munis = "Dexter Twp.";	
		cvtURL = "http://www.twp-dexter.org";
		break;
		
		case "E":
		munis = "Lyndon Twp.";	
		cvtURL = "http://www.lyndontownship.org";
		break;
		
		case "F":
		munis = "Sylvan Twp";
		cvtURL = "http://www.twp-sylvan.org";
		break;
		
		case "FC":
		munis = "Chelsea City";
		break;
		
		case "G":
		munis = "Lima Twp.";	
		cvtURL = "http://www.twp-lima.org";
		break;
		
		case "H":
		munis = "Scio Twp."	
		cvtURL = "http://www.twp.scio.mi.us";
		break;
		
		case "HD":
		//munis = "Dexter Village";
		munis = "Scio Twp.";
		cvtURL = "http://www.villageofdexter.org";
		break;
		
		case "I":
		munis = "Ann Arbor Twp.";
		cvtURL = "http://www.aatwp.org";
		break;
		
		case "IB":
		munis = "Ann Arbor Twp.";
		cvtURL = "http://vil-bartonhills.org";
		break;
		
		case "J":
		munis = "Superior Twp.";
		cvtURL = "http://www.superior-twp.org";
		break;
		
		case "K":
		munis = "Ypsilanti Twp.";
		cvtURL = "http://www.twp.ypsilanti.mi.us";
		break;
		
		case "L":
		munis = "Pittsfield Twp.";
		cvtURL = "http://www.pittsfieldtwp.org";
		break;
		
		case "M":
		munis = "Lodi Twp.";
		cvtURL = "http://www.twp-lodi.org";
		break;
		
		case "N":
		munis = "Freedom Twp.";
		cvtURL = "http://www.twp-freedom.org";
		break;
		
		case "O":
		munis = "Sharon Twp.";
		cvtURL = "http://www.twp-sharon.org";
		break;
		
		case "P":
		munis = "Manchester Twp.";
		cvtURL = "http://www.twp-manchester.org";
		break;
		
		case "PM":
		munis = "Manchester Vil";
		cvtURL = "http://www.vil-manchester.org";
		break;
		
		case "Q":
		munis = "Bridgewater Twp.";
		cvtURL = "http://township.bridgewater.mi.us";
		break;
		
		case "R":
		munis = "Saline Twp.";
		cvtURL = "http://www.salinetownship.org";
		break;
		
		case "S":
		munis = "York Twp.";
		cvtURL = "http://www.twp-york.org";
		break;
		
		case "T":
		munis = "Augusta Twp.";
		cvtURL = "http://www.augustatownship.org";
		break;
	}
	
	
	
	if (theElecResultsArr[1] != "&nbsp;"){
		var ward = theElecResultsArr[1].substring(1,2);
		var fullWard = "Ward "+ward;
		
		var precint = theElecResultsArr[0].substring(0,1);
		if (precint == "0"){
			precint = theElecResultsArr[0].substring(1,2);
		}else{
			precint = theElecResultsArr[0];
		}
		var fullPrecinct = "Precinct "+precint;
		
		
		var full = fullWard + " " + fullPrecinct;
		
	}else{
		
		var precint = theElecResultsArr[0].substring(0,1);
		
		if (precint == "0"){
			precint = theElecResultsArr[0].substring(1,2);
			
		}else{
			precint = theElecResultsArr[0];
		}
		var fullPrecinct = "Precinct "+precint;
		
		var full = fullPrecinct;
		
	}
	
	var axl = pollingLocQuery(munis,full);
	//alert(axl);
	var queryUrl = url + "&CustomService=Query";
		
		http = getHTTPObject();
		http.open("POST", queryUrl, true);
   		http.onreadystatechange = pollThis;
		isWorking = true;
   		http.send(axl);
	
	
	
	
}

function pollingLocQuery(w,p) {

    var theField = "NUM";
	if (glbPollNum == 0){
		var theVal = 139;
	}else{
    var theVal = theElecResultsArr[24];
	}
	   
	   queryString = ' ' + theField + ' = \'' + theVal + '\'';
		
	    var theString = '<?xml version="1.0" encoding="UTF-8"?>';
		theString += '<ARCXML version="1.1">\n<REQUEST>\n<GET_FEATURES outputmode="xml" geometry="false" envelope="true">';
		theString += '<LAYER id="' + pollingID + '" />';
		
		theString += '<SPATIALQUERY subfields ="#ALL# "   where="' + queryString + '" >';
        theString += '</SPATIALQUERY>';
		
		theString += '</GET_FEATURES>';
		theString += '</REQUEST>';
		theString += '</ARCXML>';
		
		return theString;
		
		
}

function pollThis(){
	if (http.readyState == 4) {
    if (http.status == 200) {

      isWorking = false;
      var result = http.responseText;
	  
	  processResult(result,101)
	  theenvelope = getEnvelopeXYs(result,0);
	  minx = theenvelope[0] - 25;
	  miny = theenvelope[1] - 25;
	  maxx = theenvelope[2] + 25;
	  maxy = theenvelope[3] + 25;
	  growEnvelope(50.0);
	  
	  var env = '<ENVELOPE minx="' + minx + '" miny="' + miny +'" maxx="' + maxx +'" maxy="' + maxy + '" />';
	  
  	  http = getHTTPObject();
 if ((http != null)) {
	 addAcetate = true;
    var axl = getMapRequest(env);
	
    http.open("POST", url, true);
    http.onreadystatechange = showPoll;
    // alert("sending :" + axl);
    showLayer('loading');
    http.send(axl);
  
}
      
	//var result = http.responseXML;  //fails
	//alert(result);

    }else alert("Error retreiving data");
     
  } 
	
}



function showPoll(){
	if (http.readyState == 4) {
    if (http.status == 200) {

      isWorking = false;
      var result = http.responseText;
      
	//var result = http.responseXML;  //fails
	//alert(result);

	var xmlDoc;
	
      if(document.implementation && document.implementation.createDocument) { 
      	// MOZILLA 
       	 xmlDoc = document.implementation.createDocument("", "", null);
      	 xmlDoc.async="false";
         xmlDoc.loadXML(result);
      } else if (window.ActiveXObject){
      	 //IE
      	  xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
	  
	  xmlDoc.async="false";
	  xmlDoc.loadXML(result);
       }
	//  alert(xmlDoc.getElementsByTagName("OUTPUT").item(0).getAttribute("url"));
	var theURL = xmlDoc.getElementsByTagName("OUTPUT").item(0).getAttribute("url");
	 document.getElementById('theImage').src = theURL;
	 glbURL = theURL;
	 var env = xmlDoc.getElementsByTagName("ENVELOPE").item(0);
	  minx = parseFloat(env.getAttribute("minx"));
	  miny = parseFloat(env.getAttribute("miny"));
	  maxx = parseFloat(env.getAttribute("maxx"));
	  maxy = parseFloat(env.getAttribute("maxy"));
	  //alert(minx +","+ miny +","+ maxx+","+maxy);

	
	displayElecResults();
	hideLayer('loading');
	if (glbPollNum == 0){
	hideLayer('mapContainer');
	hideLayer('mapArea');
	hideLayer('theImage');
	hideLayer('toolbar');
	var obj2 = document.getElementById('pollingText');
var obj3 = document.getElementById('printText');
	var obj4 = document.getElementById('pollingDirections');	
	var obj5 = document.getElementById('toolbar');	
	obj2.innerHTML = "&nbsp;";
	obj3.innerHTML = "";
	obj4.innerHTML = "";
	}else{
	showLayer('mapContainer');
showLayer('mapArea');
showLayer('theImage');
showLayer('toolbar');
glbPollNum = 0;
}
//showLayer('north');
addAcetate = false;
useGeocode = false;
tryParcel = false;



    }else alert("Error retreiving data");
     
  } 
	

}