var myProperty = false;
var propertyLatitude;
var propertyLongitude;

var propertyStreetViewLoaded = false;
var propertyStreetViewLoaded2 = false;

var maptypes;
var maptypes2;
// 1 for map 2 for stret view
var currentMapSwitcher = 1;
var currentMapSwitcher2 = 1;

var gmap;
var gmap2;

var myPano;   
var myPano2;

var client;
var nextPanoId;

var streetviewProperty;
var streetviewFlash;
var streetviewDes;

var viewMarker;
var previousMarkerLocation;

// Get property marker
function propertyMarker(latitude, longitude, listing_id, name, price, thumbnail, listing_sub_type)
{
	var marker 			= new GMarker(new GLatLng(latitude, longitude), houseIcon());
	var mapProperty 	= $.DIV({className: 'mapProperty'});
	var thumbnail 		= $.DIV ({className: 'thumbnail'}, $.A({href: '/' +listing_id}, $.IMG({src: thumbnail, width: 80, height: 60, alt: ''})));

	$(mapProperty).append(thumbnail);

	var details = $.DIV({className: 'details'});

	$(details).append($.A({ href: '/' +listing_id }, name));
	$(details).append($.BR());


	if(listing_sub_type) {
		$(details).append($.SPAN({className: 'listing_sub_type'}, listing_sub_type));
		$(details).append($.BR());
	}

	if(price) {
		$(details).append($.SPAN({className: 'price'}, price));
		$(details).append($.BR());
	}

	var url 		= (myProperty) ? '/account/saved-listings?delete=' :  '/account/save-listing?listing_id=';
	var label 		= (myProperty) ? 'Delete from My Property' :  'Add to My Property';
	var favourite 	= $.A({href:url+listing_id,className:'favourite'}, label);

	$(favourite).click(function()
	{
		if(!myProperty) {
			return save_listing(this,listing_id);
		}
		return confirm_redirect(url+listing_id, 'Are you sure you want to delete this saved listing?');
	});

	$(details).append($(favourite));
	$(mapProperty).append($(details));

	GEvent.addListener(marker, 'click', function() {
		marker.openInfoWindowHtml(mapProperty)
	});

	return marker;
}

function propertyChartMarker(latitude, longitude, street, suburb, city)
{
	var marker 			= new GMarker(new GLatLng(latitude, longitude), houseIcon());
	var mapProperty 	= $.DIV({className: 'mapProperty'});
	
	var details = $.DIV({className: 'details'});
	
	$(details).append($.SPAN({}, street));
	$(details).append($.BR());
	$(details).append($.SPAN({}, suburb));
	$(details).append($.BR());
	$(details).append($.SPAN({}, city));
	
	$(mapProperty).append($(details));

	GEvent.addListener(marker, 'click', function() {
		marker.openInfoWindowHtml(mapProperty)
	});

	return marker;
}

// Get office marker
function officeMarker(latitude, longitude, office_id, name, street_address, city)
{
	var marker 		= new GMarker(new GLatLng(latitude, longitude), houseIcon());
	var mapOffice 	= $.DIV({className: 'mapOffice'});
	var details 	= $.DIV({className: 'details'});

	$(details).append($.A({ href: '/offices/' +office_id }, name));
	$(details).append($.BR());
	$(details).append($.SPAN({}, street_address));
	$(details).append($.BR());
	$(details).append($.SPAN({}, city));

	$(mapOffice).append($(details));

	GEvent.addListener(marker, 'click', function() {
		marker.openInfoWindowHtml(mapOffice)
	});

	return marker;
}

// set school marker
function schoolMarker(latitude, longitude, name, distance, suburb, street, authority, institution_type, icon_type, zoned) {

	var marker 		= new GMarker(new GLatLng(latitude, longitude), schoolIcon(icon_type));
	var mapSchool 	= $.DIV({className: 'mapSchool'});
	var details 	= $.DIV({className: 'details'});

	$(details).append($.SPAN({}, name + " (" + distance + ")"));
	$(details).append($.BR());
	$(details).append($.SPAN({}, street + ", " + suburb));
	$(details).append($.BR());
	$(details).append($.SPAN({}, authority + " " + institution_type));
	if(zoned){
		$(details).append($.BR());
		$(details).append($.SPAN({}, "Zoned"));
	}
	$(mapSchool).append($(details));

	GEvent.addListener(marker, 'click', function() {
		marker.openInfoWindowHtml(mapSchool)
	});

	return marker;

}

