// googleMap.js
//
// Takes care of all the functions that deal with the Google Maps API: allow 
// the user to select a region on the map, draws/clears markers and image 
// swaths (polygons) for the search results, etc.

<!--
function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.0
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && document.getElementById) x=document.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}
//-->


var map;
var marker1Lat, marker1Lng;
var marker2Lat, marker2Lng;
var countMarkers = 0; // number of markers currently on map
var rect; // selection rectangle
var circleIcon;
var precisionMarker;
var results = new Array();

function initialize() 
{
  if (!GBrowserIsCompatible()) 
  {
    alert('Your browser is not compatible with Google Maps');
    return;
  } 
  else 
  {	    
   
    // Add all the controls to the map UI
    map = new GMap2(document.getElementById("map"));
    map.setCenter(new GLatLng(38, -97), 4);
    map.addMapType(G_NORMAL_MAP);
    map.addMapType(G_SATELLITE_MAP);
    map.addMapType(G_HYBRID_MAP);
    map.addMapType(G_PHYSICAL_MAP);
    map.setMapType(G_PHYSICAL_MAP);
    map.addControl(new GLargeMapControl());
    map.addControl(new GHierarchicalMapTypeControl());      

    
    // Selection marker icon
    var selectionIcon = new GIcon(G_DEFAULT_ICON);
    selectionIcon.image = "http://airsar-t.jpl.nasa.gov/markerYellow.png";

    
    // Precision marker
    var precisionIcon = new GIcon(G_DEFAULT_ICON);
    precisionIcon.image = "http://airsar-t.jpl.nasa.gov/markerTurquoise.png";
    // Set up our GMarkerOptions object
    precisionMarker = { icon:precisionIcon };

    // Only allow 2 mouse clicks (countMarkers).  Third mouse click, draws a 
    // new region.
    GEvent.addListener(map, "click", function(overlay,latlng) 
    {   
      if (countMarkers == 2 && latlng)
      {
	map.clearOverlays();
	countMarkers = 0;
      }

      if (countMarkers < 2 && latlng)
      {
	var marker = new GMarker(latlng, 
          {draggable: true, icon:selectionIcon});
        marker.value = countMarkers + 1;
	map.addOverlay(marker);
	updateCoords(marker);
	countMarkers++;

	GEvent.addListener(marker, "click", function() 
        {
            marker.openInfoWindowHtml("<p align=left class=mapMarker>Latitude: " + marker.getPoint().lat() + "<br>Longitude: " 
	      + marker.getPoint().lng());
        });

	GEvent.addListener(marker, "drag", function() 
        {
	  updateCoords(marker);
	  
	  // If there are 2 markers on the map, redraw the polygon
	  if (countMarkers == 2)
	  {
	    map.removeOverlay(rect);
            rect = new GPolygon([
              new GLatLng(marker1Lat, marker1Lng),
              new GLatLng(marker1Lat, marker2Lng),
              new GLatLng(marker2Lat, marker2Lng),
              new GLatLng(marker2Lat, marker1Lng),
              new GLatLng(marker1Lat, marker1Lng)],
	      "#ffec22", 7, 0.6);
            map.addOverlay(rect);
	  }
        });
          
        if (countMarkers == 1)
        {
          marker1Lat = latlng.lat();
          marker1Lng = latlng.lng();
    	} 
	else // (countMarkers == 2)
	{
 	  marker2Lat = latlng.lat();
	  marker2Lng = latlng.lng();
	    
	  rect = new GPolygon([
            new GLatLng(marker1Lat, marker1Lng),
            new GLatLng(marker1Lat, marker2Lng),
            new GLatLng(marker2Lat, marker2Lng),
            new GLatLng(marker2Lat, marker1Lng),
            new GLatLng(marker1Lat, marker1Lng)],
            "#ffec22", 7, 0.6);
	  map.addOverlay(rect);
	}  
      }
    });
  }
}


