var lastbounds;
var lastzoom;
var points = new Array();
var numPoints=0;
var maxPoints=250;
var map;
var markers;
var i=0;
var cmpltdrqst=0;
var newrequest=0;
var icon = new GIcon();
var timeOut = 100;
var lMessage;


lastzoom=1;

function a_trim(str) {
 return str?str.replace(/^\s*|\s*$/g,""):"";
}

function addCommas(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

function clearmap() {

	for (var i in points)
	{
		GEvent.clearListeners(points[i],'click');
		map.removeOverlay(points[i]);
		delete points[i];	
	}

	numPoints=0;

}




function zoomTo(pointx,pointy) {

	var zz=5;
	
	zz=5-parseInt(document.getElementById("detail").value);
	if (zz<0) zz=0;
	if (zz>17) zz=17;

	map.centerAndZoom(new GPoint(pointx,pointy), zz);
}



function createHouse(markers) {

	//this hashing may have to modified when doing the assessmetn maps

	//if house sale has already been displayed, don't send to map
	//if (hashPoints[markers.getAttribute("id") + "," + markers.getAttribute("date")] == true)
	if (hashPoints[markers.getAttribute("id")] == true)
	{
		//alert("dupe house sent");
		return;
	}

	//hashPoints[markers.getAttribute("id") + "," + markers.getAttribute("date")] = true; //house displayed
	hashPoints[markers.getAttribute("id")] = true; //house displayed


	      	var id=markers.getAttribute("id");

		var point = new GPoint(parseFloat(markers.getAttribute("lat")),
	                             parseFloat(markers.getAttribute("lng")));
	    	var marker;

		if ( typeof( window[ 'vacant_search' ] ) != "undefined")
		{
			marker  = createMarkerVacant(point,markers.getAttribute("address"),
						  markers.getAttribute("state"));
		}
		else
		{ //normal sales search
			marker  = createMarker(point,markers.getAttribute("address"),
						  markers.getAttribute("state"),
						  markers.getAttribute("date"),
						  markers.getAttribute("price"));
		}

  	      	map.addOverlay(marker);

	points[id]=marker;
	numPoints++;

}



// Creates a marker whose info window displays the given number
function createMarker(point, address, state, date, price) {
  var marker = new GMarker(point);

  // Show this marker's index in the info window when it is clicked
  var html = address
          	+"<br/><b>Date Sold: </b>"+date
                +"<br/><b>Sale Price: </b>$"+addCommas(price);

    
  GEvent.addListener(marker, "click", function() {
    var htmldiv = document.createElement('div');
    htmldiv.style.width = 290;
    htmldiv.style.height = 255;
    htmldiv.innerHTML = html;
    aL_publicA9(htmldiv, point.x, point.y);
    marker.openInfoWindow(htmldiv);
  });

  return marker;
}

// Creates a marker whose info window displays the given number
function createMarkerVacant(point, address, state) {
  var markerV = new GMarker(point);

  // Show this marker's index in the info window when it is clicked
  var htmlVacant = "Vacant Property:<br/>" + address;

  GEvent.addListener(markerV, "click", function() {
    var htmldiv = document.createElement('div');
    htmldiv.style.width = 290;
    htmldiv.style.height = 235;
    htmldiv.innerHTML = htmlVacant;
    aL_publicA9(htmldiv, point.x, point.y);
    markerV.openInfoWindow(htmldiv);
  });

  return markerV;
}


function ontok_geocoder_onload()
{
  if ( ontok_geocoder[0] ) {
    var result = ontok_geocoder[0];
    s = result.split(";");
    if ( s.length > 4 ) {
      s_lat = s[0];
      s_long = s[1];
      s_description = s[2];
      s_q = s[3]; 
      s_score = s[4];
      // ***************************************************
      // HERE IS WHERE YOU PLACE YOUR CODE:
      	//map.centerAndZoom(new GPoint(s_lat, s_long), 1);  //1 is the most zoomed in. 2 is also good

	var newURL;

	//if vacant property search
	if ( typeof( window[ 'vacant_search' ] ) != "undefined")
	{
		newURL = "/vacant.php?";
		newURL += "lat=" + s_lat;
		newURL += "&long=" + s_long;
		if (document.getElementById("addr").value != 0)
			{newURL += "&Address=" + document.getElementById("addr").value;}

	}
	else
	{

	newURL = "/sales.php?";
	newURL += "lat=" + s_lat;
	newURL += "&long=" + s_long;
	//if (document.getElementById("SaleDate").value != 0) //always submit sale date.  0 == no limit
	{newURL += "&SaleDate=" + document.getElementById("SaleDate").value;}
	if (document.getElementById("LowPrice").value != 0)
		{newURL += "&LowPrice=" + document.getElementById("LowPrice").value;}
	if (document.getElementById("HighPrice").value != 0)
		{newURL += "&HighPrice=" + document.getElementById("HighPrice").value;}
	if (document.getElementById("addr").value != 0)
		{newURL += "&Address=" + document.getElementById("addr").value;}
	}

	//navigate to the new URL:
	location.href = newURL;
	
      // ***************************************************
    }
  }
}


function mapOne() {

  ///Convoluted fixup that works
  if((cmpltdrqst==1) && (newrequest==1)) {
	i=0;
      if (lMessage) { lMessage.innerHTML="<p>Loading " + i + " of " + markers.length + "</p>";}
    	document.getElementById('loading').style.visibility='visible';
	cmpltdrqst=0;
	newrequest=0;
  }  
   
  
  if ( i < markers.length ) {
  var max=Math.min(i+20, markers.length);
    while (i<max) {
//      var point = new GPoint(parseFloat(markers[i].getAttribute("lon")),
//  			   parseFloat(markers[i].getAttribute("lat")));
//      var marker = new GMarker(point, icon);
//      map.addOverlay(marker);
	
	createHouse(markers[i]);
      	i++;
    }
    if (lMessage) { lMessage.innerHTML="<p>Loading " + i + " of " + markers.length + "</p>";}
    window.setTimeout(mapOne,timeOut);
  }
  if ( i >= markers.length ) {
    document.getElementById('loading').style.visibility='hidden';
    cmpltdrqst=1;
  }
}



function startRequest(minx,miny,maxx,maxy,z,clear,minx2,miny2,maxx2,maxy2) {
	var url;
	var request;
 
	lMessage = document.getElementById('lMessage');
  
	//////zz is for the detail control
	/////var zz;
	////zz=parseInt(z)+parseInt(document.getElementById("detail").value);
	////if (zz<0) zz=0;
	///if (zz>17) zz=17;   
var zz= map.getZoomLevel();

	request = GXmlHttp.create();

	if (minx2==null) 
		url="xml.php?minx="+minx+"&miny="+miny+"&maxx="+maxx+"&maxy="+maxy+"&zoom="+zz;
	else
		url="xml.php?minx="+minx
		+"&miny="+miny
		+"&maxx="+maxx
		+"&maxy="+maxy
		+"&minx2="+minx2
		+"&miny2="+miny2
		+"&maxx2="+maxx2
		+"&maxy2="+maxy2
		+"&zoom="+zz;

	if ( typeof( window[ 'varLowPrice' ] ) != "undefined" )
		url += "&LowPrice=" + varLowPrice;
	if ( typeof( window[ 'varHighPrice' ] ) != "undefined" )
		url += "&HighPrice=" + varHighPrice;
	if ( typeof( window[ 'varSaleDate' ] ) != "undefined" )
		url += "&SaleDate=" + varSaleDate;
	if ( typeof( window[ 'vacant_search' ] ) != "undefined")
		url += "&type=vacant";

//alert(url);
	request.open("GET", url , true);
	request.onreadystatechange = function() {
	
	if (request.readyState == 4) {

  	////    if (z!=lastzoom) return;

	    var xmlDoc = request.responseXML;
	    markers = xmlDoc.documentElement.getElementsByTagName("marker");
//alert(markers.length);

    cmpltdrqst=1;
    newrequest=1;
    window.setTimeout(mapOne,timeOut);

//  	    if (clear)
//		 clearmap();
//			
//
//	    for (var i = 0; i < markers.length; i++) {
//  	  	createHouse(markers[i]);
//          }

	}
	}
  
	request.send(null);
}

function onLoad() {
	if (map) //only execute if there is a map on the page
	{
		var zoom= map.getZoomLevel();
		var bs = map.getBoundsLatLng();
		startRequest(bs.minX, bs.minY, bs.maxX, bs.maxY, zoom, 1);
	}
}

function update_m() {
alert("herhe");
	var zoom= map.getZoomLevel();
	var bounds = map.getBoundsLatLng();
	startRequest(bounds.minX, bounds.minY, bounds.maxX, bounds.maxY, zoom, 1);
}

function changeDetail() {
	var zoom= map.getZoomLevel();
	var bounds = map.getBoundsLatLng();
	startRequest(bounds.minX, bounds.minY, bounds.maxX, bounds.maxY, zoom, 1);
}
