function Momentum(callback, options){
    
    this.braking = options.braking
    this.timeout = options.timeout // msec before each step
    this.callback = callback
    this.speed = 0;
    this.running = false;
    this.data = null;
    
    this.stop = function(){
        this.running = false;
        this.speed = 0;
    }
    
    this.start = function(speed, data){
        this.running = true;
        this.speed = speed;
        this.data = data
        this._step()
    }
    
    this._step = function()
    {
        if(!this.running) return;
   
        //suppose we move 1 pixel each time, so timeout will be 1/speed
        d = 100*this.speed

        if(Math.abs(this.speed) < .0005 || Math.abs(d) < 1){
            this.running = false
            return
        }
        
        this.callback(-d, this.data)
        
        this.speed = this.speed*(1-this.braking)
        _this = this;
        setTimeout( function(){ _this._step() }, this.timeout );
    }
    
}

function VMousePos(x, y)
{
    this.x = x;
    this.y = y;
    var currentTime = new Date()
    this.t = currentTime.getTime();
    
    this.dump = function(){
    console.log("x="+this.x+" y="+this.y+" t="+this.t)
    }
}

function VMouse()
{
    this.positions = new Array();
    this.maxLength = 5
    this.xSpeed = this.ySpeed = 0
    
    this.addPos = function(pos){
        this.positions.push(pos)
        l = this.positions.length
        if(l > this.maxLength)
        {
            this.positions = this.positions.slice(l-this.maxLength)
        }
        this.calculate()
    }
    
    this.calculate = function(){
        if(this.positions.length < 2)
        {
            this.xSpeed = this.ySpeed = 0
        }
        
        fisrtPos = this.positions[0]
        lastPos = this.positions[this.positions.length-1]
        
        this.xSpeed = (lastPos.x - fisrtPos.x)/(lastPos.t - fisrtPos.t)
        this.ySpeed = (lastPos.y - fisrtPos.y)/(lastPos.t - fisrtPos.t)
    }
    
    this.recentlyMoved = function(){
        if(this.positions.length < 2) return false;
        ct = new Date()
        diff = ct.getTime() - this.positions[this.positions.length-1].t
        return diff < 500 // les than half sec old
    }
    
    this.dump = function(){
        console.log("xSpeed="+this.xSpeed+" ySpeed="+this.ySpeed)
        jQuery.each(this.positions, function(i,a){a.dump()})
    }
}
