//INITIALISATION FUNCTIONS

var year = 2009;
var map = null;
var pointsArray = new Array();
var pushPinsDetailArray = new Array();
var results;

results = $.cookie('results');
//alert(results);

//load preloader image and then hide it when page is ready to render       
$('#loading').show();

$(document).ready(
            function() {
            	$('#loading').hide(); //hide loading div when page is ready for display
            }
        );

$(function() {

	//Snapshot Form remove values for dropdowns above postcode search
	$("#snapshotFormPostcode").change(function() {
		$('#snapshotFormSuburb').val('');
		document.getElementById('SuburbSuggestionsResults').style.display = 'none';
	});

	$("#snapshotFormSuburb").change(function() {
		$('#snapshotFormPostcode').val('');
	});


	$("#snapshotSuburbSuggestions").change(function() {
		GetSnapShotResultsBySuburbOrPostcode(0);
		document.getElementById('SuburbSuggestionsResults').style.display = 'none';
	});


	//Hotspot Form auto select regions 
	$("select#hotspotFormState").change(function() {
		PopulateHotspotFormRegionDropdown();
		results = 0;
	});

	//Hotspot Form auto select regions 
	$("select#rentalFormState").change(function() {
		PopulateRentalFormRegionDropdown();
		results = 0;
	});

	//Hotspot Form add selected region to cookie
	$("select#rentalFormRegion").change(function() {

		$.cookie('rentalFormRegion', $("select#rentalFormRegion").val(), { path: '/', expires: 1 });

	});
});

$(document).ready(


		function() {


			//populate sliders either from initial values or cookied values
			var prepopHotspotFormGrowthMin = CookieCheck('hotspotFormGrowthMin', '-599');
			var prepopHotspotFormGrowthMax = CookieCheck('hotspotFormGrowthMax', '600');

			$('#hotspotFormGrowthSlider').slider({ range: true,
				min: -599,
				max: 600,
				step: 1,
				values: [prepopHotspotFormGrowthMin, prepopHotspotFormGrowthMax],
				slide: function(event, ui) {
					$("#amountGrowth").html(ui.values[0] + ' % to ' + ui.values[1] + '%');
				}
			});

			$("#amountGrowth").html($("#hotspotFormGrowthSlider").slider("values", 0) + '% to ' + $("#hotspotFormGrowthSlider").slider("values", 1) + '%');

			var prepopHotspotFormAverageDaysMarketMin = CookieCheck('hotspotFormAverageDaysMarketMin', '0');
			var prepopHotspotFormAverageDaysMarketMax = CookieCheck('hotspotFormAverageDaysMarketMax', '365');

			$('#hotspotFormAverageDaysMarketSlider').slider({ range: true,
				min: 0,
				max: 365,
				step: 2,
				values: [prepopHotspotFormAverageDaysMarketMin, prepopHotspotFormAverageDaysMarketMax],
				slide: function(event, ui) {
					$("#amountAverageDaysMarket").html(ui.values[0] + ' days - ' + ui.values[1] + ' days');
				}
			});

			$("#amountAverageDaysMarket").html($("#hotspotFormAverageDaysMarketSlider").slider("values", 0) + ' days - ' + $("#hotspotFormAverageDaysMarketSlider").slider("values", 1) + ' days');

			$('#hotspotFormAverageDaysMarketSlider').slider('disable');

			var prepopHotspotFormDiscountMin = CookieCheck('hotspotFormDiscountMin', '0');
			var prepopHotspotFormDiscountMax = CookieCheck('hotspotFormDiscountMax', '50');

			$('#hotspotFormDiscountSlider').slider({ range: true,
				min: 0,
				max: 50,
				step: 2,
				values: [prepopHotspotFormDiscountMin, prepopHotspotFormDiscountMax],
				slide: function(event, ui) {
					$("#amountDiscount").html(ui.values[0] + '% - ' + ui.values[1] + '%');
				}
			});

			$("#amountDiscount").html($("#hotspotFormDiscountSlider").slider("values", 0) + '% - ' + $("#hotspotFormDiscountSlider").slider("values", 1) + '%');

			$('#hotspotFormDiscountSlider').slider('disable');


			var prepopRentalYieldMin = CookieCheck('rentalRentalYieldMin', '0');
			var prepopRentalYieldMax = CookieCheck('rentalRentalYieldMax', '300');

			$('#rentalYieldSlider').slider({ range: true,
				min: 0,
				max: 300,
				step: 2,
				values: [prepopRentalYieldMin, prepopRentalYieldMax],
				slide: function(event, ui) {
					$("#amount").html(ui.values[0] + ' % - ' + ui.values[1] + '%');

				}

			});

			$("#amount").html($("#rentalYieldSlider").slider("values", 0) + '% - ' + $("#rentalYieldSlider").slider("values", 1) + '%');

			$("#rentalFormBOTH").attr("checked", "checked");


			RenderForm();



		}


	);


//check for cookie and set a default if not valid
function CookieCheck(cookieName, defaultValue) {
	var cookieValue;
	if ($.cookie(cookieName) && (results == 1)) {
		cookieValue = $.cookie(cookieName)
		//alert( cookieName + $.cookie(cookieName));

	}
	else {
		cookieValue = defaultValue;
	}
	return cookieValue;
}

//Return suburb name matches for snapshot search

function PopulateSnapshotFormSuburbSuggestionSelect() {
	$("#snapshotSuburbSuggestions").removeOption(/./);
	$('.snapshot_rateyourplace').html("");

	var suburbName = $('#snapshotFormSuburb').val() + '%';
	$.getJSON(getBaseDataUrl() + "/Services/Service.axd?ServiceName=RealEstate&ServiceAction=GetSuburbsBySuburbName&suburbName=" + suburbName + "&AttributeStyle=true&ServiceFormat=JSON&callback=?", function(data) {

		if (data.DataList == null) {
			document.getElementById('snapshotFormSuburbError').innerHTML = "There are no suburbs matching your suburb name";
			document.getElementById('snapshotFormSuburbError').style.display = 'block';
			ResetMap();
		}
		if (data && data.DataList && data.DataList.Data) {

			var list = data.DataList.Data;
			var options = "";

			if (list.length) {//is array returning more than one suburb
				document.getElementById('SuburbSuggestionsResults').style.display = 'block';
				for (var i = 0; i < list.length; i++) {

					options = options + "<option value=\"" + list[i].SuburbId + "\">" + list[i].SuburbName + ', ' + list[i].State + "</option>";
					$("#snapshotSuburbSuggestions").html(options);
				}
			}
			else {//single object then call map results directly
				GetSnapShotResultsBySuburbOrPostcode(list.SuburbId);
			}
		}

	});
}

function PopulateHotspotFormRegionDropdown() {

	var stateID = $('#hotspotFormState').val();

	$.getJSON(getBaseDataUrl() + "/Services/Service.axd?ServiceName=RealEstate&ServiceAction=GetRegionsbyStateID&stateid=" + stateID + "&year=" + year + "&AttributeStyle=true&ServiceFormat=JSON&callback=?", function(data) {

		if (data && data.DataList && data.DataList.Data) {
			var list = data.DataList.Data;

			if (list.length) {//is array
				var options = "<option value=\"" + 0 + "\">Select a region</option>";
				for (var i = 0; i < list.length; i++) {
					options = options + "<option value=\"" + list[i].RegionCode + "\">" + list[i].RegionName + "</option>";
					$("select#hotspotFormRegion").html(options);
				}
			}
			else {//single object

				options = options + "<option value=\"" + list.RegionCode + "\">" + list.RegionName + "</option>";
				$("select#hotspotFormRegion").html(options);

			}

			//search map with prepopulation only if returning from Results screen
			if (results == 1) {
				$("#hotspotForm" + $.cookie('hotspotPropertyCategorisation')).attr("checked", "checked");
				//get cookie value
				//dodgey hack for IE6 which returns an error when the region is populated, so timeout needs to be set to give it time to think
				setTimeout("SetHotspotRegion();", 1000);
			}
		}

	});

}

