//
//    google maps API
//

function initialize_route_least_time()
	{
		//alert( "initialize_route_least_time()" );
		
		//    clear the div's
		
		document.getElementById( "map_canvas" ).innerHTML 				= "";
		document.getElementById( "route" ).innerHTML 					= "";
		document.getElementById( "est_total_route_time" ).innerHTML 	= "The <a href='/node/13#est_del_time_def'>estimated delivery time</a>, including returning to the restaurant,  is based on an average stop time of 3 minutes per delivery (the first and last point represent your restaurant location).";
		
		locale				= "en_US";
		
		//    delivery addresses
		
		pa			= {};    //    object
		
		pa[0*1]	= "1111 W Town and Country Rd, Orange, CA 92868";
		pa[1*1]	= "1600 W Palmyra Ave, Orange, CA‎, 92868";
		pa[2]	= "1601 W La Veta Ave, Orange, CA, 92868";
		pa[3]	= "400 S Batavia St, Orange, CA‎, 92868";
		pa[4]	= "1200 W Chapman Ave, Orange, CA, 92868";
		
		//debug_array( "pa definition", pa, "debug" );
		
		pa_cnt		= 0 * 1;
		pa_cnt_max	= get_object_size( pa );    //  start and end at restaurant
		
		pa_copy		= {};    		//    object
		pa_copy		= pa;
		//debug_array( "pa copy definition", pa_copy, "debug" );
		
		//    routing
		
		rlt				= 1 * 1;
		rlt_max			= pa_cnt_max;
		
		mKey			= "";				//  key of object whose duration is being measured
		
		tfr				= {};  				//  object used to store time from restaurant
		lt				= [];				//  array
		
		ltf				= [];      			//  array contains the least time final
		ltf_cnt			= 1 * 1;
		ltf_cnt_max		= pa_cnt_max;
		
		//debug_variable( "ltf_cnt_max", ltf_cnt_max, "debug" );
		
		ltf.push( pa[0] );					//  starting point is restaurant
		
		//
		//    delivery area boundary points - must be at least 4 points
		//    with first and last points the same to close the area
		//
		
		mc		= "1111 Town and Country Rd, Orange, CA, 92868";
		mc_gps	= "";

		bp		= [];	// array
		
		bp.push( "2320 N Bush St, Santa Ana, CA, 92706" );
		bp.push( "2100 W La Veta Ave, Orange, CA, 92868" );
		bp.push( "3001 W Chapman Ave, Orange, CA, 92868" );
		bp.push( "120 N Cambridge St, Orange, CA, 92866" );
		bp.push( "16500 E Santa Clara Ave, Santa Ana, CA, 92705" );
		bp.push( "2350 Lincoln Ave, Santa Ana, CA, 92705" );
		bp.push( "2300 Lincoln Ave, Santa Ana, CA, 92705" );
		bp.push( "2320 N Bush St, Santa Ana, CA, 92706" );
		
		bp_count	= 0 * 1;
		bp_max		= bp.length;
		
		bp_gps		= [];    //  array

		//  start

		route_least_time( pa_copy, rlt, rlt_max );
		
	}    //    end of function


function route_least_time( arr, cnt, cnt_max )
	{
		if ( GBrowserIsCompatible() )
			{      
				if( cnt < cnt_max )
					{
						//debug_variable( "cnt", cnt, "debug" );
						//debug_array( "arr", arr, "debug" );
						
						map 			= new GMap2( document.getElementById("map_canvas") );
						
						geocoder 		= new GClientGeocoder();
						
						route_prep 		= new GDirections( map );
						
						GEvent.addListener( route_prep, "load", onGDirectionsLoad_before_route );
						GEvent.addListener( route_prep, "error", handleErrors );
						
						var ta		= [];
						ta.push( arr[0*1] );				//		starting point
						
						var i 		= 0 * 1;
						for( mKey in arr )
							{
								if ( i == cnt )
									{
										ta.push( arr[ mKey ] );	//    measure point
										break;
									}
								
								i++;
							}
						
						//debug_array( "ta", ta, "debug" );
						
						route_prep.loadFromWaypoints( ta, locale );  //  find duration from restaurant to each delivery
					}
			}

	}    //    end of function


function onGDirectionsLoad_before_route()
	{
		// Use this function to access information about the latest load() results
		
		rlt++;
		//debug_variable( "rlt", rlt, "debug" );
		
		var time	= route_prep.getDuration();
		
		tfr[ mKey ]	= time['seconds'];
		//debug_array( "tfr", tfr, "debug" );
		
		if( ltf_cnt < ltf_cnt_max )
			{
				if( rlt < rlt_max )
					{
						route_least_time( pa_copy, rlt, rlt_max );
					}
				else
					{
						//   sort from least to most time
						
						ltf_cnt++;
						//debug_variable( "ltf_cnt", ltf_cnt, "debug" );
						
						ret = sortAssoc( tfr );
						//debug_array( "ret", ret, "debug" );
						
						for( var key in ret )
							{
								//debug_variable( "key", key, "debug" );
								
								ltf.push( pa_copy[ key ] );    	//	take the first element
								
								//debug_array( "pa_copy before delete", pa_copy, "debug" );
								delete pa_copy[ key ];
								//debug_array( "pa_copy after delete", pa_copy, "debug" );
								
								//debug_array( "ltf build", ltf, "debug" );
								
								if( ltf_cnt >= ltf_cnt_max )
									{
										finish_routing();
										return;
									}
								
								
								//    reset variables for next loop
								
								tfr			= {};   			//	empty object
								ret			= [];				//	empty array
								
								rlt			= 1 * 1;
								rlt_max--;						//  one less each loop		
								
								route_least_time( pa_copy, rlt, rlt_max );
								return;
							}
					}
			}
			
	}    //    end of function


