/* Maps Directions Plugin */

var globalMap = null;

(function($) {
	$.fn.directions = function(options) {
		var map = null;
		var directions = null;
		var defaults = {
			mapDiv:'map',
			directionsDiv:'directions',
			address:'227 E. Lawrence St., Mishawaka, IN, 46545',
			lat:41.667951,
			lng:-86.179139,
			zoom:12,
			width:536,
			height:500,
			forceLatLng:false  // set to true if you want to use a more accurate lat/lng instead of address
		};
		var options = $.extend(defaults, options);		
		return this.each(function() {
			init();
			$('form').submit(function(e) {
				e.preventDefault();
				setupDirections();
			});
		});
		
		function init() {
			if (GBrowserIsCompatible()) {
				options.mapDiv = $('#'+options.mapDiv)[0];
				options.directionsDiv = $('#'+options.directionsDiv)[0];
				
				$(options.mapDiv).css({ 'display':'block', 'width':options.width, 'height':options.height }).html('');
				
				map = new GMap2(options.mapDiv);
				globalMap = map;
				map.setCenter(new GLatLng(options.lat, options.lng), options.zoom);
				map.addControl(new GSmallMapControl);
				map.addControl(new GMapTypeControl);
				
				var geo = new GClientGeocoder();	
				geo.getLatLng(options.address, function(p) {
					marker = new GMarker((options.forceLatLng ? new GLatLng(options.lat, options.lng) : p));
					GEvent.addListener(marker,"dragend", function() { alert(marker.getLatLng()); });
					map.addOverlay(marker);	
					map.setCenter(p, options.zoom);
				});		
				
				directions = new GDirections(map);
				
				GEvent.addListener(directions,"error", function() { onError(); });
				GEvent.addListener(directions,"load", function() {
					var fun = function() {
						onLoadDirections();
					};
					setTimeout(fun, 1);
				});
			}	
		}
		
		function onLoadDirections() {
			if(options.forceLatLng) directions.getMarker(1).setLatLng(new GLatLng(options.lat, options.lng));
			var html = '';
			for (var i=0; i<directions.getNumRoutes(); i++) {
				var route = directions.getRoute(i);
				var geocode = route.getStartGeocode();
				var point = route.getStep(0).getLatLng();
	
				html += routeDistance(route.getDistance().html+" (about "+route.getDuration().html+")");
				html += waypoint(point, geocode.address);
			
				html += '<table id="steps"><tbody>';
				for (var j=0; j<route.getNumSteps(); j++) {
					var step = route.getStep(j);
					html += detail(step.getLatLng(), j+1, step.getDescriptionHtml(), step.getDistance().html, j%2)
				}
				html += '</tbody></table>';
				html += topoint(route.getStep(j-1).getLatLng(), geocode.address);			
			}
			$(options.directionsDiv).html(html);
		}
		
		function waypoint(point, address) {
			var target = '"'+"globalMap.showMapBlowup(new GLatLng("+point.toUrlValue(6)+"))" +'"';
			var h = '<table id="origin"><tr onclick="'+target+'">';
			h += '		<td>';
			h += ' 			<img src="http://maps.google.com/intl/en_us/mapfiles/marker_greenA.png">'
			h += '		</td>';
			h += ' 		<td style="vertical-align: middle; width: 100%;">';
			h += 			address;
			h += ' 		</td>';
			h += ' 	</tr></table>';
			return h;
		}
		
		function routeDistance(dist) {
			var h = '<div id="route-distance">Distance: ' + dist + '</div>';
			return h;
		}
		
		function detail(point, num, description, dist, oddRow) {
			var target = '"'+"globalMap.showMapBlowup(new GLatLng("+point.toUrlValue(6)+"))" +'"';
			var h = '<tr '+(oddRow ? '' : 'class="even" ')+'onclick='+target+'>';
			h += '		<td>'+num+'</td>';
			h += '		<td>'+description+'</td>';
			h += '		<td>'+dist+'</td>';
			h += '	</tr>';
			return h;
		}
		
		function topoint(point) {
			var target = '"'+"globalMap.showMapBlowup(new GLatLng("+point.toUrlValue(6)+"))" +'"';
			var h = '	<table id="destination"><tr onclick='+target+'>';
			h += '			<td>';
			h += ' 				<img src="http://maps.google.com/intl/en_us/mapfiles/marker_greenB.png">'
			h += '			</td>';
			h += ' 			<td style="vertical-align: middle; width: 100%;">';
			h += 				options.address;
			h += ' 			</td>';
			h += ' 		</tr></table>';
			return h;
		}
	
		function setupDirections() {
			var value = '';
			$('input').not('input[@type=submit]').each(function() { value += this.value+', '; });
			directions.load("from: "+value+" to: "+options.address, { getSteps:true });
		}
		
		function onError() {
			alert('An error has occured. Please re-enter your address and try again.');
		}
	};
})(jQuery);

$(document).ready(function() {
	$('<form action="" enctype="multipart/form-data"><fieldset> Address <input class="text" type="text" /> <input class="blue submit" type="submit" value="Get Directions" /> </fieldset></form>').appendTo('#directions-address');				   
	$('#map').directions({ address:'5108 Bull Rapids Road, Woodburn, IN, 46797', lat:41.131033556517195, lng:-84.85608100891113, forceLatLng:true });
});
