ttlpts = 7;

var xtemp = 0;
var ytemp = 0;

// Function to create drop-down menus for selecting date and hour
function selectDateHour(x)
{
  var now = new Date();
  var year = now.getUTCFullYear();
  var m = now.getMonth();
  var d = now.getDate() - 1;
  var h = now.getHours();
  var ms = now.getTime();
  document.getElementById(x).innerHTML = 
    "Date: <select class='datecell' id='" + x + "_month" + "'><option value='01'>01</option><option value='02'>02</option><option value='03'>03</option><option value='04'>04</option><option value='05'>05</option><option value='06'>06</option><option value='07'>07</option><option value='08'>08</option><option value='09'>09</option><option value='10'>10</option><option value='11'>11</option><option value='12'>12</option></select>"
    + "<select class='datecell' id='" + x + "_day" + "'><option value='01'>01</option><option value='02'>02</option><option value='03'>03</option><option value='04'>04</option><option value='05'>05</option><option value='06'>06</option><option value='07'>07</option><option value='08'>08</option><option value='09'>09</option><option value='10'>10</option><option value='11'>11</option><option value='12'>12</option><option value='13'>13</option><option value='14'>14</option><option value='15'>15</option><option value='16'>16</option><option value='17'>17</option><option value='18'>18</option><option value='19'>19</option><option value='20'>20</option><option value='21'>21</option><option value='22'>22</option><option value='23'>23</option><option value='24'>24</option><option value='25'>25</option><option value='26'>26</option><option value='27'>27</option><option value='28'>28</option><option value='29'>29</option><option value='30'>30</option><option value='31'>31</option></select>"
    + "<select class='datecell' id='" + x + "_year" + "'><option value='" + (year - 1) + "'>" + (year - 1) + "</option><option value='" + year + "'>" + year + "</option><option value='" + (year + 1) + "'>" + (year + 1) + "</option></select>"
    + "&#160&#160 Time (military): "
    + "<select class='datecell' id='" + x + "_hour" + "'><option value='00'>00</option><option value='01'>01</option><option value='02'>02</option><option value='03'>03</option><option value='04'>04</option><option value='05'>05</option><option value='06'>06</option><option value='07'>07</option><option value='08'>08</option><option value='09'>09</option><option value='10'>10</option><option value='11'>11</option><option value='12'>12</option><option value='13'>13</option><option value='14'>14</option><option value='15'>15</option><option value='16'>16</option><option value='17'>17</option><option value='18'>18</option><option value='19'>19</option><option value='20'>20</option><option value='21'>21</option><option value='22'>22</option><option value='23'>23</option></select>"
    + "<input type='hidden' name='" + x + "_timestamp" + "' id='" + x + "_timestamp" + "'/>"
  document.getElementById(x + "_year").selectedIndex = 1;
  document.getElementById(x + "_month").selectedIndex = m;
  document.getElementById(x + "_day").selectedIndex = d;
  document.getElementById(x + "_hour").selectedIndex = h;
  document.getElementById(x + "_timestamp").value = ms;
}



// Function to set timestamp value, a hidden input
function setTimestamp(x)
{
  var y = document.getElementById(x + "_year").value;
  var m = document.getElementById(x + "_month").value;
  var d = document.getElementById(x + "_day").value;
  var h = document.getElementById(x + "_hour").value;
  var ms = Date.parse(m + "/" + d + "/" + y + " " + h + ":00");
  document.getElementById(x + "_timestamp").value = ms;
}



// Function to categorize risk based on interpolation of nomogram
function riskcat(HOL, bilival)
{
  var x = new Array(12,16,20,24,28,40,44,48,60,72,84,96,120,132,144,168);
  var y40 = new Array(3.9,4.2,4.7,5,5.6,7.8,8,8.5,9.6,11.1,11.6,12.4,13.2,13.2,13.2,13.2);
  var y75 = new Array(4.6,5.3,5.8,6.4,7,9.9,10.1,10.9,12.6,13.4,14.7,15.2,15.8,15.5,15.5,15.5);
  var y95 = new Array(6.6,6.5,7.4,7.8,8.9,12.1,12.5,13.1,15.1,16,16.6,17.4,17.6,17.4,17.4,17.4);
  if (HOL > x[15]) { HOL = x[15]; }
  for (var i=0; i<15; i++)
  {
    if (HOL >= x[i])
    {
      var cutoff95 = (y95[i+1] - y95[i]) / (x[i+1] - x[i]) * (HOL - x[i]) + y95[i];
      var cutoff75 = (y75[i+1] - y75[i]) / (x[i+1] - x[i]) * (HOL - x[i]) + y75[i];
      var cutoff40 = (y40[i+1] - y40[i]) / (x[i+1] - x[i]) * (HOL - x[i]) + y40[i];
    }
  }
  var riskcategory = new Array("low",0);
  if (bilival > cutoff95) { riskcategory[0] = "high"; riskcategory[1] = 3; }
  else if (bilival > cutoff75) { riskcategory[0] = "high intermediate"; riskcategory[1] = 2; }
  else if (bilival > cutoff40) { riskcategory[0] = "low intermediate"; riskcategory[1] = 1; }
  if (HOL < x[0]) { riskcategory[0] = "invalid"; riskcategory[1] = 4; }
  return riskcategory;
}



