
var request = null;
var siteId = null;
var officeID = null;
var agentID = null;
var domainName = null;
var url = null;
var indexVar = null;
var clientSearch = null;
var mapZoom = null
var mapCenter = null;
var map = null;
var icon = null;
var tooltip = null;
var defaultLat = null;
var defaultLon = null;
//var windowOpen = 0;
var mapDataPoints = new Array();
var mapToolTipData = new Array();
var directionsActive = 0;

var om = new OverlayMessage(document.getElementById('map'));

function setIndex(temp)
{
	indexVar = temp;
}

function setOfficeID(temp)
{
	officeID = temp;
}

function setAgentID(temp)
{
	agentID = temp;
}

function setSiteID(temp)
{
	siteId = temp;
}

function setMapZoom(temp)
{
	mapZoom = temp;
}

function setMapCenter(temp)
{
	mapCenter = temp;
}

function setDefault_lat(temp)
{
	defaultLat = temp;
}
function setDefault_lon(temp)
{
	defaultLon = temp;
}

function setDomain(temp)
{
	domainName = temp;
	url =  domainName + "/lib/map/get_listings.php?stuff=" + new Date().getTime() + "&site_id=" + siteId;
}

function startMessage(displayMessage)
{
	om.Set(displayMessage);
}

// remove the loading message when the page has finished loading
function pausedClearMessage()
{
	//window.setTimeout("om.Clear();", 1500);
}

function clearMessage()
{
	om.Clear();
}

function createRequest()
{
	try
	{	request = new XMLHttpRequest();	}
	catch(trymicrosoft)
	{
		try
		{	request = new ActiveXObject("Msxm12.XMLHTTP");	}
		catch(othermicrosoft)
		{
			try
			{	request = new ActiveXObject("Microsoft.XMLHTTP");	}
			catch(fail)
			{	request = null;	}
		}
	}
	if(request == null)
	{	alert("Error creating XMLHttpRequest!");	}
}

function createSearchCriteria()
{
	// Displays Loading Message
	startMessage("<img src=\"images/map/google-map-loading-thingy.gif\"/>");
	//document.getElementById("hello").style.display = "inline";
	try{
	createRequest();

	var mapBounds = map.getBounds();
	var centerBounds = map.getCenter();
	var zoomLevel = map.getZoom();

	mapUrl = url + "&officeID=" + officeID + "&agentID=" + agentID + "&mapbounds=" + mapBounds;
	mapUrl += "&mapCenter=" + centerBounds + "&zoomLevel=" + zoomLevel;

	if(document.getElementById("class_id").value != "")
	{
		mapUrl = mapUrl + "&class_id=" + document.getElementById("class_id").value;
	}

	if(document.getElementById("bedrooms").value != "")
	{
		mapUrl = mapUrl + "&bedrooms=" + document.getElementById("bedrooms").value;
	}

	if(document.getElementById("bathrooms").value != "")
	{
		mapUrl = mapUrl + "&bathrooms=" + document.getElementById("bathrooms").value;
	}

	if(document.getElementById("price_min").value != "")
	{
		mapUrl = mapUrl + "&price_min=" + document.getElementById("price_min").value;
	}

	if(document.getElementById("price_max").value != "")
	{
		mapUrl = mapUrl + "&price_max=" + document.getElementById("price_max").value;
	}

	//document.getElementById("message").innerHTML = mapUrl;
	//alert(mapUrl);
	request.open("GET", mapUrl, true);
	request.onreadystatechange = updateMap;
	request.send(null);
	}
	catch(err)
	{
		alert(err);
	}



}

