$(document).ready(function() {
    var statuses = ['new', 'in progress', 'retry', 'done', 'fail', 'cancel'];

    draw_status_chart = function(block, stage_name, data, tick) {
        block.empty();

        var lines = [];
        for (i in statuses) {
            var status = statuses[i];
            var newline = {label: status, data: []};
            var counts = data[status].counts;

            var cur_tick;
            if (tick > counts.length) {
                cur_tick = tick - counts.length;
            } else {
                cur_tick = 0;
            }

            lines.push(newline);

            for (j in counts) {
                newline.data.push([cur_tick, counts[j]]);
                cur_tick += 1;
            }
        }

        var plot = $('<div>');
        plot.height(300);

        var close = $('<a>', {text: 'close', href: '#close'});
        close.click(function () { block.empty(); });

        block.append($('<h4>', {text: stage_name}).css({display: 'inline'}));
        block.append('&nbsp;');
        block.append(close);
        block.append(plot);

        $.plot(plot, lines, {
            series: {
                lines: { show: true },
                points: { show: true }
            }
        });
    };

    var chart = $('.chart'),
        chart_data = chart.find('.plot-data').text();
    if (chart_data) {
        var data = JSON.parse(chart_data);

        $('.stage-chart-btn').click(function () {
            var stage = $(this).data('stage');
            draw_status_chart(chart.find('.plot-container'), stage, data[stage], data.tick);
        });
    }
});
