var build_cost;
var reuse_cost;
var buy_cost;
var contract_cost;
var reuseSub_cost;
var contractSub_cost;

var order = new Array;
  order[0] = new Array;
  order[1] = new Array;
  order[2] = new Array;
  order[3] = new Array;


//****************************************************************
// This function is called when the user blurs a cost text
//     box.  The input is sent to this function along with the
//     form name, and box name.  Depending on what errors are found
//     here, the value of the box will be reset or reformatted
//     appropriately.
//****************************************************************
function money_format(x, form, boxname)
{
  x = "" + x;

  while( (x.charAt(0) == "0") && (parseInt(x) >= 1) )      // If there are leading zeros in the number.
    x = x.substring(1, x.length);

  if(x.indexOf(".") == -1)       // If it is missing a decimal point completely.
    x = x + ".00";

  if(x.lastIndexOf(".") != x.indexOf("."))   // If there are more than one decimal point.
  {
    alert("ERROR:\n\nInvalid format for money.  Cannot have two decimal points.\nValue reset to 0.00.");

    eval( "document." + form + "." + boxname + ".value = '0.00'" );
    setTimeout("  eval('document." + form + "." + boxname + ".focus()')", 50);
    setTimeout("  eval('document." + form + "." + boxname + ".select()')", 100);
    return;
  }

  if(isNaN(x) == true)    // If it is not a number.
  {
    alert("ERROR:\n\nInvalid format for money.\nNo characters allowed.\nValue reset to 0.00.");

    eval( "document." + form + "." + boxname + ".value = '0.00'" );
    setTimeout("  eval('document." + form + "." + boxname + ".focus()')", 50);
    setTimeout("  eval('document." + form + "." + boxname + ".select()')", 100);
    return;
  }

  if( x.indexOf(".") < x.length - 3)  // If there are more than 2 decimal places...rount up to 2 decimal places.
  {
    if( x.substring(x.indexOf(".") + 3,x.indexOf(".") + 4) != 0)
      x = parseFloat(x) + .01;
    x = "" + x;
    x = x.substring(0, x.indexOf(".") + 3);
  }

  while( x.indexOf(".") > (x.length - 3) )  // If there are less than 2 decimal places...add zeros to pad.
    x = "" + x + "0";

    eval( "document." + form + "." + boxname + ".value = x" );
  return x;
}





//****************************************************************
// This function is called indirectly when the user blurs a 
//     probability text box or when we must recover a text box's
//     value from an invalid one entered by the user.  This function
//     sets the text box in the form "form", named "boxname" to the
//     value in "x".
//****************************************************************
function one_minus(x, form, boxname)
{
  if(x == 1.00)        // If the value is 1, return "0.00".
  {
    eval( "document." + form + "." + boxname + ".value = '1.00'" );
    return;
  }
  if(x == 0.00)        // If the value is 0, return "1.00".
  {
    eval( "document." + form + "." + boxname + ".value = '0.00'" );
    return;
  }

  x = 1.00 - x;   // Subtracting value from 1.
  x = x*100;      // Since we want 2 decimal places, we multiply by 100 to get 2 whole numbers.
  x = Math.round(x);   // Rounding to the nearest whole number.
  x = x/100;      // Now we devide by 100 to put it back to a decimal rounded
                  //     by two decimal places.
  x = "" + x;     // Changing x into a string for string manipulation.
  if(x.length < 4)   // If value has less than 4 characters, add a zero to the end.
    x = x + "0";

  format_probability(x, form, boxname);  // Put answer in correct format.

  return;
}



