 
var gdirections;
var gLine2;
var river_select;
var river_text_input;
var img_html = "<img src="
var beginMarker;
var old_marker;
var trip_flag = 0;
var trip_distance = 0;
var avg_lat = 0;
var avg_lon = 0;
var marker_length;
var C_ADD_MARKER = 1;
var C_NO_MARKER = 0;
var edit_trip_flag = 0;
var mgr;

function formatField( fieldValue ) {
 return fieldValue = fieldValue.replace(/\n/g, "<br/>");
}


function load() {
  //switchOffPutInForm();
  //switchOffDamForm();
  switchOffDirections();



  if (GBrowserIsCompatible()) {
    river_select = $("riverSelectID");
    river_dam_select = $("DamForm_river_name");
    river_text_input = INPUT( {'type' : 'text', 'style':'width:50mm', 'name' : 'river', 'value': 'Enter name of new river/lake', 'id': 'riverTextID'} );
    river_dam_text_input = INPUT( {'type' : 'text', 'style':'width:50mm', 'name' : 'river', 'value': 'Enter name of new river/lake', 'id': 'riverDamTextID'} );

    map = new GMap2(document.getElementById("map"));
    map.setMapType(G_HYBRID_MAP);

    //map.G_SATELLITE_MAP
    //map.G_SATELLITE_TYPE
    //map.G_PHYSICAL_MAP_
    //map.G_HYBRID_TYPE;

    map.addControl(new GLargeMapControl());
    map.addControl(new GScaleControl());
    //map.addControl(new GMapTypeControl());
    map.addControl(new GHierarchicalMapTypeControl());
    map.addMapType(G_PHYSICAL_MAP);

    //map.setUIToDefault();


    //Get center lat and lon from hidden input field.
    var center_gps_lat = $("center_gps_lat").value;
    var center_gps_lon = $("center_gps_lon").value;

    center_zoom_level_string = $("center_zoom_level").value;
    var center_zoom_level = parseInt(center_zoom_level_string);  

    //map.setCenter(new GLatLng(float(center_gps_lon), float(center_gps_lat)), 13);
    map.setCenter(new GLatLng(42.2, -88.1419), 13);
    //alert(map.getZoom());

    //add ad marker manager to manage marker visibility at various zoom levels
    //var mgrOptions = { borderPadding: 50, maxZoom: 17, trackMarkers: true };
    var mgrOptions = { borderPadding: 50 };
    mgr = new MarkerManager(map, mgrOptions); 


    //This code contains the yellow kayaker image and size attributes.
    var kayak_icon = new GIcon();
    kayak_icon.image = "/static/images/icons/icon_kayak.png";
    kayak_icon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
    //kayak_icon.iconSize = new GSize(17, 22);
    kayak_icon.iconSize = new GSize(14, 18);
    kayak_icon.shadowSize = new GSize(0, 0);
    kayak_icon.iconAnchor = new GPoint(6, 20);
    kayak_icon.infoWindowAnchor = new GPoint(5, 1);
    display_icon = kayak_icon;
	    

    var startIcon = new GIcon();
    startIcon.image = "static/images/icons/icon_16_button_green.png"
    startIcon.iconSize = new GSize(16, 16);
    startIcon.shadow = "static/images/icons/icon_16_button_red.png"
    startIcon.shadowSize = new GSize(16, 16);
    startIcon.iconAnchor = new GPoint(10, 34);
    startIcon.infoWindowAnchor = new GPoint(10, 1);


    //Get the GPX filename from a hidden input field
    //If we load a gpx file then center the map based on the points in the file, else, center on hidden form field passed in.
    if ($("gpx_filename").value!=""){
        var gpx_filename_string = $("gpx_filename").value;
        var gpx_id_string = $("gpx_id").value;
        //alert(gpx_filename_string);
        loadGPXRoutes(gpx_filename_string);

        //open up the window displaying the info for the gpx route/trip
        
        switchOnViewTripForm(gpx_id=gpx_id_string);    
        //switchOnViewTripForm();    
        }
    else{
        //map.setCenter(new GLatLng(center_gps_lat, center_gps_lon), center_zoom_level, G_PHYSICAL_MAP); //Center on hidden form value.
        map.setCenter(new GLatLng(center_gps_lat, center_gps_lon), center_zoom_level, G_HYBRID_MAP); //Center on hidden form value.
        var point = new GLatLng(parseFloat(center_gps_lat),parseFloat(center_gps_lon));
    }
  }

    var put_in_list = loadJSONDoc("/load_put_ins");
    put_in_list.addCallback(displayPut_ins);

    var dam_list = loadJSONDoc("/load_dams");
    dam_list.addCallback(displayDams);

    var rentals_list = loadJSONDoc("/load_rentals");
    rentals_list.addCallback(displayRentals);


    //loadGPXRoutes("kishwaukee_south_branch.txt");
    //loadGPXRoutes("kishwaukee_north_branch.gpx");
    //loadGPXRoutes("nippersink_glacial_park_to_xxx.gpx");
    //loadGPXRoutes("desplaines_river.gpx");
    //loadGPXRoutes("salt_creek_schaumburg_rolling_meadows.gpx");
}


function usgs_clicked(){
    if ($("usgs_checkbox_id").checked )
    {   //map.savePosition();
        var usgs_list = loadJSONDoc("/load_usgs");
        usgs_list.addCallback(displayUSGS);
	//map.returnToSavedPosition(); 
    }
    else {
   
    }

}


// Creates a marker at the given point with the given number label
function createMarker(point, icon, windowText, title) {
    var marker = new GMarker(point, icon);


    var styledWindowText = "";

    //Add a css class .iwstyle for the info window text
    styledWindowText = "<span class='iwstyle'>" + windowText + "</span>"; 

    GEvent.addListener(marker, "click", function() {
		    marker.openInfoWindowHtml(styledWindowText,{maxWidth:600});
		    //marker.openInfoWindowHtml(windowText);

                    //Add the coords to the destination address form
                    document.directions_form.end_addr.value = point.y + "," + point.x; 
                    document.DamForm.DamForm_gps_lon.value = point.x;
                    document.DamForm.DamForm_gps_lat.value = point.y;
    });
    return marker;
}
    
