var map = null;
var mapdiv = null;
var currentLayer = 0;
var currentPin = 0;
var currentProps = 0;

var processingProperty = false;
var processingPage = false;
var processingPins = false;
var processingCriteria = false;

var mousedMarker = null;
var closePropDiv = null;

var curPage = 1;
var displayMode = "condensed";
var sortBy = "price";

var SWlat, SWlng, NElat, NElng;

function switchDisplayMode(ele) {
	displayMode = (displayMode == "condensed" ? "detailed" : "condensed");
	getResultsPage(curPage, displayMode);
	ele.innerHTML = (displayMode == "condensed" ? "Switch to detailed property view" : "Switch to condensed property view");
}

function loadInteractiveMap(lat, lng, zoom) {
	
	var cSWlat = getCookie('swlat');
	var cSWlng = getCookie('swlng');
	var cNElat = getCookie('nelat');
	var cNElng = getCookie('nelng');
	var cZoom = getCookie('zoom');
	
	if (cSWlat != "" && cNElat != "") { lat = (cSWlat/2 + cNElat/2); }
	if (cSWlng != "" && cNElng != "") { lng = (cSWlng/2 + cNElng/2); }
	if (cZoom != "") { zoom = cZoom; }
	
	map = new VEMap('myMap');
	map.LoadMap(new VELatLong(lat, lng), zoom ,'r' ,false);
	map.AttachEvent('onchangeview', changeView);
	map.AttachEvent('onmousedown', hidePropDiv);
	map.AttachEvent('onstartzoom', hidePropDiv);
	
	VEPushpin.ShowDetailOnMouseOver = false;
	VEPushpin.OnMouseOverCallback = function(x, y, title, details)
	{
		getListing(details, 1);
	}
	
	getProperties();
}

var gpto;
function changeView() {
	clearTimeout(gpto);
	document.getElementById('MapMessage').innerHTML = "Loading..";
	document.getElementById('additional-results').innerHTML = "";
	gpto = setTimeout(getProperties, 750);
}

function getProperties() {

	if (!processingPage && !processingProperty) {
		if (processingPins) {//Cancel current request
			httpRequester.abort();
		}
		
		hidePropDiv();
		
		var currentMapView = map.GetMapView();
		
		if (map.GetMapStyle() == VEMapStyle.Birdseye || map.GetMapStyle() == VEMapStyle.Oblique || map.GetMapStyle() == VEMapStyle.BirdseyeHybrid) {
			var be = map.GetBirdseyeScene();
			var northWest = (new _xy1).Decode(map.GetMapView().TopLeftLatLong);
			var southEast = (new _xy1).Decode(map.GetMapView().BottomRightLatLong);
			
			SWlat = southEast.Latitude;
			SWlng = northWest.Longitude;
			NElat = northWest.Latitude;
			NElng = southEast.Longitude;
			
		} else {
			var northWest = currentMapView.TopLeftLatLong;
			var southEast = currentMapView.BottomRightLatLong;
			
			SWlat = southEast.Latitude;
			SWlng = northWest.Longitude;
			NElat = northWest.Latitude;
			NElng = southEast.Longitude;
		}
		
		if (map.GetMapStyle() != VEMapStyle.Birdseye && map.GetMapStyle() != VEMapStyle.Oblique && map.GetMapStyle() != VEMapStyle.BirdseyeHybrid) {
			setCookie('swlat', SWlat, 1);
			setCookie('swlng', SWlng, 1);
			setCookie('nelat', NElat, 1);
			setCookie('nelng', NElng, 1);
			setCookie('zoom', map.GetZoomLevel(), 1);
		}
		
		document.getElementById('MapMessage').innerHTML = 'Loading...';
		
		httpRequester.open("getNoCache", "/search/interactive-results-pins.cfm?searchID=" + searchID + "&SWlat=" + SWlat + "&SWlng=" + SWlng + "&NElat=" + NElat + "&NElng=" + NElng, true);
		httpRequester.onreadystatechange = addPins;
		processingPins = true;
		httpRequester.send(null);
	}
	
	//if (map.GetMapStyle() == VEMapStyle.Birdseye) {
	//	map.DeleteAllPushpins();
	//}
}


