//Global variables

var CookieManager = Class.create( {
	initialize : function() {
	},

	createCookie : function(name, value, days) {
		if (days) {
			var date = new Date();
			date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
			var expires = "; expires=" + date.toGMTString();

		} else
			var expires = "";
		document.cookie = name + "=" + value + expires + "; path=/";
	},

	readCookie : function(name) {
		var nameEQ = name + "=";
		var ca = document.cookie.split(';');
		for ( var i = 0; i < ca.length; i++) {
			var c = ca[i];
			while (c.charAt(0) == ' ')
				c = c.substring(1, c.length);
			if (c.indexOf(nameEQ) == 0)
				return c.substring(nameEQ.length, c.length);
		}
		return null;
	},

	eraseCookie : function(name) {
		this.createCookie(name, "", -1);
	}

});

var _DEFAULT_INTEREST_RATE = 7.0;
var _DEFAULT_LOAN_TERM = 30;
var _shortListTab;
var _tabContent;
var _indicator;
var _currentSearchResults;
var _activePage = '';
var _prevPage ='';

var TABS = "tabs";
var TAB_WIDTH = 200;

function initGlobalVariables() {
	_shortListTab = $('shortlist-tab');
	_tabContent = $('tab-content');
	_indicator = $('indicator1');
}

var tabArray = new Array();
var TabRenderer = Class.create( {
	TABS :"tabs",
	SEARCH_RESULTS_TAB :"search-results-tab",
	RESULTS :"results-content",
	initialize : function() {
		Event.observe($(this.SEARCH_RESULTS_TAB), 'click', this.showResultsTab
				.bindAsEventListener(this));
		Event.observe(_shortListTab, 'click', this.showShortListTab
				.bindAsEventListener(this));
	},

	addTab : function(id, title) {

		this.clearTabs();
		var tab = new Tab(id, title, true);
		if (!this.doesTabExist(tab)) {
			tabArray[tabArray.length] = tab;
		}

		this.renderTabs();
	},

	attachEventHandlers : function() {
		TabUtils.AttachCloseTabEventHandler();
	},

	doesTabExist : function(tab) {
		var tabCount = tabArray.length;
		var exist = false;
		if (tabCount > 0) {
			for ( var i = 0; i < tabCount; i++) {
				if (tab.id == tabArray[i].id) {
					tabArray[i].setActive(true);
					exist = true;
					break;
				}
			}
		}
		return exist;
	},

	renderTabs : function() {
		TabUtils.RenderTabs();
	},

	clearTabs : function() {
		TabUtils.ClearTabs();
	},

	unactivateAllTabs : function() {
		TabUtils.UnactivateAllTabs();
	},

	showResultsTab : function() {
		TabUtils.ShowResultsTab();
	},

	showShortListTab : function() {
		TabUtils.ShowShortListTab();
	},

	hideResultsTab : function() {
		$(this.RESULTS).hide();
		$(this.SEARCH_RESULTS_TAB).removeClassName('active');
		var tabContent = _tabContent;
		tabContent.show();
		tabContent.addClassName('tab-content-active');
	}

});

var Tab = Class.create( {
	TAB :"tab",
	ACTIVE :"active",
	CLOSE_ID_PREFIX :"closeId_",
	initialize : function(id, title, isActive) {
		this.id = id;
		this.title = title;
		this.active = isActive;
	},

	getId : function() {
		return this.id;
	},

	getCloseId : function() {
		return this.CLOSE_ID_PREFIX + this.id;
	},

	getTabId : function() {
		return this.TAB + "_" + this.id;
	},

	getTitle : function() {
		return this.title;
	},

	setActive : function(isActive) {
		this.active = isActive;
	},
	isActive : function() {
		return this.active == true;
	},

	toHTMLElement : function() {
		var closeId = this.CLOSE_ID_PREFIX + this.id
		var a = new Element('a', {'title':'close', 'href':'javascript:void(0);'});
		a.addClassName('tab-close');
		var img = new Element('img', {'id':closeId,'src':'/images/close.gif'});
		a.appendChild(img);

		var addressLink = new Element('a', {'href': ListingUtils.BuildBookmarkableUrl(
				this.id, this.title), 'id':'tabaddr_' + this.id, 'style':'vertical-align:top;'});

		var tab = new Element('li',{'id': this.TAB + "_" + this.id, 'tab':this.TAB});
		if (this.isActive()) {
			tab.addClassName(this.ACTIVE);
		}

		var title = document.createTextNode(this.title.unescapeHTML());

		var addressLength = this.title.length;
		if (addressLength > 25) {
			title = document
					.createTextNode((this.title.substring(0, 23) + "..")
							.unescapeHTML());
		}
		addressLink.appendChild(title);
		tab.appendChild(a);
		tab.appendChild(addressLink);

		return tab;
	},

	element : function() {
		return $(this.TAB + "_" + this.id);
	}
});

var listings = null;

var NumberUtils = {};
NumberUtils.convertToCurrency = function(num) {
	num = num.toString().replace(/\$|\,/g, '');
	if (isNaN(num))
		num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num * 100 + 0.50000000001);
	cents = num % 100;
	num = Math.floor(num / 100).toString();
	if (cents < 10)
		cents = "0" + cents;
	for ( var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
		num = num.substring(0, num.length - (4 * i + 3)) + ','
				+ num.substring(num.length - (4 * i + 3));
	return (((sign) ? '' : '-') + '$' + num);
}

var ListingLookup = {};
ListingLookup.ListingCacheStore = new Hash();
ListingLookup.basicMap;
ListingLookup.FindById = function(id) {
	function decorate() {
		new ImageManager();
	}

	var cachedListing = ListingLookup.ListingCacheStore.get(id);

	if (cachedListing) {
		_indicator.show();
		_tabContent.update(cachedListing);
		decorate();
		window.setTimeout( function() {
			_indicator.hide();
		}, 500);
		Event.observe($('submitEmailForm'), 'click', ListingUtils.EmailAgent
				.bindAsEventListener(this));
		var latitude = $F('pLat');
		var longitude = $F('pLng');
		
		ListingLookup.basicMap = new BasicMap("map-details-canvas", 15, latitude, longitude);
		PropertyUtils.showNearestAmenities('amenitiesRP', latitude, longitude,$F('listingState'), true);
		PropertyUtils.showComments(id);
		PropertyUtils.showPropertyPassHistory(id);
	} else {
		new Ajax.Updater('tab-content', '/ajax/listing/show/'+id, {
			asynchronous :true,
			evalScripts :true,
			method :'get',
			onLoading : function() {
				_indicator.show();
			},
			onComplete : function(response) {
				decorate();
				ListingLookup.ListingCacheStore.set(id, response.responseText);
				window.setTimeout( function() {
					_indicator.hide();
				}, 500);
				Event.observe($('submitEmailForm'), 'click',
						ListingUtils.EmailAgent.bindAsEventListener(this));
				var latitude = $F('pLat');
				var longitude = $F('pLng');
				
				PropertyUtils.showNearestAmenities('amenitiesRP', latitude, longitude,$F('listingState'), true);
				PropertyUtils.showComments(id);
				PropertyUtils.showPropertyPassHistory(id);
				ListingLookup.basicMap = new BasicMap("map-details-canvas", 15, latitude, longitude);

			},
			onSuccess :function(response){
		
			}
		});

		var currentPageHref = (window.location.href).replace(
				window.location.host, '').replace("http://", '');
		GoogleUtils.trackPage(currentPageHref);
	}
}

ListingLookup.SearchResultsCache = new Object;
ListingLookup.Find = function(page) {
	
	initGlobalVariables();
	var params = new Object();
	var suburb = $F('suburb');
	var state = $F('state');
	params['suburb'] = suburb;
	params['state'] = state;
	params['listingType'] = $F('listingTypeValue');
	
	if (page) {
		params['page'] = page;
	} else {
		params['page'] = $F('currentPage');
	}
	params['maxResults'] = '30';
	params['sortby'] = $F('sortby');

	ListingUtils.GetMetaDataCount(params, 'bedRoomCount', 'bedrooms-num');
	ListingUtils.GetMetaDataCount(params, 'bathRoomCount', 'bathrooms-num');
	ListingUtils.GetMetaDataCount(params, 'carParkCount', 'carparks-num');
	ListingUtils.GetMetaDataCount(params, 'landSize', 'landsize-num');

	priceFrom = $F('price-from');
	if (priceFrom && priceFrom > 0) {
		params['startingPrice'] = priceFrom;
	}

	priceTo = $F('price-to');
	if (priceTo && priceTo < 2000000) {
		params['closingPrice'] = priceTo;
	}

	ListingUtils.AddToFilterBySelection(params, 'house');
	ListingUtils.AddToFilterBySelection(params, 'townhouse');
	ListingUtils.AddToFilterBySelection(params, 'unit');
	ListingUtils.AddToFilterBySelection(params, 'apartment');
	ListingUtils.AddToFilterBySelection(params, 'land');
	var inspectionAuctionTime = $('inspectionAuction');
	if(inspectionAuctionTime && inspectionAuctionTime.visible()){
		var inspectionOrAuction = $F('displayInspectionOrAuction');
		if(inspectionOrAuction == 'AUCTION'){
//			$('auctionLnk').addClassName('active');
//			$('inspectionLnk').removeClassName('active');
			params['displayAuctions'] = true;
		}else if(inspectionOrAuction == 'INSPECTION'){
//			$('inspectionLnk').addClassName('active');
//			var auctLnk = $('auctionLnk');
//			if(auctLnk){
//				auctLnk.removeClassName('active');
//			}
			
			params['displayInspections'] = true;
		}
		params['inspectionAuctionDateRange'] = $F('inspectionAuctionDateRange');
	}

	var searchResults = ListingLookup.SearchResultsCache[page];

	function init(searchResults, isCached) {
		if (!isCached) {
			ListingLookup.SearchResultsCache[searchResults.currentPage] = searchResults;
		}
		var listings = searchResults.listings;
		
		//find first listing that has address and set to center
		if(listings){
			listings
				.each( function(listing) {
					var listingAddress = listing.listingAddress;
					if(listingAddress.streetName && listingAddress.streetName !='' && listingAddress.latitude && listingAddress.longitude){
						$('latitude').setValue(listingAddress.latitude);
						$('longitude').setValue(listingAddress.longitude);
						throw $break;
					}
				});
		}

		_currentSearchResults = searchResults;
		new ListingsResultsRender(listings);
		new Paginator(searchResults.totalResults, searchResults.currentPage,
				searchResults.maxResults);
		new ShortlistManager();

		ListingUtils.DrawMapForResults();
		ListingUtils.Decorate(listings);

		window.setTimeout( function() {
			_indicator.hide();
		}, 500);
	}
	_indicator.show();
	if (searchResults) {		
		init(searchResults, true);
	} else {
		ListingSearchServiceJS.search(params, function(searchResults) {
			init(searchResults, false);
		});
	}
}

