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("Oxalis", 480, 0, 142, 16, 1, "images/oxalis/%04d.jpg");
  addAnimation("Painting", 480, 0, 127, 16, 1, "images/painting/%04d.jpg");
  addAnimation("Polygon", 580, 0, 17, 4, 1, "images/polygon/%04d.jpg");
  addAnimation("Kitty", 580, 0, 63, 16, 1, "images/kitty/%04d.jpg");
  addAnimation("Tree", 450, 0, 63, 16, 1, "images/tree/%04d.jpg");
  addAnimation("WorldMap", 450, 0, 63, 16, 1, "images/world_map/%04d.jpg");
  addAnimation("Coin", 450, 0, 56, 16, 1, "images/coin/%04d.jpg");
  addAnimation("Octagon", 450, 0, 32, 10, 1, "images/octagon/%04d.jpg");
});
