Prototype.Browser.IE6=Prototype.Browser.IE && parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5))==6;


var pS = null;

function searchOnTheHouse() {
	this.smallMapDimensions = '';
	this.iconAgentImg = "/images/pins/agent_icon_med.png";
	this.iconPrivateImg = "/images/pins/private_icon_med.png";
	this.iconSoldImg = "/images/pins/sold_icon_med.png";
	this.iconAgentRentImg = "/images/pins/agent_rent_icon_med.png";
	this.iconPrivateRentImg = "/images/pins/private_rent_icon_med.png";
	this.iconRentedImg = "/images/pins/rented_icon_med.png";

	this.request = GXmlHttp.create();
	this.existingMarkers = {};
	this.icon = new GIcon();
	this.icon.image = this.iconSoldImg;
	this.icon.iconSize = new GSize(25, 30);
	this.icon.iconAnchor = new GPoint(10, 35);

	this.iconPrivate= new GIcon(this.icon, this.iconPrivateImg);
	this.iconAgent = new GIcon(this.icon, this.iconAgentImg);
	this.iconSold = new GIcon(this.icon, this.iconSoldImg);
	this.iconAgentRent = new GIcon(this.icon, this.iconAgentRentImg);
	this.iconPrivateRent = new GIcon(this.icon, this.iconPrivateRentImg);
	this.iconRented = new GIcon(this.icon, this.iconRentedImg);

	this.currentState = '';
	
	this.selectedId = null;
	this.mapMaximised = false;

	this.loadMaps = function(centerPoint, zoom, recentsearch) {
		var zoom = parseInt(zoom);
		this.trigger = false;
		this.inti = recentsearch;
		if($('map') != null)
		{
			this.map = new GMap2($('map'));
	      	var mt = this.map.getMapTypes();
	      	for (var i=0; i<mt.length; i++) {
    	    	mt[i].getMinimumResolution = function() {return 13;}
        		mt[i].getMaximumResolution = function() {return 19;}
      		}
			this.map.setCenter(centerPoint, zoom);
			this.map.addControl(new ExpandControl());
			this.map.addControl(new GMapTypeControl());
			this.map.addControl(new GSmallMapControl());
			this.keyboardHandler = new GKeyboardHandler(this.map);
			this.requestMarkers();
			GEvent.addListener(this.map, 'moveend', new Function('mySearchApp.requestMarkers()'));
			GEvent.addListener(this.map, 'infowindowopen', new Function('mySearchApp.markWindowOpened()'));
		}
	}
	this.createMarker = function(point, type, title, id, list, record_type) {
		
		if (type == 'private') {
			var marker = new GMarker(point, {icon:this.iconPrivate, zIndexProcess:privateIndex});
		} else if (type == 'sold') {
			var marker = new GMarker(point, {icon:this.iconSold, zIndexProcess:soldIndex});
		} else if (type == 'agent') {
			var marker = new GMarker(point, {icon:this.iconAgent, zIndexProcess:agentIndex});
		} else if (type == 'agent_rent') {
			var marker = new GMarker(point, {icon:this.iconAgentRent, zIndexProcess:rentIndex});
		} else if (type == 'private_rent') {
			var marker = new GMarker(point, {icon:this.iconPrivateRent, zIndexProcess:rentIndex});
		} else if (type == 'rented') {
			var marker = new GMarker(point, {icon:this.iconRented, zIndexProcess:rentedIndex});
		}

		GEvent.addListener(marker, 'click', new Function('mouseClick("'	+ id + '","' + record_type + '")'));
 		return marker;
	}
	this.showMarkers = function(points) {
		this.map.clearOverlays();
		this.existingMarkers = {};
		this.selectedId = null;
		for (i in points) {
			var type = points[i].type;
			var title = points[i].title;
			var property_id = points[i].property_id;
			
			this.existingMarkers[i] = this.createMarker(new GLatLng(points[i].lat,points[i].lng), type, '',	points[i].id, property_id, points[i].id_type);
			p[points[i].id] = this.existingMarkers[i];
			this.map.addOverlay(this.existingMarkers[i])
		}
		this.message("");
	}
	this.loadMarkers = function() {
		this.message("Loading Properties");
		if (this.request.readyState == 4) {
			for (i in this.existingMarkers) {
				if (!this.map.getBounds().contains(
						this.existingMarkers[i].getPoint())) {
					this.map.removeOverlay(this.existingMarkers[i]);
					delete this.existingMarkers[i];
				}
			}
			var num = 0;
			var points = {};
			var suburbs = {};
			if (this.request.responseText) {
				var jscript = this.request.responseText;
				if (jscript != '') {
					eval(jscript);
					this.showMarkers(points);
					this.showSuburbs(suburbs);
					//new Ajax.Updater('RecentSearch','/index.htm?Action=recent_search');
				}
			}
			this.requestBusy = false;
		}
	}
	this.markWindowOpened = function() {
		this.windowOpened = true;
	}
	this.requestMarkers = function() {
		if(this.windowOpened == true)
		{
			this.windowOpened = false;
			return;
		}


		this.message("Requesting Properties");
		var getVars = 'ne=' + this.map.getBounds().getNorthEast().toUrlValue()
				+ '&sw=' + this.map.getBounds().getSouthWest().toUrlValue()
				+ '&known=' + this.map.getCenter().toUrlValue() + '&zoom='
				+ this.map.getZoom()
				+ '&MapSearch=1';

		if (this.inti == true)
		{
			getVars = getVars + '&RecentSearchAdd=1';
			this.inti = false;
		}
		
		if (this.requestBusy == true) {
			this.request.abort();
			this.request = GXmlHttp.create(); 
		}
		this.request.open('GET', '/server/?' + getVars, true);
		this.request.onreadystatechange = new Function('mySearchApp.loadMarkers();');
		this.request.send(null);
		this.requestBusy = true;
	}
	this.showSuburbs = function(suburbs) {
		var adState = '';
		if (suburbs.num > 0) {
			var n = 0;
			for (i in suburbs) {
				// Ensure that only s variables get in
				if (i.substr(0, 1) == 's') {
					if (n == 0) {
						$('Suburb').value = suburbs[i].suburb;
						if(suburbs[i].suburb && suburbs[i].postcode)
						{
							$('Suburb').value = $('Suburb').value+' ('+suburbs[i].postcode+')';
							$('State').value = '';
						}
						if(suburbs[i].state)
						{
							$('State').value = suburbs[i].state;
						}
						adState = suburbs[i].state;
            var topAgentDiv = $('TopAgentBanner');
            new Ajax.Updater(topAgentDiv, '/?Action=top_agent&page_nr=1&postcode='+suburbs[i].postcode);
					}
					n++;
				}
			}
			
			if(this.currentState != adState)
			{
				if (adState == 'QLD')
				{
					adUpdateState = 'QLD';
				}
				else
				{
					adUpdateState = '';
				}
				
				new Ajax.Updater('StateSalesDisclaimer', '/?Action=property_results_map_disclaimer&State='+adState);
				this.currentState = adState;
			}
		}

	}

	this.message = function(messageString)
	{
		$('message').innerHTML = messageString;
	}

	this.toggleExpandMap = function()
	{
		this.mapWidth = 440;
		$('TopAgentBanner').setStyle({'width':'100%'});
		$('map').setStyle({'width' :'99%','overflow':'hidden'});
		$('map_view').setStyle({'float': 'right'});
		if (this.mapMaximised) {
			new Effect.Morph('map_view' , { style: 'width: '+this.mapWidth+'px; margin: 0px; ', queue: { position: 'end' , scope: 'a' } });
			new Effect.BlindDown('list_view_table', { delay: 1.1, queue: { position: 'start', scope: 'b' } });
			$('expand').innerHTML = '<< Expand Map';
			this.mapMaximised = false;
		} else  {
			new Effect.BlindUp('list_view_table', {queue:    {position: 'start', scope: 'a' }});
			margin = Prototype.Browser.IE6 ? margin = '5' : '15';
			new Effect.Morph('map_view' , { style: 'width: 910px; margin: '+margin+'px;', delay: 1.1, queue: {position:'end' , scope: 'b'}});
			$('expand').innerHTML = 'Shrink Map >>';
			this.mapMaximised = true;
		}

		setTimeout(function() { if (typeof(this.map) != undefined) {
				mySearchApp.map.checkResize();
				mySearchApp.requestMarkers();
		} }, 2500);
	}
}

