/* 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.
 */
/*
<img id="banner" src="/pub/tobaksfakta.org/pic1.jpg">
<script type="text/javascript">
  create_animation ('banner', 955, 94, 7000, [
    '/pub/tobaksfakta.org/pic1.jpg',
    '/pub/tobaksfakta.org/pic2.jpg',
    '/pub/tobaksfakta.org/pic3.jpg'
  ]);
</script>
*/

function create_animation (id, w, h, timeout, imgs) {
    for(var i = 0; i < imgs.length; i++) {
        jQuery("<img>").attr("src", getsrc(imgs[i]));
    }
    
    id = '#'+id;
    var p = 1, l = imgs.length, current = imgs[0];
    
    function getsrc(i) { return i.src || i; }
    function next() { return current = imgs[(p - 1) % l], imgs[p++ % l]; };
    function src() { return getsrc(next()); }
    
    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;
        var hasA = typeof imgs[0] !== 'string';
        $(id).wrap('<div style="cursor: ' + (hasA ? 'pointer' : 'default') + '; background-image: url(\'' + src() + '\'); width: ' + w + 'px; height: ' + h + 'px"></div>');
        $(id).parent().click(function() {
            window.location.href = current.href;
        })
        window.setTimeout(animate_out, timeout);
    };
    
    $('#banner').load(load);
}