var displayPut_ins = function(self, put_ins) {
    newline= "<br/>";
    href_close = "</a>";
    href_start = "<a  href=\"put_ins?put_in_id_param=";
    quote = "\"";
    bracket_close = ">";

    //This is the global marker event listner, despite being inside of displayPut_ins function.
    GEvent.addListener(map, "click", function(marker, point) {
      //Check if a marker was clicked, if so dont' add another marker on top of it.
      if (marker) {
        var marker_point = marker.getPoint();
        updateGPSCoord(marker_point, C_NO_MARKER);
     }
      //A point without a marker was clicked, add a marker at this point. 
      else {
        updateGPSCoord(point, C_ADD_MARKER);

        //Add the coords to the destination address form
        document.directions_form.end_addr.value = point.y + "," + point.x; 
        document.DamForm.DamForm_gps_lon.value = point.x;
        document.DamForm.DamForm_gps_lat.value = point.y;
        //map.addOverlay(new GMarker(point));
      }
    });

    //This code contains the yellow kayaker image and size attributes.
    var kayak_icon = new GIcon();
    kayak_icon.image = "/static/images/icons/icon_kayak.png";
    kayak_icon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
    //kayak_icon.iconSize = new GSize(17, 22);
    kayak_icon.iconSize = new GSize(14, 18);
    kayak_icon.shadowSize = new GSize(0, 0);
    kayak_icon.iconAnchor = new GPoint(6, 20);
    kayak_icon.infoWindowAnchor = new GPoint(5, 1);
    display_icon = kayak_icon;

    var markers = [];
    var markers_sparse = [];
	    
    for (var i = 0; i < self.put_ins.length; i++) {
      var point = new GLatLng(parseFloat(self.put_ins[i][1]),parseFloat(self.put_ins[i][2]));
      info_window_text = href_start + self.put_ins[i][0] + quote + bracket_close + self.put_ins[i][6] + ", " + self.put_ins[i][3] + href_close + newline + newline + self.put_ins[i][5];
      title = self.put_ins[i][6];
      info_window_text = formatField(info_window_text);
      map.addOverlay(createMarker(point, display_icon, info_window_text, title));
/*
      if (i % 4 == 0){
          //mgr.addMarker( , 1);
          markers_sparse.push(createMarker(point, display_icon, info_window_text, title));
      } 
      else {
          //mgr.addMarker( createMarker(point, display_icon, info_window_text, title), 8);
          markers.push(createMarker(point, display_icon, info_window_text, title));
      }

*/
    }
/*
    mgr.addMarkers(markers,8);	
    mgr.addMarkers(markers_sparse,1);	

    mgr.refresh();
*/
    return false;
}

var displaySinglePut_in = function(put_in) {
    newline= "<br/><br/>";
    href_close = "</a>";
    href_start = "<a  href=\"";
    quote = "\"";
    bracket_close = ">";

    //This code contains the yellow kayaker image and size attributes.
    var kayak_icon = new GIcon();
    kayak_icon.image = "/static/images/icons/icon_kayak_red.png";
    kayak_icon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
    kayak_icon.iconSize = new GSize(17, 22);
    kayak_icon.shadowSize = new GSize(0, 0);
    kayak_icon.iconAnchor = new GPoint(6, 20);
    kayak_icon.infoWindowAnchor = new GPoint(5, 1);
    display_icon = kayak_icon;

    var point = new GLatLng(parseFloat(put_in[1]),parseFloat(put_in[2]));
    info_window_text = href_start + put_in[4] + quote + bracket_close + put_in[6] + ", " + put_in[3] + href_close + newline; 
    title = put_in[6];
    map.addOverlay(createMarker(point, display_icon, info_window_text, title));

    return false;
}


var displayDams = function(self, put_ins) {
    newline= "<br/><br/>";
    href_close = "</a>";
    href_start = "<a  href=\"";
    quote = "\"";
    bracket_close = ">";

    //This code contains the dam icon image and size attributes.
    var dam_icon = new GIcon();
    dam_icon.image = "/static/images/icons/icon_danger.png";
    //dam_icon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
    dam_icon.iconSize = new GSize(10, 10);
    dam_icon.shadowSize = new GSize(0, 0);
    dam_icon.iconAnchor = new GPoint(1, 1);
    dam_icon.infoWindowAnchor = new GPoint(5, 1);
    display_icon = dam_icon;

    var markers = [];
    var markers_sparse = [];
	    
    for (var i = 0; i < self.put_ins.length; i++) {
      dam_url = "dams?dam_id_param=" + self.put_ins[i][0]
      var point = new GLatLng(parseFloat(self.put_ins[i][1]),parseFloat(self.put_ins[i][2]));
      info_window_text = href_start + dam_url + quote + bracket_close + self.put_ins[i][6] + ", " + self.put_ins[i][3] + href_close + newline + self.put_ins[i][5];
      title = self.put_ins[i][6];

      info_window_text = formatField(info_window_text);
      map.addOverlay(createMarker(point, display_icon, info_window_text, title));

/*
      if (i % 4 == 0){
          //mgr.addMarker( createMarker(point, display_icon, info_window_text, title), 1);
          markers_sparse.push(createMarker(point, display_icon, info_window_text, title));
      } 
      else {
          //mgr.addMarker( createMarker(point, display_icon, info_window_text, title), 8);
          markers.push(createMarker(point, display_icon, info_window_text, title));

      }
*/ 
    }
/*
    mgr.addMarkers(markers,8);	
    mgr.addMarkers(markers_sparse,1);	

    mgr.refresh();
*/
    return false;
}


