//     SearchManager.js
// will be added to searchPage-sweet.js after it is debugged.
// 
var SearchManager = Class.create();
Object.extend(SearchManager.prototype,{
  // do independent propj and dataset searchs.
  // as requested, harvest appropriate projectuid info from either the propj results
  // or the dataset results and research the opposite side
  // 
  // to include projectUids in the initial data-side search, use the 
  // format "projectuid=##,##,##" parameter this will OR the results with the 
  // rest of the data search.
  // to do the post-propj-search data-side query for the linked datasets, use the 
  // "project_number: ## OR "project_number: ##" format which will return only 
  // the linked data sets

  initialize: function () {
    this.searchHistory = new Array();
    this.currentPropjResultSet = new Array();
    this.currentDataResultSet = new Array();
    this.propJSearchString = '';
    this.propjSearchUidResults = new Array();
    this.dataSearchParams = new Object();
    this.dataSearchUidResults = new Array();
  },

  doInitialSearch: function (searchTermObject) { // "searchTermObject" is the AllSearchTerms object
    makeResultsTables();
    this.searchTermObject = searchTermObject;;
    this.dataSearchParams = searchTermObject.makeDataSearchParams();
    this.doPropjSearch(this.searchTermObject.makePropjSearchString());
    this.doDataSearch(this.dataSearchParams,'data');
    displayAllResults3(this.currentPropjResultSet);
  },

  savePropjSearchResults: function (theResultSet) {
    this.currentPropjResultSet = theResultSet;
    this.propjSearchUidResults = theResultSet.pluck('uid');
  },

  doPropjSearch: function (searchJSON) {
    var mySavePropjResultSet = this.savePropjSearchResults.bind(this);
    new Ajax.Request('lib/amis/search/search.php', {
                        asynchronous: false,
                        parameters: 'theSearch='+searchJSON,
                        onComplete: function (theResponse) {
                          var theResultSet = (theResponse.responseText.strip()).evalJSON();
                          mySavePropjResultSet(theResultSet);
                        }
                    });
  },

  doDataSearch: function (params,propjOrData) {
    var myPropjOrData = propjOrData || 'both';  
    // 'propj' uses ONLY params.projectuid and ignore all other search parameters
    // 'data' uses all search parameters EXCEPT params.projectuid
    // 'both' uses all search parameters INCLUDING params.projectuid
    if (Object.keys(params).length == 0) {
      // no data search parameters
      $('datasetSearchResults').update('<div><h1>No Data Search Specified.</h1></div>');
      return;
    }
    delete params.projonly;
    delete params.dataonly;
    switch (myPropjOrData) {
      case 'propj':
        delete params.dataonly;
        params.projonly = true;
        break;
      case 'data':
        delete params.projonly;
        params.dataonly = true;
        break;
    }
    this.dataSearchUidResults = amis.search.dataSearch(params);
    // thats the list of propj uids associated with the dataset results
  },

  reformPropjSearch: function (propjOrData) {
    var myPropjOrData = propjOrData || 'both';
    // bound to a button; if there are no additional uids to search with, 
    // the button should be hidden.
    if (this.dataSearchUidResults && (this.dataSearchUidResults.length > 0)) {
      if (myPropjOrData == 'data') {
        // save only the data search term sets



      }
    }
    this.doPropjSearch(theSearchTerms);
    displayAllResults3(this.currentPropjResultSet);
  },

/*  still not right; try 3
  reformPropjSearch: function (propjOrData) {
    var myPropjOrData = propjOrData || 'both';
    // bound to a button; if there are no additional uids to search with, 
    // the button should be hidden.
    if (this.dataSearchUidResults && (this.dataSearchUidResults.length > 0)) {
      var theSearchTerms = "{\"searchNumber\":\"1\",\"termSets\":[";
      theSearchTerms += "{\"setNumber\":\"1\",\"terms\":[";
      if (myPropjOrData == 'data') {
        // save only the data search term sets
        for (var termIndex = 0, numberOfTerms = this.searchTermObject.termSets[0].terms.length; termIndex < numberOfTerms; ++termIndex) {
          theSearchTerms += '{"termNumber":"'+(termIndex+1)+'","termValue":';
          theSearchTerms += this.searchTermObject.termSets[0].terms[termIndex];
          theSearchTerms += '},';
        }
        theSearchTerms = theSearchTerms.substring(0,theSearchTerms.length-1);
        theSearchTerms += "]}";  // closes setNumber:1
      }      

      if (myPropjOrData == 'proj') {
        // remove the data set search term
        theSearchTerms += "{\"termNumber\":\"1\",\"termValue\":\"empty\"}";
        // now add any of the remaining terms that need to be kept
        // (here)
        console.log("SearchManager::reformPropjSearch('propj') not implemented");
      }

      // create additional single term termsets for each uid
      var setCounter = 1;
      this.dataSearchUidResults.split(',').each(function (thisUid) {
        theSearchTerms += ",{\"setNumber\":\""+ (setCounter+1) +"\",\"terms\":[";
        theSearchTerms += "{\"termNumber\":\"1\",\"termValue\":";
        theSearchTerms += "{\"category\":\"uid\",\"value\":\""+ thisUid +"\",\"forDisplay\":\"uid\"}}";
        theSearchTerms += "]}";
        setCounter++;
      });
      theSearchTerms += "]}";
      // close out the search string
      // (here)
    }
    this.doPropjSearch(theSearchTerms);
    displayAllResults3(this.currentPropjResultSet);
  },
*/


  dummy: function () {}
});

