function initPage() {
  thePage = new Object();
  thePage.stateHistory = new Array();
  mainState();
  $('goback').observe('click',goBack.bind(this));
}

function resetPage() {
  if ($('finalChoice')) {$('finalChoice').remove()};
  $('AMISprojects').update();
  $('AMISliteResults').update();
}

function mainState() {
  resetPage();
  findState();
//  new Ajax.Updater('TOP3','inc/TOP3-main.html',{evalScripts: true});
//  thePage.stateHistory.push(mainState);
}

function findState() {
  resetPage();
  new Ajax.Updater('TOP3','inc/TOP3-find.html',{evalScripts: true});
  thePage.stateHistory.push(findState);
}

function seeState() {
  alert('not yet implemented');
}

function manageState() {
  alert('not yet implemented');
}

function findFundingState() {
  resetPage();
  new Ajax.Updater('TOP3','inc/TOP3-findByFunding.html',{evalScripts: true});
  new Ajax.Updater('centercontent','inc/findByFunding.html',{evalScripts: true, insertion: 'top'});
  thePage.stateHistory.push(findFundingState);
}

function findTitleState() {
  resetPage();
  new Ajax.Updater('TOP3','inc/TOP3-findByTitle.html',{evalScripts: true});
  new Ajax.Updater('centercontent','inc/findByTitle.html',{evalScripts: true, insertion: 'top'});
  thePage.stateHistory.push(findTitleState);
}

function findPersonState() {
  resetPage();
  new Ajax.Updater('TOP3','inc/TOP3-findByPerson.html',{evalScripts: true});
  new Ajax.Updater('centercontent','inc/findByPerson.html',{evalScripts: true, insertion: 'top'});
  thePage.stateHistory.push(findPersonState);
}

function findRegionState() {
  resetPage();
  new Ajax.Updater('TOP3','inc/TOP3-findByRegion.html',{evalScripts: true});
  new Ajax.Updater('centercontent','inc/findByRegion.html',{evalScripts: true, insertion: 'top'});
  thePage.stateHistory.push(findRegionState);
}

/*       -- local autocompleter version
function makeProjectTitleInput() {
  new Ajax.Request('inc/projectTitles.txt',{
                      onComplete: function(theResponse) {
                        evalScripts: true,
                        projectTitles = theResponse.responseText.strip().split('"|-|"');;
                        titleAC = new Autocompleter.Local('projectTitleInput','projectTitleChoices',projectTitles);
                      }
                  });
}
*/

function goBack() {
  if (thePage.stateHistory.length > 1) { 
    thePage.stateHistory.pop(); 
    thePage.stateHistory.pop()();
    return 
  };
  thePage.stateHistory.pop();
  mainState();
}

function doSearchWithUid(selectId) {
  var mySubmitSearch = submitSearch.bind(this);
  var selectedIndex = $(selectId).selectedIndex;
  var theUid = $(selectId).options[selectedIndex].value;
  // bogusing up the allSearchTerms object
  allSearchTerms = new Object();
  allSearchTerms.termSets = new Array();
  allSearchTerms.termSets[0] = new Object();
  allSearchTerms.termSets[0].terms = new Array();
  allSearchTerms.termSets[0].terms[0] = "{'category':'"+selectId+"','value':'"+theUid+"','forDisplay':''}";
  submitSearch();
}

function doSearchWithTitle(inputId) {
  var mySubmitSearch = submitSearch.bind(this);
  var theWords = $(inputId).value;
  // bogusing up the allSearchTerms object
  allSearchTerms = new Object();
  allSearchTerms.termSets = new Array();
  allSearchTerms.termSets[0] = new Object();
  allSearchTerms.termSets[0].terms = new Array();
  allSearchTerms.termSets[0].terms[0] = "{'category':'text::title','value':'"+theWords+"','forDisplay':''}";
  submitSearch();
}

