var drag = document.getElementById("drag");
var pageWrap = document.getElementById("page-wrap");

var bounds = {top: 0, right: 900, bottom: 700, left: 0};
var current = {x: drag.offsetTop, y: drag.offsetLeft};
var prev = {x: current.x, y: current.y};
var v = {x: 0, y: 0};
var isDragging = false;
var offset = {x: 0, y: 0};
    
    var throwBall = function(e){
        if(isDragging){
            var x = e.pageX || (e.clientX + document.body.scrollLeft);
            var y = e.pageY || (e.clientY + document.body.scrollTop);
            
            prev.x = current.x;
            prev.y = current.y;
            current.x = x - pageWrap.offsetLeft;
            current.y = y - pageWrap.offsetTop;
            
            v.x = (current.x - prev.x);
            v.y = (current.y - prev.y);
        } else {
            drag.style.left = (drag.offsetLeft + v.x) + "px";
            drag.style.top = (drag.offsetTop + v.y) + "px";
            
            v.x *= .95;
            v.y *= .95;
        }
        if(drag.offsetLeft <= bounds.left){
            drag.style.left = bounds.left + "px";
            v.x *= -1;
        } else if(drag.offsetLeft >= bounds.right){
            drag.style.left = bounds.right + "px";
            v.x *= -1;
        }
        
        if(drag.offsetTop <= bounds.top){
            drag.style.top = bounds.top + "px";
            v.y *= -1;
        } else if(drag.offsetTop >= bounds.bottom){
            drag.style.top = bounds.bottom + "px";
            v.y *= -1;
        }
        
        setTimeout(function(){ throwBall(e); }, 1);
    };
    
    var onDown = function(e){
        var x = e.pageX || e.clientX + document.body.scrollLeft;
        var y = e.pageY || e.clientY + document.body.scrollTop;
        
        isDragging = true;
        offset.x = x - drag.offsetLeft;
        offset.y = y - drag.offsetTop;
        
        window.onmousemove = function(e){ onMove(e) };
    };
    
    var onMove = function(e){
        var x = e.pageX || e.clientX + document.body.scrollLeft;
        var y = e.pageY || e.clientY + document.body.scrollTop;
    
        drag.style.top = (y-offset.y) + "px";
        drag.style.left = (x-offset.x) + "px";
        
        if(drag.offsetLeft <= bounds.left){
            drag.style.left = bounds.left + "px";
        } else if(drag.offsetLeft >= bounds.right){
            drag.style.left = bounds.right + "px";
        }
        
        if(drag.offsetTop <= bounds.top){
            drag.style.top = bounds.top + "px";
        } else if(drag.offsetTop >= bounds.bottom){
            drag.style.top = bounds.bottom + "px";
        }
    };
    
    var onUp = function(){
        isDragging = false;
        window.onmousemove = function(){ return false };
    };

        
    window.onmousemove = function(e){ throwBall(e); }
    drag.onmousedown = function(e){ onDown(e) };
    window.onmouseup = function(){ onUp() };
    pageWrap.onmouseout = function(){ onUp() };