<!--

function numOnly(evt){ //v3
	var charCode = (evt.which) ? evt.which : window.event.keyCode;

	if (charCode <= 13)
	{
		return true;
	}
	else
	{
		var keyChar = String.fromCharCode(charCode);
		var re = /[0-9]/
		return re.test(keyChar);
	}
}
//-------------------------------------------------------
function Marker_Increment( Incr, myForm ){ //v3
	var dx_markers = 2;

	var str = new String( '' );
	str  = myForm.dx_markers.value;

	str = Trim(str);
	dx_markers = parseInt(str, 10);

	if( isNaN(dx_markers) )dx_markers = 1;

	if( Incr == 1 )dx_markers = dx_markers + 1;
	else           dx_markers = dx_markers - 1;

	myForm.dx_markers.value = dx_markers;
	Show_Markers();
}
//-------------------------------------------------------
function dxMarker(){ //v3

	var dx_markers = 2;

	var str = new String( '' );
	str  = document.Map_Form.dx_markers.value;

	str = Trim(str);
	dx_markers = parseInt(str, 10);

	if( isNaN(dx_markers) )dx_markers = 1;

	return dx_markers;
}
//-------------------------------------------------------
  function Turn_Markers_On_OFF( b_On ){ //v3

    if( b_Markers_ON == 0 ){
        Hide_Markers();
    }

    if( b_On == 1 ){
        Markers_On();
    }else{
        Hide_Markers();
    }
}
//-------------------------------------------------------
   function Markers_OFF_Alert(){ //v3

    iUnits = document.Map_Form.Dist_Units.value;

    if( iUnits == 0 )var msg = '\nMarkers are DISABLED when the Total Route Exceeds 150 miles.';
    else             var msg = '\nMarkers are DISABLED when the Total Route Exceeds 240 kilometers.';

    document.Map_Form.b_Markers.checked = false;
    alert(msg);

   }
//-------------------------------------------------------    
  function Markers_On_OFF(){ //v3   

    if( b_Markers_ON == 0 ){
        document.Map_Form.b_Markers.checked = false;
        Markers_OFF_Alert();
        return;
    }

    var b_On = 0;
    if( document.Map_Form.b_Markers.checked )b_On = 1;
    Turn_Markers_On_OFF( b_On );
    
  }
//-------------------------------------------------------
  function Markers_On(){ //v3

        var iUnits = document.Map_Form.Dist_Units.value;

        if( iUnits == 0 )Show_Mile_Markers();
        else             Show_Kilo_Markers();
  }
//-------------------------------------------------------
  function Show_Markers(){ //v3

    if( b_Markers_ON == 1 ){
	    if( document.Map_Form.b_Markers.checked ){
            Hide_Markers();
            Markers_On();
        }
    }else{
        Markers_OFF_Alert();
    }

  }
//-------------------------------------------------------
  function recalc_dist(){ //v3

    display_distance( plength );

	if( document.Map_Form.b_Markers.checked ){
        iUnits = document.Map_Form.Dist_Units.value;

        if( iUnits == 0 )Show_Mile_Markers();
        else             Show_Kilo_Markers();
    }

  }
//-------------------------------------------------------
  function Hide_Markers(){ //v3

     for( var i=1; i < D_Miles.length; ++i ){
     	   D_Miles[i].mmarker.setVisible( false ); 
     }

     for( var j=1; j < D_Kilos.length; ++j ){
     	  D_Kilos[j].mmarker.setVisible( false ); 
     }
  }
//-------------------------------------------------------
  function Show_Mile_Markers(){ //v3

     var nStep = dxMarker();

     if( nStep <= 0 )nStep = 1;

     for( var i=nStep; i < D_Miles.length; i+=nStep ){
     	   D_Miles[i].mmarker.setVisible( true ); 
     }

     for( var j=1; j < D_Kilos.length; ++j ){
     	  D_Kilos[j].mmarker.setVisible( false ); 
     }
  }
//-------------------------------------------------------
  function Show_Kilo_Markers(){ //v3

     for( var i=1; i< D_Miles.length;++i ){
  	      D_Miles[i].mmarker.setVisible( false ); 
     }

     var nStep = dxMarker();
     if( nStep <= 0 )nStep = 1;

     for( var j=nStep; j< D_Kilos.length; j+=nStep ){
     	  D_Kilos[j].mmarker.setVisible( true ); 
     }

   }
//-------------------------------------------------------
  function display_distance( meters ){ //v3
    
    iUnits = document.Map_Form.Dist_Units.value;

    if( meters > Max_Dist && b_Markers_ON == 1 ){
        b_Markers_ON = 0;
        Markers_OFF_Alert();
        Hide_Markers();
    }else{
        if( meters < Max_Dist )b_Markers_ON = 1;
    }

    var dist = 0.0;

    if( iUnits == 0 )dist = meters * meters_to_miles;
    else             dist = meters * meters_to_KMs;

    document.Map_Form.iUnits.value = iUnits;
    document.Map_Form.Meters.value = meters;
    

    if( nPoints != 0 )document.getElementById("disp_distance").innerHTML = dist.toFixed(2);
    else              document.getElementById("disp_distance").innerHTML = '';

  }
//-------------------------------------------------------
function end_loop(){ //v3

  if( nPoints < 2 ){
      alert('\nEnding the Route with "Loop Back to Start" requires at least 2 points on your map.');
      return;
  }
  
  if( same_as_prev_pt( Map_UI[0].mLxL ) ){
      alert('\nYou are already back at the start - you have closed the loop.');
      return;    
  }

  
  var msg = '\nThis option will connect the last point on the route to the starting point.';
      msg+= '\n\nIf the last point is near the first point, the path will be a straight line to the start,';
      msg+= '\notherwise the shortest path will be automatically determined.';                                        
      msg+= '\n\n(End point of the route will be the same as starting point)';
      msg+= '\n\nClick "OK" to Close the route back to the start - Otherwise Click Cancel.';

  if( confirm(msg) ){
      map_click_event( Map_UI[0].mLxL );
  }

}
//-------------------------------------------------------
  function loop_back(){ //v3

    if( nPoints < 2 ){
        alert('\nEnding the Route with "Loop Back to Start" requires at least 2 points on your map.');
        return;
    }    
    var msg = '\nThis option will Trace the route back to the starting point.';
        msg+= '\n\nThis will double the total distance.';                                        
        msg+= '\n\n(End point of the route will be the same as starting point)';
        msg+= '\n\nClick "OK" to Loop Back - Otherwise Click Cancel.';

    if( confirm(msg) ){
        map_loop_back();
    }

  }