ListingLookup.FindByInspectionAuctionTimes = function(inspectionOrAuction){
	$('displayInspectionOrAuction').setValue(inspectionOrAuction);
	//clear search results
	ListingLookup.SearchResultsCache = new Object;
	ListingLookup.Find(1);
	FilterUtil.updateInspectionAuctionText(inspectionOrAuction);
}

ListingLookup.FindListingInSearchResults = function(id) {
	var listings = _currentSearchResults.listings;
	var count = listings.length;
	for ( var i = 0; i < count; i++) {
		var listing = listings[i];
		if (listing.listingId == id) {
			return listing;
		}
	}
	return null;
}

var ListingUtils = {};

ListingUtils.Decorate = function(listings){
	function renderDistanceToStation(listingId, stationName, dist,
			listingLat, listingLng, latitude, longitude) {
		var a = new Element('a', {'href':'javascript:void(0);', "title": dist + " km to " + stationName + " station"});

		a.onclick = function(){
			MapService.addCustomMarker(new CustomMarker(stationName + " Train Station", "/images/train.png", latitude, longitude));
			MapService.calcRoute(listingLat,listingLng, latitude, longitude);
		}
		
		var txt = document.createTextNode(dist + " km to nearest station ");
		a.appendChild(txt);
		var distance = $("st-" + listingId);
		if (distance) {
			distance.update();
			distance.appendChild(a);
		}
	}

	function renderDistanceToCbdAndMoreLink(listingId, cbd, dist, latitude, longitude, state) {
		var distance = $("cbd-" + listingId);
		var txt = document.createTextNode(" " + dist + " km to CBD | ");
		if (distance) {
			distance.update();
			distance.appendChild(txt);
		}
		var moreNearestLink = new Element('a', {'title':'Expand to see nearest: schools, shops etc', 'href':'javascript:void(0);'});
		moreNearestLink.addClassName('nearest');
		moreNearestLink.update(" nearest ");
		moreNearestLink.onclick= function(){
			PropertyUtils.showNearestAmenities("rph-"+listingId, latitude, longitude, state, false);
		}
		distance.appendChild(moreNearestLink);
	}
	
	if(listings){
		listings
		.each( function(listing) {
			var address = listing.listingAddress;
			MapService.addMarkers(listing);
			if(address.streetName && address.streeName !=''){
			
				if (address.latitude && address.longitude) {
	
					if (address.distanceToTrainStation) {
						renderDistanceToStation(listing.listingId,
								address.nearestTrainStation.stationName,
								address.distanceToTrainStation,
								address.latitude,
								address.longitude,
								address.nearestTrainStation.latitude,
								address.nearestTrainStation.longitude);
					} else {
						DistanceServiceJS
								.locateNearestStation(
										address.latitude,
										address.longitude,
										address.state,
										function(result) {
											if (result) {
												var dist = ((result.distance * 100)
														.round()) / 100;
												if (dist < 100) {
													renderDistanceToStation(
															listing.listingId,
															result.trainStation.stationName,
															dist,
															address.latitude,
															address.longitude,
															result.trainStation.latitude,
															result.trainStation.longitude);
												}
											}
										});
					}
	
					if (address.distanceToCbd) {
						renderDistanceToCbdAndMoreLink(listing.listingId, "",
								address.distanceToCbd.distance, address.latitude, address.longitude, address.state);
					} else {
						DistanceServiceJS
								.distanceToCbd(
										address.latitude,
										address.longitude,
										address.state,
										function(result) {
											if (result) {
												var dist = ((result * 100)
														.round()) / 100;
												if (dist < 200) {
//													renderDistanceToCbd(
//															listing.listingId,
//															"", dist, address.latitude, address.longitude, address.state);
												}
											}
										});
					}
				}	
			}
		});
	}
}

ListingUtils.ResizeWindow = function() {
	var top = 140;
	var bottom = 30;
	var viewportHeight = document.viewport.getHeight();
	var height = viewportHeight - top - bottom;
	var results = $('results-inner');
	var googleMapCanvas = $('google-map-canvas');
	if (results) {
		if (height < 373) {
			results.style.height = "373px";
		} else {
			results.style.height = height + "px";
		}
	}
	if (googleMapCanvas) {
		var width = document.viewport.getWidth() - 480;
		googleMapCanvas.style.width = width + "px";
		if (height < 373) {
			$('results-content').style.height = "457px";
			googleMapCanvas.style.height = "373px";
		} else {
			$('results-content').style.height = (viewportHeight - 90) + "px";
			googleMapCanvas.style.height = height + "px";
		}
	}
	TabUtils.ClearTabs();
	TabUtils.RenderTabs();

}

ListingUtils.GetParam = function(name) {
	name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
	var regexS = "[\\?&]" + name + "=([^&#]*)";
	var regex = new RegExp(regexS);
	var results = regex.exec(window.location.href);
	if (results == null) {
		return "";
	} else {
		return results[1];
	}
}

ListingUtils.GetMetaDataCount = function(params, key, input) {
	count = $F(input);
	if (count && count > 0) {
		params[key] = count;
	}
}

ListingUtils.AddToFilterBySelection = function(params, propertyType) {
	var property = $(propertyType);
	if (property.checked == true) {
		params[propertyType.toUpperCase()] = propertyType.toUpperCase();
	}
}

ListingUtils.GetValue = function(value, defaultValue) {
	if (!value) {
		return defaultValue;
	} else {
		return value;
	}
}

ListingUtils.DrawMapForResults = function() {
//	if ($('logocontrol') && $F('showingMap') == 'results'
//			&& $F('currentPage') == $F('mapPageState')) {
//	} else {
//		$('showingMap').setValue('results');
//		$('mapPageState').setValue($F('currentPage'));
//		new Initialiser($F('latitude'), $F('longitude'), $F('suburb'),
//				$F('state'), _currentSearchResults.listings, null,
//				"google-map-canvas");
//	}
	//-37.7964130, 145.1501260
	var drawMapOnDemand = $('drawMapOnDemand');
	var showMapFlag = $('showingMap');	
	var currentPage = $('currentPage');
	var mapPageState = $('mapPageState');
	if((!MapService.map || showMapFlag.value != 'results' || currentPage.value != mapPageState.value || drawMapOnDemand.value== 'true') && $F('renderMaps')){
		showMapFlag.setValue('results');
		drawMapOnDemand.setValue('false');
		mapPageState.setValue(currentPage.value);
		if(MapService.isOptionsFromSavedStateAvailable()){
			MapService.useOptionsFromLastSavedState();
		}else{
			MapService.overrideDefaultOptions(15, $F('latitude'), $F('longitude'));
		}
		//MapService.map = new google.maps.Map($("google-map-canvas"), MapService.mapOptions);
		MapService.createNew("google-map-canvas");
	}
	
}

ListingUtils.DrawMapForShortlist = function() {

		var showMapFlag = $('showingMap');	
		if((!MapService.map || showMapFlag.value != 'shortlist') && $F('renderMaps')){
			showMapFlag.setValue('shortlist');
			
			MapService.overrideDefaultOptions(15, new google.maps.LatLng($F('latitude'), $F('longitude')));
			//recenter to first listing that has lat and long
			if(shortlistCache){
				shortlistCache
					.each( function(listing) {
						var listingAddress = listing.listingAddress;
						if(listingAddress.streetName && listingAddress.streetName !='' && listingAddress.latitude && listingAddress.longitude){
							MapService.overrideDefaultOptions(15, listingAddress.latitude,listingAddress.longitude);
							throw $break;
						}
					});
			}
			
			MapService.createNew("google-map-canvas");
			ListingUtils.Decorate(shortlistCache);
		}
}

ListingUtils.BuildBookmarkableUrl = function(id, address) {
	return '#?id=' + id + '&addr=' + address.replace(/(\s)/g, "_");
}

ListingUtils.BuildFullBookmarkableUrl = function(id, address) {

	var fullUrl = window.location.href;
	var newUrl = "";
	if (fullUrl.indexOf("rent") < 0 && fullUrl.indexOf("buy") < 0) {
			newUrl = "/shortlist"
	}
	newUrl = newUrl + ListingUtils.BuildBookmarkableUrl(id, address);
	setTimeout( function() {
		window.location = newUrl;
	}, 0);
}

ListingUtils.EmailAgent = function() {
	var params = new Object();
	var listingId = $('listing-id').innerHTML;
	params['buyersName'] = $F('fullName').strip();
	params['buyersEmail'] = $F('email').strip();
	params['buyersContactNumber'] = $F('contactNumber')
	params['buyersComments'] = $F('content').strip();
	params['agentsName'] = $('primary-contact-name').innerHTML;
	params['agentsEmail'] = $('primary-contact-email').innerHTML;
	params['agentsContactNumber'] = $('primary-contact-number').innerHTML;
	params['address'] = $F('fullAddress');
	params['listingUrl'] = window.location.href;

	function validateFormFields() {
		if (params['buyersName'] == "") {
			alert("Please enter your name!");
			return false;
		}

		if (params['buyersEmail'] == "") {
			alert("Please enter your email!");
			return false;
		}

		if (params['buyersComments'] == "") {
			alert("Please enter message content!");
			return false;
		}

		return true;
	}

	if (listingId) {
		if (validateFormFields()) {
			$('indicator2').show();
			EmailServiceJS.emailAgent(params, function(result) {
				if (result == 'SUCCESS') {
					alert("Your message has been successfully sent!");
				} else {
					alert("Woops, we're having difficulties sending out the email. Please try again later!");
				}
				$('indicator2').hide();
			});
		}
	}
}

var TabUtils = {};
TabUtils.CreateTab = function(event) {
	var element = Event.element(event);
	var tabRenderer = new TabRenderer();
	tabRenderer.hideResultsTab();

	tabRenderer.addTab(element.id.replace('shortlist-', '')
			.replace('info-', ''), element.innerHTML);
}

TabUtils.CreateTabById = function(id, address) {
	var tabRenderer = new TabRenderer();
	tabRenderer.hideResultsTab();

	tabRenderer.addTab(id, address);
}