function submitSearch() {
  var searchString = '{"searchNumber":"1","termSets":[';
  for (var setIndex = 0, numberOfSets = allSearchTerms.termSets.length; setIndex < numberOfSets; ++setIndex) { 
    searchString += '{"setNumber":"1","terms":[';
    if (allSearchTerms.termSets[setIndex].terms.length == 0 ) { 
      searchString += '{"termNumber":"'+(termIndex+1)+'","termValue":"empty"},';
    } else { 
      for (var termIndex = 0, numberOfTerms = allSearchTerms.termSets[setIndex].terms.length; termIndex < numberOfTerms; ++termIndex) { 
        searchString += '{"termNumber":"'+(termIndex+1)+'","termValue":';
        searchString += allSearchTerms.termSets[setIndex].terms[termIndex];
        searchString += '},';
      }
    }
    searchString = searchString.substring(0, searchString.length-1);
    searchString += ']},';
  } 
  searchString = searchString.substring(0, searchString.length-1);
  searchString += ']}';

  var searchJSON = Object.toJSON(searchString.evalJSON());
  new Ajax.Request('searchNew.php', { 
                      asynchronous: false,
                      parameters: 'theSearch='+searchJSON,
                      onComplete: function (theResponse) { 
                        // receives back the JSON encoded matching proposal information
                        if (theResponse) {
                          thePage.ResultSet = (theResponse.responseText.strip()).evalJSON();
                          displayAllResults2(thePage.ResultSet);
                        }
                      }
                  });
} 

// ----------------------------------------------------------------------
function displayResults(resultSet) {
  if (resultSet.length < 3) {
    resultSet = 'No matching records were found.';
  }
  $('AMISprojects').update(resultSet);
}


// ----------------------------------------------------------------------
Ajax.Responders.register({
  onCreate: function () {
    $('loadingAlert').show();
  },
  onComplete: function () {
    if (Ajax.activeRequestCount == 0) {
      $('loadingAlert').hide();
    }
  }
});

// ----------------------------------------------------------------------
var InflatingEntry = Class.create();
Object.extend(InflatingEntry.prototype,{

  initialize: function (info) {
    this.whatAmI = 'listEntry';
    this.container = new Element('span');
    this.title = info.title;
    this.entries = info.entries;  // object
    this.labels = info.labels;    // object
    this.state = 'isClosed';      // isClosed or isOpen
    this.openImage = new Element('img',{src:'/amis/theme/img/open_item.gif'});
    this.closeImage = new Element('img',{src:'/amis/theme/img/close_item.gif'});
    this.makeFramework();
    this.makeTable();
    this.addObservers();
  },

  returnEntry: function () {
    return this.container;
  },

  makeFramework: function () {
    this.titleSpan = new Element('span');
    this.titleSpan.insert('<b><i style="font-size:1.1em; color:#069">'+this.title+'</i></b>');
 //   this.titleSpan.insert('<h2>'+this.title+'</h2>'); 
    this.iconSpan = new Element('span');
    this.iconSpan.insert(this.openImage);
    this.bodySpan = new Element('span');
    this.container.insert(this.iconSpan);
    this.container.insert(this.titleSpan);
    this.container.insert('<br>');
    this.container.insert(this.bodySpan);
    this.bodySpan.hide();
  },

  makeTable: function () {
    var myEntries = this.entries;
    var myLabels = this.labels;
    var theTable = new Element('table');
    theTable.insert(new Element('thead'));
    theTable.insert(new Element('tbody'));
    theTable.insert(new Element('tfoot'));
    var theValues = Object.values(this.entries);
    Object.keys(this.entries).each(function(theKey,iterator) {
      if (!Object.isArray(myEntries[theKey])) {
        if ((myEntries[theKey] != null) && (myEntries[theKey] != 'null')) { // ignoring keys where the value is null 
          if (myLabels[theKey] != null) { // and ignoring entries where the label has been set to null
            if (myLabels[theKey] != 'Abstract Text:') {
              var theTd = new Element('td').insert('<b>'+myLabels[theKey]+'</b>: '+myEntries[theKey]);
            } else {
              var theTdText = '<b>'+myLabels[theKey]+'</b>: ';
              theTdText += '<p style="font-family:Georgia; color:#069; font-size:"85%",font-stretch:"wider">'+myEntries[theKey]+'</p>';
              var theTd = new Element('td').insert(theTdText);
            }
            theTable.down('tbody').insert((new Element('tr')).insert(theTd));
          }
        }
      } else {
        if (myEntries[theKey].length > 0) {
          var theTd = new Element('td').insert(myLabels[theKey]+': '+myEntries[theKey]);
          theTable.down('tbody').insert((new Element('tr')).insert(theTd));
        }
      }
    })
    this.bodySpan.insert(theTable);
  },

  toggleState: function () {
    switch (this.state) {
      case 'isClosed':
        this.bodySpan.show();
        this.iconSpan.update(this.closeImage);
        this.state = 'isOpen';
        break;
      case 'isOpen':
        this.bodySpan.hide();
        this.iconSpan.update(this.openImage);
        this.state = 'isClosed';
        break;
      default:
        console.log('InflatingEntry::toggleState: invalid state');
    }
  },

  myMouseOver: function () {
    var myUid = this.entries.uid;
//    thePage.mapOutput.selectProjectWFSFeature(myUid);
  },

  myMouseOut: function () {
    var myUid = this.entries.uid;
//    thePage.mapOutput.unselectProjectWFSFeature(myUid);
  },

  addObservers: function () {
    $(this.iconSpan).observe('click',this.toggleState.bind(this));
    $(this.container).observe('mouseover',this.myMouseOver.bind(this));
    $(this.container).observe('mouseout',this.myMouseOut.bind(this));
  }

})

