(function ($) {
    Airport = function Airport (node, figure) {
        this.sprite = node.find('i img').stop(true, true);
        this.cover = node.find('span img').stop(true, true);
        this.number = Number(this.sprite.data('number')) || 0;
        this.figure = figure;
        this.figure_num = Number(figure) || 0;
        this._beforeSpin();
    };

    Airport.prototype = {
        /*
         * Sprite of numbers
         */
        sprite: null,

        /*
         * Sprite of shadows
         */
        cover: null,

        /*
         * Digit currently shown
         */
        number: null,

        /*
         * Digit that should be after animation
         */
        figure: null,
        figure_num: null,
        
        /*
         * Checking if animation needed
         */
        _beforeSpin: function () 
        {
            if (this.figure_num == 0 || this.figure == ' ' ) 
            {
                this.sprite.stop(true, true);
                this.number = 0;
                this.sprite.data({number: 0});
                // vstavitj kod
                if ( this.figure == ' ' )
                {
                    this.sprite.animate({left: 100, top: 0 }, 0);
                }
                else
                {
                    this.sprite.animate({left: 0, top: 0}, 0);
                }
            }
            else if (this.number != this.figure_num ) 
            {
                this.spin();
            } 
            else 
            {
                this.sprite.data({number: this.number});
            }
            
        },

        /*
         * Animating
         */
        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, $.proxy(this._beforeSpin, this));
                    
        }
    };

    $.fn.airport = function (numbers) {
        var digit = $(this).find('.digit'),
			numbers = String(numbers).replace(/[,|.]/g, '');

        digit.each(function (i) 
        {
            var node = $(this);
            var figure = numbers.substr(i, 1);
                        
            node.data('airport', new Airport(node, figure ));
            
        });

        return $(this);
    };
})(jQuery);
