/*
SelectionRange Class - Copyright 2005 Six Apart
$Id: selectionrange.js 17027 2005-09-01 23:44:52Z ydnar $

Copyright (c) 2005, Six Apart, Ltd.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

    * Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.

    * Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.

    * Neither the name of "Six Apart" nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

*/


SelectionRange = new Class( Object, {
    init: function() {
        // mozilla selection
        if( arguments[ 0 ].getRangeAt )
            this.fromMozillaSelection( arguments[ 0 ] );
        
        // khtml (safari) selection
        else if( arguments[ 0 ].setBaseAndExtent )
            this.fromKHTMLSelection( arguments[ 0 ] );
        
        // w3c range
        else if( arguments[ 0 ].selectNodeContents )
            this.fromRange( arguments[ 0 ] );
        
        // internet explorer selection
        else if( arguments[ 0 ].createRange )
            this.fromIESelection( arguments[ 0 ] );
        
        // internet explorer control range
        else if( arguments[ 0 ].addElement )
            this.fromIEControlRange( arguments[ 0 ] );
        
        // internet explorer text range
        else if( arguments[ 0 ].compareEndPoints )
            this.fromIETextRange( arguments[ 0 ] );
        
        // 4-argument form
        else {
            this.startContainer = arguments[ 0 ];
            this.startOffset = arguments[ 1 ];
            this.endContainer = arguments[ 2 ];
            this.endOffset = arguments[ 3 ];
        }
    },
    
    
    fromMozillaSelection: function( selection ) {
        var range = selection.getRangeAt( 0 );
        this.fromRange( range );
    },
    
    
    fromKHTMLSelection: function( selection ) {
        this.startContainer = selection.baseNode;
        this.startOffset = selection.baseOffset;
        this.endContainer = selection.extentNode;
        this.endOffset = selection.extentOffset;
    },
    
    
    fromIESelection: function( selection ) {
        var range = selection.createRange();
        this.fromIERange( range );
    },
    
    
    fromRange: function( range ) {
        this.startContainer = range.startContainer;
        this.startOffset = range.startOffset;
        this.endContainer = range.endContainer;
        this.endOffset = range.endOffset;
    },
    
    
    fromIERange: function( range ) {
        if( range.addElement )
            this.fromIEControlRange( range );
        else if( range.compareEndPoints )
            this.fromIETextRange( range );
    },
    
    
    fromIEControlRange: function( range ) {
        // fixme: this is kinda broken
        this.startContainer = range.item( 0 );
        this.startOffset = 0;
        this.endContainer = range.item( range.length - 1 );
        this.endOffset = 0;
    },
    
    
    fromIETextRange: function( range ) {
        var position = this.findIETextRangePosition( range, "StartToStart" );
        this.startContainer = position.node;
        this.startOffset = position.offset;
        
        position = this.findIETextRangePosition( range, "EndToEnd" );
        this.endContainer = position.node;
        this.endOffset = position.offset;
    },
    
    
    findIETextRangePosition: function( range, compareType ) {
        var range2 = range.duplicate();
        range2.collapse( true );
        var parent = range2.parentElement();
        range2.moveToElementText( parent );
        var length = range2.text.length;
        var delta = max( 1, finiteInt( length * 0.5 ) );
        range2.collapse( true );
        var offset = 0;
        var steps = 0;
        
        // bail after 10k iterations in case of borkage
        while( (test = range2.compareEndPoints( compareType, range )) != 0 ) {
            if( test < 0 ) {
                range2.move( "character", delta );
                offset += delta;
            } else {
                range2.move( "character", -delta );
                offset -= delta;
            }
            delta = max( 1, finiteInt( delta * 0.5 ) );
            steps++;
            if( steps > 1000 )
                throw "unable to find textrange endpoint in " + steps + " steps";
        }
        
        // this breaks if the user selects all, where the selection endpoint is at the
        // end of body
        
        log( "steps: " + steps );
        return DOM.findTextPosition( parent, offset );
    },
    
    
    getCommonAncestorContainer: function() {
        if( this.startContainer == this.endContainer )
            return this.startContainer;
        var start = DOM.getAncestors( this.startContainer, true );
        var end = DOM.getAncestors( this.endContainer, true );
        var common = null;
        for( i = 1; i <= start.length && i <= end.length; i++ ) {
            if( start[ start.length - i ] == end[ end.length - i ] )
                common = start[ start.length - i ];
        }
        return common;
    },
    
    
    hilight: function( className ) {
        var document = this.startContainer.ownerDocument;
        
        if( this.startContainer == this.endContainer ) {
            var parent = this.startContainer.parentNode;
            if( this.endOffset < this.startOffset ) {
                var temp = this.endOffset;
                this.endOffset = this.startOffset;
                this.startOffset = temp;
            }
            var value = this.startContainer.nodeValue;
            var a = document.createTextNode( value.substring( 0, this.startOffset ) );
            var b = document.createTextNode( value.substring( this.startOffset, this.endOffset ) );
            var c = document.createTextNode( value.substring( this.endOffset, value.length ) );
            
            var span = document.createElement( "span" );
            span.className = className;
            span.appendChild( b );
            
            parent.replaceChild( c, this.startContainer );
            parent.insertBefore( span, c );
            parent.insertBefore( a, span );
        }
    }
} );