TabUtils.ActivateTab = function(id) {
	var tabCount = tabArray.length;
	for ( var i = 0; i < tabCount; i++) {
		if (id == tabArray[i].getId()) {
			$(tabArray[i].getTabId()).addClassName('active');
			tabArray[i].setActive(true);
		} else {
			$(tabArray[i].getTabId()).removeClassName('active');
			tabArray[i].setActive(false);
			tabArray;
		}
	}
}

TabUtils.UnactivateAllTabs = function() {
	var tabCount = tabArray.length;
	if (tabCount > 0) {
		for ( var i = 0; i < tabCount; i++) {
			tabArray[i].setActive(false);
			tabArray[i].element().removeClassName('active');
		}
	}
	TabUtils.ClearTabs();
	TabUtils.RenderTabs();
}

TabUtils.RenderTabs = function() {
	var tabs = $(TABS);
	var length = tabArray.length;
	var viewport = document.viewport.getWidth() - 390;

	tabArray.each( function(tab) {
		tabs.appendChild(tab.toHTMLElement());

		if (viewport < length * TAB_WIDTH) {
			var newWidth = Math.round(viewport / length);
			$(tab.getTabId()).setStyle( {
				width :newWidth + "px",
				overflow :'hidden'
			});
		}

		if (tab.isActive()) {
			RoundedTop("span#" + tab.getTabId(), "#FFF", "#9DD4FF");
		} else {
			RoundedTop("span#" + tab.getTabId(), "#FFF", "#EFEFEF");
		}
	});
	TabUtils.AttachCloseTabEventHandler();
}

TabUtils.ClearTabs = function() {
	var tabs = $(TABS);
	tabArray.each( function(tab) {
		tabs.removeChild(tab.element());
	});
}

TabUtils.ShowResultsTab = function() {
	var results_content = $('results-content');

	if (!results_content.visible()) {
		results_content.show();
		$('search-results-tab').addClassName('active');
		_tabContent.hide();
	}
	window.location.hash = "#";
	TabUtils.UnactivateAllTabs();
}

TabUtils.AttachCloseTabEventHandler = function() {

	function removeTabEvent(element) {
		var tabCount = tabArray.length;
		var tmpArray = new Array();

		for ( var i = 0; i < tabCount; i++) {
			if (element.id == tabArray[i].getCloseId()) {
				var currentTab = tabArray[i];
				$(this.TABS).removeChild(currentTab.element());
				if (currentTab.isActive()) {
					var index = 0;
					if (i == 0) {
						index = 1;
					}
					tab = tabArray[index];
					if (tab) {
						$(tab.getTabId()).addClassName('active');
						tabArray[index].setActive(true);
						window.location.hash = ListingUtils
								.BuildBookmarkableUrl(tab.getId(), tab
										.getTitle());
						ListingLookup.FindById(tab.getId());
					}
				}
			} else {
				tmpArray[tmpArray.length] = tabArray[i];
			}
		}

		tabArray = tmpArray;
		if (tabArray.length <= 0) {
			window.location.hash = "#";
			TabUtils.ShowResultsTab();
		}
	}

	tabArray.each( function(tab) {
		$(tab.getCloseId()).onclick = function(){ removeTabEvent(this);}
	});
}

TabUtils.ShowShortListTab = function() {
	var results_content = $('results-content');
	if (!results_content.visible()) {
		$('results-content').show();
		$('search-results-tab').addClassName('active');
		_tabContent.hide();
	}

	TabUtils.UnactivateAllTabs();
}

TabUtils.ShowShortlist = function() {

	$('activeTab').setValue('shortlist');

	var results_content = $('results-content');
	var indicator = $('indicator1');
	if (!results_content.visible()) {
		$('results-content').show();
		$('search-results-tab').addClassName('active');
		_tabContent.hide();
	} else {
		indicator.show();
	}

	$('shortlist-count').update(shortlistCache.length);
	new ListingsResultsRender(shortlistCache);
	new ShortlistManager();
	var pages = $('pages');
	if(pages){
		pages.hide();
	}
	window.setTimeout( function() {
		indicator.hide();
	}, 500);
	$('shortlist-options').removeClassName('hide');
	$('results-summary').addClassName('hide');
	$('shortlist-tab').addClassName('underline');
	$('search-results-tab').removeClassName('underline');
	ListingUtils.DrawMapForShortlist();
	TabUtils.UnactivateAllTabs();

}

TabUtils.ShowSearchResults = function() {
	$('activeTab').setValue('results');
	var results_content = $('results-content');

	if (!results_content.visible()) {
		//ShortlistUtil.toggleShortlistMode();
		$('results-content').show();
		$('search-results-tab').addClassName('active');
		_tabContent.hide();
	}
	ListingLookup.Find($F('currentPage'));
	$('shortlist-options').addClassName('hide');
	$('results-summary').removeClassName('hide');
	_shortListTab.removeClassName('underline');
	$('search-results-tab').addClassName('underline');
	TabUtils.UnactivateAllTabs();
}

