var ajaxEnabled = true;

var MAP_BOUNDS_COOKIE = 'MAP_BOUNDS_COOKIE';

var markers = {}
var activityIndicator = null;

function logEmail(type, propertyId) {
	new Ajax.Request('/contact/' + type + '/log/' + propertyId + '/');
    return true;
}

function getResult(result_id, search_id, pagenum, position, perpage){
	if ($(result_id).nextSibling && $(result_id).nextSibling.className == 'result_expanded'){
		return true;
	}
	var url = '/search/expander/' + result_id + '/' + search_id + '/' + pagenum + '/' + position + '/' + perpage + '/';
	var myAjax = new Ajax.Request(
		url,
		{
			method: 'get',
			parameters: '',
			onComplete: function(myAjax) {resultResponse(myAjax, result_id, search_id, pagenum, position, perpage)}
		});
	return false;
}

function resultResponse(request, result_id, search_id, pagenum, position, perpage){
	var newDiv = document.createElement('li');
	newDiv.className = 'result_expanded';
	newDiv.innerHTML = request.responseText;
	newDiv.style.display = 'none';
	$(result_id).parentNode.insertBefore(newDiv, $(result_id).nextSibling);

	var scripts = $(result_id +"_script");

	new Effect.Appear(newDiv);
	new Effect.SlideDown(newDiv, {
		afterFinish: function() {
			if(scripts){
				try{
					eval(scripts.innerHTML);
				}catch(e){
				}
			}
		}
	});

    var as = $(result_id).getElementsByTagName('a');
    //as[as.length - 1].style.display = 'none';
    as[as.length - 1].innerHTML = 'Hide details';
    as[as.length - 1].onclick = function() {
	    as[as.length - 1].innerHTML = 'Show details';
	    as[as.length - 1].onclick = new Function('getResult("'+result_id+'", '+search_id+', '+pagenum+', '+position+', '+perpage+');return false;');
    	new Effect.Fade(this);
		new Effect.SlideUp(this, {
			afterFinish: function() {
				this.parentNode.removeChild(this)
			}.bind(this)
		});
    	return false;
    }.bind(newDiv);

	//loadMap(result_id, false);
}

function hideResult(url, property_element, confirm_message){
	var hidden_results = $('hidden_results');
	var the_span = hidden_results.getElementsByTagName('span')[0];
	var count = hidden_results.getElementsByTagName('strong')[0];

	if (parseInt(count.innerHTML) > 0 || confirm(confirm_message)) {
		$(property_element).style.display = 'block';
		if (property_element.nextSibling.className == 'result_expanded') {
    		new Effect.SlideUp(property_element.nextSibling);
    	}
		new Effect.SlideUp(property_element, {queue:'front'});
		var myAjax = new Ajax.Request(
			url,
			{
				method: 'get',
				parameters: '',
				onComplete: function(myAjax) {
					count.innerHTML = parseInt(count.innerHTML) + 1;
					if (parseInt(count.innerHTML) == 1) {
						new Effect.SlideDown(hidden_results, {queue:'front'});
					} else {
						new Effect.Highlight(hidden_results, {queue:'end'});
					}
				}
			});
	}
	return false;
}

function loadMap(result_id, latitude, longitude, property_type, onload){

	var icon = new GIcon();
	icon.image = MEDIA_URL + "img/furniture/gmap_marker_blue.png";
	icon.iconSize = new GSize(16, 15);
	icon.iconAnchor = new GPoint(8, 8);
	icon.infoWindowAnchor = new GPoint(8, 8);

	var name = result_id + "_map";
	element = $(name);

	var name = result_id + "_map";
	element = $(name);

	if (GBrowserIsCompatible()) {
		if(onload){
			window.onload = function() {
				var map = new GMap2(element);
				map.setCenter(new GLatLng(latitude, longitude), 13);
				var marker = new GMarker(map.getCenter(), icon);
				map.addControl(new GMapTypeControl());
				var OMap = new GOverviewMapControl();
				map.addControl(OMap);
				OMap.hide(true);
				map.addControl(new GSmallMapControl());
				map.addControl(new GScaleControl());
				map.addOverlay(marker);
			}
		}else{
			var map = new GMap2(element);
			map.setCenter(new GLatLng(latitude, longitude), 13);
			var marker = new GMarker(map.getCenter(), icon)
			map.addControl(new GMapTypeControl());
			var OMap = new GOverviewMapControl();
			map.addControl(OMap);
			OMap.hide(true);
			map.addControl(new GSmallMapControl());
			map.addControl(new GScaleControl());
			map.addOverlay(marker);
		}
	}
}