function SetHotspotRegion() {
	$('select#hotspotFormRegion').val($.cookie('hotspotFormRegion'));
	GetHotSpotResults();
	//stop cookies prepopulating accross page
	$.cookie('results', '0', { path: '/', expires: 1 });

}

function SetRentalRegion() {
	$('select#rentalFormRegion').val($.cookie('rentalFormRegion'));
	GetRentalResults();
	//stop cookies prepopulating accross page
	$.cookie('results', '0', { path: '/', expires: 1 });

}

function PopulateRentalFormRegionDropdown() {
	var stateID = $('#rentalFormState').val();

	$.getJSON(getBaseDataUrl() + "/Services/Service.axd?ServiceName=RealEstate&ServiceAction=GetRegionsbyStateID&stateid=" + stateID + "&year=" + year + "&AttributeStyle=true&ServiceFormat=JSON&callback=?", function(data) {

		if (data && data.DataList && data.DataList.Data) {
			var list = data.DataList.Data;

			if (list.length) {//is array
				var options = "<option value=\"" + 0 + "\">All regions</option>";
				for (var i = 0; i < list.length; i++) {
					options = options + "<option value=\"" + list[i].RegionCode + "\">" + list[i].RegionName + "</option>";
					$("select#rentalFormRegion").html(options);
				}
			}
			else {//single object

				options = options + "<option value=\"" + list.RegionCode + "\">" + list.RegionName + "</option>";
				$("select#rentalFormRegion").html(options);

			}

			//perform setting of values using cookie and search map only if returning from Results screen
			if (results == 1) {
				$("#rentalForm" + $.cookie('rentalPropertyCategorisation')).attr("checked", "checked");
				setTimeout("SetRentalRegion();", 1000);
				$.cookie('results', '0', { path: '/', expires: 1 });
			}

		}
	});

}

//stores form values in a cookie and returns form values 

function Remember(selector, selectorHandleType) {
	$(selector).each(
            function() {
            	//if this item has been cookied, restore it
            	var name = $(this).attr(selectorHandleType);
            	if ($.cookie(name)) {
            		$(this).val($.cookie(name));
            	}
            	//assign a change function to the item to cookie it
            	$(this).change(
                    function() {
                    	$.cookie(name, $(this).val(), { path: '/', expires: 1 });
                    }
                );
            }
        );
}

//returns the base url for the data site that is on the same domain as the calling page
function getBaseDataUrl() {
	var base = window.location.hostname;
	var firstPart = base.substring(0, base.indexOf("."));
	var secondPart = base.substring(firstPart.length + 1, base.indexOf(".", firstPart.length + 1));
	var host = "";
	if (secondPart != "ninemsn") {
		host = secondPart + ".";
	}

	return "http://data." + host + "ninemsn.com.au";

}

// Parse the current page's querystring
function GetQueryString(ji) {
	hu = window.location.search.substring(1);
	gy = hu.split("&");
	for (i = 0; i < gy.length; i++) {
		ft = gy[i].split("=");
		if (ft[0] == ji) {
			return ft[1];
		}
	}
}

function RenderForm() {
	//if search criteria is specified then the values are placed back in the initial search page when user returns to it after navigating to the result page. Replots results in Map

	var formToShow, formType, state, region, suburb, postcode

	formToShow = $.cookie('form');
	formType = GetQueryString("formType");

	//show results if forced to
	if (formType == "results") {
		var suburbID;

		suburbID = GetQueryString("suburbID");

		document.getElementById('snapshotForm').style.display = 'none';
		document.getElementById('hotSpotForm').style.display = 'none';
		document.getElementById('rentalForm').style.display = 'none';
		document.getElementById('Results').style.display = 'block';
		document.getElementById('Results_Demographic').style.display = 'block';
		document.getElementById('links').style.display = 'block';
		document.getElementById('resultBackLink').style.display = 'block';
		//hack
		document.getElementById('main').style.height = '2600';
		setConHgt();

		GetResults(suburbID);

		//render correct tab corresponding to the form the user used to arrive at results page 
		switch (formToShow) {
			case 'snapshot':
				ChangeHeader('snapshotForm', 'hotSpotForm', 'rentalForm');
				break;
			case 'hotspot':
				ChangeHeader('hotSpotForm', 'snapshotForm', 'rentalForm');
				break;
			case 'rental':
				ChangeHeader('rentalForm', 'snapshotForm', 'hotSpotForm');
				break;
			default:
				ChangeHeader('snapshotForm', 'hotSpotForm', 'rentalForm');
				break;

		}

	}
	//if not results page then render the correct form on return from results page
	else if ((formToShow != 'undefined')) {

		switch (formToShow) {
			case 'snapshotpostcode':
				ChangeForm('snapshotForm', 'hotSpotForm', 'rentalForm', 0);

				if (results == 1) {
					//call cookies for prepopulating if coming back to this after results page is shown                  
					Remember('[id=snapshotFormPostcode]', 'id');
					GetSnapShotResultsBySuburbOrPostcode(0);
					$.cookie('results', '0', { path: '/', expires: 1 });
				}
				break;

			case 'snapshotdropdown':
				ChangeForm('snapshotForm', 'hotSpotForm', 'rentalForm', 0);


				//call cookies for prepopulating if coming back to this after results page is shown                  
				if (results == 1) {
					GetSnapShotResultsBySuburbOrPostcode(0);
					$.cookie('results', '0', { path: '/', expires: 1 });
				}
				break;

			case 'hotspot':

				ChangeForm('hotSpotForm', 'snapshotForm', 'rentalForm', 0);

				//NOTE: needs to be in this order due to JSONP calls required first to prepopulate


				break;

			case 'rental':

				ChangeForm('rentalForm', 'snapshotForm', 'hotSpotForm', 0);
				if (results == 1) {
					//prepopulate rental form state information from cookie
					Remember('[id=rentalFormState]', 'id');
					PopulateRentalFormRegionDropdown();
				}
				break;

			default:
				ChangeForm('snapshotForm', 'hotSpotForm', 'rentalForm', 0);
		}
	}
}

function CheckboxCookie(cookieName) {
	if ($.cookie(cookieName) == 1) {
		//alert('cookiecheckbox name is ' + cookieName);
		$('#' + cookieName).attr("checked", "checked");
	}
}

function ChangeForm(divIDOn, divIDOff1, divIDOff2, navEntry) {
	ResetMap();

	//switch form view
	document.getElementById(divIDOn).style.display = 'block';
	document.getElementById(divIDOff1).style.display = 'none';
	document.getElementById(divIDOff2).style.display = 'none';
	document.getElementById('Results').style.display = 'none';
	document.getElementById('Results_Demographic').style.display = 'none';
	document.getElementById('links').style.display = 'none';
	document.getElementById('resultBackLink').style.display = 'none';
	document.getElementById('SuburbSuggestionsResults').style.display = 'none';

	//hack
	document.getElementById('main').style.height = '1300';
	setConHgt();

	//if user clicks on tab for hotspot, then hotspot panels need to be reset

	if (divIDOn == 'hotSpotForm') {
		SetHotspotPanel(navEntry);
	}

	if (divIDOn == 'rentalForm') {
		SetRentalPanel();
	}

	ChangeHeader(divIDOn, divIDOff1, divIDOff2)
}

function ChangeHeader(divIDOn, divIDOff1, divIDOff2) {
	//change button style
	document.getElementById(divIDOn + 'Button').style.backgroundImage = "url('img/aussie/PM/button_bg_on.gif')";
	document.getElementById(divIDOff1 + 'Button').style.backgroundImage = "url('img/aussie/PM/button_bg_off.gif')";
	document.getElementById(divIDOff2 + 'Button').style.backgroundImage = "url('img/aussie/PM/button_bg_off.gif')";
}