function updateMap()
{
	if(request.readyState == 4)
	{
		var mapPoints = request.responseText;
		var tempMap = mapPoints.split("|");
		//alert(mapPoints);
		tempMap.reverse();
		var showListings = tempMap.pop();
		var listingsCount = tempMap.pop();

		map.clearOverlays();

		if(showListings == 1)
		{
			clearCurrentPoints();

			var tempListingsCount = listingsCount.split("+");
			clientSearch = tempListingsCount[2];
			if(tempListingsCount[0] == tempListingsCount[1])
			{
				document.getElementById("message").innerHTML = "Showing " + tempListingsCount[0] + " of " + tempListingsCount[1] + " Listings";
			}
			else
			{
				document.getElementById("message").innerHTML = "Showing " + tempListingsCount[0] + " of " + tempListingsCount[1] + " Listings";
			}
			while(tempMap.length != 0)
			{
				var data = tempMap.pop();
				var lat = tempMap.pop();
				var lng = tempMap.pop();

				var tempData = data.split("-");
				var mls = tempData[0];
				var toolTipData = tempData[1];
				var featuredListing = tempData[2]
				var classId = tempData[3];

				var somePoints = new outerPoints();
				somePoints(mls, classId, lat, lng, toolTipData, featuredListing);
			}

		}
		else if(showListings == 0)
		{
			document.getElementById("message").innerHTML = "<font color='red'><b>" + listingsCount + " Results. Please narrow your search results.</b></font>";
		}

		//document.getElementById("loading_image").style.visibility = "hidden";
		clearMessage();
	}
}

function getMlsInfo(mls)
{
	mlsUrl = url + "&index=" + indexVar + "&officeID=" + officeID + "&agentID=" + agentID + "&mls=" + mls;

	//document.getElementById("message").innerHTML = mlsUrl;
	//alert(mlsUrl);
	request.open("GET", mlsUrl, true);
	request.onreadystatechange = bubbleInfo;
	request.send(null);
}

function setFavorites(mls)
{
	favoritesUrl = url + "&cid=" + clientID + "&mls=" + mls + "&favorites=1";

	request.open("GET", favoritesUrl, true);
	request.onreadystatechange = favoritesComplete;
	request.send(null);
}

function favoritesComplete()
{
	if(request.readyState == 4)
	{
		var favoritesResponse = request.responseText;

		if(favoritesResponse == 1)
		{
			document.getElementById("favorites").innerHTML = "<font color='blue'><b>This listing has been added to your Favorites.</b></font>";
		}
		else if(favoritesResponse == 2)
		{
			document.getElementById("favorites").innerHTML = "<font color='blue'><b>This listing is already in your Favorites.</b></font>";
		}
		else if(favoritesResponse == 0)
		{
			document.getElementById("favorites").innerHTML = "<font color='blue'><b>You must sign in to Use this Feature.</b></font>";
		}
	}
}

