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 map = null;
var icon = null;
var tooltip = null;
var defaultLat = null;
var defaultLon = null;
var sid = null;
var debug = 0;
var setUrl = 0;
var mapDataPoints = new Array();
var mapToolTipData = new Array();
var directionsActive = 0;
var remoteLocation = null;
var listingLinks = 0;
var om = new OverlayMessage(document.getElementById('map-search'));

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 setDefault_lat(temp){ defaultLat = temp; }
function setDefault_lon(temp){ defaultLon = temp; }
function setRemoteLoc(temp){ remoteLocation = 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); }
function pausedClearMessage(){ window.setTimeout("om.Clear();", 1500); }
function clearMessage(){ om.Clear(); }
function clickZoomIn(){ map.zoomIn(); }
function clickZoomOut(){ map.zoomOut(); }
function sendMessage(_msg){ if(_msg != '' && debug==1){ document.getElementById("message").innerHTML = _msg; }}

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){ sendMessage("Error creating XMLHttpRequest!"); }
}

function createSearchCriteria(genID){
	// Displays Loading Message
	startMessage("<img src=\""+remoteLocation+"images/map/google-map-loading-thingy.gif\"/>");

	try{
		createRequest();

		var mapBounds = map.getBounds();
		var centerBounds = map.getCenter();
		var mapZoom = map.getZoom();

		mapUrl=url + "&officeID=" + officeID + "&agentID=" + agentID + "&mapbounds=" + mapBounds;
		mapUrl+="&mapCenter=" + centerBounds + "&mapZoom=" + mapZoom + "&listingLinks=" + listingLinks;
		if(genID == 1){ mapUrl+="&genID=1"; } else { mapUrl+="&sid="+sid; }
		if(document.getElementById("class_id").value!= "")        { mapUrl+="&class_id=" + document.getElementById("class_id").value; }
		if(document.getElementById("bedrooms").value!= "")        { mapUrl+="&bedrooms=" + document.getElementById("bedrooms").value; }
		if(document.getElementById("bathrooms").value!= "")       { mapUrl+="&bathrooms=" + document.getElementById("bathrooms").value; }
		if(document.getElementById("price_range_low").value!= "") { mapUrl+="&price_range_low=" + document.getElementById("price_range_low").value; }
		if(document.getElementById("price_range_high").value!= ""){ mapUrl+="&price_range_high=" + document.getElementById("price_range_high").value; }

		sendMessage(mapUrl);
		if(debug==1) { window.clipboardData.setData("Text", mapUrl); }
		if(setUrl==1){ document.getElementById("link_url").value = mapUrl; }
		request.open("GET", mapUrl, true);
		request.onreadystatechange = updateMap;
		request.send(null);
	}
	catch(err) {sendMessage(err+"<br>"+mapUrl);}
}

function updateMap(){

	if(request.readyState == 4){

		var mapPoints = request.responseText;
		var tempMap = mapPoints.split("|");
		//sendMessage(mapPoints);
		tempMap.reverse();
		var showListings = tempMap.pop();
		var listingsCount = tempMap.pop();
		var tempSid = tempMap.pop();
		if(tempSid != ""){ sid = tempSid; }

		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";
			}
			var intPointCount = 1;
			while(tempMap.length != 0){

				var data = tempMap.pop();
				var lat = tempMap.pop();
				var lng = tempMap.pop();

				var tempData = data.split("+");// was split on -
				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);
				//sendMessage(intPointCount)
				intPointCount++;
			}

		} else if(showListings == 0){
			document.getElementById("message").innerHTML = "<font color='red'><b>" + listingsCount + " Results. Please narrow your search results.</b></font>";
		}
		clearMessage();
	}
}

function getMlsInfo(mls){
	try{
		mlsUrl = url + "&index=" + indexVar + "&officeID=" + officeID + "&agentID=" + agentID + "&sid=" + sid+ "&mls=" + mls;
		sendMessage(mlsUrl);
		if(debug==1) { window.clipboardData.setData("Text", mlsUrl); }
		request.open("GET", mlsUrl, true);
		request.onreadystatechange = bubbleInfo;
		request.send(null);
	} catch(err){ sendMessage(err); }
}

