var xmlHttp;
var completeDiv;
var inputField;
var nameTable;
var nameTableBody;
var expertPosition = 0;
var taxanomicArray;
var browseCriteria = new Array(3);
browseCriteria[0]="2";
browseCriteria[1]="0";
browseCriteria[2]="0";
var currentBackground = "";

//Sets up the XMLHttpRequest Object for use with Ajax
function createXMLHttpRequest() {
  if (window.ActiveXObject) {
    xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
  }
  else if (window.XMLHttpRequest) {
    xmlHttp = new XMLHttpRequest();                
  }
}

//Called from the browse species page, pulls back the taxa group from the 
//enviromental group
function getTaxaGroup(intEnvGroupID) {
  //first thing we do here is change the color of the selected box to blue
  var counter = 1;
  while (document.getElementById("env" + counter) != null) {
    document.getElementById("env" + counter).style.background = "#FFFFFF";
    counter = counter + 1;
  }
  document.getElementById("env" + intEnvGroupID).style.background = "#999999";
  
  
  //addToSearch(intEnvGroupID,0);
  document.getElementById("specieslist").innerHTML = "";
  document.getElementById("taxagrouplist").innerHTML = "";
  createXMLHttpRequest();      
  var url = "SpeciesTreeSearch?envGroupID=" + escape(intEnvGroupID) + "&taxaGroupID=0";                        
  xmlHttp.open("GET", url, true);
  xmlHttp.onreadystatechange = populateTaxaGroup;
  xmlHttp.send(null);
}

//Called from the browse species page, pulls back the species group from the 
//taxa group
function getSpeciesGroup(intTaxaGroupID,intEnvGroupID,idnumber) {
  //first thing we do here is change the color of the selected box to blue
  var counter = 1;
  while (document.getElementById("spp" + counter) != null) {
    document.getElementById("spp" + counter).style.background = "#FFFFFF";
    counter = counter + 1;
  }
  document.getElementById("spp" + idnumber).style.background = "#999999";
  
  document.getElementById("specieslist").innerHTML = "";
  createXMLHttpRequest();            
  var url = "SpeciesTreeSearch?envGroupID=" + intEnvGroupID + "&taxaGroupID=" + escape(intTaxaGroupID); 
  xmlHttp.open("GET", url, true);
  xmlHttp.onreadystatechange = populateSpeciesGroup;
  xmlHttp.send(null);
}

//Is called after the taxa group information has come back 
//IMPORTANT THIS COMES BACK IN PRE-PREPARED HTML
function populateTaxaGroup() {
  if (xmlHttp.readyState == 4) {
    if (xmlHttp.status == 200) {
      document.getElementById("taxagrouplist").innerHTML = xmlHttp.responseText;
      
    }
  }
}

//Is called after the species information is brought back
//IMPORTANT THIS COMES BACK IN PRE-PREPARED HTML
function populateSpeciesGroup() {
  if (xmlHttp.readyState == 4) {
    if (xmlHttp.status == 200) {
      document.getElementById("specieslist").innerHTML = xmlHttp.responseText;
    }
  }
}

//This is part of the autocomplete, it prepares global variables for use
function initVars() {
  inputField = document.getElementById("names");
  nameTable = document.getElementById("name_table");
  completeDiv = document.getElementById("popup");
  nameTableBody = document.getElementById("name_table_body");
}

//is called on keyup from the species search input box
function findNameas() {
  initVars();
  if (inputField.value.length > 0) {
    createXMLHttpRequest();
    var url = "AutoCompleteSpeciesSearch?names=" + escape(inputField.value);
    xmlHttp.open("GET", url, true);
    xmlHttp.onreadystatechange = populateNames;
    xmlHttp.send(null);
  } else {
    clearNames();
  }
}

//is the callback for the autocomplete box
function populateNames() {
  if (xmlHttp.readyState == 4) {
    if (xmlHttp.status == 200) {
      setNames(xmlHttp.responseXML.getElementsByTagName("item"));
    } else if (xmlHttp.status == 204){
      clearNames();
    }
  }
}

