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("glass_bunny", 260, 0, 200, 20, 2, "images/inverse_rendering/bunny_glass/frame_%03d.jpg");
    addAnimation("bunny", 260, 0, 200, 20, 2, "images/inverse_rendering/bunny/frame_%03d.jpg");
    addAnimation("mug", 260, 0, 120, 10, 2, "images/inverse_rendering/mug/frame_%03d.jpg");
    addAnimation("heightmap", 260, 0, 300, 20, 2, "images/inverse_rendering/heightmap/frame_%03d.jpg");
});
