ttlpts = 6;
xleft1 = 64;
ybottom1 = 350;
xfactor1 = 7*24/347;
yfactor1 = 25/193;

// 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 = 
    "<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&#160&#160Time (hour): "
    + "<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 show_coords(event)
{
  x = event.screenX;
  y = event.screenY;

  xt = Math.floor((x - xleft1) * xfactor1 * 10 + .5) / 10;
  yt = Math.floor((- y + ybottom1) * yfactor1 * 10 + .5) / 10;

  if (xt < 0) { xt = 0; }
  if (xt > 168) { xt = 168; }
  if (yt < 0) { yt = 0; }
  if (yt > 25) { yt = 25; }
  var a = document.getElementById("DTOB_timestamp").value;
  var b = xt * 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;

  with (document.coordinatesform)
  {
    xcoordinate.innerHTML = xt;
    xcoordinatedate.innerHTML = xd;
    ycoordinate.innerHTML = yt;
  }
}

// Function plots one point sent to it 
function plotone(x, y)
{
  xleftmargin1 = 16;
  xright1 = 411;
  ylow1 = 459;
  ytop1 = 157;

  xleft2 = 35;
  ybottom2 = -36;
  xfactor2 = 168/406;
  yfactor2 = -25/266;

  xg1 = x / xfactor1 + xleft1 - xleftmargin1;
  yg1 = - (y / yfactor1 - ybottom1) - ylow1;

  xg2 = x / xfactor2 + xleft2;
  yg2 = y / yfactor2 + ybottom2;

  var jg = new jsGraphics("graph1");
  jg.setColor("red");
  jg.setStroke(3);
  jg.fillRect(xg1 - 3, yg1 - 3, 7, 7);
  jg.drawLine(xg1 - 1 , yg1 - 12, xg1 - 1, yg1 + 12);
  jg.paint();

  jg = new jsGraphics("graph2");
  jg.setColor("blue");
  jg.setStroke(3);
  jg.fillRect(xg2 - 3, yg2, 7, 7);
  jg.drawLine(xg2 - 1, yg2 - 11, xg2 - 1, yg2 + 13);
  jg.paint();
}

// 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)
    {
      var x = event.screenX;
      var y = event.screenY;

      var xt = Math.floor((x - xleft1) * xfactor1 * 10 + .5) / 10;
      var yt = Math.floor((- y + ybottom1) * yfactor1 * 10 + .5) / 10;

      if (xt < 0) { xt = 0; }
      if (xt > 168) { xt = 168; }
      if (yt < 0) { yt = 0; }
      if (yt > 25) { yt = 25; }

      document.getElementById("H" + i).innerHTML = xt;
      document.getElementById("B" + i).innerHTML = yt;
    }
  }

  // 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
  document.getElementById("graph1").innerHTML = "";  // clear graphs
  document.getElementById("graph2").innerHTML = "";
  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]);

      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];
    }
  }
}