﻿google.load("maps", "1");
google.load("search", "1");

google.setOnLoadCallback(initialize);
   
// Call this function when the page has been loaded
function initialize() 
{
	map2 = new google.maps.Map($('#map')[0]);
	map2.setUIToDefault();
	map2.setCenter(new google.maps.LatLng(
		google.loader.ClientLocation.latitude,
		google.loader.ClientLocation.longitude),
		10);
	$('#location').val(google.loader.ClientLocation.address.city + ', ' + google.loader.ClientLocation.address.region);
	
	localSearch = new google.search.LocalSearch()
	localSearch.setSearchCompleteCallback(null, find_post_offices_complete, null)
	
	find_post_offices();
}

function find_post_offices()
{
	localSearch.setCenterPoint($('#location').val());
	localSearch.execute('us post office');
	return false;
}

function find_post_offices_complete()
{
	var results_container = $('#search_results');
	results_container.html('');
	map2.clearOverlays();
	var setLocation = true;
	if (localSearch.results)
	{
		var results = localSearch.results;
		var last_div = null;
		for (var i = 0 ; i < results.length ; i++)
		{
			var result = results[i];
			var phones = new Array();
			if (result.phoneNumbers)
			{
				for (var j = 0 ; j < result.phoneNumbers.length ; j++)
				{
					phones[j] = result.phoneNumbers[j].number;
				}
			}
			phones = phones.join(' | ');
			last_div = results_container.append(
				'<div class="search_result thinborder">'+
				result.titleNoFormatting+'<br/>'+
				result.addressLines.join('<br/>')+'<br/>Phone: '+
				phones+
				'</div>'
				);
			var pos = new GLatLng(result.lat, result.lng)
			var marker = new GMarker(pos);
			if (setLocation)
			{
				map2.setCenter(pos);
				setLocation = false;
			}
			map2.addOverlay(marker);
		}
		var h = results_container.height();
		var h_main = h + 255;
		var main_div = $('#main');
		
		if (h_main > main_div.height())
		{
			main_div.height(h_main);
			$('#footer').css( { 'top': (h + 230)+'px', 'position' : 'absolute'});
		}
	}
}