//-------------------------------------------------------
function map_loop_back(){ // rewrite

    var marker;
    var lst_latlng = null;
    var prv_latlng = null;
    var new_latlng = null;
    
    var ndx       = Map_UI.length-1;
    var ndx_start = Map_UI.length-1; // Map the route from the last point back to the start
    
    // Back up all the way to the start while connecting each point to its predecessor
    prv_latlng = Map_UI[ndx].mLxL;//Previous Point is the last point in the current route 
    lst_latlng = Map_UI[0  ].mLxL; 
    
    route_load_msg( 1 );
       
    for( var i=0; i< Map_UI.length; ++i ){
         if( Map_UI[i].mpoly != null ){
             Map_UI[i].mpoly.setMap( null );
         }
    }
    
    // Total Distance and Distance Travelled since Last Kilometer & Mile Marker
    plength   = 0;
    dx_to_km  = 0; 
    dx_to_mile= 0;
        
    dir_marker_remove();
    Turn_Markers_On_OFF( 0 );
    
    Map_Steps.length = 0;
    D_Miles.length = 0;
    D_Kilos.length = 0; 
    D_Kilos.push( new KM_Markers( null, null, null, 0 ) );
    D_Miles.push( new KM_Markers( null, null, null, 0 ) );

    document.Map_Form.b_Markers.checked = false;
 
    ndx = Map_UI.length-2;
    for( var i=ndx; i>= 0; --i ){
    
         new_latlng = Map_UI[i].mLxL;
                  
         ++nPoints;
         obj_Map_UI = new Map_Data_UI( nPoints, Map_UI[i+1].mopts,  null, 1, Map_UI[i+1].mHwy, new_latlng, prv_latlng, new_latlng, 0, 0, 0 );
                          
         Map_UI[nPoints-1] = obj_Map_UI;
         prv_latlng = new_latlng;
         
    }
     
    display_route_npoints();
    display_distance( plength );
    protect_route(1);
    display_DIR_Table();
    
    Re_Route_Points(0);
    
    route_load_msg( 0 );

    pt_marker_disp_v3( 1, EndRt_marker, lst_latlng );

}
//-------------------------------------------------------
function diags_io_Map_UI(imode){ //v3

    var sPts = new String('');
    
    if( imode != 0 ){
        sPts = document.Map_Form.Diagnox.value;
        sPts+= '\n';  
        sPts+= '----------------------------\n';
    }
    
    for( var k=0; k<Map_UI.length; ++k){     
         sPts+= ''+k+')'; sPts+= Map_UI[k].mLxL +'\n';   
    }
    
    sPts+= '----------------------------\n';
    sPts+= 'nPoints='+nPoints+'\n';
    document.Map_Form.Diagnox.value = sPts;
    
    //alert('diags done....');
    
}
//-------------------------------------------------------
function progress( iMode ){ //v3

    if( iMode == 0 ){
	progress_overlay.setVisible( false );
    }else{
        var ctr = map.getCenter();
        progress_overlay.setPosition(ctr);
        progress_overlay.setVisible( true );
    }

}
//-------------------------------------------------------
function __progress(latlng){ //rewrite

    ////glatlngbounds = map.getBounds();
    ////var ctr = glatlngbounds.getCenter();
    ////var Pt = map.fromLatLngToContainerPixel(ctr);

    ////var s2 = new GScreenPoint(   0,   0 );
    ////var s1 = new GScreenPoint( Pt.x-185, Pt.y+12 );
    ////var sz = new  GScreenSize( 370,  24 );
    ////progress_overlay = new google.maps.ScreenOverlay( "http://www.entryworks.com/Dev_TLogs/images/progress_routes.jpg", s1, s2, sz );
    ////map.addOverlay( progress_overlay );

}
//-------------------------------------------------------
function dir_marker_remove(){ //v3

   pt_marker_disp_v3( 0, dir_marker );
   
}
//-------------------------------------------------------
function dir_marker_display( latlng ){ //v3

   pt_marker_disp_v3( 0, dir_marker );
   pt_marker_disp_v3( 1, dir_marker, latlng );
      
}
//-------------------------------------------------------
function pt_marker_remove(){//DEPRECATED

   map.removeOverlay( pt_marker );
   dir_marker_remove();
   
}
//-------------------------------------------------------
function pt_marker_disp_v3( iMode, mmarker, latlng ){ //v3

    if( mmarker == null )return;
    
    if( iMode == 0 ){
	mmarker.setVisible( false );
    }else{
        mmarker.setPosition(latlng);
        mmarker.setVisible( true );
    }

}
//-------------------------------------------------------
function pt_marker_display( latlng ){ //v3

   map.removeOverlay( pt_marker );
   pt_marker.setLatLng( latlng );
   map.addOverlay( pt_marker );
   
}
//-------------------------------------------------------
function remove_jump_marker(){ //v3

   if( jump_marker != null ){
       pt_marker_disp_v3( 0, jump_marker );
   }

}
//-------------------------------------------------------
function add_jump_marker( latlng ){ //v3

    pt_marker_disp_v3( 1, jump_marker, latlng );
     
    //if( nPoints == 0 ){
    //    map.addOverlay( jump_marker );
    //}else{
    //    map_click_event( latlng );
    //}

}
//----------------------------------------------------------------------
var sSpot_OFF = new String('');
sSpot_OFF = '      <table border="0" cellspacing="1" cellpadding="2" class="interior_div" >';
sSpot_OFF+= '          <tr>';
sSpot_OFF+= '            <td nowrap><div align="center">Spot Info<br><b>Turn Off</b></div></td>';
sSpot_OFF+= '          </tr>';
sSpot_OFF+= '          <tr>';
sSpot_OFF+= '            <td><div align="center"><a href="javascript:spot_info_off();" title="Turn Spot Information OFF"><img src="../icons/cancl_16.gif" width="16" height="16" border="0" /></a></div></td>';
sSpot_OFF+= '          </tr>';
sSpot_OFF+= '      </table>';
//-----------------------------------------------------------------------
function show_spot_ballon( latlng, aData, ispot_mode ){ //v3

    var addr    = aData[0];
    var country = aData[1];
    var state   = aData[2];
    var city    = aData[3];
    
    var lat   = latlng.lat();
    var lng   = latlng.lng(); 
    
    var slatlng  = 'Latitude x Longitude: '+ latlng;
    var sloc     = city+', '+state;    
    
    var sZoom    = map.getZoom();
    
    var sHeader = '';
    var sMapping_Msg = '';
    
    if( nPoints == 0 ){
        sMapping_Msg = 'Click icon to make this the FIRST point on the route:&nbsp;';
    }else{
        sMapping_Msg = 'Click icon to make this the NEXT point on the route:&nbsp;';
    }
    
    if( ispot_mode == 0 ){
        sHeader = 'The Point you Clicked:';
    }else{
        var address = new String( document.Map_Form.Mail_Code.value);
        sHeader = 'Details for: '+address;
        document.Map_Form.Mail_Code.value = '';
    }
    
var sSpot = new String('');

sSpot = '<table border="0" cellpadding="1" cellspacing="1" >';
sSpot+= '    <tr>';
sSpot+= '      <td colspan="2" bgcolor="#EEEEFF">'+sHeader+'</td>';
sSpot+= '      <td rowspan="5" align="left" valign="bottom">';

sSpot = '<table border="0" cellpadding="1" cellspacing="1" >';
sSpot+= '    <tr>';
sSpot+= '      <td colspan="2" bgcolor="#EEEEFF">'+sHeader+'</td>';
sSpot+= '      <td rowspan="5" align="left" valign="bottom">';

if( ispot_mode == 0 ){
  sSpot+= sSpot_OFF;
}else{
  sSpot+= '&nbsp;';
}

sSpot+= '      </td>';
sSpot+= '    </tr>';
sSpot+= '    <tr>';
sSpot+= '      <td nowrap="nowrap"><div align="right">Lat x Lng: </div></td>';
sSpot+= '      <td nowrap="nowrap">'+ latlng+'</td>';
sSpot+= '    </tr>';
sSpot+= '    <tr>';
sSpot+= '      <td><div align="right">ZoomScale:</div></td>';
sSpot+= '      <td nowrap="NOWRAP">'+ sZoom+'</td>';
sSpot+= '    </tr>';
sSpot+= '    <tr>';
sSpot+= '      <td><div align="right">Location:</div></td>';
sSpot+= '      <td nowrap="NOWRAP">'+ addr+'</td>';
sSpot+= '    </tr>';
sSpot+= '    <tr>';
sSpot+= '      <td nowrap="nowrap"><div align="right">&nbsp;</td>';
sSpot+= '      <td nowrap="NOWRAP">'+ sloc+'</td>';
sSpot+= '    </tr>';
sSpot+= '    <tr>';
sSpot+= '      <td colspan="3" nowrap="nowrap"><hr size="1"></td>';
sSpot+= '    </tr>';
sSpot+= '    <tr>';
sSpot+= '      <td colspan="3" nowrap="nowrap"><div align="center">';
sSpot+= '      <table border="0" cellspacing="2" cellpadding="1">';
sSpot+= '        <tr>';
sSpot+= '          <td nowrap align="right">'+sMapping_Msg+'</td>';
sSpot+= '          <td align="left"><a href="javascript:map_to_point( '+lat+','+lng+' );"><img src="../icons/map_16x16.gif" width="16" height="16" border="0"></a></td>';
sSpot+= '        </tr>';
sSpot+= '        <tr>';
sSpot+= '          <td nowrap align="right">Click icon to make this a &quot;<em>Point of Interest</em>&quot;</td>';
sSpot+= '          <td align="left"><a href="javascript:poi_latxlng('+lat+','+lng+');"><img src="../icons/map_a.gif" width="16" height="16" border="0"></a></td>';
sSpot+= '        </tr>';
sSpot+= '      </table></div></td>';
sSpot+= '    </tr>';
sSpot+= '</table>';
        
   
    dir_marker_display( latlng );
    dir_infoWindow.setContent( sSpot );
    dir_infoWindow.open( map, dir_marker );

    info_win_listener = google.maps.event.addListener( dir_infoWindow, "closeclick", function() {
        dir_marker_remove();
        google.maps.event.removeListener( info_win_listener );
    });     
            

}
//-------------------------------------------------------
function adx_geocode( geo_code_results ){  //v3

// See geocoder_callback_template.js for full review of geo_code_results
          
    var sType   = '';    
    var st_no   = '';
    var route   = '';
    var city    = '';
    var area    = '';
    var state   = '';
    var mcode   = '';
    var county  = '';
    var country = '';
    var latlng  = null;
    
    var i=0; // Only interested in 1st Result    
    var j=0; // Only interested in 1st Type
    
    latlng = geo_code_results[i].geometry.location;    
    
    for( var k=0;  k< geo_code_results[i].address_components.length; ++k ){
         
         sType = geo_code_results[i].address_components[k].types[j];
         
         if( sType == 'street_number'               )st_no   = geo_code_results[i].address_components[k].long_name;
         if( sType == 'route'                       )route   = geo_code_results[i].address_components[k].long_name;
         if( sType == 'locality'                    )city    = geo_code_results[i].address_components[k].long_name;
         if( sType == 'administrative_area_level_3' )area    = geo_code_results[i].address_components[k].long_name;
         if( sType == 'administrative_area_level_2' )county  = geo_code_results[i].address_components[k].long_name;
         if( sType == 'administrative_area_level_1' )state   = geo_code_results[i].address_components[k].long_name;
         if( sType == 'postal_code'                 )mcode   = geo_code_results[i].address_components[k].long_name;
         if( sType == 'country'                     )country = geo_code_results[i].address_components[k].long_name;
         if( sType == 'country'                     )ccode   = geo_code_results[i].address_components[k].short_name;
         
    }
    
    var geoData =new Array(9);
    
    geoData[0] = st_no  ;
    geoData[1] = route  ;
    geoData[2] = city   ;
    geoData[3] = area   ;
    geoData[4] = county ;
    geoData[5] = state  ;
    geoData[6] = mcode  ;
    geoData[7] = country;
    geoData[8] = ccode  ;
    geoData[9] = st_no +' '+ route;
    
    return geoData;

}
//-------------------------------------------------------
function show_Spot_Jump( results, status ) { //v3

    var state   = '';
    var city    = '';
    var addr    = '';
    var country = '';

    if (! results) {
      alert("Google Maps did not return a valid response");
      addr= 'No Location info for the spot you clicked.';
      document.getElementById("spot_address" ).innerHTML = addr;
      return;
    }

    if (status != google.maps.GeocoderStatus.OK) {
        alert("Google Maps  did not return a valid response");
        addr= 'No Location info for the spot you clicked.';
        document.getElementById("spot_address" ).innerHTML = addr;
    }

    var latlng = results[0].geometry.location;

    remove_jump_marker();
    map.setCenter( latlng );

    geoCode  = adx_geocode( results );

    var addr = geoCode[9];    
    aData    = [ addr, geoCode[7], geoCode[5], geoCode[2] ];

    show_spot_ballon( latlng, aData, 0 );

    //document.getElementById("spot_address" ).innerHTML = addr;
    //document.getElementById("spot_state"   ).innerHTML = geoData[5];//state
    //document.getElementById("spot_city"    ).innerHTML = geoData[2];//city
}