// set shop marker
function shopMarker(latitude, longitude, name, address, opening_hours, phone, icon_type) {

	var marker 		= new GMarker(new GLatLng(latitude, longitude), shopIcon(icon_type));
	var mapSchool 	= $.DIV({className: 'mapSchool'});
	var details 	= $.DIV({className: 'details'});

	$(details).append($.SPAN({}, name));
	if(address != ''){
		$(details).append($.BR());
		$(details).append($.SPAN({}, address));
	}
	if(opening_hours != ''){
		$(details).append($.BR());
		$(details).append($.SPAN({}, opening_hours));
	}
	if(phone != ''){
		$(details).append($.BR());
		$(details).append($.SPAN({}, phone));
	}
	
	$(mapSchool).append($(details));

	GEvent.addListener(marker, 'click', function() {
		marker.openInfoWindowHtml(mapSchool)
	});

	return marker;

}

// set restaurant marker
function restaurantMarker(latitude, longitude, name, address, url, phone, menu_url, icon_type) {

	var marker			= new GMarker(new GLatLng(latitude, longitude), shopIcon(icon_type));
	var mapRestaurant	= $.DIV({className: 'mapRestaurant'});
	var details			= $.DIV({className: 'details'});

	if(url) {
		$(details).append($.A({href: url}, name));
	} else {
		$(details).append($.SPAN({}, name));
	}
	if(address != ''){
		$(details).append($.BR());
		$(details).append($.SPAN({}, address));
	}
	if(menu_url != ''){
		$(details).append($.BR());
		$(details).append($.A({href: menu_url}, "Menu"));
	}
	if(phone != ''){
		$(details).append($.BR());
		$(details).append($.SPAN({}, phone));
	}
	
	$(mapRestaurant).append($(details));
	
	GEvent.addListener(marker, 'click', function() {
		marker.openInfoWindowHtml(mapRestaurant)
	});

	return marker;

}

// set shop marker
function communityMarker(latitude, longitude, name) {

	var marker 		= new GMarker(new GLatLng(latitude, longitude), shopIcon(10));
	var mapSchool 	= $.DIV({className: 'mapSchool'});
	var details 	= $.DIV({className: 'details'});

	$(details).append($.SPAN({}, name));
	$(mapSchool).append($(details));

	GEvent.addListener(marker, 'click', function() {
		marker.openInfoWindowHtml(mapSchool)
	});

	return marker;

}

// Get school marker
function nearbySaleMarker(latitude, longitude, address, sale_price, capital_value, floor_area, sale_date, type) {

	var marker 		= new GMarker(new GLatLng(latitude, longitude), schoolIcon());
	var mapSchool 	= $.DIV({className: type});
	var details 	= $.DIV({className: 'details'});

	$(details).append($.SPAN({}, address));
	$(details).append($.BR());
	$(details).append($.SPAN({}, 'Sale Price: ' + sale_price));
	$(details).append($.BR());
	$(details).append($.SPAN({}, 'Capital Value: ' + capital_value));
	$(details).append($.BR());
	$(details).append($.SPAN({}, 'Floor Area: ' + floor_area));
	$(details).append($.BR());
	$(details).append($.SPAN({}, 'Sale Date: ' + sale_date));

	$(mapSchool).append($(details));

	GEvent.addListener(marker, 'click', function() {
		marker.openInfoWindowHtml(mapSchool)
	});

	return marker;

}

// Get sale marker
function saleMarker(latitude, longitude, address, date, amount, cv_ratio, created_at) {

	var marker 		= new GMarker(new GLatLng(latitude, longitude), saleIcon());
	var mapSale 	= $.DIV({className: 'mapSale'});
	var details 	= $.DIV({className: 'details'});

	$(details).append($.SPAN({}, address));
	$(details).append($.BR());
	$(details).append($.SPAN({}, amount + " on" + date));
	$(details).append($.BR());
	$(details).append($.SPAN({}, "CV Ratio: " + cv_ratio));

	$(mapSale).append($(details));

	GEvent.addListener(marker, 'click', function() {
		marker.openInfoWindowHtml(mapSale)
	});

	return marker;

}