// Function that interpolates treatment cutoffs based on hour of life, bilirubin value and some risk factors
function PhotoTx(bili_HOL, bilival, risksum, premature)
{
  if (bili_HOL > 144) { bili_HOL = 144; }
  var lorisk_cutoff  = -0.00082 * bili_HOL * bili_HOL + 0.216 * bili_HOL + 6.8;
  var medrisk_cutoff = -0.00085 * bili_HOL * bili_HOL + 0.210 * bili_HOL + 5.0;
  var hirisk_cutoff  = -0.00083 * bili_HOL * bili_HOL + 0.193 * bili_HOL + 3.8;
  var phototherapy = false;
  var cutoff = lorisk_cutoff;
  if (premature && (risksum > 0)) { cutoff = hirisk_cutoff; }
  else if ((premature && (risksum == 0)) || ((premature != true) && (risksum > 0))) { cutoff = medrisk_cutoff; }
  if (bilival > cutoff) { phototherapy = true; }
  return phototherapy;
}



// Function that determines recommendations and associated references to AAP Guideline.
function recref(bili_HOL, bilival, jaundice, risksum, premature, photo, riskcategory, pts)
{
  var rrs = new Array();
  var photo_on = false;
  for (i=1; i<=pts; i++)
  {
    var rec = "Clinically assess for jaundice q8-12hrs.  Check Transcutaneous Bilirubin q24hrs.  ";
    var ref = new Array("2.2", "", "", "");
    var bilimax = bilival[0];
    var lastref = 0;
    for (j=0; j<=(i-1); j++) { if (bilival[j] >= bilimax) { bilimax = bilival[j]; } }

    if (photo[i-1] && !photo_on) { photo_on = true; rec = "Start phototherapy.  Check Total Serum Bilirubin in 4-6 hours.  Workup cause of hyperbilirubinemia, including Blood type & Coomb's test.  Keep infant in hospital.  "; ref[0] = "7.1"; ref[1] = "4.1"; lastref = 1; }
    else if ((photo[i-1] && photo_on) || (!photo[i-1] && photo_on && (bilival[i-1] >= (bilimax - 1)))) { rec = "Continue phototherapy.  Check Total Serum Bilirubin in 4-6 hours.  (Reference Lange's Neonatology in addition to AAP guideline)  Keep infant in hospital.  "; ref[0] = "A2a"; ref[1] = "4.1"; lastref = 1; }
    else if (!photo[i-1] && photo_on && (bilival[i-1] < (bilimax - 1))) { photo_on = false; rec = "Stop phototherapy.  Check Total Serum Bilirubin in 4-6 hours.  (Reference Lange's Neonatology in addition to AAP guideline)  Keep infant in hospital.  "; ref[0] = "A2b"; lastref = 0; }
    else if (jaundice[i-1] && (bili_HOL[i-1] < 24)) { rec = "Workup cause of jaundice, including Blood type & Coomb's test, check TcB now, and confirm with TSB.  Recheck TSB in 8hrs.  Keep infant in hospital.  "; ref[0] = "3.0"; ref[1] = "4.1"; lastref = 1; }
    else if (((i > 1) && (riskcategory[i-1][1] > riskcategory[i-2][1])) || ((i == 0) && (riskcategory[0][1] == 3))) { rec = "Workup cause of hyperbilirubinemia, including Blood type & Coomb's test, confirm TcB with TSB now.  Recheck TSB in 8hrs.  Keep infant in hospital.  "; ref[0] = "3.0"; ref[1] = "4.1"; lastref = 1; }
    else if ((bili_HOL[i-1] >= 24) && (riskcategory[i-1][1] < 3))
    {
      if (bili_HOL[i-1] <= 48) { rec = rec + "If considering discharge, follow-up before 4 days of life and again before 5 days of life.  ";  ref[lastref+1] = "5.1"; ref[lastref+2] = "6.1"; lastref = lastref + 2; }
      if (bili_HOL[i-1] > 48) { rec = rec + "If considering discharge, follow-up before 5 days of life.  ";  ref[lastref+1] = "5.1"; ref[lastref+2] = "6.1"; lastref = lastref + 2; }
    }
    else if ((bili_HOL[i-1] < 24) && (risksum == 0) && (riskcategory[i-1][1] < 3)) { rec = rec + "If considering discharge, follow-up before 3 days of life and again before 5 days of life.  ";  ref[lastref+1] = "5.1"; ref[lastref+2] = "6.1"; lastref = lastref + 2; }
    else { rec = rec + "Keep infant in hospital.  "; }
    if ((photo[i-1] || (jaundice[i-1] && (bili_HOL[i-1] < 24))) && ((risksum > 1) || (premature && (risksum > 0)))) { rec = rec + "Consider transfer to NICU.  "; }
    if (riskcategory[i-1][1] == 4) { rec = rec + "Hours of life must be greater than 12 to assess risk category.  "; }
    for (k=0; k<4; k++) { ref[k] = "<a href='AAP_Guideline.html#" + ref[k] + "' target='_blank'>" + ref[k] + "</a>" + "&#160"; }
    rrs[i-1] = new Array(rec,ref);
  }
  return rrs;
}