// Creates a marker whose info window displays the letter corresponding
// to the given index.
function createMarker(latLng, message, dataType) 
{
  if (dataType == "Survey")
  {
    var marker = new GMarker(latLng);
  }
  else
  {
    var marker = new GMarker(latLng, precisionMarker);
  }

  GEvent.addListener(marker, "click", function() {
    marker.openInfoWindowHtml(message);
  });

  return marker;
}


// Updates the marker coordinates 
function updateCoords(marker)
{
  if (marker.value == 1)
  {
    marker1Lat = marker.getPoint().lat();
    marker1Lng = marker.getPoint().lng();
  }
  else // (marker.value == 2)
  {
    marker2Lat = marker.getPoint().lat();
    marker2Lng = marker.getPoint().lng();
  }

  // Update the hidden coordinate values stored in the form so that they 
  // are passed when the user selects the "Search Region" button.
  document.getElementById("lat1").value = marker1Lat;
  document.getElementById("lat2").value = marker2Lat;
  document.getElementById("lng1").value = marker1Lng;
  document.getElementById("lng2").value = marker2Lng;
}


// Clears the map (when the user selects the "Reset" button)
function resetMap()
{
  // Reset the hidden coordinate values stored in the form 
  document.getElementById("lat1").value = "";
  document.getElementById("lat2").value = "";
  document.getElementById("lng1").value = "";
  document.getElementById("lng2").value = "";
  document.getElementById("precision").checked = true;
  document.getElementById("survey").checked = true;
  document.getElementById("max").value = 100;
  document.getElementById("sMonth").value = "01";
  document.getElementById("sDay").value = "01";
  document.getElementById("sYear").value = 1988;
  document.getElementById("eMonth").value = 12;
  document.getElementById("eDay").value = 31;
  document.getElementById("eYear").value = 2004;

  map.clearOverlays();
  countMarkers = 0; 
}


// Removes all the markers (radar data) from the map
function clearMarkers()
{
  while (results.length > 0)
  {
    map.removeOverlay(results.pop());
  }  
}


