var InvoiceTable = Class.create({
  initialize: function(invoice) {
    this.invoice = $(invoice);
    this.recalculate();
  },
  recalculate: function() {
    this.invoice.update('');
    this.total = 0.0;
    this.updateDonation();
    this.updateScholarshipFund();
    this.updateGreenhouseSubscriptionFee();
    this.updateTotal();
  },
  updateGreenhouseSubscriptionFee: function() {
    if ($("financial_transaction_greenhouse_subscription_1500").checked)
      this.insertRow("Greenhouse Subscription", 15);
  },
  updateTotal: function() {
    if (this.total < 1 && this.total > 0)
      this.disableCreditCard();
    else
      this.enableCreditCard();
    if (this.total > 0)
      this.insertRow("Total", this.total, true);
  },
  updateScholarshipFund: function() {
    if ($("financial_transaction_scholarship_fund_100").checked)
      this.insertRow("Scholarship Fund", 1);
  },
  updateDonation: function() {
    var donationField = $('financial_transaction_donation');
    ensureInteger(donationField);
    if (parseInt(donationField.value) > 0)
      this.insertRow("Donation", parseInt(donationField.value));
  },
  insertRow: function(label, amount, total) {
    this.total += amount;
    var row = new Element("tr", {className: total ? 'total' : ''});
    row.insert(new Element("th").update(label + ":"));
    row.insert(new Element("td").update("$" + amount.toFixed(2)));
    this.invoice.insert(row);
  },
  disableCreditCard: function() {
    if (!$("financial_transaction_payment_type_credit_card")) return;
    console.log("disabled: " + this.total)
    $("financial_transaction_payment_type_credit_card").setAttribute('disabled', 'disabled');
    $("financial_transaction_payment_type_credit_card").checked = false;
    $("credit_card").hide();
  },
  enableCreditCard: function() {
    if (!$("financial_transaction_payment_type_credit_card")) return;
    console.log("enabled: " + this.total)
    
    $("financial_transaction_payment_type_credit_card").removeAttribute('disabled');
  }
})