function SetRentalPanel() {
	SetMedianPriceSelectBoxValues('#rentalFormMedianPriceMin', 25000, 5000000, 25000, false, $.cookie('rentalMedianPriceMin'));
	SetMedianPriceSelectBoxValues('#rentalFormMedianPriceMax', 25000, 5000000, 25000, true, $.cookie('rentalMedianPriceMax'));
}

function SetHotspotPanel(navEntry) {

	SetMedianPriceSelectBoxValues('#hotspotFormMedianPriceMin', 25000, 5000000, 25000, false, $.cookie('hotspotFormMedianPriceMin'));
	SetMedianPriceSelectBoxValues('#hotspotFormMedianPriceMax', 25000, 5000000, 25000, true, $.cookie('hotspotFormMedianPriceMax'));

	//Prepare to replace Hotspot form values from cookie 
	if ((results == 1) && (navEntry != 1)) {
		CheckboxCookie('hotspotFormCheckMedianPriceRange')
		CheckSelectBoxes($.cookie('hotspotFormCheckMedianPriceRange'), 'hotspotFormMedianPriceMin', 'hotspotFormMedianPriceMax')

		CheckboxCookie('hotspotFormCheckAverageDaysMarket')
		CheckSlider($.cookie('hotspotFormCheckAverageDaysMarket'), 'hotspotFormAverageDaysMarketSlider', 'amountAverageDaysMarket')

		CheckboxCookie('hotspotFormCheckGrowth')
		CheckSlider($.cookie('hotspotFormCheckGrowth'), 'hotspotFormGrowthSlider', 'amountGrowth')

		CheckboxCookie('hotspotFormCheckDiscount')
		CheckSlider($.cookie('hotspotFormCheckDiscount'), 'hotspotFormDiscountSlider', 'amountDiscount')

		Remember('[id=hotspotFormState]', 'id');
		PopulateHotspotFormRegionDropdown();
	}
	else {
		$("#hotspotFormBOTH").attr("checked", "checked");
		$('#hotspotFormCheckGrowth').attr("checked", "checked");
		$('#hotspotFormCheckMedianPriceRange').attr("checked", "checked");

		$('#amountAverageDaysMarket').css({ 'color': '#cccccc' });
		$('#amountDiscount').css({ 'color': '#cccccc' });
	}


}

function SetMedianPriceSelectBoxValues(elementID, minPrice, maxPrice, incrementBy, setMax, cookieValue) {
	//set values for Median Price dropdown
	$(elementID).removeOption(/./);

	var number = parseInt(minPrice);
	var i = 0;

	for (i = 0; i < 300; i++) {
		$(elementID).addOption(number, number.commafy(), setMax);
		number += incrementBy;

		if (number > maxPrice) {
			break;
		}
	}

	if (cookieValue && (results == 1)) {
		$(elementID).val(cookieValue);
	}
}

function CheckSlider(checkBoxValue, SliderName, amountID) {
	if (checkBoxValue == true) {
		$("#" + SliderName).slider("enable");
		$("#" + amountID).css({ 'color': '#6a4388' });
	}
	else {
		$("#" + SliderName).slider("disable");
		$("#" + amountID).css({ 'color': '#cccccc' });
	}
}

function CheckSelectBoxes(checkBoxValue, selectBoxMinID, selectBoxMaxID) {
	if (checkBoxValue == true) {
		document.getElementById(selectBoxMinID).disabled = false;
		document.getElementById(selectBoxMaxID).disabled = false;
	}
	else {
		document.getElementById(selectBoxMinID).disabled = true;
		document.getElementById(selectBoxMaxID).disabled = true;
	}
}

function ReplaceUndefinedCheckBoxValue(checkboxValue) {
	if (checkboxValue != 1) {
		checkboxValue = 0;
	}
	return checkboxValue;
}

//CLEAR STAT/PRE SUBMISSION FUNCTIONS

function ResetMapArrays() {
	pushPinsDetailArray = [];
	pointsArray = [];
}


String.prototype.commafy = function() {
	return this.replace(/(^|[^\w.])(\d{4,})/g, function($0, $1, $2) {
		return $1 + $2.replace(/\d(?=(?:\d\d\d)+(?!\d))/g, "$&,");
	});
}

Number.prototype.commafy = function() {
	return String(this).commafy();
}


function NullifyValue(value) {
	var newValue = value;

	if ((value == 0) || (value == "")) {
		newValue = null;
	}

	return newValue

}
function FormatValue(value, valueSymbol, renderZero) {
	var newValue;

	if ((value == 0) || (value == ""))
	//render the zero value if chosen
		if (renderZero) {
		newValue = 0 + valueSymbol;
	}
	else {
		newValue = "n/a";
	}
	else {
		if (valueSymbol == '$') {
			newValue = valueSymbol + value;
		}
		else {
			newValue = value + valueSymbol;
		}
	}
	return newValue;
}

function GeneratePopupContent(listitem, formType) {
	var description;
	description = "<BR><b>" + listitem.PropertyCategorisation + "</b><BR>";
	description = description + "Sold Median Price: " + FormatValue(listitem.SoldMedianPrice.commafy(), '$', false) + "<BR>";
	description = description + "Annual Median Growth: " + FormatValue(listitem.SuburbMedianGrowthPercentage, '%', false) + "<BR>";

	switch (formType) {
		case 'hotspotForm':
			description = description + "Average Days On Market: " + FormatValue(listitem.AverageDaysOnMarket, ' days', false) + "<BR>";
			description = description + "Average Discount: " + FormatValue(listitem.AverageDiscount, '%', false) + "<BR>";
			break;
		case 'rentalForm':
			description = description + "Rent Median Price: " + FormatValue(listitem.RentMedianPrice.commafy(), '$', false) + " /week <BR>";
			description = description + "Gross Rental Yield: " + FormatValue(listitem.Grossrentalyield, '%', false) + "<BR>";
			break;
		default: break;
	}


	return description;

}
//SUBMISSION FUNCTIONS

