// This must match constant definition in include/form_lib.php.
// Note: the keyword "const" does not work for IE, so do not apply it to this
// variable.

/* Generic confirmation message plus URL redirection.  Can be used for deleting
 * any object-- simply specify the name and the URL required to delete.
 */
function confirm_deletion(object_name, url) {
  if (confirm('Are you sure you want to delete this ' + object_name + '?')) {
    window.location = url;
  }
}

function toggle_item(the_id) {
  style = document.getElementById(the_id).style;
  style.display = (style.display == "none") ? "" : "none";
}

/* Expands or collapses items of a particular tag type and name */
function toggle_items(tag, name) {
  items = getElementsByName_iefix(tag, name);
  for (i = 0; i < items.length; i++) {
    style = items[i].style;
    style.display = (style.display == "none") ? "" : "none";
  }
}

/* TODO - write this.
 * Adds a css class to an element, checking first that the class is not already
 * being used.
 */
function add_css_class(id, classname) {
  var el = document.getElementById(id);
  if (!el || !el.className) {
    return;
  }
  var cur_classname = el.className;
  if (cur_classname.indexOf(classname) > 0) {
    return;
  }
  el.className = classname + " " + el.className;
}

/* TODO - write this.  Removes a css class from an element, if it exists. */
function remove_css_class(id, classname) {
}

/* TODO - write this.  Draws a translucent layer over the whole page, making
 * all controls uneditable
 */
function disable_page() {
}

/* TODO - write this.  Hides the translucent layer that is covering the whole
 * page.
 */
function enable_page() {
}

/* TODO - write this */
function show_wait_timer() {
}

/* TODO - write this */
function hide_wait_timer() {
}

/* Helper function that is used in place of getElementsByName because that
 * is not properly supported by IE
 */
function getElementsByName_iefix(tag, name) {
  elem = document.getElementsByTagName(tag);
  arr = new Array();
  
  for(i = 0,iarr = 0; i < elem.length; i++) {
    att = elem[i].getAttribute("name");
    if(att == name) {
      arr[iarr] = elem[i];
      iarr++;
    }
  }
  return arr;
}


/* Toggles an image between filename1 and filename2 */
function toggle_img(img_id, filename1, filename2) {
  img = document.getElementById(img_id);
  
  if (img.src.toString().indexOf(filename1) === -1) {
    img.src = filename1;
  } else {
    img.src = filename2;
  }
}

function check_addmetric_inputs(radio_name, metric_select_id,
  metric_name_inputid, metric_type_inputid) {

  radios = getElementsByName_iefix("input", radio_name);
  if (radios[0].checked) {
    metric_select = document.getElementById(metric_select_id);
    if (metric_select.value == "") {
      alert("You must select a metric.");
      return false;
    }
  } else if (radios[1].checked) {
    metric_name = document.getElementById(metric_name_inputid);
    metric_type = document.getElementById(metric_type_inputid);
    str = "";
    if (metric_name.value == "Enter name of new metric..." ||
      metric_name.value == "") {
      str += "You must enter a metric name.";
    }
    if (metric_type.value == "") {
      if (str != "") {
        str += "\n";
      }
      str += "You must select a metric type.";
    }
    if (str != "") {
      alert(str);
      return false;
    }
  }

  return true;
}
  
function clear_addmetric_inputs (existing_select, user_input, type_select, radio_name) {
  existingselect = document.getElementById(existing_select);
  usertext = document.getElementById(user_input);
  type = document.getElementById(type_select);

  existingselect.options[0].selected = true;
  usertext.value = "Enter name of new metric...";
  type.options[0].selected = true;
  
  radios = getElementsByName_iefix("input", radio_name);
  radios[0].checked = true;
}

function check_radio (name, val) {
  radios = getElementsByName_iefix("input", name);
  for (i = 0; i < radios.length; i++) {
    if (radios[i].value == val) {
      radios[i].checked = true;
      break;
    }
  }
}