var displayRentals = function(self, put_ins) {
    newline= "<br/><br/>";
    href_close = "</a>";
    href_start = "<a href=\"";
    quote = "\"";
    bracket_close = ">";

    //This code contains the rental shop icon image and size attributes.
    var rental_icon = new GIcon();
    rental_icon.image = "/static/images/icons/icon_rental.png";
    //dam_icon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
    rental_icon.iconSize = new GSize(20, 20);
    rental_icon.shadowSize = new GSize(0, 0);
    rental_icon.iconAnchor = new GPoint(1, 1);
    rental_icon.infoWindowAnchor = new GPoint(5, 1);
    display_icon = rental_icon;

    var markers = [];

    for (var i = 0; i < self.put_ins.length; i++) {
      var point = new GLatLng(parseFloat(self.put_ins[i][1]),parseFloat(self.put_ins[i][2]));
      info_window_text = href_start + self.put_ins[i][4] + quote + bracket_close + self.put_ins[i][3] + ", " + self.put_ins[i][6] + href_close + newline + self.put_ins[i][5];
      title = self.put_ins[i][6];
      //map.addOverlay(createMarker(point, display_icon, info_window_text, title));
      //mgr.addMarker( createMarker(point, display_icon, info_window_text, title), 9);

      info_window_text = formatField(info_window_text);
      markers.push(createMarker(point, display_icon, info_window_text, title));

    }

    mgr.addMarkers(markers,6);	

    mgr.refresh();
    return false;
}

var displayUSGS= function(self, put_ins) {
    newline= "<br/><br/>";
    href_close = "</a>";
    href_start = "<a href=\"";
    quote = "\"";
    bracket_close = ">";

    //This code contains the rental shop icon image and size attributes.
    var rental_icon = new GIcon();
    rental_icon.image = "/static/images/icons/icon_ruler_7x18.png";
    //rental_icon.image = "/static/images/icons/icon_rental.png";
    //dam_icon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
    rental_icon.iconSize = new GSize(7, 18);
    rental_icon.shadowSize = new GSize(0, 0);
    rental_icon.iconAnchor = new GPoint(1, 1);
    rental_icon.infoWindowAnchor = new GPoint(5, 1);
    display_icon = rental_icon;

    var markers = [];
    var markers_sparse = [];

    for (var i = 0; i < self.put_ins.length; i++) {
      var point = new GLatLng(parseFloat(self.put_ins[i][1]),parseFloat(self.put_ins[i][2]));
      //info_window_text = href_start + self.put_ins[i][4] + quote + bracket_close + self.put_ins[i][3] + ", " + self.put_ins[i][6] + href_close + newline + self.put_ins[i][5] + "<br/><br/>";   
      info_window_text = 
          "USGS Flow and Depth" + 
          newline + "USGS Chart for: " + href_start + "http://waterdata.usgs.gov/usa/nwis/uv?site_no=" +
             self.put_ins[i][4] + quote + bracket_close + self.put_ins[i][3] + " - " + self.put_ins[i][5] + href_close;
          //+ newline + "PaddleAway.com Beta Chart for: " + href_start + "http://www.paddleaway.com/usgs_chart?site_num=" + 
          //   self.put_ins[i][4]  + quote + "target=" + quote + "_blank" + quote + bracket_close +
          //       self.put_ins[i][3] + " - " + self.put_ins[i][5] + href_close ;   

      title = self.put_ins[i][6];
      //map.addOverlay(createMarker(point, display_icon, info_window_text, title));
      //mgr.addMarker( createMarker(point, display_icon, info_window_text, title), 9);

      if (i % 10 == 0){
          //mgr.addMarker( createMarker(point, display_icon, info_window_text, title), 1);
          markers_sparse.push(createMarker(point, display_icon, info_window_text, title));
      } 
      else {
          //mgr.addMarker( createMarker(point, display_icon, info_window_text, title), 10);
          markers.push(createMarker(point, display_icon, info_window_text, title));

      }
 

    }

    mgr.addMarkers(markers,9);	
    mgr.addMarkers(markers_sparse,1);	

    mgr.refresh();
    return false;
}


//------------------------------------------------------------------------------------------
// Function to take the points of a polyline and add the polyline to the map. 
//------------------------------------------------------------------------------------------
function drawRoute(){
    alert("in drawRoute");
    map.removeOverlay(gLine);
    gLine=new GPolyline(arPoints); 
    map.addOverlay(gLine);
   //try{
   //  map.addOverlay(gLine);
   //}
   //catch(e){
   //  //The above line dies in IE...
   //}


}


