(function ($) {
    Airport2 = function Airport2 (node, numbers) {
        this.digits = node.find('.digit');
        this.numbers = numbers;
        this.pos = 0;

        this._beforeSpin();
    };

    Airport2.prototype = {
        /*
         * Display digits containers
         */
        digits: null,
        
        /*
         * Numbers that should be on display
         */
        numbers: null,

        /*
         * Current digit, we are working with
         */
        pos: null,

        /*
         * Initialized indicator
         */
        init: null,

        /*
         * Sprite of numbers
         */
        sprite: null,

        /*
         * Sprite of shadows
         */
        cover: null,

        /*
         * Digit currently shown
         */
        number: null,

        /*
         * Digit that should be after animation
         */
        figure: null,

        /*
         * Checking if animation needed
         */
        _beforeSpin: function () {
            if (this.init > 0) this.pos++;
            this.init = 1;
            var digit = this.digits.eq(this.pos);

            this.sprite = digit.find('i img').stop(true, true);
            this.cover = digit.find('span img').stop(true, true);
            this.number = Number(this.sprite.data('number')) || 0;
            this.figure = this.numbers.substr(this.pos, 1);

            if (this.number != this.figure) this.spin();
            else if (this.pos < this.digits.size() - 1) this._beforeSpin();
        },
        
        spin: function () {
            var self = this;
            this.number = (this.number == 9 ? 0 : this.number + 1);

            this.sprite.animate({left: 0}, 40).animate({top: -43 * this.number}, 0);
            this.cover
                .animate({left: 0}, 20).animate({top: -43}, 0)
                .animate({left: 0}, 20).animate({top: -86}, 0)
                .animate({left: 0}, 20).animate({top: -129}, 0)
                .animate({left: 0}, 20).animate({top: 0}, 0, function(){
                    self.sprite.data({number: self.number});

                    if (self.number != self.figure) self.spin();
                    else if (self.pos < self.digits.size() - 1) self._beforeSpin();
                });
        }
    };

    $.fn.airport2 = function (numbers) {
        var numbers = String(numbers).replace(/[,|.]/g, '');
        
        $(this).each(function (i) {
            var node = $(this);
            node.data('airport', new Airport2(node, numbers));
        });

        return $(this);
    };
})(jQuery);