//****************************************************************
// This function is called inderectly when the user blurs a 
//     probability text box or when we must recover a text box's
//     value from an invalid one entered by the user.  This funciton
//     formats the probability correctly and sets the text box name
//     "boxname" in form "form" to the value "x" in a correct format.
//****************************************************************
function format_probability(x, form, boxname)
{

  if(x == 1.00)              // If the value is 1, format it as "1.00".
  {
    eval( "document." + form + "." + boxname + ".value = '1.00'" );
    return;
  }

  if(x == 0.00)              // If the value is 0, format it as "0.00".
  {
    eval( "document." + form + "." + boxname + ".value = '0.00'" );
    return;
  }

  if( x.indexOf(".") < 1)     // If there are no characters in front of the
    x = "0" + x;              //     decimal point, add a zero in front.

  while( x.indexOf(".") > 1)       // As long as there are more than one character
    x = x.substring(1, x.length);  //    in front of the decimal point, remove
                                   //     one of them.
  if( x.length < 4)        // If there are less than 4 characters in the string,
    x = x + "0";           //     add a zero at the end.

  while( x.length > 4)        // Cut off any digits after a length of 4.
    x = x.substring(0, x.length-1);

  eval( "document." + form + "." + boxname + ".value = x" );
  return;
}






//****************************************************************
// This function is called when the user blurs a probability text
//     box.  If the probability is greater than 1, we call 
//     check_probability(), otherwise the probability is formatted
//     correctly.
//****************************************************************
function handle_error(form, self, counterpart)
{
  if(isNaN( eval("document." + form + "." + self + ".value") ) == true)    // If it is not a number.
  {
    alert("ERROR:\n\nInvalid format for probability.\nOnly numbers and one decimal point allowed.\nValue reset.");

    eval( "one_minus( eval('document." + form + "." + counterpart + ".value'), '" +  form + "','" + self + "')" );
    setTimeout(" eval('document." + form + "." + self + ".focus()')", 50);
    setTimeout(" eval('document." + form + "." + self + ".select()')", 100);
    return;
  }


  if( eval("document." + form + "." + self + ".value") == 1.00 )   // If the value is 1, format it as "1.00".
  {
    eval( "document." + form + "." + self + ".value = '1.00'" );
    eval( "document." + form + "." + counterpart + ".value = '0.00'" );
    return;
  }

  if( eval("document." + form + "." + self + ".value") == 0.00 )  // If the value is 0, format it as "0.00".
  {
    eval( "document." + form + "." + self + ".value = '0.00'" );
    eval( "document." + form + "." + counterpart + ".value = '1.00'" );
    return;
  }


  if( eval("document." + form + "." + self + ".value") <= 1.00 )
  {
    eval( "one_minus(eval('document." + form + "." + self + ".value'), '" +  form + "','" + counterpart + "')" );
    eval("format_probability(eval('document." + form + "." + self + ".value'), '" +  form + "','" + self + "')" );
    return;
  }
  else
  {
    alert("ERROR:\nProbability exceeds it's maximum allowed value of 1.00.\n\nValue Reset.")


    eval( "one_minus(eval('document." + form + "." + counterpart + ".value'), '" +  form + "','" + self + "')" );
    setTimeout("  eval('document." + form + "." + self + ".focus()')", 50);
    setTimeout("  eval('document." + form + "." + self + ".select()')", 100);
    return;
  }

}






//****************************************************************
// This function is called indirectly when the user presses the 
//    submit button on the HTML page.  This function calculates
//    the average costs for each decision and stores the answers
//    in the appropriate variables.
//****************************************************************
function calculate_answers()
{
  build_cost = (parseFloat(document.f1.c1.value) * parseFloat(document.f1.p1.value)) + (parseFloat(document.f1.c2.value) * parseFloat(document.f1.p2.value));
  build_cost = money_format(build_cost, "f5", "hidden");

  reuseSub_cost = (parseFloat(document.f2.c3.value) * parseFloat(document.f2.p3.value)) + (parseFloat(document.f2.c4.value) * parseFloat(document.f2.p4.value));
  reuse_cost = (parseFloat(document.f2.c1.value) * parseFloat(document.f2.p1.value)) + (( reuseSub_cost ) * parseFloat(document.f2.p2.value));
  reuse_cost = money_format(reuse_cost, "f5", "hidden");
  reuseSub_cost = money_format(reuseSub_cost, "f5", "hidden");

  buy_cost = (parseFloat(document.f3.c1.value) * parseFloat(document.f3.p1.value)) + (parseFloat(document.f3.c2.value) * parseFloat(document.f3.p2.value));
  buy_cost = money_format(buy_cost, "f5", "hidden");

  contractSub_cost = (parseFloat(document.f4.c3.value) * parseFloat(document.f4.p3.value)) + (parseFloat(document.f4.c4.value) * parseFloat(document.f4.p4.value));
  contract_cost = (parseFloat(document.f4.c1.value) * parseFloat(document.f4.p1.value)) + (( contractSub_cost ) * parseFloat(document.f4.p2.value));
  contract_cost = money_format(contract_cost, "f5", "hidden");
  contractSub_cost = money_format(contractSub_cost, "f5", "hidden");
}




