/* Database Management Functions */
var dbError = null;
var connectionManager = Packages.DBConnectionManager.getInstance();

function sqlRowSet(connectionName, sqlStatement)
{
  dbError = null;
  var connection = connectionManager.getConnection(connectionName);

  if (connection == null)
  {
    dbError = "Failed to get requested connection: " + connectionName;

    return null;
  }

  var statement = connection.createStatement();

  var resultSet;
  var result = tryEval("resultSet = statement.executeQuery(sqlStatement);");

  if (result.error)
  {
    dbError = result.error.getLocalizedMessage();
    connectionManager.freeConnection(connectionName, connection);

    return null;
  }

  var metaData = resultSet.getMetaData();

  var array = new Array();

  for (var i = 0; resultSet.next(); i++)
  {
    array[i] = new SqlRow(resultSet, metaData);

  }

  statement.close();
  connectionManager.freeConnection(connectionName, connection);

  return array;
}

function SqlRow(resultSet, metaData)
{
  var columnCount = metaData.getColumnCount();

  for (var i = 0; i < columnCount; i++)
  {
    var columnValue = resultSet.getObject(i + 1);
    var columnName = metaData.getColumnName(i + 1).toLowerCase();

    this[columnName] = columnValue;
  }
}

/* General-purpose Utility Functions */
function showErrorPage(theTitle, theMessage)
{
  output.println("<HTML>");
  output.println("  <HEAD>");
  output.println("    <TITLE>" + theTitle + "</TITLE>");
  output.println("  </HEAD>");
  output.println("  <BODY BGCOLOR='#fcefc4'>");
  output.println("    <CENTER>");
  output.println("      <H1 STYLE='color: red'>" + theTitle + "</H1>");
  output.println("    <BR>");
  output.println("    </CENTER>");
  output.println("    <B><PRE>" + theMessage + "</PRE></B>");
  output.println("  </BODY>");
  output.println("<HTML>");

  output.flush();
}

function formatCount(number)
{
  if (number == null)
  {
    return "";
  }

  return java.text.NumberFormat.getNumberInstance().format(number);
}

function formatCurrency(number)
{
  if (number == null)
  {
    return "";
  }

  return java.text.NumberFormat.getCurrencyInstance().format(new Number(number));
}

function formatPercentage(number)
{
  if (number == null)
  {
    return "";
  }

  return (new java.text.DecimalFormat("###.##%")).format(new Number(number));
}

function formatDate(date, format)
{
  if (date == null)
  {
    return "";
  }

  if (format == null)
  {
    format = "MM/dd/yyyy hh:ss";
  }

  var formatter = new java.text.SimpleDateFormat(format);
  formatter.setTimeZone(java.util.TimeZone.getDefault());

  return formatter.format(date);
}

function sleep(milliSeconds)
{
  java.lang.Thread.currentThread().sleep(milliSeconds);
}
