//this function is overwritten in the code as needed and called in load_markers()
post_marker_load=function(){};

var suburb_only;
var listing_icons=getListingMapIcons();
var mgr;
var region_markers=[];
var listing_markers=[];
var map_center_suburb='';
var keep_active=false;

function getQueryString(skip_map_positioning){
	var str="branch_id="+encodeURIComponent(branch_id)+"&portal_id="+encodeURIComponent(portal_id)+"&sale_type="+encodeURIComponent(sale_type)+"&realist_type="+encodeURIComponent(realist_type)+"&region="+encodeURIComponent(region)+"&state="+encodeURIComponent(state)+"&location="+encodeURIComponent(location_val)+"&surrounding_radius="+encodeURIComponent(surrounding_radius)+"&price_from="+encodeURIComponent(price_from)+"&price_to="+encodeURIComponent(price_to)+"&bedrooms_from="+encodeURIComponent(bedrooms_from)+"&bedrooms_to="+encodeURIComponent(bedrooms_to)+"&bathrooms_from="+encodeURIComponent(bathrooms_from)+"&bathrooms_to="+encodeURIComponent(bathrooms_to)+"&carparks_from="+encodeURIComponent(carparks_from)+"&carparks_to="+encodeURIComponent(carparks_to)+"&since_ts="+encodeURIComponent(since_ts)+"&sort="+encodeURIComponent(sort)+"&page_size="+encodeURIComponent(page_size)+"&saved="+encodeURIComponent(saved)+"&property_name="+encodeURIComponent(property_name)+"&bldg_area_range_from="+encodeURIComponent(bldg_area_range_from)+"&bldg_area_range_to="+encodeURIComponent(bldg_area_range_to)+"&land_from="+encodeURIComponent(land_from)+"&land_to="+encodeURIComponent(land_to)+"&exclude_sold="+encodeURIComponent(exclude_sold)+"&include_unset_land="+encodeURIComponent(include_unset_land)+"&exclude_rented="+encodeURIComponent(exclude_rented);
	
    if(business_type.length>0){
		for(i=0;i<business_type.length;i++){
			str+="&business_type[]="+encodeURIComponent(business_type[i]);
		}
	}
	else{
		str+="&business_type[]=";
	}
	if(commercial_type.length>0){
		for(i=0;i<commercial_type.length;i++){
			str+="&commercial_type[]="+encodeURIComponent(commercial_type[i]);
		}
	}
	else{
		str+="&commercial_type[]=";
	}
	if(residential_type.length>0){
		for(i=0;i<residential_type.length;i++){
			str+="&residential_type[]="+encodeURIComponent(residential_type[i]);
		}
	}
	else{
		str+="&residential_type[]=";
	}
	if(rural_type.length>0){
		for(i=0;i<rural_type.length;i++){
			str+="&rural_type[]="+encodeURIComponent(rural_type[i]);
		}
	}
	else{
		str+="&rural_type[]=";
	}
	if(suburb.length>0){
		for(i=0;i<suburb.length;i++){
			str+="&suburb[]="+encodeURIComponent(suburb[i]);
		}
	}
	else{
		str+="&suburb[]=";
	}
	//map pos stuff
	var tmp_lat=map.getBounds().getCenter().lat();
	var tmp_lng=map.getBounds().getCenter().lng();
	var tmp_zoom=map.getZoom();
	var tmp_type=map.getCurrentMapType().getName();
	
	if(!skip_map_positioning){
		str+="&center_lat="+encodeURIComponent(tmp_lat)+"&center_lng="+encodeURIComponent(tmp_lng)+"&z="+encodeURIComponent(tmp_zoom)+"&map_radius="+encodeURIComponent(getSurroundingRaduisForZoom())+"&active="+encodeURIComponent(active)+"&map_type="+encodeURIComponent(tmp_type);
		
		//save a cookie of the maps current status- center_lat|center_lng|z|active|map_type
		Cookie.set('map', tmp_lat+"|"+tmp_lng+"|"+tmp_zoom+"|"+active+"|"+tmp_type);
	}
	//flag to keep the cookie
	str+="&lc=1";
	
	return str;
}
function initialize_map() {
	if (GBrowserIsCompatible()) {
		//we are not confined to 512px any more, resize map
		$('map').setStyle('width','590px');
		$('map_legend').setStyle('width','574px');
		map = new GMap2(document.getElementById("map"));
		//overview map is causing errors- commented out until google resolve the issue
		//map.addControl(new GOverviewMapControl());
		map.setCenter(new GLatLng(-27.916767, 133.339844), 3);
		map.enableDoubleClickZoom();
		
		GEvent.addListener(map, 'infowindowclose', function(){
			if(!keep_active){
				active='';
			}
		});
		
		mgr = new MarkerManager(map);
		load_markers("/branch/listing_map_xml.php?"+getQueryString(true), true, z>0);
	}
}
function refine_search(){
	//overwrite the global variables
	if($('rs_price_from_val')){
		price_from=$('rs_price_from_val').value
	}
	if($('rs_price_to_val')){
		price_to=$('rs_price_to_val').value
	}
	if($('rs_bedrooms_from_val')){
		bedrooms_from=$('rs_bedrooms_from_val').value
	}
	if($('rs_bedrooms_to_val')){
		bedrooms_to=$('rs_bedrooms_to_val').value
	}
	if($('rs_bathrooms_from_val')){
		bathrooms_from=$('rs_bathrooms_from_val').value
	}
	if($('rs_bathrooms_to_val')){
		bathrooms_to=$('rs_bathrooms_to_val').value
	}
	if($('rs_land_from_val')){
		land_from=$('rs_land_from_val').value
	}
	if($('rs_land_to_val')){
		land_to=$('rs_land_to_val').value
	}
	if($('rs_bldg_area_range_from_val')){
		bldg_area_range_from=$('rs_bldg_area_range_from_val').value;
	}
	if($('rs_bldg_area_range_to_val')){
		bldg_area_range_to=$('rs_bldg_area_range_to_val').value;
	}
	
	if($('rs_include_unset_land')){
		include_unset_land=$('rs_include_unset_land').getValue();
	}
	if($('rs_rural_type')){
		var types=""+$('rs_rural_type').getValue();
		rural_type=types.split(',');
	}
	if($('rs_search_residential_type')){
		var types=""+$('rs_search_residential_type').getValue();
		residential_type=types.split(',');
	}
	if($('rs_business_type')){
		var types=""+$('rs_business_type').getValue();
		business_type=types.split(',');
	}
	if($('rs_commercial_type')){
		var types=""+$('rs_commercial_type').getValue();
		commercial_type=types.split(',');
	}
	if($('rs_carparks_from_val')){
		carparks_from=$('rs_carparks_from_val').value;
	}
	//and reload the markers
	load_markers("/branch/listing_map_xml.php?"+getQueryString(), false, true);
}
function createRegionMarker(marker_data) {
	var id= marker_data.getAttribute("id");
	var title= marker_data.getAttribute("name");
	var drill_down= marker_data.getAttribute("drill_down");
	var parent= marker_data.getAttribute("parent");
	var point = new GLatLng(parseFloat(marker_data.getAttribute("latitude")),
							parseFloat(marker_data.getAttribute("longitude")));
	marker_options = { title:title };
	var marker = new GMarker(point, marker_options);
	
	if(parent=='1'){
		//one of the state regions without sub regions. Dont zoom in as much
		GEvent.addListener(marker, 'click', function(){
			map.setCenter(marker.getPoint(), 6);
		});
		//add the marker to the array.
		region_markers.push(marker);
	}
	else{
		//lower level region marker
		GEvent.addListener(marker, 'click', function(){
			//we do not need to restrict by region for specific lists (auctions etc). price_to will not be set for these
			if(window.price_to){
				region= id;
				load_markers("/branch/listing_map_xml.php?"+getQueryString(), false, false);
			}
			map.setCenter(marker.getPoint(), 10);
		});
		//add the marker to the array
		region_markers.push(marker);
	}
}