function GetSnapShotResultsBySuburbOrPostcode(suburbIDValue) {

	//check that state and suburb exist OR postcode exists        
	var postcode = $('#snapshotFormPostcode').val();
	var suburbID;

	if (suburbIDValue != 0) {
		suburbID = suburbIDValue;
	}
	else {
		suburbID = $("#snapshotSuburbSuggestions").val();
	}

	//store value in cookies for return from results page                     
	$.cookie('snapshotSuburbSuggestions', suburbID, { path: '/', expires: 1 });
	$.cookie('snapshotFormSuburb', suburbName, { path: '/', expires: 1 });
	$.cookie('snapshotFormPostcode', postcode, { path: '/', expires: 1 });
	RenderRateYourPlaceLink(suburbID, postcode);
	
	var postcodeExists = ValidateFormSelectElement(postcode, 'snapshotFormPostcodeError', 'alternatively, please enter a postcode');

	if (postcodeExists != true) {
		var suburbExists = ValidateFormSelectElement(suburbID, 'snapshotFormSuburbError', 'please select a suburb');
	}

	if ((postcodeExists == true || (suburbExists == true))) {
		//reset Error Messages
		document.getElementById('snapshotFormSuburbError').innerHTML = '';
		document.getElementById('snapshotFormPostcodeError').innerHTML = '';
		ResetMapArrays();

		//Call JSONP service and return plot pushpins
		if (postcodeExists == true) {
			$.getJSON(getBaseDataUrl() + "/Services/Service.axd?ServiceName=RealEstate&ServiceAction=GetSuburbByPostcode&postcode=" + postcode + "&year=" + year + "&AttributeStyle=true&ServiceFormat=JSON&callback=?", function(data) {

				if (data.DataList == null) {
					document.getElementById('snapshotFormPostcodeError').innerHTML = "There are no suburbs matching your postcode";
					document.getElementById('snapshotFormPostcodeError').style.display = 'block';
					ResetMap();
				}

				var description = "";
				var f = 0;
				var longitude, lattitude;
				var stateID;
				if (data && data.DataList && data.DataList.Data) {
					var list = data.DataList.Data;

					if (list.length >= 0) {//is array

						for (var i = 0; i < list.length; i++) {

							var ahead = i + 1;
							longitude = list[i].Longitude;
							lattitude = list[i].Lattitude;
							stateID = list[i].StateId;
							//checks if there is a row ahead for same suburb data but for Units

							if (ahead < list.length) {
								if (list[ahead].SuburbName == list[i].SuburbName) {
									description = description + GeneratePopupContent(list[i], 'snapshotForm');
								}
								else {
									description = description + GeneratePopupContent(list[i], 'snapshotForm');

									if ((jQuery.trim(longitude) != "") && (jQuery.trim(lattitude) != "")) {

										description = description + "<BR><a href=\"aussiePriceMapping.aspx?formType=results&statesID=" + stateID + "&suburbID=" + list[i].SuburbId + "\">More Information...</a>";
										AddGeocodePoint(pointsArray, pushPinsDetailArray, f, list[i].Lattitude, list[i].Longitude, list[i].SuburbName, description);
										description = "";
										f = f + 1;
									}
								}
							}
							else {
								if ((jQuery.trim(longitude) != "") && (jQuery.trim(lattitude) != "")) {
									description = description + GeneratePopupContent(list[i], 'snapshotForm');
									description = description + "<BR><a href=\"aussiePriceMapping.aspx?formType=results&statesID=" + stateID + "&suburbID=" + list[i].SuburbId + "\">More Information...</a>";
									AddGeocodePoint(pointsArray, pushPinsDetailArray, f, list[i].Lattitude, list[i].Longitude, list[i].SuburbName, description);
								}
							}
						}
					}
					else {
						longitude = list.Longitude;
						lattitude = list.Lattitude;

						if ((jQuery.trim(longitude) != "") && (jQuery.trim(lattitude) != "")) {
							description = description + GeneratePopupContent(list, 'snapshotForm');
							description = description + "<BR><a href=\"aussiePriceMapping.aspx?formType=results&suburbID=" + list.SuburbId + "&statesID=" + stateID + "\">More Information...</a>";

							AddGeocodePoint(pointsArray, pushPinsDetailArray, f, list.Lattitude, list.Longitude, list.SuburbName, description);
							description = "";
						}
					}

					GetMap(pushPinsDetailArray, pointsArray, 'myMap');
					$.cookie('form', 'snapshotpostcode', { path: '/', expires: 1 });					

				}
			});


		}
		else {
			//Search by SuburbID

			$.getJSON(getBaseDataUrl() + "/Services/Service.axd?ServiceName=RealEstate&ServiceAction=GetSuburbBySuburbID&suburbID=" + suburbID + "&year=" + year + "&AttributeStyle=true&ServiceFormat=JSON&callback=?", function(data) {

				var description = "";
				var f = 0;
				var longitude, lattitude;
				var stateID;

				if (data.DataList == null) {
					document.getElementById('snapshotFormPostcodeError').innerHTML = "There are no suburbs matching your suburb";
					document.getElementById('snapshotFormPostcodeError').style.display = 'block';
					ResetMap();
				}

				if (data && data.DataList && data.DataList.Data) {
					var list = data.DataList.Data;

					if (list.length >= 0) {//is array

						for (var i = 0; i < list.length; i++) {
							var ahead = i + 1;
							longitude = list[i].Longitude;
							lattitude = list[i].Lattitude;
							var stateID = list[i].StateId;
							var suburbName = list[i].SuburbName;

							//checks if there is a row ahead for same suburb data but for Units
							if (ahead < list.length) {
								if (list[ahead].SuburbName == list[i].SuburbName) {
									description = description + GeneratePopupContent(list[i]);
								}
								else {

									if ((jQuery.trim(longitude) != "") && (jQuery.trim(lattitude) != "")) {
										description = description + GeneratePopupContent(list[i], 'snapshotForm');
										description = description + "<BR><a href=\"aussiePriceMapping.aspx?formType=results&suburbID=" + list[i].SuburbId + "&statesID=" + stateID + "\">More Information...</a>";
										AddGeocodePoint(pointsArray, pushPinsDetailArray, f, list[i].Lattitude, list[i].Longitude, list[i].SuburbName, description);
										description = "";
										f = f + 1;
									}
								}

							}
							else {
								if ((jQuery.trim(longitude) != "") && (jQuery.trim(lattitude) != "")) {
									description = description + GeneratePopupContent(list[i], 'snapshotForm');
									description = description + "<BR><a href=\"aussiePriceMapping.aspx?formType=results&suburbID=" + list[i].SuburbId + "&statesID=" + stateID + "\">More Information...</a>";

									AddGeocodePoint(pointsArray, pushPinsDetailArray, f, list[i].Lattitude, list[i].Longitude, list[i].SuburbName, description);
								}
							}
							//cookie the suburbName and populate the suburb Name field    
							$.cookie('snapshotFormSuburb', suburbName, { path: '/', expires: 1 });
							$('#snapshotFormSuburb').val($.cookie('snapshotFormSuburb'));
							RenderRateYourPlaceLink(suburbID, suburbName);
							
						}
					}
					else {
						longitude = list.Longitude;
						lattitude = list.Lattitude;

						if ((jQuery.trim(longitude) != "") && (jQuery.trim(lattitude) != "")) {
							description = description + GeneratePopupContent(list, 'snapshotForm');
							description = description + "<BR><a href=\"aussiePriceMapping.aspx?formType=results&suburbID=" + list.SuburbId + "&statesID=" + stateID + "\">More Information...</a>";

							AddGeocodePoint(pointsArray, pushPinsDetailArray, f, list.Lattitude, list.Longitude, list.SuburbName, description);
							description = "";
						}
					}

					GetMap(pushPinsDetailArray, pointsArray, 'myMap');
					$.cookie('form', 'snapshotdropdown', { path: '/', expires: 1 });

				}
			});

		}
	}
	else {
		return false;
	}
}

function RenderRateYourPlaceLink(suburbID, postcode) {

	var serviceAction1 = "GetSuburbByPostcode&postcode=" + postcode;
	var serviceAction2 = "GetSuburbBySuburbID&suburbID=" + suburbID;

	$.getJSON(getBaseDataUrl() + "/Services/Service.axd?ServiceName=RealEstate&ServiceAction=" + (typeof (suburbID) == "undefined" ? serviceAction1 : serviceAction2) + "&year=" + year + "&AttributeStyle=true&ServiceFormat=JSON&callback=?", function(data) {
		if (data.DataList == null) {
			$('.snapshot_rateyourplace').html("");
		}

		if (data && data.DataList && data.DataList.Data) {
			var list = data.DataList.Data;
			var suburbList = "";

			for (i = 0; i < list.length; i++) {
				i++;
				suburbList += "<a href='/suburb.aspx?suburbID=" + (typeof (suburbID) == "undefined" ? list[i].SuburbId : suburbID) + "'>" + list[i].SuburbName + "</a>, ";
			}

			$('.snapshot_rateyourplace').html("").html("Visit <a href='/rateyourplace.aspx'>Rate Your Place</a> to find out more about " + suburbList.substring(0, suburbList.length - 2) + ".");
		}
	});		
}