var ListingsResultsRender = Class.create( {
	initialize : function(listings) {

		var count = listings.length;
		var outerUl = new Element('ul');
		for ( var i = 0; i < count; i++) {
			outerUl.appendChild(this.renderListing(listings[i]));
		}
	
		var results = $('results');
		results.update('');
		results.appendChild(outerUl);
	},
	
	renderListing : function(listing){
		var li = new Element('li', {'id':'rb-'+listing.listingId});			
		li.addClassName('result-block');
		var div = this.renderUl();
		var parentUl = new Element('ul');
		parentUl.appendChild(this.renderImage(listing));
		parentUl.appendChild(this.renderAddress(listing));
		parentUl.appendChild(this.renderPrice(listing));
		parentUl.appendChild(this.renderMetaData(listing));
		parentUl.appendChild(this.renderTrainDistance(listing));
		parentUl.appendChild(this.renderCbdDistance(listing));
//		
		div.appendChild(parentUl);

		li.appendChild(div);
		li.appendChild(this.renderPlaceHolderReplacementPoint(listing));
		li.appendChild(this.renderComments(listing));
		li.appendChild(this.renderUserDefinedPrice(listing));
		li.appendChild(this.renderInspectionTimes(listing));
		li.appendChild(this.renderOptions(listing));
		
		li.onmouseover= function(){$(this).addClassName('highlight')};
		li.onmouseout= function(){$(this).removeClassName('highlight')};
	
		return li;
	},
	
	renderUserDefinedPrice : function(listing){
		var soldPrice = listing.priceRange.soldPrice;
		if(soldPrice){
			var soldPriceDiv = new Element('div');
			soldPriceDiv.update(soldPrice);
		}else{
			var userDefinedPrice = new Element('div', {'id':'up_'+listing.listingId, 'style':'display:none;'});
			userDefinedPrice.addClassName('uPrice');
			
			var close = new Element('a',{'href':'javascript:void(0);'});
			var closeImg = new Element('img', {'src':'/images/close.gif'});
			close.appendChild(closeImg);
			close.onclick= function(){$('up_' + listing.listingId).hide();}
			
			userDefinedPrice.appendChild(close);
			
			userDefinedPrice.appendChild((new Element('h5')).update("Know the Sold &/or Advertised price?"));
			userDefinedPrice.appendChild(document.createTextNode("Share it with everyone!"));
			userDefinedPrice.appendChild(new Element("br"));
			if(!listing.priceRange.startingPrice){
				userDefinedPrice.appendChild(document.createTextNode('$'));
				var advertInputField = new Element('input', {'type':'text'})
				userDefinedPrice.appendChild(advertInputField);
				
				var adertPriceLnk = new Element('a',{'href':'javascript:void(0);'});
				adertPriceLnk.addClassName('add');
				adertPriceLnk.update("Add advertise price");

				adertPriceLnk.onclick= function(){
					PropertyUtils.addPrice(listing.listingId, $F(advertInputField.identify()), 'ADVERTISED'); 
				};
				
				userDefinedPrice.appendChild(adertPriceLnk);
				userDefinedPrice.appendChild(new Element('br'));
				
			}
			userDefinedPrice.appendChild(document.createTextNode('$'));
			var inputField = new Element('input', {'type':'text'})
			userDefinedPrice.appendChild(inputField);
			var soldPriceLnk = new Element('a',{'href':'javascript:void(0);'});
			soldPriceLnk.addClassName('add');
			soldPriceLnk.update("Add sold price");
			soldPriceLnk.onmousedown = function(){PropertyUtils.addPrice(listing.listingId, $F(inputField.identify()), 'SOLD');};
			userDefinedPrice.appendChild(soldPriceLnk);
			return userDefinedPrice;
		}
	},
	
	renderInspectionTimes : function(listing){
		var nextInspection = listing.nextInspectionTime;
		var div = new Element("div");
		div.addClassName('nextInspectionTime');
		if(nextInspection){
			var wrapper = new Element("div");
			wrapper.addClassName('nextInspectionTimeInner');
			if(nextInspection.auctionDate){
				wrapper.appendChild((new Element("span")).update("Next auction"));
			}else{
				wrapper.appendChild((new Element("span")).update("Next inspection"));
			}
			wrapper.appendChild(document.createTextNode(nextInspection.inspectionTimeForDisplay));
			div.appendChild(wrapper);
		}
		return div;
	},
	
	renderComments :function(listing){
		var comments = listing.comments;
		var div = new Element("div",{'id':'c_' + listing.listingId, 'style':'display:none;'});
		div.addClassName('comments');
		
		var close = new Element('a',{'href':'javascript:void(0);'});
		var closeImg = new Element('img', {'src':'/images/close.gif'});
		close.appendChild(closeImg);
		close.onclick= function(){$('c_' + listing.listingId).hide();}
		div.appendChild(close);
		
		var heading = new Element('h5');
		heading.update("Log Book");
		div.appendChild(heading);
		
		var ul = new Element("ul", {'id':'cIndex_'+listing.listingId});
		var li = new Element("li");
		var totalComments = comments.length;
		var screenName = $('scrnName');
		if(comments && totalComments > 0){
			var maxComments = 3;
			for(var i =0; i <= maxComments; i++){
				var comment = comments[i];
			   if(comment){
	               if(i < maxComments){
	            	   var preComment = new Element("pre");
	            	   preComment.appendChild(document.createTextNode("> "+comment.comment));
	            	   var dateCreated = new Element('div')
	            	   dateCreated.addClassName('date');
	            	   if(comment.visibility == 'PRIVATE'){
	            		   if(screenName && comment.user.screenName == screenName.innerHTML){
	            			   li.appendChild(preComment);
	            			   li.appendChild(dateCreated.update("on "+comment.createDate.toDateString() + " by <span>"+comment.user.screenName+"</span> "));
	            			   dateCreated.appendChild(new Element('img', {'src':'/images/lock.jpg', 'title':'This comment is only visibile to you'}));
	            			   ul.appendChild(li);
	            		   }else{
	            			   preComment.update("> Private message");
	            			   li.appendChild(preComment);
	            			   ul.appendChild(li);
	            			   maxComments++;
	            		   }
	            	   }else{
	            		   li.appendChild(preComment);
	            		   li.appendChild(dateCreated.update("on "+comment.createDate.toDateString() + " by <span>"+comment.user.screenName+"</span>"));
	            		   ul.appendChild(li);
	            	   }
	               }else{
	            	   break;
	               }
				}
			}
		}else{
			li.addClassName("remove");
			li.update("Create a log book entry for this property now");
			ul.appendChild(li);
		}
		
		div.appendChild(ul);
		div.appendChild(this.renderCommentTextBox(listing));

		return div;
	},
	
	renderCommentTextBox:function(listing){
		var div = new Element('div');
		var legend = new Element('legend');
		legend.update('Add entry')
		var fieldset = new Element('fieldset');
		fieldset.appendChild(legend);
		
		var text = new Element('textarea',{'id':'comment_'+listing.listingId});
		fieldset.appendChild(text);
		fieldset.appendChild(new Element('br'));
		var submit =  new Element('button');
		submit.addClassName('go');
		submit.update("add");
		submit.onclick = function(){PropertyUtils.addComment(listing.listingId);};
		
		fieldset.appendChild(submit);
		var visibility = new Element('input', {'type':'checkbox', 'checked':'checked', 'id':'cvisib_'+listing.listingId});
		fieldset.appendChild(visibility);
		fieldset.appendChild(document.createTextNode("Keep entries private |"));
		
		var shortAddress = listing.listingAddress.shortAddress;
		if(shortAddress && shortAddress.length > 0){
			var seeAll = new Element('a',{'href':ListingUtils.BuildBookmarkableUrl(
					listing.listingId, listing.listingAddress.shortAddress)});
		}else{
			var seeAll = new Element('a',{'href':ListingUtils.BuildBookmarkableUrl(
					listing.listingId, listing.listingAddress.suburb)});
		}
		fieldset.appendChild(document.createTextNode(" "));
		
		seeAll.update("all entries");
		fieldset.appendChild(seeAll);

		div.appendChild(fieldset);
		return div;
	},

	renderTrainDistance : function(listing) {
		var element = new Element('li', {'id' : "st-" + listing.listingId});
		element.addClassName('distance');
		return element;
		
	},

	renderCbdDistance : function(listing) {
		var element = new Element('li', {'id' : "cbd-" + listing.listingId});
		element.addClassName('distance');
		return element;
	},

	renderUl : function() {
		var element = new Element('div');
		element.addClassName('result');
		return element;
	},

	renderImage : function(listing) {
		var li = new Element('li');
		li.addClassName('property-img');
		var img = new Element('img');
		var mainImage = listing.images[0];
		if (mainImage && mainImage.fileName != "") {
			var fileName = mainImage.fileName;
			img.setAttribute('src', fileName);
			img.setAttribute('alt', 'No Image')
			li.appendChild(img);
		} else {
			var text = document.createTextNode("No image");
			li.appendChild(text);
		}
		return li;
	},

	renderAddress : function(listing) {
		var li = new Element('li');
		var a = new Element('a');
		a.addClassName('address');
		var jsDate = new Date(listing.listedDate);
		jsDate.setDate(jsDate.getDate() + 3);
		var todaysDate = new Date();
		if (jsDate > todaysDate) {
			a.addClassName('new-listing');
		}
		a.setAttribute('id', listing.listingId);
		var shortAddress = listing.listingAddress.shortAddress;
		
		a.setAttribute("title", listing.listingAddress.fullAddress);

		if(shortAddress && shortAddress.length > 0){
			a.setAttribute('href', ListingUtils.BuildBookmarkableUrl(listing.listingId, shortAddress));
			a.update(this.trimToFit(listing.listingAddress.shortAddress, 24));
		}else{
			a.setAttribute('href', ListingUtils.BuildBookmarkableUrl(
					listing.listingId, listing.listingAddress.suburb));
			a.update(listing.listingAddress.suburb);
		}
		
		li.appendChild(a);
		return li;
	},

	renderPrice : function(listing) {
		var li = new Element('li');
		li.addClassName('price');
		var displayText = listing.priceRange.displayText;
		if(displayText){
			li.update(this.trimToFit(displayText.capitalize(), 30));
			
			if(!listing.priceRange.startingPrice){
				var prices = listing.userDefinedPrices;
	
					var img = new Element('img', {'src':'/images/arrow_down.png'});
					li.onclick = function(){$('up_' + listing.listingId).show();}
					li.appendChild(img);
					li.addClassName('aPrice');
					li.onmouseover= function(){
						var msgBox = new Element('div');
						msgBox.addClassName('aPrice');
						var innerUl = new Element('ul');
						var innerLi = new Element('li');
						
						if(prices.length > 0){
							innerLi.update("("+prices.length+") users have indicated the price is around:");
							innerLi.appendChild(new Element('br'));
							var priceToDisplay = new Element('span');
							priceToDisplay.update(listing.userDefinedAdvertisedPriceForDisplay);
							innerLi.appendChild(priceToDisplay);
							innerLi.appendChild(new Element('br'));
							innerLi.appendChild(document.createTextNode("(Click to add if different)"))
						}
						else{
							innerLi.update('Know the price? Click to add it');
						}
						innerUl.appendChild(innerLi);
						msgBox.appendChild(innerUl);
						li.appendChild(msgBox);
						$('m-'+listing.listingId).hide();
						$('st-'+listing.listingId).hide();
						$('cbd-'+listing.listingId).hide();
					};
					li.onmouseout = function(){
						var toDel = li.select("div.aPrice");
						toDel.each(function(item) {
							item.remove();
						});
						$('m-'+listing.listingId).show();
						$('st-'+listing.listingId).show();
						$('cbd-'+listing.listingId).show();
					}
			}
		}
		return li;
	},

	renderMetaData : function(listing) {
		var metadata = listing.metaData;
		var defaultText = "n/a";
		var li = new Element('li', {'id':'m-'+listing.listingId});
		li.addClassName('metadata');
		var bdr = new Element('span');
		bdr.addClassName('bdr');
		var bath = new Element('span');
		bath.addClassName('bath');
		var car = new Element('span');
		car.addClassName('car');

		if (metadata) {
			bdr.update(metadata.bedRoomCount);
			car.update(metadata.carParkCount);
			bath.update(metadata.bathRoomCount);

		} else {
			bdr.update(defaultText);
			car.update(defaultText);
			bath.update(defaultText);
		}

		li.appendChild(bdr);
		li.appendChild(car);
		li.appendChild(bath);
		return li;
	},

	renderOptions : function(listing) {
		var div = new Element('div');
		div.addClassName('shortlist');
		var a = new Element('a', {'href': 'javascript:void(0);', 'id':'short_' + listing.listingId});
		a.addClassName('shortlist-item');
		a.update('shortlist');
		div.appendChild(a);

		var map = new Element('a',{'href': 'javascript:void(0);', 'id':'map_' + listing.listingId});
		map.addClassName('map')
		map.update('&#187;map');
		div.appendChild(map);

		div.appendChild(this.renderCommentLink(listing));
		div.appendChild(this.renderAddPrice(listing));
		div.appendChild(this.renderCalculator(listing));
//		div.appendChild(this.renderListedDate(listing));

		return div;
	},

	renderListedDate : function(listing) {
		var span = new Element('span');
		span.addClassName('ld');
		var date = new Date(listing.listedDate);
		span.appendChild(document.createTextNode(" " + date.getDate()+"/"+date.getMonth()+"/"+date.getFullYear()));
		return span;
	},
	
	renderCommentLink : function(listing){
		var comments = new Element('a', {'href': 'javascript:void(0);'});
		comments.addClassName('commentLink');
		comments.update("log book");
		comments.onclick = function(){$('c_' + listing.listingId).show();}
		return comments;
	},

	renderCalculator : function(listing) {
		var span = new Element('span');
		if (listing.listingType == 'SALE') {
			var a = new Element('a',{'href': 'javascript:void(0);'});
			a.addClassName('calc');
			a.update('finance');
			span.appendChild(a);

			a.onclick = function(){
				LoanCalculator.calculateLoan(listing.listingId,
						listing.priceRange.startingPrice);
			} 
		}
		return span;
	},
	
	renderAddPrice : function(listing) {
		var span = new Element('span');
		if (listing.listingType == 'SALE') {
			span.update("&nbsp;");
			var a = new Element('a',{'href': 'javascript:void(0);'});
			a.addClassName('addPriceLink');
			a.update('add price');
			span.appendChild(a);

			a.onclick = function(){$('up_' + listing.listingId).show();}
		}
		return span;
	},

	renderPlaceHolderReplacementPoint : function(listing) {
		var rphdiv = new Element('div');
		rphdiv.addClassName('rph');
		var div = new Element('div',{'id':'rph-' + listing.listingId});
		rphdiv.appendChild(div);
		return rphdiv;
	},

	trimToFit : function(textToTrim, lengthToTrim) {
		if (textToTrim.length >= lengthToTrim) {
			return textToTrim.substring(0, lengthToTrim) + "..";
		}
		return textToTrim;
	}

});