function createMarker(point, id, bedrooms, title, rent, image_path, property_url, address_2, address_3, address_4, icon) {

  var marker = new GMarker(point, icon);
  marker.propertyId = id;
  GEvent.addListener(marker, "click", function() {
	var infoTabs = [
	  new GInfoWindowTab('Image', '<div class="area_iwin_tab" id="area_iwin_tab_1"><h2>' + title + '</h2><img src="' + image_path + '" /><div class="show_details"><a href="' + property_url + '" class="show_details">More details</a></div></div>'),
	  new GInfoWindowTab('Details', '<div class="area_iwin_tab" id="area_iwin_tab_2"><h2>' + title + '</h2><ul><li>' + address_2 + '</li><li>' + address_3 + '</li><li>' + address_4 + '</li></ul><dl><dt id="bedrooms">Bedrooms</dt><dd>' + bedrooms + ' bedrooms</dd><dt id="rent">Rent</dt><dd>' + rent + ' p/m</dd></dl><div class="show_details"><a href="' + property_url + '" class="show_details">More details</a></div></div>')
	];
	marker.openInfoWindowTabsHtml(infoTabs);
  });
  return marker;
}


function areaResultsMap(result_id, latitude, longitude, onload){
	var name = result_id;
	element = $(name);
	if (GBrowserIsCompatible()) {
		if(onload){
			window.onload = function() {

				var latSum = 0;
				var lonSum = 0;
				for (var i=0; i<propertiesArray.length; i++){
					latSum += propertiesArray[0][2];
					lonSum += propertiesArray[0][1];
				}
				var latCentre = latSum / propertiesArray.length;
				var lonCentre = lonSum / propertiesArray.length;

				map = new GMap2(element);
				map.addControl(new GMapTypeControl());
				map.addControl(new GSmallMapControl());
				map.addControl(new GOverviewMapControl());
				map.addControl(new GScaleControl());
				map.addControl(new GScaleControl());
				map.setCenter(new GLatLng(latCentre, lonCentre), 14);

				GEvent.addListener(map, "moveend", function() {
					bounds = map.getBounds();
					fetchNewProperties(bounds);
				});

				GEvent.addListener(map, 'zoomend', function(oldZoomLevel, newZoomLevel) {
				   if(newZoomLevel < 14){
					   map.setZoom(14);
					   alert('You cannot zoom out any further on this map.');
					   //map.centerAndZoom(new GPoint(xPoint,yPoint), newZoomLevel-1);
				   }
				})

				icon_blue = new GIcon();
				icon_blue.image = MEDIA_URL + "img/furniture/gmap_marker_blue.png";
				icon_blue.shadow = MEDIA_URL + "img/furniture/gmap_marker_shadow.png";
				icon_blue.iconSize = new GSize(31, 31);
				icon_blue.shadowSize = new GSize(31, 31);
				icon_blue.iconAnchor = new GPoint(16, 16);
				icon_blue.infoWindowAnchor = new GPoint(16, 15);

				icon_red = new GIcon();
				icon_red.image = MEDIA_URL + "img/furniture/gmap_marker_red.png";
				icon_red.shadow = MEDIA_URL + "img/furniture/gmap_marker_shadow.png";
				icon_red.iconSize = new GSize(31, 31);
				icon_red.shadowSize = new GSize(31, 31);
				icon_red.iconAnchor = new GPoint(16, 16);
				icon_red.infoWindowAnchor = new GPoint(16, 15);

				for (var i=0; i<propertiesArray.length; i++){
					if(propertiesArray[i][11] == 'House'){
						icon = icon_red;
					}
					else{
						icon = icon_blue;
					}
					point = new GLatLng(propertiesArray[i][2], propertiesArray[i][1]);
					marker = createMarker(point, propertiesArray[i][0], propertiesArray[i][3], propertiesArray[i][4], propertiesArray[i][5], propertiesArray[i][6], propertiesArray[i][7], propertiesArray[i][8], propertiesArray[i][9], propertiesArray[i][10], icon)
					markers[propertiesArray[i][0]] = 'fixed';
					map.addOverlay(marker);
				}

				bounds = map.getBounds();
				fetchNewProperties(bounds);
			}
		}else{
			map = new GMap2(element);
			map.setCenter(new GLatLng(latitude, longitude), 13);
		}
	}
}