function GetRentalResults() {
	document.getElementById('rentalFormError').innerHTML = '';
	var stateID = $('#rentalFormState').val();
	var regionCode = $('#rentalFormRegion').val();
	var propertyCategorisation = $('input:radio[name=rentalPropertyCategorisation]:checked').val();
	var rentalYieldMin = $("#rentalYieldSlider").slider("values", 0);
	var rentalYieldMax = $("#rentalYieldSlider").slider("values", 1);
	var medianPriceMin = $('#rentalFormMedianPriceMin').val();
	var medianPriceMax = $('#rentalFormMedianPriceMax').val();

	//cookie the information
	$.cookie('rentalPropertyCategorisation', propertyCategorisation, { path: '/', expires: 1 });
	$.cookie('rentalRentalYieldMin', rentalYieldMin, { path: '/', expires: 1 });
	$.cookie('rentalRentalYieldMax', rentalYieldMax, { path: '/', expires: 1 });
	$.cookie('rentalMedianPriceMin', medianPriceMin, { path: '/', expires: 1 });
	$.cookie('rentalMedianPriceMax', medianPriceMax, { path: '/', expires: 1 });
	$.cookie('rentalFormState', stateID, { path: '/', expires: 1 });
	$.cookie('rentalFormRegion', regionCode, { path: '/', expires: 1 });


	if (ValidateFormSelectElement(stateID, 'rentalFormStateError', 'please select a state') == true) {
		ResetMapArrays();
		$.getJSON(getBaseDataUrl() + "/Services/Service.axd?ServiceName=RealEstate&ServiceAction=GetSuburbsByRentalYieldStateOrRegion&stateID=" + stateID + "&regionCode=" + regionCode + "&propertyType=" + propertyCategorisation + "&rentalYieldMin=" + rentalYieldMin + "&rentalYieldMax=" + rentalYieldMax + "&soldMedianPriceMin=" + medianPriceMin + "&soldMedianPriceMax=" + medianPriceMax + "&year=" + year + "&AttributeStyle=true&ServiceFormat=JSON&callback=?", function(data) {

			if (data.DataList == null) {
				document.getElementById('rentalFormError').innerHTML = "There are no suburbs matching your search criteria. Please try again.";
				document.getElementById('rentalFormError').style.display = 'block';
				ResetMap();
			}
			else {
				var longitude, lattitude;
				var f = 0;
				var description = "";

				if (data && data.DataList && data.DataList.Data) {
					var list = data.DataList.Data;

					if (list.length >= 0) {//is array

						for (var i = 0; i < list.length; i++) {
							var ahead = i + 1;
							longitude = list[i].Longitude;
							lattitude = list[i].Lattitude;
							//checks if there is a row ahead for same suburb data but for Units

							if (ahead < list.length) {
								if (list[ahead].SuburbName == list[i].SuburbName) {
									description = description + GeneratePopupContent(list[i], 'rentalForm');
								}
								else {
									if ((jQuery.trim(longitude) != "") && (jQuery.trim(lattitude) != "")) {
										description = description + GeneratePopupContent(list[i], 'rentalForm');
										description = description + "<BR><a href=\"aussiePriceMapping.aspx?formType=results&suburbID=" + list[i].SuburbId + "&statesID=" + stateID + "\">More Information...</a>";
										AddGeocodePoint(pointsArray, pushPinsDetailArray, f, list[i].Lattitude, list[i].Longitude, list[i].SuburbName, description);
										description = "";
										f = f + 1;
									}
								}

							}
							else {

								if ((jQuery.trim(longitude) != "") && (jQuery.trim(lattitude) != "")) {
									description = description + GeneratePopupContent(list[i], 'rentalForm');
									description = description + "<BR><a href=\"aussiePriceMapping.aspx?formType=results&suburbID=" + list[i].SuburbId + "&statesID=" + stateID + "\">More Information...</a>";

									AddGeocodePoint(pointsArray, pushPinsDetailArray, f, list[i].Lattitude, list[i].Longitude, list[i].SuburbName, description);
								}
							}
						}
					}
					else {
						longitude = list.Longitude;
						lattitude = list.Lattitude;

						if ((jQuery.trim(longitude) != "") && (jQuery.trim(lattitude) != "")) {
							description = description + GeneratePopupContent(list, 'rentalForm');
							description = description + "<BR><a href=\"aussiePriceMapping.aspx?formType=results&suburbID=" + list.SuburbId + "&statesID=" + stateID + "\">More Information...</a>";
							AddGeocodePoint(pointsArray, pushPinsDetailArray, f, lattitude, longitude, list.SuburbName, description);
						}
					}

					GetMap(pushPinsDetailArray, pointsArray, 'myMap');
					$.cookie('form', 'rental', { path: '/', expires: 1 });
				}
			}
		});
	}
	else {
		return false;
	}
}


