(function($, undef) {
    var ScrollingLine = function(jQueryObject, properties) {
        this.$ = jQueryObject;
        this.properties = mergeHash(properties,{
            scrollDuration : 200
        });
        this.init();
    }



    ScrollingLine.prototype = {
        /**
         * Инициализация
         */
        init: function() {
            var self = this;
            this.pos = 0;
            this.scrollWidth = 0;
            this.$wrap = $(document.createElement('div')).addClass('scrolline').insertAfter(this.$);
            this.$area = $(document.createElement('div'))
                .addClass('in')
                .appendTo(this.$wrap)
                .scrollLeft(0)
                .append(this.$);
            this.$items = this.$.children('li');
            for (var i = 0; i < this.$items.length; i++) {
                this.scrollWidth += this.$items.eq(i).outerWidth();
            }

            this.maxPos = 0;
            this.$.width(this.scrollWidth);
            if (this.scrollWidth > this.$area.width()) {
                this._drawButtons();
                this.$area.mousewheel(function(e, d) {
                    self._mouseWheelHandler(e, d);
                    e.preventDefault();
                    e.stopPropagation();
                });
            }
        },

        /**
         * Рисование кнопок прокрутки
         */
        _drawButtons: function() {
            var self = this;
            this._$lb = $(document.createElement('div'))
                .addClass('btn l-btn')
                .append(document.createElement('ins'))
                .appendTo(this.$wrap)
                .mousedown(function(e) {
                    self.scrollLeft();
                    e.preventDefault();
                    e.stopPropagation();
                    return false;
                });
            this._$rb = $(document.createElement('div'))
                .addClass('btn r-btn')
                .append(document.createElement('ins'))
                .appendTo(this.$wrap)
                .mousedown(function(e) {
                    self.scrollRight();
                    e.preventDefault();
                    e.stopPropagation();
                    return false;
                });
            this.checkButtons();
        },

        /**
         * Проверка активности кнопок
         */
        checkButtons: function() {
            this._$lb.removeClass('disabled');
            this._$rb.removeClass('disabled');
            if (this.$area.scrollLeft() == 0)
                this._$lb.addClass('disabled');
            if (this.$area.scrollLeft() >= (this.scrollWidth - this.$area.width()))
                this._$rb.addClass('disabled');
        },

        /**
         * Прокрутить на элемент влево
         */
        scrollLeft: function() {
            this.scrollToPos(this.pos - 1);
        },

        /**
         * Прокрутить на элемент вправо
         */
        scrollRight: function() {
            this.scrollToPos(this.pos + 1);
        },

        /**
         * Прокрутить до элемента с номером
         * @param {Number} pos
         */
        scrollToPos: function(pos) {
            if ((this.maxPos) && (pos > this.maxPos))
                pos = this.maxPos;
            if (pos >= 0) {
                var left = this.$items.get(pos).offsetLeft;
                if (left > this.scrollWidth - this.$area.width()) {
                    if (this.maxPos) {
                        pos = this.maxPos;
                    } else {
                        while ((left > this.scrollWidth - this.$area.width()) && (pos >= 0)) {
                            pos--;
                            left = this.$items.get(pos).offsetLeft;
                        }
                        this.maxPos = pos + 1;
                    }
                    left = this.$items.get(this.maxPos).offsetLeft;
                }
                this.pos = pos;
                this.scrollTo(left);
            }

        },

        /**
         * Установить положение прокрутки
         * @param {Number} scrollLeft
         */
        scrollTo: function(scrollLeft) {
            var self = this;
            this.$area.stop().animate({
                scrollLeft : scrollLeft
            }, this.properties.scrollDuration, 'swing', function() {
                self.checkButtons();
            });
        },

        _mouseWheelHandler: function(e, d) {
            d *= -1;
            this.scrollToPos(this.pos + d);
        }
    };

    function mergeHash(hash, defaults) {
        var ret = hash || {};
        for (var key in defaults) {
            if (ret[key] == undef) {
                ret[key] = defaults[key];
            }
        }
        return ret;
    }

    $.fn.scrollingLine = function(properties) {
        for (var i = 0; i < this.length; i++) {
            var line = new ScrollingLine(this.eq(i), properties);
            this.eq(i).data('ScrollingLineObject', line);
        }
    }

})(jQuery);


