jQuery select set and drag 2

by craic

HTML

<div id="box0" class="box"></div>
<div id="box1" class="box"></div>
<div id="box2" class="box"></div>
<div id="box3" class="box"></div>

<div id="msg0"></div>
<div id="msg1"></div>

CSS

.box {
    width: 50px;
    height: 50px;
    border: 1px solid black;
    position: absolute;
}

#box0 {
    left: 50px;
    top:  100px;
    background-color: #e00; 
}
#box1 {
    left: 150px;
    top:  100px;
    background-color: #ee0; 
}
#box2 {
    left: 250px;
    top:  100px;
    background-color: #e0e; 
}
#box3 {
    left: 350px;
    top:  100px;
    background-color: #0ee; 
}

JavaScript

var box_ids = [ '#box0', '#box1', '#box2', '#box3' ];

var boxes = $(".box").get();

$('#msg0').text(boxes.length + ' boxes');

var selected = {};
var drag = {
    elem: null,
    color: null,
    x: 0,
    y: 0,
    state: false
};
var delta = {
    x: 0,
    y: 0
};

$.each(boxes, function(i, node) {

    $(this).mousedown(function(e) {

        if(e.shiftKey) {
            // SELECT mode
            if(selected[this.id]) {
                delete selected[this.id];               
                this.style.border = '1px solid black';
            } else {
                selected[this.id] = this.id;
                this.style.border = '2px solid black';
            }
        } else {
            // DRAG mode
            if (!drag.state) {
                drag.elem = this;
                drag.color = this.style.backgroundColor; 
                this.style.backgroundColor = '#f00';
                drag.x = e.pageX;
                drag.y = e.pageY;
                drag.state = true;
            }
            return false;
        }
        
        var str = 'selected: ';
        $.each(selected, function(key, val) {
              str = str + ' ' + key;
        });                  

        $('#msg1').text(str);

        return false;
    });

    $(this).mouseup(function(e) {
        if(e.shiftKey) {
            // SELECT mode
        } else {
            // DRAG mode
        }
    });
    
});


// mousemove and mouseup are bound to the document

$(document).mousemove(function(e) {
    if (drag.state) {

        delta.x = e.pageX - drag.x;
        delta.y = e.pageY - drag.y;

        // For a selected group then move each of them in turn
        
        drag.elem.style.backgroundColor = '#0f0';
        var cur_offset = null;

        if(selected[drag.elem.id]) {

            var str1 = 'drag.selection: ';

            $.each(selected, function(key, val) {
                var el = $('#' + key);
                cur_offset = el.offset();
                str1 =...