// Get office marker
function summaryMarker(gmap, params, latitude, longitude, id, name, level)
{
	var marker 		= new GMarker(new GLatLng(latitude, longitude), locationIcon(level));

	GEvent.addListener(marker, 'click', function() {
		loadListings(gmap, getListingParams(level, id, params));
	});

	return marker;
}

function reportLocalSalesMarker(latitude, longitude, address, age, land_area, floor_area, construction, gv_valuation, gross_sale, net_sale, chattels, sale_date, sequence) {
	var latlng = new GLatLng(latitude, longitude);
	var icon = reportLocalSalesIcon();
 	opts = { 
	  "icon": icon,
	  "clickable": true,
	  "labelText": sequence,
	  "labelOffset": new GSize(-14, -19)
	};

	var marker 		= new LabeledMarker(latlng, opts);

	var mapLocalSale 	= $.DIV({className: 'mapLocalSale'});
	var details 	= $.DIV({className: 'details'});
	$(details).append($.SPAN({}, address));
	$(details).append($.BR());
	$(details).append($.SPAN({}, "Government Valuation: " + gv_valuation));
	$(details).append($.BR());
	$(details).append($.SPAN({}, "Gross Sale: " + gross_sale));
	$(details).append($.BR());
	$(details).append($.SPAN({}, "Net Sale: " + net_sale));
	$(details).append($.BR());
	$(details).append($.SPAN({}, "Chattels: " + chattels));
	$(details).append($.BR());
	$(details).append($.SPAN({}, "Sale Date: " + sale_date));
	$(mapLocalSale).append($(details));
	
	var mapLocalSaleB 	= $.DIV({className: 'mapLocalSale'});
	var detailsB 	= $.DIV({className: 'details'});
	$(detailsB).append($.SPAN({}, address));
	$(detailsB).append($.BR());
	$(detailsB).append($.SPAN({}, "Building Age: " + gv_valuation));
	$(detailsB).append($.BR());
	$(detailsB).append($.SPAN({}, "Construction: " + construction));
	$(detailsB).append($.BR());
	$(detailsB).append($.SPAN({}, "Land Area: " + land_area));
	$(detailsB).append($.BR());
	$(detailsB).append($.SPAN({}, "Floor Area: " + floor_area));
	$(mapLocalSaleB).append($(detailsB));
	
	GEvent.addListener(marker, "click", function() {
      marker.openInfoWindowTabsHtml([new GInfoWindowTab('Sales Info', mapLocalSale), new GInfoWindowTab('Property Info', mapLocalSaleB)]);
    });
        
	return marker;
}

function reportSchoolsMarker(latitude, longitude, name, street, suburb, region, phone, distance, decile, type, authority, gender, sequence, icon_type){
	var latlng = new GLatLng(latitude, longitude);
	var icon = schoolIcon(icon_type);
 	opts = { 
	  "icon": icon,
	  "clickable": true,
	  "labelText": sequence,
	  "labelOffset": new GSize(-15, -22)
	};

	var marker 		= new LabeledMarker(latlng, opts);

	var mapSchoolA 	= $.DIV({className: 'mapSchool'});
	var details 	= $.DIV({className: 'details'});
	$(details).append($.SPAN({}, name));
	$(details).append($.BR());
	$(details).append($.SPAN({}, "Distance: " + distance));
	$(details).append($.BR());
	$(details).append($.SPAN({}, "Decile Rating: " + decile));
	$(details).append($.BR());
	if(icon_type == 1){
		$(details).append($.SPAN({}, "School Type: " + type));
	}
	else{
		$(details).append($.SPAN({}, "Age Range: " + type));
	}
	$(details).append($.BR());
	$(details).append($.SPAN({}, "Authority: " + authority));
	$(details).append($.BR());
	$(details).append($.SPAN({}, "Gender: " + gender));
	$(mapSchoolA).append($(details));
	
	var mapSchoolB 	= $.DIV({className: 'mapSchool'});
	var detailsB 	= $.DIV({className: 'details'});
	$(detailsB).append($.SPAN({}, "Address: " + street));
	$(detailsB).append($.BR());
	$(detailsB).append($.SPAN({}, suburb));
	$(detailsB).append($.BR());
	$(detailsB).append($.SPAN({}, region));
	$(detailsB).append($.BR());
	$(detailsB).append($.SPAN({}, "Phone: " + phone));
	$(mapSchoolB).append($(detailsB));
	
	GEvent.addListener(marker, "click", function() {
      marker.openInfoWindowTabsHtml([new GInfoWindowTab('School Info', mapSchoolA), new GInfoWindowTab('Contact Info', mapSchoolB)]);
    });
        
	return marker;
}

