/*

    Drag: A Really Simple Drag Handler

*/
Drag = {
    className: 'draggable',
    _move: null,
    _down: null,
    _patt: /^(INPUT|BUTTON|A)$/,

    start: function(e) {
        /*
          We click on any element inside draggable but we want
          to move with whole parent.
        */
        var elem = e.target();
        if (elem.tagName.match(Drag._patt))
            return; // for buttons drag doesn't work
        
        e.stop(); 
        while (!elem.className.match(Drag.pattern)) {
            elem = elem.parentNode;
            if (typeof(elem) == 'undefined' || elem.tagName == 'BODY' || elem.tagName == 'HTML') {
                elem = e.target(); // get originaly clicked element
                break;
            }
        }
        // We need to remember what we're dragging.
        Drag._target = elem;

        /*
            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,
            getElementPosition(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.Style.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) {
        disconnect(Drag._move);
        disconnect(Drag._down);
    },
    
    onClick: function(e) {
        var elem = e.target();
        if (elem.tagName.match(Drag._patt))
            return; // for buttons drag doesn't work
        
        // we need stop event by cause othewise the puzzle word switchs to invisible style.
        e.stop();
    }
};


connect(window, 'onload',
    function() {
        // class can be composed with more names
        Drag.pattern = new RegExp(Drag.className);
        /*
            Find all DIVs tagged with the draggable class, and connect them to
            the Drag handler.
        */
        forEach(getElementsByTagAndClassName('DIV', Drag.className),
            function(elem) {
                connect(elem, 'onmousedown', Drag.start);
                connect(elem, 'onclick', Drag.onClick);
            });
    });

//logDebug('Drag loaded OK.');