function drawMap()
{
	//Base Icon Information
   	icon = new GIcon();
	icon.iconSize = new GSize(32, 32);
	icon.shadowSize = new GSize(59, 32);
	icon.iconAnchor = new GPoint(16, 0);
	icon.infoWindowAnchor = new GPoint(13, 13);

	map = new GMap2(document.getElementById("map"));
	map.addControl(new YSliderControl());
	map.addControl(new zoomInControl());
	map.addControl(new zoomOutControl());
	//map.addControl(new GLargeMapControl());
	map.addControl(new GOverviewMapControl());
	map.addControl(new GScaleControl());
	map.addControl(new GMapTypeControl());
	//map.addControl(new ExtMapTypeControl({showTraffic: true, showTrafficKey: true}));

   	/* first set of options is for the visual overlay.*/
	var boxStyleOpts = {opacity: .5, border: "2px solid black"}
	/* second set of options is for everything else */
	var otherOpts = {
	  buttonHTML: "<img src='http://www.northwestidx.com/images/map/zoom_select_tool_off.png' onMouseover='showtip(this,event,\"Start Zoom Box\")' onMouseout='hidetip()' />",
	  buttonZoomingHTML: "<img src='http://www.northwestidx.com/images/map/zoom_select_tool_on.png' onMouseover='showtip(this,event,\"Close Zoom Box\")' onMouseout='hidetip()' />",
	  buttonStartingStyle: {width: '32px'},
	  overlayRemoveTime: 2000
	};

	map.addControl(new DragZoomControl(boxStyleOpts, otherOpts), new GControlPosition(G_ANCHOR_TOP_LEFT,new GSize(7,7)));
   	map.enableDoubleClickZoom();

	var default_center = new GLatLng(defaultLat, defaultLon);
	var windowOpen=0;

	if(mapCenter != "")
	{
		mapCenter = mapCenter.split(", ");
		mapZoom = parseInt(mapZoom);

		map.setCenter(new GLatLng(mapCenter[0], mapCenter[1]), mapZoom, G_NORMAL_MAP);
	}
	else
	{
		mapZoom = parseInt(mapZoom);
		map.setCenter(default_center, mapZoom, G_NORMAL_MAP);
	}

   	// ====== set up marker mouseover tooltip div ======
	tooltip = document.createElement("div");
	document.getElementById("map").appendChild(tooltip);
	tooltip.style.visibility="hidden";
   	// ======================================
   	GEvent.addListener(map, 'infowindowopen', function() {  	windowOpen = 1;  	});
   	GEvent.addListener(map, 'infowindowclose', function() {  	windowOpen = 0;  	});

   	GEvent.addListener(map, 'zoomend', function(oldLevel, newLevel)
   	{
   		var mapPoint = map.getCenter();
   		createSearchCriteria();
   	});

   	GEvent.addListener(map, 'dragend', function(overlay, point)
   	{
   		var mapPoint = map.getCenter();
	   	createSearchCriteria();
   	});

   	GEvent.addListener(map, 'moveend', function(overlay, point)
   	{
   		var mapPoint = map.getCenter();
	   	//createSearchCriteria();

	   	if(windowOpen == 0)
   		{	createSearchCriteria();  	}

   	});

   	return 1;
}

   	function createMarkerFunction()
   	{
	   	return function createMarker(point, mls, toolTipData, pointColor)
		{
		  	var iconMarker = new GIcon(icon);

		  	if(pointColor == 0)
		  	{
		  		iconMarker.image = domainName + "/images/map/map_house1.png";
		  		iconMarker.shadow = domainName + "/images/map/map_house1s.png";
		  	}
		  	else
		  	{
		  		iconMarker.image = domainName + "/images/map/map_house2.png";
		  		iconMarker.shadow = domainName + "/images/map/map_house2s.png";
		  	}

			var marker = new GMarker(point, iconMarker);
			marker.icon = iconMarker;
			marker.tooltip = '<div class="tooltip">' + toolTipData + '</div>';
		  	GEvent.addListener(marker, 'click', function() { getMlsInfo(mls); });
		  	GEvent.addListener(marker, 'infowindowclose', function() {

		  		var tempInfo = "data_" + mls;
				if(document.getElementById(tempInfo))
				{
					document.getElementById(tempInfo).innerHTML = "";
				}
		  	});

		  	//  ======  The new marker "mouseover" and "mouseout" listeners  ======
        			GEvent.addListener(marker,"mouseover", function() {	showTooltip(marker);       });
        			GEvent.addListener(marker,"mouseout", function() {	tooltip.style.visibility="hidden";	});

		  	return marker;
		}
   	}

   	function highlightIcon(lat, lng, mls)
   	{
		var toolTipData = window["marker_" + mls].tooltip;

		var point = new GLatLng(lat, lng);
		var markerResource = new createMarkerFunction();
		window["marker_" + mls] = markerResource(point, mls, toolTipData, 'green');
		map.addOverlay(window["marker_" + mls]);
   	}

   	function clearCurrentPoints(currentMls)
	{
		if(!currentMls) currentMls = 0

		for(var i = 0; i < mapDataPoints.length; i++)
		{
			var tempMLS = mapDataPoints[i];
			var marker = null;

			if(tempMLS != currentMls)
			{
				map.removeOverlay(window["marker_" + tempMLS]);
			}
		}

		if(directionsActive == 0)
		{
			mapDataPoints = new Array();
		}
	}

	function outerPoints()
	{
		return function addPoints(mls, classId, tempLat, tempLng, toolTipData, featuredListing)
		{
			if(featuredListing == 0)
			{	var pointColor = 0;	}
			else if(featuredListing == 1)
			{	var pointColor = 1;	}

			var point = new GLatLng(tempLat, tempLng);
			var markerResource = new createMarkerFunction();
			var marker = null;
			window["marker_" + mls] = markerResource(point, mls, toolTipData, pointColor);
			map.addOverlay(window["marker_" + mls]);
		}
	}

	function bubbleInfo()
	{
		if(request.readyState == 4)
		{
			var mapInfo = request.responseText;
			tempMapInfo = mapInfo.split("|");

			var mls = tempMapInfo[0];
			var lat = tempMapInfo[1];
			var lng = tempMapInfo[2];
			var featuredListing = tempMapInfo[3];

			var directionForm = '<form action="javascript:void(0);" onsubmit="getDirections(this.from.value, this.toLat.value, this.toLng.value, this.toMls.value); return false">';
			directionForm += '<table width="330"><tr><td><br/><br/><br/>';
			directionForm += '<table bgcolor="white" width="300">';
			directionForm += '	        <tr align="center"><td align="right"><b>Starting Location:</b></td>';
			directionForm += '	        <td>';
			directionForm += '	        <input type="text" size="35" id="fromAddress" name="from" value="808 Post AVE, Seattle, WA 98104"/>';
			directionForm += '	        <input type="hidden" name="toLat" id="toLat" value="' + lat + '" />';
			directionForm += '	        <input type="hidden" name="toLng" id="toLng" value="' + lng + '" />';
			directionForm += '	        <input type="hidden" name="toMls" id="toMls" value="' + mls + '" /></td></tr>';
			directionForm += '	        <tr><td>&nbsp;</td><td align="left">&nbsp;<input name="submit" type="submit" value="Get Directions!" />';
			//directionForm += '	        <a href="javascript:void(0);" onclick="clearDrivingDirections();">Clear Directions</a></td>';
			directionForm += '	        </td></tr>';
			directionForm += '	        </table>';
			directionForm += '</td></tr></table>';
			directionForm += '	</form>';

			var infoTabs = "";
			window["infoTabs_" + mls] = [
				new GInfoWindowTab("Summary", tempMapInfo[4]),
				//new GInfoWindowTab("Description", tempMapInfo[5]),
				new GInfoWindowTab("Directions", directionForm)
			];


			var tempInfo = "data_" + mls;
			window["marker_" + mls].openInfoWindowTabsHtml(window["infoTabs_" + mls]);
			//mapDataBubble[] = window["marker_" + mls];

		}

	}

	// ====== This function displays the tooltip ======
	// it can be called from an icon mousover or a sidebar mouseover
	function showTooltip(marker)
	{
	      	tooltip.innerHTML = marker.tooltip;

		var point=map.getCurrentMapType().getProjection().fromLatLngToPixel(map.getBounds().getSouthWest(),map.getZoom());
		var offset=map.getCurrentMapType().getProjection().fromLatLngToPixel(marker.getPoint(),map.getZoom());
		var anchor=marker.getIcon().iconAnchor;
		var width=marker.getIcon().iconSize.width;

		var pos = new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize((offset.x - point.x - anchor.x - 15) + width,- offset.y + point.y +anchor.y - 10));

		pos.apply(tooltip);
		tooltip.style.visibility="visible";
	  }


