(function($) {
  $.fn.accessibleScroller = function(options) {
    var settings = {
      interval: 150,
      paddingBetweenItems: 30,
      pause: undefined,
      play: undefined,
      step: 5
    };
    $.extend(settings, options);

    var isPlaying = false;
    var scrollerJelt = $(this);
    var scrollerListJelt = $('ul', this);
    var divWidth = scrollerJelt.width();
    var listWidth = 0;
    var timeoutId;
    var xEnd;
    var xPos;

    function playScroller() {
      if (!isPlaying) {
        isPlaying = true;
        startScroller();
      }
    }

    function pauseScroller() {
      if (isPlaying) {
        isPlaying = false;
        clearTimeout(timeoutId);
      }
    }

    function startScroller() {
      function doAnimation() {
        xPos -= settings.step;

        // reset position once scroller has completed going from right to left
        if (xPos < xEnd) {
          xPos = divWidth;
        }

        scrollerListJelt.css('left', xPos + 'px');

        timeoutId = setTimeout(doAnimation, settings.interval);
      }

      timeoutId = setTimeout(doAnimation, settings.interval);
    }

    // bind play & pause elements if they exist
    if (settings.play) $(settings.play).click(playScroller);
    if (settings.pause) $(settings.pause).click(pauseScroller);

    // set element styles
    // if you hover over the scroller, it should stop and once mouseout, it should continue scrolling
    scrollerJelt.css({
      'margin': 0,
      'overflow': 'hidden',
      'position': 'relative',
      'white-space': 'nowrap'
    }).hover(function() {
      if (isPlaying) {
        clearTimeout(timeoutId);
      }
    }, function() {
      if (isPlaying) {
        startScroller();
      }
    });
    scrollerListJelt.css({
      'left': divWidth + 'px',
      'padding-left': 0,
      'text-indent': 0,
      'position': 'relative'
    });

    // set LI styles & get widths to find out total ticker width
    $('li', scrollerListJelt).css({
        'display': 'inline',
        'padding-right': settings.paddingBetweenItems + 'px'
    }).each(function(key, value) {
      listWidth += $(value).outerWidth(true);
    });
    xEnd = listWidth * -1;

    xPos = divWidth;
    playScroller();
  }
})(jQuery);