function createListingMarker(marker_data, load_window) {
	var id= marker_data.getAttribute("id");
	var title= marker_data.getAttribute("address");
	var realist_type= marker_data.getAttribute("realist_type");
	var point = new GLatLng(parseFloat(marker_data.getAttribute("latitude")),
							parseFloat(marker_data.getAttribute("longitude")));
	
	marker_options = { icon:listing_icons[marker_data.getAttribute("realist_type")], title:title };
	
	var marker = new GMarker(point, marker_options);
	
	GEvent.addListener(marker, 'click', function(){
		active=id;
		GDownloadUrl("/branch/listing_map_property_detail.php?id=" + id + "&branch_id="+ encodeURIComponent(branch_id) + "&portal_id=" + encodeURIComponent(portal_id) + "&search_type=" + encodeURIComponent(search_type) + "&search_params=" + encodeURIComponent(getQueryString()), function(data) {
			marker.openInfoWindowHtml(data);
		});
	});
	if(load_window && id==active){
		post_marker_load=function(){
			GEvent.trigger(marker, 'click');
		};
	}
	
	listing_markers.push(marker);
}

function load_markers(url, init, manual_center){
	//display the loading overlay
	$('map_cover').className='go';
	GDownloadUrl(url, function(data) {
		var xml = GXml.parse(data);
		var markers = xml.documentElement.getElementsByTagName("marker");
		keep_active=true;
		//clear the existing markers
		mgr.clearMarkers();
		keep_active=false;
		region_markers.length = 0;
		listing_markers.length = 0;
		var bounds=false;
		
		//load the markers in again
		var n=markers.length;
		var k=n;
		if(n>0){
			do{
				var i=k-n;
				if(markers[i].getAttribute("type")=='listing'){
					createListingMarker(markers[i], manual_center);
				}
				else if(markers[i].getAttribute("type")=='property_region'){
					createRegionMarker(markers[i]);
				}
			}
			while(--n);
		}
		if(init){
			//set the map center and zoom
			if(manual_center){
				map.setCenter(new GLatLng(center_lat, center_lng), z);
				changeMapType(map_type);
			}
			else if(listing_markers.length==1){
				map.setCenter(listing_markers[0].getPoint(), 15);
			}
			else{
				//create a bound object showing australia
				var restrict_to_bounds=new GLatLngBounds(new GLatLng(-43.612217,153.808594), new GLatLng(-43.612217,153.808594));
				restrict_to_bounds.extend(new GLatLng(-10.185187,112.807617));
				
				//set the map position/zoom to fit the listings in
				var n=listing_markers.length;
				var k=n;
				if(n>1){
					do{
						var i=k-n;
						var point=listing_markers[i].getPoint();
						//only zoom out for markers within the state bounds
						if(restrict_to_bounds.containsLatLng(point)){
							if(!bounds){
								bounds=new GLatLngBounds(point, point);
							}
							else if (!bounds.containsLatLng(point)){
								bounds.extend(point);
							}
						}
					}
					while(--n);
					if(bounds){
						map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
					}
				}
			}
		}
		
		mgr.addMarkers(region_markers,0, 8);
		mgr.addMarkers(listing_markers, 9, 17);

		mgr.refresh();
		//hide the loading overlay
		$('map_cover').className='';
		
		//delay the function call to avoid errors
		setTimeout(post_marker_load, 1000);
		//reset the function
		post_marker_load=function(){};
		
		if(listing_markers.length==0){
			map.addControl(no_listings);
		}
		else{
			map.removeControl(no_listings);
		}
	});
}
function changeMapType(map_type){
	if(map_type=='Satellite'){
		map.setMapType(G_SATELLITE_MAP);
	}
	else if(map_type=='Hybrid'){
		map.setMapType(G_HYBRID_MAP);
	}
	else{
		map.setMapType(G_NORMAL_MAP);
	}
}
function getSurroundingRaduisForZoom(){
	return Math.round(map.getCenter().distanceFrom(map.getBounds().getNorthEast()))/1000;
}

function NoListingsControl() {
}
NoListingsControl.prototype = new GControl();

NoListingsControl.prototype.initialize = function(map) {
	var cont = document.createElement("div");
	cont.style.color = "#000000";
	cont.style.backgroundColor = "white";
	//cont.style.font = "small Arial";
	cont.style.border = "1px solid black";
	cont.style.padding = "5px";
	cont.style.textAlign = "center";
	cont.style.width = "560px";
	cont.appendChild(document.createTextNode("Your search returned no results."));
	cont.appendChild(document.createElement("br"));
	cont.appendChild(document.createTextNode("Try refining your search, or "));
	var link= document.createElement("a");
	link.href='/branch/sale_re.php?branch_id='+encodeURIComponent(branch_id)+"&portal_id="+encodeURIComponent(portal_id)+'&sale_type='+encodeURIComponent(sale_type);
	link.appendChild(document.createTextNode("click here to search again"));
	cont.appendChild(link);
	map.getContainer().appendChild(cont);
	return cont;
}

NoListingsControl.prototype.getDefaultPosition = function() {
	return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(10, 172));
}
var no_listings=new NoListingsControl();