function privateIndex(marker, b)
{
	return 3000;
}
function agentIndex(marker, b)
{
	return 2000;
}
function soldIndex(marker, b)
{
	return 1000;
}
function rentIndex(marker, b)
{
	return 3000;
}
function rentedIndex(marker, b)
{
	return 1000;
}



function mouseClickSuburb(id) {
	mySearchApp.map.setCenter(p[id].getPoint(), 16);
}

function mouseClick(id, type) {
	var handlerfunc = function(request) {
		setTimeout( function() {
			initLightbox();

		}, 20);
	}

	var url = '/index.htm?Action=ajax_lookup&Mode=mini_property_view&PropertyId='+id+'&PropertyType='+type;
	propertyInfo = "";
	new Ajax.Request(url, {
		asynchronous: false,
		method: 'get',
		onSuccess: function(transport) {
			propertyInfo = propertyInfo + transport.responseText;
		}
	});

	var offset = new GSize(0, -15);
	mySearchApp.map.openInfoWindow(p[id].getPoint(), propertyInfo, {pixelOffset: offset, maxWidth: 280});
}

function onClickProperty(propertyId, lat, lng, type) {
	var handlerfunc = function(request) {
		setTimeout( function() {
			initLightbox();
		}, 20);
	}
}

function gotoAddress(address) {
	mySearchApp.gotoAddress(address);
}