// House icon
function reportLocalSalesIcon (){
	var icon 				= new GIcon();
	icon.image 				= '/img/gmap/house.png';
	icon.iconSize 			= new GSize(22, 26);
	icon.iconAnchor 		= new GPoint(9, 23);
	icon.infoWindowAnchor 	= new GPoint(10, 23);
	icon.infoShadowAnchor 	= new GPoint(10, 23);
	return icon;
}

// House icon
function houseIcon ()
{
	var icon 				= new GIcon();
	icon.image 				= '/img/gmap/house-local.png';
	//icon.shadow 			= '/img/gmap/shadow.png';
	//icon.iconSize 			= new GSize(38, 23);
	//icon.shadowSize 		= new GSize(38, 23);
	icon.iconSize 			= new GSize(22, 26);
	icon.iconAnchor 		= new GPoint(9, 23);
	icon.infoWindowAnchor 	= new GPoint(10, 23);
	icon.infoShadowAnchor 	= new GPoint(10, 23);

	return icon;
}

// Location icon
function locationIcon (level)
{
	var icon 				= new GIcon();
	icon.image 				= (level == 'district') ? '/img/gmap/district.png' : '/img/gmap/suburb.png';
	icon.shadow 			= '/img/gmap/shadow.png';
	icon.iconSize 			= new GSize(38, 23);
	icon.shadowSize 		= new GSize(38, 23);
	icon.iconAnchor 		= new GPoint(9, 23);
	icon.infoWindowAnchor 	= new GPoint(10, 23);
	icon.infoShadowAnchor 	= new GPoint(10, 23);

	return icon;
}

// School icon
function schoolIcon (iconType)
{
	//default-school.png primary-school.png secondary-school.png shop.png
	//default-school-shadow.png primary-school-shadow.png secondary-school-shadow.png shop-shadow.png
	if (iconType == null){
	   iconType = 1;
	}
	
	var icon = new GIcon()
	if(iconType == 2 || iconType == 'primaryIntermediate'){
		icon.image = '/img/gmap/primary-school.png';
	}
	else if(iconType == 3 || iconType == 'secondary'){
		icon.image = '/img/gmap/secondary-school.png';
	}
	else if(iconType == 4 || iconType == 'ece'){
		icon.image = '/img/gmap/default-school.png';
	}
	else if(iconType == 5 || iconType == 'tertiary'){
		icon.image = '/img/gmap/tertiary-school.png';
	}
	else if(iconType == 'zoned'){
		icon.image = '/img/gmap/zoned-school.png';
	}
	else{
		icon.image = '/img/gmap/default-school.png';
	}
	 	
	icon.iconSize 			= new GSize(29, 24);
	//icon.shadowSize 		= new GSize(38, 23);
	icon.iconAnchor 		= new GPoint(9, 23);
	icon.infoWindowAnchor 	= new GPoint(10, 23);
	icon.infoShadowAnchor 	= new GPoint(10, 23);
	
	return icon;
}

function shopIcon (iconType)
{
	//default-school.png primary-school.png secondary-school.png shop.png
	//default-school-shadow.png primary-school-shadow.png secondary-school-shadow.png shop-shadow.png
	if (iconType == null){
	   iconType = 1;
	}
	
	var icon 				= new GIcon();	
	switch(iconType){
	case 2:
	  icon.image 			= '/img/gmap/eating-out.png';
	  icon.shadow 			= '/img/gmap/eating-out-shadow.png';
	  icon.iconSize 		= new GSize(29, 24);
	  break;    
	case 10:
	  icon.image 			= '/img/gmap/center-point.png';
	  icon.iconSize 		= new GSize(29, 24);
	  break;    
	default:
	  icon.image 			= '/img/gmap/shop.png';
	  icon.shadow 			= '/img/gmap/shop-shadow.png';
	  icon.iconSize 		= new GSize(27, 27);
	}		
	icon.iconAnchor 		= new GPoint(9, 23);
	icon.infoWindowAnchor 	= new GPoint(10, 23);
	icon.infoShadowAnchor 	= new GPoint(10, 23);
	
	return icon;
}

