(function($) {
    $.fn.shuffler = function(options) {
        var defaults = {
            container: '#shuffler',
            prevBtnSrc: 'prev.png',
            nextBtnSrc: 'next.png',
            prevBtnId: 'prev-btn',
            nextBtnId: 'next-btn',
            prevNextContainerClass: 'prev-next',
            delay: 2500,
            animationDuration: 700
        };
        var opts = $.extend(defaults, options);

        return this.each(function() {
            //set up variables
            var $shuffler = $(this).find('ul:first'),
            shufflerWidth = $shuffler.outerWidth(),
            shufflerHeight = $shuffler.outerHeight(),
            $prevNextContainer = $('<div />').addClass(opts.prevNextContainerClass),
            $prevImg = $('<img />').attr({
                src: opts.prevBtnSrc,
                alt: 'Previous',
                id: opts.prevBtnId
            }),
            $nextImg = $('<img />').attr({
                src: opts.nextBtnSrc,
                alt: 'Next',
                id: opts.nextBtnId
            });

            //append previous and next buttons
            $prevNextContainer.append($prevImg).append($nextImg)
                .insertAfter($shuffler);

            //resize the shuffler and append the first li
            var $listElms = $shuffler.find('li'),
                listElmWidth = shufflerWidth;
            $listElms.css({
                'float': 'left'
            });

            $listElms.clone().prependTo($shuffler);
            var numListElms = $listElms.length;
            $shuffler.css('left', -numListElms * listElmWidth + 'px');
            shufflerWidth *= (numListElms * 2);
            $shuffler.width(shufflerWidth);

            //animate the shuffler
            var interval = setInterval(function() {
                scrollTo('-=');
            }, opts.delay);

            var scrollTo = function(direction) {
                
                if($shuffler.css('left') === '0px') {
                    $shuffler.css('left', -(numListElms * listElmWidth) + 'px');
                } else if ($shuffler.css('left') === ( (-(2 * numListElms * listElmWidth) + listElmWidth) + 'px')) {
                    $shuffler.css('left', -(listElmWidth * (numListElms - 1)) + 'px');
                }
                                
                $shuffler.animate({
                    left: direction + listElmWidth + 'px'
                }, opts.animationDuration);
            }

            //give control to user when next / prev buttons are clicked

            $nextImg.click(function() {
                clearInterval(interval);
                $shuffler.stop(true, true);
                scrollTo('-=');
            });
            $prevImg.click(function() {
                clearInterval(interval);
                $shuffler.stop(true, true);
                scrollTo('+=');
            });
        });
    }
})(jQuery);