var EventForm = Class.create({
  initialize: function(prices, existingMembership, eventId) {
    this.tbody = $('invoice');
    this.form = $('new_registration');
    this.memberNumber = $('member_member_number');
    this.memberEmail = $('member_email');
    this.memberId = $('registration_member_id');
    this.donation = $('financial_transaction_donation');
    this.scholarshipFund = $('financial_transaction_scholarship_fund_100');
    this.noScholarshipFund = $('financial_transaction_scholarship_fund_000');
    this.greenhouseSubscription = $('financial_transaction_greenhouse_subscription_1500');
    this.noGreenhouseSubscription = $('financial_transaction_greenhouse_subscription_000');
    
    this.registrationTypes = $$('.registration-types input[type=radio]');
    this.registrationTypeHidden = $$('.registration-types input[type=hidden]')[0];

    this.primaryAttendee = $('registration_attendees_attributes_primary__delete');
    if (this.primaryAttendee) {
      this.primaryAttendeeRow = $('primary_attendee');
      this.primaryAttendeeName = this.primaryAttendeeRow.down('input[type=text]');
      this.primaryAttendeePrice = $('primary_attendee_price');
    }

    this.spouseAttendee = $('registration_attendees_attributes_spouse__delete');
    if (this.spouseAttendee) {
      this.spouseAttendeeRow = $('spouse_attendee');
      this.spouseAttendeeName = this.spouseAttendeeRow.down('input[type=text]');
    }

    this.attendees = $('attendees');
    this.newAttendeeButton = $('new_attendee_button');
    this.attendeePrototype = $$('#attendee_prototype tr')[0];

    this.relatedOffers = $('related_offers');
    this.relatedOfferFields = $$('#related_offers input');

    this.paymentFields = $('payment_fields');
    this.noPayment = $('no_payment');

    this.eventId = eventId;
    this.memberByExistingMembership = existingMembership;
    this.prices = prices;
    this.addListeners();
    this.setupInitialState();
  },
  setupInitialState: function() {
    this.updateMembership();
    if (this.registrationTypeHidden) {
      this.registrationTypeId = this.registrationTypeHidden.value;
      this.registrationType = this.registrationTypeHidden.next('label').innerHTML;
      this.updatePrimaryAttendeePrice();
    }
    if (this.attendees)
      this.updatePrimaryAttendee();
    else
      this.updateLineItems();
  },
  addListeners: function() {
    [this.memberNumber, this.memberEmail].each(function(field) {
      if (field)
        field.observe('blur', this.updateMember.bind(this));
    }, this);

    if (this.donation) {
      this.donation.observe('keyup', this.updateDonation.bind(this));
      [this.scholarshipFund, this.noScholarshipFund, this.greenhouseSubscription, this.noGreenhouseSubscription].each(function(checkbox) {
        checkbox.observe('click', this.updateLineItems.bind(this));
      }, this);
    }
    
    this.registrationTypes.each(function(radio) {
      radio.observe('click', this.updateRegistrationType.bind(this));
    }, this);
    
    if (this.attendees) {
      this.primaryAttendee.observe('click', this.updatePrimaryAttendee.bind(this));
      this.spouseAttendee.observe('click', this.updateSpouseAttendee.bind(this));
      this.newAttendeeButton.observe('click', this.addAttendee.bind(this));
    }

    this.relatedOfferFields.each(function(field) {
      field.observe('keyup', this.updateLineItems.bind(this));
    }, this);
  },
  updateMember: function() {
    var url = '/events/' + this.eventId + '/check_member';
    var parameters = {member_number: this.memberNumber.value, member_email: this.memberEmail.value};
    new Ajax.Request(url, {method: 'get', parameters: parameters, asynchronous: true, evalJSON: 'force', onComplete: function(transport) {
      this.memberByExistingMembership = transport.responseJSON.active;
      this.memberId.value = transport.responseJSON.member_id || '';
      this.updateMembership();
    }.bind(this)});
  },
  updateDonation: function() {
    ensureInteger(this.donation);
    this.memberByDonation = parseInt(this.donation.value) > 0;
    this.updateMembership();
  },
  updateMembership: function() {
    this.member = this.memberByDonation || this.memberByExistingMembership;
    this.updatePrimaryAttendeePrice();
    this.updateLineItems();
  },
  updateRegistrationType: function() {
    var radio = this.registrationTypes.detect(function(radio) {return radio.checked || radio.type == 'hidden';});
    this.registrationTypeId = radio.value;
    this.registrationType = radio.next('label').innerHTML;
    this.updatePrimaryAttendeePrice();
    this.updateLineItems();
  },
  updatePrimaryAttendeePrice: function() {
    if (!this.registrationType || !this.primaryAttendeePrice) return;
    this.primaryAttendeePrice.update('$' + this.registrationPrice().toFixed(2));
  },
  updatePrimaryAttendee: function() {
    if (!this.attendees) return;
    if (this.primaryAttendee.checked) {
      this.primaryAttendeeRow.removeClassName('disabled');
      this.primaryAttendeeName.disabled = false;
      this.spouseAttendee.disabled = false;
    } else {
      this.primaryAttendeeRow.addClassName('disabled');
      this.primaryAttendeeName.disabled = true;
      this.spouseAttendee.disabled = true;
      this.spouseAttendee.checked = false;
    }
    this.updateSpouseAttendee();
    this.updateLineItems();
  },
  updateSpouseAttendee: function() {
    if (!this.attendees) return;
    if (this.spouseAttendee.checked) {
      this.spouseAttendeeRow.removeClassName('disabled');
      this.spouseAttendeeName.disabled = false;
    } else {
      this.spouseAttendeeRow.addClassName('disabled');
      this.spouseAttendeeName.disabled = true;
    }
    this.updateLineItems();
  },
  addAttendee: function() {
    var attendeeRow = new Element('tr');
    this.attendees.insert(attendeeRow);
    attendeeRow.update(this.attendeePrototype.innerHTML.gsub('prototype', 'new_attendee_' + this.attendees.rows.length));
    var select = attendeeRow.down('select');
    select.observe('change', this.selectAttendeeType.bind(this, attendeeRow));
    var deleteButton = attendeeRow.down('.delete_button');
    deleteButton.observe('click', this.removeAttendee.bind(this, attendeeRow));
    this.updateLineItems();
  },
  selectAttendeeType: function(row) {
    var select = row.down('select');
    var price = row.down('.price');
    var amount = this.prices.attendee_types[$F(select)];
    price.update(amount == 0.0 ? 'Free' : ('$' + amount.toFixed(2)));
    this.updateLineItems();
  },
  removeAttendee: function(row) {
    var select = row.down('select');
    if ($(select.id.replace('attendee_type_id', 'id')))
      this.form.insert(new Element('input', {type: 'hidden', name: select.name.replace('attendee_type_id', '_delete'), value: '1'}));
    row.remove();
    this.updateLineItems();
  },
  registrationPrice: function() {
    return this.prices.registration_types[this.registrationTypeId][this.member ? 'member' : 'nonmember'];
  },
  updateLineItems: function() {
    if (!this.tbody) return;
    this.total = 0;
    this.tbody.update('');
    if (this.donation && parseInt(this.donation.value) > 0)
      this.lineItem("Donation", parseInt(this.donation.value));
    if (this.scholarshipFund && this.scholarshipFund.checked)
      this.lineItem("Scholarship Fund", 1);
    if (this.greenhouseSubscription && this.greenhouseSubscription.checked)
      this.lineItem("Greenhouse Subscription", 15);
    if (this.primaryAttendee && this.primaryAttendee.checked && this.registrationType)
      this.lineItem(this.registrationType + ' (' + this.prices.price_level + ' ' + (this.member ? 'member' : 'non-member') + ' price)', this.registrationPrice());

    for (var type in this.prices.attendee_types) {
      var selects = this.attendees.select('select').select(function(select) {return $F(select) == type});
      var quantity = selects.length;
      if (quantity > 0)
        this.quantityLineItem(selects[0].options[selects[0].selectedIndex].innerHTML, this.prices.attendee_types[type], quantity);
    }

    if (this.relatedOffers) {
      $A(this.relatedOffers.rows).each(function(row) {
        var input = $(row).down('input[type=text]');
        ensureInteger(input);
        if (parseInt(input.value) > 0)
          this.quantityLineItem(row.cells[0].innerHTML, parseFloat(row.cells[1].innerHTML.replace('$', '').replace('Free', '0')), parseInt(input.value));
      }, this);
    }

    this.tbody.insert("<tr class='total'><td>Total</td><td></td><td></td><td>$" + this.total.toFixed(2) + "</td></tr>");
    
    if (this.total > 0) {
      this.paymentFields.show();
      this.noPayment.hide();
    } else {
      this.paymentFields.hide();
      this.noPayment.show();
    }
  },
  lineItem: function(category, amount) {
    this.total += amount;
    this.tbody.insert("<tr><td>" + category + "</td><td>$" + amount.toFixed(2) + "</td><td>1</td><td>$" + amount.toFixed(2) + "</td></tr>");
  },
  quantityLineItem: function(category, unit_price, quantity) {
    var amount = unit_price * quantity;
    this.total += amount;
    this.tbody.insert("<tr><td>" + category + "</td><td>$" + unit_price.toFixed(2) + "</td><td>" + quantity + "</td><td>$" + amount.toFixed(2) + "</td></tr>");
  }
});