// First, the jQuery functions, which run when the page loads.
$(function(){

  // Set up our lightbox
  $('a.lightbox').lightBox();

  // Flightbox!!
  $('#closebox').click(function() {
    $('#flightbox').fadeOut("fast");
  });

  // Hide the add-to-cart features for now.
  $('#gift-assemble #addtocart').css('display', 'none');

  // Handle shopping cart
  $('#cupcakes .cake, #frostings .frosting, #sprinkles .sprinkle').draggable({
    ghosting: false,
    opacity: 0.5,
    revert: true,
    helper: 'clone',
    start: function() {
      $('.tooltip').css("display", "none");
    }
  });
  $('#cupcakes .drop').droppable({
    accept: '.cake',
    tolerance: 'pointer',
    drop: dropFunction
  });
  $('#frostings .drop').droppable({
    accept: '.frosting',
    tolerance: 'pointer',
    drop: dropFunction
  });
  $('#sprinkles .drop').droppable({
    accept: '.sprinkle',
    tolerance: 'pointer',
    drop: dropFunction
  });

  // Show tooltips if the cupcake-parts are rolled over.
  $('.cake, .frosting').hover(
    function() {$(this).children('.tooltip').fadeIn('fast');},
    function() {$(this).children('.tooltip').fadeOut('fast');}
  );
  
  $('select#occasion').bind('change', function(event) {
    $('.accessory form #decoration_number').attr("value", $('select#occasion').val());
  });
});

// Group the drop functions here, just do some nice fading.
function dropFunction(ev, ui) {
  ui.draggable.clone().fadeOut("fast", 
  function() {
      $(this).fadeIn("fast");
  }).appendTo($(this).empty());
  updateCount();
  $('.tooltip').css("display", "none");
}

// If they have nine items selected, display the checkout form
// and populate it with the correct PayPal information.
function updateCount() {
  if ($('.ui-droppable > .ui-draggable').size() == $('.ui-droppable').size()) {
    $('#gift-assemble #addtocart').show('normal');
    var checkoutString = '';
    $('.ui-droppable > .ui-draggable').each(function(n) {
      checkoutString += " " + this.id;
    });
    /* get old attribute */
    var oldValue = $('#addtocart').attr("class");
    /* set new attribute */
    $('.hiddenFields input[name=title]').attr("value", oldValue + ": " + checkoutString);
  }
}