//Interprets the XML coming back from the AutoComplete
function setNames(the_names) {
  window.alert("hello");
  clearNames();
  var size = the_names.length;
  setOffsets();
  document.getElementById("popup").style.visibility = "visible";
  document.getElementById("popup").style.display = "";
  var row, cell, txtNode;
  for (var i = 0; i < size; i++) {
    var nextNode = the_names[i].getElementsByTagName("name")[0].firstChild.data ;
    var nextNodeTaxa = the_names[i].getElementsByTagName("taxaclass")[0].firstChild.data ;
    row = document.createElement("tr");
    cell = document.createElement("td");
    cellTaxa = document.createElement("td");
    italic = document.createElement("i");
    
    cell.onmouseout = function() {this.className='mouseOver';};
    cell.onmouseover = function() {this.className='mouseOut';};
    cell.setAttribute("bgcolor", "#FFFAFA");
    cell.setAttribute("border", "0");

    cell.onclick = function() { populateName(this); } ;
    
    txtNode = document.createTextNode(nextNode);
    txtNodeTaxa = document.createTextNode(nextNodeTaxa);
    cell.appendChild(txtNode);
    italic.appendChild(txtNodeTaxa);
    cellTaxa.appendChild(italic);
    row.appendChild(cell);
    row.appendChild(cellTaxa);
    nameTableBody.appendChild(row);
  }
}

//Additional function for the autocomplete
function setOffsets() {
  var end = inputField.offsetWidth;
  var left = calculateOffsetLeft(inputField);
  var top = calculateOffsetTop(inputField) + inputField.offsetHeight;  
  completeDiv.style.border = "black 1px solid";
  completeDiv.style.left = left + "px";
  completeDiv.style.top = top + "px";
  nameTable.style.width = 300 + "px";
}

//Additional function for the autocomplete
function calculateOffsetLeft(field) {
  return calculateOffset(field, "offsetLeft");
}

//Additional function for the autocomplete
function calculateOffsetTop(field) {
  return calculateOffset(field, "offsetTop");
}

//Additional function for the autocomplete
function calculateOffset(field, attr) {
  var offset = 0;
  while(field) {
    offset += field[attr];
    field = field.offsetParent;
  }
  return offset;
}

//Additional function for the autocomplete
function populateName(cell) {
  inputField.value = cell.firstChild.nodeValue;
  clearNames();
}

//Additional function for the autocomplete
function clearNames() {
  var ind = nameTableBody.childNodes.length;
  for (var i = ind - 1; i >= 0 ; i--) {
    nameTableBody.removeChild(nameTableBody.childNodes[i]);
  }
  completeDiv.style.border = "none";
}

//This function cycles up and down the taxonomic tree for the experts on the species page
function getExpertsTable(positionMovement) {
  var max = 5;
  var min = 0;
  if ((expertPosition + positionMovement <=5)&&(expertPosition + positionMovement >=0)) {
    expertPosition = expertPosition + positionMovement;
    createXMLHttpRequest();            
    var url = "ExpertSearch?taxanomicLevel=" + taxanomicArray[expertPosition]; 
    xmlHttp.open("GET", url, true);
    xmlHttp.onreadystatechange = populateExpertsTable;
    xmlHttp.send(null);
    //Update so the user knows what level of expert they are looking at
    
    document.getElementById("expertTaxaLevel").innerHTML = document.getElementById("taxaLookupList").value.split(";")[expertPosition];
  }
}

function populateExpertsTable() {
  
  if (xmlHttp.readyState == 4) {
    if (xmlHttp.status == 200) {
      document.getElementById("expertsTable").innerHTML = xmlHttp.responseText;
    }
  }
}

//This function intially sets the starting position of the experts in the tree
function setExpertsStartingPos(value) {
  expertPosition = value;
  taxanomicArray = document.getElementById("taxanomicArray").value.split(";");
}


function browseIn(obj) {
  if (obj.style.background != "#999999") {
    currentBackground = obj.getAttribute("Class");
    obj.style.background = "#FDFFD4";
    obj.style.cursor = "pointer";
  }
}

function browseOut(obj) {
  if (obj.style.background != "#999999") {
    obj.style.color = "";
    obj.style.background = "";
    obj.setAttribute("Class",currentBackground);
  }
}

function addToSearch(val,pos) {  
  browseColorOut(pos);
  browseCriteria[pos] = val;
  browseColorIn(pos);
}

function browseColorIn(pos) {
  browseIn(document.getElementById(browseCriteria[pos]));  
}


function browseColorOut(pos) {
  
  browseOut(document.getElementById(browseCriteria[pos]));
  
  
}

function regionShowDiv(divId) {
  if (divId == "marine") {
    document.getElementById("marine").style.visibility = "hidden";
    document.getElementById("terrestrial").style.visibility = "visible";
  } else {
    document.getElementById("marine").style.visibility = "hidden";
    document.getElementById("terrestrial").style.visibility = "visible";
  }
}
