/*!
 * @copyright 2011-Present Advanced Care Solutions, Inc.
 * @author Christopher Rahauiser <crahauiser@acs-web.com>
 */
(function($) {
  /**
   * NOTE: The ticker element must have it's width set, as well as the internal
   * content element defined in $.fn.ticker.defaults.tickerContentSelector, or
   * the options object.
   */
  $.fn.ticker = function(options) {
    var opts = $.extend({}, $.fn.ticker.defaults, options);

    return this.each(function() {
      var self = $(this),
          tickerItem = self.find(opts.tickerContentSelector + ':first'),
          contentWidth = tickerItem.width(),
          containerWidth = self.width(),
          cloneAndAnimateLeft = -1 * (contentWidth / opts.cloneAndAnimateLeftDivisor),
          toLeft = -1 * contentWidth;

      var firstTickerItem = tickerItem.clone(true).css('left', containerWidth);
      tickerItem.replaceWith(firstTickerItem);
      firstTickerItem.after(tickerItem.clone(true).css('left', containerWidth));

      function moveTicker(ticker) {
        var createdNewItem = false;
        ticker
          .animate({
            left: toLeft
          }, {
            duration: opts.tickerSpeed,
            easing: 'linear',
            step: function(now, fx) {
              if (! createdNewItem && now <= cloneAndAnimateLeft) {
                createdNewItem = true;

                var newItem =
                    tickerItem
                      .clone(true)
                        .css('left', containerWidth + opts.containerOffset);

                self
                  .find(opts.tickerContentSelector + ':first')
                    .after(newItem);

                moveTicker(newItem);
              }
            },
            complete: function() {
              $(this).remove();
            }
          });
      }
      moveTicker(firstTickerItem);
    });
  };

  $.fn.ticker.defaults = {
    tickerSpeed: 15000,  // Speed of the ticker animation in ms
    containerOffset: 120,  // The offset, in pixels, from the right of the containerWidth to position the starting ticker
    cloneAndAnimateLeftDivisor: 2.85,  // Divide the content width by this to determine when to clone a new ticker item
    tickerContentSelector: '.ticker-content'  // The selector used to retrieve the scrolling content
  };
})(jQuery);
