// results.js: Javascript code to display the search results and respond to user interaction with the actual data:

//First need inArray function
Array.prototype.inArray = function (value) {
	var i;
	for (i=0; i < this.length; i++)
		if (this[i] === value) return true;
	return false;
};

var results = new Object();
results.labelView = false;
results.fadeOverlayCount = 0;
results.tester = 1;

results.load = function()
{
  if(!googleMap.loaded) googleMap.loadMap();
  if(googleMap.loaded)
  {
    interface.toggleData(true); //collapse the datapane at the start
    googleMap.map.setCenter(new GLatLng(44.084133,-120.4), googleMap.defaultZoom);
  	googleMap.clearMarkers(); //clear any existing markers
    googleMap.showMarkers();
    if(cache.totalFoundCount == 1)
    	results.updateDetailView(cache.selectedRecord, false);
  }
  //Set map header text = cache.totalFoundCount, show summary pane, map header
  document.getElementById("mapheadertext").innerHTML=cache.totalFoundCount+" matching records";
  document.getElementById("summarypane").style.display = "block";
  document.getElementById("mapheader").style.display = "block";
 //if(cache.polygonVertexCount > 0) googleMap.showPolygon();*/
};

results.removeFadeOverlay = function()
{
  this.fadeOverlayCount--;
  if(this.fadeOverlayCount <= 0)
  {
    var grayoutDiv = document.getElementById("grayout");
    grayoutDiv.style.visibility = "hidden";
  }
};

results.sort = function()
{
  // Re-sort the previous search results (equivalent to doing a new search but re-using the previous search query):
  if(cache.queryCount == 0 || cache.totalFoundCount == 0) return;
  window.location = "results.php?" + cache.queryArgs + "&" + cache.querySort + "&Limit=" + cache.pageLimit; 
};

/* results.getPage = function(pageNum, action, index)
{
  // Triggers for this function:
  // Select a marker on the map that corresponds to a record not already loaded.
  // Use the drop-down list or arrows in the list view to select another page.
  // Use the arrows in the detail view to move to a record that is not already loaded.

  // action = page: load a page of records and display the list view.
  // action = detail: load a page of records and display the detail view.
  // action = none: load a page of records then do nothing.

  // index is the value of cach.index for the selected specimen (until the page is retrieved, have no way of knowing the position in the JavaScript array)

  // Already have the page loaded, so do nothing here other than update the page size:
  if(cache.index[pageNum*cache.pageLimit] > 0)
  {
    var pageStart = cache.pageStarts[pageNum];
    var pageEnd = cache.pageStarts[pageNum + 1];
    if((pageNum+1) >= cache.pageStarts.length) pageEnd = cache.queryCount+1;
    cache.pageSize = pageEnd - pageStart;
    return;
  }
  if(cache.totalFoundCount < 1) return;  // No search results.

  if(pageNum <= 0) pageNum = 0;  // zero-based page number; catch undefined pageNum with the <= operator
  if(pageNum >= cache.pageCount) pageNum = cache.pageCount - 1;
  if(action == "") action = "none";

  // Position grayout screen over data pane if data pane is visible
  if(!interface.dataCollapsed)
  {
    var grayoutDiv = document.getElementById("grayout");
    grayoutDiv.style.top = interface.dataTop + "px";
    grayoutDiv.style.left = interface.dataLeft + "px";
    grayoutDiv.style.width = interface.dataWidth + "px";
    grayoutDiv.style.height = interface.dataHeight + "px";
    grayoutDiv.style.visibility = "visible";
    document.getElementById("loadingicon").style.visibility = "visible";
  }

  var head = document.getElementsByTagName("head")[0];
  var oldScript = document.getElementById("datapage");
  if(oldScript) head.removeChild(oldScript);

  var timestamp = new Date().getTime();

  var pageStart = cache.pageStarts[pageNum];
  var pageEnd = cache.pageStarts[pageNum + 1];
  if((pageNum+1) >= cache.pageStarts.length) pageEnd = cache.queryCount;

  var newScript = document.createElement('script');
  newScript.id = "datapage";
  newScript.type = "text/javascript";
  newScript.src = "getpage.php?" + cache.queryArgs + "&PageNum=" + pageNum + "&Start=" + pageStart + "&End=" + pageEnd + "&Limit=" + cache.pageLimit + "&" + cache.querySort + "&action=" + action + "&index=" + index + "&time=" + timestamp;
  head.appendChild(newScript);

  // Once loaded, getpage.php will copy the page of data over to the cache arrays and then call results.showPage(action) to finish the display process.
}; */

results.showPage = function(action)
{
	window.alert('implement results.showPage()');
	/*
  if(action == "detail") this.updateDetailView(cache.selectedRecord, false);
  if(action == "list") this.updateListView(cache.selectedPage);

  document.getElementById("grayout").style.visibility = "hidden";
  document.getElementById("loadingicon").style.visibility = "hidden";
  */
};