function fetchNewProperties(bounds){
	min = bounds.getSouthWest()
	max = bounds.getNorthEast()
	min_lat = min.lat();
	max_lat = max.lat();
	min_long = min.lng();
	max_long = max.lng();

	if (activityIndicator == null) {
		activityIndicator = document.createElement('div');
		activityIndicator.innerHTML = '<img src="' + MEDIA_URL + 'img/furniture/ajaxactivity.gif" align="absmiddle" /> Locating nearby properties...';
		activityIndicator.style.background = 'red';
		activityIndicator.style.color = '#fff';
		activityIndicator.style.fontWeight = 'bold';
		activityIndicator.style.padding = '0.25em .5em';
		activityIndicator.style.position = 'absolute';
		activityIndicator.style.right = '8px';
		activityIndicator.style.top = '3em';
		activityIndicator.style.zIndex = '1000000';
		map.getContainer().appendChild(activityIndicator);
	} else {
		activityIndicator.style.display = 'block';
	}

	GDownloadUrl('/search/property_search_lat_long/?min_lat='+min_lat+'&max_lat='+max_lat+'&min_long='+min_long+'&max_long='+max_long, function(data, responseCode){
		addProperties(data);
	});
}

function addProperties(data){

	return;

	var propertiesArray;
	try {
		propertiesArray = eval(data);
	} catch (e) {
		activityIndicator.style.display = 'none';
		return;
	}

	activityIndicator.style.display = 'block';

	var icon_blue = new GIcon();
	icon_blue.image = MEDIA_URL + "img/furniture/gmap_marker_blue_faded.png";
	icon_blue.shadow = MEDIA_URL + "img/furniture/gmap_marker_shadow.png";
	icon_blue.iconSize = new GSize(31, 31);
	icon_blue.shadowSize = new GSize(31, 31);
	icon_blue.iconAnchor = new GPoint(16, 16);
	icon_blue.infoWindowAnchor = new GPoint(16, 15);

	var icon_red = new GIcon();
	icon_red.image = MEDIA_URL + "img/furniture/gmap_marker_red_faded.png";
	icon_red.shadow = MEDIA_URL + "img/furniture/gmap_marker_shadow.png";
	icon_red.iconSize = new GSize(31, 31);
	icon_red.shadowSize = new GSize(31, 31);
	icon_red.iconAnchor = new GPoint(16, 16);
	icon_red.infoWindowAnchor = new GPoint(16, 15);

	var toAdd = [];
	var toRemove = [];
	var propertiesMap = {}

	for(var i=0;i<propertiesArray.length;i++){
		if (typeof(markers[propertiesArray[i][0]]) == 'undefined' || markers[propertiesArray[i][0]] == null) {
			var icon = (propertiesArray[i][11] == 'House' ? icon_red : icon_blue);
			var point = new GLatLng(propertiesArray[i][2], propertiesArray[i][1]);
			var marker = createMarker(point, propertiesArray[i][0], propertiesArray[i][3], propertiesArray[i][4], propertiesArray[i][5], propertiesArray[i][6], propertiesArray[i][7], propertiesArray[i][8], propertiesArray[i][9], propertiesArray[i][10], icon);
			toAdd.push(marker);
		}
		propertiesMap[propertiesArray[i][0]] = propertiesArray[i];
	}
	for (propertyId in markers) {
		if (markers[propertyId] != null && markers[propertyId] != 'fixed' && typeof(propertiesMap[propertyId]) == 'undefined') {
			toRemove.push(markers[propertyId]);
		}
	}

	for (var i = 0; i < toRemove.length; i++) {
		//map.removeOverlay(toRemove[i]);
		//markers[toRemove[i].propertyId] = null;
	}
	for (var i = 0; i < toAdd.length; i++) {
		map.addOverlay(toAdd[i]);
		markers[toAdd[i].propertyId] = toAdd[i];
	}

	activityIndicator.style.display = 'none';

}
//processMarkerQueue();
function processMarkerQueue() {
	if (toRemove.length > 0) {
		var marker = toRemove.shift();
		map.removeOverlay(marker);
		markers[marker.propertyId] = null;
	}
	if (toAdd.length > 0) {
		var marker = toAdd.shift();
		map.addOverlay(toAdd);
		markers[marker.propertyId] = marker;
	}
	setTimeout(processMarkerQueue, 10);
}