function add_metric(cat_id, div_id, radio_name,
  metric_select_id, metric_name_inputid, metric_type_inputid,
  table_id, action_type, is_cum_id1, init_value_id1, is_cum_id2,
  init_value_id2) {
  
  var row_id = document.getElementById("row_id").value;
  var row = document.getElementById(row_id).value;
  
  radios = getElementsByName_iefix("input", radio_name);
  if (radios[0].checked) {
    // Pull the name&type of the metric and create a new form object
    metric_select = document.getElementById(metric_select_id);
    var arr = new Array();
    arr = metric_select.value.split(":");
    
    // alert(arr[0] + " " + arr[1] + " " + arr[2] + " " + arr[3])
    // value=metric_defn_id:metric_type_id:metric_display_name:metric_type_name

    var is_cum = is_checked(is_cum_id1);
    var init_value = 0;
    if (is_cum) {
      init_value = document.getElementById(init_value_id1).value;
    }

    create_investment_metric(arr[2], // display_name
      arr[1], // type id
      arr[3], // type display name
      cat_id,
      0,
      0,
      arr[0],  // defn id
      action_type,
      is_cum,
      init_value
    );
  } else if (radios[1].checked) {
    // Pull the name & type from the selected items in the dropdowns    
    metric_name = document.getElementById(metric_name_inputid).value;
    metric_type_id = document.getElementById(metric_type_inputid).value;
    index = document.getElementById(metric_type_inputid).selectedIndex;
 
    metric_type_display =
      document.getElementById(metric_type_inputid).options[index].text;
    var is_cum = is_checked(is_cum_id2);
    var init_value = 0;
    if (is_cum) {
      init_value = document.getElementById(init_value_id2).value;
    }

    create_metric_definition(metric_name, 
      metric_type_id,
      metric_type_display,
      cat_id,
      0,
      0,
      action_type,
      is_cum,
      init_value);
  }
}

function delete_investment_metric(investment_id, org_id, is_org, defn_id,
  cat_id, row_id, table_id, action_type) {
  if (!confirm("Are you sure you want to remove this metric?")) {
    return;
  }

  table_id = document.getElementById("table_id").value;
  is_org = document.getElementById("is_org").value;
  row_id = document.getElementById("row_id").value;
  
  xmlHttp = GetXmlHttpObject();
  if (action_type == "investment_metrics") {
    url = "ajax.php?action=delete_investment_metric" +
      "&table_id=" + table_id + "&is_org=" + 
      is_org + "&row_id=" + row_id + "&investment_id=" + 
      investment_id + "&organization_id=" + org_id +
      "&defn_id=" + defn_id + "&action_type=" + action_type;
  } else {
    url = "ajax.php?action=delete_investment_metric" +
      "&table_id=" + table_id + "&is_org=" + 
      is_org + "&row_id=" + row_id + "&defn_id=" + defn_id + 
      "&action_type=" + action_type;
  }
  xmlHttp.onreadystatechange = stateChangedDeleteInvestmentMetric;
  SendAjaxRequest(xmlHttp, __GET, url, null);
}

// This is the event handler called when the XML over HTTP request comes back.
function stateChangedDeleteInvestmentMetric () {
  if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete") {
    var xml = xmlHttp.responseXML;
    var errors = xml.getElementsByTagName("errors");
    if (errors.length > 0) {
      // TODO - display errors
      alert("error!");
      return;
    }
    var returns = xml.getElementsByTagName("return");
    if (returns == null) {
      // TODO - display an error
      return;
    }
    var table_id =
      xml.getElementsByTagName("table_id").item(0).firstChild.nodeValue;
    var row_id =
      xml.getElementsByTagName("row_id").item(0).firstChild.nodeValue;
    delete_row(row_id, table_id);
  }
}

/*
function delete_organization_metric(organization_id, defn_id, cat_id, rowId,
  tableId, iframeId) {
  if (!confirm("Are you sure you want to delete this metric?")) {
    return;
  }

  iframe = document.getElementById(iframeId);
  iframe.src = "delete_investment_metric.php?metric_definition_id=" +
    defn_id + "&organization_id=" + organization_id;
  
  addMetricRowNum[cat_id]--;
  row = document.getElementById(rowId);
  table = document.getElementById(tableId);
  table.deleteRow(row.rowIndex);
}
*/

function add_required_metric(cat_id, div_id, radio_name,
  metric_select_id, metric_name_inputid, metric_type_inputid,
  table_id, add_row_id) {
  
  // Get the row index based on add
  add_row = document.getElementById(add_row_id);
  
  radios = document.getElementsByName(radio_name);
  if (radios[0].checked) {
    // Pull the name&type of the metric and create a new form object
    
    metric_select = document.getElementById(metric_select_id);
    arr = new Array();
    arr = metric_select.value.split(":");
    
    // alert(arr[0] + " " + arr[1] + " " + arr[2] + " " + arr[3] + " " + arr[4])
    // value=metric_defn_id:metric_type_id:metric_display_name:metric_type_name:preview

    insertRequiredInvestmentMetric(table_id, add_row.rowIndex, arr[2], arr[1],
      arr[3], arr[4], arr[0], cat_id);
  } else if (radios[1].checked) {
    // Pull the name & type from the selected items in the dropdowns    
    metric_name = document.getElementById(metric_name_inputid).value;
    metric_type_id = document.getElementById(metric_type_inputid).value;
    preview = "";
    metric_type_name = "";
    switch (metric_type_id) {
      case "0":
        metric_type_name = "Number";
        preview = "95";
        break;
      case "1":
        metric_type_name = "Dollars";
        preview = "$95";
        break;
      case "2":
        metric_type_name = "Percent";
        preview = "95%";
        break;
    }
    
    insertRequiredInvestmentMetric(table_id, add_row.rowIndex, metric_name,
      metric_type_id, metric_type_name, preview, null, cat_id);
  }
}