// Function to display coordinates of cursor
function show_coords(event)
{
  var G1o = document.getElementById("Graph1");

  var x1offset = document.getElementById("Graph1Box").offsetLeft + G1o.clientWidth * 0.113;
  var graph1width = 0.7705 * G1o.clientWidth;
  xtemp = Math.round((event.screenX - x1offset) * 168 / graph1width * 10) / 10;
  var y1offset = 0.014 * G1o.clientHeight + document.getElementById("Graph1Box").offsetTop - document.body.scrollTop + G1o.offsetTop;
  var graph1height = 0.649 * G1o.clientHeight;
  ytemp = Math.round((1 - (event.clientY - y1offset) / graph1height) * 25 * 10) / 10;

  if (xtemp < 0) { xtemp = 0; }
  if (xtemp > 168) { xtemp = 168; }
  if (ytemp < 0) { ytemp = 0; }
  if (ytemp > 25) { ytemp = 25; }
  var a = document.getElementById("DTOB_timestamp").value;
  var b = xtemp * 3600000;
  var d = new Date();
  d.setTime(a*1 + b*1);
  var m = d.getMinutes(); if (m < 10) { m = "0" + m; }
  xd = (d.getMonth() + 1) + "/" + d.getDate() + "/" + d.getYear() + "  " + d.getHours() + ":" + m;

  document.getElementById("coordinates").style.left = event.clientX - 50 + "px";
  document.getElementById("coordinates").style.top = document.body.scrollTop + event.clientY - 50 + "px";
  document.getElementById("coordinates").style.fontWeight = "900";
  document.getElementById("coordinates").style.color = "red";
  document.getElementById("coordinates").style.background = "black";
  if ((xtemp > 0) && (xtemp < 168) && (ytemp > 0) && (ytemp < 25)) document.getElementById("coordinates").innerHTML = xtemp + "hrs, (" + xd + "), " + ytemp + "mg/dL";
  else document.getElementById("coordinates").innerHTML = "";
}