function addToShortlist(propertyId)
{
	new Ajax.Request('/buy/property/' + propertyId + '&AddShortlistItem=1'
             ,{ method:'post',
             onSuccess: function(transport)
             {
				var html = '<span title="Remove from short list" onClick="removeFromShortlist(' + propertyId + '); return false;"> ';
				html = html + '<span style="text-decoration: underline">Shortlist</span>';
				html = html + '<img src="/images/property_icons/shortlist_remove.gif" />';
				html = html + '</span>';
				$('shortlist_'+propertyId).update(html);
   		},
           onFailure: function() { alert('Property not added to short list.'); }
    });	
}

function removeFromShortlist(propertyId)
{
	new Ajax.Request('/buy/property/' + propertyId + '&RemoveShortlistItem=1'
             ,{ method:'post',
             onSuccess: function(transport)
             {
			 	var html = '<span title="Add to short list" onClick="addToShortlist(' + propertyId + '); return false;"> ';
				html = html + '<span style="text-decoration: underline">Shortlist</span>';
				html = html + '<img src="/images/property_icons/shortlist_add.gif" />';
				html = html + '</span>';
            	$('shortlist_'+propertyId).update(html);
			},
           onFailure: function() { alert('Property not remove from short list.'); }
    });	
}

// --- Expand/Shrink Map Control
function ExpandControl() {}
ExpandControl.prototype = new GControl();
ExpandControl.prototype.initialize = function(map) {
	var container = new Element('div');
	var expandDiv = new Element('div', {'id':'expand'}).update('<< Expand Map');
	container.appendChild(expandDiv);
	this.setButtonStyle_(expandDiv);
	GEvent.addDomListener(expandDiv, "click", function() {
		mySearchApp.toggleExpandMap();
	 });
	map.getContainer().appendChild(container);
	return container;
}

ExpandControl.prototype.getDefaultPosition = function() {
  return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(7, 7));
}

ExpandControl.prototype.setButtonStyle_ = function(button) {
	button.setStyle({'color':'#ae2121', 'font':'small Arial', 'backgroundColor':'white', 'border':'1px solid black', 'padding':'1px','textAlign':'center','cursor':'pointer'});
}
  