var Paginator = Class.create( {
	initialize : function(totalResults, currentPage, maxResults) {
		var totalPages = this.getTotalPages(totalResults, maxResults);
		this.renderPaginationLinksHtml(totalPages, currentPage);
		this.renderTotalPagesHtml(totalResults);
		this.renderPageOf(totalPages, currentPage);
		this.bindEvents(totalPages);
	},

	getTotalPages : function(totalResults, maxResults) {
		return (totalResults / maxResults).ceil();
	},

	renderTotalPagesHtml : function(totalResults) {
		var totalResultDiv = $('total-results');
		totalResultDiv.update('');
		totalResultDiv.appendChild(this.renderTotalPageCount(totalResults))
	},

	renderPaginationLinksHtml : function(totalPages, currentPage) {
		var links = this.createPaginationDOM(totalPages, currentPage);
		var paginationBottom = $('pagination-bottom');
		paginationBottom.update('');
		paginationBottom.appendChild(links);
	},

	renderPageOf : function(totalPages, currentPage) {
		var total = document.createTextNode(totalPages);
		var current = document.createTextNode(currentPage);
		var fromPage = $('from-page');
		var endPage = $('end-page');
		fromPage.update('');
		endPage.update('');
		fromPage.appendChild(current);
		endPage.appendChild(total);
	},

	createPaginationDOM : function(totalPages, currentPage) {
		var div = new Element('div', {'id':'pagination'});
		var ul = new Element('ul', {'id': 'pages'});
		for ( var i = 1; i <= totalPages; i++) {
			var li = new Element('li');
			if (currentPage != i) {
				var a = new Element('a',{'href': 'javascript:void(0);','id': 'page_' + i});
				a.addClassName('pageLink');
				a.update("[" + i + "]");
				li.appendChild(a);
			} else {
				li.update("[" + i + "]");
			}
			ul.appendChild(li);
		}
		div.appendChild(ul);
		return div;
	},

	renderTotalPageCount : function(totalResults) {
		var span = new Element('span');
		span.update(totalResults);
		return span;
	},

	bindEvents : function(totalPages) {
		var paginationLinks = $$('a.pageLink');
		for ( var i = 0; i < totalPages - 1; i++) {
			Event.observe(paginationLinks[i], 'click', this.attachEvent
					.bindAsEventListener(this));
		}
	},

	attachEvent : function(event) {
		var element = Event.element(event);
		var page = element.id.replace('page_', '');
		$('currentPage').setValue(page);
		ListingLookup.Find(page);
	}
});

var DateUtil = {};

DateUtil.getNextSaturday = function(){
	var date = new Date();
	var dayOfWeek = date.getDay();
	var offset = 7-dayOfWeek;
	date.setDate(date.getDate()+offset-1);
	return date;
}

DateUtil.getNextSunday = function(){
	var date = new Date();
	var dayOfWeek = date.getDay();
	var offset = 7-dayOfWeek;
	date.setDate(date.getDate()+offset);
	return date;
}

var FilterUtil = {};

FilterUtil.updateInspectionAuctionText = function(inspectionOrAuction){
	var selection = $('inspectionAuctionDateRange');
	var sunday = DateUtil.getNextSunday();
	var saturday = DateUtil.getNextSaturday();
	var inspectionText ="";
	if(inspectionOrAuction == "INSPECTION"){
		inspectionText = "for inspection "+selection[selection.selectedIndex].innerHTML.toLowerCase();
	}else if(inspectionOrAuction == "AUCTION"){
		inspectionText = "for auction "+selection[selection.selectedIndex].innerHTML.toLowerCase();
	}
	if(selection.selectedIndex == 0){
		inspectionText = inspectionText+" (today - Sun "+sunday.getDate()+")";
	}
	
	$('inspectionTxt').update(inspectionText);
}

FilterUtil.toggleSearchByInspectionAuctionTime = function(show){
	var inspectionOrAuction = $F('displayInspectionOrAuction');
	if(inspectionOrAuction && inspectionOrAuction != ""){
		$('inspectionAuction').show();
		$('sortbyWrapper').hide();
		$('inspectionTxtAlt').hide();
		FilterUtil.updateInspectionAuctionText(inspectionOrAuction);
	}
//	if(show){
//		$('inspectionAuction').show();
//		$('sortbyWrapper').hide();
//		$('displayInspectionOrAuction').setValue('INSPECTION');
//		$('inspectionTxtAlt').hide();
//		FilterUtil.updateInspectionAuctionText('INSPECTION');
//		ListingLookup.SearchResultsCache = new Object;
//	}else{
	//	$('inspectionAuction').hide();
	//	$('sortbyWrapper').show();
	//	$('displayInspectionOrAuction').setValue('');
	//	$('inspectionTxt').update('');
	//	$('inspectionTxtAlt').show();
//	}
	//ListingLookup.Find(1);
	
	//MapService.destroy();
	TabUtils.ShowSearchResults();
}

FilterUtil.GetFormattedPrice = function(fromPrice, toPrice) {
	var from = Math.round(fromPrice);
	var to = Math.round(toPrice);
	var price = "";
	if (from != 0) {
		price = NumberUtils.convertToCurrency(from);
	}

	if (to != 3000000) {
		if (price == 0) {
			price += "0";
		}
		price = price + " - " + NumberUtils.convertToCurrency(to);
	} else {
		if (from != 0) {
			price += "+";
		}
	}

	if (price == "") {
		price = "None specified";
	}
	return price;
}

FilterUtil.GetFormattedValue = function(value) {
	return "(" + value + "+)";
}

FilterUtil.GetFormattedLandSize = function(value) {
	return "(" + value + "m<sup>2</sup>+)";
}

var Filters = Class
		.create( {
			initialize : function() {
				this.attachEventsHandlers();
				this.attachSliderEvents();
				this.attachPropertyTypeFilterEvents();
			},

			attachEventsHandlers : function() {
				Event.observe($('select-sortby'), 'change',
						this.applySortFilter.bindAsEventListener(this));
			},

			applySortFilter : function() {
				$('sortby').setValue($F('select-sortby'));
				this.clearSearchResultsCache();
				SearchOptions.saveAndUpdateResults();
			},
			
			clearSearchResultsCache : function() {
				ListingLookup.SearchResultsCache = new Object;
			},

			attachSliderEvents : function() {
				this.slider($('bedrooms-slider'), $('bedrooms-num'),
						$('bedrooms-replace'));
				this.slider($('bathrooms-slider'), $('bathrooms-num'),
						$('bathrooms-replace'));
				this.slider($('carparks-slider'), $('carparks-num'),
						$('carparks-replace'));
				this.landSizeSlider();
				this.priceRangeSlider();

			},

			slider : function(slider, formField, replacePoint) {
				var slider = slider, form_field = formField, replace_point = replacePoint;
				var sliderValue = ListingUtils.GetValue(form_field.value, 0);
				replace_point.update(FilterUtil.GetFormattedValue(sliderValue));
				new Control.Slider(slider.select('.handle'), slider, {
					range :$R(0, 5),
					sliderValue : [ sliderValue ],
					restricted :true,
					values : [ 0, 1, 2, 3, 4, 5 ],
					onSlide : function(value) {
						replace_point.update("(" + value + "+)");
					},
					onChange : function(value) {
						form_field.setValue(value);
						replace_point.update(FilterUtil
								.GetFormattedValue(value));
						ListingLookup.SearchResultsCache = new Object;
					}
				});
			},

			landSizeSlider : function() {
				var slider = $('landsize-slider'), form_field = $('landsize-num'), replace_point = $('landsize-replace');
				var sliderValue = ListingUtils.GetValue(form_field.value, 0);
				replace_point.update(FilterUtil
						.GetFormattedLandSize(sliderValue));

				new Control.Slider(slider.select('.handle'), slider, {
					range :$R(0, 2000),
					sliderValue : [ sliderValue ],
					restricted :true,
					values : [ 0, 200, 400, 600, 800, 1000, 1200, 1400, 1600,
							1800, 2000 ],
					onSlide : function(value) {
						replace_point.update(FilterUtil
								.GetFormattedLandSize(value));
					},
					onChange : function(value) {
						form_field.setValue(value);
						ListingLookup.SearchResultsCache = new Object;
					}
				});
			},

			priceRangeSlider : function() {
				var slider = $('price_slider'), price_from = $('price-from'), price_to = $('price-to'), price_range_replace = $('price-range-replace');
				var startPrice;
				var endPrice;
				var values;
				var range;
				var suffix = "";
				if ($F('listingTypeValue') == "RENT") {
					startPrice = ListingUtils.GetValue(price_from.value, 0);
					endPrice = ListingUtils.GetValue(price_to.value, 2000);
					values = [ 0, 100, 200, 300, 400, 500, 600, 700, 800, 900,
							1000, 1100, 1200, 1300, 1400, 1500, 1600, 1700,
							1800, 1900, 2000 ];
					range = $R(0, 2000);
					suffix = " pr/wk"
				} else {
					startPrice = ListingUtils.GetValue(price_from.value, 0);
					endPrice = ListingUtils.GetValue(price_to.value, 3000000);
					values = [ 0, 100000, 150000, 200000, 250000, 300000,
							350000, 400000, 450000, 500000, 550000, 600000,
							650000, 700000, 750000, 800000, 850000, 900000,
							950000, 1000000, 2000000, 3000000 ];
					range = $R(0, 3000000);
				}

				price_range_replace.update(FilterUtil.GetFormattedPrice(
						startPrice, endPrice)
						+ suffix);

				new Control.Slider(slider.select('.handle'), slider, {
					range :range,
					sliderValue : [ startPrice, endPrice ],
					restricted :true,
					values :values,
					onSlide : function(values) {
						price_range_replace.update(FilterUtil
								.GetFormattedPrice(values[0], values[1])
								+ suffix);
					},
					onChange : function(values) {
						price_from.setValue(Math.round(values[0]));
						price_to.setValue(Math.round(values[1]));
						ListingLookup.SearchResultsCache = new Object;
					}
				});
			},

			attachPropertyTypeFilterEvents : function() {

				$('house').onclick = function() {
					ListingLookup.SearchResultsCache = new Object;
				};
				$('townhouse').onclick = function() {
					ListingLookup.SearchResultsCache = new Object;
				};
				$('unit').onclick = function() {
					ListingLookup.SearchResultsCache = new Object;
				};
				$('apartment').onclick = function() {
					ListingLookup.SearchResultsCache = new Object;
				};
				$('land').onclick = function() {
					ListingLookup.SearchResultsCache = new Object;
				};
				
			},

			attachMiscellaneousFilterEvents : function() {
				$('inspection').onclick = function() {
					ListingLookup.SearchResultsCache = new Object;
				};
				
			}
		});

var SearchOptions = {};

SearchOptions.saveAndUpdateResults = function(){
	$('drawMapOnDemand').setValue('true');
	ListingLookup.Find(1);
	SearchOptions.saveSearchOptionsOnResultsPage();
}