//------------------------------------------------------------------------------------------
//  Try and load a GPX file and display it as polylines on the map.
//------------------------------------------------------------------------------------------
function loadGPXRoutes(fileName) {
    strFilePath = "/static/gpx/" + fileName; 
    var myPoints = new Array(); 
    avg_lat = 0;
    avg_lon = 0;
    var i = 0;

    center_zoom_level_string = $("center_zoom_level").value;
    var center_zoom_level = parseInt(center_zoom_level_string);  
    var bounds = new GLatLngBounds;
    var glat_lng_point; 

    var google_icon = new GIcon();

    google_icon.image = "http://labs.google.com/ridefinder/images/mm_20_red.png";
    google_icon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
    google_icon.iconSize = new GSize(12, 20);
    google_icon.shadowSize = new GSize(22, 20);
    google_icon.iconAnchor = new GPoint(6, 20);
    google_icon.infoWindowAnchor = new GPoint(5, 1);

    var distance = 0.0;
    var mile_counter = 1;

    GDownloadUrl(strFilePath, function(data, responseCode) {
        // To ensure against HTTP errors that result in null or bad data,
        // always check status code is equal to 200 before processing the data
        

        if(responseCode == 200) 
        {
            var xml = GXml.parse(data);
            var markers = xml.documentElement.getElementsByTagName("rtept");
            marker_length = markers.length
            //alert("marker_length: " + marker_length);
 
            for (i = 0; i < markers.length; i=i+1) 
            //for (var i = 0; i < markers.length; i=i+20) 
            //for (var i = 0; i < 100 ; i++) 
            {
                var x = parseFloat(markers[i].getAttribute("lon"));
                var y = parseFloat(markers[i].getAttribute("lat"));
            
                var new_point = new GPoint(x, y);
                glat_lng_point = new GLatLng(y, x);
                bounds.extend(glat_lng_point);
                myPoints.push(new_point);
           
                //-------------------------------------------------------------------------------          
                //Try and calculate the distance and add a mile marker
                if (i > 0)
                {
                    //alert("distance: " + distance);
                    var x_prev = parseFloat(markers[i-1].getAttribute("lon"));
                    var y_prev = parseFloat(markers[i-1].getAttribute("lat"));
                    glat_lng_prev = new GLatLng(y_prev, x_prev);
                    //alert("glat_lng_prev: " + glat_lng_prev + "  glat_lng_point:  " + glat_lng_point);
                
                    //center.distanceFrom(new GLatLng(center.lat()+0.1, center.lng()))/100; 
                    //alert("distanceFrom: " + glat_lng_point.distanceFrom(glat_lng_prev) * 0.000621371192); 
                    distance = distance + glat_lng_point.distanceFrom(glat_lng_prev) * 0.000621371192; 
                    //alert("distance: " + distance);
   
                    // Check if we've passed a mile marker
                    // if so go back to the previous point and add the difference between the previous point and 
                    // the mile marker and then add a marker 
                    if (distance > mile_counter)
                    {
                        //alert("i==20: " + distance);

                        var distance_delta = (distance/0.000621371192 - mile_counter);  //converted to meters
                        var slope = (y - y_prev)/(x - x_prev);
                        var delta_x = distance_delta/slope;
                        var x_marker = x - delta_x;
                        var y_marker = y - (delta_x*slope);
                        //var mile_marker_point = new GLatLng(y_marker, x_marker);
                        //var mile_marker_point = new GLatLng(y_marker, x_marker);
                        var mile_marker_point = new GLatLng(y, x);
 
                        mileMarker=createMarker(mile_marker_point, google_icon, distance.toFixed(0) + " mile(s) (not yet working, have to convert spherical GPS coordinates to a cartesian coordinate and then add an offset and then convert back to spherical GPS coords -aargh!!!)", "Start");
                        map.addOverlay(mileMarker);
                        //alert("x: " +  x_marker + "     y: " + y_marker);
                        //alert("x: " +  x_marker + "     y: " + y_marker);
                        mile_counter = mile_counter + 1;
                    }
                }
                
             
             
                //
                //-------------------------------------------------------------------------------          


                if (edit_trip_flag == 1)
                {
                    linePoints.push(new_point);
                    update_distance();
                }
                
           
                //alert("myPoints[" + i +"]" + myPoints[i]); 
           
           
                //get the average lat and lon to use as the point to center map on.
                avg_lat = avg_lat + y;
                avg_lon = avg_lon + x;
            } //end markers loop
                
           // alert("distance: " + distance);


            if (i == 0){
              map.setCenter(glat_lng_point);
              var newMarker = new GMarker(new_point, startIcon);
            } 
           
            else if (i == markers.length){
              //Divided the total lat and lon from above by the number of points to get an average.
              avg_lat =  avg_lat/(marker_length)
              avg_lon =  avg_lon/(marker_length)
              //zoom level of 11 gives about 2 miles per cm on screen
              //zoom level of 12 gives about 2 miles per 1.5 inch on screen
              //map.setCenter(new GLatLng(avg_lat, avg_lon), center_zoom_level, G_PHYSICAL_MAP); //Center on avg coordinates of gpx file 
           
            } 
           
            map.setZoom(map.getBoundsZoomLevel(bounds));
            map.setCenter(bounds.getCenter());
           
            gLine2=new GPolyline(myPoints,"#0000FF", 10); 
            //alert("gLine2.getVertexCount: " + gLine2.getVertexCount());
            
            try
              {
              //map.addOverlay(new GPolyline(myPoints));
              map.addOverlay(gLine2);
              }
            catch(e)
              {
              //alert("Failed/Excepted trying to add polyline overlay"); 
              //The above line dies in IE...
              }
            
            //alert("Finished Trying to add polyline overlay"); 

        }
 
        else if(responseCode == -1)
        {
            alert("Data request timed out. Please try later.");
        } 

        else 
        { 
            alert("Request resulted in error. Check XML file is retrievable.");
        }
    }
    );

    myPoints = [];

   return false;

}

function updateGPSCoordNoMarker(point){
    document.put_in_form.gps_lat.value = point.y;
    document.put_in_form.gps_lon.value = point.x;
    document.DamForm.DamForm_gps_lon.value = point.x;
    document.DamForm.DamForm_gps_lat.value = point.y;

    if (old_marker){
        map.removeOverlay(old_marker); //remove old marker if it exists
    }


}

function update_distance(){
    trip_distance = 0;
    //Create an array of lat and lon for all points.
    for (var i = 0; i < linePoints.length; i++) {
        if (i == 0){
        }
        else{ 
            point1 = new GLatLng(linePoints[i].y, linePoints[i].x)
            point2 = new GLatLng(linePoints[i-1].y, linePoints[i-1].x)

            trip_distance = trip_distance + point1.distanceFrom(point2)/1609.344;
        }
    } 
    $("total_miles_id").innerHTML = trip_distance.toFixed(2) + " miles"
    $("total_points_id").innerHTML = linePoints.length + " points"
}