function insertRequiredInvestmentMetric(table_id, rowIndex, metric_display_name,
  metric_type_id, metric_type_display, preview, metric_definition_id, cat_id) {
  if (metric_definition_id == null) {
    formobj = "<input type=\"hidden\" name=\"" + objNum + ":_table\" " +
    "value='metric_definitions' />\n";
    formobj += "<input type='hidden' name='" + objNum + ":_mode' " +
    "value='1' />\n";
    formobj += "<input type='hidden' name='" + objNum + ":is_required_for_all' " +
    "value='1' />\n";
    formobj += "<input type='hidden' name='" + objNum + ":metric_type_id' " +
    "value='" + metric_type_id + "' />\n";
    formobj += "<input type='hidden' name='" + objNum + ":display_name' " +
    "value=\"" + metric_display_name + "\" />\n";
    formobj += "<input type='hidden' name='" + objNum + ":metric_category_id' " +
    "value='" + cat_id + "' />\n";
  } else {
    formobj = "<input type='hidden' name='" + objNum + ":_table' " +
      "value='metric_definitions'/>\n";
    formobj += "<input type='hidden' name='" + objNum + ":_mode' " +
      "value='2'/>\n";
    formobj += "<input type='hidden' name='" + objNum + ":is_required_for_all' " +
    "value='1' />\n";
    formobj += "<input type='hidden' name='" + objNum + ":id' " +
      "value='" + metric_definition_id + "' />";
  }

  objNum++;

  table = document.getElementById(table_id);
  newrow = table.insertRow(rowIndex);
  newrow.id = "__newMetricRow" + objNum;
  cell1 = newrow.insertCell(0);
  cell1.innerHTML = "<a href=\"JavaScript:" +
    "if(confirm('Are you sure you want to make this metric non-required?')) { " +
    "delete_row('" + newrow.id +
    "', '" + table_id + "');}\"><img src='images/trash.gif'/></a> " + 
    metric_display_name + formobj;
  cell2 = newrow.insertCell(1);
  cell2.innerHTML = metric_type_display;
  cell3 = newrow.insertCell(2);
  cell3.innerHTML = preview;
  cell3.className = "right_align";
}

function delete_row (row_id, table_id) {
  var table = document.getElementById(table_id);
  var row = document.getElementById(row_id);
  table.deleteRow(row.rowIndex);
}

function delete_required_metric(defn_id, cat_id, rowId,
  tableId, iframeId) {
  if (!confirm("Are you sure you want to make this metric non-required?")) {
    return;
  }

  iframe = document.getElementById(iframeId);
  iframe.src = "delete_required_metric.php?metric_definition_id=" +
    defn_id;
  
  addMetricRowNum[cat_id]--;
  row = document.getElementById(rowId);
  table = document.getElementById(tableId);
  table.deleteRow(row.rowIndex);
}

function clear_text(id, txt) {
  input = document.getElementById(id);
  if (input.value === txt) {
    input.value = "";
  }
}

// Deprecated.  Use hide()
function close_popup(element) {
  element.style.display = "none";
}

// Makes an element invisible.
function hide(id) {
  var element = document.getElementById(id);
  if (element) {
    element.style.display = "none";
  }
}

// Deprecated.  Use show()
function show_popup(element) {
  element.style.display = "";
}

// Makes an element visible again, or more accurately, returns it to the
// display mode dictated by the applied CSS classes.
function show(id) {
  var element = document.getElementById(id);
  if (element) {
    element.style.display = "";
  }
}

// Disables a form field.
function disable(id) {
  var element = document.getElementById(id);
  if (element) {
    element.disabled = true;
  }
}

// Enables a form field (but not in Opera 5, apparently).
function enable(id) {
  var element = document.getElementById(id);
  if (element) {
    element.disabled = false;
  }
}

// For convenience
function disable_and_hide(field, element) {
  disable(field);
  hide(element);
}

// For convenience
function disable_and_show(field, element) {
  disable(field);
  show(element);
}

function enable_and_show(field, element) {
  enable(field);
  show(element);
}

// TODO - fix this to close other notes or disable background...
function show_note(formid) {
  form = document.getElementById(formid);
  show_popup(form);
}

function save_note_edit(formid, textareaname, varName, num) {
  toggle_item(formid);
  items = getElementsByName_iefix("textarea", textareaname);
  if (items != null && items[num]) {
    eval(varName + " = '" + escape(items[num].value) + "';");
  }
}


// Restore the previously entered value.
function cancel_note_edit(formid, textareaname, varName, num) {
  toggle_item(formid);
  items = getElementsByName_iefix("textarea", textareaname);
  if (items != null && items[num] != null) {
    eval("items[num].value = unescape(" + varName + ");");
  }
}