function drawBaseMap()
{

	map = new GMap2(document.getElementById("map"));

	document.getElementById("message").innerHTML = "";
	var default_center = new GLatLng(defaultLat, defaultLon);

	mapZoom = parseInt(mapZoom);
	map.setCenter(default_center, mapZoom, G_NORMAL_MAP);

   	return 1;
}


/**
 *
 * @access public
 * @return void
 **/
function clickZoomIn()
{
	map.zoomIn();
}

/**
 *
 * @access public
 * @return void
 **/
function clickZoomOut()
{
	map.zoomOut();
}

/**
 * Gets address from Google Map API
 */
function getDirections(from_address, toLat, toLng, toMls)
{
	var directionWindow = "map_directions.php?site_id=" + siteId + "&mls=" + toMls + "&f=" + escape(from_address);
	window.open(directionWindow, 'MapDirections', 'scrollbars=yes,resizable=yes,width=750,height=850')
	document.getElementById("getFromAddress").style.display = "none";
}

/**
 * Handles Errors returned for directiosn on google maps.
 */
function handleErrors()
{
	if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
	{
		var message = "No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is ";
		message += "relatively new,	or it may be incorrect.\nError code: " + gdir.getStatus().code;

		alert(message);
	}
	else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
	{
		var message = "A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n ";
		message += "Error code: " + gdir.getStatus().code;
		alert(message);
	}


	   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.");

}