function GetHotSpotResults() {

	var stateID = $('#hotspotFormState').val();
	var regionCode = $('#hotspotFormRegion').val();
	var propertyCategorisation = $('input:radio[name=hotspotPropertyCategorisation]:checked').val();
	var averageDaysMarketCheckBox = ReplaceUndefinedCheckBoxValue($('#hotspotFormCheckAverageDaysMarket:checked').val());
	var medianPriceRangeCheckBox = ReplaceUndefinedCheckBoxValue($('#hotspotFormCheckMedianPriceRange:checked').val());
	var growthCheckBox = ReplaceUndefinedCheckBoxValue($('#hotspotFormCheckGrowth:checked').val());
	var discountPercentageCheckBox = ReplaceUndefinedCheckBoxValue($('#hotspotFormCheckDiscount:checked').val());
	var medianPriceMin;
	var medianPriceMax;
	var suburbMedianGrowthPercentageMin;
	var suburbMedianGrowthPercentageMax;
	var averageDaysMarketMin;
	var averageDaysMarketMax;
	var discountPercentageMin;
	var discountPercentageMax;

	//reset Error Messages
	document.getElementById('hotspotFormError').innerHTML = '';

	//checks if the optional sliders are on and set accordingly

	if (medianPriceRangeCheckBox == 1) {
		medianPriceMin = $('#hotspotFormMedianPriceMin').val();
		medianPriceMax = $('#hotspotFormMedianPriceMax').val();
	}
	else {
		medianPriceMin = 0;
		medianPriceMax = 0;
	}

	if (growthCheckBox == 1) {
		suburbMedianGrowthPercentageMin = $("#hotspotFormGrowthSlider").slider("values", 0);
		suburbMedianGrowthPercentageMax = $("#hotspotFormGrowthSlider").slider("values", 1);
	}
	else {
		//set to a value which includes all results in stored proc
		suburbMedianGrowthPercentageMin = -1000000;
		suburbMedianGrowthPercentageMax = -1000000;
	}

	if (averageDaysMarketCheckBox == 1) {
		averageDaysMarketMin = $("#hotspotFormAverageDaysMarketSlider").slider("values", 0);
		averageDaysMarketMax = $("#hotspotFormAverageDaysMarketSlider").slider("values", 1);
	}
	else {
		averageDaysMarketMin = 0;
		averageDaysMarketMax = 0;
	}

	if (discountPercentageCheckBox == 1) {
		discountPercentageMin = $("#hotspotFormDiscountSlider").slider("values", 0);
		discountPercentageMax = $("#hotspotFormDiscountSlider").slider("values", 1);
	}
	else {
		discountPercentageMin = 0;
		discountPercentageMax = 0;
	}

	//cookie the information

	$.cookie('hotspotFormState', stateID, { path: '/', expires: 1 });
	$.cookie('hotspotFormRegion', regionCode, { path: '/', expires: 1 });
	$.cookie('hotspotPropertyCategorisation', propertyCategorisation, { path: '/', expires: 1 });
	$.cookie('hotspotFormMedianPriceMin', medianPriceMin, { path: '/', expires: 1 });
	$.cookie('hotspotFormMedianPriceMax', medianPriceMax, { path: '/', expires: 1 });


	//cookies of checkboxes
	$.cookie('hotspotFormCheckMedianPriceRange', medianPriceRangeCheckBox, { path: '/', expires: 1 });
	$.cookie('hotspotFormCheckAverageDaysMarket', averageDaysMarketCheckBox, { path: '/', expires: 1 });
	$.cookie('hotspotFormCheckGrowth', growthCheckBox, { path: '/', expires: 1 });
	$.cookie('hotspotFormCheckDiscount', discountPercentageCheckBox, { path: '/', expires: 1 });

	//cookie the information if its set to be used by user for sliders
	if ((suburbMedianGrowthPercentageMin != -1000000) && (suburbMedianGrowthPercentageMax != -1000000)) {
		$.cookie('hotspotFormGrowthMin', suburbMedianGrowthPercentageMin, { path: '/', expires: 1 });
		$.cookie('hotspotFormGrowthMax', suburbMedianGrowthPercentageMax, { path: '/', expires: 1 });
	}
	//cookie the information if its set to be used by user for sliders
	if ((averageDaysMarketMin != 0) && (averageDaysMarketMax != 0)) {
		$.cookie('hotspotFormAverageDaysMarketMin', averageDaysMarketMin, { path: '/', expires: 1 });
		$.cookie('hotspotFormAverageDaysMarketMax', averageDaysMarketMax, { path: '/', expires: 1 });
	}

	//cookie the information if its set to be used by user for sliders
	if ((discountPercentageMin != 0) && (discountPercentageMax != 0)) {
		$.cookie('hotspotFormDiscountMin', discountPercentageMin, { path: '/', expires: 1 });
		$.cookie('hotspotFormDiscountMax', discountPercentageMax, { path: '/', expires: 1 });
	}


	if (ValidateFormSelectElement(stateID, 'hotspotFormStateError', 'please select a state') == true) {

		//Call JSONP service and return plot pushpins
		$.getJSON(getBaseDataUrl() + "/Services/Service.axd?ServiceName=RealEstate&ServiceAction=GetSuburbsbyHotspotsAndRegionID&stateID=" + stateID + "&regionCode=" + regionCode + "&propertyType=" + propertyCategorisation + "&averageDaysOnMarketMin=" + averageDaysMarketMin + "&averageDaysOnMarketMax=" + averageDaysMarketMax + "&soldMedianValueMin=" + medianPriceMin + "&soldMedianValueMax=" + medianPriceMax + "&averageDiscountMin=" + discountPercentageMin + "&averageDiscountMax=" + discountPercentageMax + "&suburbMedianGrowthPercentageMin=" + suburbMedianGrowthPercentageMin + "&suburbMedianGrowthPercentageMax=" + suburbMedianGrowthPercentageMax + "&year=" + year + "&AttributeStyle=true&ServiceFormat=JSON&callback=?", function(data) {

			if (data.DataList == null) {
				document.getElementById('hotspotFormError').innerHTML = "There are no suburbs matching your search criteria. Please try again.";
				document.getElementById('hotspotFormError').style.display = 'block';
				ResetMap();

			}
			else {
				var list = data.DataList.Data;
				var description = "";
				var longitude, lattitude;
				var f = 0;

				if (data && data.DataList && data.DataList.Data) {

					ResetMapArrays();

					if (list.length >= 0) {//is array

						for (var i = 0; i < list.length; i++) {
							var ahead = i + 1;
							longitude = list[i].Longitude;
							lattitude = list[i].Lattitude;
							//checks if there is a row ahead for same suburb data but for Units

							if (ahead < list.length) {
								if (list[ahead].SuburbName == list[i].SuburbName) {
									description = description + GeneratePopupContent(list[i], 'hotspotForm');
								}
								else {
									if ((jQuery.trim(longitude) != "") && (jQuery.trim(lattitude) != "")) {
										description = description + GeneratePopupContent(list[i], 'hotspotForm');
										description = description + "<BR><a href=\"aussiePriceMapping.aspx?formType=results&suburbID=" + list[i].SuburbId + "&statesID=" + stateID + "\">More Information...</a>";
										AddGeocodePoint(pointsArray, pushPinsDetailArray, f, list[i].Lattitude, list[i].Longitude, list[i].SuburbName, description);
										description = "";
										f = f + 1;
									}
								}
							}
							else {

								if ((jQuery.trim(longitude) != "") && (jQuery.trim(lattitude) != "")) {
									description = description + GeneratePopupContent(list[i], 'hotspotForm');
									description = description + "<BR><a href=\"aussiePriceMapping.aspx?formType=results&suburbID=" + list[i].SuburbId + "&statesID=" + stateID + "\">More Information...</a>";

									AddGeocodePoint(pointsArray, pushPinsDetailArray, f, list[i].Lattitude, list[i].Longitude, list[i].SuburbName, description);
									description = "";
								}
							}
						}
					}
					else {
						longitude = list.Longitude;
						lattitude = list.Lattitude;

						if ((jQuery.trim(longitude) != "") && (jQuery.trim(lattitude) != "")) {
							description = description + GeneratePopupContent(list, 'hotspotForm');
							description = description + "<BR><a href=\"aussiePriceMapping.aspx?formType=results&suburbID=" + list.SuburbId + "&statesID=" + stateID + "\">More Information...</a>";

							AddGeocodePoint(pointsArray, pushPinsDetailArray, f, list.Lattitude, list.Longitude, list.SuburbName, description);
							description = "";
						}
					}

					GetMap(pushPinsDetailArray, pointsArray, 'myMap');
					$.cookie('form', 'hotspot', { path: '/', expires: 1 });
				}
			}
		});
	}
	else {
		return false;
	}
}

function AddGeocodePoint(pointsArray, pushPinsDetailArray, i, lattitude, longitude, title, description, suburbID) {
	//add geocode to position array
	pointsArray[i] = new VELatLong(lattitude, longitude, 0, VEAltitudeMode.RelativeToGround)

	//add details for popup hover
	pushPinsDetailArray[i] = [title, description];
}

//Validates Field in Form

function ValidateFormSelectElement(selectboxElement, errorMessageElement, errorMessage) {
	document.getElementById(errorMessageElement).innerHTML = '';

	if (selectboxElement == "") {
		document.getElementById(errorMessageElement).innerHTML = errorMessage;
		return false;
	}
	else {
		return true;
	}
}

//resets map to Australia

var map;
//map = new VEMap('myMap');

function ResetMap() {
	var map = new VEMap('myMap');

	map.LoadMap(new VELatLong(-28.48295117535531, 134.296875), 4, 'Road', true);

}

function GetMap(pushPinsDetailArray, pointsArray, mapID) {
	map = new VEMap(mapID);
	map.LoadMap();
	//sets best focused map view based on points in array
	map.SetMapView(pointsArray);

	//Add suburb pushpin layer
	var myShapeLayer = new VEShapeLayer();
	map.AddShapeLayer(myShapeLayer);

	//loops through arrays to plot pushpin and pushpin details
	for (i = 0; i < pushPinsDetailArray.length; i++) {
		var pin = new VEShape(VEShapeType.Pushpin, pointsArray[i]);
		pin.SetTitle(pushPinsDetailArray[i][0]);
		pin.SetDescription(pushPinsDetailArray[i][1]);
		pin.SetMoreInfoURL(pushPinsDetailArray[i][2]);
		//pin.SetPhotoURL("http://marcgrabanski.com/img/jQuery-logo.gif");
		myShapeLayer.AddShape(pin);
	}

	myShapeLayer.SetClusteringConfiguration(VEClusteringType.Grid);


}



//RESULTS FUNCTION

function GetResults(suburbID) {
	GetRegionalAndSuburbData(suburbID);
	GetTenYearRegionalAndSuburbChartData(suburbID);
	GetDemographicData(suburbID);
	$.cookie('results', '1', { path: '/', expires: 1 });
}

