var httpRequest = getHTTPObject();
//var httpRequest = new XMLHttpRequest();
var url = "/cgi-bin/get_contigs_json.pl"; // This URL should give us JSON data. 
var ctgData = new Object;

// work in both IE and firebox 
// stolen from 
// http://developer.apple.com/internet/webcontent/xmlhttpreq.html
function getHTTPObject() {
  var req = false;
  // branch for native XMLHttpRequest object
  if(window.XMLHttpRequest) {
    try {
      req = new XMLHttpRequest();
    } catch(e) {
      req = false;
    }
  // branch for IE/Windows ActiveX version
  } else if(window.ActiveXObject) {
    try {
      req = new ActiveXObject("Msxml2.XMLHTTP");
    } catch(e) {
      try {
        req = new ActiveXObject("Microsoft.XMLHTTP");
      } catch(e) {
        req = false;
      }
    }
  }
  return req;
}


function getJson() { 
  // Download the JSON data from the server.
 httpRequest.onreadystatechange = parseContigs;
  httpRequest.open("GET", url, true);
  httpRequest.send(null);
}

function sortObject(o) {
    var sorted = {},
    key, a = [];

    for (key in o) {
        if (o.hasOwnProperty(key)) {
                a.push(key);
        }
    }

    a.sort();

    for (key = 0; key < a.length; key++) {
        sorted[a[key]] = o[a[key]];
    }
    return sorted;
}


function parseContigs() {
  if (httpRequest.readyState == 4) {
    if (httpRequest.status == 200) {
      var jsonData = httpRequest.responseText; 
      eval("ctgData = ("+jsonData+")");

      /* For some reason, the sorted organism list gets jumbled */
      /* Hack to work around */
      var sortedData = sortObject( ctgData );

      var i = 0;
      /* one field on each of two forms needs setting */
      document.genomic.species[ i ] = new Option( "Choose species:" );
      document.cluster.org[ i ] = new Option( "Choose species:" );
	i++;
      for( org in sortedData ) {
	document.genomic.species[ i ] = new Option( sortedData[org]['desc'], org );
	document.cluster.org[ i ] = new Option( sortedData[org]['desc'], org );
	i++
      }
    } else {
      alert('There was a problem with the URL.');
    }
    httpRequest = null;
  }
}

function populateChromo( org ) {
  var i = 0;
  document.genomic.chromosome.options.length = i;
//  document.genomic.chromosome[ i++ ] = new Option( "Chr:" );
  for ( chromo in ctgData[org]['chr'] ) {
    document.genomic.chromosome[ i++ ] = new Option( ctgData[org]['chr'][chromo] );
  }
}


