Select cells in table analogous to text selection

Can be refactored

HTML

<table id="table">
      <tr>
        <td>A</td>
        <td>B</td>
        <td>C</td>
        <td>D</td>
        <td>E</td>
        <td>F</td>
      <td>G</td>
        <td>H</td>
        <td>I</td>
      </tr>
    </table>

CSS

#table { border:1px solid #ccc; }
    #table td { padding:50px; }
    #table td.selected { background-color:#ccc; }

JavaScript

$(function () {
            $("#table td")
                .mousedown(rangeMouseDown)
                .mouseup(rangeMouseUp)
                .mousemove(rangeMouseMove);
        });

        var dragStart = 0;
        var dragEnd = 0;
        var isDragging = false;

        function rangeMouseDown(e) {
            if (isRightClick(e)) {
                return false;
            } else {
                var allCells = $("#table td");
                dragStart = allCells.index($(this));
                isDragging = true;

                if (typeof e.preventDefault != 'undefined') { e.preventDefault(); } 
                document.documentElement.onselectstart = function () { return false; };
            } 
        }

        function rangeMouseUp(e) {
            if (isRightClick(e)) {
                return false;
            } else {
                var allCells = $("#table td");
                dragEnd = allCells.index($(this));

                isDragging = false;
                if (dragEnd != 0) {
                    selectRange();
                }

                document.documentElement.onselectstart = function () { return true; }; 
            }
        }

        function rangeMouseMove(e) {
            if (isDragging) {
                var allCells = $("#table td");
                dragEnd = allCells.index($(this));
                selectRange();
            }            
        }

        function selectRange() {
            $("#table td").removeClass('selected');
            if (dragEnd + 1 < dragStart) { // reverse select
                $("#table td").slice(dragEnd, dragStart + 1).addClass('selected');
            } else {
                $("#table td").slice(dragStart, dragEnd + 1).addClass('selected');
            }
        }

        function isRightClick(e) {
            if (e.which) {
                return (e.which == 3);
            } else if (e.button) {
                return (e.button == 2);
            }
            return false;
        }