//****************************************************************
// This function is called indirectly when the user presses the 
//    submit button on the HTML page.  This function puts the
//    average costs of each of the decisions in order from least
//    to greatest in an array.  The array uses bubble sort to sort.
//****************************************************************
function put_in_cost_order()
{           //use a sorting routine to put in order from least to greatest.
  var change = 1;

  order[0][0] = build_cost;
  order[0][1] = "BUILD";
  order[1][0] = reuse_cost;
  order[1][1] = "REUSE";
  order[2][0] = buy_cost;
  order[2][1] = "BUY";
  order[3][0] = contract_cost;
  order[3][1] = "CONTRACT";

  while(change == 1) // While there are swaps taking place, check for order.
  {
    change = 0;   // Reset "change" flag.
    for(var i = 0; i < 3; i++)  // Loop to Bubble Sort.
    {
      if( parseFloat(order[i][0]) > parseFloat(order[i+1][0]) )  
      {        // If index is greater than next index, swap them and record that a change occured.
        one = order[i][0];
        two = order[i][1];
        order[i][0] = order[i+1][0];
        order[i][1] = order[i+1][1];
        order[i+1][0] = one;
        order[i+1][1] = two;
        change = 1;
      } // end of if...
    } // end of for...
  } // end of while...

}




//****************************************************************
// This function is called indirectly when the user presses the 
//    submit button on the HTML page.  This function creates a 
//    table (decision table with results) to appear on the output page.
//****************************************************************
function create_table_of_inputs()
{
    var HTMLstring = "<table cellspacing=0 cellpadding=1 border=1 width=88% align=center>";
    HTMLstring += "<tr align=center valign=bottom style='color:yellow; background-color:black; font-size:13pt; font-family:arial;'><td><font face=arial size=+1 color=yellow>Decision</font></td><td><font face=arial size=+1 color=yellow>Type</font></td><td><font face=arial size=+1 color=yellow>Cost</font></td><td><font face=arial size=+1 color=yellow>Probability</font></td><td><font face=arial size=+1 color=yellow>Average Cost</font></td></tr>";

// Build decision.
    HTMLstring += "<tr bgcolor='#BBBBBB'><td rowspan=2 align=center><font size=+1>Build</font>"
    HTMLstring += "</td><td align=center>Simple";
    HTMLstring += "</td><td align=right>$" + document.f1.c1.value;
    HTMLstring += "</td><td align=right>" + document.f1.p1.value;
    HTMLstring += "</td><td rowspan=2 align=center>$" + build_cost + "</td></tr>";

    HTMLstring += "<tr bgcolor='#BBBBBB'><td align=center>Difficult";
    HTMLstring += "</td><td align=right>$" + document.f1.c2.value;
    HTMLstring += "</td><td align=right>" + document.f1.p2.value + "</td></tr>";

// Reuse decision.
    HTMLstring += "<tr bgcolor='#BBBBBB'><td rowspan=4 align=center><font size=+1>Reuse</font>"
    HTMLstring += "</td><td align=center>Minor Changes";
    HTMLstring += "</td><td align=right>$" + document.f2.c1.value;
    HTMLstring += "</td><td align=right>" + document.f2.p1.value;
    HTMLstring += "</td><td rowspan=4 align=center>$" + reuse_cost + "</td></tr>";

    HTMLstring += "<tr bgcolor='#BBBBBB'><td align=center>Major Changes";
    HTMLstring += "</td><td align=right> (calc. from below) &nbsp;$" + reuseSub_cost;
    HTMLstring += "</td><td align=right>" + document.f2.p2.value + "</td></tr>";

    HTMLstring += "<tr bgcolor='#DDDDDD'><td align=center>Major Simple Changes";
    HTMLstring += "</td><td align=right>$" + document.f2.c3.value;
    HTMLstring += "</td><td align=right>" + document.f2.p3.value + "</td></tr>";

    HTMLstring += "<tr bgcolor='#DDDDDD'><td align=center>Major Complex Changes";
    HTMLstring += "</td><td align=right>$" + document.f2.c4.value;
    HTMLstring += "</td><td align=right>" + document.f2.p4.value + "</td></tr>";

// Buy decision.
    HTMLstring += "<tr bgcolor='#BBBBBB'><td rowspan=2 align=center><font size=+1>Buy</font>"
    HTMLstring += "</td><td align=center>Minor Changes";
    HTMLstring += "</td><td align=right>$" + document.f3.c1.value;
    HTMLstring += "</td><td align=right>" + document.f3.p1.value;
    HTMLstring += "</td><td rowspan=2 align=center>$" + buy_cost + "</td></tr>";

    HTMLstring += "<tr bgcolor='#BBBBBB'><td align=center>Major Changes";
    HTMLstring += "</td><td align=right>$" + document.f3.c2.value;
    HTMLstring += "</td><td align=right>" + document.f3.p2.value + "</td></tr>";

// Contract decision.
    HTMLstring += "<tr bgcolor='#BBBBBB'><td rowspan=4 align=center><font size=+1>Contract</font>"
    HTMLstring += "</td><td align=center>No Changes";
    HTMLstring += "</td><td align=right>$" + document.f4.c1.value;
    HTMLstring += "</td><td align=right>" + document.f4.p1.value;
    HTMLstring += "</td><td rowspan=4 align=center>$" + contract_cost + "</td></tr>";

    HTMLstring += "<tr bgcolor='#BBBBBB'><td align=center>Some Changes";
    HTMLstring += "</td><td align=right> (calc. from below) &nbsp;$" + contractSub_cost;
    HTMLstring += "</td><td align=right>" + document.f4.p2.value + "</td></tr>";

    HTMLstring += "<tr bgcolor='#DDDDDD'><td align=center>Simple Changes";
    HTMLstring += "</td><td align=right>$" + document.f4.c3.value;
    HTMLstring += "</td><td align=right>" + document.f4.p3.value + "</td></tr>";

    HTMLstring += "<tr bgcolor='#DDDDDD'><td align=center>Complex Changes";
    HTMLstring += "</td><td align=right>$" + document.f4.c4.value;
    HTMLstring += "</td><td align=right>" + document.f4.p4.value + "</td></tr>";

  HTMLstring += "</table>";

  return HTMLstring;
}