results.resetPageSelector = function()
{
  document.getElementById("pageselector").selectedIndex = 0;
};

results.getLatLon = function(lat,lon) {
	// Oregon - map_lat always positive (N), map_long always negative (W)
    if (isNaN(lat) || isNaN(lon)) 
    	return "Error - lat/long not valid numbers";
    // Change long to absolute value, calculate degrees, minutes, seconds
    lon = Math.abs(lon);
    LatDeg = Math.floor(lat);
    LatMin = Math.floor((lat-LatDeg)*60);
    LatSec =  (Math.round((((lat - LatDeg) - (LatMin/60)) * 60 * 60) * 100) / 100 ) ;
    LonDeg = Math.floor(lon);
    LonMin = Math.floor((lon-LonDeg)*60);
    LonSec = (Math.round((((lon - LonDeg) - (LonMin / 60 )) * 60 * 60) * 100 ) / 100);
	return LatDeg+"&deg; "+LatMin+"&#39; "+LatSec+"&#34 N, "+LonDeg+"&deg; "+LonMin+"&#39; "+LonSec+"&#34 W";
}

results.updateDetailView = function(i, showOnMap)
{
  if(i > cache.totalFoundCount-1 || i<0) return;
  if(showOnMap) {
    if (googleMap.selectedMarkerIndex >=0 && !cache.clusters[googleMap.selectedMarkerIndex][3].inArray(i))
      googleMap.map.closeInfoWindow(); // Hide info window
    var c = googleMap.findSpecimenCluster(cache.index[i]);
    googleMap.selectMarker(c, true);  // Mark the record on the map.\
  }

  cache.selectedRecord = i;
  cache.showOnMap=showOnMap;
  ajaxHelper('POST','results.detail', './includes/atlasdetail.php', 'type='+cache.type[i]+'&source='+cache.source[i]);
}

