/*
 * Provides a nice interface for adding/removing event attendees.
 * NOTE: There is a JS var called 'price' that gets initialized in app/views/events/register.html.haml.
 * christianbryan@gmail.com
 */

var attendees = 1;

/* Register event handlers. */
$(document).ready(function() {
  $('#add-new-attendee').click(function() {
    create_new_attendee();
  });
  
  $("#event_registration_free_tickets").change(function() {
    update_totals();
  });
  
  attendees = $('#tickets').val();
  update_totals();
})

/* Creates and inserts the form field for adding a new attendee. */
function create_new_attendee() {
  $('#attendees').append("<li id='attendee" + attendees + "'><input  name='attendees[" + attendees + "]' type='text' value='Attendee Name' /><a href='' onclick='remove_attendee(" + attendees + "); return false;'>Remove</a></li>");
  attendees++;
  update_totals();
}

/* Removes an attendee field and list element. */
function remove_attendee(attendee_id) {
  $('#attendee' + attendee_id).remove();
  attendees--;
  update_totals();
}

/* Updates ticket totals and recalculates price. */
function update_totals() {
  var free_tickets = $("#event_registration_free_tickets").val();
  
  if (free_tickets == null) {
    var total = price * attendees;
  } else {
    if (free_tickets > attendees) {
      var total = 0;
    } else {
      var total = (price * (attendees - free_tickets));  
    }
  }
  
  console.log("There are currently " + attendees + " attendees.");
  $('#tickets').val(attendees)
  $('#total_price').html(total.toFixed(2));
}