function GetRegionalAndSuburbData(suburbID) {
	$.getJSON(getBaseDataUrl() + "/Services/Service.axd?ServiceName=RealEstate&ServiceAction=GetRegionalAndSuburbDataBySuburbID&suburbId=" + suburbID + "&year=" + year + "&AttributeStyle=true&ServiceFormat=JSON&callback=?", function(data) {

		if (data.DataList == null) {
			document.getElementById('resultFormError').innerHTML = "There are no results matching your suburb";
			document.getElementById('resultFormError').style.display = 'block';
			ResetMap();
		}


		var f = 0;
		var longitude, lattitude;
		var propertyCategorisationType;
		var description = "";

		if (data && data.DataList && data.DataList.Data) {
			var list = data.DataList.Data;

			if (list.length >= 0) {//is array

				for (var i = 0; i < list.length; i++) {
					longitude = list[i].Longitude;
					lattitude = list[i].Lattitude;
					//checks if there is a row ahead for same suburb data but for Units

					if ((jQuery.trim(longitude) != "") && (jQuery.trim(lattitude) != "")) {
						$("#suburbName").html(list[i].SuburbName);
						$("#regionName").html(list[i].RegionName);
						$("#stateName").html(list[i].State);


						propertyCategorisationType = list[i].PropertyCategorisation;
						//House stats
						if (propertyCategorisationType == 'HOUSE') {

							$("#HouseMedianPrice").html(FormatValue(list[i].SoldMedianPrice.commafy(), '$'), false);
							$("#HouseAnnualMedianGrowth").html(FormatValue(list[i].SuburbMedianGrowthPercentage, '%'), false);
							$("#HouseAverageTimeMarket").html(FormatValue(list[i].AverageDaysOnMarket, ' days', false));
							$("#HouseAverageDiscount").html(FormatValue(list[i].AverageDiscount, '%'), false);
							$("#HouseAuctionClearanceRate").html(FormatValue(list[i].AuctionClearanceRate, '%', true));
							$("#HouseVolumeOfSales").html(FormatValue(list[i].PriceCalculationRecordCount, '', false));
							$("#RentalHouseMedianWeeklyRental").html(FormatValue(list[i].RentMedianPrice, '$', false));
							$("#RentalGrossRentalYieldsHouses").html(FormatValue(list[i].GrossRentalYield, '%', false));
						}
						//Unit stats
						if (propertyCategorisationType == 'UNIT') {
							$("#UnitsMedianPrice").html(FormatValue(list[i].SoldMedianPrice.commafy(), '$'), false);
							$("#UnitsAnnualMedianGrowth").html(FormatValue(list[i].SuburbMedianGrowthPercentage, '%', false));
							$("#UnitsAverageTimeMarket").html(FormatValue(list[i].AverageDaysOnMarket, ' days', false));
							$("#UnitsAverageDiscount").html(FormatValue(list[i].AverageDiscount, '%', false));
							$("#UnitsAuctionClearanceRate").html(FormatValue(list[i].AuctionClearanceRate, '%', true));
							$("#UnitsVolumeOfSales").html(FormatValue(list[i].PriceCalculationRecordCount, '', false));
							$("#RentalUnitsMedianWeeklyRental").html(FormatValue(list[i].RentMedianPrice, '$', false));
							$("#RentalGrossRentalYeldUnits").html(FormatValue(list[i].GrossRentalYield, '%', false));
						}

						description = description + GeneratePopupContent(list[i], 'result');

						AddGeocodePoint(pointsArray, pushPinsDetailArray, f, list[i].Lattitude, list[i].Longitude, list[i].SuburbName, description);
					}
				}
			}

			GetMap(pushPinsDetailArray, pointsArray, 'myMap');
		}
	});
}


function GetDemographicData(suburbID) {

	$.getJSON(getBaseDataUrl() + "/Services/Service.axd?ServiceName=RealEstate&ServiceAction=GetDemographicDataBySuburbID&suburbId=" + suburbID + "&AttributeStyle=true&ServiceFormat=JSON&callback=?", function(data) {

		if (data && data.DataList && data.DataList.Data) {
			var list = data.DataList.Data;

			if (list) {//is array

				$("#Population2006").html(FormatValue(list.Population2006, '', false));
				$("#DistanceToCBD").html(FormatValue(parseInt(list.DistanceToCBD) / 1000, ' kms', false));
				$("#MedianResidentsAge").html(FormatValue(list.MedianResidentsAge, '', false));
				$("#MedianHouseholdWeeklyIncome").html(FormatValue(list.MedianHouseholdWeeklyIncome, '$', true));
				$("#AverageHouseholdSize").html(FormatValue(list.AverageHouseholdSize, '', false));
				$("#Rented").html(FormatValue(list.Rented, '', false));
				$("#FullOwned").html(FormatValue(list.FullOwned, '', false));
				$("#BeingPurchased").html(FormatValue(list.BeingPurchased, '', false));
				$("#OtherOwnership").html(FormatValue(list.OtherOwnership, '', false));
				$("#TenureNotStated").html(FormatValue(list.TenureNotStated, '', false));
				$("#House").html(FormatValue(list.House, '', false));
				$("#SemiDetached").html(FormatValue(list.SemiDetached, '', false));
				$("#FlatUnitApartment").html(FormatValue(list.FlatUnitApartment, '', false));
				$("#OtherType").html(FormatValue(list.OtherType, '', false));
				$("#DwellingStructureNotStated").html(FormatValue(list.DwellingStructureNotStated, '', false));
				$("#Married").html(FormatValue(list.Married, '', false));
				$("#NeverMarried").html(FormatValue(list.NeverMarried, '', false));
				$("#Divorced").html(FormatValue(list.Divorced, '', false));
				$("#Seperated").html(FormatValue(list.Seperated, '', false));
				$("#Widowed").html(FormatValue(list.Widowed, '', false));
				$("#WeeklyIncome0").html(FormatValue(list.WeeklyIncome0, '', true));
				$("#WeeklyIncome1to149").html(FormatValue(list.WeeklyIncome1to149, '', false));
				$("#WeeklyIncome150to249").html(FormatValue(list.WeeklyIncome150to249, '', false));
				$("#WeeklyIncome250to349").html(FormatValue(list.WeeklyIncome250to349, '', false));
				$("#WeeklyIncome350to499").html(FormatValue(list.WeeklyIncome350to499, '', false));
				$("#WeeklyIncome500to649").html(FormatValue(list.WeeklyIncome500to649, '', false));
				$("#WeeklyIncome650to799").html(FormatValue(list.WeeklyIncome650to799, '', false));
				$("#WeeklyIncome800to999").html(FormatValue(list.WeeklyIncome800to999, '', false));
				$("#WeeklyIncome1000to1199").html(FormatValue(list.WeeklyIncome1000to1199, '', false));
				$("#WeeklyIncome1200to1399").html(FormatValue(list.WeeklyIncome1200to1399, '', false));
				$("#WeeklyIncome1400to1699").html(FormatValue(list.WeeklyIncome1400to1699, '', false));
				$("#WeeklyIncome1700to1999").html(FormatValue(list.WeeklyIncome1700to1999, '', false));
				$("#WeeklyIncome2000to2499").html(FormatValue(list.WeeklyIncome2000to2499, '', false));
				$("#WeeklyIncome2500to2999").html(FormatValue(list.WeeklyIncome2500to2999, '', false));
				$("#WeeklyIncome3000plus").html(FormatValue(list.WeeklyIncome3000plus, '', false));
				$("#AustralianBirth").html(FormatValue(list.AustralianBirth, '', false));
				$("#ForeignBirth").html(FormatValue(list.ForeignBirth, '', false));
				$("#CountryofBirthRank1").html(FormatValue(list.CountryofBirthRank1, '', false));
				$("#CountryofBirthPercentageRank1").html(FormatValue(list.CountryofBirthPercentageRank1, '', false));
				$("#CountryofBirthRank2").html(FormatValue(list.CountryofBirthRank2, '', false));
				$("#CountryofBirthPercentageRank2").html(FormatValue(list.CountryofBirthPercentageRank2, '', false));
				$("#CountryofBirthRank3").html(FormatValue(list.CountryofBirthRank3, '', false));
				$("#CountryofBirthPercentageRank3").html(FormatValue(list.CountryofBirthPercentageRank3, '', false));
				$("#CountryofBirthRank4").html(FormatValue(list.CountryofBirthRank4, '', false));
				$("#CountryofBirthPercentageRank4").html(FormatValue(list.CountryofBirthPercentageRank4, '', false));
				$("#CountryofBirthRank5").html(FormatValue(list.CountryofBirthRank5, '', false));
				$("#CountryofBirthPercentageRank5").html(FormatValue(list.CountryofBirthPercentageRank5, '', false));
				$("#ReligionRank1").html(FormatValue(list.ReligionRank1, '', false));
				$("#ReligionPercentageRank1").html(FormatValue(list.ReligionPercentageRank1, '', false));
				$("#ReligionRank2").html(FormatValue(list.ReligionRank2, '', false));
				$("#ReligionPercentageRank2").html(FormatValue(list.ReligionPercentageRank2, '', false));
				$("#ReligionRank3").html(FormatValue(list.ReligionRank3, '', false));
				$("#ReligionPercentageRank3").html(FormatValue(list.ReligionPercentageRank3, '', false));
				$("#ReligionRank4").html(FormatValue(list.ReligionRank4, '', false));
				$("#ReligionPercentageRank4").html(FormatValue(list.ReligionPercentageRank4, '', false));
				$("#ReligionRank5").html(FormatValue(list.ReligionRank5, '', false));
				$("#ReligionPercentageRank5").html(FormatValue(list.ReligionPercentageRank5, '', false));
				$("#OccupationRank1").html(FormatValue(list.OccupationRank1, '', false));
				$("#OccupationPercentageRank1").html(FormatValue(list.OccupationPercentageRank1, '', false));
				$("#OccupationRank2").html(FormatValue(list.OccupationRank2, '', false));
				$("#OccupationPercentageRank2").html(FormatValue(list.OccupationPercentageRank2, '', false));
				$("#OccupationRank3").html(FormatValue(list.OccupationRank3, '', false));
				$("#OccupationPercentageRank3").html(FormatValue(list.OccupationPercentageRank3, '', false));
				$("#OccupationRank4").html(FormatValue(list.OccupationRank4, '', false));
				$("#OccupationPercentageRank4").html(FormatValue(list.OccupationPercentageRank4, '', false));
				$("#OccupationRank5").html(FormatValue(list.OccupationRank5, '', false));
				$("#OccupationPercentageRank5").html(FormatValue(list.OccupationPercentageRank5, '', false));
				$("#EducationAttendanceRank1").html(FormatValue(list.EducationAttendanceRank1, '', false));
				$("#EducationAttendancePercentageRank1").html(FormatValue(list.EducationAttendancePercentageRank1, '', false));
				$("#EducationAttendanceRank2").html(FormatValue(list.EducationAttendanceRank2, '', false));
				$("#EducationAttendancePercentageRank2").html(FormatValue(list.EducationAttendancePercentageRank2, '', false));
				$("#EducationAttendanceRank3").html(FormatValue(list.EducationAttendanceRank3, '', false));
				$("#EducationAttendancePercentageRank3").html(FormatValue(list.EducationAttendancePercentageRank3, '', false));
				$("#EducationAttendanceRank4").html(FormatValue(list.EducationAttendanceRank4, '', false));
				$("#EducationAttendancePercentageRank4").html(FormatValue(list.EducationAttendancePercentageRank4, '', false));
				$("#EducationAttendanceRank5").html(FormatValue(list.EducationAttendanceRank5, '', false));
				$("#EducationAttendancePercentageRank5").html(FormatValue(list.EducationAttendancePercentageRank5, '', false));
				$("#Age0to4").html(FormatValue(list.Age0to4, '', false));
				$("#Age5to19").html(FormatValue(list.Age5to19, '', false));
				$("#Age20to34").html(FormatValue(list.Age20to34, '', false));
				$("#Age35to49").html(FormatValue(list.Age35to49, '', false));
				$("#Age50to64").html(FormatValue(list.Age50to64, '', false));
				$("#Age65plus").html(FormatValue(list.Age65plus, '', false));
			}
		}
	});
}