//----------------------------------------------------------------
function displayResult(aResult,reportLabels) {
  var tmpString = 'http://ak.aoos.org/amis/projectInfo.php?uids='+aResult.uid;
  aResult.detailsLink = '<a href="'+tmpString+'" target="_blank">'+tmpString+'</a>';
  var theEntryInfo = new Object();
  theEntryInfo.title = aResult.fullTitle;
  theEntryInfo.entries = aResult;
  theEntryInfo.labels = reportLabels || null;
  theEntry = new InflatingEntry(theEntryInfo);
  return (theEntry.returnEntry());
}

//----------------------------------------------------------------
function displayAllResults2(theResults) {
  var theContainer = $('AMISliteResults');
  theContainer.update();  // remove previous results

  var reportLabels = new Object();
  reportLabels.uid = null;   // 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.detailsLink = "Full Details";
//  reportLabels.dataLink = "Access Data";

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

  var leftInnerTable = new Element('table');
  leftInnerTable.insert((new Element('thead')).insert('Proposal/Project Results'));
  var leftInnerTableBody = new Element('tbody');
  if (theResults.length < 1) {
    leftInnerTableBody.insert((new Element('tr')).insert((new Element('td')).insert('<h1>No Matching Proposals or Projects found.</h1>')))
  } else {
    for (var iterator=0, last=theResults.length; iterator<last; ++iterator) {
      // create the link to directly access the data
      leftInnerTableBody.insert((new Element('tr')).insert((new Element('td')).insert(displayResult(theResults[iterator],reportLabels))));
    }
  }
  leftInnerTable.insert(leftInnerTableBody);
  leftInnerTable.insert(new Element('tfoot'));

/*
  var rightInnerTable = new Element('table');
  rightInnerTable.insert((new Element('thead')).insert('Dataset Results'));
  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'));
*/

  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', style: 'width: 400px; height: 320px; float: left; border: 1px solid black;'});
//  $(td3).insert(mapDiv);
//  var panelDiv = new Element('div',{id:'outputMapPanelDiv', 'class': 'olControlPanel', style: 'margin-top: -320px; margin-left: 0px; width: 100px; z-index: 900; float: left; position: relative;'});
//  $(td3).insert(panelDiv);
//  var thisMapOutput = new RegionOutputMap($(mapDiv));
//  thePage.mapOutput = thisMapOutput;
  $(theContainer).insert('</div>');
  $(theContainer).show();
  var theUids = theResults.pluck('uid');
//  thisMapOutput.updateProjectsWFSLayer(theUids.join(','));
//  thisMapOutput.updateDataWFSLayer(amis.search.dslist);
}
//----------------------------------------------------------------