//-------------------------------------------------------
function show_Spot_Click( results, status ) { //v3

    var state   = '';
    var city    = '';
    var addr    = '';
    var country = '';
          
    if (! results) {
      alert("Google Maps did not return a valid response");
      addr= 'No Location info for the spot you clicked.';
      document.getElementById("spot_address" ).innerHTML = addr;
      return;
    } 
    
    if (status != google.maps.GeocoderStatus.OK) { 
        alert("Google Maps  did not return a valid response");
        addr= 'No Location info for the spot you clicked.';
        document.getElementById("spot_address" ).innerHTML = addr;
    } 
           
    var latlng = results[0].geometry.location; 
    geoCode  = adx_geocode( results );      
    var addr = geoCode[9];
    
    aData = [ addr, geoCode[7], geoCode[5], geoCode[2] ];
       
    show_spot_ballon( latlng, aData, 0 );
    
    //document.getElementById("spot_address" ).innerHTML = addr;
    //document.getElementById("spot_state"   ).innerHTML = geoData[5];//state
    //document.getElementById("spot_city"    ).innerHTML = geoData[2];//city
}

//-------------------------------------------------------
  function spot_location( latlng, imode ){ //v3

      onClicks();
            
      var request = { 'location': latlng };
      my_geocoder.geocode( request, show_Spot_Click );

  }
//-------------------------------------------------------
function Sx_Route_Steps( Map_UI_ndx, dir ){ //v3

    var sDirTest = '';
    var nRoutes= dir.getNumRoutes();
    var nlen = 0;
    var sStr = '';
    
    for( var iR = 0; iR < nRoutes; ++iR ){
    
         var mRoute = dir.getRoute(iR);
         var nSteps= mRoute.getNumSteps();
         
         for( var iS = 0; iS < nSteps; ++iS ){
              var mStep = mRoute.getStep(iS);
              var latlng = mStep.getLatLng();
              
              var mText = mStep.getDescriptionHtml();
              
              nlen = mText.length;
              if( nlen > 6 ){
                 sStr = mText.substr( nlen-6, nlen );
                 if( sStr != '</div>' )mText+='&nbsp;&nbsp;';
              }
              mText+= '('+mStep.getDistance().html+')';
                                           
              Map_Steps.push( new Map_Steps_Obj( Map_UI_ndx, mText, latlng ) );
         }
    }
    
    display_DIR_Table();
}
//-------------------------------------------------------
function Set_Jump_Opt_Message( PtCount ){ //v3

//if(!document.getElementById("jump_opt_msg") 
//||  document.getElementById("jump_opt_msg") == null 
//||  document.getElementById("jump_opt_msg") == "undefined")return;

//if( PtCount == 0 )document.getElementById("jump_opt_msg").innerHTML = 'Start Route at Location';
//else              document.getElementById("jump_opt_msg").innerHTML = 'Draw Route to Location';

}
//-------------------------------------------------------
function Direction_Start( latlng, sRoute_Ref, sCity  ){	 //v3

   var sRef  = 'Start: ' + sRoute_Ref;   
   var mText = sRef + '<br>City: ' + sCity;
   Map_Steps.length = 0;
      
   Map_Steps.push( new Map_Steps_Obj( 0, mText, latlng ) );
   
   display_DIR_Table();
}
//-------------------------------------------------------      
function same_points( latlng_A, latlng_B ){ //v3

    
    var lat_A   = latlng_A.lat();
    var lng_A   = latlng_A.lng();
    
    var lat_B   = latlng_B.lat();
    var lng_B   = latlng_B.lng();
    
    if( lat_A == lat_B && lng_A == lng_B )return true;
    
    return false;
}
//-------------------------------------------------------
function same_as_prev_pt( latlng ){ //v3

    if( nPoints == 0 ){
        return false;
    }
    
    var prev_lat   = Map_UI[nPoints-1].mLxL.lat();
    var prev_lng   = Map_UI[nPoints-1].mLxL.lng();
    
    var this_lat   = latlng.lat();
    var this_lng   = latlng.lng();
    
    //var msg1 = '\nprev: '+prev_lat+' x '+ prev_lng;
    //var msg2 = '\nthis: '+this_lat+' x '+ this_lng;
    //var msg  = msg1 + msg2;        
    //alert(msg);
    
    if( this_lat == prev_lat 
    &&  this_lng == prev_lng )return true;
    
    return false;
}
//-------------------------------------------------------   
function show_Dir_Start( results, status ) { //v3

    var state   = '';
    var city    = '';
    var addr    = '';
    var country = '';
          
    if (! results) {
      alert("Google Maps did not return a valid response");
      addr= 'No Location info for the spot you clicked.';
      document.getElementById("spot_address" ).innerHTML = addr;
      return;
    } 
    
    if (status != google.maps.GeocoderStatus.OK) { 
        alert("Google Maps  did not return a valid response");
        addr= 'No Location info for the spot you clicked.';
        document.getElementById("spot_address" ).innerHTML = addr;
    }
           
    var latlng = results[0].geometry.location; 
    geoCode    = adx_geocode( results );
      
    var addr  = geoCode[9];
    var sRef  = 'Start: ' + addr;   
    var mText = sRef + '<br>City: ' + geoCode[2];
    Map_Steps.length = 0;
    Map_Steps.push( new Map_Steps_Obj( 0, mText, latlng ) );
   
    display_DIR_Table();
}

//------------------------------------------------------- 
function Reset_Direction_Start( latlng ){ //v3

      my_geocoder.geocode( { 'location': latlng }, show_Dir_Start );
}
//------------------------------------------------------- 
function gx_polyline( poly_pts, color ){
     
     var polyline = new google.maps.Polyline({
        path: poly_pts,
        strokeColor: '#0000FF',
        strokeOpacity: 0.5,
        strokeWeight: 5
      });
      
     polyline.setMap(map);
     
     return polyline;   
}
//-------------------------------------------------------   
  function Follow_Roads( evt_Map_UI, ndx, iCallBack  ){ //v3

        var prv_latlng = evt_Map_UI.mLxL_Prv;
        var     latlng = evt_Map_UI.mLxL; 

        bb_Walking    = false;
        bb_Avoid_Hwys = document.Map_Form.b_Avoid_Hwys.checked;
        
        evt_Map_UI.mopts = 1;
        if( bb_Avoid_Hwys )evt_Map_UI.mHwy  = 1;
        else               evt_Map_UI.mHwy  = 0;

        if( bb_Walking )tmode = google.maps.DirectionsTravelMode.WALKING;
        else            tmode = google.maps.DirectionsTravelMode.DRIVING;
        
        tmode = google.maps.DirectionsTravelMode.WALKING;
                   
        var dir_request = 
        { origin       : prv_latlng, 
          destination  : latlng,
          travelMode   : tmode,
          avoidHighways: bb_Avoid_Hwys,
          avoidTolls   : false
        };
        
// Route the directions and pass the response to a function to create markers for each step
      //progress(1);
        directionsService.route(dir_request, function( directionsResult, directionsStatus ) {
        
            if (directionsStatus == google.maps.DirectionsStatus.OK) {
                var warnings = document.getElementById("walking_id");
                warnings.innerHTML = "" + directionsResult.routes[0].warnings + "";
                
                gx_display( directionsResult, evt_Map_UI );
                //progress(0);
                if( iCallBack == 1 )Re_Route_Points( ndx+1 ); // Couldn't recursively call Re_Route_Points in that subroutine (??)
                if( iCallBack == 2 )   Route_Points( ndx+1 ); // Couldn't recursively call    Route_Points in that subroutine (??)
            }else{
                //progress(0);
            }
            
        }); 
        
  }

