$(document).ready(function()
{
    var nextPosition = currentPosition;

    var numberOfPics = thumbnails.length;

    if (0 == (maxItems % 2))
    {
        maxItems = (maxItems + 1);
    }

    var picQueue = ((maxItems + 1) / 2);

    var goNext = parseInt(maxItems / 2);

    if (nextPosition < picQueue)
    {
        var cacheIndex = 0;
    }
    else if (nextPosition > (numberOfPics - picQueue))
    {
        var cacheIndex = (numberOfPics - maxItems);
    }
    else
    {
        var cacheIndex = (nextPosition - goNext);
    }

    if (nextPosition < goNext)
    {
        nextPosition = goNext;
    }

    if (nextPosition > (numberOfPics - picQueue))
    {
        nextPosition = (numberOfPics - picQueue);
    }

    $("#firstLink").click(function()
    {
        nextPosition = (goNext + 1);

        $("#previousLink").click();

        return false;
    });

    $("#previousLink").click(function()
    {
        nextPosition--;

        cacheIndex = (nextPosition - goNext);

        if (0 > cacheIndex)
        {
            nextPosition++;
            return false;
        }

        for (var i = 0; i < maxItems; i++)
        {
            var j = (cacheIndex + i);

            $("#td_" + i).html($("#thumbnail_" + thumbnails[j]).html());
        }

        return false;
    });

    $("#nextLink").click(function()
    {
        nextPosition++;

        cacheIndex = (nextPosition + goNext);

        if (cacheIndex >= numberOfPics)
        {
            nextPosition--;
            return false;
        }

        for (var i = 0; i < maxItems; i++)
        {
            var j = (cacheIndex - maxItems + i + 1);

            $("#td_" + i).html($("#thumbnail_" + thumbnails[j]).html());
        }

        return false;
    });

    $("#lastLink").click(function()
    {
        nextPosition = (numberOfPics - 2 - goNext);

        $("#nextLink").click();

        return false;
    });
});
