jQuery.fn.iStacker = function(providedOptions)
{
    var opts = $.extend({}, jQuery.fn.iStacker.defaults, providedOptions);

    return this.each(function() {
        var me = $(this);
        var stack = me.children().toArray();
        var max_w = 0, max_h = 0;
        var opacity_step = 100 / opts.num_images / 100;

        function set_css(idx, el) {
            var left = idx * opts.increment * 3;
            var top = idx * opts.increment;
            var width = max_w - (idx * opts.increment * 2);
            var height = max_h - (idx * opts.increment * 2);
            var z_index = 100 - idx;
            var opacity = 1 - (idx * opacity_step);

            el
                .css('left', left)
                .css('top', top)
                .width(width)
                .height(height)
                .css('z-index', z_index)
                .css('opacity', opacity);
        }

        function step() {
            $(stack).each(function(idx) {
                if (idx > opts.num_images) {
                    return;
                }

                var opacity = idx == 0 ? 0 : ('+=' + opacity_step);
                var done_fn = idx == 0 ? step_done : $.noop;
                $(this).animate({
                    left: '-=' + (opts.increment * 3),
                    top: '-=' + opts.increment,
                    width: '+=' + (opts.increment * 2),
                    height: '+=' + (opts.increment * 2),
                    opacity: opacity,
                }, opts.animation_time, done_fn);
            });
        }

        function step_done() {
            for (var i = 1; i < stack.length; ++i) {
                stack[i - 1] = stack[i];
            }
            stack[stack.length - 1] = this;
            $(stack).each(function(idx) {
                set_css(idx, $(this));
            });

            setTimeout(step, opts.timeout);
        }

        /* Find maximum width */
        $(stack).each(function() {
            var w = $(this).width();
            var h = $(this).height();

            if (w > max_w) {
                max_w = w;
            }
            if (h > max_h) {
                max_h = h;
            }
        });

        /* Set initializing CSS */
        me
            .css('position', 'relative')
            .css('width', max_w + (opts.increment * (opts.num_images + 1)))
            .css('height', max_h + (opts.increment * (opts.num_images + 1)))
            .css('overflow', 'hidden');

        $(stack).css('position', 'absolute');

        $(stack).each(function(idx) {
            set_css(idx, $(this));
        });

        setTimeout(step, opts.timeout);
    });
}

jQuery.fn.iStacker.defaults = {
    num_images: 4,
    increment: 14,
    animation_time: 750,
    timeout: 8000,
};