function updateGPSCoord(point, add_marker_flag){
    document.put_in_form.gps_lat.value = point.y;
    document.put_in_form.gps_lon.value = point.x;
    document.DamForm.DamForm_gps_lon.value = point.x;
    document.DamForm.DamForm_gps_lat.value = point.y;


    var google_icon = new GIcon();

    google_icon.image = "http://labs.google.com/ridefinder/images/mm_20_red.png";
    google_icon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
    google_icon.iconSize = new GSize(12, 20);
    google_icon.shadowSize = new GSize(22, 20);
    google_icon.iconAnchor = new GPoint(6, 20);
    google_icon.infoWindowAnchor = new GPoint(5, 1);

    //distance = parseFloat(self.trips[i].distance).toFixed(2);
    var new_point = new GPoint(point.x.toFixed(5), point.y.toFixed(5)); 
    //new_point = new GPoint(point.x, point.y); 


    //Don't start drawing polylines until flag is set meaning that the trip form has been opened.
    if (trip_flag == 1){
        //Check if flag indicating first time through or the linePoints array is currently 0
        //if ((old_trip_marker_flag==0) || (linePoints.length==0)){

        //Is it first time through, i.e. no points in array yet?
        if (linePoints.length==0){
            old_point = new GLatLng(41.95, -88.3)
            old_trip_marker_flag=1;
            //map.addOverlay(createMarker(new_point, google_icon, " ", "Start"));

            //Check add_marker_flag to see if a marker should be added or no.
            //Marker will only be added if there is not a marker at the current point already.
            if(add_marker_flag==1) {
                beginMarker=createMarker(new_point, google_icon, "Test ", "Start");
                map.addOverlay(beginMarker);
            }
            linePoints.push(new_point); //add new point to the linePoints array
            $("total_points_id").innerHTML = linePoints.length + " points"
     
        }
        else{
            //Create the new line with the new point added in.
            var temp_line = new Array(); 
            temp_line[0]=new_point;
            temp_line[1]=linePoints[linePoints.length-1];

            gLine3=new GPolyline(temp_line,"#0000FF", 8); 

            linePoints.push(new_point); //add new point to the linePoints array

            update_distance();
            //remove the old overlay.
            //map.removeOverlay(gLine3); 
     
     
     
            //Create an array and line from the current point and the previous point
            //at the end of the array.
            var current_points = new Array(); 
            //current_points.push(linePoints[linePoints.length-1]);
            //current_points.push(new_point);
            //gCurrentLine = new GPolyline(current_points, "#0000FF", 8); 
            
            try
              {
              //map.addOverlay(new GPolyline(linePoints));
              map.addOverlay(gLine3);
              //map.addOverlay(gCurrentLine);
              }
            catch(e)
              {
              //alert("Failed/Excepted trying to add polyline overlay"); 
              //The above line dies in IE...
              }
            
            //alert("Finished Trying to add polyline overlay"); 
        }

    
    }
    //If a trip is not currently being added, then remove and add markers each time user clicks.
    else{
        if (old_marker){
            map.removeOverlay(old_marker); //remove old marker if it exists
        }
        current_marker=createMarker(new_point, google_icon, "Add a put-in here?", "Add put-in here");

        //Don't add another marker if an existing marker was just clicked
        if(add_marker_flag==1) {
          map.addOverlay(current_marker);
        }
        //save off the current marker into old marker so that it can be removed next time through 
        old_marker = current_marker;
    }

    old_point =  new_point;

}


function removeLinePoint(){
    if (linePoints.length==1){
        new_point_temp=linePoints.pop();          //remove the last point in array.

        map.removeOverlay(beginMarker);
        update_distance();
       }
    else{
        map.removeOverlay(gLine3); //remove old trip polyline.
        //alert(linePoints.length);

        if (linePoints.length > 1) { 
            new_point_temp=linePoints.pop();       //remove the last point in the array.
        }

        gLine3=new GPolyline(linePoints,"#0000FF", 8); 
        map.addOverlay(gLine3);    //re-draw the polyline with the last point removed.
        update_distance();
    }
}

function removeMarker(){
    if (old_marker){
        map.removeOverlay(old_marker); //remove old marker if it exists
    }
}


function saveTrip() {
    //var submit_status_pending = IMG( {'src' : '/static/images/status/status_ajax-loader_green_bar_pending.gif', 'id': 'submit_status'} );
    //var submit_status = $("submit_status");
    //swapDOM(submit_status, submit_status_pending);
    lat = "";
    lon = "";

    var url="/save_trip"


    //Create an array of lat and lon for all points.
    for (var i = 0; i < linePoints.length-1; i++) {
        if (i == 0){
            lon = linePoints[i].y;     
            lat = linePoints[i].x;     
        }
        else{ 
            lon = lon + "," + linePoints[i].y;     
            lat = lat + "," + linePoints[i].x;     
        }
    } 
   
    //alert(lat);



    data_obj =             {
            //'linePoints'  : linePoints,
            'lat'         : lat,
            'lon'         : lon,
            'name'        : document.trip_form.name.value,
            'distance'    : trip_distance.toFixed(2),
            'trip_date'   : document.trip_form.trip_date.value,
            'rating'      : document.trip_form.trip_rating.value,
            'username'    : document.trip_form.username.value,
            'description' : document.trip_form.trip_description.value
            }


    //alert(document.trip_form.trip_rating.value);

    //var d = doXHR(url,{ method:"POST", queryString:data_obj})
    //var d = doXHR(format="json", url,{ method:"POST", sendContent:data_obj})
    //var d = doXHR(url, {
    //    sendContent: MochiKit.Base.serializeJSON(data_obj),
    //    method: 'POST',
    //    'mimeType': 'text/plain',
    //    'headers': [['Accept', 'application/json']]
    //});  //.addCallback(MochiKit.Async.evalJSONRequest); 

    //var d = loadJSONDoc(url, linePoints);
    var d = loadJSONDoc(url, data_obj);

    //Wait for 1 second to allow server to update database.
    pause(3000); 

    //Once server returns data, open up the ViewTrip window to show the newly added trip.
    d.addCallback(switchOnViewTripForm());    
    return false;
}


