// 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 (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;
  document.getElementById(x + "_timestamp").value = Date.parse(m + "/" + d + "/" + y + " " + h + ":00");
}

// 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)
{
  var rrs = new Array(5);
  var photo_on = false;
  for (var i=1; i<6; i++)
  {
    var rec = "Clinically assess for jaundice q8-12hrs.  Check Transcutaneous Bilirubin q24hrs.  ";
    var ref = new Array("2.2", "", "", "");
    if (bili_HOL[i] <= bili_HOL[i-1])
    {
      rec = "Data must be in chronological order.  ";
      ref[0] = "";
    }
    else
    {
      var bilimax = bilival[1];
      var lastref = 0;
      for (var j=1; j<(i+1); j++)
      {
        if (bilival[j] >= bilimax) { bilimax = bilival[j]; }
      }
      if (photo[i] && !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] && photo_on) || (!photo[i] && photo_on && (bilival[i] >= (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] && photo_on && (bilival[i] < (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] && (bili_HOL[i] < 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] > riskcategory[i-1][1])) || ((i == 1) && (riskcategory[i][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] >= 24) && (riskcategory[i][1] < 3))
      {
        if (bili_HOL[i] <= 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] > 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] < 24) && (risksum == 0) && (riskcategory[i][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] || (jaundice[i] && (bili_HOL[i] < 24))) && ((risksum > 1) || (premature && (risksum > 0)))) { rec = rec + "Consider transfer to NICU.  "; }
      if (riskcategory[i][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] = new Array(rec,ref);
  }
  return rrs;
}

// Function called on loading of bili page to call functions that make drop-down menus
function page_setup_scripts()
{
  selectDateHour("DTOB");
  for (i=1; i<6; i++) { selectDateHour("DTB" + i); }
}

// Function to bring up printable window with table and graphics
function printable()
{
  printablepage = window.open('');
  printablepage.document.write("<img src='Bhutani_PhotoTx_graph.gif'/>");
}

// Function to perform all calculations and display results (the "guts")
function DoCalcs()    
{
  // Calculate and set timestamps to selected dates and hours for birthtime and each bilirubin measurement
  setTimestamp("DTOB");
  for (i=1; i<6; i++) { setTimestamp("DTB" + i); }

  // Calculate and display hours of life in results table
    // Calc hours of life since birth
  var now = new Date();
  var TOB = document.getElementById("DTOB_timestamp").value;                         // Timestamp of Birth
  var HOL = Math.round((now.getTime() - TOB)/3600000);                               // Hour of Life now
  document.getElementById("HOL").innerHTML = HOL;

    // Calculate and display hours of life for bilirubin measurements in results table
  var TO_Bilival = new Array(5);                                                     // Array of Timestamps of bilirubin measurements
  var HOL_Bilival = new Array(5);                                                    // Array of Hours of life of bilirubin measurements
  for (i=1; i<6; i++)
  {
    TO_Bilival[i] = document.getElementById("DTB" + i + "_timestamp").value;
    HOL_Bilival[i] = Math.round((TO_Bilival[i] - TOB)/3600000);
    if (document.getElementById("VB" + i).value != "") { document.getElementById("HOLB" + i).innerHTML = HOL_Bilival[i]; } else { document.getElementById("HOLB" + i).innerHTML = ""; }
  }

  // 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;

  // Copy bilirubin values to results table and make array of bilirubin values
  var bilival = new Array(5);
  for (i=1; i<6; i++)
  {
    bilival[i] = document.getElementById("VB" + i).value;
    document.getElementById("VBR" + i).innerHTML = bilival[i];
  }

  // Categorize risk based on interpolation of nomogram
  var riskcategories = new Array(5);
  for (i=1; i<6; i++)
  {
    riskcategories[i] = riskcat(HOL_Bilival[i], bilival[i]);
    if (bilival[i] == 0)
    {
      riskcategories[i][0] = "";
      riskcategories[i][1] = "";
    }
    document.getElementById('RC' + i).innerHTML = riskcategories[i][0];
  }

  // Determine indication for phototherapy by interpolating graph using treatment cutoffs based on hour of life, bilirubin value and risk factors
  var photo = new Array(5);
  for (i=1; i<6; i++)
  {
    photo[i] = PhotoTx(HOL_Bilival[i], bilival[i], risksum, premature);
    if (bilival[i] != 0)
    {
      if (photo[i]) { document.getElementById('P' + i).innerHTML = "yes"; }
      else          { document.getElementById('P' + i).innerHTML = "no"; }
    }
    else if (bilival[i] == 0) { document.getElementById('P' + i).innerHTML = ""; }
  }

  // Copy jaundice presence data to results table and make array of jaundice presence data
  var jaundice = new Array(5);
  for (i=1; i<6; i++)
  {
    jaundice[i] = document.getElementById("J" + i).checked;
    if (document.getElementById("VB" + i).value != "")
    {
      if (jaundice[i]) { document.getElementById("JR" + i).innerHTML = "yes"; }
      else { document.getElementById("JR" + i).innerHTML = "no"; }
    }
    else { document.getElementById("JR" + i).innerHTML = ""; }
  }

  // Determine recommendations and associated references to AAP Guideline.
  var recsnrefs = new Array(5);
  recsnrefs = recref(HOL_Bilival, bilival, jaundice, risksum, premature, photo, riskcategories);
  for (i=1; i<6; i++)
  {
    if (bilival[i] == 0)
    {
      recsnrefs[i][0] = "";
      recsnrefs[i][1] = "";
    }
    document.getElementById('RE' + i).innerHTML = recsnrefs[i][0];
    document.getElementById('AAP' + i).innerHTML = recsnrefs[i][1];
  }

  // Plot points on graphs
  document.getElementById("graph1").innerHTML = "";
  var jg = new jsGraphics("graph1");
  jg.setColor("red");
  jg.setStroke(3);
  var xoffset = 47;
  var yoffset = -107;
  var xfactor = 2.07;
  var yfactor = 7.85;
  for (i=1; i<6; i++) 
  {
    if (bilival[i] != 0) 
    {
      if (HOL_Bilival[i] > 168) { HOL_Bilival[i] = 168; }
      var x1 = Math.floor(HOL_Bilival[i] * xfactor) + xoffset;
      var y1 = - Math.floor(bilival[i] * yfactor) + yoffset;
      jg.fillRect(x1, y1, 5, 5);
      jg.drawLine(x1 + 1, y1 - 12, x1 + 1, y1 + 12);
    }
  }
  jg.paint();

  document.getElementById("graph2").innerHTML = "";
  var jg = new jsGraphics("graph2");
  jg.setColor("red");
  jg.setStroke(3);
  var xoffset = 34;
  var yoffset = -37;
  var xfactor = 2.42;
  var yfactor = 10.6;
  for (i=1; i<6; i++) 
  {
    if (bilival[i] != 0) 
    {
      var x1 = Math.floor(HOL_Bilival[i] * xfactor) + xoffset;
      var y1 = - Math.floor(bilival[i] * yfactor) + yoffset;
      jg.fillRect(x1, y1, 5, 5);
      jg.drawLine(x1 + 1, y1 - 12, x1 + 1, y1 + 12);
    }
  }
  jg.paint();

}
