// AJAX callback - replace timeslot selection contents with new slots
function replaceslots(data) {
  $('#slotlist').html(data);
  // When a timeslot is selected, show the number of places selector
  $("input[name='slot']").click(function() {
    if ($("input[name='slot']:checked").val()) {
      $('#placeselect').fadeIn(200);
    }
  });

  if (window.isie6) {
    $('#slotselect label').click(function(ev) {
      $('input', this).click();
      event.stopPropagation();
    });
  }
  
}
function updatetimeslots(date) {
  var slist = $('#slotlist');
  var slots = $.get('timeslots.php', {date: date}, replaceslots);
}

// Onload actions
$(document).ready(function() {
  // Hide various bits of the UI
  $('.defaulthidden').hide();

  // When a new day is selected, update the timeslot list
  $('#day').change( function() {
   updatetimeslots($(this).val());
   $('.defaulthidden').fadeOut(100);
   $('#places').val('');

   if ($('#day').val()) {
     $('#slotselect').fadeIn(200);
   }
  });

  // When a number of places is chosen, show the details form
  $('#places').change(function() {
    if ($(this).val()) {
      $('#detailtitle, #detailform').fadeIn(200);
    } else {
      $('#detailtitle, #detailform').fadeOut(100);
    }
  });

  // Callback to handle successful AJAX requests
  function handleBooking(data, textstatus) {
   var result = $.parseJSON(data, true);
   if (!(result instanceof Object)) {
     do_error('Sorry, but an error occurred processing your booking. Please try again later.');
     return;
   } 

   if (result['status'] == 0) {
     window.location = "booked.php?c=" + result.code;
   }
   if (result['status'] == 1) {
     do_error(result['message']);
   }
   if (result['status'] == 3) {
     do_error(result['message']);
   } 
  }

  function handleBookingError(xhr, err, e) {

  }

  function hideerror() {
    $('#error').fadeOut(100);
    return false;
  }

  // Generic error notifier
  function do_error(text) {
     $('#error').html('<span>' + text + '</span> <div class="errorlink"><a href="#" class="errorclose">Close</a></div>');
     $('#error .errorclose').click(function() {
        hideerror();
        return false;
     });
     $('#error').fadeIn(200);
  }


  // Form submission - AJAX it instead of full submission.
  $('#bookingform').submit(function() {
    $.ajax({
      type: "post",
      data: $(this).serialize(),
      success: handleBooking,
      error: handleBookingError,
      url: $(this).attr('action')
    });
    return false;
  });

});