function addPutIn() {

   var submit_status_pending = IMG( {'src' : '/static/images/status/status_ajax-loader_green_bar_pending.gif', 'id': 'submit_status'} );
   var submit_status = $("submit_status");
   swapDOM(submit_status, submit_status_pending);

    put_in_new =             {
            'river'       : document.put_in_form.river.value,
            'name'        : document.put_in_form.name.value,
            'description' : document.put_in_form.description.value,
            'city'        : document.put_in_form.city.value,
            'state'       : document.put_in_form.state.value,
            'country'     : document.put_in_form.country.value,
            'zipcode'     : document.put_in_form.zipcode.value, 
            'gps_lat'     : document.put_in_form.gps_lat.value,
            'gps_lon'     : document.put_in_form.gps_lon.value,
            'username'    : document.put_in_form.username.value,
            'url'         : document.put_in_form.url.value
            }

    //var d = doXHR(url, {
    //     method : "POST", 
    //     sendContent: put_in_new 
    //     });

    var url="/add_put_in"
    var d = loadJSONDoc(url, put_in_new);



    d.addCallback(showChanges);    
    return false;
}


var showChanges = function(self, put_in){
    //This works --> $("txtDescription").value="accessed from txtDescription";
    // $("txtDescription").value= self.put_in[2][1];

    var error_flag = 0;

    //Check if there were any errors in form submission.

    //Check status of river field.
    if (self.status[0][1] != "Good") {
        error_flag = 1;
        //Set the text in the tags to indicated and error.

        //alert(document.put_in_form.riverLabelText.value);
        $("riverID").innerHTML = document.put_in_form.riverLabelText.value + "<font color=#FF0000> ***Error***</font>";
    }
    else {
        $("riverID").innerHTML = document.put_in_form.riverLabelText.value;
        //$("riverID").innerHTML = $("riverID").labelText.value;
    }

    //Check status of name field.
    if (self.status[1][1] != "Good") {
        error_flag = 1;
        //Set the text in the tags to indicated and error.
        //$("put_in_nameID").innerHTML = $("put_in_nameID").labelText.value + " ***Error***";
        $("put_in_nameID").innerHTML = document.put_in_form.put_in_nameLabelText.value + "<font color=#FF0000> ***Error***</font>";
    }
    else {
        //$("put_in_nameID").innerHTML = $("put_in_nameID").labelText.value;
        $("put_in_nameID").innerHTML = document.put_in_form.put_in_nameLabelText.value;
    }

    //Check status of description field.
    if (self.status[2][1] != "Good") {
        error_flag = 1;
        //Set the text in the tags to indicated and error.
        //$("descriptionID").innerHTML = $("descriptionID").labelText.value + " ***Error***";
        $("descriptionID").innerHTML = document.put_in_form.descriptionLabelText.value + "<font color=#FF0000> ***Error***</font>";
    }
    else {
        //$("descriptionID").innerHTML = $("descriptionID").labelText.value;
        $("descriptionID").innerHTML = document.put_in_form.descriptionLabelText.value;
    }

    //Check status of city field.
    if (self.status[3][1] != "Good") {
        error_flag = 1;
        //Set the text in the tags to indicated and error.
        //$("cityID").innerHTML = $("cityID").labelText.value + " ***Error***";
        $("cityID").innerHTML = document.put_in_form.cityLabelText.value + "<font color=#FF0000> ***Error***</font>";
    }
    else {
        //$("cityID").innerHTML = $("cityID").labelText.value;
        $("cityID").innerHTML = document.put_in_form.cityLabelText.value;
    }

    //Check status of state field.
    if (self.status[4][1] != "Good") {
        error_flag = 1;
        //Set the text in the tags to indicated and error.
        //$("stateID").innerHTML = $("stateID").labelText.value + " ***Error***";
        $("stateID").innerHTML = document.put_in_form.stateLabelText.value + "<font color=#FF0000> ***Error***</font>";
    }
    else {
        //$("stateID").innerHTML = $("stateID").labelText.value;
        $("stateID").innerHTML = document.put_in_form.stateLabelText.value;
    }

    //Check status of country field.
    if (self.status[5][1] != "Good") {
        error_flag = 1;
        //Set the text in the tags to indicated and error.
        //$("countryID").innerHTML = $("countryID").labelText.value + " ***Error***";
        $("countryID").innerHTML = document.put_in_form.countryLabelText.value + "<font color=#FF0000> ***Error***</font>";
    }
    else {
        //$("countryID").innerHTML = $("countryID").labelText.value;
        $("countryID").innerHTML = document.put_in_form.countryLabelText.value;
    }

    //Check status of zipcode field.
    if (self.status[6][1] != "Good") {
        //error_flag = 1; //Don't make this required, allow it to be blank
        //Set the text in the tags to indicated and error.
        //$("zipcodeID").innerHTML = $("zipcodeID").labelText.value + " ***Error***";
        $("zipcodeID").innerHTML = document.put_in_form.zipcodeLabelText.value + "<font color=#FF0000> ***Error***</font>";
    }
    else {
        //$("zipcodeID").innerHTML = $("zipcodeID").labelText.value;
        $("zipcodeID").innerHTML = document.put_in_form.zipcodeLabelText.value;
    }

    //Check status of gps_lat field.
    if ((self.status[8][1] != "Good") || (self.status[9][1] != "Good")) {
        error_flag = 1;
        //Set the text in the tags to indicated and error.
        $("gpsID").innerHTML = "GPS<br></br>Click on map or enter in format as below:" + "<font color=#FF0000> ***Error***</font>";
        //$("gpsID").innerHTML = document.put_in_form.gpsLabelText.value + " ***Error***";
    }
    else {
        //$("gpsID").innerHTML = "GPS<br></br>Click on map or enter in format as below:";
        $("gpsID").innerHTML = document.put_in_form.gpsLabelText.value;
    }


    if (error_flag == 1) {
        var submit_status_error = IMG( {'src' : '/static/images/status/status_ajax-loader_red_bar_error.gif', 'id': 'submit_status'} );
        var submit_status = $("submit_status");
        swapDOM(submit_status, submit_status_error);
        alert("One or more errors were found.  Please try and fix the flagged fields and re-submit.");
    }
    else {

        //alert("txDescription.value" + MochiKit.DOM.getElement(txtDescription).value);
        //alert("txDescription.value" +  $("txtDescription").value); 
        //document.put_in_form.description.value=put_in.description;
        //document.put_in_form.city.value=put_in.city;;
        //document.put_in_form.state.value=put_in.state;
        //document.put_in_form.country.value=put_in.country;
        //document.put_in_form.zipcode.value=put_in.zipcode;
        //document.put_in_form.gps_lat.value=put_in.gps_lat;
        //document.put_in_form.gps_lon.value=put_in.gps_lon;
        //document.put_in_form.url.value=put_in.url;

        var submit_status_complete = IMG( {'src' : '/static/images/status/status_ajax-loader_green_bar_complete.gif' , 'id': 'submit_status'} );
        var submit_status_pending = $("submit_status");
        swapDOM(submit_status_pending, submit_status_complete);

        //Display the new put in on the map.
        new_put_in = new Array(7); 
        new_put_in[0] = 0; 
	new_put_in[1] = document.put_in_form.gps_lat.value;
	new_put_in[2] = document.put_in_form.gps_lon.value;
	new_put_in[3] = document.put_in_form.name.value;
	new_put_in[4] = document.put_in_form.url.value + "null";
	new_put_in[5] = document.put_in_form.description.value;
	new_put_in[6] = document.put_in_form.river.value; //only the id is passed back from controller so this is a kludge to get the real name.
        removeMarker(); // Remove the red marker indicating  the new put in.
        displaySinglePut_in(new_put_in); // Add in a new kayaker marker.

    }
}