//----------------------------------------------------------------
function makeResultsTables(theResultsContainer) {
  var theContainer = theResultsContainer || $('searchResultsDiv');
  theContainer.update();  // remove previous results

  var outerTable = new Element('table',{width:'95%'});
  outerTable.insert(new Element('thead'));

  var leftInnerTable = new Element('table');
  leftInnerTable.insert(new Element('thead'));
  leftInnerTable.down('thead').insert('Proposal/Project Results');
  var propjButtonSpan = new Element('span',{id:'propjButtonSpan'});
  propjButtonSpan.insert('<br>');
  propjButtonSpan.insert(new Element('input',{type:"button",value:"add associated data",id:"addPropjData"}));
  propjButtonSpan.insert('<br>');
  propjButtonSpan.insert(new Element('input',{type:"button",value:"show only associated data",id:"showOnlyPropjData"}));
  leftInnerTable.down('thead').insert(propjButtonSpan);
  $(propjButtonSpan).hide();
  var leftInnerTableBody = new Element('tbody');
  leftInnerTable.insert(leftInnerTableBody);
  leftInnerTable.insert(new Element('tfoot'));
  thePage.propjResultsTable = leftInnerTable;

  var rightInnerTable = new Element('table');
  rightInnerTable.insert(new Element('thead'));
  rightInnerTable.down('thead').insert('Dataset Results');
  var dataButtonSpan = new Element('span',{id:'dataButtonSpan'});
  dataButtonSpan.insert('<br>');
  dataButtonSpan.insert(new Element('input',{type:"button",value:"add associated projects",id:"addDataPropjs"}));
  dataButtonSpan.insert('<br>');
  dataButtonSpan.insert(new Element('input',{type:"button",value:"show only associated projects",id:"showOnlyDataPropjs"}));
  rightInnerTable.down('thead').insert(dataButtonSpan);
  $(dataButtonSpan).hide();
  var theForm = new Element('form',{id:'amis.search.form',action:'javascript:{}'});
  theForm.insert(new Element('div',{id:'datasetSearchResults'}));
  var rightInnerTableBody = new Element('tbody');
  rightInnerTableBody.insert((new Element('tr')).insert((new Element('td')).insert(theForm)))
  rightInnerTable.insert(rightInnerTableBody);
  rightInnerTable.insert(new Element('tfoot'));
  thePage.dataResultsTable = rightInnerTable;

  var outerTableBody = new Element('tbody');
  var td1 = (new Element('td',{valign:'top'})).insert(leftInnerTable); 
  var td2 = (new Element('td',{valign:'top'})).insert(rightInnerTable); 
  var td3 = (new Element('td',{valign:'top'})); 
  var tr1 = new Element('tr');
  tr1.insert(td1);
  tr1.insert(td2);
  tr1.insert(td3);
  outerTableBody.insert(tr1);
  outerTable.insert(outerTableBody);
  outerTable.insert(new Element('tfoot'));
  $(theContainer).insert(outerTable);

  var mapDiv = new Element('div',{id:'outputMapDiv', width:'500', height:'400'});
  $(td3).insert(mapDiv);
}

//----------------------------------------------------------------
function displayAllResults3(thePropjResults,theResultsContainer) {
  var theContainer = theResultsContainer || $('searchResultsDiv');

  var leftInnerTableBody = thePage.propjResultsTable.down('tbody');
  var rightInnerTableBody = thePage.dataResultsTable.down('tbody'); 

  var reportLabels = new Object();
//  reportLabels.uid = null;   // null label value indicates do not display value
  reportLabels.uid = "uid";   // null label value indicates do not display value
  reportLabels.fullTitle = "Full Title";
  reportLabels.subDate = "Submission Date";
  reportLabels.leadSci = "Principle Investigator"
  reportLabels.mainContact = null;
  reportLabels.abstract = "Abstract Text";
  reportLabels.notes = "Notes";
  reportLabels.startDate = "Funding Start Date";
  reportLabels.endDate = "Funding End Date";
  reportLabels.dataLink = "Access Data";

  // show proposal results
  leftInnerTableBody.update();
  if (thePropjResults.length < 1) {
    leftInnerTableBody.insert((new Element('tr')).insert((new Element('td')).insert('<h1>No Matching Proposals or Projects found.</h1>')))
    $('propjButtonSpan').hide();
  } else {
    for (var iterator=0, last=thePropjResults.length; iterator<last; ++iterator) {
      leftInnerTableBody.insert((new Element('tr')).insert((new Element('td')).insert(displayResult(thePropjResults[iterator],reportLabels))));
    }
    $('propjButtonSpan').show();
  }

  // show data results
  if (amis.search.dslist) {
    amis.search.printDslist();
    $('dataButtonSpan').show();
  } else {
    $('dataButtonSpan').hide();
    $('datasetSearchResults').update('<div><h1>No Matching Datasets.</h1></div>');
  }

  // show the map
  var mapDiv = $('outputMapDiv');
  mapDiv.update();
  var thisMapOutput = new RegionOutputMap($(mapDiv));
  thePage.mapOutput = thisMapOutput;
  $(theContainer).insert('</div>');
  $(theContainer).show();
  var theUids = thePropjResults.pluck('uid');
  thisMapOutput.updateProjectsWFSLayer(theUids.join(','));
  if (amis.search.dslist) {
    thisMapOutput.updateDataWFSLayer(amis.search.dslist);
  }
}