SearchOptions.saveSearchOptionsOnResultsPage = function() {

	if ($F('listingTypeValue') == "SALE") {
		var priceFromBuy = $F('price-from');
		var priceToBuy = $F('price-to');
		var priceFromRent = $F('price-from-rent');
		var priceToRent = $F('price-to-rent');
	} else {
		var priceFromRent = $F('price-from');
		var priceToRent = $F('price-to');
		var priceFromBuy = $F('price-from-buy');
		var priceToBuy = $F('price-to-buy');
	}

	var sortBy = $F('select-sortby');
	var landSize = $F('landsize-num');
	var bedRoomCount = $F('bedrooms-num');
	var carParkCount = $F('carparks-num');
	var bathRoomCount = $F('bathrooms-num');
	var houses = $('house').checked;
	var townhouses = $('townhouse').checked;
	var units = $('unit').checked;
	var apartments = $('apartment').checked;
	var land = $('land').checked;

	new Ajax.Updater('rvrp', '/ajax/user/search-options/save', {
		parameters : {
			"priceFromBuy" :priceFromBuy,
			"priceToBuy" :priceToBuy,
			"priceFromRent" :priceFromRent,
			"priceToRent" :priceToRent,
			"sortBy" :sortBy,
			"landSize" :landSize,
			"bedRoomCount" :bedRoomCount,
			"carParkCount" :carParkCount,
			"bathRoomCount" :bathRoomCount,
			"houses" :houses,
			"townhouses" :townhouses,
			"units" :units,
			"apartments" :apartments,
			"land" :land
		},
		asynchronous :true,
		evalScripts :true,
		method :'post',
		onLoading : function() {
			PageStatusManager.registerStatus(" ...saving search options");
		},
		onComplete : function(response) {
			PageStatusManager.deregisterStatus();
		}
	});
}

var shortlistCache = new Array();
var ShortlistManager = Class
		.create( {
			initialize : function() {
				this.attachEventHandlersForResultsTab();
				this.highlightSelectedShortList();
				this.attachEventHandlersForShortlistTab();
				this.attachPrintEvent();
			},

			attachEventHandlersForResultsTab : function() {
				var shortlist = $$('a.shortlist-item');
				var count = shortlist.length;
				for ( var i = 0; i < count; i++) {
					Event.observe(shortlist[i], 'click',
							this.addPropertyToShortlist
									.bindAsEventListener(this));
				}

			},

			attachEventHandlersForShortlistTab : function() {
				if ($F('activeTab') == 'shortlist') {
					var shortlist = $$('a.shortlist-item-active');
					var count = shortlist.length;
					for ( var i = 0; i < count; i++) {
						Event.observe(shortlist[i], 'click',
								this.removeFromShortlistTab
										.bindAsEventListener(this));
					}
				}
			},

			addPropertyToShortlist : function(event) {
				var searchResults = ListingLookup.SearchResultsCache[$F('currentPage')];
				var element = Event.element(event);
				var listing_id = element.id.replace('short_', '');
				var listings = searchResults.listings;
				var count = listings.length;
				for ( var i = 0; i < count; i++) {
					var listing = listings[i];
					if (listing.listingId == listing_id) {
						this.addRemove(listing);
						break;
					}
				}
				$('shortlist-count').update(shortlistCache.length)
			},

			addRemove : function(listing) {
				var listingId = listing.listingId;
				var shortlistItem = $('short_' + listingId);
				if (shortlistItem) {
					if (shortlistItem.hasClassName('shortlist-item-active')) {
						shortlistItem.addClassName('shortlist-item');
						shortlistItem.removeClassName('shortlist-item-active');
						this.removeShortlistFromCache(listingId);
						SessionManager.removeShortlist(listingId);
					} else {
						shortlistItem.removeClassName('shortlist-item');
						shortlistItem.addClassName('shortlist-item-active');
						shortlistCache[shortlistCache.length] = listing;
						SessionManager.storeShortlist(listing);
					}
				}
			},

			removeShortlistFromCache : function(listingId) {

				var tempShortList = new Array();
				var count = shortlistCache.length;
				for ( var i = 0; i < count; i++) {
					var shortlistItem = shortlistCache[i];
					if (listingId != shortlistItem.listingId) {
						tempShortList[tempShortList.length] = shortlistItem;
					}
				}
				shortlistCache = tempShortList;
			},

			removeFromShortlistTab : function(event) {
				var element = new Event.element(event);
				var listingId = element.id.replace('short_', '');
				SessionManager.removeShortlist(listingId);
				this.removeShortlistFromCache(listingId);
				new ListingsResultsRender(shortlistCache);
				new ShortlistManager();
				ListingUtils.DrawMapForShortlist();
			},

			highlightSelectedShortList : function() {
				var count = shortlistCache.length;
				for ( var i = 0; i < count; i++) {
					var shortlistItem = shortlistCache[i];
					var shortlist = $('short_' + shortlistItem.listingId);
					if (shortlist) {
						shortlist.removeClassName('shortlist-item');
						shortlist.addClassName('shortlist-item-active');
					}
				}
			},

			attachPrintEvent : function() {
				Event.observe($('print-shortlist'), 'click',
						this.printShortlist.bindAsEventListener(this));
			},

			printShortlist : function() {
				window.open("/ajax/user/short-list/print?listingIds="
						+ $F('shortlistPropertyIds'), "newwin",
						"toolbar=no,menubar=no,scrollbars=1");
			}

		});

var Init = Class.create( {
	initialize : function() {

		SessionManager.reloadShortlist();
		new Filters();
		Event.observe($('clear-shortlist'), 'click', this.resetShortlist
				.bindAsEventListener(this));
		new SearchResultsPage();

		this.monitorActivePage();
		ListingUtils.ResizeWindow();
		Event.observe(window, 'resize', ListingUtils.ResizeWindow
				.bindAsEventListener(this));
	},

	monitorActivePage : function() {
		new PeriodicalExecuter( function(pe) {
			var href = window.location.href;
			if (href != _activePage) {
				var showMapLnk = $('showMapT');
				if(showMapLnk){
					showMapLnk.hide();
				}
				_prevPage = _activePage;
				_activePage = href;
				if (href.indexOf("#shortlist") > 0) {
					// ensures that the cache is ready
					if(!_shortlistCacheReady){
						_activePage = "";
					}else{
						TabUtils.ShowShortlist();
					}
				} else if (href.indexOf("#?id=") > 0) {
					if (!_indicator) {
						ListingLookup.Find(1);
					}
					var listingId = ListingUtils.GetParam('id');
					var hrefTmp = window.location.href;
					var start = hrefTmp.indexOf('addr=') + 5;
					var listingAddress = hrefTmp.substring(start,
							hrefTmp.length);
					TabUtils.ActivateTab(listingId);
					if (listingId && listingAddress) {
						TabUtils.CreateTabById(listingId, listingAddress
								.replace(/(_)/g, ' '));
						ListingLookup.FindById(listingId);
					}
				}else if(href.indexOf("#profile=") > 0){
					showMapLnk.show();
					showMapLnk.onclick= function(){
						SuburbProfileUtils.goBack();
					}
					var suburbId= (window.location.hash.split("="))[1];
					if(suburbId){
						SuburbProfileUtils.showSuburbProfile(suburbId);
					}
				}
				else {
					FilterUtil.toggleSearchByInspectionAuctionTime(false);
				}
			}

		}, 0.5);
	},

	resetShortlist : function() {
		var count = shortlistCache.length;
		for ( var i = 0; i < count; i++) {
			var shortlistItem = shortlistCache[i];
			var short = $('short_' + shortlistItem.listingId);
			if (short) {
				short.removeClassName('shortlist-item-active');
				short.addClassName('shortlist-item');
			}
		}
		shortlistCache = new Array();
		$('shortlist-count').update('0');
		SessionManager.removeAllShortlist();
		new ListingsResultsRender(shortlistCache);
		ListingUtils.DrawMapForShortlist();
	}

});

var cookieManager = new CookieManager();
var SessionManager = {};
SessionManager.storeShortlist = function(shortlist) {

	var shortlistIds = $('shortlistPropertyIds');
	var currentShortlist = shortlistIds.value;
	var listingId = shortlist.listingId;
	currentShortlist = currentShortlist + listingId + ",";

	shortlistIds.setValue("" + currentShortlist.split(",").uniq().flatten());
	
	new Ajax.Updater('rvrp', '/ajax/user/short-list/add', {
		parameters : {
			listingId :listingId
		},
		asynchronous :true,
		evalScripts :true,
		method :'post'
	});
	SessionManager.updateCount();
}

SessionManager.removeShortlist = function(listingId) {
	var shortlistIds = $('shortlistPropertyIds');
	var currentShortlist = shortlistIds.value;
	if (currentShortlist) {

		var delimitedShortlist = currentShortlist.split(",");
		shortlistIds.setValue(delimitedShortlist.without(listingId));
		ShortlistUtil.removeShortListItem(listingId);
	}
	SessionManager.updateCount();
}

SessionManager.removeAllShortlist = function() {
	$('shortlistPropertyIds').setValue("");
	ShortlistUtil.clearAllShortList();
	SessionManager.updateCount();
}

var _shortlistCacheReady = false;
SessionManager.reloadShortlist = function() {

	var shortlistIndexes = $F('shortlistPropertyIds');

	if (shortlistIndexes) {
		var shortlistTokenized = shortlistIndexes.split(',');
		var count = shortlistTokenized.length;
		var shortlistIds = new Array();
		for ( var i = 0; i < count; i++) {
			var token = shortlistTokenized[i];
			if (token && token != "") {
				shortlistIds[shortlistIds.length] = token;
			}
		}
		if (shortlistIds.length > 0) {
			searchResults = ListingSearchServiceJS.searchByIds(shortlistIds,
					function(searchResults) {
						if (searchResults) {
							shortlistCache = searchResults.listings;
							_shortlistCacheReady = true;
						}
					});
		}
	}else{
		_shortlistCacheReady = true;
	}
	SessionManager.updateCount();
}

SessionManager.updateCount = function() {
	var shortlist = $F('shortlistPropertyIds');
	if (shortlist) {
		var count = (shortlist.split(",")).length;
		if (count) {
			$('shortlistCount').update(" (" + (count - 1) + ")");
		}
	} else {
		$('shortlistCount').update(" (0)");
	}
}

var ShortlistUtil = {};
ShortlistUtil.clearAllShortList = function() {
	new Ajax.Updater('rvrp', '/ajax/user/short-list/delete-all', {
		asynchronous :true,
		evalScripts :true,
		method :'post'
	});
}

ShortlistUtil.removeShortListItem = function(id) {
	new Ajax.Updater('rvrp', '/ajax/user/short-list/delete', {
		parameters : {
			listingId :id
		},
		asynchronous :true,
		evalScripts :true,
		method :'post'
	});
}

