
var cicon;

function getCenterPoint()
{
	var minLat = 10000000000;
	var maxLat = 0;
	var minLng = 10000000000;
	var maxLng = -1000000000;
	for( var i = 0; i < points.length; i++ )
	{
		var point = points[i];
		if( point.lat() > maxLat )
			maxLat = point.lat();
		if( point.lat() < minLat )
			minLat = point.lat();
		if( point.lng() > maxLng )
			maxLng = point.lng();
		if( point.lng() < minLng )
			minLng = point.lng();
	}
	
	var latDiff = maxLat-minLat;
	var lngDiff = maxLng - minLng;
//	GLog.write(minLat+latDiff/2+" "+minLng+lngDiff/2);
	var point = new GLatLng(minLat+latDiff/2, minLng+lngDiff/2);
}
				
// Initialize the map
function load(lat, lng, add, cit, st) 
{
  if (GBrowserIsCompatible()) 
  {
		var mapDiv = document.getElementById("map");
		// if we can't find the map div, return. it means we aren't editing any
		// open houses
    	if( !mapDiv )
			return;

		map = new GMap2(mapDiv);
		mapControl = new GSmallMapControl();
		
		cicon = new GIcon();
		cicon.image = "../images/house_icon.png";
		cicon.iconSize = new GSize(14, 15);
		cicon.iconAnchor = new GPoint(7, 15);
		cicon.maxHeight = 15;
		
		map.addControl(mapControl);
		geocoder = new GClientGeocoder();
		geocoder.getLatLng("Boise, ID", function(p){markGeoCode(p)});
		//map.setCenter(init, 12);
		GEvent.addListener(map, "mousemove", mapMouseMove);
		GEvent.addListener(map, "mouseout", mapMouseOut);
		//GEvent.addListener(map, "mouseover", mapMouseOver);
		loadData(lat, lng, add, cit, st);
	}
}

function mapDragEnd()
{
	checkBounds();
}

function loadData(lat, lng, add, cit, st)
{
		var point = null;
		addressInp = document.getElementById(add);
		cityInp = document.getElementById(cit);
		stateInp = document.getElementById(st);
		latInp = document.getElementById(lat);
		lngInp = document.getElementById(lng);
		if( latInp.value == "" || lngInp.value == "" )
		{
			geoCodeAddress();
		}
		else
		{
			point = new GLatLng(latInp.value, lngInp.value);
			
			// this will cause our variables to overwrite each other,
			// but this is OK because it will be the same values.
			markGeoCode(point);
			enableUpdate();
		}
}

function geocodeAddr(addID, add)
{
	var a = document.getElementById(addID);
	var aval = document.getElementById(add);
	a.value = aval.value;
	
	var address = addressInp.value;
	geocoder.getLatLng( address, 
	function(p)
	{
		if( p )
		{
			markGeoCode(p);
		}
		else
		{
			geocoder.getLatLng("Boise, ID",
				function(p2)
				{
					if( p2 )
					{
						markGeoCode(p2);
					}
					else
					{
						geocoder.getLatLng("Boise, ID, USA",
						function(p3)
						{
							if( p3 )
							{
								markGeoCode(p3);
							}
							else
							{
								//alert("no geocode");
								geocoder.GetLatLng("Boise, ID",
								function(p4)
								{
									if( p4 )
									{
										markGeoCode(p4);
									}
									else
									{
										// we can't do anything at this point
										// (except maybe hardcode a number)
									}
								});
							}
						});
					}
				});
			}
		});
}

function loadArr(latArr, detList, mlsList, idList)
{
	var mapDiv = document.getElementById("map");
		// if we can't find the map div, return. it means we aren't editing any
		// open houses
  	if( !mapDiv )
		return;

	map = new GMap2(mapDiv);
	listings = new Array();
	mapControl = new GSmallMapControl();
	map.addControl(mapControl);
		geocoder = new GClientGeocoder();
	geocoder.getLatLng("Boise, ID", function(p){markGeoCodeNoSave(p, latArr, detList, mlsList, idList);});
	GEvent.addListener(map, "dragend", mapDragEnd);	
	GEvent.addListener(map, "zoomend", checkBounds);
}