function geocoderCheckForEnter(e){
    if(e.keyCode==13){
        geoCode();
    }
    return false;
}

function geoCode(){
    var address;
    obj=document.getElementById("txtGeocoder");
    if(obj){
        address=obj.value;
    }
    if(address=="") return;
    var geocoder = new GClientGeocoder();
    geocoder.getLatLng(
        address,
        function(point) {
            if (!point) {
                alert("\n'" + address + "' not found.\n\nPlease note that there are currently legal/contractual reasons why Google cannot search in the UK, Japan and China, amongst other countries.");
            } else {
                map.setCenter(point, 13);
            }
        }
    );
}



function directionsCheckForEnter(e){
    if(e.keyCode==13){
        getDirections();
    }
    return false;
}

function getDirections(){
    //alert("Inside getDirections()");
    //'city'        : document.put_in_form.city.value,
    //start_addr = $("start_addr");
    //end_addr   = $("end_addr");

    start_addr = document.directions_form.start_addr.value; 
    end_addr   = document.directions_form.end_addr.value; 
    //gdirections.clear();

    var directions_text = "from:" + start_addr + " to:" + end_addr;


    try{
     gdirections.clear();
    }
    catch(e){

    }


    //Test of directions routing
    gdirections = new GDirections(map,$("google_directions"));

    // === Array for decoding the failure codes ===
    var reasons=[];
    reasons[G_GEO_SUCCESS]            = "Success";
    reasons[G_GEO_MISSING_ADDRESS]    = "Missing Address: The address was either missing or had no value.";
    reasons[G_GEO_UNKNOWN_ADDRESS]    = "Unknown Address:  No corresponding geographic location could be found for the specified address.";
    reasons[G_GEO_UNAVAILABLE_ADDRESS]= "Unavailable Address:  The geocode for the given address cannot be returned due to legal or contractual reasons.";
    reasons[G_GEO_BAD_KEY]            = "Bad Key: The API key is either invalid or does not match the domain for which it was given";
    reasons[G_GEO_TOO_MANY_QUERIES]   = "Too Many Queries: The daily geocoding quota for this site has been exceeded.";
    reasons[G_GEO_SERVER_ERROR]       = "Server error: The geocoding request could not be successfully processed.";
    reasons[G_GEO_BAD_REQUEST]        = "A directions request could not be successfully parsed.";
    reasons[G_GEO_MISSING_QUERY]      = "No query was specified in the input.";
    reasons[G_GEO_UNKNOWN_DIRECTIONS] = "The GDirections object could not compute directions between the points.";

    //GEvent.addListener(gdirections, "load", onGDirectionsLoad);
 
    // === catch Directions errors ===
    GEvent.addListener(gdirections, "error", function() {
      var code = gdirections.getStatus().code;
      var reason="Code "+code;
      if (reasons[code]) {
        reason = reasons[code]
      } 

    alert("Failed to obtain directions, "+reason);
    });

    gdirections.load(directions_text);

    return false;
}


function clearFormText(){
    alert("clearFormText()");
    river_input = $("riverTextID");
    river_input.value="";
}


function changeRiverDamSelectToText(){
   //alert("Attempting to change input to text input");
   if ($("DamForm_new_river_checkbox").checked) {
       //store off the select values that were generated in river_select
       //Change this input to a text input
       swapDOM(river_dam_select, river_dam_text_input);
   } 
   else {

       //Change this input to the select box that was saved previously 
       swapDOM(river_dam_text_input, river_dam_select);
  }
}

function changeRiverSelectToText(){
   //river_text_input = INPUT( { 'onFocus': 'clearFormText()', 'onClick': 'clearFormText()', 'onSelect': 'clearFormText()', 'id': 'riverTextID', 'type' : 'text', 'name' : 'river',   'value': 'Enter name of new river/lake'});
   //river_text_input = createDOM(INPUT, { 'onFocus': 'clearFormText()', 'onClick': 'clearFormText()', 'onSelect': 'clearFormText()', 'id': 'riverTextID', 'type' : 'text', 'name' : 'river',   'value': 'Enter name of new river/lake'});

   //river_input = $("riverSelectID");
   //river_select = $("riverSelectID");
   //river_text_input = $("riverTextID");

   if ($("newRiverID").checked) {
       //store off the select values that were generated in river_select
       //Change this input to a text input
       swapDOM(river_select, river_text_input);
   } 
   else {

       //Change this input to the select box that was saved previously 
       swapDOM(river_text_input, river_select);
  }
}

//-----Dam form on/off handling