//****************************************************************
// This function is called indirectly when the user presses the 
//    submit button on the HTML page.  This button creates the
//    results table displaying the different decisions in order
//    from least to greatest and displaying the differences.
//****************************************************************
function create_results_output()
{
  var HTMLstring = "";

  HTMLstring += "<table cellspacing=0 cellpadding=10 border=1 width=88% align=center bgcolor='#EEEEEE'><tr><td align=left>";

  HTMLstring += "<font face=arial size=-1>To <b>" + order[0][1] + "</b> is estimated to yield the <i>least</i> cost at <b>$" + order[0][0] + "</b>.</font>";
  HTMLstring += "<ul type=square><li><font face=arial size=-1>To <b>" + order[1][1] + "</b> is estimated to cost an <i>extra</i> <b>$" + money_format(order[1][0] - order[0][0], "f5", "hidden") + "</b>.</font></li>";
  HTMLstring += "<li><font face=arial size=-1>To <b>" + order[2][1] + "</b> is estimated to cost an <i>extra</i> <b>$" + money_format(order[2][0] - order[0][0], "f5", "hidden") + "</b>.</font></li>";
  HTMLstring += "<li><font face=arial size=-1>To <b>" + order[3][1] + "</b> is estimated to cost an <i>extra</i> <b>$" + money_format(order[3][0] - order[0][0], "f5", "hidden") + "</b>.</font></li></ul>";

  HTMLstring += "</td></tr></table>";

  return HTMLstring;
}





