/* Author: Jonas E. Jonsson (fatbrain@gmail.com)
 * Copyright (C) 2009 Jonas E. Jonsson
 * All rights reserved.
 *
 * Dependencies: jQuery
 *
 * Usage:
 *
 * create_animation ('banner',
 *      900,
 *      100,
 *      2000,
 *      [ 'url-to-picture-1',
 *        'url-to-picture-2',
 *        'url-to-picture-3' ]);
 *
 * 'banner' - The ID of the image element holding the first picture.
 * 900      - Width of the images
 * 100      - Height of the images
 * 2000     - Time each picture will stay (in milliseconds).
 * [ ... ]  - List of urls to pictures used in the animation.
 *
 * All images used in the animation *must* have the same dimensions.
 * The minimum number of images in the picture-list is 2. There is no
 * maximum limit.
 */

function create_animation (id, w, h, timeout, imgs) {
    for(var i = 0; i < imgs.length; i++)
        jQuery("<img>").attr("src", imgs[i]);
    
    id = '#'+id;
    var p = 1, l = imgs.length;
    
    function src () { return imgs[p++ % l]; }
    
    var animate_out = function () {
        $(id).fadeIn(1).fadeOut('slow', function () {
            $(this).attr ('src', src ());
            window.setTimeout (animate_in, timeout);
        });
    };

    var animate_in  = function () {
        $(id).fadeIn('slow', function () {
            $(id).parent().css ('background-image', 'url(' + src () + ')');
            window.setTimeout (animate_out, timeout);
        });
    };
    var loaded = false;
    var load = function () {
        if (loaded) return;
        loaded = true;
        $(id).wrap('<div style="background-image: url(' + src () + '); width: ' + w + 'px; height: ' + h + 'px"></div>');
        window.setTimeout (animate_out, timeout);
    };
    
    $('#banner').load(load);
}