var arrSuburbHouse = [];
var arrRegionHouse = [];
var arrSuburbUnit = [];
var arrRegionUnit = [];

function GetTenYearRegionalAndSuburbChartData(suburbID) {
	$(function() {

		$.getJSON(getBaseDataUrl() + "/Services/Service.axd?ServiceName=RealEstate&ServiceAction=GetTenYearRegionalAndSuburbMedianGrowthBySuburbID&suburbid=" + suburbID + "&AttributeStyle=true&ServiceFormat=JSON&callback=?", function(data) {

			if (data.DataList == null) {
				document.getElementById('resultFormError').innerHTML = "There are no results matching your suburb";
				document.getElementById('resultFormError').style.display = 'block';
			}

			if (data && data.DataList && data.DataList.Data) {

				var list = data.DataList.Data;

				if (list.length >= 0) {//is array
					var description = "";
					var f = 0;
					var dateYear, suburbGrowthValue, regionGrowthValue;


					for (var i = 0; i < list.length; i++) {
						dateYear = NullifyValue(list[i].Dateyear);
						regionalGrowthValue = NullifyValue(list[i].RegionMedianGrowthPercentage);
						suburbGrowthValue = NullifyValue(list[i].SuburbMedianGrowthPercentage);

						propertyCategorisationType = list[i].PropertyCategorisation;

						//House stats
						if (propertyCategorisationType == 'HOUSE') {
							Array.prototype.push.call(arrRegionHouse, [dateYear, regionalGrowthValue]);
							Array.prototype.push.call(arrSuburbHouse, [dateYear, suburbGrowthValue]);
						}

						if (propertyCategorisationType == 'UNIT') {

							Array.prototype.push.call(arrRegionUnit, [dateYear, regionalGrowthValue]);
							Array.prototype.push.call(arrSuburbUnit, [dateYear, suburbGrowthValue]);
						}

					}

				}

				//plots House map                   

				var data = [
                    {
                    	label: "Region (%)",
                    	data: arrRegionHouse
                    },

                    {
                    	label: "Suburb (%)",
                    	data: arrSuburbHouse
                    }
                ];

				var optionsHouse = {
					legend: {
						show: true,
						margin: 10,
						backgroundOpacity: 0.5
					},
					points: {
						show: true,
						radius: 3
					},
					lines: {
						show: true,
						fillColor: "rgba(255, 255, 255, 0.8)"

					},

					xaxis: { ticks: 9 },

					colors: ["#ccc", "#a48bb8", "#a48bb8", "#000", "#9440ed"]

				};

				$.plot($("#PlotHouseRegion"), data, optionsHouse);

				//plots units
				var data = [
                    {
                    	label: "Region (%)",
                    	data: arrRegionUnit
                    },

                    {
                    	label: "Suburb (%)",
                    	data: arrSuburbUnit
                    }
                ];

				var optionsUnits = {
					legend: {
						show: true,
						margin: 10,
						backgroundOpacity: 0.5
					},
					points: {
						show: true,
						radius: 3
					},
					lines: {
						show: true,
						fillColor: "rgba(255, 255, 255, 0.8)"
					},

					xaxis: { ticks: 9 },

					colors: ["#ccc", "#a48bb8", "#a48bb8", "#000", "#9440ed"]

				};

				$.plot($("#PlotUnitsRegion"), data, optionsUnits);
			}
		});
	});

}

function CreateBookmarkLink() {

	title = document.title;
	url = window.location.href;

	if (window.sidebar) { // Mozilla Firefox Bookmark 
		window.sidebar.addPanel(title, url, "");
	}
	else if (window.external) { // IE Favorite 
		window.external.AddFavorite(url, title);
	}
	else if (window.opera && window.print) { // Opera Hotlist 
		return true;
	}
}



function OpenWindow() {

	var printContent = document.getElementById("ContentWrap");

	var sFeatures = "height=800,width=800,status=no,toolbar=no,menubar=no,location=no,scrollbars=yes";

	win = window.open("", "Print", sFeatures);
	win.document.write(printContent.innerHTML);

	//win.focus();
	win.print();
	win.document.close();
	win.close();

}











