
// search.js: code to control the functionality of the search pane contents (eg: browse view, search form, search map):

/*
 TODO: after fetching summary data, if the number of matching records exceeds an upper limit (say, 5000) then display a popup dialog asking if the user wants to continue, with a warning that very large search results will take a while to display and could slow down responsiveness.
*/

var search = new Object();
search.queryArgs = "";

search.performSearch = function(action)
{
  // This function controls and synchronizes the various steps of the search process for a new search

  if(action == "new search")
  {
    // Initiate a new search:
    if(!this.createQueryArgs()) return false;
    this.showGrayoutScreen();
    this.loadSummary();  // Fetches summary data into "summarydata" JavaScript tag and calls search.performSearch("load data") to continue the process
  }
  else if(action == "sort")
  {
    // Re-sort the previous search results (equivalent to doing a new search but using the previous search query):
    if(cache.queryCount == 0 || cache.totalFoundCount == 0) return;
    this.queryArgs = "QueryCount=" + cache.queryCount + "&" + cache.queryArgs + "&" + cache.queryLimit + "&Sort1=" + cache.querySort;
    this.showGrayoutScreen();
    this.loadSummary();  // Fetches summary data into "summarydata" JavaScript tag and calls search.performSearch("load data") to continue the process
  }
  else if(action == "load data")
  {
    // the search.loadSummary() request returned > 0 matches, so clear out the previous search results and retrieve actual list and map data:
    cache.clearCache();
    results.clearDisplay();
    googleMap.clearMap();
    loadSummaryVariables();  // Function is defined in "summarydata" JavaScript tag after calling search.loadSummary()
    //window.alert("NOT GETTING PAST LoadSummaryVariables()");
    var introtext = document.getElementById("introtext");
    if(introtext)
    {
      introtext.parentNode.removeChild(introtext);
      document.getElementById("resultspane").style.background = "#F0F2E9";
    }
    this.createDownloadLinks();
    results.updateSummary();
    resultspane.redraw();  // The summary text may change the size of the summary pane; so redraw just in case.
    resultspane.showResultsPanes();
    this.loadListData();
    this.loadMapData();
  }
  else if(action == "show data" && cache.mapDataLoaded && cache.listDataLoaded)
  {
    // Both the map data and list data have been loaded, so update the display to show the new search results:
    results.updatePageSelector();
    results.updateListView(cache.selectedPage);
    resultspane.switchDataTab(1);
    results.updateGridView(cache.selectedPage);
    //results.updateDetailView(cache.selectedRecord, false);
    this.removeGrayoutScreen();
    if(!googleMap.loaded) googleMap.loadMap();
    if(googleMap.loaded)
    {
      // TODO: reset map extent to default for PNW?
      googleMap.updateMapHeader();
      googleMap.showMarkers();
      if(resultspane.activeDataTab == 3)
      {
        cache.selectedRecord = 0;
        results.updateDetailView(cache.selectedRecord, false);
        googleMap.selectMarker(cache.selectedRecord, true);
        results.markListEntry(cache.selectedRecord);
      }
    }
  }

  return false;
};

search.showGrayoutScreen = function()
{
  results.fadeOverlayCount = 3;
  var grayoutDiv = document.getElementById("grayout");
  grayoutDiv.style.top = resultspane.top + "px";
  grayoutDiv.style.left = resultspane.left + "px";
  grayoutDiv.style.width = resultspane.width + "px";
  grayoutDiv.style.height = resultspane.height + "px";
  grayoutDiv.style.visibility = "visible";
};

search.removeGrayoutScreen = function()
{
  document.getElementById("grayout").style.visibility = "hidden";
};

