/*

    Drag: A Really Simple Drag Handler
    
*/
Drag = {
    _move: null,
    _down: null,
    
    start: function(e) {
        e.stop();
        
        // We need to remember what we're dragging.
        Drag._target = e.target();
        
        /*
            There's no cross-browser way to get offsetX and offsetY, so we
            have to do it ourselves. For performance, we do this once and
            cache it.
        */
        Drag._offset = Drag._diff(
            e.mouse().page,
            elementPosition(Drag._target));
        
        Drag._move = connect(document, 'onmousemove', Drag._drag);
        Drag._down = connect(document, 'onmouseup', Drag._stop);
    },

    _offset: null,
    _target: null,
    
    _diff: function(lhs, rhs) {
        return new MochiKit.DOM.Coordinates(lhs.x - rhs.x, lhs.y - rhs.y);
    },
        
    _drag: function(e) {
        e.stop();
        setElementPosition(
            Drag._target,
            Drag._diff(e.mouse().page, Drag._offset));
    },
    
    _stop: function(e) {    	
    	var crossx = document.getElementById('crossx');
    	var crossy = document.getElementById('crossy');
    	var pos = elementPosition(Drag._target);
    	var map = elementPosition(document.getElementById('map'));
    	crossx.value = pos.x - map.x;
    	crossy.value = pos.y - map.y;    	
        disconnect(Drag._move);
        disconnect(Drag._down);
    }
};

connect(window, 'onload',   
    function() {
    	var crossx = document.getElementById('crossx');
    	var crossy = document.getElementById('crossy');
    	var map = elementPosition(document.getElementById('map'));
        var d = getElementsByTagAndClassName('IMG', 'draggable');
		var coord = new MochiKit.DOM.Coordinates( parseInt(map.x) + parseInt(crossx.value),  parseInt(map.y) + parseInt(crossy.value));
        forEach(d,
            function(elem) {
                connect(elem, 'onmousedown', Drag.start);
        		setElementPosition(elem,coord);                
            });
                        
    });
    