function addPins() {
	if ( httpRequester.readyState == 4 ) {// Complete
	
		var docx = xmlLoad(httpRequester.responseText);
		var recordcount = 0, pincount = 0, additional = 0;

		//Get the data returned from request
		try {
			recordcount = docx.getElementsByTagName('recordcount')[0].firstChild.nodeValue;
			pincount = docx.getElementsByTagName('pincount')[0].firstChild.nodeValue;
			additional = docx.getElementsByTagName('additional')[0].firstChild.nodeValue;
		} catch(e) {
			
		}
		
		currentProps = recordcount;
		
		//Clear off existing pins
		map.DeleteAllPushpins();

		if (pincount > 0 && pincount <= 150) {
			// loop through resutls and add each pin
			props = docx.selectNodes('/response/results/property');
			for (var i=0; i<props.length; i++) {
				
				var prop = props[i];
				var pLat = prop.selectNodes("lat")[0].firstChild.nodeValue;
				var pLng = prop.selectNodes("lng")[0].firstChild.nodeValue;
				var pOH = prop.selectNodes("oh")[0].firstChild.nodeValue;
				
				var imgPath = (pOH == 1 ? "oh/oh-" : "reg/blue-house-");
				
				var pin = new VEPushpin(
					currentPin,
					new VELatLong(pLat, pLng),
					"/images/gmaps/icons/" + imgPath + (i+1) + ".gif",
					'0',
					pLat + ',' + pLng
				);

				pin.ll = pLat + ',' + pLng;
				map.AddPushpin(pin);
				currentPin++;
			}
			
			document.getElementById('MapMessage').innerHTML = 'Now showing ' + recordcount + ' properties';
			if (additional != 0) {
				document.getElementById('additional-results').innerHTML = 'To view up to <strong>' + additional + '</strong> properties that meet your criteria <a href="/my/register.cfm">register for My Jameson</a>';
			}
			
			if (curPage > 1) {			
				document.getElementById('prevControl').innerHTML = "<a href=\"#\" onclick=\"getResultsPage(curPage-1, displayMode);return false;\">&lt; See previous 10</a>";
			} else {
				document.getElementById('prevControl').innerHTML = "&lt; See previous 10";
			}
			
			if (curPage * 10 < currentProps) {
				document.getElementById('nextControl').innerHTML = "<a href=\"#\" onclick=\"getResultsPage(curPage+1, displayMode);return false;\">See next 10 &gt;</a>";
			} else {
				document.getElementById('nextControl').innerHTML = "See next 10 &gt;";
			}
			
			
			processingPins = false;
			getResultsPage(1, displayMode);
			
		} else if (pincount == 0) {
			
			
			document.getElementById('nextControl').innerHTML = "See next 10 &gt;";
			
			document.getElementById('MapMessage').innerHTML = 'Now showing ' + recordcount + ' properties';
			document.getElementById('search-results').innerHTML = "";
			document.getElementById('additional-results').innerHTML = 'To view up to ' + additional + ' properties that meet your criteria';
			processingPins = false;
			
		} else {
			document.getElementById('prevControl').innerHTML = "&lt; See previous 10";
			document.getElementById('nextControl').innerHTML = "See next 10 &gt;";
		
			document.getElementById('MapMessage').innerHTML = 'There are too many properties, please zoom in or narrow your search.';
			document.getElementById('search-results').innerHTML = "";
			document.getElementById('additional-results').innerHTML = "";
			processingPins = false;
		}
		
	}
}

// Function to draw page html to the screen
function drawPage() {
	if ( httpRequester.readyState == 4 ) {// Complete
		document.getElementById('search-results').innerHTML = httpRequester.responseText;
		
		if (curPage > 1) {			
			document.getElementById('prevControl').innerHTML = "<a href=\"#\" onclick=\"getResultsPage(curPage-1, displayMode);return false;\">&lt; See previous 10</a>";
		} else {
			document.getElementById('prevControl').innerHTML = "&lt; See previous 10";
		}
		
		if (curPage * 10 < currentProps) {
			document.getElementById('nextControl').innerHTML = "<a href=\"#\" onclick=\"getResultsPage(curPage+1, displayMode);return false;\">See next 10 &gt;</a>";
		} else {
			document.getElementById('nextControl').innerHTML = "See next 10 &gt;";
		}
		
		processingPage = false;
	}
}

function getListing(latlng, record) {
	if (!processingPins && !processingPage) {
		if (processingProperty) {
			httpRequester.abort();
		}
		
		clearTimeout(closePropDiv);
		
		var llArray = latlng.split(",");
		var pinXY = map.LatLongToPixel(new VELatLong(llArray[0], llArray[1]));
		
		var infoDiv = document.getElementById('vePropInfo');
		infoDiv.innerHTML = "";
		//infoDiv.style.display = 'none';
		
		infoDiv.style.left = pinXY.x + 'px';
		infoDiv.style.top = (pinXY.y-71) + 'px';
		
		//document.getElementById('vePropInfo').innerHTML = "";
		infoDiv.style.display = 'block'; //Show an empty bubble to start
		httpRequester.open("getNoCache", "/search/interactive-results-detail.cfm?searchID=" + searchID + "&latlng=" + latlng + "&record=" + record, true);
		httpRequester.onreadystatechange = drawListing;
		processingProperty = true;
		httpRequester.send(null);
	}
}