var RegionOutputMap = Class.create();
Object.extend(RegionOutputMap.prototype,{

  initialize: function (theMapContainer) {
    this.whatAmI = 'RegionOutputMap';
    this.mapContainer = theMapContainer;
    this.addObservers();
    this.theMap = this.makeMapObject();
    this.makeMap();
  },

  makeMapObject: function () {
    theMap = new Object();
    theMap.regionOutputMap = this;
    theMap.baseMap = null;
    theMap.controlPanel = null;
    theMap.drawLayer = null;
    theMap.container =this.mapContainer.identify();
    theMap.width = 500;
    theMap.height = 400;
    return theMap;
  },

  makeMap: function () {
    Proj4js.defs["EPSG:3338"] = "+proj=aea +lat_1=55 +lat_2=65 +lat_0=50 +lon_0=-154 +x_0=0 +y_0=0 +ellps=GRS80 +datum=NAD83 +units=m +no_defs";
    aoos_wms = "http://ak.aoos.org/op/mapserver/ows.php?";
    options = {
      maxExtent: new OpenLayers.Bounds(-1833104.77, 289608.57, 1698564.68, 2938360.66),
      width: theMap.width,
      height: theMap.height,
      controls: [],
      units: 'm',
      projection: new OpenLayers.Projection("EPSG:3338"),
      displayProjection: new OpenLayers.Projection("EPSG:4326")
    };
    options.maxResolution = Math.round((options.maxExtent.right-options.maxExtent.left)/theMap.width);
    this.makeBaseMap(this.theMap,options);
    this.makeBasicControls(this.theMap);
    this.makeProjectWFSLayer(this.theMap);
    this.makeDataWFSLayer(this.theMap);
    this.makeDrawBoxLayer(this.theMap);
    this.makeRegionsWFSLayer(this.theMap);
    this.addControlPanel(this.theMap);
    $(this.theMap.container).show();
  },

  makeBaseMap: function(theMap,theOptions) {
    // creating base map
    var baseMap = new OpenLayers.Map(theMap.container, theOptions );
    var layer = new OpenLayers.Layer.WMS.Untiled( "Coastlines", aoos_wms, {layers: 'coastlines_l'});
    layer.setIsBaseLayer(true);
    layer.setVisibility(true);
    baseMap.addLayer(layer);
    if (!baseMap.getCenter()) baseMap.zoomToMaxExtent();
    theMap.baseMap = baseMap;
  },

  makeBasicControls: function(theMap) {
    theMap.baseMap.addControl(new OpenLayers.Control.MousePosition());
    zoom_box = new OpenLayers.Control.ZoomBox({title:"Zoom box"});
    zoom_out = new OpenLayers.Control.ZoomToMaxExtent({title:"Zoom out"});
    theControlPanel = new OpenLayers.Control.Panel({defaultControl: zoom_box, div: $('outputMapPanelDiv')});
    theControlPanel.addControls([ new OpenLayers.Control.MouseDefaults({title:"Pan"}), zoom_box, zoom_out ]);
    theMap.controlPanel = theControlPanel;
  },

  resetMap: function() {

  },

  addExistingBounds: function (theCorners,theProjection) {
    // "theCorners" is an array [lon/westing, lat/northing]
    // of two element arrays [lon lat]
    theProjection = ( theProjection || 'lonlat' );
    if (theProjection != 'albers') {
      var albersCorners = lonlatToAlbers(theCorners);
    } else {
      var albersCorners = theCorners;
    }
    switch (albersCorners.length) {
      case 0:
        // somethin' just ain't right
        break;
      case 1:
        // its a point; not dealt with at this time
        break;
      case 2:
        // bounding box; assume points are NW corner and SE corner
        var cornerPoints = new Array (new OpenLayers.Geometry.Point(albersCorners[0][0], albersCorners[0][1]),
                                      new OpenLayers.Geometry.Point(albersCorners[1][0], albersCorners[0][1]),
                                      new OpenLayers.Geometry.Point(albersCorners[1][0], albersCorners[1][1]),
                                      new OpenLayers.Geometry.Point(albersCorners[0][0], albersCorners[1][1]),
                                      new OpenLayers.Geometry.Point(albersCorners[0][0], albersCorners[0][1]));
        break;
      default:
        // assume its an arbitrary, closed polygon
        var cornerPoints = new Array();
        for (var iterator=0, last=albersCorners.length; iterator < last; ++iterator) {
          cornerPoints.push(new OpenLayers.Geometry.Point(albersCorners[iterator][0], albersCorners[iterator][1]));
        }
    }
    var ring = new OpenLayers.Geometry.LinearRing(cornerPoints);
    var theBox = new OpenLayers.Geometry.Polygon(ring);
    var theFeature = new OpenLayers.Feature.Vector(theBox);
    var theLayer = this.theMap.baseMap.getLayersByName('existingBoundsLayer')[0];
    theLayer.addFeatures([theFeature]);
  },

  makeDrawBoxLayer: function(theMap) {
    selectLayer = new OpenLayers.Layer.Vector("select_layer");
    selectLayer.setVisibility(true);
    // ------------- drawing event handlers
    // when starting to draw a box, first remove any box that had already been drawn
    selectLayer.events.register("beforefeatureadded", selectLayer, function(event) {
      if (selectLayer.features.length > 1) { selectLayer.removeFeatures(selectLayer.features[0]); }
    });
    // after a box is drawn, get the corners and transform the coordinates
    selectLayer.events.register("featureadded", selectLayer, function(event) {
      // get the corners of the box; note: in epsg:102006
      var bounds = this.features[0].geometry.getBounds();
      var albersCorners = new Array( new Array(bounds.left, bounds.top),new Array(bounds.right, bounds.bottom));
      var lonlatCorners = albers2lonlat(albersCorners);
      // use the entered values to update the search parameters
      theMap.regionOutputMap.updateSearchByRegion(lonlatCorners,albersCorners);
      // theMap.reportTo.updateFields(lonlatCorners,'map');
    });
    // -------------- end of event handlers
    theMap.baseMap.addLayers([selectLayer]);
    rectControl = new OpenLayers.Control.DrawFeature(selectLayer, OpenLayers.Handler.RegularPolygon,
                                                  {handlerOptions: {sides: 4, irregular: true},
                                                   displayClass: 'olControlDrawRect', title:'Select Region'});
    theMap.controlPanel.addControls(rectControl);
  },

  addControlPanel: function(theMap) {
    theMap.baseMap.addControl(theMap.controlPanel);
  },

  updateSearchByRegion: function (lonlatCorners,albersCorners) {
    var newTermObject = new Object();
    newTermObject.category = 'region::custom';
    newTermObject.value = albersCorners[0][0] + " " + albersCorners[0][1] +","+ albersCorners[1][0] + " " + albersCorners[1][1];
//    newTermObject.forDisplay = "("+lonlatCorners[0][0]+","+lonlatCorners[0][1]+"),("+lonlatCorners[1][0]+" "+lonlatCorners[1][1]+")";
    newTermObject.forDisplay = "(" + (Math.round(lonlatCorners[0][0]*1000)/1000);
    newTermObject.forDisplay += "," + (Math.round(lonlatCorners[0][1]*1000)/1000);
    newTermObject.forDisplay += "),(" + (Math.round(lonlatCorners[1][0]*1000)/1000);
    newTermObject.forDisplay += "," + (Math.round(lonlatCorners[1][1]*1000)/1000) + ")";
    allSearchTerms.overloadRegionSearch(Object.toJSON(newTermObject));
  },

  addObservers: function () {
  }
})