function setFavorites(mls){
	try{
		favoritesUrl = url + "&cid=" + clientID + "&mls=" + mls + "&favorites=1";
		request.open("GET", favoritesUrl, true);
		request.onreadystatechange = favoritesComplete;
		request.send(null);
	} catch(err){ sendMessage(err); }
}

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-search"));
	map.addControl(new YSliderControl());
	map.addControl(new zoomInControl());
	map.addControl(new zoomOutControl());
	map.addControl(new resetControl());
	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: .3, border: "2px solid black"}
	/* second set of options is for everything else */
	var otherOpts = {
	  buttonHTML: "<img src='"+remoteLocation+"images/map/zoom_select_tool_off.png' onMouseover='showtip(this,event,\"Start Zoom Box\")' onMouseout='hidetip()' />",
	  buttonZoomingHTML: "<img src='"+remoteLocation+"images/map/zoom_select_tool_on.png' onMouseover='showtip(this,event,\"Close Zoom Box\")' onMouseout='hidetip()' />",
	  buttonStartingStyle: {width: '32px'},
	  overlayRemoveTime: 2000
	};

	var default_center = new GLatLng(defaultLat, defaultLon);
	var windowOpen=0;
	map.addControl(new DragZoomControl(boxStyleOpts, otherOpts), new GControlPosition(G_ANCHOR_TOP_LEFT,new GSize(7,7)));
   	map.enableDoubleClickZoom();
	mapZoom = parseInt(mapZoom);
	map.setCenter(default_center, mapZoom, G_NORMAL_MAP);

   	// ====== set up marker mouseover tooltip div ======
	tooltip = document.createElement("div");
	document.getElementById("map-search").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();
	   	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 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 border="0" cellspacing="1" cellpadding="4" class="map-bubble">';
		directionForm += '<tr><td align="center"><b>Enter Your Starting Location Below</b><br></td></tr>';
		directionForm += '<tr><td align="center">';
		directionForm += '	<input type="text" size="45" id="fromAddress" name="from" onkeyup="javascript:var subElem=document.getElementById(\'submitDirections\');if(document.getElementById(\'fromAddress\').value!=\'\'){subElem.disabled=false;}else{subElem.disabled=true;}"/>';
		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 + '" />';
		directionForm += '</td></tr><td align="center"><b>Example: 808 Post AVE, Seattle, WA 98104</b><br></td></tr>';
		directionForm += '<tr><td align="center"><input id="submitDirections" name="submit" type="submit" value="Get Directions!" disabled="true"/></td></tr>';
		directionForm += '</table></form>';

		var infoTabs = "";
		if(tempMapInfo[5]!=""){
			window["infoTabs_" + mls] = [new GInfoWindowTab("Summary", tempMapInfo[4]),new GInfoWindowTab("Description", tempMapInfo[5]),new GInfoWindowTab("Directions", directionForm)];
		} else {
			window["infoTabs_" + mls] = [new GInfoWindowTab("Summary", tempMapInfo[4]),new GInfoWindowTab("Directions", directionForm)];
		}
		sendMessage("handler called:" + mls);
		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-search"));

	document.getElementById("message").innerHTML = "";
	var default_center = new GLatLng(defaultLat, defaultLon);

	mapZoom = parseInt(mapZoom);
	map.setCenter(default_center, mapZoom, G_NORMAL_MAP);

   	return 1;
}

/**
 * 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_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 sendMessage("An unknown error occurred.");

}

/*
Text Link/Image Map Tooltip Script-
© Dynamic Drive (www.dynamicdrive.com)
For full source code, and 100's more DHTML scripts
Visit http://www.dynamicdrive.com
*/

if (!document.layers&&!document.all&&!document.getElementById)
event="test"
function showtip(current,e,text){

if (document.all||document.getElementById){
thetitle=text.split('<br>')
if (thetitle.length>1){
thetitles=''
for (i=0;i<thetitle.length;i++)
thetitles+=thetitle[i]
current.title=thetitles
}
else
current.title=text
}

else if (document.layers){
document.tooltip.document.write('<layer bgColor="#ffffff" style="font-size:12px;font-family:verdana;opacity:.70;">'+text+'</layer>')
document.tooltip.document.close()
document.tooltip.left=e.pageX+5
document.tooltip.top=e.pageY+5
document.tooltip.visibility="show"
}
}
function hidetip(){
if (document.layers)
document.tooltip.visibility="hidden"
}

function MM_openBrWindow(theURL,winName,features) { //v2.0
	w = window.open(theURL,winName,features);
	w.focus();
}