function addAnimation(id, height, start, end, fps, interval, files) {
    'use strict'

    var nframes = (end - start)/interval;
    var imgs = new Array(nframes);
    var totLoaded = 0;

    for ( var i = start; i < end; i+=interval ) {
        var j = (i - start)/interval;
        imgs[j] = new Image();
        imgs[j].onload = function() {
            if ( ++totLoaded == nframes ) {
                var canvasId = id + "_canvas";
                $("#" + id).css("background-image", "none").css("height", "auto")
                           .append("<canvas id='" + canvasId + "'></canvas>");
                var canvasObj = $("#" + canvasId);
                var ctx = canvasObj[0].getContext("2d");

                var h = height, scl = height/imgs[0].height;
                var w = imgs[0].width*scl;

                canvasObj.attr("width", w);
                canvasObj.attr("height", h);
                ctx.scale(scl, scl);

                canvasObj.css("display", "block");
                canvasObj.css("cursor", "pointer");
                ctx.drawImage(imgs[0], 0, 0);

                var playing = false;
                var curFrame = 0;
                var timer = null;
                canvasObj.click(function() {
                    if ( !playing ) {
                        playing = true;
                        timer = setInterval(function() {
                            if ( curFrame == nframes ) {
                                clearTimeout(timer);
                                playing = false;
                                curFrame = 0;
                            }
                            else {
                                ctx.drawImage(imgs[curFrame++], 0, 0);
                            }
                        }, 1000/fps);
                    } else {
                        clearTimeout(timer);
                        playing = false;
                    }
                }).contextmenu(function() {
                    clearTimeout(timer);
                    playing = false;
                    ctx.drawImage(imgs[curFrame = 0], 0, 0);
                    return false;
                });
            }
        };
        imgs[j].src = sprintf(files, i);
    }
}

$(document).ready(function() {
    'use strict'
    // General inverse rendering
    addAnimation("ablation", 660, 0, 60, 20, 1, "images/ablation/frame_%03d.jpg");
    addAnimation("bunny_in_glass", 660, 0, 150, 30, 1, "images/bunny_in_glass/frame_%03d.jpg");
    addAnimation("dodoco", 660, 0, 50, 20, 1, "images/dodoco/frame_%03d.jpg");
    addAnimation("lucy_mirror", 660, 0, 29, 20, 1, "images/lucy_mirror/frame_%03d.jpg");
});
