function loadImages(base_name, count) {
    var names = [];
    for (var i=1; i<=count; i++) {
        names[i-1] = base_name.replace(/(.*)#(.*)/, '$1' + i + '$2');
    }
    var loadedImages = [];
    var images = new Asset.images(names, {
        onProgress: function(counter, index) {
            loadedImages.push(images[index]);
        }
    });
    return loadedImages;
}

function crossfade(img, selection, time, duration) { 
    // Crossfades between 'img' and a random img from 'selection'
    // Exit if we only have one selection
    if (selection.length <= 1) { return; }
    var currentName = img.getAttribute('src');
    var newImg = selection.getRandom();
    // Make sure we get a different image
    var endRe = /\/[^\/]*?$/
    while (newImg.src.match(endRe)[0] == currentName.match(endRe)[0]) {
        newImg = selection.getRandom();
    }
    // Insert the new img in the parent
    var parentEle = img.getParent();
    newImg.setStyle('opacity', 0);
    parentEle.grab(newImg);
    // Start the cross fade
    var fadeOut = new Fx.Tween(img, {property: 'opacity', duration: duration});
    var fadeIn = new Fx.Tween(newImg, {property: 'opacity', duration: duration});
    fadeOut.addEvent('complete', function () {img.dispose();});
    fadeIn.addEvent('complete', function () {crossfade.delay(time, {}, [newImg, selection, time, duration]);});
    fadeOut.start(0.0);
    fadeIn.start(1.0);
}

function animate(img, selection, time, duration) { 
    // Starts a slideshow, changing img to a random selection, for 'time' msecs, crossfading for 'duration'
    var workIt = function (img, selection, time, duration) {
        crossfade(img, selection, time, duration);
    }
    workIt.delay(time, {}, [img, selection, time, duration]);
}

