// Constants
var BIZ = "Made by Adam Hahn (adam@dontsay.biz)".split(' ').length;
var BIZ_STR = "Biz";
var TOSSER_TO_COLOR = ['#000', '#F00'];
var CANVAS_WIDTH = 90 * BIZ;


// Now
var start = new Date();


// On DOM ready
$(applyCSS3);
$(addRedrawHandlers);
$(addRenameHandlers);


/*
 * The main logic for the game. Where all the event data is kept.
 */
function addRedrawHandlers() {
    var eventsArray = [];

    $('.stat').each(function() {
        var events = [];
        eventsArray.push(events);

        $(this).children('.number').each(function(i) {
            $(this).click(function() {
                var t = $(this);

                t.text(increment(t.text()));

                var div = document.createElement('div');
                div.style.background = TOSSER_TO_COLOR[i];

                t.siblings('.canvas').append(div);

                var e = {timestamp: new Date(), div: div};
                events.push(e);

                redrawAll();
            });
        });
    });

    function redrawAll() {
        $.map(eventsArray, redraw);
    }
}

/*
 * Lets people rename each stat.
 */
function addRenameHandlers() {
    $('.label').click(function() {
        var t = $(this);
        t.text(prompt("New stat name?", t.text()));
    });
}

/*
 * Returns the text to display after incrementing the count (gracefully
 * avoiding biz, natch).
 *
 * N.B.: Doesn't work for twenty biz. If you get up to that many points,
 * plunks, etc. in one game, I'm buying you a beer.
 *
 * TODO: Make generic for all numbers?
 */
function increment(text) {
    switch (text) {
    case String(BIZ - 1):
        return BIZ_STR;
    case BIZ_STR:
        return BIZ + 1;
    default:
        return ++text;
    }
}

/*
 * Clears and redraws, scaled between the load time of the page and now.
 */
function redraw(events) {
    var now = new Date();

    $.each(events, function(i, e) {
        var width = (e.timestamp - start) / (now - start);

        // Don't use the left and rightmost pixels so we can see the whole line
        var widthPixels = width * (CANVAS_WIDTH - 20) + 10;

        e.div.style.left = widthPixels + 'px';
    });
};

/*
 * Until we stop using these prefixes, we have to do this to get CSS3 to work.
 */
function applyCSS3() {
    var propertyExtractor = /\w+:/g;
    var css3 = $('#css3').html();
    var head = $('head');

    $.each(['-webkit-', '-moz-', '-o-'], function(i, prefix) {
        var customizedCSS = css3.replace(propertyExtractor, prefix + '$&');
        $('<style type="text/css"></style>').html(customizedCSS).appendTo(head);
    });
}

