(function($) {
    $.fn.bannerScroller = function(options) {
        return this.each(function(){
            var settings = $.extend({}, $.fn.bannerScroller.defaults, options || {});
            var $this = $(this);
            var id = $this.attr('id');

            $.fn.bannerScroller.settings[id] = settings;

            var items    = $this.find('.scroller-items .item');
            var interval = setInterval(function(){
                $.fn.bannerScroller.selectNext(id);
            }, 3000);

            if (items.length) {
                $this.find('.scroller-items').width(548 * items.length);

                var controlsContainer = $this.find('.scroller-controls .inner');
                for (i=0; i<items.length; i++) {
                    controlsContainer.append('<div class="control">');
                }

                $.fn.bannerScroller.select(id, 0, true);

                $('.scroller-controls .control').mouseover(function(){
                    clearInterval(interval);

                    var index = $('.scroller-controls .control').index(this);
                    $.fn.bannerScroller.select(id, index);
                });
            }
        });
    };

    $.fn.bannerScroller.defaults = {
        changeFreq: 3
    };

    $.fn.bannerScroller.settings = {};

    $.fn.bannerScroller.select = function(id, index) {
        var settings = $.fn.bannerScroller.settings[id];
        var $this = $('#' + id);

        $this.find('.scroller-items').animate({left: -(548 * index)}, {queue: false});

        $($this.find('.scroller-controls .control')
               .removeClass('active')
               .get(index))
               .addClass('active');
    };

    $.fn.bannerScroller.selectNext = function(id) {
        var settings = $.fn.bannerScroller.settings[id];
        var $this = $('#' + id);

        var items   = $this.find('.scroller-items .item');
        var current = $('.scroller-controls .control')
            .index($('.scroller-controls .control.active'));
        var next    = 0;

        if (current < (items.length - 1)) {
            next = current + 1;
        }

        $.fn.bannerScroller.select(id, next);
    };
})(jQuery);
