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/blue_pin_med.png";
	this.iconSoldImg = "/images/pins/red_pin_med.png";
	this.iconAgentRentImg = "/images/pins/light_blue_pin_med.png";
	this.iconRentedImg = "/images/pins/orange_pin_med.png";
	this.iconSponsorImg = "/images/pins/suncorp.png";
	this.sponsorIndex = 4000;
	this.privateIndex = 3000;
	this.agentIndex   = 2000;
	this.soldIndex    = 1000;
	this.request    = null;
	this.existingMarkers = {};
	this.currentState = '';
	this.appendProperty = true;
	this.runOnce  = false;
	this.showSuburbsFlag = false;
	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)
		{
			var Options = {  zoom: zoom,  center: centerPoint,  mapTypeId: google.maps.MapTypeId.ROADMAP ,
				streetViewControl: false,
				mapTypeControl: true,
				mapTypeControlOptions: {    style: google.maps.MapTypeControlStyle.DROPDOWN_MENU },
				navigationControl: true,
				navigationControlOptions: { style: google.maps.NavigationControlStyle.SMALL }
			};
			this.map = new google.maps.Map($('map'), Options);
			var maxZoom = 19;
			var minZoom = 13;
			google.maps.event.addListener(this.map, 'zoom_changed', function() {
				if(mySearchApp.map.getZoom() > maxZoom){
							 mySearchApp.map.setZoom(maxZoom);
					 }else if(mySearchApp.map.getZoom() < minZoom){
							 mySearchApp.map.setZoom(minZoom);
					 }
			 });
			google.maps.event.trigger(this.map, "zoom_changed");
			this.requestMarkers();
			google.maps.event.addListener(this.map, 'moveend', new Function('mySearchApp.requestMarkers()'));
			google.maps.event.addListener(this.map, 'infowindowopen', new Function('mySearchApp.markWindowOpened()'));
			google.maps.event.addListener(this.map, "idle", function(){
				google.maps.event.trigger(mySearchApp.map, 'resize');
			});
		}
	}
	this.createMarker = function(point, type, title, id, list, record_type) {

		if (type == 'sold') {
			var marker = new google.maps.Marker({position:point, map: this.map, icon:this.iconSoldImg, zIndexProcess:this.soldIndex});
		} else if (type == 'agent' || type == 'private') {
			var marker = new google.maps.Marker({position:point, map: this.map, icon:this.iconAgentImg, zIndexProcess:this.agentIndex});
		} else if (type == 'agent_rent' || type == 'private_rent') {
			var marker = new google.maps.Marker({position:point, map: this.map, icon:this.iconAgentRentImg, zIndexProcess:this.agentIndex});
		} else if (type == 'rented') {
			var marker = new google.maps.Marker({position:point, map: this.map, icon:this.iconRentedImg, zIndexProcess:this.soldIndex});
		} else if (type == 'suncorp') {
			var marker = new google.maps.Marker({position:point, map: this.map, icon:this.iconSponsorImg, zIndexProcess:this.sponsorIndex});
		}
		if (type == 'suncorp')
			google.maps.event.addListener(marker, 'click', new Function('mouseSponsorClick("' + id + '")'));
		else
			google.maps.event.addListener(marker, 'click', new Function('mouseClick("'	+ id + '","' + record_type + '")'));
 		return marker;
	}
	this.showMarkers = function(points) {
		this.existingMarkers = {};
		this.selectedId = null;
		for (i in points) {
			var type = points[i].type;
			var property_id = points[i].property_id;
			this.existingMarkers[i] = this.createMarker(new google.maps.LatLng(points[i].lat,points[i].lng), type, '',	points[i].id, property_id, points[i].id_type);
			p[points[i].id] = this.existingMarkers[i];
		}
		if (this.appendProperty  && typeof(pAuto)=='object')
		{
			this.existingMarkers[++i] = this.createMarker(new google.maps.LatLng(pAuto.lat,pAuto.lng), type, '',	pAuto.id, pAuto.property_id, pAuto.id_type);
			p[pAuto.id] = this.existingMarkers[i];
			mouseClick(pAuto.property_id, pAuto.id_type);
			this.appendProperty = false;
		}
		this.message("");
	}
	
	this.loadMarkers = function(data) {
	this.message("Loading Properties");

			for (i in this.existingMarkers) {
					this.existingMarkers[i].setMap(null);
					delete this.existingMarkers[i];
			}
			var num = 0;
			var points = {};
			var suburbs = {};
		//	if (this.request.responseText) {
				var jscript = data;
				if (jscript != '') {
					eval(jscript);
					this.showMarkers(points);
					this.showSuburbs(suburbs);
				}
		//	}
			this.requestBusy = false;
//		}
	}
	
	this.markWindowOpened = function() {
		this.windowOpened = true;
	}
	this.requestMarkers = function() {
		if(this.windowOpened == true)
		{
			this.windowOpened = false;
			return;
		}
		google.maps.event.addListener(this.map, 'tilesloaded', function() {

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

			if (mySearchApp.inti == true)
			{
				getVars = getVars + '&RecentSearchAdd=1';
				mySearchApp.inti = false;
			}

			if (mySearchApp.requestBusy == true) {
				mySearchApp.request.abort();
			}

			if (!mySearchApp.runOnce)
			{
				var ExpandControlDiv = new Element('div');
				var iExpandControl = new ExpandControl(ExpandControlDiv);
				iExpandControl.index = 1;
				mySearchApp.map.controls[google.maps.ControlPosition.TOP_RIGHT].push(ExpandControlDiv);
				mySearchApp.runOnce = true;
			}

			mySearchApp.request = $j.ajax({
				url: '/server/?' + getVars,
				dataType: "script",
				success: function(data) { mySearchApp.loadMarkers(data); }
			});
			mySearchApp.requestBusy = true;
		});
	}
	
	this.showSuburbs = function(suburbs) {
		if (!this.showSuburbsFlag)
		{
			this.showSuburbsFlag = true;
			return;
		}
		
		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;
					}
					n++;
				}
			}
			
			if(this.currentState != adState)
			{
				$j('#StateSalesDisclaimer').load('/?Action=property_results_map_disclaimer&State='+adState);
				this.currentState = adState;
			}
		}

	}

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

	this.toggleExpandMap = function()
	{
		this.mapWidth = 440;
		$('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.setZoom( mySearchApp.map.getZoom()-1 );
				mySearchApp.map.setZoom( mySearchApp.map.getZoom()+1 );
				mySearchApp.requestMarkers();
		} }, 2500);
	}
}