function switchOnDamForm(){
    dam_form_dom_div = MochiKit.DOM.getElement("add_dam_id");
    //MochiKit.Visual.appear(dam_form_dom_div,{delay: 0});
    dam_form_dom_div.style.visibility = 'visible';
    return false;
}


function switchOffDamForm(){
    dam_form_dom_div = MochiKit.DOM.getElement("add_dam_id");
    dam_form_dom_div.style.visibility = 'hidden';
    return false;
}


//-----Put-in form on/off handling

function switchOnPutInForm(){
    //add_put_in_form_dom = document.getElementById("add_put_in_form_div");
    add_put_in_form_dom_div = MochiKit.DOM.getElement("add_put_in_form_div");
    //MochiKit.Visual.toggle(add_put_in_form_dom_div);
    add_put_in_form_dom_div.style.visibility = 'visible';
    return false;
}
 
function switchOffPutInForm(){
    add_put_in_form_dom_div = MochiKit.DOM.getElement("add_put_in_form_div");
    //MochiKit.Visual.switchOff(add_put_in_form_dom_div);
    add_put_in_form_dom_div.style.visibility = 'hidden';
    return false;
}


//-----Google directions form on/off handling

function switchOnDirections(){
    google_directions_div = MochiKit.DOM.getElement("google_directions");
    directions_form_div= MochiKit.DOM.getElement("directions_form");
    //MochiKit.Visual.toggle(google_directions_div);
    //MochiKit.Visual.toggle(directions_form_div);
    //MochiKit.Visual.appear(google_directions_div);
    MochiKit.Visual.appear(directions_form_div);
    directions_form_div.style.visibility = 'visible';
    //google_directions_div.style.visibility = 'visible';
    return false;
}

function switchOffDirections(){
    google_directions_div = MochiKit.DOM.getElement("google_directions");
    directions_form_div= MochiKit.DOM.getElement("directions_form");
    //MochiKit.Visual.toggle(google_directions_div);
    //MochiKit.Visual.toggle(directions_form_div);
    //MochiKit.Visual.switchOff(google_directions_div);
    MochiKit.Visual.switchOff(directions_form_div);
    return false;
}

function toggleDirections(){
    //google_directions_div = MochiKit.DOM.getElement("google_directions");
    directions_form_div= MochiKit.DOM.getElement("directions_form");
    //MochiKit.Visual.toggle(google_directions_div);
    MochiKit.Visual.toggle(directions_form_div);
    //MochiKit.Visual.appear(google_directions_div);
    MochiKit.Visual.appear(directions_form_div);
    //google_directions_div.style.visibility = 'visible';
    directions_form_div.style.visibility = 'visible';
    return false;
}



function switchOnTripForm(){
    trip_flag = 1
    add_trip_form_dom_div = MochiKit.DOM.getElement("add_trip_form_div");
    add_trip_form_dom_div.style.visibility = 'visible';

    //remove the last marker placed on the map since user will need to restart
    //when adding in a new trip.
    if (old_marker){
        map.removeOverlay(old_marker); //remove old marker if it exists
    }
    return false;
}
 
function switchOffTripForm(){
    trip_flag = 0
    add_trip_form_dom_div = MochiKit.DOM.getElement("add_trip_form_div");
    add_trip_form_dom_div.style.visibility = 'hidden';
    return false;
}

function pause(millis) 
{
        var date = new Date();
        var curDate = null;

        do { curDate = new Date(); } 
        while(curDate-date < millis)
} 


function switchOnViewTripForm(gpx_id){
    trip_flag = 0

    //call load_trips on server and also add a drandom param to prevent IE caching.
    if (!gpx_id){
        //call load_trips and load all trips
        query_string = "/load_trips?" + "tg_random=" +  Math.random()
    }
    else{
        //call load_trips with the id of gpx file to load just one trip 
        query_string = "/load_trips?gpx_id=" + gpx_id + "&tg_random=" +  Math.random()
        //query_string = "/load_trips?" + "tg_random=" +  Math.random()
    }  

    view_trip_form_dom_div = MochiKit.DOM.getElement("view_trip_form_div");
    view_trip_form_dom_div.style.visibility = 'visible';
    $("trip_list_id").innerHTML = "...loading trips....";
    var trip_list = loadJSONDoc(query_string);
    trip_list.addCallback(displayTrips);
    return false;
}
 
function switchOffViewTripForm(){
    trip_flag = 0
    view_trip_form_dom_div = MochiKit.DOM.getElement("view_trip_form_div");
    view_trip_form_dom_div.style.visibility = 'hidden';
    return false;
}



//Create a list of trips from the trips list we got back from the server. 
var displayTrips = function(self, trips) {
    var text_string="";
    //$("trip_list_id").innerHTML = "list of trips goes here";
    for (var i = 0; i < self.trips.length; i++) {
      distance = parseFloat(self.trips[i].distance).toFixed(2);
      text_string = text_string + "<b>" + 
          "<a href=\"gmap?center_gps_lat=41.9017&center_gps_lon=-87.66952&center_zoom_level=11&gpx_file_id=" +
          self.trips[i].id + "\">"  + self.trips[i].tripname + "</a>" + "  <i>posted by: " + self.trips[i].username + "</i>" + 
          "</b>" + "<br/><font size=\"+1\" color=\"yellow\">" + distance  + " miles</font>, " + self.trips[i].trip_date + "<br/>" + 
          "Rating: " + self.trips[i].rating + "/10<br/><br/>" +
          self.trips[i].description + "<br/><br/>"  +
          "<a href=\"static/gpx/" + self.trips[i].filename + "\">Download/save</a><i> (can be opened in Google Earth)</i>" + 
          //"<br/><a href=\"static/gpx/" + self.trips[i].filename + "\">Edit Trip (coming soon)</a>"  + 
          //"<br/><br/>Edit Trip (coming soon)"  + 
          "<br/><hr/><br/>"
    }

    //alert(text_string);
    $("trip_list_id").innerHTML = text_string; 
    return false;
}


