var path = 'ajax/spy.json';
var lastId;

function initImages() {
    $('spy-container').cleanWhitespace();
    
    new Ajax.PeriodicalUpdater(
        {}, path, { method: 'get', frequency: 5, onSuccess: addImages, onFailure: reportError }
    );
}

function addImages(transport, images, append) {
    if (!lastId)
        append = true;

    for (var i = images.length - 1; i >= 0; i--) {
        if (lastId == undefined || lastId < images[i].id) {
            addImage(images[i], append);
            lastId = images[i].id;
        }
    }
}

function addImage(img, append) {
    var append = (append == true) ? true : false;
    var id = 'preview-' + img.id;
    
    var elt = Builder.node('a',
        {
            id: id,
            href: 'view.php?id=' + img.id,
            style: 'display: none;',
            className: 'spy-preview',
            target: '_blank'
        }, [
            Builder.node('img',
                {
                    src: img.src,
                    onload: "appear('" + id + "', " + append + ")"
                })
        ]);
    $('spy-container').insertBefore(elt, $('spy-container').firstChild);
}

function appear(id, append) {
    if (!append) {
        $('spy-container').removeChild($('spy-container').lastChild);
    }

    new Effect.Appear(id, { duration: 0.5 });
}

function reportError(transport, json) {
}

function log(message) {
    if (console && console.log) {
        console.log(message);
    }
}

Event.observe(window, 'load', initImages, false);