function moveOption(to, id, hidden_list_id) {
  var list = document.getElementById(id);
  var hidden_list = document.getElementById(hidden_list_id);
  var index = list.selectedIndex;
  var total = list.options.length-1;
  if (index == -1) {
    return false;
  }
  if (to == +1 && index == total) {
    return false;
  }
  if (to == -1 && index == 0) {
    return false;
  }
  var items = new Array;
  var values = new Array;
  var hidden_items = new Array;
  var hidden_values = new Array;
  for (i = total; i >= 0; i--) {
    items[i] = list.options[i].text;
    values[i] = list.options[i].value;
    hidden_items[i] = hidden_list.options[i].text;
    hidden_values[i] = hidden_list.options[i].value;
  }

  for (i = total; i >= 0; i--) {
    if (index == i) {
      list.options[i + to] = new Option(items[i],values[i + to], 0, 1);
      list.options[i] = new Option(items[i + to], values[i]);
      hidden_list.options[i + to] =
        new Option(hidden_items[i], hidden_values[i + to], 0, 1);
      hidden_list.options[i] = new Option(hidden_items[i + to],
        hidden_values[i]);
      i--;
    } else {
      list.options[i] = new Option(items[i], values[i]);
      hidden_list.options[i] = new Option(hidden_items[i], hidden_values[i]);
    }
  }
  list.options[index+to].selected = true;
  list.focus();
}

function submitForcedRankings(id, formid, hidden_list_id) {
  var hidden_list = document.getElementById(hidden_list_id);
  var theList = "?_forcedRankSubmit=1&";
 
  for (i = 0; i <= hidden_list.options.length-1; i++) { 
    theList += "__organization:" + hidden_list.options[i].value + "=" + 
      hidden_list.options[i].text;
    if (i != hidden_list.options.length-1) {
      theList += "&";
    }
  }
  location.href = document.getElementById(formid).action + theList;
}

function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft,curtop];
}


function move_box(an, box) {
  var cleft = 0;
  var ctop = 0;
  var obj = an;
  while (obj.offsetParent) {
    cleft += obj.offsetLeft;
    ctop += obj.offsetTop;
    obj = obj.offsetParent;
  }
  box.style.left = cleft + 'px';
  ctop += an.offsetHeight + 8;
  if (document.body.currentStyle &&
    document.body.currentStyle['marginTop']) {
    ctop += parseInt(
      document.body.currentStyle['marginTop']);
  }
  box.style.top = ctop + 'px';
}

function show_hide_box(an, id) {
  var boxdiv = document.getElementById(id);

  if (boxdiv != null) {
    if (boxdiv.style.display == 'none') {
      move_box(an, boxdiv);
      boxdiv.style.display = "block";
    } else {
      boxdiv.style.display='none';
    } 
  }
}

function set_metric_inputs(table_id, row_id, parent_id, level, is_org, cat_id)
{
  document.getElementById("table_id").value = table_id;
  document.getElementById("row_id").value = row_id;  
  document.getElementById("parent_id").value = parent_id;
  document.getElementById("level").value = level;
  document.getElementById("is_org").value = is_org;
  document.getElementById("cat_id").value = cat_id;
}

var xmlHttp;

function GetXmlHttpObject()
{ 
  var objXMLHttp = null;
  if (window.XMLHttpRequest)
  {
    objXMLHttp = new XMLHttpRequest();
  } else if (window.ActiveXObject) {
    objXMLHttp = new ActiveXObject("Microsoft.XMLHTTP");
  }
  return objXMLHttp;
}

var __POST = "post";
var __GET  = "get";

// Sends both get and post requests to the specified url.  Calling functions
// should already have set up the stateChanged attribute on the xmlHttp object.
function SendAjaxRequest(xmlHttpObj, method, url, parameters) {
  xmlHttpObj.open(method, url, true);
  if (method == __POST) {
    xmlHttpObj.setRequestHeader("Content-type",
      "application/x-www-form-urlencoded");
    xmlHttpObj.setRequestHeader("Content-length", parameters.length);
    xmlHttpObj.setRequestHeader("Connection", "close");
    xmlHttpObj.send(parameters);
  } else if (method == __GET) {
    xmlHttpObj.send(null);
  }
}

// Use this function to encode user-entered text strings before sending them
// over to the server.
function encodeURI_iefix(str) {
  ret = str;
  try {
    ret = encodeURI(str);
  } catch(e) {
    ret = escape(str);
  }
  return ret;
}

// Retrieves a node value from within XML.  Does not understand XML tree.
function GetValueFromXml(xml, name) {
  if (!xml || !xml.getElementsByTagName(name) ||
    !xml.getElementsByTagName(name).item(0) || 
    !xml.getElementsByTagName(name).item(0).firstChild || 
    !xml.getElementsByTagName(name).item(0).firstChild.nodeValue) {
    
    return null;
  } else {
    return xml.getElementsByTagName(name).item(0).firstChild.nodeValue;
  }
}