function finish_routing()
	{
		//  ltf complete
		
		ltf.push( "900 W Town and Country Rd, Orange, CA" );			//    end at restaurant
		//debug_array( "ltf complete", ltf, "debug" );
		
		geocoder.getLatLng( mc, function( point ){ make_center_point( point ); } );  //  center map
		
	}    //    end of function


function make_center_point( p )
	{
		mc_gps	= p;
		map_route();
		
		//make_route_array();
	
	}    //    end of function


function map_route()
	{
		route_map 			= new GDirections( map );
		
		GEvent.addListener( route_map, "load", onGDirectionsLoad_after_route );
		GEvent.addListener( route_map, "error", handleErrors );
		
		route_map.loadFromWaypoints( ltf, locale );    //  route
	}


function onGDirectionsLoad_after_route()
	{
		// Use this function to access information about the latest load() results

		route_duration		= route_map.getDuration();
		//alert( "total route time = " + route_duration['seconds']  );
		
		//    estimated total time is lt.length - 2 * 3 minutes per stop plus route_duration
		
		var etrt	= ( ( ltf.length - 2 ) * 3 * 60 ) + route_duration['seconds'] ;
		
		var minutes		= Math.floor( etrt / 60 ) ;
		
		var seconds		= Math.floor( ( ( etrt / 60 ) - minutes ) * 60 );
		
		var rm	= "The <a href='/node/13#est_del_time_def'>estimated delivery time</a>, including returning to the restaurant, for these <b>" + ( ltf.length - 2 ) + " deliveries is " + minutes + " minutes and " + seconds + " seconds</b> based on an average stopping time of 3 minutes per delivery (the first and last point represent your restaurant location).";
		
		document.getElementById( "est_total_route_time" ).innerHTML 	= rm;
		
		//    show locations
		
		var phone	= "<br />Phone : 123-456-7890<br /><br />";
		
		var let		= new Array( "A", "B", "C", "D", "E", "F", "G", "H", "I", "J" );
		
		var rp 		= "<b>Restaurant location: " + let[0] + " and " + let[ ltf.length - 1 ] + "</b><br />" + ltf[0] + phone ;
		
		for( i = 1; i < ltf.length - 1; i++ )
			{
				rp	+= "<b>Delivery location " + let[i] + ":</b><br />" + ltf[i] + phone ;
			}
		
		document.getElementById( "route" ).innerHTML 	= rp;
		
		geocoder.getLatLng( bp[ bp_count ], function( point ){ make_delivery_array( point ); } );

	}    //    end of function


function make_delivery_array( p )
	{
		bp_gps.push( p );
		
		bp_count++;
	
		if( bp_count < bp_max )
			{
				geocoder.getLatLng( bp[ bp_count ], function( point ){ make_delivery_array( point ); } );
			}
		else
			{
				map_delivery_area();
			}
	
	}    //    end of function


function map_delivery_area()
	{
		//map 			= new GMap2( document.getElementById("map_canvas") );
		
		map.setCenter( mc_gps, 14 );
		map.addControl( new GSmallMapControl() );
		
		delivery_area = new GPolygon( bp_gps, "#f33f00", 5, 1, "#ff0000", 0.2 ); 
		map.addOverlay( delivery_area );

		//    listen for clicks
		
		GEvent.addListener( map, "click", function( delivery_area, point )
			{
				if( delivery_area )
					{ 
						alert( "Inside Delivery Area" )
					}
				else if( point )
					{
						alert( "Out of Delivery Area" )
					}
			} );

	}    //    end of function

//
//    error handling
//

function handleErrors()
	{
		 if ( route_prep.getStatus().code == G_GEO_UNKNOWN_ADDRESS )
		 	{
			   alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + route_prep.getStatus().code);
			}
		 else if ( route_prep.getStatus().code == G_GEO_SERVER_ERROR )
		 	{
			   alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + route_prep.getStatus().code);
			}
		 
		 else if ( route_prep.getStatus().code == G_GEO_MISSING_QUERY )
		 	{
			   alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + route_prep.getStatus().code);
			}


/*
		else if ( route_prep.getStatus().code == G_UNAVAILABLE_ADDRESS )//  <--- Doc bug... this is either not defined, or Doc is wrong
			{
				alert("The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.\n Error code: " + route_prep.getStatus().code)
			}
*/
		 
		 else if ( route_prep.getStatus().code == G_GEO_BAD_KEY )
		 	{
		   		alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + route_prep.getStatus().code);
			}
		
		 else if ( route_prep.getStatus().code == G_GEO_BAD_REQUEST )
		 	{
		   		alert("A directions request could not be successfully parsed.\n Error code: " + route_prep.getStatus().code);
			}
		  
		 else 
		 	{
				alert("An unknown error occurred.");
			}

}    //    end of function


