// Called when the document is loaded (body.onload).

function checkLinks(currentItem, maxItem, totalItems, displayCount, $prev, $next)
{
    if (currentItem == 0)
    {
        $prev.css('visibility', 'hidden');
    }
    else
    {
        $prev.css('visibility', 'visible');
    }
    if (currentItem == maxItem || totalItems < displayCount)
    {
        $next.css('visibility', 'hidden');
    }
    else
    {
        $next.css('visibility', 'visible');
    }
}

//$(function()
//$(window).ready(function ()
window.onload = function ()
{

    $('.carrousel').each(function()
    {
        var $carrousel = $(this);
        var $prev = $('.prev', $carrousel);
        var $next = $('.next', $carrousel);
        var time = 500;
        var wasHidden = false;
        if ($carrousel.css('display') == 'none')
        {
            wasHidden = true;
            $carrousel.css('display', 'block');
        }
        var $list = $('.carrousel-list', this);
        var totalItems = $('.carrousel-item', $list).length;
        var fullLength = $list.innerWidth() + 4;
        var currentItem = 0;
        var itemWidth = $('.carrousel-item:first', $list).outerWidth(true);
        if (totalItems > 0)
        {
            itemWidth = Math.round(fullLength / totalItems);
        }
        var displayCount = Math.floor($(this).innerWidth() / itemWidth);
        var maxItem = totalItems - displayCount;

        checkLinks(currentItem, maxItem, totalItems, displayCount, $prev, $next);

        // "Next" button handler
        $('.next', this).click(function()
        {
            // Animate if we are not on the last item
            if (currentItem + 1 <= maxItem)
            {
                currentItem++;
                $list.animate({'left':'-' + (currentItem * itemWidth) + 'px'}, time, 'linear');
            }
            checkLinks(currentItem, maxItem, totalItems, displayCount, $prev, $next);
            
            return false;
        });

        // "Previous" button handler
        $('.prev', this).click(function()
        {
            // Animate if we are not on the first item
            if (currentItem - 1 >= 0)
            {
                currentItem--;
                $list.animate({'left':'-' + (currentItem * itemWidth) + 'px'}, time, 'linear');
            }

            checkLinks(currentItem, maxItem, totalItems, displayCount, $prev, $next);

            return false;
        });
        if (wasHidden)
        {
            $carrousel.css('display', 'none');
        }
    });
}