//-------------------------------------------------------
function Follow_Pt2pt( evt_Map_UI, ndx ){ //v3

     var b_Markers = 0;
     if( document.Map_Form.b_Markers.checked )b_Markers = 1;

     var poly_pts = new Array(2);

     poly_pts[0]  = evt_Map_UI.mLxL_Prv;
     poly_pts[1]  = evt_Map_UI.mLxL;
     
     var polyline = gx_polyline( poly_pts, '#ff0000' );     
     var meters   = google.maps.geometry.spherical.computeDistanceBetween( poly_pts[0], poly_pts[1] );
     
     plength += meters;
     display_distance( plength );          
     
     evt_Map_UI.mpoly  = polyline;          
     evt_Map_UI.mdist  = meters;          
     evt_Map_UI.mEndPt = poly_pts[1];       
     evt_Map_UI.mopts  = 0;           
     evt_Map_UI.mHwy   = 0;          

     if( b_Markers_ON == 1 ){ 
         Dist_Marks( 0, ndx, poly_pts, b_Markers ); 
         Dist_Marks( 1, ndx, poly_pts, b_Markers ); 
     }

}
//-------------------------------------------------------
function gx_display( directionResult, evt_Map_UI ) {//v3
  
  var myRoute;
  var route_path;
  var ppath;
  var polyline;
  var iPt_ndx;
  
  var b_Markers = 0;
  var dx_leg = 0;
  var end_pt_latlng;
  
  if( document.Map_Form.b_Markers.checked )b_Markers = 1;
    
  //directionResult.routes: An array of DirectionsRoutes, each of which contains information 
  //                        about the legs and steps of which it is composed. There will only 
  //                        be one route unless the DirectionsRequest was made with provideRouteAlternatives 
  //                        set to true. (This property was formerly known as "trips".)
  
  //for (var k = 0; k < directionResult.routes.length; ++k ){
      
      myRoute = directionResult.routes[0].legs[0];
      dx_leg += directionResult.routes[0].legs[0].distance.value;
      
      iPt_ndx = nPoints-1;
      io_steps( myRoute, iPt_ndx );
      
      route_path = directionResult.routes[0].overview_path;
      
      if( route_path.length > 0 ){ 
          end_pt_latlng = route_path[route_path.length-1];
          
          pt_marker_disp_v3( 1, EndRt_marker, end_pt_latlng ); // Put the end point marker square on the end of the path
          if( nPoints == 2 )pt_marker_disp_v3( 1, Start_marker, route_path[0] ); // Put the starting marker square on the start
          evt_Map_UI.mEndPt = end_pt_latlng;
          evt_Map_UI.mdist  = dx_leg;
      }
      
      var polyline = gx_polyline( route_path, '#ff0000' );
      evt_Map_UI.mpoly = polyline;
      evt_Map_UI.mopts = 1;
      evt_Map_UI.mopts = 1;

      Map_UI[iPt_ndx] = evt_Map_UI;

      if( b_Markers_ON == 1 && route_path.length > 0 ){
          Dist_Marks( 0, iPt_ndx, route_path, b_Markers );
          Dist_Marks( 1, iPt_ndx, route_path, b_Markers );
      }        
        
  //}
  
  plength += dx_leg;
  display_distance( plength );  
  
  display_DIR_Table();
}
//-------------------------------------------------------
function sx_steps( Map_UI_ndx, dir ){ //v2 (Check if other domain apps call this function

    var sDirTest = '';
    var nRoutes= dir.getNumRoutes();
    var nlen = 0;
    var sStr = '';
    
    for( var iR = 0; iR < nRoutes; ++iR ){
    
         var mRoute = dir.getRoute(iR);
         var nSteps= mRoute.getNumSteps();
         
         for( var iS = 0; iS < nSteps; ++iS ){
              var mStep = mRoute.getStep(iS);
              var latlng = mStep.getLatLng();
              
              var mText = mStep.getDescriptionHtml();
              
              nlen = mText.length;
              if( nlen > 6 ){
                 sStr = mText.substr( nlen-6, nlen );
                 if( sStr != '</div>' )mText+='&nbsp;&nbsp;';
              }
              mText+= '('+mStep.getDistance().html+')';
                                           
              Map_Steps.push( new Map_Steps_Obj( Map_UI_ndx, mText, latlng ) );
         }
    }
    
    display_DIR_Table();
}
//-------------------------------------------------------
function io_steps( myRoute, Map_UI_ndx ){ //v3

  var myHTML = '';
  var myText = '';
  var sline = '';
  
                      
      for (var iS = 0; iS < myRoute.steps.length; iS++) {
      
          Map_Steps.push( new Map_Steps_Obj( Map_UI_ndx, myRoute.steps[iS].instructions, myRoute.steps[iS].start_location ) );
            
          sline = ''+iS+'.)';
          myHTML += sline;
          
          myHTML += myRoute.steps[iS].instructions;
          myHTML += '<br>';
          
          myHTML += myRoute.steps[iS].distance.text;
          myHTML += '<br>';
          
          myHTML += myRoute.steps[iS].start_location; //latlng
          myHTML += '<br>';
          
          myText += sline;
          myText += myRoute.steps[iS].instructions;
          myText += '\n';
      }
      
  //document.getElementById("walking_id").innerHTML = myHTML;
    document.Map_Form.Diagnox.value = myText;
}
//-------------------------------------------------------
function showSteps(directionResult) { //v3??

     var markerArray = new Array();
     
  // For each step, place a marker, and add the text to the marker's
  // info window. Also attach the marker to an array so we
  // can keep track of it and remove it when calculating new
  // routes.
  
  var myHTML = '';
  
  var myRoute = directionResult.routes[0].legs[0];
  var myPath  = directionResult.routes[0].overview_path;

  for (var i = 0; i < myRoute.steps.length; i++) {
      var marker = new google.maps.Marker({
        position: myRoute.steps[i].start_point, 
        map: map
      });
      
      myHTML += "<br>"+myRoute.steps[i].instructions;
  }
  
  alert('showSteps:  routes.overview_path.length = '+ directionResult.routes[0].overview_path.length );
  
  var ppath    = directionResult.routes[0].overview_path;  
  var polyline = gx_polyline( ppath, '#ff0000' );
  
  alert('showSteps:  routes.length = '+ directionResult.routes.length );
  alert('showSteps:  steps = '+ myRoute.steps.length );
}



function attachInstructionText(marker, text) {
  google.maps.event.addListener(marker, 'click', function() {
    stepDisplay.setContent(text);
    stepDisplay.open(map, marker);
  });
}

//-------------------------------------------------------
function poly_point( dx_remaining, lxl_A, lxl_B ){ //v3

/// to_degs = 180.00/Math.PI;
var to_degs = 57.2957795;
var to_rads = 0.0174532925;
var Rm      = 6378137;

var qDxR = 0.0;
var lng1 = 0.0;
var lng2 = 0.0;

var lat1 = 0.0;
var lat2 = 0.0;
var dLon = 0.0;
var y    = 0.0;
var x    = 0.0;
var brng = 0.0;

          qDxR = dx_remaining/Rm;

          lng1 = lxl_A.lng() * to_rads;
          lng2 = lxl_B.lng() * to_rads;
          lat1 = lxl_A.lat() * to_rads;
          lat2 = lxl_B.lat() * to_rads;
          dLon = lng2 - lng1;

          sin_lat1 = Math.sin(lat1);
          sin_lat2 = Math.sin(lat2);
          cos_lat1 = Math.cos(lat1);
          cos_lat2 = Math.cos(lat2);
          cos_qDxR = Math.cos(qDxR);
          sin_qDxR = Math.sin(qDxR);

          y = Math.sin(dLon) * cos_lat2;
          x = cos_lat1*sin_lat2 - sin_lat1*cos_lat2*Math.cos(dLon);
          brng = Math.atan2(y, x);

          lat2 = Math.asin( sin_lat1*cos_qDxR + cos_lat1*sin_qDxR*Math.cos(brng) );
          lng2 = lng1 + Math.atan2(Math.sin(brng)*sin_qDxR*cos_lat1, cos_qDxR-sin_lat1*sin_lat2 );

          lat2 = lat2*to_degs;
          lng2 = lng2*to_degs;
          lxl_C = new google.maps.LatLng( lat2, lng2 );

          return lxl_C;
}