search.createQueryArgs = function()
{
  this.queryArgs = "";
  var c = 1;
  if(document.getElementById("ts_add").checked && cache.totalFoundCount > 0)
  {
    // Add this search request to the previous search request:
    c = cache.queryCount + 1;
    this.queryArgs += "QueryCount=" + c + "&" + cache.queryArgs;
  }
  else this.queryArgs += "QueryCount=1";

  var newArgs = "";
  var arg = "";
  arg = document.getElementById("ts_group").value;
  if(arg) newArgs += "&Group" + c + "=" + arg;
  arg = document.getElementById("ts_institution").value;
  if(arg) newArgs += "&Institution" + c + "=" + arg;
  arg = document.getElementById("ts_catalog").value;
  if(arg) newArgs += "&Catalog" + c + "=" + arg;
  arg = document.getElementById("ts_family").value;
  if(arg) newArgs += "&Family" + c + "=" + arg;
  arg = document.getElementById("ts_sciname").value;
  if(arg) newArgs += "&Scientific" + c + "=" + arg;
  arg = document.getElementById("ts_genus").value;
  if(arg) newArgs += "&Genus" + c + "=" + arg;
  arg = document.getElementById("ts_species").value;
  if(arg) newArgs += "&Species" + c + "=" + arg;
  arg = document.getElementById("ts_subtaxon").value;
  if(arg) newArgs += "&Subtaxon" + c + "=" + arg;
  arg = document.getElementById("ts_collectors").value;
  if(arg) newArgs += "&Collectors" + c + "=" + arg;
  arg = document.getElementById("ts_collnum").value;
  if(arg) newArgs += "&CollNum" + c + "=" + arg;
  arg = document.getElementById("ts_day").value;
  if(arg) newArgs += "&Day" + c + "=" + arg;
  arg = document.getElementById("ts_month").value;
  if(arg) newArgs += "&Month" + c + "=" + arg;
  arg = document.getElementById("ts_year").value;
  if(arg) newArgs += "&Year" + c + "=" + arg;
  arg = document.getElementById("ts_country").value;
  if(arg) newArgs += "&Country" + c + "=" + arg;
  arg = document.getElementById("ts_state").value;
  if(arg) newArgs += "&State" + c + "=" + arg;
  arg = document.getElementById("ts_county").value;
  if(arg) newArgs += "&County" + c + "=" + arg;
  arg = document.getElementById("ts_locality").value;
  if(arg) newArgs += "&Locality" + c + "=" + arg;
  arg = document.getElementById("ts_elevationlower").value;
  if(arg) newArgs += "&ElevLower" + c + "=" + arg;
  arg = document.getElementById("ts_elevationupper").value;
  if(arg) newArgs += "&ElevUpper" + c + "=" + arg;

  if(newArgs  == "") 
  {
    this.searchURL = "";
    window.alert("Error: no search parameters were defined.");
    return false;
  }
  else this.queryArgs += newArgs;

  arg = document.getElementById("ts_sort1").value;
  if(arg != "") this.queryArgs += "&Sort1=" + arg;
  // arg = document.getElementById("ts_sortorder1").value;
  // if(arg != "") this.queryArgs += "&SortOrder1=" + arg;
  arg = document.getElementById("ts_limit").value;
  if(arg != "") this.queryArgs += "&Limit=" + arg;

  //this.clearTextSearch();  // Avoid problems with certain browser behaviors
  field = document.getElementById("ts_sciname");
  if(field) field.value = "";

  return true;
};

search.loadSummary = function()
{
  var head = document.getElementsByTagName("head")[0];

  var oldScript = document.getElementById("summarydata");
  if(oldScript) head.removeChild(oldScript);

  var timestamp = new Date();
  var newScript = document.createElement('script');
  newScript.id = "summarydata";
  newScript.type = "text/javascript";
  newScript.src = "summarydata.php?" + this.queryArgs + "&time=" + timestamp.getTime();

  head.appendChild(newScript);
  //window.alert("summarydata.php?" + this.queryArgs + "&time=" + timestamp.getTime());

//  var timestamp = new Date();
//  new Ajax.Request("summarydata.php?" + this.queryArgs + "&time=" + timestamp.getTime(), { method: "get" });

  return true;
};

search.loadListData = function()
{
  //window.alert("Loading list data 5");
  var head = document.getElementsByTagName("head")[0];

  var oldScript = document.getElementById("listdata");
  if(oldScript) head.removeChild(oldScript);

  var timestamp = new Date();
  var newScript = document.createElement('script');
  newScript.id = "listdata";
  newScript.type = "text/javascript";
  newScript.src = "listdata.php?" + this.queryArgs + "&action=new&time=" + timestamp.getTime();
  head.appendChild(newScript);

//  var timestamp = new Date();
//  new Ajax.Request("listdata.php?" + this.queryArgs + "&action=new&time=" + timestamp.getTime(), { method: "get" });

  return true;
};

search.loadMapData = function()
{
  //window.alert("Loading map data 5");
  var head = document.getElementsByTagName("head")[0];

  var oldScript = document.getElementById("mapdata");
  if(oldScript) head.removeChild(oldScript);

  var timestamp = new Date();
  var newScript = document.createElement('script');
  newScript.id = "mapdata";
  newScript.type = "text/javascript";
  if(this.queryArgs != "") newScript.src = "mapdata.php?" + this.queryArgs + "&time=" + timestamp.getTime();
  else newScript.src = "mapdata.php?action=nodata";
  head.appendChild(newScript);

//  var timestamp = new Date();
//  new Ajax.Request("mapdata.php?" + this.queryArgs + "&time=" + timestamp.getTime(), { method: "get" });

  return true;
};

search.createDownloadLinks = function()
{
  if(cache.queryArgs == "") return false;

  var linkAnchor = document.getElementById("downloadtxt");
  if(linkAnchor && linkAnchor.href) linkAnchor.href = "downloadtxt.php?" + cache.queryArgs + "&" + cache.querySort;

  var linkAnchor = document.getElementById("downloadxml");
  if(linkAnchor && linkAnchor.href) linkAnchor.href = "downloadxml.php?" + cache.queryArgs + "&" + cache.querySort;

  var linkAnchor = document.getElementById("downloadkml");
  if(linkAnchor && linkAnchor.href) linkAnchor.href = "downloadkml.php?" + cache.queryArgs + "&" + cache.querySort;

  var linkAnchor = document.getElementById("downloadrtf");
  if(linkAnchor && linkAnchor.href) linkAnchor.href = "downloadrtf.php?" + cache.queryArgs + "&" + cache.querySort;

  return true;
};