// This uses AJAX to create a new metric definition in the system, and then
// associate the metric with either the organization or investment as
// appropriate.
function create_metric_definition(display_name, metric_type_id,
  metric_type_display, metric_category_id, required_for_organizations,
  required_for_investments, action_type, is_cumulative, initial_value) {
  
  var parent_id = null;
  if (action_type == "investment_metrics") {
    parent_id = document.getElementById("parent_id").value;
    var investment_id = document.getElementById("investment_id").value;
    var organization_id = document.getElementById("organization_id").value;
  }
  var table_id = document.getElementById("table_id").value;
  var is_org = document.getElementById("is_org").value;
  var row_id = document.getElementById("row_id").value;
  var level = document.getElementById("level").value;
  var cat_id = document.getElementById("cat_id").value;
  display_name = escape(display_name);

  xmlHttp = GetXmlHttpObject(); 

  if (action_type == "investment_metrics") {
    var url = "ajax.php?action=create_metric&display_name=" +
      display_name + "&metric_type_id=" + metric_type_id + 
      "&metric_type_display=" +
      metric_type_display + "&metric_category_id=" + metric_category_id + 
      "&required_for_organizations=" + required_for_organizations + 
      "&required_for_investments=" + required_for_investments + "&table_id=" +
      table_id + "&is_org=" + is_org + "&row_id=" + row_id + "&level=" + 
      level + "&investment_id=" + investment_id + "&organization_id=" +
      organization_id + "&cat_id=" + cat_id + "&action_type=" + action_type;
    if (parent_id != null && parent_id != "") {
      url += "&parent_id=" + parent_id;
    }
    if (is_cumulative) {
      url += "&is_cumulative=1&initial_value=" + initial_value;
    }
  } else if (action_type == "metrics_setup") {
    var colname = "required_for_investments";
    if (is_org == 1) {
      colname = "required_for_organizations";
    }
    var url = "ajax.php?action=create_metric_and_make_required&display_name=" +
      display_name + "&metric_type_id=" + metric_type_id + 
      "&metric_type_display=" + metric_type_display + "&metric_category_id=" + 
      metric_category_id + "&" + colname + "=1" + "&table_id=" + table_id + 
      "&is_org=" + is_org + "&row_id=" + row_id + "&level=" + level + 
      "&cat_id=" + cat_id + "&action_type=" + action_type; 
  }

  xmlHttp.onreadystatechange = stateChangedCreateInvestmentMetric;
  SendAjaxRequest(xmlHttp, __GET, url, null);
}

// This is the event handler called when the XML over HTTP request comes back.
function stateChangedCreateInvestmentMetric () {
  if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete") {
    var xml = xmlHttp.responseXML;
    var errors = xml.getElementsByTagName("errors");
    if (errors.length > 0) {
      // TODO - display errors
      return;
    }
    var returns = xml.getElementsByTagName("return");
    if (returns == null) {
      // TODO - display an error
      return;
    }
    var action = xml.getElementsByTagName("action").item(0).firstChild.nodeValue;
    var action_type =
      xml.getElementsByTagName("action_type").item(0).firstChild.nodeValue;

    if (action_type == "investment_metrics") {
      var investment_id =
        xml.getElementsByTagName("investment_id").item(0).firstChild.nodeValue;
      var org_id = xml.getElementsByTagName("org_id").item(0).firstChild.nodeValue;
    
      var parents = xml.getElementsByTagName("parent_id");
      var parent_id = null;
      if (parents.length == 1) {
        parent_id = parents.item(0).firstChild.nodeValue;
      } 

      var is_cum_outer = xml.getElementsByTagName("is_cumulative");
      var is_cum = null;
      if (is_cum_outer.length == 1) {
        is_cum = is_cum_outer.item(0).firstChild.nodeValue;
      }
      var init_value_outer = xml.getElementsByTagName("initial_value");
      var init_value = null;
      if (init_value_outer.length == 1) {
        init_value = init_value_outer.item(0).firstChild.nodeValue;
      }
    }

    var defn_id =
      xml.getElementsByTagName("metric_definition_id").item(0).firstChild.nodeValue;
    var table_id = xml.getElementsByTagName("table_id").item(0).firstChild.nodeValue;
    
    var row_id = xml.getElementsByTagName("row_id").item(0).firstChild.nodeValue;
    var display_name = xml.getElementsByTagName("display_name").item(0).firstChild.nodeValue;
    var metric_type_id = xml.getElementsByTagName("metric_type_id").item(0).firstChild.nodeValue;
    var is_org = xml.getElementsByTagName("is_org").item(0).firstChild.nodeValue;
    var level = xml.getElementsByTagName("level").item(0).firstChild.nodeValue;
    var metric_type_display =
      xml.getElementsByTagName("metric_type_display").item(0).firstChild.nodeValue;
    var cat_id = xml.getElementsByTagName("cat_id").item(0).firstChild.nodeValue;

    if (action == "create_metric") {
      insert_metric(table_id, row_id, defn_id, display_name, metric_type_display,
        level, is_org, parent_id, metric_type_id, cat_id, investment_id, org_id,
        action_type, is_cum, init_value);
    } else {
      insert_metric(table_id, row_id, defn_id, display_name, metric_type_display,
        level, is_org, parent_id, metric_type_id, cat_id, investment_id, org_id,
        action_type, is_cum, init_value);
    }
  }
}

