
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 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)
		{
			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 GLargeMapControl());
	map.addControl(new GOverviewMapControl());
	map.addControl(new GScaleControl());
	map.addControl(new GMapTypeControl());
   	map.enableDoubleClickZoom();
	//var seattle = new GLatLng(47.606389, -122.330833);
	var default_center = new GLatLng(defaultLat, defaultLon);

	if(mapCenter != "")
	{
		mapCenter = mapCenter.split(", ");
		mapZoom = parseInt(mapZoom);

		map.setCenter(new GLatLng(mapCenter[0], mapCenter[1]), mapZoom, G_HYBRID_MAP);
	}
	else
	{
		mapZoom = parseInt(mapZoom);
		map.setCenter(default_center, mapZoom, G_HYBRID_MAP);
	}

   	// ====== set up marker mouseover tooltip div ======
	tooltip = document.createElement("div");
	document.getElementById("map").appendChild(tooltip);
	tooltip.style.visibility="hidden";
   	// ======================================

   	GEvent.addListener(map, 'zoomend', function(oldLevel, newLevel)
   	{
   		var mapPoint = map.getCenter();
   		createSearchCriteria();
   	});

   	GEvent.addListener(map, 'dragend', function(overlay, point)
   	{
   		var mapPoint = map.getCenter();
	   	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 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 infoTabs = "";
			window["infoTabs_" + mls] = [ new GInfoWindowTab("Summary", tempMapInfo[4])];

			var lat = tempMapInfo[1];
			var lng = tempMapInfo[2];
			var featuredListing = tempMapInfo[3];

			var tempInfo = "data_" + mls;
			window["marker_" + mls].openInfoWindowTabsHtml(window["infoTabs_" + 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_HYBRID_MAP);

   	return 1;
}