search.noMatches = function()
{
  this.removeGrayoutScreen();

  // TODO: replace this alert with code to display a dialog box stating that no matching records were found.
  window.alert("No matching records were found.");
};

search.clearTextSearch = function()
{
  var field = "";

  field = document.getElementById("ts_replace");
  if(field) field.checked = true;

  field = document.getElementById("ts_group");
  if(field) field.selectedIndex = 0;
  field = document.getElementById("ts_institution");
  if(field) field.selectedIndex = 0;
  field = document.getElementById("ts_catalog");
  if(field) field.value = "";
  field = document.getElementById("ts_family");
  if(field) field.value = "";
  field = document.getElementById("ts_sciname");
  if(field) field.value = "";
  field = document.getElementById("ts_genus");
  if(field) field.value = "";
  field = document.getElementById("ts_species");
  if(field) field.value = "";
  field = document.getElementById("ts_subtaxon");
  if(field) field.value = "";
  field = document.getElementById("ts_collectors");
  if(field) field.value = "";
  field = document.getElementById("ts_collnum");
  if(field) field.value = "";
  field = document.getElementById("ts_day");
  if(field) field.value = "";
  field = document.getElementById("ts_month");
  if(field) field.value = "";
  field = document.getElementById("ts_year");
  if(field) field.value = "";
  field = document.getElementById("ts_country");
  if(field) field.value = "";
  field = document.getElementById("ts_state");
  if(field) field.value = "";
  field = document.getElementById("ts_county");
  if(field) field.value = "";
  field = document.getElementById("ts_locality");
  if(field) field.value = "";
  field = document.getElementById("ts_elevationlower");
  if(field) field.value = "";
  field = document.getElementById("ts_elevationupper");
  if(field) field.value = "";

  field = document.getElementById("ts_sort1");
  if(field) field.selectedIndex = 3;
  field = document.getElementById("ts_sortorder1");
  if(field) field.selectedIndex = 0;
};


/*

1) Show list of data types to begin the browse
  Family
  Scientific Name
  Collector
  Collection Date
  Location
2) User selects a data type and
    a) The other data types are hidden
    b) A list of values for that data type are displayed, constrained by any previously selected values.
3) User checks one or more values from the list
4) ?
5) List collapses to show data type heading + value + count; under this is an indented list of the remaining data types
6) User selects one of these remaining data types, and the process repeats at step 2 above.


Upon startup show a header without any search button stating "Select a data category from the list below to begin browsing"
Once the first value has been selected, switch the header to state "View selected specimens by clicking View Specimens, or start over by clicking Reset."

[] Collector: C. Leo Hitchcock (23,805)
  [] Year: 1971 (497)
    [] Month: Apr (59)
      [] Genus: Carex (6)
        [] Collector's Number: 22105 (1)
            (there are no additional records to browse)




Browse Categories:

Family
Scientific Name (Genus, Species, Subtaxon)
Location (Country -> State -> County -> Locality?)
Collection Date (Year, Month, or Day)
Collector (Collector -> Collector Number)


Family
Scientific Name
Collector
  A
  B
  C
    Charles B. Fiker
    C. Leo Hitchcock
      Browse further by:
      Family
      Scientific Name
      Collection Year
        1972
        1971
          Browse further by:
          Family
          Scientific Name
          Collection Month
            Feb
            Mar
            Apr
            May
            Jun
            Jul
            Aug
            Sep
            Oct
          Collection Day
          Collector's Number
        1970
         .
         .
         .
       1949
       1948
      Collection Month
      Collection Day
      Collector's Number
    Constance Smith
  D
  E
  .
  .
  .
  Z
Year
Month
Day
Location


Family
Scientific Name
Collector
Collection Date
Location


ScientificName
  B
    Botrychium
      > select another category
      ascendens
      crenulatum
      hesperium
      lanceolatum
      lineare
      lunaria
      michiganense
      minganense
      montanum
      multifidum
      paradoxum
      pedunculosum
      pinnatum
      pumicola
      robustum
      simplex
      venulosum
      virginianum


Collector Name:
  C. Leo Hitchcock (23,805)
    Collection Year:
      1971 (497)
        Collection Month:
          Feb
          Mar
          Apr
          May
          Jun
          Jul
          Aug
          Sep
          Oct


[] Collector: C. Leo Hitchcock (23,805)
  [] Year: 1971 (497)
    [] Month: Apr (59)
      [] Carex (6)
        [] Collector's Number: 22105 (1)
            (there are no additional records to browse)




Collector
  Family
  Scientific Name
  Collection Date
    Year
    Month
    Day
  Collector's Number
    0-100
    101-200
    201-300
  Location


*/