// Inserts metric info below the row corresponding to the given ID.
function insert_metric(table_id, row_id, metric_definition_id, display_name,
  metric_type_display, level, is_org, parent_id, metric_type_id, cat_id,
  investment_id, org_id, action_type, is_cum, init_value) {

  var table = document.getElementById(table_id);
  var row = document.getElementById(row_id);

  var newrow = table.insertRow(row.rowIndex + 1);
  newrow.className = " ";
  if (is_org == 1) {
    newrow.id = "__organizationMetricRow" + metric_definition_id;
  } else {
    newrow.id = "__investmentMetricRow" + metric_definition_id;
  }

  var cell1 = newrow.insertCell(0);
  var cell2 = newrow.insertCell(1);
  var cell3 = null;
  if (action_type != "metrics_setup") {
    cell3 = newrow.insertCell(2);
  }

  var str = "";
  if (level == 0) {
    if (action_type == "metrics_setup") {
      cell1.className = "parent_metric italic";
      cell2.className = "parent_metric italic";
    } else {
      cell1.className = "parent_metric";
      cell2.className = "parent_metric";
      cell3.className = "parent_metric right_align";
    }
    str += "<div class=\" \">" + display_name;
  } else if (level == 1) { 
    cell1.className = "submetric";
    cell2.className = "submetric";
    cell3.className = "submetric right_align";
    str += "<div class=\"child_metric\">"  +
      "&nbsp;&nbsp;&bull; " + display_name;
  } else if (level == 2) {
    cell1.className = " ";
    cell2.className = " ";
    cell3.className = "right_align";
    str += "<div class=\"grandchild_metric\">" +
      "&nbsp;&nbsp;&bull; " + display_name;
  }

  level = parseInt(level);

  if ((level == 0 || level == 1) && action_type == "investment_metrics") {
    str += " <a class=\"tiny_subdued_link\" href=\"JavaScript:" + 
      "clear_addmetric_inputs('" + 
      make_popup_id("existing_metric", cat_id, is_org) + "', '" +
      make_popup_id("user_metric", cat_id, is_org) + "', '" +
      make_popup_id("metric_type", cat_id, is_org) + "', '" +
      make_popup_id("__newmetric", cat_id, is_org) + "');" +
      "set_metric_inputs('" + table_id + "', '" + newrow.id + "', " +
      "'" + metric_definition_id + "', " + (level + 1) + ", ";
    if (is_org == 1) {
      str += "1, ";
    } else {
      str += "0, ";
    }
    str += cat_id + "); toggle_item('" +
      make_popup_id("add_metric", cat_id, is_org) + "');\">Add</a>";
  }

  str += " <a class=\"tiny_subdued_link\" href=\"JavaScript:" +
      "set_metric_inputs('" + table_id + "', '" + newrow.id + "', " +
      "'" + metric_definition_id + "', " + (level + 1) + ", ";
  if (is_org == 1) {
    str += "1, ";
  } else {
    str += "0, ";
  }
  str += cat_id + ");delete_investment_metric(" +
      investment_id + ", " + org_id + ", " + is_org + ", " +
      metric_definition_id + ", " + cat_id + ", " + "'" + newrow.id + "', '" +
      table_id + "', '" + action_type + "');\">Del</a>\n";

  str += "</div>\n";
  cell1.innerHTML = str;

  if (level == 0) {
    cell2.innerHTML = metric_type_display;
  } else {
    cell2.innerHTML = "&nbsp;";
  }

  if (action_type == "investment_metrics") {
    if (is_cum == 1) {
      cell3.innerHTML = "<div>Yes</div>";
    } else {
      cell3.innerHTML = "<div>No</div>";
    }
  }

  // Remove this metric as an option
  remove_option(metric_definition_id, cat_id, is_org);
}

function remove_option(metric_definition_id, cat_id, is_org) {
  var id = make_popup_id("existing_metric", cat_id, is_org);
  var selectbox = document.getElementById(id);
  for (i = 0; i < selectbox.options.length; i++) {
    var option = selectbox.options[i];
    arr = option.value.split(":");
    if (arr[0] == metric_definition_id) {
      selectbox.options[i] = null;
      break;
    }
  }
}

