// alert("Loading display.js 4");

if (typeof Node == "undefined") {
  var Node = {
    TEXT_NODE: 3
  }
}

// define XMLHttpRequest() if using IE

function myXMLHttpRequest() {
  if (typeof XMLHttpRequest == "undefined" && window.ActiveXObject) {
    var arrSignatures = ["MSXML2.XMLHTTP.5.0", "MSXML2.XMLHTTP.4.0",
			 "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP",
			 "Microsoft.XMLHTTP"];
    // look for most recent version that works
    for (var i=0; i < arrSignatures.length; i++) {
      try {
	var oRequest = new ActiveXObject(arrSignatures[i]);
	return oRequest;
      } catch (oError) {
	// ignore error
      }
    }          
    throw new Error("MSXML is not installed on your system.");               
  } else {			// not IE
    return new XMLHttpRequest();
  }
}

function findcite(cites, id) {
  for (var i=0; i<cites.length; i++)
    if (cites[i].getAttribute("id") == id)
      return cites[i];
  return;
}

function extract(n, name) {
  var a = n.getElementsByTagName(name);
  if (a[0].firstChild) 
    return a[0].firstChild.nodeValue;
  else
    return '';
}

function span(n, classname, tagname) {
  // should htmlentities encode the result of extract, in case e.g. title
  // has < char in it.
  return '<span class="'+classname+'">'+extract(n, tagname)+'</span>';
}

// need 'newwindow' because if user goes to link on this page, then goes back,
// it wipes out DOM state (expanded, collapsed nodes) and gets a vanilla copy.
// Ack.

function pubmed_abs_link (id) {
  return '<A HREF="http://www.ncbi.nlm.nih.gov/entrez/query.fcgi?cmd=Retrieve&db=PubMed&list_uids=' + id + '&dopt=Abstract" target="newwindow">[PubMed abstract]</A>';
}

function pubmed_linkout_link (id) {
  return '<A HREF="http://www.ncbi.nlm.nih.gov/entrez/query.fcgi?cmd=Retrieve&db=PubMed&list_uids=' + id + '&dopt=ExternalLink" target="newwindow">[Full-text links]</A>';
}

// return closure as event handler (to make thread safe)

function response_handler (request, ids, tofix) {
  function prettify () {
    if (request.readyState == 4) {
      if (request.status == 200) { // OK
	var cites = request.responseXML.getElementsByTagName("citation");
	if (cites.length == 0)
	  alert("no cites: "+request.myurl + "\n"+request.responseText);
	for (var i=0; i<ids.length; i++) {
	  var child = tofix[i];
	  var cite  = findcite(cites, ids[i]);
	  // convert XML citation info to XHTML
	  child.innerHTML =
	    '<span class="bibinfo">' +
	    span(cite, 'articletitle', 'title') + ' ' +
	    span(cite, 'journal', 'journal') + ' ' +
	    span(cite, 'volume', 'volume') + ":" +
	    span(cite, 'pages', 'pages') + ' ' + 
	    span(cite, 'year',  'year') + ".\n" +
	    pubmed_abs_link(ids[i]) + ' ' +
	    pubmed_linkout_link(ids[i]) +
	    comment_link(find_hash(child)) +
	    "</span>\n";
	  child.setAttribute('filledin', 'true');
	}
      } else
	alert("There was a problem retrieving the XML data:\n" + request.statusText + request.myurl);
    }
  }
  return prettify;
}

function comment_link (hash) {
  if (!hash)
    return '';
  var ret = '&nbsp;<span class="introlink"><a href="intro_content.php?hash=';
  ret += hash + '" target="newwindow">(comments)</a></span>\n';
  return ret;
}

function getTextValue(n) {
  for (var i=0; i<n.childNodes.length; i++) {
    var child = n.childNodes[i];
    if (child.nodeType == Node.TEXT_NODE) {	// text node
      return child.nodeValue;
    }
  }
  return '';
}

function find_hash(n) {
  var hash = '';
  for (var j=0; j<n.childNodes.length; j++)
    if (n.childNodes[j].tagName == 'SPAN' &&
	n.childNodes[j].className == 'intro')
      hash = getTextValue(n.childNodes[j]);
  return hash;
}

function fixup_articles(n) {
  var ids = [];
  var tofix = [];
  for (var i=0; i<n.childNodes.length; i++) {
    var child =  n.childNodes[i];
    if (child.tagName == 'LI' && child.className == 'article' &&
	child.getAttribute('filledin') != 'true') {
      for (var j=0; j<child.childNodes.length; j++) {
	if (child.childNodes[j].tagName == 'SPAN' &&
	    child.childNodes[j].className == 'pmid') {
	  var id = getTextValue(child.childNodes[j]);
	  ids.push(id);
	  tofix.push(child);
	}
      }
    }
  }
  getinfo(ids, tofix)
}

function getinfo (ids, tofix) {
  if (ids.length > 0) {		// at least 1 child needs bibinfo added
    var url = base_url + '/pubmed_xml.php?ids='+ids.join(',')+'&confusecache='+Math.random();
    var r = myXMLHttpRequest();
    r.onreadystatechange = response_handler(r, ids, tofix);
    r.open("GET", url, true);	// async: info added when request completes
    r.send(null);
  }
}

var opposite_color = new Array();
opposite_color['blue'] = 'red';
opposite_color['red'] = 'blue';

function toggle_field(n) {
  n.style.color = opposite_color[n.style.color]; // flip color
  // n is <span class="fieldname"> node.  Find the <ul> sibling
  var pnode = n.parentNode;	// <li> node
  for (var i=0; i<pnode.childNodes.length; i++) {
    var child = pnode.childNodes[i];
    if (child.tagName == 'UL') {
      // exposed items of this field, so may need to fill in bibinfos
      if (child.style.display == 'none') {
	child.style.display = 'block';
	fixup_articles(child);	// fill in bibinfos if needed
      } else
	child.style.display = 'none';
    }
  }
}

function toggle_display(n, evt) {
  evt.cancelBubble = true;	// works on IE and Mozilla
  //  alert(evt.type);
  toggle_field (n);
}

function setup() {
 
}

// expand "Search results" field automatically

function setup_search() {
  n = document.getElementById('expandthis');
  if (n) 
    toggle_field(n);
  else
    alert ("could not find field to expand");
}
