// $Id: speciesList.js,v 1.3 2008/12/08 22:59:37 ccusack Exp $
//

// holds an instance of XMLHttpRequest
var xmlHttp = createXmlHttpRequestObject();
// holds the remote server address 
//var serverAddress = "aj01.php";
// when set to true, display detailed error messages
var showErrors = true;
// initialize the validation requests cache 
var cache = new Array();
var handle = '';	//stores the ItemRef currently being used
var serverAddress = "speciesListSrv.php";
var sendTimer = 1000;	//1000 = 1 sec
var updateOnTimer = 0;

function test() {
alert('test triggered');
}

function expand(itemRef) {
	handle = itemRef;
	// Change from expand to retract
	boxId=document.getElementById(itemRef+'2');
	boxId.setAttribute('src','../images/close_box.gif');
	//boxId.setAttribute('onClick','retract("' + itemRef + '")');
	//need this for IE
	boxId.onclick = function() { var temp = new Function("retract('"+itemRef+"')"); temp(); }
	callServer();
}

function retract(itemRef) {
	// Change from expand to expand
	boxId=document.getElementById(itemRef+'2');
	boxId.setAttribute('src','../images/open_box.gif');
	//boxId.setAttribute('onClick','expand("' + itemRef + '")');
	//need this for IE
	boxId.onclick = function() { var temp = new Function("expand('"+itemRef+"')"); temp(); }
	divID = document.getElementById(itemRef);
	divID.innerHTML='';
}

// creates an XMLHttpRequest instance
function createXmlHttpRequestObject() 
{
  // will store the reference to the XMLHttpRequest object
  var xmlHttp;
  // this should work for all browsers except IE6 and older
  try
  {
    // try to create XMLHttpRequest object
    xmlHttp = new XMLHttpRequest();
  }
  catch(e)
  {
    // assume IE6 or older
    var XmlHttpVersions = new Array("MSXML2.XMLHTTP.7.0",
									"MSXML2.XMLHTTP.6.0",
                                    "MSXML2.XMLHTTP.5.0",
                                    "MSXML2.XMLHTTP.4.0",
                                    "MSXML2.XMLHTTP.3.0",
                                    "MSXML2.XMLHTTP",
                                    "Microsoft.XMLHTTP");
    // try every id until one works
    for (var i=0; i<XmlHttpVersions.length && !xmlHttp; i++) 
    {
      try 
      { 
        // try to create XMLHttpRequest object
        xmlHttp = new ActiveXObject(XmlHttpVersions[i]);
      } 
      catch (e) {} // ignore potential error
    }
  }
  // return the created object or display an error message
  if (!xmlHttp)
    displayError("Error creating the XMLHttpRequest object.");
  else 
    return xmlHttp;
}

// function that displays an error message
function displayError($message)
{
  // ignore errors if showErrors is false
  if (showErrors)
  {
    // turn error displaying Off
    showErrors = false;
    // display error message
     alert("Error encountered: \n" + $message);
    // retry validation after 10 seconds
    setTimeout("callServer();", 20000);
  }
}

// the function handles the validation for any form field
function callServer()
{
  // only continue if xmlHttp isn't void
  //var ztoday = new Date();
		inputValue = handle;
		fieldID = 'xxx';
		//alert(handle);
		
  if (xmlHttp)
  {
    // if we received non-null parameters, we add them to cache in the
    // form of the query string to be sent to the server for validation
    if (fieldID)
    {
      // encode values for safely adding them to an HTTP request query string

      inputValue = encodeURIComponent(inputValue);
      fieldID = encodeURIComponent(fieldID);
      
	  // add the values to the queue
      //cache.push("inputValue=" + inputValue + "&fieldID=" + fieldID);
	  cache.push("inputValue=" + inputValue + "&fieldID=" + fieldID);
	  //alert('inputValue: ' + inputValue);
    }
    // try to connect to the server
    try
    {
      // continue only if the XMLHttpRequest object isn't busy
      // and the cache is not empty
      if ((xmlHttp.readyState == 4 || xmlHttp.readyState == 0) 
         && cache.length > 0)
      {
        // get a new set of parameters from the cache
        var cacheEntry = cache.shift();
        // make a server request to callServer the extracted data
		
        xmlHttp.open("POST", serverAddress, true);
        xmlHttp.setRequestHeader("Content-Type", 
                                 "application/x-www-form-urlencoded");
        xmlHttp.onreadystatechange = handleRequestStateChange;
        xmlHttp.send(cacheEntry);
      }
    }
    catch (e)
    {
      // display an error when failing to connect to the server
      
	  displayError(e.toString()+'(1)');
    }
  }
}

// function that handles the HTTP response
function handleRequestStateChange() 
{
  // when readyState is 4, we read the server response
  if (xmlHttp.readyState == 4) 
  {
    // continue only if HTTP status is "OK"
    if (xmlHttp.status == 200) 
    {
      try
      {
        // read the response from the server
        readResponse();
      }
      catch(e)
       {
        // display error message
        displayError(e.toString()+'(2)');
      }
    }
    else
    {
      // display error message
      displayError(xmlHttp.statusText+'(3)');
    }
  }
}

// read server's response 


// sets focus on the first field of the form
function setFocus()    
{
  //document.getElementById("txtUsername").focus();
}

function readResponse()
{
  // retrieve the server's response 
  var response = xmlHttp.responseText;
  
  // server error?
  if (response.indexOf("ERRNO") >= 0 
      || response.indexOf("error:") >= 0
      || response.length == 0)
    throw(response.length == 0 ? "Server error." : response);
  // get response in XML format (assume the response is valid XML)
	responseXml = xmlHttp.responseXML;
  	
	xmlDoc = responseXml.documentElement;
	itemRef = xmlDoc.getElementsByTagName("itemRef")[0].firstChild.data;
	
	PoleOD = xmlDoc.getElementsByTagName("PoleOD")[0].firstChild.data;
	
		if (PoleOD=='ERR') { PoleOD='Unknown'}
	Origin = xmlDoc.getElementsByTagName("Origin")[0].firstChild.data;
		if (Origin=='ERR') { Origin='Unknown'}
	//alert('debug1');
	//Desc ='aaa';
	Desc = xmlDoc.getElementsByTagName("Desc")[0].firstChild.data;
	//alert('debug2');
	IconFileName = xmlDoc.getElementsByTagName("IconFileName")[0].firstChild.data;
	
	divID = document.getElementById(itemRef);
	
	//divID.innerHTML='<img class="icon" src="../images/icon/'+IconFileName+'" height="50" width="50" hspace="10" />'
	divID.innerHTML='<img class="icon" src="../images/icon/'+IconFileName+'" hspace="10" />';
	if (IconFileName!='ERR') {
		divID.innerHTML='<img class="icon" src="../images/icon/'+IconFileName+'" hspace="10" />';
	} else {
		divID.innerHTML='';
	}
	divID.innerHTML=divID.innerHTML
	+ 'Max. pole diameter [mm]: '+PoleOD
	+'<br />'
	+'Origin: '+Origin
	+'<br />'
	+Desc
	//+'<br /><a href="./species_datasheet.php?species=' 
	//+ itemRef + '" target="_blank" title="Click here to view data sheet and photos"><b>Click here to view datasheet and photos</b></a>';

  // call callServer() again, in case there are values left in the cache
  //setTimeout("callServer();", 500);
  if (updateOnTimer==1) {
		setTimeout("callServer();", sendTimer);
	}
}