// Draws the search results: image swaths (rectangles) and markers with 
// appropriate information in the pop-up, marker-info windows. 
function drawResults()
{
  var imageServer = "http://airsar.jpl.nasa.gov/airdata";
  var ftpServer = "http://airsar.asf.alaska.edu/data";
  var info = arguments[0];  
  var message;
  var tempMarker;
  var tempRect;
  var dataType, centerLat, centerLng, corner1_lat, corner2_lat, corner3_lat,
    corner4_lat, corner1_lon, corner2_lon, corner3_lon, corner4_lon, tapeid,
    flight_date, detailed_mode, general_mode, survey_imagename, 
    path_to_survey_image, proc_id, path_to_image, image, image_full, 
    dem_image_full, dem_image, dem_image_l, dem_image_l_full, intf_image_c, 
    intf_image_l, survey_imagename, precision_data;

  document.getElementById("info").innerHTML = info; 

  var i = 1;  
  while (i < arguments.length)
  {
    dataType = arguments[i];
    centerLat = arguments[i+1];
    centerLng = arguments[i+2];
    corner1_lat = arguments[i+3];
    corner2_lat = arguments[i+4]; 
    corner3_lat = arguments[i+5];
    corner4_lat = arguments[i+6];
    corner1_lon = arguments[i+7];
    corner2_lon = arguments[i+8];
    corner3_lon = arguments[i+9];
    corner4_lon = arguments[i+10];
	
    if (dataType == "Survey")
    {
      tapeid = arguments[i+11];
      flight_date = arguments[i+12];
      detailed_mode = arguments[i+13];
      general_mode = arguments[i+14];
      path_to_survey_image = arguments[i+15];
      survey_imagename = imageServer + path_to_survey_image + "/" + 
	                 arguments[i+16];

      message = "<p align=left class=mapMarker><b>" + dataType + "</b>" + 
	        "<br>Tapeid: " + tapeid + 
	        "<br>Flight Date: " + flight_date +
	        "<br>Detailed Mode: " + detailed_mode +
                "<br>General Mode: " + general_mode +
	        "<br><A href=" + survey_imagename + 
	        " target='_new'>Survey Image</A>";
      i+=17;
    }	
    else
    {
      proc_id = arguments[i+11];
      tapeid = arguments[i+12];
      flight_date = arguments[i+13];
      detailed_mode = arguments[i+14];
      path_to_image = arguments[i+15];
      image = arguments[i+16]; 
      image_full = arguments[i+17];
      dem_image_full = arguments[i+18];
      dem_image = arguments[i+19];
      dem_image_l = arguments[i+20]; 
      dem_image_l_full = arguments[i+21];
      intf_image_c = arguments[i+22]; 
      intf_image_l = arguments[i+23]; 
      path_to_survey_image = arguments[i+24];
      survey_imagename = imageServer + path_to_survey_image + "/" + 
	arguments[i+25];
      precision_data = ftpServer + arguments[i+26]; 

      link = imageServer + path_to_image + "/"; // http://blacks.../PRECISION

      message = "<p align=left class=mapMarker><b>" + dataType + "</b>" + 
	        "<br>Proc_id: " + proc_id + 
	        "<br>Tapeid: " + tapeid +
	        "<br>Flight Date: " + flight_date +
	        "<br>Detailed Mode: " + detailed_mode;
      if (image != "" && image != "not_available.gif" && image != "NULL")
      {
	message += "<br><A href=" + link + image + 
	           " target='_new'>Band Overlay</A>";
      }	
      if (image_full != "" && image_full != "not_available.gif" 
	  && image_full != "NULL")
      {
	message += "<br><A href=" + link + image_full + 
	           " target='_new'>Full-Res Band Overlay</A>";
      }	
      if (dem_image != "" && dem_image != "not_available.gif" 
	  && dem_image != "NULL")
      {
	message += "<br><A href=" + link + dem_image + 
	           " target='_new'>C-Band DEM</A>";
      }	
      if (dem_image_full != "" && dem_image_full != "not_available.gif" 
	  && dem_image_full != "NULL")
      {
	message += "<br><A href=" + link + dem_image_full + 
	           " target='_new'>Full-res C-Band DEM</A>";
      }	
      if (dem_image_l != "" && dem_image_l != "not_available.gif"
	  && dem_image_l != "NULL")
      {
	message += "<br><A href=" + link + dem_image_l + 
	           " target='_new'>L-Band DEM</A>";
      }	
      if (dem_image_l_full != "" && dem_image_l_full != "not_available.gif"
	  && dem_image_l_full != "NULL")
      {
	message += "<br><A href=" + link + dem_image_l_full + 
	           " target='_new'>Full-res L-Band DEM</A>";
      }	
      if (intf_image_c != "" && intf_image_c != "not_available.gif"
	  && intf_image_c != "NULL")
      {
	message += "<br>Intf_image_c: " + intf_image_c;
	message += "<br><A href=" + link + intf_image_c + 
	           " target='_new'>C-Band ATI Image</A>";
      }	
      if (intf_image_l != "" && intf_image_l != "not_available.gif"
	  && intf_image_l != "NULL")
      {
	message += "<br><A href=" + link + intf_image_l + 
	           " target='_new'>L-Band ATI Image</A>";
      }	
      
      message += "<br><A href=" + survey_imagename + 
	         " target='_new'>Survey Image</A>" + 
	         "<br><A href=" + precision_data + 
	         " target='_new'>Link to precision data</A>";
      i+=27;
    }
    
    // Add the center marker and image swaths (polygons) to the map
    tempMarker = createMarker(new GLatLng(centerLat, centerLng), message, 
	dataType);

    if (dataType == "Survey")
    {
      tempRect = new GPolygon([
        new GLatLng(corner1_lat, corner1_lon),
        new GLatLng(corner2_lat, corner2_lon),
        new GLatLng(corner3_lat, corner3_lon),
        new GLatLng(corner4_lat, corner4_lon),
        new GLatLng(corner1_lat, corner1_lon)],
        "#f33f00", 3, 1, "#b0a74a", 0.2);
    }
    else // (dataType == "Precision")
    {
      tempRect = new GPolygon([
        new GLatLng(corner1_lat, corner1_lon),
        new GLatLng(corner2_lat, corner2_lon),
        new GLatLng(corner3_lat, corner3_lon),
        new GLatLng(corner4_lat, corner4_lon),
        new GLatLng(corner1_lat, corner1_lon)],
        "#3f8e96", 3, 1, "#3f8e96", 0.2);
    }

    results.push(tempMarker);
    results.push(tempRect);
    map.addOverlay(tempMarker);
    map.addOverlay(tempRect);
  }
}