// Function plots one point sent to it on both graphs
function plotone(x, y, i, what)
{
  if ((what = "plot") && (x != 0) && (y != 0))
  {
   var G1o = document.getElementById("Graph1");

   var x1offset = document.getElementById("Graph1Box").offsetLeft + G1o.clientWidth * 0.113;
   var graph1width = 0.7705 * G1o.clientWidth;
   var y1offset = 0.014 * G1o.clientHeight + document.getElementById("Graph1Box").offsetTop + G1o.offsetTop;
   var graph1height = 0.649 * G1o.clientHeight;
   var xg1 = Math.floor(x / 168 * graph1width + x1offset);
   var yg1 = Math.floor((1 - y / 25) * graph1height + y1offset);

   document.getElementById("graph1pointsL" + i).innerHTML = "I";
   document.getElementById("graph1pointsL" + i).style.fontSize = "56";
   document.getElementById("graph1pointsL" + i).style.fontWeight = "normal";
   document.getElementById("graph1pointsL" + i).style.position = "absolute";
   document.getElementById("graph1pointsL" + i).style.display = "inline";
   document.getElementById("graph1pointsL" + i).style.top = (yg1 - 33) + "px";
   document.getElementById("graph1pointsL" + i).style.left = (xg1  - 11) + "px";
   document.getElementById("graph1pointsL" + i).style.color = "red";
   document.getElementById("graph1pointsC" + i).innerHTML = "--";
   document.getElementById("graph1pointsC" + i).style.fontSize = "32";
   document.getElementById("graph1pointsC" + i).style.fontWeight = "900";
   document.getElementById("graph1pointsC" + i).style.position = "absolute";
   document.getElementById("graph1pointsC" + i).style.display = "inline";
   document.getElementById("graph1pointsC" + i).style.top = (yg1 - 23) + "px";
   document.getElementById("graph1pointsC" + i).style.left = (xg1  - 12) + "px";
   document.getElementById("graph1pointsC" + i).style.color = "red";

   var G2o = document.getElementById("Graph2");
   var x2offset = document.getElementById("Graph2Box").offsetLeft + G2o.clientWidth * 0.0812;
   var graph2width = 0.902 * G2o.clientWidth;
   var y2offset = 0.012 * G2o.clientHeight + G2o.offsetTop;
   var graph2height = 0.885 * G2o.clientHeight;
   var xg2 = Math.floor(x / 168 * graph2width + x2offset);
   var yg2 = Math.floor((1 - y / 25) * graph2height + y2offset);

   document.getElementById("graph2pointsL" + i).innerHTML = "I";
   document.getElementById("graph2pointsL" + i).style.fontSize = "56";
   document.getElementById("graph2pointsL" + i).style.fontWeight = "normal";
   document.getElementById("graph2pointsL" + i).style.position = "absolute";
   document.getElementById("graph2pointsL" + i).style.display = "inline";
   document.getElementById("graph2pointsL" + i).style.top = (yg2 - 33) + "px";
   document.getElementById("graph2pointsL" + i).style.left = (xg2  - 11) + "px";
   document.getElementById("graph2pointsL" + i).style.color = "blue";
   document.getElementById("graph2pointsC" + i).innerHTML = "--";
   document.getElementById("graph2pointsC" + i).style.fontSize = "32";
   document.getElementById("graph2pointsC" + i).style.fontWeight = "900";
   document.getElementById("graph2pointsC" + i).style.position = "absolute";
   document.getElementById("graph2pointsC" + i).style.display = "inline";
   document.getElementById("graph2pointsC" + i).style.top = (yg2 - 23) + "px";
   document.getElementById("graph2pointsC" + i).style.left = (xg2  - 12) + "px";
   document.getElementById("graph2pointsC" + i).style.color = "blue";
  }
  else
  {
   document.getElementById("graph1pointsL" + i).style.display = "none";
   document.getElementById("graph1pointsC" + i).style.display = "none";
   document.getElementById("graph2pointsL" + i).style.display = "none";
   document.getElementById("graph2pointsC" + i).style.display = "none";
  }
}



