FlipDigit = function(n, e) {
    this.id = e;
    this.element = $("#" + e);
    this.number = n;
    this.digits = this.element.children();
    this.numbers = new Array(this.digits.length);
    this.intervals = new Array();
    this.height = this.element.is(".flipdigit-large") ? 70: (this.element.is(".flipdigit-tiny") ? 18: 35);
    this.show();
    this.element.bind('click', {
        flipper: this,
        number: this.number
    },
    function(e) {
        e.data.flipper.resetAll(e.data.number);
    });
}

FlipDigit.prototype.setDigit = function(digit, n) {
    if (n == undefined) {
        n = -1;
    }
    clearInterval(this.intervals[digit]);

    this.digits.eq(digit).css('background-position', "0px -" + ((n * this.height) + this.height) + "px ")
}

FlipDigit.prototype.flipDigit = function(digit) {
    this.digits.eq(digit).css('backgroundPosition', (Math.floor(Math.random() * 2) == 1) ? "0px 0px": "0px " + this.height + "px ")
}
FlipDigit.prototype.show = function() {
    this.set(this.number)
}
FlipDigit.prototype.resetAll = function(n) {
    this.numbers = new Array(this.digits.length);
    this.set(n)
}
FlipDigit.prototype.set = function(n) {

    num = (n + "").split("");

    while (num.length < this.digits.length) {
        num.unshift(undefined);
    }
    selfx = this


    $.each(num,
    function(i, n) {
        if (selfx.numbers[i] != n) {
            x = selfx.numbers[i]
            if (!x) x = 0
            diff = Math.abs(n - x)
            delay = (100 * diff) + Math.random() * 300
            clearInterval(selfx.intervals[i])
            setTimeout("flipdigit_" + selfx.id + ".setDigit(" + i + ", " + n + ")", delay);
            selfx.intervals[i] = setInterval("flipdigit_" + selfx.id + ".flipDigit(" + i + ")", Math.random() * 100)
        }
    });
    this.numbers = num
}
FlipDigit.prototype.increment = function() {
    this.number++;
    this.show();
}