var ImageManager = Class.create( {
	initialize : function() {
		this.resizeMainImage();
		this.addThumbnailControlls();
	},

	resizeMainImage : function() {
		var mainImage = $('active-image');
		if (mainImage) {
			var height = mainImage.height - 400;
			var width = mainImage.width - 500;
			if (height > 0) {
				var marginTop = Math.round(height / 2) * -1;
				mainImage.style.marginTop = marginTop + "px";
			}
			if (width > 0) {
				var marginLeft = Math.round(width / 2) * -1;
				mainImage.style.marginLeft = marginLeft + "px";
			}
		}
	},

	addThumbnailControlls : function() {
		var thumbnails = $$('img.thumb-img');
		var count = thumbnails.length;
		for ( var i = 0; i < count; i++) {
			Event.observe(thumbnails[i], 'click', this.setMainImage
					.bindAsEventListener(this));
		}
	},

	setMainImage : function(event) {
		var element = Event.element(event);
		var mainImage = $('active-image');
		mainImage.src = element.src;
		mainImage.removeAttribute('width');
		mainImage.removeAttribute('height');
		mainImage.style.marginLeft = "0px";
		mainImage.style.marginTop = "0px";
		this.resizeMainImage();
	}

});

var SearchResultsPage = Class.create( {
	initialize : function() {
		if ($('results')) {
			this.initialiseStyles();
			this.attachAutoCompleteEventHandlerForQuickSearch();
		}
	},
	initialiseStyles : function() {
		if (!NiftyCheck())
			return;
		RoundedTop("div#search-results-tab", "#FFF", "#79BB16");
		RoundedTop("div#shortlist-tab", "#FFF", "#dc0101");
		RoundedBottom("div.results-bottom", "#FFF", "#BBD8FF");
	},

	attachAutoCompleteEventHandlerForQuickSearch : function() {
		new Ajax.Autocompleter("quick-search-autocomplete",
				"quick-autocomplete_choices", "/ajax/suburb/show", {
					method :"get",
					paramName :"suburbOrPostcode",
					minChars :2,
					indicator :'indicator1'
				});
	}
});

var SuburbProfileUtils = {};

SuburbProfileUtils.goBack = function() {
	
	if(_prevPage.indexOf("#shortlist") > 0){
		window.location.hash = "#shortlist";
	}else{
		window.location.hash = "#";
	}
	MapService.destroy();
}


SuburbProfileUtils.gotoToRecentlyViewdSuburb = function(form) {
	if (form.value) {
		window.location.href = "/" + form.value;
	}
}

SuburbProfileUtils.toggleUserSearchProfilePanel = function() {
	$('usp').toggle();
}

var LoanCalculator = {};
LoanCalculator.calculateInterestPrinciple = function(loanAmount, interestRate,
		loanTerm) {
	var interest = interestRate / 1200;
	var term = loanTerm * 12;
	return Math.round(loanAmount * interest
			/ (1 - (Math.pow(1 / (1 + interest), term))));
}

LoanCalculator.calculateInterestOnly = function(loanAmount, interestRate) {
	var interest = interestRate / 1200;
	return Math.round(loanAmount * interest);
}

LoanCalculator.calculate = function(form) {
	var loanAmount = form.loanAmount.value;
	var interestRate = form.interestRate.value;
	var loanTerm = form.loanTerm.value;
	if (loanAmount && interestRate && loanTerm) {
		form.principleInterest.value = LoanCalculator
				.calculateInterestPrinciple(loanAmount, interestRate, loanTerm);
		form.interestOnly.value = LoanCalculator.calculateInterestOnly(
				loanAmount, interestRate);
	}
	return false;
}

LoanCalculator.calculateLoan = function(id, loan) {
	var replacePoint = $('rph-' + id).down(".calculator")
	if (!replacePoint) {
		new Ajax.Updater('rph-' + id, '/ajax/tools/calculator', {
			parameters : {
				loanAmount :loan,
				interestRate :_DEFAULT_INTEREST_RATE,
				loanTerm :_DEFAULT_LOAN_TERM
			},
			asynchronous :true,
			evalScripts :true,
			method :'get',
			onLoading : function() {
				_indicator.show();
			},
			onComplete : function(response) {
				window.setTimeout( function() {
					_indicator.hide();
				}, 500);
			}
		});
		GoogleUtils.trackPage("calculator");
	} else {
		replacePoint.removeClassName("hide");
	}
}

var GoogleUtils = {};

GoogleUtils.isLiveSite = function() {
	if (window.location.hostname.indexOf("propertyboard.com") > 0) {
		return true;
	}
	return false;
}

GoogleUtils.trackPage = function(url) {
	if (GoogleUtils.isLiveSite()) {
		pageTracker._trackPageview(url);
	}
}

var WindowUtils = {};
WindowUtils.close = function(parentElement, element) {
	$(element).up('.' + parentElement).addClassName("hide");
}

//var SuburbProfileUtils = {};

SuburbProfileUtils.gotoToRecentlyViewdSuburb = function(form) {
	if (form.value) {
		window.location.href = "/" + form.value;
	}
}

SuburbProfileUtils.toggleSearchHistory = function(element) {
	
	EffectsUtil.toggle(element, 'recent');
	PageStatusManager.deregisterStatus();

	function toggleExpandeCollapse(event) {
		var element = Event.element(event);
		element.toggleClassName('collapse');
		element.next().toggleClassName('hide');
	}

	var collapse = $('recent').select('h4');
	if (!$('recent').hasClassName('hide')) {
		collapse.each( function(item) {
			Event.observe(item, 'click', toggleExpandeCollapse
					.bindAsEventListener(this));
		});
	} else {
		collapse.each( function(item) {
			item.stopObserving();
		});
	}

}

var UserSearchPreferenceUtils = {};

UserSearchPreferenceUtils.UpdateSearchField = function(element){
	var textfield = $('autocomplete');
	
	if(textfield){
		textfield.setValue($(element).title);
	}else{
		textfield = $('quick-search-autocomplete');
		textfield.setValue($(element).title);
	}
	Effect.Pulsate(textfield,  { pulses: 2, duration: 0.5 });
}

UserSearchPreferenceUtils.clearAllRecentlyViewed = function() {

	var suburb = $("recentlyViewedSuburbs")
	if (suburb && suburb.innerHTML != '--none--') {

		new Ajax.Updater('rvrp', '/ajax/user/recently-viewed-suburbs/delete-all', {

			asynchronous :true,
			evalScripts :true,
			method :'post',
			onLoading : function() {
				PageStatusManager.registerStatus(" ...saving preferences");
			},
			onComplete : function(response) {
				SuburbProfileUtils.toggleSearchHistory();
			}
		});
	}
}

UserSearchPreferenceUtils.clearAllFavouriteSuburbs = function() {
	var suburb = $("favouriteSuburbs")
	if (suburb && suburb.innerHTML != '--none--') {
		new Ajax.Updater('rvrp', '/ajax/user/favourite-suburbs/delete-all', {
			asynchronous :true,
			evalScripts :true,
			method :'post',
			onLoading : function() {
				PageStatusManager.registerStatus(" ...saving preferences");
			},
			onComplete : function(response) {
				SuburbProfileUtils.toggleSearchHistory();
			}
		});
	}
}

UserSearchPreferenceUtils.showAllFavouriteSuburbs = function(element){
	var suburb = $("favouriteSuburbs");
	if(suburb){
		var html = suburb.innerHTML;
		
		var rentUrl = new Element('a', {'title': 'go to rental favourites', href: '/rent/favourites'}).update("rent");
		var saleUrl = new Element('a', {'title': 'go to sale favourites', href: '/buy/favourites'}).update("buy");
		
		var parent =  $(element).up();
		parent.appendChild(saleUrl);
		parent.appendChild(document.createTextNode(" | "));
		parent.appendChild(rentUrl);
		element.replace("Show all -> ");
	}
}

UserSearchPreferenceUtils.showAllRecentlyViewedSuburbs = function(element){
	var suburb = $("recentlyViewedSuburbs");
	if(suburb){
		var html = suburb.innerHTML;
		
		var rentUrl = new Element('a', {'title': 'go to rental recently viewed', href: '/rent/recently_viewed'}).update("rent");
		var saleUrl = new Element('a', {'title': 'go to sale recently viewed', href: '/buy/recently_viewed'}).update("buy");
		
		var parent = $(element).up();
		parent.appendChild(saleUrl);
		parent.appendChild(document.createTextNode(" | "));
		parent.appendChild(rentUrl);
		element.replace("Show all -> ");
	}
}

UserSearchPreferenceUtils.addToFavouriteSuburb = function(id) {
	if (id) {
		new Ajax.Updater('rvrp', '/ajax/user/favourite-suburbs/add',
		{
			parameters : {
				suburbId :id
			},
			asynchronous :true,
			evalScripts :true,
			method :'post',
			onLoading : function() {
				PageStatusManager
						.registerStatus(" ...saving preferences");
			},
			onComplete : function(response) {
				SuburbProfileUtils.toggleSearchHistory();
			}
		});
	}
}

UserSearchPreferenceUtils.deleteFavouriteSuburb = function(id) {
	if (id) {
		new Ajax.Updater('rvrp', '/ajax/user/favourite-suburbs/delete', {
			parameters : {
				suburbId :id
			},
			asynchronous :true,
			evalScripts :true,
			method :'post',
			onLoading : function() {
				PageStatusManager.registerStatus(" ...saving preferences");
			},
			onComplete : function(response) {
				SuburbProfileUtils.toggleSearchHistory();
			}
		});
	}
}

UserSearchPreferenceUtils.Login = function(){
	var email = $F('lemail');
	var pwd = $F('lpassword');
	
	new Ajax.Request('/ajax/user/login', {
		parameters : {
			emailAddress : email,
			password : pwd
		},
		asynchronous :true,
		evalScripts :true,
		method :'post',
		onLoading : function() {
			PageStatusManager.registerStatus(" ...logging in");
		},
		onComplete : function(response) {
			var responseTxt = response.responseText;
			if(responseTxt == "ok"){
				setTimeout( function() {
					window.location.reload();
				}, 0);
			}else{
				setTimeout( function() {
					PageStatusManager.deregisterStatus();
					$('loginBox').update(responseTxt);
					UserSearchPreferenceUtils.LoginBoxEventHandlers();
				}, 0.5);
			}
		}
	});	
}

UserSearchPreferenceUtils.SendForgotPassword = function(){
	var email = $F('femail');
	new Ajax.Updater('loginBox', '/ajax/user/forgot-password', {
		parameters : {
			emailAddress : email
		},
		asynchronous :true,
		evalScripts :true,
		method :'post',
		onLoading : function() {
			PageStatusManager.registerStatus(" ...sending password");
		},
		onComplete : function(response) {
			PageStatusManager.deregisterStatus();
			UserSearchPreferenceUtils.LoginBoxEventHandlers();
		}
	});	
}

