$(function() {
	
	
	$('.contact .map').each( function() {
									  
		if (GBrowserIsCompatible()) {
			var map = new GMap2( this );
			map.addControl( new GSmallMapControl() );
			map.addControl( new GMapTypeControl() );
			$(this).attr( 'map', map );
		
			var address = parseAddressElement( $(this).parents('.contact').find('.address') );
			$(this).attr( 'address', address );
			showAddress( address, map );
		}
		
	} );
	
	$('.directions').submit( function() {
		var address = $(this).parents('.contact').find('.map').attr( 'address' );
		var zip = $(this).find('.zip').attr( 'value' );
		
		showDirections(
			'from: ' + zip + ' to: ' + address
		);
		
		return false;
	} );
	
	$('.email_image').click( function() {
		var address = $(this).parents('.contact').find('.email').text();
		url = this.href + '?to_address=' + address + '&redirect=' + window.location.href;
									  
		$('<div></div>').load( url ).dialog( {
			width: '330px', 
			height: '470px', 
			modal: true,
			overlay: { background: 'black', opacity: '.8', filter: 'alpha(opacity=80)' },
			draggable: false,
			title: 'Contact Us'
		} );
		
		return false;
	} );
	
	
	window.onunload = GUnload;
	  
});

function parseAddressElement( element ) {
	return $(element).text().replace( /\s+/g, ' ' );
}


var geocoder = new GClientGeocoder();
function showAddress(address, map) {
	
	geocoder.getLatLng(
		address,
		function(point) {
			if (!point) {
				alert(address + " not found");
			} else {
				map.setCenter(point, 13);
				var marker = new GMarker(point);
				map.addOverlay(marker);
				//marker.openInfoWindowHtml(address);
			}
		}
	);
	
}


function showDirections( query ) {
	var directions_map = $( '<div style="position: relative; width: 300px; height: 300px; float: left; "></div>' );
	var directions_panel = $( '<div style="position: relative; width: 400px; float: left; margin-right: 8px;"></div>' );
	
	$('<div id="directions_div" ></div>').append( directions_panel ).append( directions_map ).dialog( {
		width: '748px', 
		height: '', 
		modal: true,
		overlay: { background: 'black', opacity: '.8', filter: 'alpha(opacity=80)' },
		draggable: false,
		title: 'Directions <a onclick="window.print();" href="javascript:;" style="margin-left:40px;font-weight:normal;" class="color1">print</a>'
	} );
	
	map2 = new GMap2( $(directions_map).get(0) );
	map2.addControl( new GSmallMapControl() );
	map2.addControl( new GMapTypeControl() );
	directions = new GDirections(map2, $(directions_panel).get(0) );
	directions.load( query );
	
}