function markGeoCodeNoSave(point, latArr, detList, mlsList, idList)
{
	map.clearOverlays();
	map.setCenter(point, 13);
	marker = new GMarker(point, {icon: cicon});
	map.addOverlay(marker);
	var p = null;
	var lst = latArr.split('|');
	var mls = mlsList.split('|');
	var idL = idList.split('|');
	var det = detList.split('^');
	for (var i=0; i < lst.length; i++)
	{	
		listings[i] = new listing();
		listings[i].mlsNum = mls[i];
		listings[i].id = idL[i];
		var pts = lst[i].split(',');
		var dets = det[i].split('|');
		p = new GLatLng(pts[0], pts[1]);
		listings[i].pt = p;
		totLat = totLat + parseFloat(pts[0]);
		totLng = totLng + parseFloat(pts[1]);
		totCt++;
		var mkr = new GMarker(p, {icon: cicon});
		mkr.bindInfoWindowHtml(createDetailHTML(dets[0], dets[1], dets[2], 
		dets[3], dets[4], dets[5], dets[6], dets[7], dets[8]));
		map.addOverlay(mkr);
	}
	
	checkBounds();
	
	if (lst.length > 0)
	{
		center = new GLatLng(totLat / totCt, totLng / totCt);
		map.setCenter(center, 15);
		for (var k=0; k < lst.length; k++)
		{
			var pts = lst[k].split(',');
			p = new GLatLng(pts[0], pts[1]);
			if (!map.getBounds().contains(p))
			{
				map.zoomOut();
				checkBounds();
				k--;
			}
		}
	}
}

function checkBounds()
{
	var shown = document.getElementById("lblVisible");
	var notshown = document.getElementById("lblInvisible");
	var showCt = 0;
	if (listings != null)
	{
		for (var i=0; i < listings.length; i++)
		{
			var dli = document.getElementById(listings[i].id);
			if (!map.getBounds().contains(listings[i].pt))
			{
				dli.style.display = "none";
			}
			else
			{
				showCt++;
				dli.style.display = "";
			}
		}
		shown.innerHTML = showCt;
		notshown.innerHTML = listings.length - showCt;
	}
}

function createDetailHTML(mlsnumber, address, city, askingprice, numbeds, numbaths, sqft, lotsz, nextoh)
{
    var html = "";
    html += mlsnumber + "<br>";
    html += address + "<br>";
    html += city + "<br>";
    html += askingprice + "<br>";
    html += numbeds + "<br>";
    html += numbaths + "<br>";
    html += sqft + "<br>";
    html += lotsz + "<br>";
    html += nextoh;
	return html;
}

function saveMarkedPoint()
{
	latInp.value = marker.getPoint().lat();
	lngInp.value = marker.getPoint().lng();
}


// map and mouse events

var origPoint;
var dragging;
function mapMouseMove(point)
{
	checkBounds();
	if( dragging && marker )
	{
		marker.setPoint(point);
		saveMarkedPoint();
	}
}

function mapMouseOver()
{
	var textArea = document.getElementById("testText");
	textArea.select();
}

function mapMouseOut()
{
	if( dragging && marker )
	{
		marker.setPoint(origPoint);
	}
}

function dragIconStart()
{
	dragging = true;
	if( marker )
		origPoint = marker.getPoint();
}

function dragIconEnd()
{
	dragging = false;
}

function dragIconEndMap()
{
	var map = document.getElementById("testText");
	map.select();
	dragging = false;
}

function markerDragEnd(v)
{
	saveMarkedPoint();
	map.panTo(marker.getPoint());
}

// marker events
var marker;

function markGeoCode(point)
{
	map.clearOverlays();
	map.setCenter(point, 13);
	marker = new GMarker(point, {icon: cicon, draggable: true, bouncy: false});
	GEvent.addListener(marker, "dragend", markerDragEnd);
	map.addOverlay(marker);
	
	saveMarkedPoint();
	//GLog.write("Lat:" + latInp.value);
	//GLog.write("Lng:" + lngInp.value);	
}

function regeocode(updateID)
{
	try
	{
		updateBtn = document.getElementById(updateID);
		updateBtn.disabled = true;
	}
	catch (err)
	{
	}
	geoCodeAddress();
}

function geoCodeAddress()
{
	var address = addressInp.value;
	var city = cityInp.value;
	var state = stateInp.value;
	//GLog.write(address +", "+city+", "+state);
	if (city == "" && state == "")
	{
		city = "Boise";
		state = "ID";
	}
	geocoder.getLatLng( address+", "+city+" "+state, 
	function(p)
	{
		if( p )
		{
			markGeoCode(p);
		}
		else
		{
			geocoder.getLatLng(city+" "+state,
				function(p2)
				{
					if( p2 )
					{
						markGeoCode(p2);
					}
					else
					{
						geocoder.getLatLng(state + ", USA",
						function(p3)
						{
							if( p3 )
							{
								markGeoCode(p3);
							}
							else
							{
								//alert("no geocode");
								geocoder.GetLatLng("Boise, ID",
								function(p4)
								{
									if( p4 )
									{
										markGeoCode(p4);
									}
									else
									{
										// we can't do anything at this point
										// (except maybe hardcode a number)
									}
								});
							}
						});
					}
				});
			}
		});
}
function geoCodeZip(zipV)
{
	geocoder = new GClientGeocoder();
	var gridZ = document.getElementById(zipV);
	var zip = gridZ.value;
	if (zip == "")
	{
		geocoder.getLatLng("Boise, ID", function(p){markGeoCode(p)});
	}
	else
	{
		geocoder.getLatLng(zip, function(p){markGeoCode(p)});
	}
}

