var request = null;
var siteId = null;
var officeID = null;
var agentID = null;
var domainName = null;
var url = null;
var clientID = null;
var clientSearch = null;
var mapZoom = null
var mapCenter = null;
var map = null;
var icon = null;
var tooltip = null;
var windowOpen = 0;
var cache = 0;
var display_count = 0;
var current_count = 0;
var defaultLat = null;
var defaultLng = null;
var db = null;

var om = new OverlayMessage(document.getElementById('map'));   

function setCID(temp)
{
	clientID = 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 setDomainName(temp)
{
	domainName = temp;
	
	if(db == 1)
	{
		url = "http://" + domainName + "/lib/map/get_listings_db.php?stuff=" + new Date().getTime() + "&site_id=" + siteId;
	}
	else
	{
		url = "http://" + 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(count)
{	
	// Displays Loading Message
	
	current_count = count;
	if(count == 1)
	{
		startMessage("<img src=\"images/map/google-map-loading-thingy.gif\"/>");
		map.clearOverlays();
	}
	
	try
	{
		createRequest();
	
		var mapBounds = map.getBounds();
		var centerBounds = map.getCenter();
		var zoomLevel = map.getZoom();
		
		mapUrl = url + "&cid=" + clientID + "&officeID=" + officeID + "&agentID=" + agentID + "&mapbounds=" + mapBounds + "&client_search=" + clientSearch;
		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;
		}	
		
		//if(cache == 1)
		//{
			mapUrl = mapUrl + "&cache=1&count=" + count + "&display_count=" + display_count;
			//alert(mapUrl);
		//}
		
		//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("|");
		
		if(cache == 1)
		{
			//alert(mapPoints);
		}
		
		if(siteId == 45)
		{
			//alert(mapPoints);
		}
		tempMap.reverse();
		var showListings = tempMap.pop();
		var listingsCount = tempMap.pop();			
			
		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();
		
		current_count++;
		if(current_count <= 6 || showListings == 0)
		{
			createSearchCriteria(current_count);
		}
	}
}

function getMlsInfo(mls, featured)
{
	mlsUrl = url + "&cid=" + clientID + "&officeID=" + officeID + "&agentID=" + agentID + "&mls=" + mls + "&client_search=" + clientSearch + "&featured=" + featured;
	//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(map_type)
{
	//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();

	if(map_type == "road")
   	{
   		var new_map_type = G_NORMAL_MAP;
   	}
   	else if(map_type == "aerial")
   	{
   		var new_map_type = G_SATELLITE_MAP;
   	}
   	else if(map_type == "hybrid")
   	{
   		var new_map_type = G_HYBRID_MAP;
   	}
	
	if(defaultLat == 0)
	{
		var defaultCenter = new GLatLng(36.175000, -115.136389);
	}
	else
	{
		var defaultCenter = new GLatLng(defaultLat, defaultLng);
	}
	
	//var mercerIsland = new GLatLng(36.175000, -115.136389);
	
	if(mapCenter != "")
	{
		mapCenter = mapCenter.split(", ");
		mapZoom = parseInt(mapZoom);
		
		map.setCenter(new GLatLng(mapCenter[0], mapCenter[1]), mapZoom, new_map_type);
	}
	else
	{
		mapZoom = parseInt(mapZoom);
		map.setCenter(defaultCenter, mapZoom, new_map_type);
	}
	
   	// ====== 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(1);
   	});
    
   	GEvent.addListener(map, 'dragend', function(overlay, point) 
   	{ 	
   		var mapPoint = map.getCenter();
	   	createSearchCriteria(1);
   	});

   	GEvent.addListener(map, 'moveend', function(overlay, point) 
   	{ 	
   		var mapPoint = map.getCenter();
	   	//createSearchCriteria();
	   	
	   	if(windowOpen == 0)
   		{	createSearchCriteria(1);  	}
	   	
   	});

   	return 1;
}    

   	function createMarkerFunction()
   	{
	   	return function createMarker(point, mls, toolTipData, pointColor) 
		{
		  	var iconMarker = new GIcon(icon);

		  	if(pointColor == 0)
		  	{
		  		iconMarker.image = "http://" + domainName + "/images/map/map_house1.png";
		  		iconMarker.shadow = "http://" + domainName + "/images/map/map_house1s.png";
		  	}
		  	else
		  	{
		  		iconMarker.image = "http://" + domainName + "/images/map/map_house2.png";
		  		iconMarker.shadow = "http://" + 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, pointColor); });
		  	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])];
			
			//, new GInfoWindowTab("Description", tempMapInfo[5])	];
			
			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";
	  }
