// CAROUSEL HELPERS

// Called to init carousel in carousel_frame.tpl
function setUpCarousel() {
    var carousel_cookie_id = 'ut_carousel_scroll_position';
    var carousel_items = jQuery('.carousel .content div');
    // Calculate content item count
    var itemCount = carousel_items.length;
    // Calculate content size
    var totalWidth = 0;
    carousel_items.each(function() {
        totalWidth += jQuery(this).outerWidth();
    });
    //alert("TOT: "+totalWidth+" NUM: "+itemCount);
    var itemWidth = totalWidth / itemCount;
    // Set speed and batch
    var tempo = "slow";
    var ease = "swing";
    var batchSize = 4;
    var animSize = Math.round(batchSize * itemWidth);
    var index = 0;
    var inMovement = false;
    var nextButton = jQuery('.carousel .next');
    var prevButton = jQuery('.carousel .prev');
    function fixPosition(p) {
        return Math.min(Math.max(p, 0), itemCount - batchSize)
    }
    function scrollToItem(raw) {
        var idx = fixPosition(raw);
        
        if ((idx < 0) || (idx > (itemCount - batchSize))) return;
        if (inMovement) return;
        
        var moveDistance = 0;
        var ct = 0;
        carousel_items.each(function() {
            if (ct < idx) {
                var w = jQuery(this).outerWidth();
                moveDistance += w;
                ct++;
            }
        });
        inMovement = true;
        prevButton.addClass('disabled');
        nextButton.addClass('disabled');
        //alert("NEW IDX "+idx + " FROM "+index+"takes "+moveDistance+"pixels");
        jQuery('.carousel .content').animate( {
            "left" : "-" + moveDistance + "px"
        }, tempo, ease, function() {
            inMovement = false;
            index = idx;
            // Disable handles that should not work
                if (index > 0) prevButton.removeClass('disabled');
                if (index < (itemCount - batchSize)) nextButton.removeClass('disabled');
                // Save scroll position in cookie
                jQuery.cookie(carousel_cookie_id, index);
            });
    }
    // Hook clicks
    prevButton.click(function() {
        scrollToItem(index - batchSize);
        return false;
    });
    nextButton.click(function() {
        scrollToItem(index + batchSize);
        return false;
    });
    // Removing scrollbar (being properly unobtrusive like we should)
    jQuery('.carousel .frame').css('overflow', 'hidden');
    // Move to the saved scrollposition (with a twist)
    var pos = jQuery.cookie(carousel_cookie_id);
    scrollToItem(pos > ((itemCount - batchSize) * 0.5) ? (itemCount - batchSize) : 0);
    scrollToItem(pos);
}