function geoCodeZipPhotog(zipV, srchBtn)
{
	geocoder = new GClientGeocoder();
	var gridZ = document.getElementById(zipV);
	var zip = gridZ.value;
	if (zip == "")
	{
		geocoder.getLatLng("Boise, ID", function(p){markGeoCodeZip(p, srchBtn)});
	}
	else
	{
		geocoder.getLatLng(zip, function(p){markGeoCodeZip(p, srchBtn)});
	}
}

function markGeoCodeZip(point, srchBtn)
{
	map.clearOverlays();
	map.setCenter(point, 13);
	
	marker = new GMarker(point, {icon: cicon, draggable: true, bouncy: false});
	GEvent.addListener(marker, "dragend", markerDragEnd);
	map.addOverlay(marker);
	
	saveMarkedPointZip(srchBtn);
	//GLog.write("Lat:" + latInp.value);
	//GLog.write("Lng:" + lngInp.value);	
}

function saveMarkedPointZip(srchBtn)
{
	latInp.value = marker.getPoint().lat();
	lngInp.value = marker.getPoint().lng();
	__doPostBack(srchBtn, '');
}

function setVars(add, cit, st)
{
	var gridA = document.getElementById(add);
	var gridC = document.getElementById(cit);
	var gridS = document.getElementById(st);
	//GLog.write(gridA.value);
	//GLog.write(gridC.value);
	//GLog.write(gridS.value);
	addressInp.value = gridA.value;
	cityInp.value = gridC.value;
	stateInp.value = gridS.value;
}

function setVarsCheckingLatLng(add, cit, st, lat, lng)
{
	var latA = document.getElementById(lat);
	var lngA = document.getElementById(lng);
	var gridA = document.getElementById(add);
	var gridC = document.getElementById(cit);
	var gridS = document.getElementById(st);
	if (latA.value != "" && lngA.value != "")
	{
		return;
	}
	else
	{
		//GLog.write(gridA.value);
		//GLog.write(gridC.value);
		//GLog.write(gridS.value);
		addressInp.value = gridA.value;
		cityInp.value = gridC.value;
		stateInp.value = gridS.value;
		geoCodeAddress();
	}
}

function setHiddenFields(latID, lngID, addID, citID, stID, latVal, lngVal, addVal, citVal, stVal)
{
	document.getElementById(latID).value = latVal;
	document.getElementById(lngID).value = lngVal;
	document.getElementById(addID).value = addVal;
	document.getElementById(citID).value = citVal;
	document.getElementById(stID).value = stVal;
}

function enableUpdate()
{
	try
	{
		updateBtn.disabled = false;
	}
	catch (err)
	{
	}
}

function responseEnd(sender, arguments)
{
	loadData();
}

function requestStart(updateID)
{
	try
	{
		updateBtn = document.getElementById(updateID);
		updateBtn.disabled = true;
	}
	catch (err)
	{
	}
}

var map_canvas;
var homePoint;
var orgPoint;

function initDirections(orgaddr, zip)
{
	if (GBrowserIsCompatible())
	{
		if (homePoint != null)
		{
			map_canvas = new GMap2(document.getElementById("map"));
			map_canvas.setCenter(new GLatLng(homePoint.lat(), homePoint.lng()), 10);
			var waypoints = new Array();
			var s = new GLatLng(orgPoint.lat(), orgPoint.lng());
			var h = new GLatLng(homePoint.lat(), homePoint.lng());
			waypoints[0] = h;
			waypoints[1] = s;
			var directionsPanel = document.getElementById("divDir");
			gdir = new GDirections(map_canvas, directionsPanel);
			GEvent.addListener(gdir, "error", handleErrors);
			gdir.loadFromWaypoints(waypoints);
		}
	}
}

function setHome(addr, orgaddr, zip)
{
	geocoder = new GClientGeocoder();
	geocoder.getLatLng(addr, function(p){homePoint = p; geocodeOrg(addr, orgaddr, zip);}); 
}

function geocodeOrg(addr, orgaddr, zip)
{
	geocoder.getLatLng(orgaddr + ", " + zip, function(p){orgPoint = p; initDirections(orgaddr, zip);});
}

function handleErrors(){
	   if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
	     alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + gdir.getStatus().code);
	   else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
	     alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code);
	   
	   else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
	     alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);

	//   else if (gdir.getStatus().code == G_UNAVAILABLE_ADDRESS)  <--- Doc bug... this is either not defined, or Doc is wrong
	//     alert("The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.\n Error code: " + gdir.getStatus().code);
	     
	   else if (gdir.getStatus().code == G_GEO_BAD_KEY)
	     alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);

	   else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
	     alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);
	    
	   else alert("An unknown error occurred.");
	   
	}

