// animation.js
// Requires prototype + scriptaculous
//---------------------------------------------------------------------------
var animate = function(source, destination, fly_options) { 
  source = $(source);
  destination = $(destination);
  var animation;  // The element to be animationated as flying.
  var offset = destination.cumulativeOffset();

  // Stash the requested on-complete handler.  We first remove it from the incoming options,
  var after_finish = fly_options.fly.afterFinish;
  delete fly_options.fly.afterFinish;
  
  var options = {                           // The options to be defined.
    content:    source.textContent,
    id:         'rand_' + Math.random() * 5000000,
    fade:       Object.extend( {
      // These are positioned in descending order of likelihood anyone would want to override them in incoming args.
      duration:       0.15,
      beforeStart:    function() { animation.show() },
      from:           0,  
      to:             1,  
      queue:          "end"
    }, fly_options.fade),                   // Override these defaults as requested by caller.
    fly:        Object.extend( {
      duration:       0.3,
      afterFinish:    function(e) { animation.remove(); if (after_finish) { after_finish(e); } }, // Chain into the requested on-complete handler.
      transition:     function(position) { return Math.pow(position, 5); },
      y:              offset.top + destination.getHeight() / 2, 
      x:              offset.left, 
      queue:          "end",
      mode:           "absolute"
    }, fly_options.fly)                     // Override these defaults as requested by caller.
  }   
  delete fly_options.fly;                   // These have already been incorporated.
  delete fly_options.fade;                  // Into the options structure above.

  Object.extend(options, fly_options);      // Override with options passed in.

  // Add some basic styling of our own, so that things can 'just work'.
  options.style += ';display:none;position:absolute;'

  // Clone the content from the source element into a new item.
  $(document.body).insert('<div id="' + options.id + '" style="' + options.style + '">' + options.content + '</div>');
  animation = $(options.id);

  animation.clonePosition(source);
  animation.setOpacity(0);

  // Okay, everything is all set.  Create the animationations back to back, and let 'er rip.
  new Effect.Opacity(animation, options.fade);
  new Effect.Move(animation, options.fly);
}
