/**
@title jSimpleCarosel
@autor hp-stuff MAG-Studio
	
<div class="carousel">
<ul>
<li></li>
<li></li>
<li></li>
</ul>
</div>
	
#Example 1:
$('.carousel ul').simpleCarousel({
btnNext : '.next',					//only selector for element or real DOM element;
btnPrev : '.prev'					//only selector for element or real DOM element;
});
	
#Example 2:
$('.carousel ul').simpleCarousel({
btnNext : '.next',					
btnPrev : '.prev',
event : 'mouseover',				//manual change button event ('click' by default);  
visible : 2,						//set how visible items have (1 by default);
itemWidth : 90,						//manual set item with use for moving;
speed : 200							//set animation speed (330 by default);					
});
	
#Example 3:
$('.carousel ul').simpleCarousel({
btnNext : '.next',					
btnPrev : '.prev',
beforeStart : function(){			//function before start animation;
//inset code
}	
afterFinish : function(){			//function after finish animation;
//inset code
}			
});
*/
(function ($) {
    $.fn.simpleCarousel = function (options) {
        var obj = $(this),
            carouselEvent = options.event ? options.event : 'click',
            items = options.item ? $(this).find(options.item) : $(this).children(),
            itemWidth = options.itemWidth ? options.itemWidth : getItemWidth(),
            visibles = options.visibles ? options.visibles : 1,
            itemsLength = items.length,
            index = 0,
            easing = options.easing ? options.easing : 'linear',
            animateProparty = options.animateProparty ? options.animateProparty : 'left',
            circle = options.circle ? options.circle : false,
            autoTime = options.autoTime ? options.autoTime : 3000,
            auto = options.auto ? options.auto : false,
            btnNext = options.btnNext ? options.btnNext : null,
            btnPrev = options.btnPrev ? options.btnPrev : null,
            navigation = options.navigation ? options.navigation : null,
            itemsHTML = options.itemsHTML ? options.itemsHTML : 'li',
            speed = options.speed ? options.speed : 300,
            afterFinish = options.afterFinish ? options.afterFinish : function () { },
            beforeStart = options.beforeStart ? options.beforeStart : function () { },
            navigationClickable = options.navigationClickable;

        check();
        
        if (navigation) {
            createNavigation();
        } else {
            navigation = options.controls ? options.controls : null;
        }

        function check() {
            if (itemsLength <= visibles) {
                $(btnNext).hide();
                $(btnPrev).hide();
                if (navigation) {
                    $(navigation).hide();
                }
            }
        }

        function createNavigation() {
            var navItems, i = 0;
            navItems = itemsLength / visibles;

            while (i < navItems) {
                $(navigation).append('<' + (itemsHTML == 'a' ? (itemsHTML + ' href="#"') : itemsHTML) + '>' + (++i) + '</' + itemsHTML + '>');
            }
        }

        if (navigation) {
            $(navigation).find(itemsHTML).each(function (i, el) {
                if (i == 0) $(el).addClass('active');
                if (navigationClickable) {
                    $(el).bind(carouselEvent, function () {
                        index = 0;
                        if (auto) stopInterval();
                        if (visibles * i > itemsLength - visibles) {
                            index = itemsLength - visibles;
                            if (circle) {
                                carouselMoveCircle(++index);
                            } else {
                                carouselMove(index);
                            }
                        }
                        else {
                            index = visibles * i;
                            if (circle) {
                                carouselMoveCircle(++index);
                            } else {
                                carouselMove(index);
                            }
                        }

                        return false;
                    });
                }
            });
        }

        function getItemWidth() {
            var width = items.width() + parseInt(items.css('margin-left')) + parseInt(items.css('margin-right')) + (parseInt(items.css('border-width')) ? parseInt(items.css('border-width')) : 0);
            return width;
        }

        if (circle) {
            var position = {};
            var firstposition = {};
            var lastposition = {};

            $(items[0]).before(items.last().clone());
            items.last().after(items.first().clone());

            position[animateProparty] = -itemWidth + 'px';
            obj.css(position);
            index = 1;

            obj.css({
                'width': itemWidth * itemsLength + (itemWidth * 2) + 'px'
            });

            if (itemsLength > visibles) {

                $(btnNext).bind(carouselEvent, function () {

                    if (auto) {
                        stopInterval();
                    }

                    if (!$(obj.children()[index]).next().length) {
                        index = 1;
                        firstposition[animateProparty] = -itemWidth + 'px';
                        obj.css(firstposition);
                    }

                    index++;
                    carouselMoveCircle(index);
                    return false;
                });

                $(btnPrev).bind(carouselEvent, function () {

                    if (auto) {
                        stopInterval();
                    }

                    if (!$(obj.children()[index]).prev().length) {
                        index = itemsLength;
                        lastposition[animateProparty] = -itemsLength * itemWidth + 'px';
                        obj.css(lastposition);
                    }

                    index--;
                    carouselMoveCircle(index);
                    return false;
                });

                function carouselMoveCircle(currenItems) {
                    // var index = currenItems == 0 ? 1 : currenItems;
                    var item_index = currenItems - 1 == itemsLength ? 0 : currenItems - 1 < 0 ? itemsLength - 1 : currenItems - 1;
                    var animation = {};

                    animation[animateProparty] = -(currenItems * itemWidth) + 'px';
                    beforeStart(item_index, items[item_index]);

                    obj.stop(true).animate(animation, speed, easing, function () {
                        afterFinish(item_index, items[item_index]);
                        if (auto) {
                            startInterval();
                        }
                    });

                    $(navigation).find('.active').removeClass('active');
                    $($(navigation).find(itemsHTML)[item_index]).addClass('active');
                }

                var interval = "";

                function startInterval() {
                    if (interval === "") {
                        interval = setInterval(function () {
                            if (!$(obj.children()[index]).next().length) {
                                index = 1;
                                position = {};
                                position[animateProparty] = -itemWidth + 'px';
                                obj.css(position);
                            }

                            index++;
                            carouselMoveCircle(index);
                        }, autoTime + speed);
                    }
                }

                function stopInterval() {
                    window.clearInterval(interval);
                    interval = "";
                }

                if (auto) {
                    startInterval();
                }
            }
        }
        else {
            obj.css({
                'width': itemWidth * itemsLength + 'px'
            });

            if (index == 0) {
                $(btnPrev).addClass('disable');
            }

            function carouselMove(currenItems) {
                beforeStart(index, obj);
                var animation = {};

                animation[animateProparty] = -(currenItems * itemWidth) + 'px';

                obj.stop(true).animate(animation, speed, easing, function () {
                    afterFinish(index, obj);
                });

                $(navigation).find('.active').removeClass('active');
                $($(navigation).find(itemsHTML)[index / visibles]).addClass('active');
            }

            $(btnNext).bind(carouselEvent, function () {
                $(btnPrev).removeClass('disable');

                if (itemsLength - (index + visibles) < visibles && itemsLength - (index + visibles) > 0) {
                    index = index + (itemsLength - (index + visibles));
                    carouselMove(index);
                }
                else {
                    if (index < itemsLength - visibles) {
                        index = index + visibles;
                        carouselMove(index);
                    }
                }

                if (index + visibles == itemsLength) {
                    $(this).addClass('disable');
                }
                return false;
            });

            $(btnPrev).bind(carouselEvent, function () {
                $(btnNext).removeClass('disable');
                if (index < visibles) {
                    index = 0;
                    carouselMove(index);
                }
                else {
                    if (index > 0) {
                        index = index - visibles;
                        carouselMove(index);
                    }
                }
                if (index == 0) {
                    $(this).addClass('disable');
                }
                return false;
            });


            if (auto) {
                var flag = true;

                setInterval(function () {
                    if (index == 0) {
                        flag = true;
                    }
                    else
                        if (index == itemsLength - visibles) {
                            flag = false;
                        }

                    if (flag) {
                        index = index + visibles;
                        carouselMove(index);
                    }
                    else {
                        index = index - visibles;
                        carouselMove(index);
                    }
                }, autoTime);
            }
        }
    };
})(jQuery);