//****************************************************************
// This function is called when the user presses the submit button
//    on the HTML page.  This function calls two other function to
//    calculate the output.  That output is returned from these two
//    functions in the form of strings (strings of HTML).
//    These strings are concatenated in this function and written to
//    the document of a new window that this function must create.
//****************************************************************
function submitted()
{
  HTMLstring = "";
  calculate_answers();
  put_in_cost_order();

  resultswin = window.open("","output", "WIDTH=" + (screen.width*.92) + ",HEIGHT=" + (screen.height*.86) + ",TOOLBAR=1,TOP=1,LEFT=0,SCROLLBARS=1,RESIZABLE=1")
    resultswin.focus();

  HTMLstring += "<font size=+2><b><u><center>Decision Table:</center></u></b></font>";
  HTMLstring += create_table_of_inputs();
  HTMLstring += "<br><font size=+2><b><u><center>Results and Comparisons:</center></u></b></font>";
  HTMLstring += create_results_output()
  HTMLstring += "<hr size=1 width=99%><center><font face=arial size=-1>The information on this page shows the estimated least expensive decision.  Cost should not be the only factor in making such a decision.  This tool is used only to display estimated costs for each decision.  Please be advised before making your final choice.</font></center><hr size=1 width=89%>";
  HTMLstring += "<center><form><input type='button' value='     CLOSE THIS WINDOW     ' OnClick='window.close();'></form></center>";

  resultswin.document.close();
  resultswin.document.write(HTMLstring);
}





//****************************************************************
// This function is called when the user clicks on the "On-line
//      Help" link.  This function pops up a window and loads
//      the help page into it.
//****************************************************************
function help()
{
  helpwin = window.open("","help", "WIDTH=" + (screen.width*.64) + ",HEIGHT=" + (screen.height*.59 ) + ",TOOLBAR=0,TOP=1,LEFT=0,SCROLLBARS=1,RESIZABLE=1")
  helpwin.focus();
  helpwin.location = "help.html";
  return;
}



//****************************************************************
// This function is called when the user presses the "clear all"
//      button.  This sets every text box to "0.00".  The focus 
//      is then set to the first text box on the page.
//****************************************************************
function clear_all()
{
  document.f1.c1.value = "0.00";
  document.f1.c2.value = "0.00";
  document.f1.p1.value = "0.00";
  document.f1.p2.value = "0.00";

  document.f2.c1.value = "0.00";
  document.f2.c3.value = "0.00";
  document.f2.c4.value = "0.00";
  document.f2.p1.value = "0.00";
  document.f2.p2.value = "0.00";
  document.f2.p3.value = "0.00";
  document.f2.p4.value = "0.00";

  document.f3.c1.value = "0.00";
  document.f3.c2.value = "0.00";
  document.f3.p1.value = "0.00";
  document.f3.p2.value = "0.00";

  document.f4.c1.value = "0.00";
  document.f4.c3.value = "0.00";
  document.f4.c4.value = "0.00";
  document.f4.p1.value = "0.00";
  document.f4.p2.value = "0.00";
  document.f4.p3.value = "0.00";
  document.f4.p4.value = "0.00";

  setTimeout("document.f1.c1.focus()", 50);
  setTimeout("document.f1.c1.select()", 100);
}