function mouseClickSuburb(id) {
	alert('Depreciated function ? ');
	mySearchApp.map.setCenter(p[id].getPosition(), 16);
}

var infoWindow = null;
function mouseClick(id, type) {
	var handlerfunc = function(request) {
		setTimeout( function() {
			initLightbox();
		}, 20);
	}

	if (!infoWindow)
	{
		var offset = new google.maps.Size(0, 15);
		infoWindow = new google.maps.InfoWindow({maxWidth: 280, pixelOffset: offset});
	}
	infoWindow.close();
	infoWindow.open(mySearchApp.map, p[id]);
	infoWindow.setContent("");
	
	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;
		}
	});

	infoWindow.setContent(propertyInfo);
}

function mouseSponsorClick(id) {
	var handlerfunc = function(request) {
		setTimeout( function() {
			initLightbox();
		}, 20);
	}

	if (!infoWindow)
	{
		var offset = new google.maps.Size(0, 15);
		infoWindow = new google.maps.InfoWindow({maxWidth: 280, pixelOffset: offset});
	}

	infoWindow.close();
	infoWindow.open(mySearchApp.map, p[id]);
	infoWindow.setContent("");

	var url = '/index.htm?Action=ajax_lookup&Mode=sponsor_view&Id='+id;
	SponsorResponse = '';
	new Ajax.Request(url, {
		asynchronous: false,
		method: 'get',
		onSuccess: function(transport)
		{
			SponsorResponse = SponsorResponse + transport.responseText;
		}
	});
	infoWindow.setContent(SponsorResponse);
}

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

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

function addToShortlist(propertyId, recordType, e)
{
	if (typeof(e)!=='undefined'){ if (e.stopPropagation) e.stopPropagation(); e.cancelBubble = true; }
	new Ajax.Request('/buy/property/' + propertyId + '&AddShortlistItem=1&RecordType=' + recordType
             ,{ method:'post',
             onSuccess: function(transport)
             {
				var html = '<span title="Remove from short list" onClick="removeFromShortlist(' + propertyId + ', \'' + recordType + '\',event); 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.'); }
    });
	return false;
}

function removeFromShortlist(propertyId, recordType, e)
{
	if (typeof(e)!=='undefined'){ if (e.stopPropagation) e.stopPropagation(); e.cancelBubble = true; }
	new Ajax.Request('/buy/property/' + propertyId + '&RemoveShortlistItem=1&RecordType=' + recordType
             ,{ method:'post',
             onSuccess: function(transport)
             {
			 	var html = '<span title="Add to short list" onClick="addToShortlist(' + propertyId + ',\'' + recordType + '\', event); 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.'); }
    });
	return false;
}

// --- Expand/Shrink Map Control
function ExpandControl(expandDiv)
{
	expandDiv.id = 'expand';
	expandDiv.update('<< Expand Map');
	expandDiv.setStyle({'color':'#ae2121', 'font':'small Arial', 'backgroundColor':'white', 'border':'1px solid black', 'padding':'1px','textAlign':'center','cursor':'pointer','marginTop':'5px'});
	google.maps.event.addDomListener(expandDiv, "click", function() {
		mySearchApp.toggleExpandMap();
	 });
}  

