var processingProperty = false;
var processingPage = false;
var processingPins = false;
var map = null;
var mapdiv = null;
var houseIcon = null;
var handlingMarker = false;
var curPage = 1;
var displayMode = "condensed";
var clickedMarker = null;
var pageHttp = getHTTPRequestObject();

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(cLat, cLng, zoom) {
	if (GBrowserIsCompatible()) {

		mapdiv = document.getElementById("myMap");
		map = new GMap2(document.getElementById("myMap"));
	
		map.addControl(new GLargeMapControl());
		map.addControl(new GMapTypeControl());
		
		
		GEvent.addListener(map, "moveend", function() {
			if (!handlingMarker) {
				getProperties(map);
			} else {
				handlingMarker = false;
			}
		});

		GEvent.addDomListener(mapdiv, "DOMMouseScroll", wheelZoom); // Firefox 
		GEvent.addDomListener(mapdiv, "mousewheel", wheelZoom); // IE 
		
		houseIcon = new GIcon();
		houseIcon.shadow = "/images/gmaps/icons/reg/blue-house-1.gif";
		houseIcon.iconSize = new GSize(25, 21);
		houseIcon.shadowSize = new GSize(25, 21);
		houseIcon.iconAnchor = new GPoint(13, 11);
		houseIcon.infoWindowAnchor = new GPoint(9, 2);
		houseIcon.infoShadowAnchor = new GPoint(18, 25);

		map.setCenter(new GLatLng(cLat, cLng), zoom);
	}
}

function wheelZoom(event) { 
// Prevent from scrolling the page when zooming the map 
	if(window.event) { event.returnValue = false; } // IE 
	if(event.cancelable) { event.preventDefault(); } // DOM-Standard 
	if((event.detail || -event.wheelDelta) < 0) {
		map.zoomIn();
	} else {
		map.zoomOut();
	}
}


function createMarker(point, index, imgPath, latlng) {
	// Create a lettered icon for this point using our icon class 
	var icon = new GIcon(houseIcon);
	icon.image = "/images/gmaps/icons/" + imgPath  + (index+1) + ".gif";
	var marker = new GMarker(point, icon);
	GEvent.addListener(marker, "mouseover", function() {
		handlingMarker = true;
		showProp(marker, latlng, 1);
	});
	
	return marker;
}

