var bounds:Object = {top: 0, right: 500, bottom: 350, left: 0};
var current:Object = {xx: ball.x, yy: ball.y};
var prev:Object = {xx: ball.x, yy: ball.y};
var v:Object = {xx: 0, yy: 0};
var isDragging:Boolean = false;
var offset:Object = {xx: 0, yy: 0};
ball.buttonMode = true;

addEventListener(Event.ENTER_FRAME, throwBall);
ball.addEventListener(MouseEvent.MOUSE_DOWN, onDown);
addEventListener(MouseEvent.MOUSE_UP, onUp);
hit.addEventListener(MouseEvent.MOUSE_OUT, onUp);

function throwBall(e:Event):void {
    if(isDragging){
        prev.xx = current.xx;
        prev.yy = current.yy;
        current.xx = hit.mouseX;
        current.yy = hit.mouseY;
        
        v.xx = current.xx - prev.xx;
        v.yy = current.yy - prev.yy;
    } else {
        ball.x += v.xx;
        ball.y += v.yy
        
        v.xx *= .94;
        v.yy *= .94;
    }
    
    if(ball.x <= bounds.left) {
        ball.x = bounds.left;
        v.xx *= -1;
    } else if(ball.x >= bounds.right) {
        ball.x = bounds.right;
        v.xx *= -1;
    }
    if(ball.y <= bounds.top) {
        ball.y = bounds.top;
        v.yy *= -1;
    } else if(ball.y >= bounds.bottom) {
        ball.y = bounds.bottom;
        v.yy *= -1;
    }
}

function onDown(e:MouseEvent):void {
    isDragging = true;
    offset.xx = ball.mouseX;
    offset.yy = ball.mouseY;
    addEventListener(MouseEvent.MOUSE_MOVE, onMove);
}

function onMove(e:MouseEvent):void {
    ball.x = hit.mouseX - offset.xx;
    ball.y = hit.mouseY - offset.yy;
    
    if(ball.x <= bounds.left)
        ball.x = bounds.left;
    else if(ball.x >= bounds.right)
        ball.x = bounds.right;
        
    if(ball.y <= bounds.top)
        ball.y = bounds.top;
    else if(ball.y >= bounds.bottom)
        ball.y = bounds.bottom;
    
    e.updateAfterEvent();
}

function onUp(e:MouseEvent):void {
    isDragging = false;
    removeEventListener(MouseEvent.MOUSE_MOVE, onMove);
}