//-------------------------------------------------------
function Dist_Marks( iUnits, iPt_ndx, route_path, b_Display ){ //v3

// iUnits == 0 miles
// iUnits == 1 kms

var kilometer  = 1000;      //one thousand meters = 1km
var mile       = 1609.344;  //1609.344 meters = 1 mile
var conversion = 1;

var dx_increment = 1;

var to_degs      = 180.00/Math.PI;
var Rm           = 6378137;

   if( iUnits == 1 )dx_increment = kilometer;
   else             dx_increment = mile;

   var mmarker = null;
   var tmp;
   var lxl_A;
   var lxl_B;
   var meters;
   var dx_remaining = 0;

   var mIcon = null;

   var lat_B  = 0;
   var lng_B  = 0;
   var lat_C  = 0;
   var lng_C  = 0;
   var mrkndx = 0;

   var kUnits     = document.Map_Form.Dist_Units.value;
   var dx_markers = document.Map_Form.dx_markers.value;

   var b_Hide_KM = true;
   var b_Hide_MM = true;

   if( kUnits == 1 )b_Hide_KM = false;
   else             b_Hide_MM = false;

   if( kUnits != iUnits )b_Display = 0; // Do not Display Markers if Current Units is NOT what is getting processed here

   if( b_Display == 0 ){
       b_Hide_KM = true;
       b_Hide_MM = true;
   }

   dx_to_km   = Map_UI[iPt_ndx-1].mdx_km;
   dx_to_mile = Map_UI[iPt_ndx-1].mdx_mile;

   if( iUnits == 1 )dx_remaining = dx_increment - dx_to_km;
   else             dx_remaining = dx_increment - dx_to_mile;

   var n = route_path.length;
   lxl_A = route_path[0];

   for( var i=1; i<n; ++i ){

       lxl_B = route_path[i];
      
       meters = google.maps.geometry.spherical.computeDistanceBetween( lxl_A, lxl_B );
              
       lat_C = lxl_A.lat();
       lng_C = lxl_A.lng();
       lat_B = lxl_B.lat();
       lng_B = lxl_B.lng();

	   do{  	   
           if( meters < dx_remaining ){ 
               
               lat_C = lat_B;
               lng_C = lng_B;

               dx_remaining -= meters;

               if( iUnits == 1 )dx_to_km   += meters;
               else             dx_to_mile += meters;

           }else{
               lxl_C = poly_point( dx_remaining, lxl_A, lxl_B ); 

               if( iUnits == 1 ){

                   if( b_Display == 0 ){
                       b_Hide_KM = true;
                   }else{
                       mrkndx = D_Kilos.length%dx_markers;
                       if( mrkndx == 0 )b_Hide_KM = false;
                       else             b_Hide_KM = true;
	           }

                   if(D_Kilos.length < 100){                  
                      mmarker = new google.maps.Marker(
                      { map:map, 
                        icon:'../map_markers/mm'+(D_Kilos.length)+'.png', position:lxl_C, 
                        visible:!b_Hide_KM,
                        title: 'km:'+D_Kilos.length
                      });                               
                   }else{                
                      mmarker = new google.maps.Marker(
                      { map:map, 
                        icon:'../map_markers/marker_sm_gray.png', position:lxl_C, 
                        visible:!b_Hide_KM,
                        title: 'km:'+D_Kilos.length
                      });                      
                   }
               }else{ 

                   if( b_Display == 0 ){
                       b_Hide_MM = true;
                   }else{
                       mrkndx = D_Miles.length%dx_markers;
                       if( mrkndx == 0 )b_Hide_MM = false;
                       else             b_Hide_MM = true;
	               }

                   if(D_Miles.length < 100){       
                      var icon = '../map_markers/mm' + (D_Miles.length) +'.png';
                      var title = 'mile:'+D_Miles.length;
                      mmarker = new google.maps.Marker(
                      { map     : map, 
                        icon    : icon, 
                        position: lxl_C, 
                        visible : !b_Hide_MM,
                        title   : title
                      });  
                   }else{       
                      var icon = '../map_markers/marker_sm_gray.png';
                      var title = 'mile:'+D_Miles.length;
                      mmarker = new google.maps.Marker(
                      { map     : map, 
                        icon    : icon, 
                        position: lxl_C, 
                        visible : !b_Hide_MM,
                        title   : title
                      });  
                   }
               } 

               if( iUnits == 1 ){
                   dx_to_km = 0.0;
                   D_Kilos.push( new KM_Markers( mmarker, lxl_A, lxl_B, iPt_ndx ) );
               }else{
                   dx_to_mile = 0.0;
                   D_Miles.push( new KM_Markers( mmarker, lxl_A, lxl_B, iPt_ndx ) );
               }

               dx_remaining = dx_increment;

               lat_C = lxl_C.lat();
               lng_C = lxl_C.lng();

               lxl_A = lxl_C; 

               meters = google.maps.geometry.spherical.computeDistanceBetween( lxl_C, lxl_B );

           }

       }while( lat_C != lat_B && lng_C != lng_B );

       lxl_A = lxl_B;
   }
   
   if( iUnits == 1 )Map_UI[iPt_ndx].mdx_km   = dx_to_km;
   else             Map_UI[iPt_ndx].mdx_mile = dx_to_mile;
}
//-------------------------------------------------------
function Show_Poly_Data( mpoly ){

   var str = new String( document.Map_Form.Diagnox.value );
       str+= '\n\n';

   var tmp;
   var lxl_A;
   var lxl_B;
   var poly_pts = new Array(2);

   var n = mpoly.getVertexCount();

   lxl_A = mpoly.getVertex(0);
   lxl_B = mpoly.getVertex(1);
   poly_pts[0] = lxl_A;
   poly_pts[1] = lxl_B; 
   
   var mypolyline = gx_polyline( poly_pts, '#ff0000' );
   var meters     = mypolyline.getLength();

   tmp  = 'Start: ' + lxl_A + '\n';
   str += tmp;
   document.Map_Form.Diagnox.value = str;

   var to_rads = Math.PI/180.00;
   var to_degs = 180.00/Math.PI;

   var lng1 = lxl_A.lngRadians();
   var lng2 = lxl_B.lngRadians();

   var lat1 = lxl_A.latRadians();
   var lat2 = lxl_B.latRadians();

   dLon = lng2 - lng1;

   var Rm = 6378137;
   var dm = meters;
   var qDxR = dm/Rm;

   sin_lat1 = Math.sin(lat1);
   sin_lat2 = Math.sin(lat2);
   cos_lat1 = Math.cos(lat1);
   cos_lat2 = Math.cos(lat2);
   cos_qDxR = Math.cos(qDxR);
   sin_qDxR = Math.sin(qDxR);


   var y = Math.sin(dLon) * cos_lat2;
   var x = cos_lat1*sin_lat2 - sin_lat1*cos_lat2*Math.cos(dLon);
   var brng = Math.atan2(y, x);

   lat2 = Math.asin( sin_lat1*cos_qDxR + cos_lat1*sin_qDxR*Math.cos(brng) );
   lng2 = lng1 + Math.atan2(Math.sin(brng)*sin_qDxR*cos_lat1, cos_qDxR-sin_lat1*sin_lat2 );

   //var y = Math.sin(dLon) * Math.cos(lat2);
   //var x = Math.cos(lat1)*Math.sin(lat2) - Math.sin(lat1)*Math.cos(lat2)*Math.cos(dLon);
   //var brng = Math.atan2(y, x);

   //lat2 = Math.asin( Math.sin(lat1)*Math.cos(qDxR) + Math.cos(lat1)*Math.sin(qDxR)*Math.cos(brng) );
   //lng2 = lng1 + Math.atan2(Math.sin(brng)*Math.sin(qDxR)*Math.cos(lat1),
   //                         Math.cos(qDxR)-Math.sin(lat1)*Math.sin(lat2));


   lat2 = lat2*to_degs;
   lng2 = lng2*to_degs;
   lxl_C = new google.maps.LatLng( lat2, lng2 );

   lxl_A  = mpoly.getVertex(0);
   meters = -999;
   meters = lxl_A.distanceFrom(lxl_C);
   lxl_B  = mpoly.getVertex(1);
   diff   = lxl_B.distanceFrom(lxl_C);

   ////var mmarker = new GMarker(lxl_C);
   ////map.addOverlay( mmarker );

   tmp  = 'cmput..' + lxl_C + ' | ' + meters + '\n';
   str += tmp;
   tmp  = 'DiFF..' + diff + '\n';
   str += tmp;

   for( var i=1; i<n; ++i ){

       lxl_B = mpoly.getVertex(i);
       poly_pts[0] = lxl_A;
       poly_pts[1] = lxl_B;

       mypolyline = gx_polyline( poly_pts, '#ff0000' );
       meters     = mypolyline.getLength();

       tmp  = '...... ' + lxl_B + ' | ' + meters + '\n';
       str += tmp;

       lxl_A = lxl_B;
   }

   document.Map_Form.Diagnox.value = str;

}
//.....................................................
  function Display_Error_Msg( code ){

      var msg = '\nUnable to Generate Directions for this point.';

            if( code == 200 ){ msg = '\nNo errors occurred; the address was successfully parsed and its geocode has been returned.'; }
       else if( code == 400 ){ msg = '\nA directions request could not be successfully parsed.';
                               msg+= '\nFor example, the request may have been rejected if it contained more than';
                               msg+= '\nthe maximum number of waypoints allowed.'; }
       else if( code == 500 ){ msg = '\nA geocoding or directions request could not be successfully processed,';
                               msg+= '\nyet the exact reason for the failure is not known.'; }
       else if( code == 601 ){ msg = '\nThe HTTP q parameter was either missing or had no value.';
                               msg+= '\nFor geocoding requests, this means that an empty address was specified as input.';
                               msg+= '\nFor directions requests, this means that no query was specified in the input.'; }
       else if( code == 602 ){ msg = '\nNo corresponding geographic location could be found for the specified address.';
                               msg+= '\nThis may be due to the fact that the address is relatively new, or it may be incorrect.'; }
       else if( code == 603 ){ msg = '\nThe geocode for the given address or the route for the given directions query cannot be returned';
                               msg+= '\ndue to legal or contractual reasons.'; }
       else if( code == 604 ){ msg = '\nThe GDirections object could not compute directions between the points mentioned in the query.';
                               msg+= '\nThis is usually because there is no route available between the two points, or because Google does not have';
                               msg+= '\ndata for routing in that region.'; }
       else if( code == 610 ){ msg = '\nThe given key is either invalid or does not match the domain for which it was given.'; }
       else if( code == 620 ){ msg = '\nToo Many Queries to Handle\nPlease Try again.';   }
       else                  { msg = '\nUnable to Generate Directions for this point';
                               msg+= '\nTry changing the zoom scale to narrow the possibilites.';
                               msg+= '\n\nOR: For some locales you might want to Turn OFF "Follow Roads."';
                               msg+= '\n\nError Code: ';
                               msg+=  code; }

      alert(msg);
  }