//----------------------------------------------------------------
// Steve Gaffigan's extensions to RegionInputMap, applied to RegionOutputMap
Object.extend(RegionOutputMap.prototype,{
  makeProjectWFSLayer: function(theMap) {
      // Add WFS layer for project bounds
      // Add control for selecting features
      var styleMap = new OpenLayers.StyleMap({strokeColor: "red",strokeWidth: 2,fillOpacity: 0});
      var layer = new OpenLayers.Layer.WFS("wfs_projects", 'http://ak.aoos.org/cgi-bin/sumplots_cgi.py?',
                                           {request2: 'projectShapes'},
                                           {styleMap: styleMap, isBaseLayer: false, visibility: true, extractAttributes: true});
      theMap.baseMap.addLayer(layer);
      var selectStyle = OpenLayers.Util.applyDefaults({strokeColor: '#ff0000', strokeWidth: 4, strokeOpacity: 0.9},
                                                       OpenLayers.Feature.Vector.style["select"]);
      theMap.controlPanel.addControls([new OpenLayers.Control.SelectFeature(layer,
                                      {hover: true, selectStyle: selectStyle, title: 'wfs_projects', displayClass: 'olControlSelectProject'})]);
  },

  updateProjectsWFSLayer: function(projectuid) {
      // Update WFS projects layer with given projectuid
      // Argument should be a comma-delimited list
      this.theMap.baseMap.getLayersByName("wfs_projects")[0].mergeNewParams({projectuid: projectuid});
  },

  getProjectWFSFeature: function(projectuid) {
      // Return feature from WFS project layer corresponding to given (single) projectuid
      var layer = this.theMap.baseMap.getLayersByName("wfs_projects")[0];
      for (var i=0; i<layer.features.length; i++) {
          if (layer.features[i].attributes.projectUid==projectuid) {
              return layer.features[i];
          }
      }
  },

  selectProjectWFSFeature: function(projectuid) {
      // Select feature from WFS project layer corresponding to given (single) projectuid
      var feature = this.getProjectWFSFeature(projectuid);
      if (feature != null) {
          this.theMap.controlPanel.getControlsBy('title', 'wfs_projects')[0].select(feature);
      }
  },

  unselectProjectWFSFeature: function(projectuid) {
      // Unselect feature from WFS project layer corresponding to given (single) projectuid
      var feature = this.getProjectWFSFeature(projectuid);
      if (feature != null) {
          this.theMap.controlPanel.getControlsBy('title', 'wfs_projects')[0].unselect(feature);
      }
  },

  makeDataWFSLayer: function(theMap) {
      // Add WFS layer for data bounds
      // Add control for selecting features
      var styleMap = new OpenLayers.StyleMap({strokeColor: "red",strokeWidth: 2,fillOpacity: 0});
      var layer = new OpenLayers.Layer.WFS("wfs_datafiles", 'http://ak.aoos.org/cgi-bin/sumplots_cgi.py?',
                                           {request2: 'datafilesWFS'},
                                           {styleMap: styleMap, isBaseLayer: false, visibility: true, extractAttributes: true});
      theMap.baseMap.addLayer(layer);
      var selectStyle = OpenLayers.Util.applyDefaults({strokeColor: '#ff0000', strokeWidth: 4, strokeOpacity: 0.9},
                                                       OpenLayers.Feature.Vector.style["select"]);
      theMap.controlPanel.addControls([new OpenLayers.Control.SelectFeature(layer,
                                      {hover: true, selectStyle: selectStyle, title: 'wfs_datafiles', displayClass: 'olControlSelectDataset'})]);
  },

  updateDataWFSLayer: function(dslist) {
      // Update WFS data layer with given datasets
      if (dslist==null) return;
      var dslist2 = new Array();
      var keys = ['id','id2'];
      for (var i=0; i<dslist.length; i++) {
          dslist2[i] = {dsid: dslist[i].dsid};
          for (var j=0; j<keys.length; j++) {
              if (dslist[i][keys[j]] != null) {
                  dslist2[i][keys[j]] = dslist[i][keys[j]];
              }
          }
      }
      // this breaks in IE with large urls due to GET limitation
      try {
          this.theMap.baseMap.getLayersByName("wfs_datafiles")[0].mergeNewParams({dslist: escape(Object.toJSON(dslist2))});
      } catch(err) {
      }
  },

  getDataWFSFeature: function(item) {
      // Return feature from WFS data layer corresponding to given (single) dataset
      var a,layer = this.theMap.baseMap.getLayersByName("wfs_datafiles")[0];
      for (var i=0; i<layer.features.length; i++) {
          a = layer.features[i].attributes;
          if (a.dsid==item.dsid && a.id==item.id && a.id2==item.id2) {
              return layer.features[i];
          }
      }
  },

  selectDataWFSFeature: function(itemstr) {
      // Select feature from WFS data layer corresponding to given (single) dataset
      var item = unescape(itemstr).evalJSON();
      var feature = this.getDataWFSFeature(item);
      if (feature != null) {
          this.theMap.controlPanel.getControlsBy('title', 'wfs_datafiles')[0].select(feature);
      }
  },

  unselectDataWFSFeature: function(itemstr) {
      // Unselect feature from WFS data layer corresponding to given (single) dataset
      var item = unescape(itemstr).evalJSON();
      var feature = this.getDataWFSFeature(item);
      if (feature != null) {
          this.theMap.controlPanel.getControlsBy('title', 'wfs_datafiles')[0].unselect(feature);
      }
  },

  makeRegionsWFSLayer: function(theMap) {
      // Add WFS layer for regions
      // Add control for selecting features
      var styleMap = new OpenLayers.StyleMap({strokeWidth: 1, strokeColor: 'yellow', strokeOpacity: 0, fillOpacity: 0});
      var layer = new OpenLayers.Layer.WFS("wfs_regions", 'http://ak.aoos.org/cgi-bin/sumplots_cgi.py?',
                                           {request2: 'regionsWFS'},
                                           {styleMap: styleMap, isBaseLayer: false, visibility: true, extractAttributes: true});
      theMap.baseMap.addLayer(layer);
      var selectStyle = OpenLayers.Util.applyDefaults({strokeColor: 'red', strokeWidth: 2, strokeOpacity: 0.9, fillColor: 'yellow'},
                                                       OpenLayers.Feature.Vector.style["select"]);
      theMap.controlPanel.addControls([new OpenLayers.Control.SelectFeature(layer,
                                      {hover: true, selectStyle: selectStyle, title: 'wfs_regions', displayClass: 'olControlSelectRegion'})]);
  },

  getRegionWFSFeature: function(name) {
      var layer = this.theMap.baseMap.getLayersByName("wfs_regions")[0];
      for (var i=0; i<layer.features.length; i++) {
          if (layer.features[i].attributes.name == name) {
              return layer.features[i];
          }
      }
  },

  selectRegionWFSFeature: function(name, unselect) {
      var layer, control, feature;

      layer = this.theMap.baseMap.getLayersByName("wfs_regions")[0];
      control = this.theMap.controlPanel.getControlsBy('title', 'wfs_regions')[0];
      for (var i=0; i<layer.features.length; i++) {
          feature = layer.features[i];
          if (feature.attributes.name == name && !unselect) {
              control.select(feature);
          } else {
              control.unselect(feature);
          }
      }
  }
});

//--------------------------------------------------------------

