/**
 * @author Sébastien Riguet <sebastien.riguet@zebnet.fr>
 */


(function($) { //create closure
    
    // Putting class variables here !
    
    $.fn.zcarousel = function(options) 
    {
        
        slideTo = function() 
        {
            if (isSlideshow) {
                currentI++;
                if (currentI >= slidesNum)
                    currentI = 0
                
                updateButton();
                
                slides.fadeOut(1000).animate({left: "-" +  (currentI * offset) + "px" }, 0 ).fadeIn(1000);
            }
            else {
                clearInterval(slideShowTimer)
            }
        };
        
        updateButton = function() {
            $("#featured-navigate .thumb-navigate a").each(function() {
                if ($(this).attr('id') == currentI) {
                    $(this).fadeTo(500, 1);
                    $(this).removeClass('hidden')
                
                }
                else {
                    $(this).fadeTo(500, 0.3);
                    $(this).addClass('hidden');
                }
            });
        };
        
        jumpTo = function(i) {
            if (currentI == i) return;
            isSlideshow = false;
            currentI = i;
            updateButton();
            slides.stop(true).fadeTo(10, 1)
            slides.fadeOut(200).animate({left: "-" +  (currentI * offset) + "px" }, 0 ).fadeIn(200);
            clearInterval(slideShowTimer)
            slideShowTimer = setInterval("slideTo()", timerLength*2);
            isSlideshow = true;
        };
        
        var slidesNum = $(this).children().length;
        
        if (slidesNum > 0) 
        {
            var slides = $($(this).children()[0]);
            slidesNum = slides.children().length;
            var width = slides.outerWidth("true");
            var height = slides.outerHeight("true");
            var offset = width + 5;
            slides.css('width', offset * slidesNum * 1.1)
            
            slides.css('position', 'absolute')
            $(this).css('overflow-x', 'hidden')
            $(this).css('overflow-y', 'visible')
            $(this).css('position', 'relative')
            var shownInViewport = Math.round($(this).width() / offset);
            var firstElementOnViewPort = 1;
            var isAnimating = false;
            var currentI = 0
            var isSlideshow = true;
            var timerLength = 8000;
            slideShowTimer = setInterval("slideTo()", timerLength);
            
            
            $("#featured-navigate .thumb-navigate a").each(function() {
                // add click functionality to buttons
                $(this).mouseover(function() {
                    jumpTo($(this).attr('id'));
                    return (false);
                }); // click
            }); //each
        }
        updateButton();
        
        return $(this);
    }
})($);
