/*
 * class: infiniteCarousel-item     : scroll items
 *        infiniteCarousel-pages    : scroll page
 *        infiniteCarousel-direct   : direct jump to item
 *
 *        property 'rel': auto scroll time
 */

(function () {
    function repeat(str, n) {
        return new Array( n + 1).join(str);
    }

    //direct: in direct mode, only one item, ignore pages
    //paged: true, false; rotate one item or by page
    $.fn.infiniteCarousel = function (direct, paged) {
        return this.each(function () {
            var container = this;
            var $wrapper = $('> div', this).css('overflow', 'hidden');
            var $slider = $wrapper.find('> ul').width(9000);
            var $items = $slider.find('> li');
            var $single = $items.filter(':first');

            var singleWidth = $single.outerWidth();
            var itemsVisible = Math.ceil($wrapper.innerWidth() / singleWidth);

            var currentItem = 1;
            var totalItems = $items.length;

            var scrollFactor = 1;

            var pages = Math.ceil($items.length / itemsVisible);

            var timer = null;

            var sTime = 0;

            var t = $(this).attr("rel");
            if (t) {
                sTime = parseFloat(t) * 1000;
            }


            /* TASKS */

            //1. pad pages with elements if required
            if(direct == false && paged == true && $items.length % itemsVisible != 0) {
                //pad
                $slider.append(repeat('<li class="promoitem-empty" />', itemsVisible - ($items.length % itemsVisible)));
                $items = $slider.find('> li');
                totalItems = $items.length;
            }

            if (direct == false && paged == true) {
                scrollFactor = itemsVisible;
            }

            //2. create carousel padding on left and right (cloned items)
            $items.filter(':first').before($items.slice(-itemsVisible).clone().addClass('cloned'));
            $items.filter(':last').after($items.slice(0, itemsVisible).clone().addClass('cloned'));
            $items = $slider.find('> li');

            //3. reset scroll
            $wrapper.scrollLeft(singleWidth * itemsVisible);

            //4. scrolling function
            function gotoItem(item) {
                var dir = item < currentItem ? -1 : 1;
                var n = Math.abs(currentItem - item);
                var left = singleWidth * dir * n;
                $wrapper.filter(':not(:animated)').animate({
                    scrollLeft : '+=' + left
                }, 500, function () {
                    //if page == last page - then reset position
                    if (item > totalItems) {
                        $wrapper.scrollLeft(singleWidth * itemsVisible);
                        item = 1;
                    } else if (item == 1 - itemsVisible) {
                        item = totalItems - itemsVisible + 1;
                        $wrapper.scrollLeft(singleWidth * totalItems);
                    }
                    currentItem = item;

                    if (direct == true) {
                        $('.item-current', container).attr('class','item-others');
                        $('[alt=' + currentItem + ']', container).attr('class','item-current');
                    }
                });

            }

            if (direct == true) {
                //5. insert shorcuts
                //var idx = 0;
                var links = '<div class="direct-links">';
                for (idx = 1; idx <= totalItems; idx++) {
                    links += '<a href="#" alt="' + idx + '" class="item-others">' + idx + '</a>';
                }
                links += '</div>';
                $wrapper.after(links);

                for (idx = 1; idx <= totalItems; idx++) {
                    $('[alt='+idx+']', this).click(function (){
                        resetTimeAndGotoItem(parseInt($(this).attr("alt")));
                        return false;
                  });
                }
                $('[alt=' + currentItem + ']', container).attr('class','item-current');
            } else {
                //5. insert back/fwd links
                $wrapper.before('<a href="#" id="discounts-previous" class="prev">Anterior</a> <a href="#" id="discounts-next" class="next">Próximo</a>');

                //6. bind back/fwd links
                $('a.prev', this).click(function (){
                    gotoItem(currentItem - scrollFactor);
                    return false;
                });
                $('a.next', this).click(function (){
                    gotoItem(currentItem + scrollFactor);
                    return false;
                });
            }

            if (sTime > 0) {
                /*
                //stop when mouse over
                $(this).hover(function() {
                    stopAutoScroll();
                }, function() {
                    startAutoScroll();
                });
                */

                startAutoScroll();
            }


            function resetTimeAndGotoItem(item) {
                stopAutoScroll();
                gotoItem(item);
                startAutoScroll();
            }

            function scrollWithTime() {
                if (timer != null) {
                    gotoItem(currentItem + scrollFactor);

                    timer = setTimeout(function() {
                        scrollWithTime();
                    }, sTime);
                }
            }

            function startAutoScroll() {
                if (timer == null) {
                    timer = setTimeout(function() {
                        scrollWithTime();
                    }, sTime);
                }
            }
            function stopAutoScroll() {
                if (timer != null) {
                    clearTimeout(timer);
                    timer = null;
                }
            }

        });
    };
})(jQuery);

$(document).ready(function () {
    $('div.infiniteCarousel-item').infiniteCarousel(false, false);
});
$(document).ready(function () {
    $('div.infiniteCarousel-pages').infiniteCarousel(false, true);
});
$(document).ready(function () {
    $('div.infiniteCarousel-direct').infiniteCarousel(true, false);
});