//.....................................................
  function remove_previous(){ //v3

    if( nPoints == 0 )return;

    var i   = 0;
    var iss = 0;
    var ndx = nPoints-1;
               
    del_dir_by_route( ndx );
    
    if( nPoints > 0 ){
   
        iss = D_Miles.length-1;
        if( iss > 0 ){
        for( i=iss; i > 0; --i ){
        	  if( D_Miles[i].mndx == ndx ){
        	      D_Miles[i].mmarker.setVisible( false ); 
        	      --D_Miles.length;
        	  }
        }}
 
        iss = D_Kilos.length-1;
        if( iss > 0 ){
        for( i=iss; i > 0; --i ){
        	  if( D_Kilos[i].mndx == ndx ){
        	      D_Kilos[i].mmarker.setVisible( false );
        	      --D_Kilos.length;
        	  }
        }}
                                                   
        if( ndx != 0 && Map_UI[ndx].mpoly != null ){                
            plength -= Map_UI[ndx].mdist;
            display_distance( plength );               
        }
    }
    
    
    // If this is the First Point, remove the starting marker
    if( ndx == 0 )pt_marker_disp_v3( 0, Start_marker );
    else          pt_marker_disp_v3( 0, EndRt_marker );
    
    if( ndx > 0 )Map_UI[ndx].mpoly.setMap( null );
    
    --Map_UI.length;
    --nPoints;
    var ndx = nPoints-1;
    if( ndx > 0 )pt_marker_disp_v3( 1, EndRt_marker, Map_UI[ndx].mEndPt ); 
        
    b_Modified = 1;
    display_route_npoints();
    
    if( nPoints == 0 )protect_route(1);

  }
//-------------------------------------------------------
function display_route_npoints(){

  var sPts = ''+nPoints;
  document.getElementById("marker_count").innerHTML = 'Pts: '+sPts;
  display_route_status( 1 );
  Jump_To_On_Off();
  
}
//.....................................................
function display_route_status( iStatus ){

}
//-------------------------------------------------------
function display_start_button( nPts ){

    if( nPts == 0 )document.getElementById("start_pause" ).innerHTML = '<strong>Start</strong>';
    else           document.getElementById("start_pause" ).innerHTML = '<strong>Continue</strong>';
}    
//-------------------------------------------------------
function map_opts_disableDoubleClickZoom_v3( b_Bool ){

    var map_opts = {
        disableDoubleClickZoom: b_Bool
    };
    map.setOptions(map_opts);
}    
//-------------------------------------------------------
function cursor_control_v3( iMode ){

    var sCursor = 'move';
    var b_disable_Zoom = true;

    if( iMode == 0 ){
        sCursor = 'default';
        b_disable_Zoom   = false;	  
    }else{
        sCursor = 'crosshair';
        b_disable_Zoom   = true;	  
    
    }

    var map_opts = {
        draggableCursor: sCursor,
        disableDoubleClickZoom: b_disable_Zoom
    };
    
    map.setOptions(map_opts);

}    
//-------------------------------------------------------
  function map_router( iMode ){

    //alert('map_router iMode ='+iMode );
    var href = '';
    var msg  = '';
      
    
    switch (iMode) {
    case 0:
          cursor_control_v3( 0 );
          
	  href = '<a href="javascript:map_router(1)" title="Click to pick Route Points"><img src="../icons/play_24.gif" width="24" height="24" border="0"></a>';
	  
	  display_start_button( nPoints );
	  
	  iState = 0;
	  display_route_status( 0 );
	  mapping_state( iState );
	  break;
    case 1:
	  if( iState == 2 ){
	      spot_info_off();
	      return;
	  }
	  
          POI_OFF();
          spot_info_off();
	  
	  RtZoom = map.getZoom();
	  
          cursor_control_v3( 1 );
          
	  href = '<a href="javascript:map_router(0)"  title="Click to PAUSE Route"><img src="../icons/pause_24.gif" width="24" height="24" border="0"></a>';
	  document.getElementById("start_pause").innerHTML = '<strong>Pause</strong>';
	  
	  iState = 1;
	  display_route_status( 1 );
	  ////mapping_state( iState );
	  break;
    case 2:
	  if( iState == 1 ){
	      map_router( 0 );
	      return;
	  }
          cursor_control_v3( 1 );//crosshair
	  href = '<a href="javascript:map_router(1)" title="Click to pick Route Points"><img src="../icons/play_24.gif" width="24" height="24" border="0"></a>';

	  display_start_button( nPoints );
	  
	  iState = 2;
	  display_route_status( 0 );
	  map_opts_disableDoubleClickZoom_v3( false );
	  mapping_state( iState );
	  break;
    case 3:
	  if( iState == 1 ){
	      map_router( 0 );
	      return;
	  }
          cursor_control_v3( 1 );//crosshair
	  href = '<a href="javascript:map_router(1)" title="Click to pick Route Points"><img src="../icons/play_24.gif" width="24" height="24" border="0"></a>';

	  display_start_button( nPoints );
	
	iState = 3;
	  display_route_status( 0 );
	  map_opts_disableDoubleClickZoom_v3( false );
	  mapping_state( iState );
	  break;
    default:
        break;
    }

    document.getElementById("marker_ctrl").innerHTML = href;

  }
//-------------------------------------------------------
    function set_cookie ( name, value, exp_y, exp_m, exp_d, path, domain, secure )
    {
      var cookie_string = name + "=" + escape ( value );

      if ( exp_y )
      {
        var expires = new Date ( exp_y, exp_m, exp_d );
        cookie_string += "; expires=" + expires.toGMTString();
      }

      if ( path )
            cookie_string += "; path=" + escape ( path );

      if ( domain )
            cookie_string += "; domain=" + escape ( domain );

      if ( secure )
            cookie_string += "; secure";

      document.cookie = cookie_string;
    }
//-------------------------------------------------------
    function get_cookie ( cookie_name )
    {
      var results = document.cookie.match ( '(^|;) ?' + cookie_name + '=([^;]*)(;|$)' );

      if ( results )
        return ( unescape ( results[2] ) );
      else
        return null;
}