results.detail_ajax = function(data)
{
  i=cache.selectedRecord;
  showOnMap=cache.showOnMap;
  data=data.replace(/:null,/g,':"",'); //replace nulls with empty strings for display in the details pane
  details=eval('(' + data + ')'); //assign data from detail query to details object
  document.getElementById("selectedRecord").innerHTML="<b>Record " + (i+1) + " of " + cache.totalFoundCount + "</b>";
  var divText = "</div><div class=\"detailtext\">";
  var divEnd = "&nbsp;</div></div>";
  var entryHTML = "";
  
  if(cache.type[i]=="s" && this.labelView) {//show specimen label view
  	var source=details.source;
    entryHTML += '<div class="labelview">';
	entryHTML += '(<a href="javascript:results.labelView=false; results.updateDetailView('+i+',false);">return to field view</a>)<br /><br />';
    if (details.typestatus != "")
	   	entryHTML += details.typestatus + "<br />";
    entryHTML += '<div style="text-align:center;">Identified as:<br />';
    if (details.syntaxonauths=="") entryHTML += details.taxonauths;
    else entryHTML += details.syntaxonauths;
    entryHTML += "<br />"+details.family+"</div><br />";
    entryHTML += "Original determination: "; 
    if (details.originaldet=="") entryHTML += "Not provided";
    else entryHTML += details.originaldet;
    entryHTML += '<p>' + details.county + " Co.; " + details.location;
    if (details.elevation != "")
    	entryHTML += "; Elev. " + details.elevation + "m.";
    if (details.trs != "")
	    entryHTML += "; " + details.trs;
    if (details.location!="Sensitive species &ndash; location undisclosed" && details.label_lat_long != "")
    	entryHTML += "; " + details.label_lat_long;
    if (details.utm != "")
	    entryHTML += "; " + details.utm;
	entryHTML += "</p>";
    entryHTML += '<p>' + details.habitat + "</p>";
    if (details.associates != "")
    	entryHTML += '<p>Associated with:' + details.associates + "</p>";
    if (details.phenology != "")
	    entryHTML += details.phenology + "<br />";
    entryHTML += details.notes + "<br />";
    entryHTML += '<table width="100%"><tr><td align="left">' + details.collector_observer + "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;#" + details.collectors_num + "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + details.date + '</td>';
    entryHTML += '<td align="right">' + details.source + "&nbsp;&nbsp;</td></tr></table>";
    entryHTML += '<br />&nbsp;</div>';
  }
  else //show fields
  {
    if(details.cd != undefined && details.cd != '') {  // thumbnail exists, show with link to full image. . .
        entryHTML += '<p style="text-align:center;"><img src="/OFPimagesNEW/OFPImages_thumbs/'+details.cd+'/'+details.filename+'.jpg" alt="" ';
        entryHTML += 'title="Click to view full size image in new window" onclick="window.open(\'imgFull.php?CD=' +details.cd+ '&file=' +details.filename+ '&taxon=' + cache.taxon[i];
    	if (cache.type[i]=="p")
    		entryHTML += '&fieldphotonum='+cache.source[i];
        entryHTML += '\',\'' + cache.source[i] + '\');" /></p>';
    }
    var divRow1 = "<div class=\"detailrow1\"><div class=\"detaillabel\">";
    var divRow2 = "<div class=\"detailrow2\"><div class=\"detaillabel\">";
	var source;
	if (cache.type[i]=="s") 
		source = details.source + '(<a href="javascript:results.labelView=true; results.updateDetailView('+i+',false);">label view</a>)';
	else if (cache.type[i]=="a")
		source = 'Associated plant #' + cache.source[i];
	else if (cache.type[i]=="o")
		source = 'Species list #' + cache.source[i];
	else if (cache.type[i]=="p")
		source = 'Photograph #' + cache.source[i];

    entryHTML += divRow1 + "Source" + divText + source + divEnd;

    entryHTML += divRow2 + "Family" + divText + details.family + divEnd;

    entryHTML += divRow2 + "Current Name" + divText + "<b><i>" + details.taxon + "</i></b>" + divEnd;

    entryHTML += divRow2 + "Common Name(s)" + divText + details.common + divEnd;

    entryHTML += divRow2 + "Synonym(s)" + divText + details.synonyms + divEnd;

    if (cache.type[i]=="s" || cache.type[i]=="p")
    	entryHTML += divRow2 + "Identified By" + divText + details.id_by + divEnd;

    entryHTML += divRow1 + "Collector/Observer(s)" + divText + details.collector_observer + divEnd;

    if (cache.type[i]=="s")
    	entryHTML += divRow1 + "Collector #" + divText + details.collectors_num + divEnd;

    entryHTML += divRow1 + "Date" + divText + details.date + divEnd;

    entryHTML += divRow2 + "County" + divText + details.county + divEnd;

    entryHTML += divRow2 + "Location" + divText + details.location + divEnd;

    entryHTML += divRow2 + "Elevation" + divText + details.elevation + divEnd;

    entryHTML += divRow2 + "Lat/Lon" + divText;
    if (details.location!="Sensitive species &ndash; location undisclosed")
    	entryHTML += this.getLatLon(cache.lat[i],cache.lon[i]);
    entryHTML += divEnd;

    if (cache.type[i]!="p")
	    entryHTML += divRow2 + "Accuracy" + divText + details.accuracy + divEnd;

    if (cache.type[i]=="s" || details.type=="a")
    	entryHTML += divRow2 + "UTM" + divText + details.utm + divEnd;

    if (cache.type[i]!="o")
    	entryHTML += divRow2 + "TRS" + divText + details.trs + divEnd;

    if (cache.type[i]!="p")
    	entryHTML += divRow1 + "Habitat" + divText + details.habitat + divEnd;

    if (cache.type[i]=="s" || cache.type[i]=="a")
    	entryHTML += divRow1 + "Associated Plants" + divText + details.associates + divEnd;

    if (cache.type[i]=="s") {
    	entryHTML += divRow1 + "Specimen Notes" + divText + details.notes + divEnd;
    	entryHTML += divRow1 + "Phenology" + divText + details.phenology + divEnd;
    	entryHTML += divRow1 + "Type Status" + divText + details.typestatus + divEnd;
    }
    
    if(cache.type[i]== "o" && details.sitecount>1) // show link to all taxa from same site
      entryHTML += "<div style=\"padding-left:10px;\"><a href=\"sitePlants.php?source=" + cache.source[i] +
      "\" target=\"_blank\">View all other taxa found at this site (opens new window)</a><br /></div>";
  }
  entryHTML += "<div style=\"clear:both; padding:5px 5px 0px 7px;\">If you have a question or comment about this record, please ";
// Email obfuscator script 2.1 by Tim Williams, University of Arizona
// Random encryption key feature by Andrew Moulden, Site Engineering Ltd
// This code is freeware provided these four comment lines remain intact
// A wizard to generate this code is at http://www.jottings.com/obfuscator/
  var coded = "hWus47so@hLqlhBW7hLs.hLl";
  var key = "waSMyv1JrE8hUjpBbil9fXkF6smetZxDL3KIRYudPT7GWAcVHo0q4n5zgQ2NOC";
  var link="";
  for (i=0; i<coded.length; i++)
    if (key.indexOf(coded.charAt(i))==-1) {
      ltr = coded.charAt(i)
      link += (ltr)
    }
    else {     
      ltr = (key.indexOf(coded.charAt(i))-coded.length+key.length) % key.length
      link += (key.charAt(ltr))
    }
    entryHTML += "<a href='mailto:"+link+"?subject=Atlas record "+source+"'>contact us</a>.</div>";
  var dataview1 = document.getElementById("dataview1");
  if("innerHTML" in dataview1) dataview1.innerHTML=entryHTML;
  else if("firstChild" in dataview1 && "data" in dataview1.firstChild) dataview1.firstChild.data=entryHTML;
  
    
};