function tips()
{
  alert("Tips coming soon...")
}


// Display tips one at a time when the user clicks the "Tips" button.
function showTips()
{
  var tips = new Array();
  var moreTips = true;
  var next;
  var i = 0;

  tips.push(
      "The yellow markers indicating the geographic search window may " + '\n' 
    + "be individually moved to change the selected region.  Then, you " + '\n'
    + "may click on the 'Search Region' button again to search the new " + '\n'
    + "selected region.");
  tips.push(
      "After searching a region and results are returned, the blue " + '\n'
    + "markers indicate precision (full resolution data products) " + '\n'
    + "data, and the red markers indicate survey (low resolution " + '\n'
    + "imagery of entire data line) data.  The precision data is a " + '\n'
    + "subset of the survey data.");
  tips.push(
      "The maximum number of search results may be changed to whatever " + '\n'
    + "number you want. However, a large number of markers will result " + '\n'
    + "in poor performance of Google Maps.  We recommend trying to "  + '\n'
    + "limit your search to no more than 100 results.");
  tips.push(
      "The image swaths are approximate locations.  The precision " + '\n' 
    + "image swaths should be identical to the survey swaths in width, " + '\n'
    + "but in practice they are not.");
  tips.push(
      "The interactive map uses Google Maps, and works just like " + '\n'
    + "Google Maps: click and hold will pan the image, and double " + '\n'
    + "click will zoom in.");
  tips.push(
      "When you click on a blue marker indicating a precision image " + '\n'
    + "location, the info window, in addition to basic information " + '\n'
    + "about the data take, has several links that may be clicked on: " + '\n'
    + "jpg images, links to the corresponding survey imagery, and a " + '\n'
    + "link to the Alaska Satellite Facility " + '\n' 
    + "(http://asf.alaska.edu) website where the full resolution " + '\n'
    + " polarimetric and interferometric AIRSAR data is archived. The " + '\n'
    + "data may be downloaded by ftp at no charge.");
  tips.push(
      "If the density of results is high, making it difficult to " + '\n'
    + "select the images to view, zooming in to differentiate the " + '\n'
    + "images can help.  Narrowing the search by date, or showing just " + '\n'
    + "precision or survey, can reduce the density of markers as well.");
  tips.push(
      "AIRSAR data is available outside the continental states as " + '\n'
    + "well. Simply zoom out and/or pan to navigate to any location " + '\n'
    + "on Earth,  and search for AIRSAR data in whichever region you " + '\n'
    + "have an interest.");


  // Display more tips until the user selects "Cancel" or the end of the 
  // tips is reached.  
  do
  {
    next = confirm("Tip " + (i+1) + " of " + tips.length + '\n\n' + tips[i]);

    if (next != true || (i+1) == tips.length)
    {
      moreTips = false;
    }
    else 
    {
      i++;
    }
  }
  while (moreTips == true)
}