// SimpleDrag Class
var SimpleDrag = function(datas) {
    SimpleDrag.superclass.constructor.call(this);
    
    this.addEvents(['drag', 'start', 'end'], (datas) ? datas.listeners : null);
    
    this.initialize(datas);
};
BOX.extend(SimpleDrag, BOX.Observable, {
    initialize: function(datas) {
        var that = this;
        
        that.root = $(datas.root);
        that.handle = datas.handle ? $(datas.handle) : null;
        if (!that.handle || !that.handle.length) {that.handle = that.root;}
        
        that.setMinMax({
            minX: datas.minX,
            maxX: datas.maxX,
            minY: datas.minY,
            maxY: datas.maxY
        });
        that.sx = null;
        that.sy = null;
        
        that.handle.mousedown(function(e) {
            that.start(e);
        });
        $(D).mouseup(function(e) {
            that.end(e);
        });
    },
    
    setMinMax: function(datas) {
        if (typeof datas == 'object') {
            for (var p in datas) {
                if (isOwnProperty(datas, p)) {
                    this[p] = datas[p];
                }
            }
        }
        return this;
    },
    
    drag: function(e) {
        var y = e.pageY - this.sy, x = e.pageX - this.sx;
        if (this.minX !== undefined) {x = Math.max(x, this.minX);}
        if (this.maxX !== undefined) {x = Math.min(x, this.maxX);}
        if (this.minY !== undefined) {y = Math.max(y, this.minY);}
        if (this.maxY !== undefined) {y = Math.min(y, this.maxY);}
        this.root.css({
            'top': y +'px',
            'left': x +'px'
        });
        e.preventDefault();
        this.fireEvent('drag', x, y);
    },
    
    start: function(e) {
        var that = this;
        var x = parseInt(that.root.css('left'), 10) || 0;
        var y = parseInt(that.root.css('top'), 10) || 0;
        that.root.css('top', y + 'px');
        that.root.css('left', x + 'px');
        that.sx = e.pageX - x;
        that.sy = e.pageY - y;
        $(D).bind('mousemove.simpleDrag', function(e) {
            that.drag(e);
        });
        e.preventDefault();
        that.fireEvent('start');
    },
    
    end: function(e) {
        this.fireEvent('end');
        $(D).unbind('mousemove.simpleDrag');
    }
});

BOX.SimpleDrag = SimpleDrag;