// Function that calls all procedures and does everything.
function plotstuff(event, num)
{
  // Delete or add data to table (all hours of life, bilirubin values, and jaundice stored in DOM)
  if (num != "")    // Delete selected data from DOM table
  {
    document.getElementById("H" + num).innerHTML = "";
    document.getElementById("B" + num).innerHTML = "";
    document.getElementById("J" + num).checked = false;
  }
  else if (event != "")     // Add data to DOM table if blank row available
  {
    var blankrow = false;
    var i = 1;
    while (!blankrow && (i <= ttlpts))
    {
      if (document.getElementById("H" + i).innerHTML == "") { blankrow = true; }
      else { i++ }
    }

    if (blankrow)
    {
      document.getElementById("H" + i).innerHTML = xtemp;
      document.getElementById("B" + i).innerHTML = ytemp;
    }
  }

  // Calculate and set timestamp of Date and Time of Birth
  setTimestamp("DTOB");

  // Accumulate risks
  var risksum = 0;
  if ( document.getElementById("other").checked == true) { risksum++; }
  if ( document.getElementById("isoimmune").checked == true) { risksum++; }
  if ( document.getElementById("G6PD").checked == true) { risksum++; }
  if ( document.getElementById("asphyxia").checked == true) { risksum++; }
  if ( document.getElementById("lethargy").checked == true) { risksum++; }
  if ( document.getElementById("temperature").checked == true) { risksum++; }
  if ( document.getElementById("sepsis").checked == true) { risksum++; }
  if ( document.getElementById("acidosis").checked == true) { risksum++; }
  if ( document.getElementById("albumin").checked == true) { risksum++; }
  var premature = document.getElementById("premature").checked;

  // Assign data from DOM table to array
  var xd = new Array();
  var yd = new Array();
  var jd = new Array();
  var pts = 0;

  for (i=1; i<=ttlpts; i++)
  {
    var xt = document.getElementById("H" + i).innerHTML;
    var yt = document.getElementById("B" + i).innerHTML;
    var jt = document.getElementById("J" + i).checked;
    if (xt != "")
    {
      pts++;
      xd[pts-1] = xt * 1;
      yd[pts-1] = yt * 1;
      jd[pts-1] = jt * 1;
    }
  }

  // Make sure remaining rows in array are blank
  for (i=pts; i<=ttlpts; i++) { xd[i] = ""; yd[i] = ""; jd[i] = ""; }

  // Sorting Algorithm
  var sorted = false;
  while (!sorted)
  {
    sorted = true;
    for (i=1; i<=(pts-1); i++)
    {
      var a = xd[i-1]; var b = xd[i];
      if (a > b)
      {
        xd[i-1] = b*1;
        xd[i] = a*1;
        a = yd[i-1]; b = yd[i];
        yd[i-1] = b*1;
        yd[i] = a*1;
        a = jd[i-1]; b = jd[i];
        jd[i-1] = b*1;
        jd[i] = a*1;
        sorted = false;
      }
    }
  }

  // interpolate graphs, (risk category & phototherapy), and calculate recommendations, assign references
  var riskcategories = new Array();
  var photo = new Array();
  var recsnrefs = new Array();
  for (i=1; i<=pts; i++)
  {
    riskcategories[i-1] = riskcat(xd[i-1], yd[i-1]);                             // Categorize risk based on interpolation of nomogram
    photo[i-1] = PhotoTx(xd[i-1], yd[i-1], risksum, premature);                 // Determine indication for phototherapy by interpolating graph using treatment cutoffs based on hour of life, bilirubin value and risk factors
  }
  recsnrefs = recref(xd, yd, jd, risksum, premature, photo, riskcategories, pts);  // Determine recommendations and associated references to AAP Guideline.

  // Plot each point, transfer data from arrays to table
  var a = document.getElementById("DTOB_timestamp").value;
  var d = new Date();
  for (i=1; i<=ttlpts; i++)
  {
    document.getElementById("H" + i).innerHTML = xd[i-1];
    document.getElementById("B" + i).innerHTML = yd[i-1];
    document.getElementById("D" + i).innerHTML = "";
    document.getElementById("K" + i).innerHTML = "";
    document.getElementById("P" + i).innerHTML = "";
    document.getElementById("C" + i).innerHTML = "";
    document.getElementById("F" + i).innerHTML = "";
    document.getElementById("J" + i).checked = false;
    if (i<=pts)
    {
      plotone(xd[i-1], yd[i-1], i-1, 'plot');

      var b = document.getElementById("H" + i).innerHTML * 3600000;
      d.setTime(a*1 + b*1);
      var m = d.getMinutes(); if (m < 10) { m = "0" + m; }
      document.getElementById("D" + i).innerHTML = (d.getMonth() + 1) + "/" + d.getDate() + "/" + d.getYear() + "  " + d.getHours() + ":" + m;

      if (photo[i-1]) { document.getElementById('P' + i).innerHTML = "yes"; }
      else            { document.getElementById('P' + i).innerHTML = "no"; }

      document.getElementById("K" + i).innerHTML = riskcategories[i-1][0];
      document.getElementById("J" + i).checked = (jd[i-1] == 1);
      document.getElementById("C" + i).innerHTML = recsnrefs[i-1][0];
      document.getElementById("F" + i).innerHTML = recsnrefs[i-1][1];
    }
    else plotone(xd[i-1], yd[i-1], i-1, 'erase');
  }
}



// Opens new window from which the data and graphs can be printed.  
function PrintWin()
{
 var pwin = window.open("","","height=500,width=500,menubar=1,resizable=1");
 var stuff = "<html><head><link rel='stylesheet' type='text/css' href='bilirubin2.css' /></head><body>";
 stuff = stuff + "<h1>Neonatal Hyperbilirubinemia Tool</h1> <h2>Graphs</h2> ";
 stuff = stuff + "<img src='Bhutani_PhotoTx_graph.gif' class='PGraph' alt='Phototherapy Treatment Decision Graph' /><div id='Graph1Pts'></div>";
 stuff = stuff + "<img src='Bhutani_Risk_graph.gif' class='PGraph' alt='Risk Category Nomogram' /> <br> ";
 stuff = stuff + "Birth date: &#160 &#160 Birth time: <br> ";
 stuff = stuff + "Risk Factors: <br> ";
 stuff = stuff + "<h2>Summary Table of Data and Recommendations</h2> ";
 stuff = stuff + "</body></html>";

 pwin.document.write(stuff);
 pwin.focus();
}