LettingWebMapTooltip = function(point, content) {
	this.point = point
	this.content = content;
}
if (typeof GOverlay != 'undefined') {
	LettingWebMapTooltip.prototype = new GOverlay();
	LettingWebMapTooltip.prototype.initialize = function(map) {
		this.map = map;
		this.div = document.createElement('div');
		this.div.style.background = 'url(' + MEDIA_URL + 'img/furniture/map_tooltip_right.png) no-repeat top right';
		this.div.style.fontSize = '11px';
		this.div.style.paddingRight = '10px';
		this.div.style.position = 'absolute';
		this.div.style.whiteSpace = 'nowrap';
		this.div.style.zIndex = 1000;

		var div = document.createElement('div');
		div.innerHTML = this.content;
		div.style.padding = '10px 0 10px 10px';
		div.style.height = '70px';
		div.style.background = 'url(' + MEDIA_URL + 'img/furniture/map_tooltip_left.png) no-repeat top left';
		this.div.appendChild(div);

		this.map.getPane(G_MAP_FLOAT_SHADOW_PANE).appendChild(this.div);
	}
	LettingWebMapTooltip.prototype.redraw = function(force) {
		var point = this.map.fromLatLngToDivPixel(this.point);
		var right = this.map.fromDivPixelToLatLng(new GPoint(point.x + this.div.offsetWidth + 30, point.y));
		if (this.map.getBounds().contains(right)) {
			this.div.style.left = (point.x + 30) + "px";
		} else {
			this.div.style.left = (point.x - 30 - this.div.offsetWidth) + "px";
		}
		this.div.style.top = (point.y - (this.div.offsetHeight / 2)) + "px";
	}
	LettingWebMapTooltip.prototype.remove = function() {
		this.map.getPane(G_MAP_FLOAT_SHADOW_PANE).removeChild(this.div);
	}
}