// Sale icon
function saleIcon ()
{
	var icon 				= new GIcon();
	icon.image 				= '/img/gmap/suburb.png';
	icon.shadow 			= '/img/gmap/shadow.png';
	icon.iconSize 			= new GSize(38, 23);
	icon.shadowSize 		= new GSize(38, 23);
	icon.iconAnchor 		= new GPoint(9, 23);
	icon.infoWindowAnchor 	= new GPoint(10, 23);
	icon.infoShadowAnchor 	= new GPoint(10, 23);

	return icon;
}

// Get listing params
function getListingParams(type, id, params)
{
	switch(type) {
		case 'listing_type':
			params['listing_type_id'] 		= id;
			params['listing_sub_type_id'] 	= false;
			break;
		case 'listing_sub_type':
			params['listing_sub_type_id'] 	= id;
			break;
		case 'region':
			params['region_id'] 			= id;
			params['district_id'] 			= false;
			params['suburb_id'] 			= false;
			break;
		case 'district':
			params['district_id'] 			= id;
			params['suburb_id'] 			= false;
			break;
		case 'suburb':
			params['suburb_id'] 			= id;
			break;
	}
	
	return params;
}
//street view part error handler
function handleNoFlash(errorCode) {
  if (errorCode == FLASH_UNAVAILABLE) {
    alert("Error: Flash doesn't appear to be supported by your browser");
    return;
  }
}


function showPanoData(panoData) {
	if (panoData.code != 200) {
	  GLog.write('showPanoData: Server rejected with code: ' + panoData.code);
	  return;
	}
	nextPanoId = panoData.links[0].panoId;
	myPano.setLocationAndPOV(panoData.location.latlng);
    GEvent.addListener(myPano, "error", handleNoFlash);
}


function next() {
  // Get the next panoId
  // Note that this is not sophisticated. At the end of the block, it will get stuck
  panoClient.getPanoramaById(nextPanoId, showPanoData);
}

function streetViewInit(response){
 // can not find user position on streetview
 if (response.code != 200){
 	viewMarker.setLatLng(previousMarkerLocation);
 }
 else{
 	var latlng = new GLatLng(response.Location.lat, response.Location.lng);
	// get the last marker and calculate angle to turn by streetview
	panorama.setLocationAndPOV(viewMarker.getLatLng());
 	previousMarkerLocation = viewMarker.getLatLng();
 }
}
 
function openPanoramaBubble(){
 	streetviewProperty 		= $.DIV({className: 'streetviewProperty'});
	streetviewDes 			= $.DIV ({className: 'streetviewDes'});
	streetviewFlash 		= $.DIV({className: 'streetviewFlash'});
	$(streetviewProperty).append(streetviewDes);
	$(streetviewProperty).append(streetviewFlash);
	    
 	// marker opening the normal-sized infoWindow
 	viewMarker.openInfoWindow(streetviewProperty);
 	GEvent.clearListeners(gmap.getInfoWindow(), "click");
 	
 	panorama = new GStreetviewPanorama(streetviewFlash);
 	client.getNearestPanorama(viewMarker.getLatLng(), streetViewInit);
} 
// Init google map
function googleMap(element, latitude, longitude, zoom, large)
{
	if(GBrowserIsCompatible()) {
		var mapCenter = new GLatLng(latitude, longitude);
		
		gmap = new GMap2(document.getElementById(element));
		gmap.setCenter(mapCenter, zoom);

		if(large) {
			gmap.addControl(new GLargeMapControl());
		}
		else {
			gmap.addControl(new GSmallMapControl());
		}
		maptypes = gmap.getMapTypes();
		init_control_tab();
	
		gmap.setMapType(maptypes[0]);
		
		set_property_point(latitude, longitude);
		InitializeStreetView();
		
		return gmap;
	}

	$('#'.element).html('Maps are not compatible with your browser.');

	return false;
}

