// Order information
tkts.order = {};

//
// ORDER
//
// Represents an order.
tkts.order.Order = function(payment_method) {
  this.clearPerformance();
  this.first_name = null;
  this.last_name = null;
  this.email = null;
  this.aid = null;
  this.phone = null;
  this.seats = [];
  this.payment_method = payment_method;
};

// Convert the order to JSON
tkts.order.Order.prototype.json = function() {
  var data;
  if (!this.valid()) {
    data = {
      type: 'error'
    };
  } else {
    data = {
      type: 'order',
      comments: this.comments,
      first_name: this.first_name,
      last_name: this.last_name,
      email: this.email,
      aid: this.aid,
      phone: this.phone,
      performance: this.performance.id,
      section: this.section.id,
      seats: this.seats,
      payment_method: this.payment_method,
      tickets: this.tickets };
  }
  return Object.toJSON(data);
};

// Check if the order is valid
tkts.order.Order.prototype.valid = function() {
  if (!this.performance) {
    return false;
  }
  if (!this.first_name || !this.last_name || !this.email || !this.phone) {
    return false;
  }
  if (this.aid == 0) {
    return false;
  }
  if (!this.tickets || !this.count || this.count <= 0) {
    return false;
  }
  if (!this.isSeatingValid()) {
    return false;
  }
  return true;
};

// Return true if the seating is valid.
tkts.order.Order.prototype.isSeatingValid = function() {
  if (!this.section) {
    return false;
  }
  if (this.count > this.section.available) {
    return false;
  }
  if (this.seats.length != this.count) {
    return false;
  }
  // Validate that there is a seat selected.
  return this.seats.length > 0;
};

// Clear the performance
tkts.order.Order.prototype.clearPerformance = function() {
  this.performance = null;
  this.clearSection();
};

// Clear the selection
tkts.order.Order.prototype.clearSection = function() {
  this.section = null;
  this.tickets = null;
  this.count = 0;
};

// Reset an order using the new show information
//   show: the show information
tkts.order.Order.prototype.reset = function(show) {
  if (this.performance) {
    this.performance = show.findPerformance(this.performance.id);
    if (this.performance && this.section) {
      this.section = show.findSection(this.performance, this.section.id);
      if (!this.section) {
        this.clearSection();
      }
    }
    return;
  }
  this.clearPerformance();
};

