Notice that you're using merge function that I provide to you, well.
As I tell you, code is only to explain the general approach to follow.
Remember also to call this function to make new element droppable:
var modifyAsDroppable = function(target) {
var what = "<div class=\"handle ui-selectee\"><span class=\"ui-icon ui-icon-carat-2-n-s ui-selectee\"></span></div>";
target.prepend(what);
}
In this version I divide each task in different function, so merge() become:
var merge = function() {
/* contains: top left bottom right */
var properties = calculateSize();
var $merged = createNewDiv();
insert($merged, searchWhereInsert(properties));
modifyAsDroppable($merged);
setSize($merged, properties);
removeMerged();
}
If you want that it works not only first time, you have to make working the way on how you fullfill the selected array.
UPDATE
In this demo I've fixed "one-time-working" and now works always. There was a bug on selected array creation, now is:
if(index >= 0) {
selected.push(index);
}
The more is done, now provide by yourself "undo" functionality.
Update + rollBack
In this version you have a rollBack functionality, but it quite bugged (don't work in some case).
Improve it!
Update + rollBack fixed && working
Just for personal ego, HERE working rollBack. (cool!)