/*
 	@title jSimpleCarosel
	@autor hp-stuff
	
	<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;
		btnPrve : '.prev'					//only selector for element or real DOM element;
	});
	
	#Example 2:
	$('.carousel ul').simpleCarousel({
		btnNext : '.next',					
		btnPrve : '.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',					
		btnPrve : '.prev',
		beforeStart : function(){			//function before start animation;
			//inset code
		}	
		afterFinish : function(){			//function after finish animation;
			//inset code
		}			
	});
*/
(function ($) {
    $.fn.simpleCarousel = function (options) {
        return this.each(function () {
            var obj = $(this),
				carouselEvent = options.event ? options.event : 'click',
				items = options.item ? $(this).find(options.item) : $(this).children(),
				itemWidth = options.itemWidth ? options.itemWidth : itemWidth(),
				visibles = options.visibles ? options.visibles : 1,
				itemsLength = items.length,
				index = 0,
                itemsCount = 5,
                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><a href="#"></a></li>',
				speed = options.speed ? options.speed : 300,
				afterFinish = options.afterFinish ? options.afterFinish : function () { },
				beforeStart = options.beforeStart ? options.beforeStart : function () { };


            check();
            createNavigation();

            function check() {
                if (itemsLength < visibles) {
                    $(btnNext).hide();
                    $(btnPrev).hide();
                    $(navigation).hide();
                }
            }

            function createNavigation() { 
                var navItems, i = 1;
                navItems = itemsLength / visibles;
				
                while (i < navItems) { 
                    $(navigation).append(itemsHTML);
                    i++;
                }
            }

            $(navigation).find('a').each(function (i, el) {
                $(el).click(function () {
                    index = 0;
                    stopInterval();
                    if (visibles * i > itemsLength - visibles) {
                        index = itemsLength - visibles;
                        carouselMoveCircle(++index);
                    } else {
                        index = visibles * i;
                        carouselMoveCircle(++index);
                    }
                    return false;
                });
            });

            function itemWidth() {
                var width = items.width() + parseInt(items.css('margin-left')) + parseInt(items.css('margin-right')) + parseInt(items.css('border-right-width')) + parseInt(items.css('border-left-width'));
                return width;
            }


            if (circle) {
                $(items[0]).before(items.last().clone());
                items.last().after(items.first().clone());
                obj.css({ 'left': -itemWidth + 'px' });
                index = 1;
                obj.css({ 'width': itemWidth * itemsLength + (itemWidth * 2) + 'px' });

                $(btnNext).bind(carouselEvent, function () {



                    if (!$(obj.children()[index]).next().length) {
                        index = 1;
                        obj.css({ 'left': -itemWidth + 'px' });
                    }

                    index++;
                    stopInterval();
                    carouselMoveCircle(index);

                    return false;
                });

                $(btnPrev).bind(carouselEvent, function () {

                    if (!$(obj.children()[index]).prev().length) {
                        index = itemsLength;
                        obj.css({ 'left': -itemsLength * itemWidth + 'px' });
                    }

                    index--;
                    stopInterval();
                    carouselMoveCircle(index);

                    return false;
                });

                function carouselMoveCircle(currenItems) {
                    var index = currenItems == 0 ? 1 : currenItems;
                    var item_index = currenItems - 1 == itemsCount ? 0 : currenItems - 1 < 0 ? itemsLength - 1 : currenItems - 1;
                    beforeStart(item_index, items[item_index]);
                    obj.stop(true).animate({ 'left': -(currenItems * itemWidth) + 'px' }, speed, function () {
                        afterFinish(item_index, items[item_index]);
                        startInterval();
                    });

                    $(navigation).children('.active').removeClass('active');
                    $($(navigation).children('a')[item_index]).addClass('active');
                }

                var interval = "";

                function startInterval() {
                    if (interval == "") {
                        interval = setInterval(function () {
                            if (!$(obj.children()[index]).next().length) {
                                index = 1;
                                obj.css({
                                    'left': -itemWidth + 'px'
                                });
                            }

                            index++;

                            carouselMoveCircle(index);
                        }, autoTime + speed);
                    }
                }

                function stopInterval() {
                    window.clearInterval(interval);
                    interval = "";
                }

                if (auto) {
                    startInterval()
                }

            }
            else {
                obj.css({ 'width': itemWidth * itemsLength + 'px' });
                function carouselMove(currenItems) { 
                    beforeStart(index, obj);
                    obj.stop(true).animate({
                        'left': -(currenItems * (itemWidth * 2)) + 'px'
                    }, speed, function () {
                        afterFinish(index, obj);
                    });
                    $(navigation).children('.active').removeClass('active');
                    $($(navigation).children('a')[index / visibles]).addClass('active');
                }

                $(btnNext).bind(carouselEvent, function () {
                    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);
                        }
                    }
                    return false;
                });

                $(btnPrev).bind(carouselEvent, function () {
                    if (index < visibles) {
                        index = 0;
                        carouselMove(index);
                    }
                    else {
                        if (index > 0) {
                            index = index - visibles;
                            carouselMove(index);
                        }
                    }
                    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);
