$(function () {

  var $animSpans = $('div#container > span:not(#contact, #for, #we)');
  $animSpans.each (function () {$(this).flipText ();})

});

$.fn.flipText = function () {
  var $this = $(this);
  //$('div#container').after ($this.css ('top') + 20 + 'px' + ' in ' + $this.attr ('id') + '<br />');
  $this
    .delay (2000 + getRandNum (10000))
    .animate (
      {'left' : '0px'},
      10,
      'linear',
      function () { 
        $this.showNext ();
        $this.flipText ();
      }
    );
}

$.fn.showNext = function () {
  var $this = $(this);
  var $activeItem = $('span.active', this);
  var currentIndex = $activeItem.index ();
  var nextIndex = currentIndex + 1;
  if (nextIndex == $('span', this).length) {
    nextIndex = 0;
  }
  var $nextItem = $($('span', this)[nextIndex]);
  $activeItem.after ($nextItem);
  $nextItem.toggleClass ('active');
  $activeItem.animate (
    {'marginTop' : '-' + $activeItem.outerHeight() },
    500,
    'swing',
    function () { 
      $activeItem
        .toggleClass ('active')
        .removeAttr ('style');
    }
  );
}

function getRandNum (top) {
  return Math.floor (Math.random () * top);
}