// Function to pull back data for the current page of properties
function getResultsPage(page, display) {
	
	if (!processingPins && !processingProperty) {
		if (processingPage) {//Cancel current request
			httpRequester.abort();
		}
		
		if (page == 0) { page = 1; }
		if (page > currentProps/10 + 1) { page = currentProps/10 + 1; }
		
		httpRequester.open("getNoCache", "/search/interactive-results-page.cfm?searchID=" + searchID + "&SWlat=" + SWlat + "&SWlng=" + SWlng + "&NElat=" + NElat + "&NElng=" + NElng + "&display=" + display + "&page=" + page, true);
		httpRequester.onreadystatechange = drawPage;
		processingPage = true;
		httpRequester.send(null);
		curPage = page;
	}
}

function drawListing() {
	if ( httpRequester.readyState == 4 ) {// Complete
		clearTimeout(closePropDiv);
		document.getElementById('vePropInfo').innerHTML = httpRequester.responseText;
		processingProperty = false;
	}
}

function propDivOut(){
	clearTimeout(closePropDiv);
	closePropDiv = setTimeout('hidePropDiv()', 1000);
}

function hidePropDiv() {
	document.getElementById('vePropInfo').style.display = 'none';
}

function updateCriteria(f, v) {
	
	httpRequester.abort();
	httpRequester.open("getNoCache", "/search/interactive-results-criteria.cfm?searchID=" + searchID + "&field=" + f + "&value=" + v, true);
	httpRequester.onreadystatechange = refreshMap;
	httpRequester.send(null);
	
}

function selectedPropTypes() {

	var retval = "";

	for (var j=0; j<document.frmCriteria.propType.length; j++) {
		if (document.frmCriteria.propType[j].checked) {
			if (retval != "") { retval += ","; }
			retval += document.frmCriteria.propType[j].value;
		}
	}
	return retval;
}

function refreshMap() {
	if ( httpRequester.readyState == 4 ) {
		getProperties();
	}
}


/* Functions below are for the map these results page - some access functions above */
function loadResultsMap(lat, lng, zoom) {
	map = new VEMap('myMap');
	map.LoadMap(new VELatLong(lat, lng), zoom ,'r' ,false);
	docx = xmlLoad(pinXML);

	map.AttachEvent('onmousedown', hidePropDiv);
	map.AttachEvent('onstartzoom', hidePropDiv);
	
	VEPushpin.ShowDetailOnMouseOver = false;
	VEPushpin.OnMouseOverCallback = function(x, y, title, details)
	{
		getResultsListing(details, title, 1);
	}
	
	// loop through resutls and add each pin
	props = docx.selectNodes('/response/results/property');
	for (var i=0; i<props.length; i++) {
		var prop = props[i];
		var pLat = prop.selectNodes("lat")[0].firstChild.nodeValue;
		var pLng = prop.selectNodes("lng")[0].firstChild.nodeValue;
		var pOH = prop.selectNodes("oh")[0].firstChild.nodeValue;

		var imgPath = (pOH == 1 ? "oh/oh-" : "reg/blue-house-");
		
		var pin = new VEPushpin(
			currentPin,
			new VELatLong(pLat, pLng),
			"/images/gmaps/icons/" + imgPath + (i+1) + ".gif",
			'' + (i+1),
			pLat + ',' + pLng
		);
		
		map.AddPushpin(pin);
		currentPin++;
	}
}

function getResultsListing(latlng, pin, prop) {

	clearTimeout(closePropDiv);
		
	var llArray = latlng.split(",");
	var pinXY = map.LatLongToPixel(new VELatLong(llArray[0], llArray[1]));
	
	var infoDiv = document.getElementById('vePropInfo');
	infoDiv.innerHTML = "";
	infoDiv.style.display = 'none';
	infoDiv.style.left = pinXY.x + 'px';
	infoDiv.style.top = (pinXY.y-71) + 'px';

	clearTimeout(closePropDiv);
	infoDiv.style.display = 'block';
	infoDiv.innerHTML = document.getElementById('bubble_pin' + pin + '_prop' + prop).innerHTML;
}