function googleMapReport(element, latitude, longitude, zoom, large)
{
	if(GBrowserIsCompatible()) {
		var mapCenter = new GLatLng(latitude, longitude);
		
		gmap = new GMap2(document.getElementById(element));
		gmap.setCenter(mapCenter, zoom);

		if(large) {
			gmap.addControl(new GLargeMapControl());
		}
		else {
			gmap.addControl(new GSmallMapControl());
		}
		maptypes = gmap.getMapTypes();
		init_control_tab_report();
	
		gmap.setMapType(maptypes[0]);
		
		set_property_point(latitude, longitude);
		InitializeStreetViewReport();
		
		return gmap;
	}

	$('#'.element).html('Maps are not compatible with your browser.');

	return false;
}

function googleMapReport2(element, latitude, longitude, zoom, large)
{
	if(GBrowserIsCompatible()) {
		var mapCenter = new GLatLng(latitude, longitude);
		
		gmap2 = new GMap2(document.getElementById(element));
		gmap2.setCenter(mapCenter, zoom);

		if(large) {
			gmap2.addControl(new GLargeMapControl());
		}
		else {
			gmap2.addControl(new GSmallMapControl());
		}
		maptypes2 = gmap2.getMapTypes();
		init_control_tab_report2();
	
		gmap2.setMapType(maptypes2[0]);
		
		set_property_point(latitude, longitude);
		InitializeStreetViewReport2();
		
		return gmap2;
	}

	$('#'.element).html('Maps are not compatible with your browser.');

	return false;
}

// Add schools
function addSchools(gmap, schools)
{
	var mgr 		= new MarkerManager(gmap);
	var bounds 		= new GLatLngBounds;
	var zoom		= [12, 16];

	addMarkers (gmap, mgr, bounds, null, schools, zoom, "school");
}

// Add sales
function addSales(gmap, sales)
{
	var mgr 		= new MarkerManager(gmap);
	var bounds 		= new GLatLngBounds;
	var zoom		= [12, 16];

	addMarkers (gmap, mgr, bounds, null, sales, zoom, "sale");
}

// Load listings
function loadListings(gmap, params)
{
	var mgr 		= new MarkerManager(gmap);
	var bounds 		= new GLatLngBounds;

	function resultListingParser(data) {
		$('#ajaxListings').html(data);
	}

	function listingParser(data) {

		var json = eval("(" + data + ")");

		$(document).attr({title: json.title});
		$('h1:first').html(json.title);
		$('#output').html('');
		
		// There are no results to display
		if(json.location.markers.length == 0) {
			
			$('#output').append('<p class="error">There are no properties that match your criteria.</p>');
			return;
		}
		
		// We need to set params in global scope
		for(var prop in search_params) {
			if(params[prop]) search_params[prop] = params[prop];
		}
		
		// Load markers
		gmap.clearOverlays();
		addMarkers(gmap, mgr, bounds, params, json.location.markers, json.location.zoom, json.location.marker_type);
		toggle_filter_menu(json.location.marker_type);
	}

	params['geocoded_only'] = 1;

	// listings json
	$.post (
		'/ajax/listings?format=json',
		params,
		listingParser
	);

	// listings html
	$.post (
		'/ajax/listings?format=html',
		params,
		resultListingParser
	);

	$('div#loading').hide();
}

// Add markers to map
function addMarkers(gmap, mgr, bounds, params, locations, zoom, marker_type)
{
    var markers = [];

    for(var i=0; i<locations.length; i++) {

		var location = locations[i];

    	if(null == location.latitude) continue;

		switch(marker_type) {
			case 'summary':
				var marker = summaryMarker(gmap, params, location.latitude, location.longitude, location.id, location.name, location.level);
				break;
			case 'office':
				var marker = officeMarker(location.latitude, location.longitude, location.id, location.name, location.street_address, location.city);
				break;
			case 'school':
				var marker = schoolMarker(location.latitude, location.longitude, location.id, location.name, location.distance, location.street, location.suburb, location.authority, location.student_gender)
				break;
			case 'sale':
				var marker = saleMarker(location.latitude, location.longitude, location.address, location.date, location.amount, location.cv_ratio);
				break;
			default:
				var marker = propertyMarker(location.latitude, location.longitude, location.id, location.name, location.price, location.thumbnail, location.listing_sub_type);
				break;
		}

		bounds.extend(marker.getPoint());
		markers.push(marker);
	}

   	mgr.addMarkers(markers, zoom[0], zoom[1]);
  	mgr.refresh();

	gmap.setCenter(bounds.getCenter(), (gmap.getBoundsZoomLevel(bounds) > zoom[1]) ? zoom[1] : gmap.getBoundsZoomLevel(bounds));
}

