$(document).ready(function()
{
	// Create map.
	var latitude  = $('input[name=Latitude]', $('#storeMap')).val();
	var longitude = $('input[name=Longitude]', $('#storeMap')).val();
	
	if(latitude != null && longitude != null)
	{
		var mapIcon = new GIcon(G_DEFAULT_ICON);
		
		// Set up map.
		map = new GMap2(document.getElementById('storeMap'));
		map.setCenter(new GLatLng(latitude, longitude), 15);
		map.setUIToDefault();
		
		var currMarker = createMarker(latitude, longitude, null, mapIcon);
		map.addOverlay(currMarker);
	}
	
	// Event Handlers.
	$('select[name=State]', $('#selectStateSearch')).change(function(e)
	{
		$(this).parents('form').submit();
	});
	
	$('select[name=SortBy]', $('#findStoreSorter')).change(function(e)
	{
		$(this).parents('form').submit();
	});
	
	$('input[name=Postcode]').parents('form').submit(function(e)
	{
		var invalid = $(':input', this).removeClass('invalid').filter('.integer').filter(function()
		{
			var regex = /[0-9]{3,4}/;
			return !regex.test($(this).val()) || $(this).val() == 'Postcode' || $(this).val().length >= 5;
		});
		
		if($(invalid).size() > 0)
		{
			$(invalid).addClass('invalid');
			e.preventDefault();
		}
	});
});

function createMarker(latitude, longitude, html, mapIcon)
{
	try
	{
		var markerLocation = new GLatLng(latitude, longitude);
		var currMarker = new GMarker(markerLocation, mapIcon);

		// Add on click popup.
		if(html != null)
		{
			GEvent.addListener(currMarker, 'click', function() 
			{
				currMarker.openInfoWindowHtml(html);
			});
		}
		
		// Position and show.
		return currMarker;
	}
	catch(exc)
	{
		return null;
	}
}