//
// ratecalcform.js -- Copyright 2008 David J. Meppelink. All rights reserved.
//

function setElement(id, value) {
  var element = document.getElementById(id);
  element.innerHTML = value || '';
}

function appendCell(row, index, style, text) {
  var cell = row.insertCell(index);
  cell.setAttribute('class', style);
  cell.setAttribute('valign', 'top');
  if (text != null) {
    cell.innerHTML = text;
  }
  return cell;
}

function appendAnchor(parent, text, title, func) {
  var image = document.createElement('img');
  image.setAttribute('alt', text);
  image.setAttribute('src', RateCalcSettings.baseURL + '/image/action_' + text + '.png');

  var anchor = document.createElement('a');
  anchor.href = '#';
  anchor.setAttribute('title', title);
  anchor.setAttribute('onclick', func);
  anchor.appendChild(image);

  if (parent.childNodes.length > 0) {
    parent.appendChild(document.createTextNode('\u00A0'));
  }
  parent.appendChild(anchor);
  return anchor;
}

function show(object) {
  if (object != null)
    object.style.visibility = 'visible';
}

function hide(object) {
  if (object != null)
    object.style.visibility = 'hidden';
}

function toggleById(id) {
  var e = document.getElementById(id);
  if(e.style.display == 'block')
    e.style.display = 'none';
  else
    e.style.display = 'block';
}

function expandById(id) {
  var e = document.getElementById(id);
  e.style.display = 'block';
}

function collapseById(id) {
  var e = document.getElementById(id);
  e.style.display = 'none';
}

function upAnchorOf(row) {
  // This is pretty fragile, but at least it is in one place.
  if (row == null || row.nodeType != Node.ELEMENT_NODE)
    return null;
  return row.childNodes[5].childNodes[2];
}

function downAnchorOf(row) {
  // This is pretty fragile, but at least it is in one place.
  if (row == null || row.nodeType != Node.ELEMENT_NODE)
    return null;
  return row.childNodes[5].childNodes[4];
}

function updateAnchors(tbody) {
  var size = tbody.rows.length;
  if (size >= 1) {
    // hide the up/down anchors for the first/last rows.
    hide(upAnchorOf(tbody.rows[0]));
    hide(downAnchorOf(tbody.rows[size - 1]));
    if (size >= 2) {
      // show the up/down anchors of the interior rows.
      show(upAnchorOf(tbody.rows[1]));
      show(downAnchorOf(tbody.rows[size - 2]));
    }
    for (var index = 0; index < size; index++) {
      if (index % 2 == 0)
        tbody.rows[index].setAttribute('class', 'even');
      else
        tbody.rows[index].setAttribute('class', 'odd');
    }
  }
}

function removeRow(event) {
  var row = event.target.parentNode.parentNode.parentNode;
  var tbody = row.parentNode;

  tbody.removeChild(row);

  updateAnchors(tbody);

  return false;
}

function raiseRow(event) {
  var row = event.target.parentNode.parentNode.parentNode;
  var ref = row.previousSibling;
  var tbody = row.parentNode;

  tbody.removeChild(row);
  tbody.insertBefore(row, ref);

  updateAnchors(tbody);

  return false;
}

function lowerRow(event) {
  var row = event.target.parentNode.parentNode.parentNode;
  var ref = row.nextSibling;
  var tbody = row.parentNode;

  tbody.removeChild(ref);
  tbody.insertBefore(ref, row);

  updateAnchors(tbody);

  return false;
}

function calculateRate() {
  var form = document.forms['ratecalcform'];

  var mysack = new sack(RateCalcSettings.baseURL + '/php/server.php');
  mysack.method = 'GET';
  if (form.sack_async) {
      mysack.async = (form.sack_async.value == 'true');
  }

  // Set the sack variables by reading the form <input>s.
  for (var index = 0; index < form.elements.length; index++) {
    var elem = form.elements[index];
    if (elem.nodeType == 1 && elem.nodeName == 'INPUT') { // ELEMENT_NODE
      mysack.setVar(elem.name, elem.value);
    }
  }

  mysack.onError = function() {
    alert('Ajax error while calculating rate');
  };

  mysack.onCompletion = function() {
    eval('var obj = ' + this.response);
    setElement('fs_comment', obj.query.ficoScore.comment);
    setElement('oa_comment', obj.query.openAccounts.comment);
    setElement('ci_comment', obj.query.creditInquiries.comment);
    setElement('cu_comment', obj.query.creditUsage.comment);
    setElement('ch_comment', obj.query.creditHistory.comment);
    setElement('la_comment', obj.query.loanAmount.comment);

    if (obj.rate != null) {
      if (obj.rate && obj.rate.display.length > 0) {
        var table = document.getElementById('ratecalctable');
        var tbody = table.tBodies[0];
        var row = tbody.insertRow(0);
        appendCell(row, 0, 'fs_cell', obj.query.ficoScore.display);
        appendCell(row, 1, 'oa_cell', obj.query.openAccounts.display);
        appendCell(row, 2, 'ci_cell', obj.query.creditInquiries.display);
        appendCell(row, 3, 'cu_cell', obj.query.creditUsage.display);
        appendCell(row, 4, 'ch_cell', obj.query.creditHistory.display);
        appendCell(row, 5, 'la_cell', obj.query.loanAmount.display);
	if (obj.rate.comment == null) {
	  appendCell(row, 6, 'rate_cell', obj.rate.display);
	} else {
	  appendCell(row, 6, 'comment_cell',
		     "<i>" + obj.rate.display + "</i><br/>" + obj.rate.comment);
	}
        var actions = appendCell(row, 7, 'actions_cell');
        appendAnchor(actions, 'remove', 'remove this row', 'return removeRow(event)');
        appendAnchor(actions, 'up', 'move this row up', 'return raiseRow(event)');
        appendAnchor(actions, 'down', 'move this row down', 'return lowerRow(event)');
        updateAnchors(tbody);
        show(table);
      }
    }
  };

  mysack.runAJAX();
}

function calculateClick(event) {
  // Catch exceptions so that this method always returns false and the
  // browser does not submit the form on its own.
  try {
    calculateRate();
  } catch (e) {
    alert('Unable to calculate rate: ' + e.message + ' (' + e.name + ')');
  }
  event.preventDefault();
  event.returnValue=false;
  return false;
}
