// ajax submit
$.googleMap = function(obj, options) {
	var
		container = obj,
		bounds = null,
		directionDisplay = null,
		directionsService = null;

	// init options
	var opts = {
		points: [],
		zoom: 15,
		panel: null
	};
	opts = $.extend(opts, options);

	// generate map bounds if multiple points present
	$.googleMap.setBounds = function() {
		if (opts.points.length <= 1) return;

		bounds = new google.maps.LatLngBounds();
		for (var i = 0; i < opts.points.length; i++)
			bounds.extend(new google.maps.LatLng(opts.points[i].lat, opts.points[i].lon));
	}

	// simply get directions
	$.googleMap.getDirections = function(options) {
		if (!directionsService) {
			directionsDisplay = new google.maps.DirectionsRenderer();
			directionsDisplay.setMap(map);
			if (opts.panel)
				directionsDisplay.setPanel(opts.panel);
		
			directionsService = new google.maps.DirectionsService();
		}

		directionsService.route(
			{ origin: options.origin, destination: options.destination, travelMode: google.maps.DirectionsTravelMode.DRIVING },
			function(response, status) {
				if (status == google.maps.DirectionsStatus.OK) {
					directionsDisplay.setDirections(response);
					if (options.success)
						setTimeout(options.success, 1000);
				}
				else
					alert('Route not found, please be more specific!');

				if (options.complete)
					options.complete();
			}
		);
	}

	// print support
	$.googleMap.print = function() {
		var a = window.open('', '', 'width=' + (opts.panel ? 800 : 520) + ', height=500, scrollbars=yes, top=0, left=0');
		a.document.open("text/html");
		a.document.write('<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head></head><body>');
		a.document.write('<table width=100% cellpadding=0 cellspacing=0><tr>');
		if (opts.panel)
			a.document.write('<td valign=top width=100% style="padding-right: 10px; font-family: verdana; font-size: 12px">' + $(opts.panel).html() + '</td>');
		a.document.write('<td valign=top><div style="width: 500px; height: 500px; position: relative; overflow: hidden">' + $(container).html() + '</div></td>');
		a.document.write('</tr></table></body>');
		a.document.close();
		a.print();
	}
	
	// if address present limit points to a single geocoded one, else check if bounds need to be calculated
	if (opts.address)
		opts.points = [{ lat: 42.053436, lon: -88.046913 }];
	else
		
	// set center based on bounds or point
	$.googleMap.setBounds();
	var center = bounds ? bounds.getCenter() : new google.maps.LatLng(opts.points[0].lat, opts.points[0].lon);
	
	// build map
	var map = new google.maps.Map(container, {
		zoom: opts.zoom,
		center: center,
		mapTypeId: google.maps.MapTypeId.ROADMAP,
		mapTypeControl: false
	});
	if (bounds)
		map.fitBounds(bounds);
	
	// add points
	for (var i = 0; i < opts.points.length; i++)
		new google.maps.Marker({
			position: new google.maps.LatLng(opts.points[i].lat, opts.points[i].lon),
			map: map
		});

};