function create_investment_metric(display_name, metric_type_id,
  metric_type_display, metric_category_id, required_for_organizations,
  required_for_investments, defn_id, action_type, is_cumulative,
  initial_value) {
  
  var investment_id = null;
  var organization_id = null;
  var parent_id = null;
  if (action_type == "investment_metrics") {
    investment_id = document.getElementById("investment_id").value;
    organization_id = document.getElementById("organization_id").value;
    parent_id = document.getElementById("parent_id").value;
  }
  var table_id = document.getElementById("table_id").value;
  var is_org = document.getElementById("is_org").value;
  var row_id = document.getElementById("row_id").value;
  var level = document.getElementById("level").value;
  var cat_id = document.getElementById("cat_id").value;
  display_name = escape(display_name);

  xmlHttp = GetXmlHttpObject();
  var url = null;
  if (action_type == "investment_metrics") {
    url = "ajax.php?action=create_investment_metric&display_name=" +
      display_name + "&defn_id=" + defn_id + "&metric_type_id=" +
      metric_type_id + "&metric_type_display=" +
      metric_type_display + "&metric_category_id=" + metric_category_id + 
      "&required_for_organizations=" + required_for_organizations + 
      "&required_for_investments=" + required_for_investments + "&table_id=" +
      table_id + "&is_org=" + is_org + "&row_id=" + row_id + "&level=" + 
      level + "&investment_id=" + investment_id + "&organization_id=" +
      organization_id + "&cat_id=" + cat_id + "&action_type=" + action_type;
  
    if (parent_id != null && parent_id != "") {
      url += "&parent_id=" + parent_id;
    }
    if (is_cumulative) {
      url += "&is_cumulative=1&initial_value=" + initial_value;
    }
  } else if (action_type == "metrics_setup") {
    // Either required_for_investments or required_for_organizations will be
    // set to 1.
    var colname = "required_for_investments";
    if (is_org == 1) {
      colname = "required_for_organizations";
    }
    url = "ajax.php?action=update_metric_requirements&display_name=" +
      display_name + "&defn_id=" + defn_id + "&metric_type_id=" +
      metric_type_id + "&metric_type_display=" + metric_type_display + 
      "&metric_category_id=" + metric_category_id + "&" + colname + "=1" +
      "&table_id=" + table_id + "&is_org=" + is_org + "&row_id=" + row_id + 
      "&level=" + level + "&cat_id=" + cat_id + "&action_type=" + action_type;
  }

  xmlHttp.onreadystatechange = stateChangedCreateInvestmentMetric;
  SendAjaxRequest(xmlHttp, __GET, url, null);
}

function make_popup_id(prefix, cat_id, is_org) {
  return prefix + cat_id + (is_org == 1 ? "_org" : "_inv");
}

function toggle_li_class(id, class1, class2) {
  el = document.getElementById(id);
  if (el.className == class1) {
    el.className = class2;
  } else {
    el.className = class1;
  }
}

function is_checked(id) {
  var input = document.getElementById(id);
  if (input && input.checked) {
    return true;
  }
  return false;
}

// When the user changes the selection of the "is pending" radio button, this
// function should show/hide/disable/enable all the right input fields.
function handle_txn_pending(pending_input_name, txn_type_dropdown_id,
  date_planned_id, date_planned_div_id, date_actual_id, date_actual_div_id,
  amount_planned_debit_id, amount_planned_debit_div_id, amount_planned_credit_id, amount_planned_credit_div_id,
  amount_actual_debit_id, amount_actual_debit_div_id, amount_actual_credit_id, amount_actual_credit_div_id) {

  pending = is_pending(pending_input_name);
  is_debit = is_txn_debit(txn_type_dropdown_id);
  if (pending) {
    // It is pending, so only show the "planned" inputs.  Disable/hide all else
    disable_and_hide(date_actual_id, date_actual_div_id);
    disable_and_hide(amount_actual_debit_id, amount_actual_debit_div_id);
    disable_and_hide(amount_actual_credit_id, amount_actual_credit_div_id);
    enable_and_show(date_planned_id, date_planned_div_id);
    if (is_debit) {
      enable_and_show(amount_planned_debit_id, amount_planned_debit_div_id);
      disable_and_show(amount_planned_credit_id, amount_planned_credit_div_id);
    } else {
      disable_and_show(amount_planned_debit_id, amount_planned_debit_div_id);
      enable_and_show(amount_planned_credit_id, amount_planned_credit_div_id);
    }
  } else {
    // It is not pending.  Show the "actual" inputs for sure, then show the
    // "planned" inputs only if they have been filled in.
    enable_and_show(date_actual_id, date_actual_div_id);
    hide_and_disable_if_field_empty(date_planned_id, date_planned_div_id);
    disable(date_planned_id);

    if (is_debit) {
      enable_and_show(amount_actual_debit_id, amount_actual_debit_div_id);
      disable_and_show(amount_actual_credit_id, amount_actual_credit_div_id);

      // Planned amounts should be disabled if they are empty.  The debit field
      // should be disabled no matter what.
      hide_and_disable_if_field_empty(amount_planned_debit_id, 
        amount_planned_debit_div_id);
      hide_and_disable_if_field_empty(amount_planned_credit_id, 
        amount_planned_credit_div_id);
      disable(amount_planned_credit_id);
    } else {
      disable_and_show(amount_actual_debit_id, amount_actual_debit_div_id);
      enable_and_show(amount_actual_credit_id, amount_actual_credit_div_id);

      // Planned amounts should be disabled if they are empty.  The debit field
      // should be disabled no matter what.
      hide_and_disable_if_field_empty(amount_planned_debit_id, 
        amount_planned_debit_div_id);
      disable(amount_planned_debit_id);
      hide_and_disable_if_field_empty(amount_planned_credit_id, 
        amount_planned_credit_div_id);
    }
  }
}