/**
 * Load google map asynchronously
 *
 */
function loadMap()
{
	// Init gmap
	var gmap 		= googleMap('listingsMap',-41.283333,174.783333,5,true);
	var mgr 		= new MarkerManager(gmap);
	var bounds 		= new GLatLngBounds;

	function listingParser(data)
	{
		json = eval("(" + data + ")");

		if(json.location.markers.length == 0) {
			$(output).append('<p class="error">There are no properties that match your criteria.</p>');
			return;
		}

		addMarkers(gmap, mgr, bounds, params, json.location.markers, json.location.zoom, json.location.marker_type);
	}

	// Set params object
	var params 			= search_params;
	params.geocoded 	= 1;

	// Get listings
	$.post(
		'/ajax/listings?format=json',
		params,
		listingParser
	);

	$('div#loading').hide();
}

function changeOrder(gmap, params, order)
{
	params['order_by'] = order;
	loadListings(gmap, params);
}

function switchNormalMap(){
	$("#listingStreetviewMap").hide();
	$("#listingMap").show();
}

function switchStreetviewMap(){
	$("#listingMap").hide();
	$("#listingStreetviewMap").show();
	if(!propertyStreetViewLoaded){
		InitializeStreetView();
	}
}

function set_property_point(latitude, longitude){
	propertyLatitude = latitude;
	propertyLongitude = longitude;
}

function InitializeStreetView(){
	client = new GStreetviewClient();
	var propertylatlong = new GLatLng(propertyLatitude,propertyLongitude);
	if(propertylatlong){
		client.getNearestPanorama(propertylatlong, propertyStreetViewInit);
	}
}
 
function propertyStreetViewInit(response){
 // can not find user position on streetview
 if (response.code != 200){
 	//handle the exception here
 	$("#showStreetViewTab").remove();
 }
 else{
 	var latlng = new GLatLng(response.Location.lat, response.Location.lng);
 	myPano = new GStreetviewPanorama(document.getElementById("listingStreetviewMap"));
	myPano.setLocationAndPOV(latlng);
	propertyStreetViewLoaded = true;
	currentMapSwitcher = 2;
	GEvent.addListener(myPano, "error", handleNoFlash);
 }
}

function init_control_tab(){
	if($("#listingMap") && $("#showMapTab")){
	    $("#showMapTab").click(function(){if(currentMapSwitcher > 1){switchNormalMap();} gmap.setMapType(G_NORMAL_MAP);});
	}
	if($("#listingMap") && $("#showStreetViewTab")){
	    $("#showStreetViewTab").click(switchStreetviewMap);
	}
	if($("#listingMap") && $("#satelliteMapTab")){
	    $("#satelliteMapTab").click(function(){if(currentMapSwitcher > 1){switchNormalMap();} gmap.setMapType(G_SATELLITE_MAP);});
	}
	if($("#listingMap") && $("#hybridMapTab")){
	    $("#hybridMapTab").click(function(){if(currentMapSwitcher > 1){switchNormalMap();} gmap.setMapType(G_HYBRID_MAP);});
	}
	if($("#listingMap") && $("#terrainMapTab")){
	    $("#terrainMapTab").click(function(){if(currentMapSwitcher > 1){switchNormalMap();} gmap.setMapType(G_PHYSICAL_MAP);});
	}
}

function switchStreetviewMapReport(){
	$("#reportLocalSalesMap").hide();
	$("#reportLocalSalesStreetviewMap").show();
	if(!propertyStreetViewLoaded){
		InitializeStreetViewReport();
	}
}

function InitializeStreetViewReport(){
	client = new GStreetviewClient();
	var propertylatlong = new GLatLng(propertyLatitude,propertyLongitude);
	if(propertylatlong){
		client.getNearestPanorama(propertylatlong, propertyStreetViewInitReport);
	}
}
 