//-------------------------------------------------------
  function set_pos_data(){

     var center = map.getCenter();

     var map_ID = map.getMapTypeId();
     
     mapType = map_ID.toLowerCase();
                                 document.Map_Form.iMapType.value = 0;
     if( mapType == 'roadmap'   )document.Map_Form.iMapType.value = 0;
     if( mapType == 'satellite' )document.Map_Form.iMapType.value = 1;
     if( mapType == 'hybrid'    )document.Map_Form.iMapType.value = 2;
     if( mapType == 'terrain'   )document.Map_Form.iMapType.value = 3;

     document.Map_Form.Latitude.value  = center.lat();
     document.Map_Form.Longitude.value = center.lng();
     document.Map_Form.ZoomScale.value = map.getZoom();

     set_cookie ( "google_map_type", document.Map_Form.iMapType.value );
  }
//.....................................................
  function alert_zoom_scale(){

      var sZoom = new String(document.Map_Form.ZoomScale.value);
      var izoom = parseInt(sZoom, 10);

      //if( izoom > 17 ){
      //var msg  = '\nCurrent Zoom Scale = '+izoom;
      //    msg += '\n\nZoom Scales Greater than "17" will not Redisplay in Map Mode when you reopen this Map - You will have to Zoom Out.';
      //    msg += '\n\nSave anyway ?';
      //
      //    if( confirm( msg ) )return true;
      //    else return false;
      //}

      return true;
  }
//-------------------------------------------------------
  function del_Map_Pos( Map_Pos_ID ){
  
    var msg ='\nDelete this Map from your Map List ? (Note: Cannot Undo Once Deleted)';
	if( confirm(msg) ){
	    var href = 'My_Map_Delete.cfm?Del_Record_ID='+Map_Pos_ID;
	    location.replace( href );
	}
  }
//-------------------------------------------------------
  function del_route(){
    var msg ='';
	var Route_ID = document.Map_Form.Route_OSN.value;

	if( Route_ID == 0 ){
        msg ='\nThis Route has not yet been saved - Cannot Delete.';
	    return;
	}

    msg ='\nDelete this Route from your Account ? (Note: Cannot Undo Once Deleted)';

	if( confirm(msg) ){
	    var latlng = map.getCenter();
	    var lat = latlng.lat();
	    var lng = latlng.lng();
	    var href = 'My_Route_Delete.cfm?Del_Record_ID='+Route_ID+'&ctrlat='+lat+'&ctrlng='+lng;
	    location.replace( href );
	}

  }
//-------------------------------------------------------
// These 3 utilities are called from the Flash component
function set_opts_Avoid_Hwys( iValue ){
    document.Map_Form.opts_Avoid_Hwy.value = iValue;
}
function set_opts_Walking( iValue ){
    document.Map_Form.opts_Walking.value = iValue;
}
function set_opts_Value( iValue ){
  //Follow Roads   = 1
  //Point to Point = 0
  //Bicycling      = 2
    document.Map_Form.opts_Misc.value = iValue;
}
//-------------------------------------------------------
function CloseDiv( divid ){


  if (document.getElementById(divid)) {
      document.getElementById(divid).style.display = 'none';
  }
  
}
//.....................................................
function ShowDiv( divid ){

  var str = new String( document.getElementById(divid).style.display );

  if( str == 'none' || str == '' ){
      document.getElementById(divid).style.display = 'block';
  }

}
//.....................................................
function toggleDiv( divid ){

var str = new String( document.getElementById(divid).style.display );

  if( str == 'none' || str == '' ){
      document.getElementById(divid).style.display = 'block';
  }else{
      document.getElementById(divid).style.display = 'none';
  }

}
//-------------------------------------------------------
function info_save_as(){
	arg = 'UG_Jot_Map_Locs.cfm';
	if ( help_win && !help_win.closed){ help_win.close() }
	help_win = window.open( arg, 'help_win', 'menubar=yes,scrollbars=yes,resizable=yes,width=750, height=575' );
}
//.....................................................
function info_goto_location(){
	arg = 'UG_Jot_Map_Locs.cfm';
	if ( help_win && !help_win.closed){ help_win.close() }
	help_win = window.open( arg, 'help_win', 'menubar=yes,scrollbars=yes,resizable=yes,width=750, height=575' );
}
//.....................................................
function info_save_route(){
	arg = 'UG_Route_Save.cfm';
	if ( help_win && !help_win.closed){ help_win.close() }
	help_win = window.open( arg, 'help_win', 'menubar=yes,scrollbars=yes,resizable=yes,width=750, height=575' );
}
//.....................................................
function info_create_route(){
	arg = 'UG_Route_Create.cfm';
	if ( help_win && !help_win.closed){ help_win.close() }
	help_win = window.open( arg, 'help_win', 'menubar=yes,scrollbars=yes,resizable=yes,width=750, height=575' );
}
//.....................................................
function info_my_routes(){
	arg = 'UG_My_Routes.cfm';
	if ( help_win && !help_win.closed){ help_win.close() }
	help_win = window.open( arg, 'help_win', 'menubar=yes,scrollbars=yes,resizable=yes,width=750, height=575' );
}
//.....................................................
function Not_Found(){
    var msg = '\nLocation NOT FOUND.  Try again.';
    alert(msg);
}
//.....................................................
function Spot_Requests_Too_Many(){
    var msg = '\nToo Many "Spot" Requests - Try again after a brief puase.';
    alert(msg);
}
//-------------------------------------------------------
function Jump_To_On_Off(){

   var cName = document.Map_Form.Mail_Code.className;
   //if( nPoints == 0 ){
       if( cName != 'border_lhooq'     ){
           document.Map_Form.Mail_Code.className='border_lhooq';
           document.Map_Form.Mail_Code.value='';
       }
   //}else{
   //    if( cName != 'border_lhooq_dim' ){
   //        document.Map_Form.Mail_Code.className='border_lhooq_dim';
   //        document.Map_Form.Mail_Code.value='Jump To DISABLED';
   //    }
   //}

}
//-------------------------------------------------------
function open_dir_win(){

    var itoggle = 1; 
    var nLen    = Map_Steps.length; 	
    var IO      = '';
    
    var sDelim = String.fromCharCode(9);
    var sDelim = escape(sDelim);
    
    if( nLen == 0 ){
        alert('\nNo Directions Yet to Display.');
        return;
    }
    
    for( var i = 0; i < nLen-1; ++i ){
    
        if( Map_Steps[i].Map_UI_ndx != -1 ){
            IO += escape(Map_Steps[i].mText);
            IO += sDelim;
        }
    }
    
    i=nLen-1;
    if( Map_Steps[i].Map_UI_ndx != -1 ){
        IO += escape(Map_Steps[i].mText);
    }
    
    if( IO.length == 0 ){
        alert('\nNo Directions Yet to Display.');
        return;
    }
    
    document.Map_Form.DIR_IO.value = IO;
 
    var newWindow = window.open( 'my_directions.html', '_blank');
    newWindow.focus();    
    
}
//-------------------------------------------------------
function sx_dir_opts_table(){
    var tbl = '';
    tbl = '<table border="0" cellspacing="0" cellpadding="0">';
    tbl+= '      <tr>';
    tbl+= '        <td><a href="javascript:Toggle_DIR_Display();" title="HIDE Directions Sidebar"><img src="../icons/close_16.gif" width="16" height="16" border="0" /></a></td>';
    tbl+= '        <td><img src="../images/spacer.gif" width="8" height="5"></td>';
    tbl+= '        <td><a href="javascript:about_directions();" title="About Directions"><img src="../icons/about_16.gif" width="16" height="16" border="0" /></a></td>';
    tbl+= '        <td><img src="../images/spacer.gif" width="8" height="5"></td>';
    tbl+= '        <td><a href="javascript:regen_dir();" title="Refresh Directions"><img src="../icons/ref_16.gif" width="16" height="16" border="0" /></a></td>';
    tbl+= '        <td><img src="../images/spacer.gif" width="8" height="5"></td>';
    tbl+= '        <td><a href="javascript:open_dir_win();" title="Open Directions in New Window"><img src="../icons/opnbr_16.gif" width="16" height="16" border="0" /></a></td>';
if( Map_POI.length > 0 ){
    tbl+= '        <td><img src="../images/spacer.gif" width="8" height="5"></td>';
    tbl+= '        <td><img src="../images/spacer.gif" width="8" height="5"></td>';
    tbl+= '        <td><a href="javascript:Toggle_POI_Display( 1 );" title="Display Points of Interest in Sidebar"><img src="../icons/map_a.gif" width="16" height="16" border="0"></a></td>';
}
    tbl+= '      </tr>';
    tbl+= '    </table>';
    return tbl;
}
//-------------------------------------------------------
function sx_table_DIR(){
    
    var tbl = '';
    tbl = '<table width="300" border="0" cellspacing="0" cellpadding="1">';
    tbl+= '  <tr>';
    tbl+= '    <td colspan="2">';
    tbl+=      sx_dir_opts_table();
    tbl+= '    </td>';
    tbl+= '  </tr>';
    tbl+= '  <tr>';
    tbl+= '    <td  colspan="2" width="299" class="poi_heading" >&nbsp;Directions:&nbsp;</td>';
    tbl+= '  </tr>';
    tbl+= '  <tr>';
    tbl+= '    <td colspan="2"><hr size="1" /></td>';
    tbl+= '</tr>';

    return tbl;
}
//-------------------------------------------------------
function sx_row_dir( irow, ndx, sText, itoggle ){

  var row_dir = '';
  
  if( itoggle == 1 )row_dir = '<tr bgcolor="#FFFFFF" >';
  else              row_dir = '<tr bgcolor="#EFEFEF" >';

  row_dir+= '    <td valign="top"><table width="100%" border="0" cellspacing="0" cellpadding="0">';
  row_dir+= '      <tr>';
  row_dir+= '        <td>';
  row_dir+= '      <a title="Modify or Delete this Direction" href="javascript:edit_dir(' +ndx+ ');"> ';
  row_dir+= '      <img src="../icons/edit_16.gif" width="16" height="16" border="0" /></a>';        
  row_dir+= '        </td>';
  row_dir+= '      </tr>';
  row_dir+= '      <tr>';
  row_dir+= '        <td>';
  row_dir+= '      <a title="Show the location associated with this direction" href="javascript:pinpoint_dir(' +ndx+ ');">';
  row_dir+= '      <img src="../icons/bullet_layout.gif" width="15" height="15" border="0" /></a>';
  row_dir+= '        </td>';
  row_dir+= '      </tr>';
  row_dir+= '    </table></td>';
  row_dir+= '    <td valign="top">'+irow+')'+ sText +'</td>';
  row_dir+= '  </tr>';
  
  return row_dir;
}
//-------------------------------------------------------
function sx_hr_dir( ndx, sText ){
  var row_dir = '';
  row_dir = '<tr>';
  row_dir+= '  <td colspan="2"><hr size="1"</td>';
  row_dir+= '</tr>';
  return row_dir;
}
//-------------------------------------------------------

