;(function($)
{
    $.fn.frictionScroll = function(options)
    {
        var config = $.extend({}, $.fn.frictionScroll.defaults, options);

        return this.each(function()
        {
            var $this = $(this);

            var portalWidth = ($this.innerWidth() - config.paddingRight - $this.parent().innerWidth()) * -1;
            if (config.moveInit)
                $this.css('left', portalWidth + 'px');

            var lastPos;
            var thePosBeforeThat;
            var vels = [];
            var measureTimer = null;
            $this.draggable({
                axis: 'x',
                containment: (config.noContainment ? false : ([-1 * ($this.innerWidth() - config.paddingRight), 0, 0, 0])),
                distance: 2,
                scroll: false,
                start: function(event, ui)
                {
                    thePosBeforeThat = lastPos = 0;
                    measureTimer = setInterval(function()
                    {
                        vels.push(thePosBeforeThat - lastPos);
                        thePosBeforeThat = lastPos;
                        if (vels.length > 20)
                            vels = vels.slice(1, 21);
                    }, 10);
                },
                drag: function(event, ui)
                {
                    thePosBeforeThat = lastPos;
                    lastPos = ui.absolutePosition.left;
                    $this.closest('.question')
                        .data('dotcalm-value', parseInt($this.css('left')) / portalWidth * -1);
                },
                stop: function(event, ui)
                {
                    clearInterval(measureTimer);

                    var avg = 0;
                    vels = vels.slice(1, 21);
                    while (vels.length > 0)
                        avg += vels.pop();
                    avg /= 5;

                    var velTimer = null;
                    velTimer = setInterval(function()
                    {
                        var position = Math.max(Math.min(parseInt($this.css('left')) - avg, 0), portalWidth);
                        $this.css('left', position + 'px');
                        avg *= config.coefficient;
                        if (Math.abs(avg) < 0.05)
                            clearInterval(velTimer);
                    }, 10);
                }
            });
        });
    };

    $.fn.frictionScroll.defaults = {
        coefficient: 0.95,
        moveInit: true,
        noContainment: false,
        paddingRight: 0
    };
})(jQuery);