UserSearchPreferenceUtils.Register = function(){
	var screenName = $F('rscreenname');
	var email = $F('remail');
	var pwd = $F('rpassword');
	var cPwd = $F('rcpassword');
	new Ajax.Request('/ajax/user/create', {
		parameters : {
			screenName : screenName,
			emailAddress : email,
			password : pwd,
			confirmPassword : cPwd
		},
		asynchronous :true,
		evalScripts :true,
		method :'post',
		onLoading : function() {
			PageStatusManager.registerStatus(" ...creating account");
		},
		onComplete : function(response) {
			var responseTxt = response.responseText;
			if(responseTxt == "ok"){
				setTimeout( function() {
					window.location.reload();
				}, 0);
			}else{
				
				setTimeout( function() {
					$('loginBox').update(responseTxt);
					PageStatusManager.deregisterStatus();
					UserSearchPreferenceUtils.LoginBoxEventHandlers();
				}, 0.5);
			}
		}
	});	
}


UserSearchPreferenceUtils.Logout = function(){
	new Ajax.Request('/ajax/user/logout', {
		asynchronous :true,
		evalScripts :true,
		method :'post',
		onLoading : function() {
			PageStatusManager.registerStatus(" ...logging out");
		},
		onComplete : function(response) {		
			var responseTxt = response.responseText;
			if(responseTxt == "ok"){
				setTimeout( function() {
					window.location.reload();
				}, 0);
			}
		}
	});	
}

UserSearchPreferenceUtils.LoginBoxEventHandlers = function(){
	function highlight(element){
		element.onmouseover= function(){$(this).addClassName('highlight')};
		element.onmouseout= function(){$(this).removeClassName('highlight')};
	}
	
	function onSubmit(inputArray, callBackFunction){
		inputArray.each( function(input) {
			input.onkeyup=function(event){
				//To make it work for IE 6
				if(!event){
					event = window.event;
				}
				
				if(event.keyCode==13){
					callBackFunction();
				}
			}
		});
	}
	
	onSubmit($$("input.rsubmit"), UserSearchPreferenceUtils.Register);
	onSubmit($$("input.lsubmit"), UserSearchPreferenceUtils.Login);
	onSubmit($$("input.fsubmit"), UserSearchPreferenceUtils.SendForgotPassword);
	
	highlight($('registerBox'));
	highlight($('authBox'));
	highlight($('forgotPasswordBox'));
}

UserSearchPreferenceUtils.ShowLoginBox = function(){
	var msg = $('sysMsg');
	if(msg){
		msg.update("");
	}
	UserSearchPreferenceUtils.LoginBoxEventHandlers();
	$('loginBox').appear();
	var jtop = $('jTop');
	if(jtop){
		jtop.focus();
	}
}

UserSearchPreferenceUtils.CloseLoginBox = function(){
	$('loginBox').fade();
}

var PageStatusManager = {};

PageStatusManager.registerStatus = function(statusText) {
	$("statusText").update(statusText);
	$("indicator1").show();
}

PageStatusManager.deregisterStatus = function() {
	var indicator = $("indicator1");
	indicator.hide();
	$("statusText").update(" ...loading");
}

SuburbProfileUtils.showSuburbProfile = function(suburbId){
	if (suburbId) {
		MapService.saveCurrentState();
		new Ajax.Updater('google-map-canvas', '/ajax/suburb/profile/show', {
			parameters : {
				suburbId :suburbId
			},
			asynchronous :true,
			evalScripts :true,
			method :'post',
			onLoading : function() {
				PageStatusManager.registerStatus(" ...loading suburb profile");
			},
			onComplete : function(response) {
				PageStatusManager.deregisterStatus();
			}
		});
	}
}

SuburbProfileUtils.addComment = function(element){
	var suburbId = $(element).id;
	var comment = $F('commentContent').truncate(1500);
	
	if (suburbId && comment) {
		new Ajax.Request('/ajax/suburb/profile/comment/add', {
			parameters : {
				suburbId :suburbId,
				comment :comment
			},
			asynchronous :true,
			evalScripts :true,
			method :'post',
			onLoading : function() {
				PageStatusManager.registerStatus(" ...adding comment");
			},
			onComplete : function(response) {
				if(response.getHeader("AUTH") == "false"){
					$('loginBox').update(response.responseText);
					UserSearchPreferenceUtils.ShowLoginBox();
				}else{
					$('google-map-canvas').update(response.responseText);
				}
				PageStatusManager.deregisterStatus();
			}
		});
	}	
}

SuburbProfileUtils.toggleProfileList = function(element){
	EffectsUtil.toggle(element, 'suburbProfilesList');
}

var EffectsUtil = {};

EffectsUtil.toggle = function(onclickElement, effectElement){
	var el = $(onclickElement);
	if(el){
		el.toggleClassName('show');
		if(!el.hasClassName('show')){
			$(effectElement).appear();
		}else{
			$(effectElement).fade();
		}
	}else{
		$(effectElement).appear();
	}
}

var PropertyUtils ={}

PropertyUtils.closeAmenitiesWindow = function(element){
	var windowsBox = $(element);
	windowsBox.up().up().up().hide();
}

PropertyUtils.showNearestAmenities = function(replacePoint, latitude, longitude, state, propertyDetailsPage){
	if (replacePoint && latitude && longitude && state) {
		new Ajax.Updater(replacePoint, '/ajax/listing/nearest-amenities/show', {
			parameters : {
				latitude :latitude,
				longitude :longitude,
				state: state,
				propertyDetailsPage : propertyDetailsPage
			},
			asynchronous :true,
			evalScripts :true,
			method :'post',
			onCreate : function() {
				PageStatusManager.registerStatus(" ...caluclating nearest amenities");
			},
			onSuccess : function(response) {
				$(replacePoint).show();
				PageStatusManager.deregisterStatus();
			}, 
			onComplete : function(response){
				var ammenities = $$("#"+replacePoint+" li.amenityName");
				
				ammenities.each( function(amenity) {
					amenity.onclick = function(){
						var amenityType = amenity.getAttribute("amenityType");
						var icon = "/images/"
						if(amenityType == "ss"){
							icon += "secondary.png";
						}else if(amenityType == "ps"){
							icon += "primary.png";
						}
						else if(amenityType == "k"){
							icon += "kindy.png";
						}else if(amenityType == "s"){
							icon += "superm.png";
						}
						var lat = amenity.getAttribute("lat");
						var lng = amenity.getAttribute("lng");
						if(propertyDetailsPage){
							var basicMap = ListingLookup.basicMap;
							MapService.addCustomMarkerToMap(basicMap.map, new CustomMarker(amenity.getAttribute("name"),icon, lat, lng))
							MapService.calcRouteWith(basicMap.directionsDisplay, basicMap.directionsService, basicMap.centerLatLng.lat(),basicMap.centerLatLng.lng(), lat, lng);
						}else{
							MapService.addCustomMarker(new CustomMarker(amenity.getAttribute("name"),icon, lat, lng));
							MapService.calcRoute(latitude,longitude, lat, lng);
						}
					}
				});
				
			}
		});
	}	
}

PropertyUtils.showPropertyPassHistory = function(listingId){
	new Ajax.Updater('pastHistoryRP', '/ajax/listing/history/show/'+listingId, {
		asynchronous :true,
		evalScripts :true,
		method :'post',
		onCreate : function() {
			PageStatusManager.registerStatus(" ...loading historical data");
		},
		onSuccess : function(response) {
			$(replacePoint).show();
			PageStatusManager.deregisterStatus();
		}
	});
}

PropertyUtils.addComment = function(listingId){
	var commentBox = $('comment_'+listingId);
	var comment = commentBox.value.truncate(250);
	
	var visibility = $('cvisib_'+listingId);
	var visibStatus = 'PUBLIC';
	if(visibility.checked == true){
		visibStatus = 'PRIVATE';
	}
	if (listingId && comment) {
		new Ajax.Request('/ajax/listing/comments/add', {
			parameters : {
			listingId :listingId,
				comment :comment, 
				visibility: visibStatus
			},
			asynchronous :true,
			evalScripts :true,
			method :'post',
			onLoading : function() {
				PageStatusManager.registerStatus(" ...saving comment");
			},
			onComplete : function(response) {
				if(response.responseText != "ok"){
					$('loginBox').update(response.responseText);
					UserSearchPreferenceUtils.ShowLoginBox();
				}else{
					var date = new Date();
					var li = new Element("li");
					var pre = new Element("pre")
					pre.appendChild(document.createTextNode("> "+comment));
					li.appendChild(pre);
					var dateCreated = new Element('div')
					dateCreated.addClassName('date');
					li.appendChild(dateCreated.update("on "+date.toDateString() + " " +date.toLocaleTimeString()));
					var commentList = $('cIndex_'+listingId);
					if((commentList.childElements()[0]).hasClassName('remove')){
						(commentList.childElements()[0]).remove();
					}
					commentList.insert({top:li});
					commentBox.setValue("");
					
					if(!$('results-content').visible()){
						PropertyUtils.showComments(listingId);
					}
				}
				PageStatusManager.deregisterStatus();
			}
		});
	}	
}

PropertyUtils.showComments = function(listingId){
	new Ajax.Updater("commentsRP", '/ajax/listing/comments/show', {
		parameters : {
			listingId :listingId
		},
		asynchronous :true,
		evalScripts :true,
		method :'post',
		onCreate : function() {
		},
		onSuccess : function(response) {
		}
	});
}

PropertyUtils.addPrice = function(listingId, price, priceType){
	if(isNaN(price)){
		alert(price +" is not a number");
	}
	else if(listingId && price && priceType){
		new Ajax.Request('/ajax/listing/price/add', {
			parameters : {
				listingId :listingId,
				price : price,
				priceType : priceType
			},
			asynchronous :true,
			evalScripts :true,
			method :'post',
			onComplete : function(response) {
				if(response.responseText != "ok"){
					$('loginBox').update(response.responseText);
					UserSearchPreferenceUtils.ShowLoginBox();
				}else{
					MessageService.displayDelayedMessage("The price will be updated shortly. Thank you for participating.");
				}
			},
			onSuccess : function(response) {
			}
		});
	}
}

var MessageService ={}
MessageService.displayDelayedMessage = function(message){
	var sysMsg = $("globalSysMsg");
	sysMsg.update(message);
	sysMsg.style.top=document.viewport.getScrollOffsets()[1]+"px";
	sysMsg.show();
	sysMsg.fade({duration: 5.0});
}