var info_win_listener = null;

function pinpoint_dir(ndx){ //v3

    var bounds = map.getBounds();
    var latlng = Map_Steps[ndx].mLxL; 

    if( !bounds.contains(latlng) ){
        map.setCenter( latlng );
    }

    dir_marker_display( latlng );
        
    dir_infoWindow.setContent( Map_Steps[ndx].mText );
    dir_infoWindow.open( map, dir_marker );

    info_win_listener = google.maps.event.addListener( dir_infoWindow, "closeclick", function() {
        dir_marker_remove();
        google.maps.event.removeListener( info_win_listener );
    });
    
}
//-------------------------------------------------------
function dir_display_off(){
    
    b_DIR_Displayed = 0;    
    document.getElementById("POI_Table_ID").innerHTML = '<img src="images/spacer.gif" width="1" height="1">';

}
//-------------------------------------------------------
function dir_display_on(){
    
    b_DIR_Displayed = 1;
    display_DIR_Table();

}
//-------------------------------------------------------
function Toggle_DIR_Display(){
    
    b_DIR_Displayed = 1 - b_DIR_Displayed;
    
    if( b_DIR_Displayed == 1 ){
        display_DIR_Table();
    }else{
        document.getElementById("POI_Table_ID").innerHTML = '<img src="images/spacer.gif" width="1" height="1">';
    }
    
    resize();

}
//-------------------------------------------------------
function display_DIR_Table(){

    if( b_DIR_Displayed == 0 )return;
    
    if( b_POI_Displayed != 0 ){
        b_POI_Displayed  = 0;
    }

    var itoggle = 1; 
    var nLen    = Map_Steps.length; 	
    var IO      = '';
    var irow    = 0;

    IO += sx_table_DIR();
    
    for( var i = 0; i < nLen; ++i ){
    
        if( Map_Steps[i].Map_UI_ndx != -1 ){
            itoggle = 1-itoggle;
            ++irow;
            IO += sx_row_dir( irow, i, Map_Steps[i].mText, itoggle );
        }
    }

    IO += '</table>';
    document.getElementById("POI_Table_ID").innerHTML = IO;
  
}
//-------------------------------------------------------
function edit_dir( ndx ){
    
    document.Map_Form.Route_Dir.value = Map_Steps[ndx].mText;
    document.Map_Form.DIR_Ndx.value = ndx;
    
    ShowDiv( 'dir_id_div' );

}
//-------------------------------------------------------
function close_dir_edit(){

    document.Map_Form.Route_Dir.value   = '';
    document.Map_Form.DIR_Ndx.value     = -1;
                     
    CloseDiv( 'dir_id_div' );   

}
//-------------------------------------------------------
function help_directions(){

    arg = 'UG_My_Routes.cfm';
    if ( help_win && !help_win.closed){ help_win.close() }
    help_win = window.open( arg, 'help_win', 'menubar=yes,scrollbars=yes,resizable=yes,width=750, height=575' );

}
//-------------------------------------------------------
function about_directions(){

    arg = 'UG_My_Routes.cfm';
    if ( help_win && !help_win.closed){ help_win.close() }
    help_win = window.open( arg, 'help_win', 'menubar=yes,scrollbars=yes,resizable=yes,width=750, height=575' );

}
//-------------------------------------------------------
function save_directions(){
    
    var ndx = document.Map_Form.DIR_Ndx.value;
    
    if( Map_Steps.length == 0 )return;
    if( ndx < 0 )return;
    if( ndx > Map_Steps.length-1 )return;
    
    Map_Steps[ndx].mText = document.Map_Form.Route_Dir.value;
    close_dir_edit();
    
    display_DIR_Table();
    
}
//-------------------------------------------------------
function del_dir_by_route( ndx ){

    if( Map_Steps.length == 0 )return;
    
    for( var i=0; i< Map_Steps.length; ++i ){
         if( Map_Steps[i].Map_UI_ndx == ndx ) Map_Steps[i].Map_UI_ndx = -1;            
    }
    display_DIR_Table();

}
//-------------------------------------------------------
function delete_directions(){

    var msg ='\nDelete this Direction from the List ? (Note: Cannot Undo Once Deleted)';
    
    if( confirm(msg) ){    
        var ndx = document.Map_Form.DIR_Ndx.value;
    
        if( Map_Steps.length == 0 )return;
        if( ndx < 0 )return;
        if( ndx > Map_Steps.length-1 )return;
        
        Map_Steps[ndx].Map_UI_ndx = -1;
        
        close_dir_edit();
        display_DIR_Table();
    }

}
//-------------------------------------------------------
function DIR_to_XML(){

    var sXML      = ''
    var ndx       = '';
    var sDir      = '';
    
    if( Map_Steps.length == 0 )return sXML;

    sXML = '<?xml version="1.0" encoding="UTF-8"?>';
    sXML+= '<route_directions name="DIRECTIONS" >';

    for( var i=0; i<Map_Steps.length; ++i ){

         if( Map_Steps[i].Map_UI_ndx >= 0 ){

             var instr = escape( Map_Steps[i].mText );//Route Instructions
             var lat   = Map_Steps[i].mLxL.lat();
             var lng   = Map_Steps[i].mLxL.lng();

             sXML+= '<STEP id="' +i+ '" >';
             sXML+= '    <lat>'      + lat       + '</lat>';
             sXML+= '    <lng>'      + lng       + '</lng>';
             sXML+= '    <instr>'+ instr+'</instr>';
             sXML+= '</STEP>'
         }
    }
    sXML+= '</route_directions>';

    return sXML;
}
//.....................................................
function regen_dir(){

    var msg = '\nRefresh Route Directions ??'
        msg+= '\n\nNOTE: This Erases all modifications made through the "Edit Directions" resource.';
        
    if( !confirm(msg) ){
        return;
    } 

    ////map.removeOverlay( Map_UI[0].mmarker );

    for( var i=1; i< Map_UI.length; ++i ){
         if( Map_UI[i].mpoly != null )map.removeOverlay( Map_UI[i].mpoly );
    }

    for( var i=1; i< D_Miles.length;++i ){
           map.removeOverlay( D_Miles[i].mmarker );
    }

    for( var j=1; j< D_Kilos.length; ++j ){
           map.removeOverlay( D_Kilos[j].mmarker );
    }

    Map_Steps.length = 0;
    nPoints          = 0;
    b_Modified       = 0;
    plength          = 0;
    dx_to_km         = 0;
    dx_to_mile       = 0;

    display_route_npoints();
    display_distance( plength );
    protect_route(1);
    display_DIR_Table();
        
    D_Miles.length = 0;
    D_Kilos.length = 0;

    D_Kilos.push( new KM_Markers( null, null, null, 0 ) );
    D_Miles.push( new KM_Markers( null, null, null, 0 ) );

    CloseDiv( "save_route_div" );

    map.addOverlay( standby_overlay );
    
    Re_Route_Points(0);
    
}
//.....................................................

// -->