var LettingWebMap = function(element, minLat, maxLat, minLng, maxLng, searchId) {

	this.updating = false;
	this.searchId = searchId;

	this.element = $(element);
	this.gmap = new GMap2(this.element);

	var previousBounds = readCookie(MAP_BOUNDS_COOKIE);
	if (previousBounds != null) {
		previousBounds = previousBounds.split(',');
		minLat = parseFloat(previousBounds[0]);
		minLng = parseFloat(previousBounds[1]);
		maxLat = parseFloat(previousBounds[2]);
		maxLng = parseFloat(previousBounds[3]);
	}
	var bounds = new GLatLngBounds(new GLatLng(minLat, minLng), new GLatLng(maxLat, maxLng));;
	var zoom = this.gmap.getBoundsZoomLevel(bounds);

	this.gmap.addControl(new GMapTypeControl());
	this.gmap.addControl(new GSmallMapControl());
	this.gmap.addControl(new GOverviewMapControl());
	this.gmap.addControl(new GScaleControl());
	this.gmap.setCenter(new GLatLng((minLat + maxLat) / 2, (minLng + maxLng) / 2), zoom);
	this.gmap.enableContinuousZoom();
	this.gmap.enableDoubleClickZoom();

	//this.gmap.addOverlay(new GPolyline([new GLatLng(minLat, minLng), new GLatLng(minLat, maxLng), new GLatLng(maxLat, maxLng), new GLatLng(maxLat, minLng), new GLatLng(minLat, minLng)]));

	this.tooltip = null;
	this.activityIndicator = null;
	this.markers = [];

	this.filterHandler = function(event) {
		this.update();
	}.bind(this);

	this.selectLocationHandler = function(event) {
		this.update(true);
	}.bind(this);

	this.addFormEventHandlers = function() {
        this.clearFormEventHandlers();
    	var searchForm = $('search-form');
    	var searchFormSelects = searchForm.getElementsByTagName('select');
    	var searchFormInputs = searchForm.getElementsByTagName('input');

    	for (var i = 0; i < searchFormSelects.length; i++) {
    	    if (searchFormSelects[i].name.substring(0, 9) == 'location_') {
        		Event.observe(searchFormSelects[i], 'change', this.selectLocationHandler);
        	} else {
        		Event.observe(searchFormSelects[i], 'change', this.filterHandler);
        	}
    	}
    	for (var i = 0; i < searchFormInputs.length; i++) {
    		if (searchFormInputs[i].type == 'checkbox') {
    			Event.observe(searchFormInputs[i], 'click', this.filterHandler);
    		}
    	}
	}.bind(this);

	this.clearFormEventHandlers = function() {
    	var searchForm = $('search-form');
    	var searchFormSelects = searchForm.getElementsByTagName('select');
    	var searchFormInputs = searchForm.getElementsByTagName('input');

    	for (var i = 0; i < searchFormSelects.length; i++) {
    	    if (searchFormSelects[i].name.substring(0, 9) == 'location_') {
    	        Event.stopObserving(searchFormSelects[i], 'change', this.selectLocationHandler);
        	} else {
        	    Event.stopObserving(searchFormSelects[i], 'change', this.filterHandler);
        	}
    	}
    	for (var i = 0; i < searchFormInputs.length; i++) {
    		if (searchFormInputs[i].type == 'checkbox') {
    		    Event.stopObserving(searchFormInputs[i], 'click', this.filterHandler);
    		}
    	}
	}.bind(this);

    this.addFormEventHandlers();

	this.showActivityIndicator = function() {
	    var message = arguments[0] || '<img src="' + MEDIA_URL + 'img/furniture/ajaxactivity.gif" align="absmiddle" /> Locating properties...';
		if (this.activityIndicator == null) {
			this.activityIndicator = document.createElement('div');
			this.activityIndicator.innerHTML = message;
			this.activityIndicator.style.background = 'red';
			this.activityIndicator.style.color = '#fff';
			this.activityIndicator.style.fontWeight = 'bold';
			this.activityIndicator.style.padding = '0.25em .5em';
			this.activityIndicator.style.position = 'absolute';
			this.activityIndicator.style.right = '8px';
			this.activityIndicator.style.top = '3em';
			this.activityIndicator.style.zIndex = '1000000';
			this.gmap.getContainer().appendChild(this.activityIndicator);
		} else {
		    this.activityIndicator.innerHTML = message;
			this.activityIndicator.style.display = 'block';
		}
	}

	this.hideActivityIndicator = function() {
		if (this.activityIndicator != null) {
			this.activityIndicator.style.display = 'none';
		}
	}

	this.removeMarkers = function() {
		while (this.markers.length > 0) {
			var marker = this.markers.pop();
			if (marker != null) {
				this.gmap.removeOverlay(marker);
			}
		}
	}

	this.removeMarker = function(marker) {
		for (var i = 0; i < this.markers.length; i++) {
			if (this.markers[i] == marker) {
				this.markers[i] = null;
				this.gmap.removeOverlay(marker);
			}
		}
	}

	this.update = function() {

	    this.updating = true;

		this.updateCookies();

	    var reposition = arguments[0] || false;

	    //if (!confirm('update:' + reposition)) return;

		this.showActivityIndicator();

		this.updateForm();

		var ajax = (reposition ? 2 : 1)

		var elements = Form.getElements('search-form');
        var queryComponents = new Array();
        var advancedSearchDiv = $('advancedSearch');
        for (var i = 0; i < elements.length; i++) {
            if (!reposition && elements[i].name.substring(0, 9) == 'location_') continue;
            if (!Element.childOf(elements[i], advancedSearchDiv) || advancedSearchDiv.style.display != 'none') {
                var queryComponent = Form.Element.serialize(elements[i]);
                if (queryComponent) queryComponents.push(queryComponent);
            }
        }
        var parameters = queryComponents.join('&');

		new Ajax.Request('/search/results/', {
			parameters: parameters.replace('Please%20wait...','') + '&ajax=' + ajax,
			method: 'get',
			onComplete: function(transport) {
				this.plot(transport.responseXML);
				this.updating = false;
				//this.addFormEventHandlers();
			}.bind(this)
		});
	}

	this.updateCookies = function() {
		var bounds = this.gmap.getBounds();
		min = bounds.getSouthWest()
		max = bounds.getNorthEast()
		min_lat = min.lat();
		max_lat = max.lat();
		min_long = min.lng();
		max_long = max.lng();
		bounds = min.lat() + ',' + min.lng() + ',' + max.lat() + ',' + max.lng();
		writeCookie(MAP_BOUNDS_COOKIE, bounds);
	}

	this.clearCookies = function() {
		deleteCookie(MAP_BOUNDS_COOKIE);
	}

	this.updateForm = function() {

		var bounds = this.gmap.getBounds();
		min = bounds.getSouthWest()
		max = bounds.getNorthEast()
		min_lat = min.lat();
		max_lat = max.lat();
		min_long = min.lng();
		max_long = max.lng();
		zoom_level = this.gmap.getZoom();

		var form = $('search-form');
		form.elements['min_latitude'].value = min_lat;
		form.elements['max_latitude'].value = max_lat;
		form.elements['min_longitude'].value = min_long;
		form.elements['max_longitude'].value = max_long;
		form.elements['zoom_level'].value = zoom_level;
	}

	this.clearForm = function() {
		var form = $('search-form');
		form.elements['min_latitude'].value = '';
		form.elements['max_latitude'].value = '';
		form.elements['min_longitude'].value = '';
		form.elements['max_longitude'].value = '';
		form.elements['zoom_level'].value = '';
	}

	this.plot = function(xml) {

        var boundsElements = xml.getElementsByTagName('bounds');
        if (boundsElements.length > 0) {
            bounds = boundsElements[0];
			var bounds = new GLatLngBounds(new GLatLng(bounds.getAttribute('min_latitude'), bounds.getAttribute('min_longitude')), new GLatLng(bounds.getAttribute('max_latitude'), bounds.getAttribute('max_longitude')));
			var zoom = this.gmap.getBoundsZoomLevel(bounds);
			//if (confirm(bounds + "\n\n" + zoom)) return;
			this.gmap.setCenter(bounds.getCenter(), zoom);
            return;
        }

		var icon_single = new GIcon();
		icon_single.image = MEDIA_URL + "img/furniture/gmap_marker_blue.png";
		icon_single.iconSize = new GSize(16, 15);
		icon_single.iconAnchor = new GPoint(8, 8);
		icon_single.infoWindowAnchor = new GPoint(8, 8);

		var icon_mini_multiple = new GIcon();
		icon_mini_multiple.image = MEDIA_URL + "img/furniture/gmap_marker_blue_mini_multi.png";
		icon_mini_multiple.iconSize = new GSize(16, 15);
		icon_mini_multiple.iconAnchor = new GPoint(8, 8);
		icon_mini_multiple.infoWindowAnchor = new GPoint(8, 8);

		var icon_multiple = new GIcon();
		icon_multiple.image = MEDIA_URL + "img/furniture/gmap_marker_blue_multiple.png";
		icon_multiple.iconSize = new GSize(31, 31);
		icon_multiple.iconAnchor = new GPoint(11, 11);
		icon_multiple.infoWindowAnchor = new GPoint(11, 11);

		this.removeMarkers();

        var count = 0;

		var properties = xml.getElementsByTagName('property');

		var properties_by_postcode = {};
		for (var i = 0; i < properties.length; i++) {
		    var postcode = properties[i].getAttribute('postcode');
		    if (typeof(properties_by_postcode[postcode]) == 'undefined') {
		        properties_by_postcode[postcode] = [];
		    }
		    properties_by_postcode[postcode].push(properties[i]);
		}

		for (var i = 0; i < properties.length; i++) {
			var property = properties[i];
			var markerProperties = properties_by_postcode[property.getAttribute('postcode')];
			var marker = new GMarker(new GLatLng(property.getAttribute('latitude'), property.getAttribute('longitude')), markerProperties.length == 1 ? icon_single : icon_mini_multiple);
			marker.lettingWebMap = this;
			marker.tooltipText = '<strong>' + property.getAttribute('title') + '<br />&pound;' + parseInt(property.getAttribute('rent')) + ' per month</strong><br /><strong style="color:#797A7F">Click to view&hellip;</strong>';
			marker.properties = markerProperties;

			GEvent.addListener(marker, 'mouseover', function() {
				this.tooltip = new LettingWebMapTooltip(this.getPoint(), this.tooltipText);
				this.lettingWebMap.gmap.addOverlay(this.tooltip);
			}.bind(marker));

			GEvent.addListener(marker, 'mouseout', function() {
				this.lettingWebMap.gmap.removeOverlay(this.tooltip);
			}.bind(marker));

			GEvent.addListener(marker, 'click', function() {
				var infoTabs = [];
				for (var j = 0; j < this.properties.length; j++) {
				    if (j < 2) {
				    	var rent = this.properties[j].getAttribute('rent');
				    	try {
					    	if (parseInt(rent) == parseFloat(rent)) {
					    		rent = parseInt(rent);
					    	}
					    } catch (e) {
					    	// Exception will occur if rent is not parsable.
					    	// This can just be ignored.
					    }
				    	var html = '<div class="area_iwin_tab" style="float:left" id="area_iwin_tab_1">'
				    	         + '<img src="' + this.properties[j].getAttribute('image_path') + '" />'
				    	         + '<h2>' + this.properties[j].getAttribute('title') + '</h2>'
				    	         + '<div class="info">'
				    	         + '&#163;' + rent + ' p/m - '
				    	         + this.properties[j].getAttribute('total_bedrooms') + ' bed ' + this.properties[j].getAttribute('type').toLowerCase()
				    	         + '</div>'
				    	         + '<div class="agent">'
				    	         + 'Agent: <strong>' + this.properties[j].getAttribute('agent') + '</strong><br />'
				    	         + 'Phone: <strong>' + this.properties[j].getAttribute('phone') + '</strong> or '
				    	         + '<a href="mailto:' + this.properties[j].getAttribute('email') + '" onclick="return logEmail(\'enquiry\', ' + this.properties[j].getAttribute('id') + ')"><strong>Email</strong></a>'
				    	         + '</div>'
				    	         + '<div class="show_details">'
				    	         + '<a href="' + this.properties[j].getAttribute('url') + '?map_display=1&search_id=' + this.lettingWebMap.searchId + '" class="more_details">More details</a>'
				    	         + '</div>'
				    	         + '<br style="clear: both" />'
				    	         + '</div>';
				        infoTabs.push(new GInfoWindowTab('Property ' + (j + 1), html));
				    } else {
				        infoTabs.push(new GInfoWindowTab('More...', 'There are ' + this.properties.length + ' properties at this postcode. <a href="/search/results?location_text=' + escape(this.properties[j].getAttribute('postcode')) + '">View all &raquo;</a>'));
				        break;
				    }
				}
				this.openInfoWindowTabsHtml(infoTabs);
			}.bind(marker));

			count++;
			this.gmap.addOverlay(marker);
			this.markers.push(marker);
		}

		var clusters = xml.getElementsByTagName('cluster');
		for (var i = 0; i < clusters.length; i++) {
			var cluster = clusters[i]
			var marker = new GMarker(new GLatLng(cluster.getAttribute('latitude'), cluster.getAttribute('longitude')), icon_multiple);
			marker.lettingWebMap = this;
			count += parseInt(cluster.getAttribute('count'));
			if (cluster.getAttribute('count') == 1) {
				marker.tooltipText = '<strong>1 property in this area';
				if (cluster.getAttribute('name')) {
					marker.tooltipText += ' of ' + cluster.getAttribute('name');
				}
				marker.tooltipText += '</strong><br /><strong style="color:#797A7F">Click to zoom&hellip;</strong>';
			} else {
				marker.tooltipText = '<strong>' + cluster.getAttribute('count') + ' properties in this area';
				if (cluster.getAttribute('name')) {
					marker.tooltipText += ' of <br />' + cluster.getAttribute('name');
				}
				marker.tooltipText += '</strong><br /><strong style="color:#797A7F">Click to zoom&hellip;</strong>';
			}
			marker.min_lat = cluster.getAttribute('min_latitude')
			marker.max_lat = cluster.getAttribute('max_latitude')
			marker.min_long = cluster.getAttribute('min_longitude')
			marker.max_long = cluster.getAttribute('max_longitude')

			GEvent.addListener(marker, 'mouseover', function() {
				this.tooltip = new LettingWebMapTooltip(this.getPoint(), this.tooltipText);
				this.lettingWebMap.gmap.addOverlay(this.tooltip);
				this.lettingWebMap.markers.push(this.tooltip);

				var points = [
					new GLatLng(this.min_lat, this.min_long),
					new GLatLng(this.min_lat, this.max_long),
					new GLatLng(this.max_lat, this.max_long),
					new GLatLng(this.max_lat, this.min_long),
					new GLatLng(this.min_lat, this.min_long)
				];

				this.polyline = new GPolyline(points, '#0000ff', 10);
				this.lettingWebMap.gmap.addOverlay(this.polyline);
				this.lettingWebMap.markers.push(this.polyline);

			}.bind(marker));

			GEvent.addListener(marker, 'mouseout', function() {
				this.lettingWebMap.removeMarker(this.tooltip);
				this.lettingWebMap.removeMarker(this.polyline);
			}.bind(marker));

			GEvent.addListener(marker, 'click', function() {
				this.lettingWebMap.gmap.removeOverlay(this.tooltip);
				this.lettingWebMap.gmap.removeOverlay(this.polyline);
				var bounds = new GLatLngBounds(new GLatLng(this.min_lat, this.min_long), new GLatLng(this.max_lat, this.max_long));
				var zoom = this.lettingWebMap.gmap.getBoundsZoomLevel(bounds);
				this.lettingWebMap.gmap.setCenter(this.getPoint(), zoom);
			}.bind(marker));

			this.gmap.addOverlay(marker);
			this.markers.push(marker);
		}

        if (count == 0) {
            this.showActivityIndicator('No matching properties');
        } else {
            if (count == 1) {
                $('map-property-count').innerHTML = '1 matching property';
            } else {
                $('map-property-count').innerHTML = count + ' matching properties';
            }
            this.hideActivityIndicator();
        }

	}

	GEvent.addListener(this.gmap, 'moveend', function() {
		this.update();
	}.bind(this));

	GEvent.addListener(this.gmap, 'zoomstart', function() {
		this.gmap.clearOverlays();
		this.markers = [];
	}.bind(this));

	GEvent.addListener(this.gmap, 'zoomend', function(oldZoomLevel, newZoomLevel) {
		this.gmap.clearOverlays();
		this.markers = [];
		if(newZoomLevel < 5){
			this.gmap.setZoom(5);
			alert('You cannot zoom out any further on this map.');
		}
	}.bind(this));

	this.update();
}