function propertyStreetViewInitReport(response){
 // can not find user position on streetview
 if (response.code != 200){
 	//handle the exception here
 	$("#showStreetViewTab").remove();
 }
 else{
 	var latlng = new GLatLng(response.Location.lat, response.Location.lng);
 	myPano = new GStreetviewPanorama(document.getElementById("reportLocalSalesStreetviewMap"));
	myPano.setLocationAndPOV(latlng);
	propertyStreetViewLoaded = true;
	currentMapSwitcher = 2;
	GEvent.addListener(myPano, "error", handleNoFlash);
 }
}

function switchNormalMapReport(){
	$("#reportLocalSalesStreetviewMap").hide();
	$("#reportLocalSalesMap").show();
}

function init_control_tab_report(){
	if($("#reportLocalSalesMap") && $("#showMapTab")){
	    $("#showMapTab").click(function(){if(currentMapSwitcher > 1){switchNormalMapReport();} gmap.setMapType(G_NORMAL_MAP);});
	}
	if($("#reportLocalSalesMap") && $("#showStreetViewTab")){
	    $("#showStreetViewTab").click(switchStreetviewMapReport);
	}
	if($("#reportLocalSalesMap") && $("#satelliteMapTab")){
	    $("#satelliteMapTab").click(function(){if(currentMapSwitcher > 1){switchNormalMapReport();} gmap.setMapType(G_SATELLITE_MAP);});
	}
	if($("#reportLocalSalesMap") && $("#hybridMapTab")){
	    $("#hybridMapTab").click(function(){if(currentMapSwitcher > 1){switchNormalMapReport();} gmap.setMapType(G_HYBRID_MAP);});
	}
	if($("#reportLocalSalesMap") && $("#terrainMapTab")){
	    $("#terrainMapTab").click(function(){if(currentMapSwitcher > 1){switchNormalMapReport();} gmap.setMapType(G_PHYSICAL_MAP);});
	}
}

function switchStreetviewMapReport2(){
	$("#reportSchoolsMap").hide();
	$("#reportSchoolsStreetviewMap").show();
	if(!propertyStreetViewLoaded2){
		InitializeStreetViewReport2();
	}
}

function InitializeStreetViewReport2(){
	client = new GStreetviewClient();
	var propertylatlong = new GLatLng(propertyLatitude,propertyLongitude);
	if(propertylatlong){
		client.getNearestPanorama(propertylatlong, propertyStreetViewInitReport2);
	}
}
 
function propertyStreetViewInitReport2(response){
 // can not find user position on streetview
 if (response.code != 200){
 	//handle the exception here
 	$("#showStreetViewTab2").remove();
 }
 else{
 	var latlng = new GLatLng(response.Location.lat, response.Location.lng);
 	myPano2 = new GStreetviewPanorama(document.getElementById("reportSchoolsStreetviewMap"));
	myPano2.setLocationAndPOV(latlng);
	propertyStreetViewLoaded2 = true;
	currentMapSwitcher2 = 2;
	GEvent.addListener(myPano2, "error", handleNoFlash);
 }
}

function switchNormalMapReport2(){
	$("#reportSchoolsStreetviewMap").hide();
	$("#reportSchoolsMap").show();
}

function init_control_tab_report2(){
	if($("#reportSchoolsMap") && $("#showMapTab2")){
	    $("#showMapTab2").click(function(){if(currentMapSwitcher2 > 1){switchNormalMapReport2();} gmap2.setMapType(G_NORMAL_MAP);});
	}
	if($("#reportSchoolsMap") && $("#showStreetViewTab2")){
	    $("#showStreetViewTab2").click(switchStreetviewMapReport2);
	}
	if($("#reportSchoolsMap") && $("#satelliteMapTab2")){
	    $("#satelliteMapTab2").click(function(){if(currentMapSwitcher2 > 1){switchNormalMapReport2();} gmap2.setMapType(G_SATELLITE_MAP);});
	}
	if($("#reportSchoolsMap") && $("#hybridMapTab2")){
	    $("#hybridMapTab2").click(function(){if(currentMapSwitcher2 > 1){switchNormalMapReport2();} gmap2.setMapType(G_HYBRID_MAP);});
	}
	if($("#reportSchoolsMap") && $("#terrainMapTab2")){
	    $("#terrainMapTab2").click(function(){if(currentMapSwitcher2 > 1){switchNormalMapReport2();} gmap2.setMapType(G_PHYSICAL_MAP);});
	}
}