// Given the name of the radio button set, returns true if the pending radio
// button has been checked Yes.  Returns false otherwise.
function is_pending(pending_input_name) {
  var radios = getElementsByName_iefix("input", pending_input_name);
  return radios[0].checked;
}

// Checks if the currently selected transaction type is a debit or credit.
function is_txn_debit(txn_type_select_id) {
  var select = document.getElementById(txn_type_select_id);
  if (!select || select.options.length == 0) {
    return true;
  }
  if (!__txn_types_debit_array || __txn_types_debit_array.length == 0) {
    return true;
  }
  var index = select.selectedIndex;
  if (index < 0) {
    return true;
  }
  for (i = 0; i < __txn_types_debit_array.length; i++) {
    if (select.options[index].value == __txn_types_debit_array[i]) {
      return true;
    }
  }
  return false;
}

function hide_and_disable_if_field_empty(field_id, div_id) {
  if (empty(field_id)) {
    hide(div_id);
    disable(field_id);
  }
}

// Tests if an input field is empty.
function empty(id) {
  var regexEmpty = /^\s*$/;
  var element = document.getElementById(id);
  if (!element || !element.value) {
    return true;
  }
  return regexEmpty.test(element.value);
}

// Tests if a string variable is empty.
function empty_var(textvar) {
  var regexEmpty = /^\s*$/;
  if (!textvar) {
    return true;
  }
  return regexEmpty.test(textvar);
}

// Enables/disables the appropriate user input fields based on selected
// dropdown (Is it a credit or a debit?  Pending or not pending?)
function handle_changed_txn_type(dropdown_id, pending_input_name,
  amount_planned_debit_id, amount_planned_credit_id, amount_actual_debit_id,
  amount_actual_credit_id) {

  is_debit = is_txn_debit(dropdown_id);
  pending = is_pending(pending_input_name);

  if (is_debit) {
    // Disable the credit fields, enable the correct debit field
    disable(amount_planned_credit_id);
    disable(amount_actual_credit_id);
    if (pending) {
      enable(amount_planned_debit_id);
    } else {
      enable(amount_actual_debit_id);
      // XXX - If the user has entered something, leave it.  Otherwise, disable?
      if (empty(amount_planned_credit_id)) {
        disable(amount_planned_credit_id);
      }
    }
  } else {
    // Disable the debit fields, enable the correct credit field
    disable(amount_planned_debit_id);
    disable(amount_actual_debit_id);
    if (pending) {
      enable(amount_planned_credit_id);
    } else {
      enable(amount_actual_credit_id);
      // XXX - If the user has entered something, leave it.  Otherwise, disable?
      if (empty(amount_planned_credit_id)) {
        disable(amount_planned_credit_id);
      }
    }
  }
}

// Pulls the investment or organization id out of the dropdown menu
// and forward onto the proper report.
function canned_report_nav(page_name, report_id, select_id, value_name) {
  if (!page_name || !report_id) {
    return;
  }
  select = document.getElementById(select_id);
  if (!select || select.options.length == 0) {
    return;
  }
  val = select.options[select.selectedIndex].value;
  if (val) {
    // Should produce something like "report.php?id=4&investment_id=5"
    window.location = 
      page_name + "?id=" + report_id + "&" + value_name + "=" + val;
  }
}

// Depends on forms_js
function add_capassess(year_input_id, inv_id) {
  input = document.getElementById(year_input_id);
  if (!input) {
    return;
  }
  var value = input.value;
  if (!reSignedInteger.test(trim(value))) {
    alert('You must enter a valid year.');
    return;
  }
  var val = parseFloat(value);
  if (val < 0) {
    alert('You must enter a valid year.');
    return;
  }

  // Go to the creation page
  window.location = "capabilities_assessment.php?year=" + trim(value) +
    "&investment_id=" + inv_id;
}

function download_monthly_report(month, select_id) {
  var select = document.getElementById(select_id);
  window.location = "report.php?id=3&year=" + select.value + "&month=" + month;
}