function getProperties() {
	
	if (processingPins) {//Cancel current request
		httpRequester.abort();
	}
	
	var bounds = map.getBounds();
	var southWest = bounds.getSouthWest();
	var northEast = bounds.getNorthEast();
	
	SWlat = southWest.lat();
	SWlng = southWest.lng();
	NElat = northEast.lat();
	NElng = northEast.lng();

	document.getElementById('MapMessage').innerHTML = 'Loading...';
	
	httpRequester.open("Post", "/search/interactive-results-pins.cfm?searchID=" + searchID + "&SWlat=" + SWlat + "&SWlng=" + SWlng + "&NElat=" + NElat + "&NElng=" + NElng, true);
	httpRequester.onreadystatechange = addPins;
	processingPins = true;
	httpRequester.send(null);
}

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;
		map.clearOverlays();
		
		if (pincount > 0 && pincount <= 150) {
			// loop through resutls and add each pin
			props = docx.getElementsByTagName('property');
			
			for (var i=0; i<props.length; i++) {
					
				var prop = props[i];
				var pLat = prop.getElementsByTagName("lat")[0].firstChild.nodeValue;
				var pLng = prop.getElementsByTagName("lng")[0].firstChild.nodeValue;
				var pOH = prop.getElementsByTagName("oh")[0].firstChild.nodeValue;
				var point = new GLatLng(pLat, pLng);
				
				var imgPath = (pOH == 1 ? "oh/oh-" : "reg/blue-house-");
				
				map.addOverlay(createMarker(point, i, imgPath, pLat + ',' + pLng));
			}
			
			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 showProp(marker, latlng, record) {
	activeMarker = marker;
	markerLL = marker.getPoint();
	httpRequester.open("Post", "/search/interactive-results-detail.cfm?searchID=" + searchID + "&latlng=" + latlng + "&record=" + record, true);
	httpRequester.onreadystatechange = drawProperty;
	httpRequester.send(null);
}

function drawProperty() {
	if ( httpRequester.readyState == 4 ) {// Complete
		activeMarker.openInfoWindowHtml(httpRequester.responseText);
		activeMarker = null;
	}
}

function showNthProp(latlng, record) {
	httpRequester.open("Post", "/search/interactive-results-detail.cfm?searchID=" + searchID + "&latlng=" + latlng + "&record=" + record, true);
	httpRequester.onreadystatechange = drawNthProperty;
	httpRequester.send(null);
}

function drawNthProperty() {
	if ( httpRequester.readyState == 4 ) {// Complete
		document.getElementById('active-popup').innerHTML = httpRequester.responseText;
	}
}


// Function to draw page html to the screen
function drawPage() {
	if ( pageHttp.readyState == 4 ) {// Complete
		document.getElementById('search-results').innerHTML = pageHttp.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 getResultsPage(page, display) {
	if (!processingPins && !processingProperty) {
		if (processingPage) {//Cancel current request
			pageHttp.abort();
		}
		
		if (page == 0) { page = 1; }
		if (page > currentProps/10 + 1) { page = currentProps/10 + 1; }
		
		pageHttp.open("Post", "/search/interactive-results-page.cfm?searchID=" + searchID + "&SWlat=" + SWlat + "&SWlng=" + SWlng + "&NElat=" + NElat + "&NElng=" + NElng + "&display=" + display + "&page=" + page, true);
		pageHttp.onreadystatechange = drawPage;
		pageHttp.send(null);
		processingPage = true;
		
		curPage = page;
	}
}


function updateCriteria(f, v) {
	
	httpRequester.abort();
	httpRequester.open("Post", "/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(cLat, cLng, zoom) {
	if (GBrowserIsCompatible()) {

		mapdiv = document.getElementById("myMap");
		map = new GMap2(document.getElementById("myMap"));
		docx = xmlLoad(pinXML);
	
		map.addControl(new GLargeMapControl());
		map.addControl(new GMapTypeControl());

		GEvent.addDomListener(mapdiv, "DOMMouseScroll", wheelZoom); // Firefox 
		GEvent.addDomListener(mapdiv, "mousewheel", wheelZoom); // IE 
		
		houseIcon = new GIcon();
		houseIcon.shadow = "/images/gmaps/icons/reg/blue-house-1.gif";
		houseIcon.iconSize = new GSize(25, 21);
		houseIcon.shadowSize = new GSize(25, 21);
		houseIcon.iconAnchor = new GPoint(13, 11);
		houseIcon.infoWindowAnchor = new GPoint(9, 2);
		houseIcon.infoShadowAnchor = new GPoint(18, 25);

		map.setCenter(new GLatLng(cLat, cLng), zoom);
		
		// loop through resutls and add each pin
		props = docx.getElementsByTagName('property');
		for (var i=0; i<props.length; i++) {
			var prop = props[i];
			var pLat = prop.getElementsByTagName("lat")[0].firstChild.nodeValue;
			var pLng = prop.getElementsByTagName("lng")[0].firstChild.nodeValue;
			var pOH = prop.getElementsByTagName("oh")[0].firstChild.nodeValue;
	
			var imgPath = (pOH == 1 ? "oh/oh-" : "reg/blue-house-");
			
			// Create a lettered icon for this point using our icon class 
			var icon = new GIcon(houseIcon);
			icon.image = "/images/gmaps/icons/" + imgPath  + (i+1) + ".gif";
			var marker = new GMarker(new GLatLng(pLat, pLng), icon);
			marker.relatedElement = 'bubble_pin' + (i+1) + '_prop1';
			GEvent.addListener(marker, "mouseover", function() {
				this.openInfoWindowHtml(document.getElementById(this.relatedElement).innerHTML);
			});
			
			map.addOverlay(marker);
		}
	}
}
