/*
 * FCKeditor - The text editor for Internet - http://www.fckeditor.net
 * Copyright (C) 2003-2007 Frederico Caldeira Knabben
 *
 * == BEGIN LICENSE ==
 *
 * Licensed under the terms of any of the following licenses at your
 * choice:
 *
 *  - GNU General Public License Version 2 or later (the "GPL")
 *    http://www.gnu.org/licenses/gpl.html
 *
 *  - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
 *    http://www.gnu.org/licenses/lgpl.html
 *
 *  - Mozilla Public License Version 1.1 or later (the "MPL")
 *    http://www.mozilla.org/MPL/MPL-1.1.html
 *
 * == END LICENSE ==
 *
 * Class for working with a selection range, much like the W3C DOM Range, but
 * it is not intended to be an implementation of the W3C interface.
 */

var FCKDomRange = function( sourceWindow )
{
	this.Window = sourceWindow ;
}

FCKDomRange.prototype =
{
	TypeName : 'FCKDomRange',		// @Packager.RemoveLine

	_UpdateElementInfo : function()
	{
		var innerRange = this._Range ;

		if ( !innerRange )
			this.Release( true ) ;
		else
		{
			// For text nodes, the node itself is the StartNode.
			var eStart	= innerRange.startContainer ;
			var eEnd	= innerRange.endContainer ;

			var oElementPath = new FCKElementPath( eStart ) ;
			this.StartNode			= eStart.nodeType == 3 ? eStart : eStart.childNodes[ innerRange.startOffset ] ;
			this.StartContainer		= eStart ;
			this.StartBlock			= oElementPath.Block ;
			this.StartBlockLimit	= oElementPath.BlockLimit ;

			if ( eStart != eEnd )
				oElementPath = new FCKElementPath( eEnd ) ;
			this.EndNode			= eEnd.nodeType == 3 ? eEnd : eEnd.childNodes[ innerRange.endOffset ] ;
			this.EndContainer		= eEnd ;
			this.EndBlock			= oElementPath.Block ;
			this.EndBlockLimit		= oElementPath.BlockLimit ;
		}
	},

	CreateRange : function()
	{
		return new FCKW3CRange( this.Window.document ) ;
	},

	DeleteContents : function()
	{
		if ( this._Range )
		{
			this._Range.deleteContents() ;
			this._UpdateElementInfo() ;
		}
	},

	ExtractContents : function()
	{
		if ( this._Range )
		{
			var docFrag = this._Range.extractContents() ;
			this._UpdateElementInfo() ;
			return docFrag ;
		}
	},

	CheckIsCollapsed : function()
	{
		if ( this._Range )
			return this._Range.collapsed ;
	},

	Collapse : function( toStart )
	{
		if ( this._Range )
			this._Range.collapse( toStart ) ;

		this._UpdateElementInfo() ;
	},

	Clone : function()
	{
		var oClone = FCKTools.CloneObject( this ) ;

		if ( this._Range )
			oClone._Range = this._Range.cloneRange() ;

		return oClone ;
	},

	MoveToNodeContents : function( targetNode )
	{
		if ( !this._Range )
			this._Range = this.CreateRange() ;

		this._Range.selectNodeContents( targetNode ) ;

		this._UpdateElementInfo() ;
	},

	MoveToElementStart : function( targetElement )
	{
		this.SetStart(targetElement,1) ;
		this.SetEnd(targetElement,1) ;
	},

	// Moves to the first editing point inside a element. For example, in a
	// element tree like "<p><b><i></i></b> Text</p>", the start editing point
	// is "<p><b><i>^</i></b> Text</p>" (inside <i>).
	MoveToElementEditStart : function( targetElement )
	{
		var child ;

		while ( ( child = targetElement.firstChild ) && child.nodeType == 1 && FCKListsLib.EmptyElements[ child.nodeName.toLowerCase() ] == null )
			targetElement = child ;

		this.MoveToElementStart( targetElement ) ;
	},

	InsertNode : function( node )
	{
		if ( this._Range )
			this._Range.insertNode( node ) ;
	},

	CheckIsEmpty : function()
	{
		if ( this.CheckIsCollapsed() )
			return true ;

		// Inserts the contents of the range in a div tag.
		var eToolDiv = this.Window.document.createElement( 'div' ) ;
		this._Range.cloneContents().AppendTo( eToolDiv ) ;

		FCKDomTools.TrimNode( eToolDiv ) ;

		return ( eToolDiv.innerHTML.length == 0 ) ;
	},

	CheckStartOfBlock : function()
	{
		// Create a clone of the current range.
		var oTestRange = this.Clone() ;

		// Collapse it to its start point.
		oTestRange.Collapse( true ) ;

		// Move the start boundary to the start of the block.
		oTestRange.SetStart( oTestRange.StartBlock || oTestRange.StartBlockLimit, 1 ) ;

		var bIsStartOfBlock = oTestRange.CheckIsEmpty() ;

		oTestRange.Release() ;

		return bIsStartOfBlock ;
	},

	CheckEndOfBlock : function( refreshSelection )
	{
		// Create a clone of the current range.
		var oTestRange = this.Clone() ;

		// Collapse it to its end point.
		oTestRange.Collapse( false ) ;

		// Move the end boundary to the end of the block.
		oTestRange.SetEnd( oTestRange.EndBlock || oTestRange.EndBlockLimit, 2 ) ;

		var bIsEndOfBlock = oTestRange.CheckIsCollapsed() ;

		if ( !bIsEndOfBlock )
		{
			// Inserts the contents of the range in a div tag.
			var eToolDiv = this.Window.document.createElement( 'div' ) ;
			oTestRange._Range.cloneContents().AppendTo( eToolDiv ) ;
			FCKDomTools.TrimNode( eToolDiv ) ;

			// Find out if we are in an empty tree of inline elements, like <b><i><span></span></i></b>
			bIsEndOfBlock = true ;
			var eLastChild = eToolDiv ;
			while ( ( eLastChild = eLastChild.lastChild ) )
			{
				// Check the following:
				//		1. Is there more than one node in the parents children?
				//		2. Is the node not an element node?
				//		3. Is it not a inline element.
				if ( eLastChild.previousSibling || eLastChild.nodeType != 1 || FCKListsLib.InlineChildReqElements[ eLastChild.nodeName.toLowerCase() ] == null )
				{
					// So we are not in the end of the range.
					bIsEndOfBlock = false ;
					break ;
				}
			}
		}

		oTestRange.Release() ;

		if ( refreshSelection )
			this.Select() ;

		return bIsEndOfBlock ;
	},

	// This is an "intrusive" way to create a bookmark. It includes <span> tags
	// in the range boundaries. The advantage of it is that it is possible to
	// handle DOM mutations when moving back to the bookmark.
	// Attention: the inclusion of nodes in the DOM is a design choice and
	// should not be changes as there are other points in the code that may be
	// using those nodes to perform operations. See GetBookmarkNode.
	// For performance, includeNodes=true if intended to SelectBookmark.
	CreateBookmark : function( includeNodes )
	{
		// Create the bookmark info (random IDs).
		var oBookmark =
		{
			StartId	: (new Date()).valueOf() + Math.floor(Math.random()*1000) + 'S',
			EndId	: (new Date()).valueOf() + Math.floor(Math.random()*1000) + 'E'
		} ;

		var oDoc = this.Window.document ;
		var eSpan ;
		var oClone ;

		// For collapsed ranges, add just the start marker.
		if ( !this.CheckIsCollapsed() )
		{
			eSpan = oDoc.createElement( 'span' ) ;
			eSpan.id = oBookmark.EndId ;
			eSpan.setAttribute( '_fck_bookmark', true ) ;

			// For IE, it must have something inside, otherwise it may be
			// removed during DOM operations.
//			if ( FCKBrowserInfo.IsIE )
				eSpan.innerHTML = '&nbsp;' ;

			oClone = this.Clone() ;
			oClone.Collapse( false ) ;
			oClone.InsertNode( eSpan ) ;

			if ( includeNodes )
				oBookmark.EndNode = eSpan ;
		}

		eSpan = oDoc.createElement( 'span' ) ;
		eSpan.id = oBookmark.StartId ;
		eSpan.setAttribute( '_fck_bookmark', true ) ;

		// For IE, it must have something inside, otherwise it may be removed
		// during DOM operations.
//		if ( FCKBrowserInfo.IsIE )
			eSpan.innerHTML = '&nbsp;' ;

		oClone = this.Clone() ;
		oClone.Collapse( true ) ;
		oClone.InsertNode( eSpan ) ;

		if ( includeNodes )
			oBookmark.StartNode = eSpan ;

		return oBookmark ;
	},

	// This one should be a part of a hypothetic "bookmark" object.
	GetBookmarkNode : function( bookmark, start )
	{
		var doc = this.Window.document ;

		if ( start )
			return bookmark.StartNode || doc.getElementById( bookmark.StartId ) ;
		else
			return bookmark.EndNode || doc.getElementById( bookmark.EndId ) ;
	},

	MoveToBookmark : function( bookmark, preserveBookmark )
	{
		var eStartSpan	= this.GetBookmarkNode( bookmark, true ) ;
		var eEndSpan	= this.GetBookmarkNode( bookmark, false ) ;

		this.SetStart( eStartSpan, 3 ) ;

		if ( !preserveBookmark )
			FCKDomTools.RemoveNode( eStartSpan ) ;

		// If collapsed, the end span will not be available.
		if ( eEndSpan )
		{
			this.SetEnd( eEndSpan, 3 ) ;

			if ( !preserveBookmark )
				FCKDomTools.RemoveNode( eEndSpan ) ;
		}
		else
			this.Collapse( true ) ;

		this._UpdateElementInfo() ;
	},

	// Non-intrusive bookmark algorithm
	CreateBookmark2 : function()
	{
		// If there is no range then get out of here.
		// It happens on initial load in Safari #962 and if the editor it's hidden also in Firefox
		if ( ! this._Range )
			return { "Start" : 0, "End" : 0 } ;

		// First, we record down the offset values
		var bookmark =
		{
			"Start" : [ this._Range.startOffset ],
			"End" : [ this._Range.endOffset ]
		} ;
		// Then, we record down the precise position of the container nodes
		// by walking up the DOM tree and counting their childNode index
		var curNode = this._Range.startContainer ;
		while ( curNode && curNode != this.Window.document.documentElement )
		{
			var curParent = curNode.parentNode ;
			for( var i = 0 ; i < curParent.childNodes.length ; i++ )
			{
				if ( curParent.childNodes.item( i ) == curNode )
				{
					bookmark.Start.unshift( i ) ;
					break ;
				}
			}
			curNode = curParent;
		}
		curNode = this._Range.endContainer;
		while ( curNode && curNode != this.Window.document.documentElement )
		{
			var curParent = curNode.parentNode;
			for ( var i = 0 ; i < curParent.childNodes.length ; i++ )
			{
				if ( curParent.childNodes.item( i ) == curNode )
				{
					bookmark.End.unshift( i );
					break;
				}
			}
			curNode = curParent;
		}
		return bookmark;
	},

	MoveToBookmark2 : function( bookmark )
	{
		// Reverse the childNode counting algorithm in CreateBookmark2()
		var curStart = this.Window.document.documentElement ;
		var curEnd = this.Window.document.documentElement ;
		for ( var i = 0 ; i < bookmark.Start.length - 1 ; i++ )
			curStart = curStart.childNodes.item( bookmark.Start[ i ] ) ;
		for ( var i = 0 ; i < bookmark.End.length - 1 ; i++ )
			curEnd = curEnd.childNodes.item( bookmark.End[ i ] ) ;

		// Generate the W3C Range object and update relevant data
		this.Release( true ) ;
		this._Range = new FCKW3CRange( this.Window.document ) ;
		this._Range.setStart( curStart, bookmark.Start[ bookmark.Start.length - 1 ] ) ;
		this._Range.setEnd( curEnd, bookmark.End[ bookmark.End.length - 1 ] ) ;
		this._UpdateElementInfo() ;
	},

	MoveToPosition : function( targetElement, position )
	{
		this.SetStart( targetElement, position ) ;
		this.Collapse( true ) ;
	},

	/*
	 * Moves the position of the start boundary of the range to a specific position
	 * relatively to a element.
	 *		@position:
	 *			1 = After Start		<target>^contents</target>
	 *			2 = Before End		<target>contents^</target>
	 *			3 = Before Start	^<target>contents</target>
	 *			4 = After End		<target>contents</target>^
	 */
	SetStart : function( targetElement, position )
	{
		var oRange = this._Range ;
		if ( !oRange )
			oRange = this._Range = this.CreateRange() ;

		switch( position )
		{
			case 1 :		// After Start		<target>^contents</target>
				oRange.setStart( targetElement, 0 ) ;
				break ;

			case 2 :		// Before End		<target>contents^</target>
				oRange.setStart( targetElement, targetElement.childNodes.length ) ;
				break ;

			case 3 :		// Before Start		^<target>contents</target>
				oRange.setStartBefore( targetElement ) ;
				break ;

			case 4 :		// After End		<target>contents</target>^
				oRange.setStartAfter( targetElement ) ;
		}
		this._UpdateElementInfo() ;
	},

	/*
	 * Moves the position of the start boundary of the range to a specific position
	 * relatively to a element.
	 *		@position:
	 *			1 = After Start		<target>^contents</target>
	 *			2 = Before End		<target>contents^</target>
	 *			3 = Before Start	^<target>contents</target>
	 *			4 = After End		<target>contents</target>^
	 */
	SetEnd : function( targetElement, position )
	{
		var oRange = this._Range ;
		if ( !oRange )
			oRange = this._Range = this.CreateRange() ;

		switch( position )
		{
			case 1 :		// After Start		<target>^contents</target>
				oRange.setEnd( targetElement, 0 ) ;
				break ;

			case 2 :		// Before End		<target>contents^</target>
				oRange.setEnd( targetElement, targetElement.childNodes.length ) ;
				break ;

			case 3 :		// Before Start		^<target>contents</target>
				oRange.setEndBefore( targetElement ) ;
				break ;

			case 4 :		// After End		<target>contents</target>^
				oRange.setEndAfter( targetElement ) ;
		}
		this._UpdateElementInfo() ;
	},

	Expand : function( unit )
	{
		var oNode, oSibling ;

		switch ( unit )
		{
			// Expand the range to include all inline parent elements if we are
			// are in their boundary limits.
			// For example (where [ ] are the range limits):
			//	Before =>		Some <b>[<i>Some sample text]</i></b>.
			//	After =>		Some [<b><i>Some sample text</i></b>].
			case 'inline_elements' :
				// Expand the start boundary.
				if ( this._Range.startOffset == 0 )
				{
					oNode = this._Range.startContainer ;

					if ( oNode.nodeType != 1 )
						oNode = oNode.parentNode ;

					while ( FCKListsLib.InlineNonEmptyElements[ oNode.nodeName.toLowerCase() ] )
					{
						this._Range.setStartBefore( oNode ) ;

						if ( oNode != oNode.parentNode.firstChild )
							break ;

						oNode = oNode.parentNode ;
					}
				}

				// Expand the end boundary.
				oNode = this._Range.endContainer ;
				var offset = this._Range.endOffset ;

				if ( ( oNode.nodeType == 3 && offset >= oNode.nodeValue.length ) || ( oNode.nodeType == 1 && offset >= oNode.childNodes.length ) || ( oNode.nodeType != 1 && oNode.nodeType != 3 ) )
				{
					if ( oNode.nodeType != 1 )
						oNode = oNode.parentNode ;

					while ( FCKListsLib.InlineNonEmptyElements[ oNode.nodeName.toLowerCase() ] )
					{
						this._Range.setEndAfter( oNode ) ;

						if ( oNode != oNode.parentNode.lastChild )
							break ;

						oNode = oNode.parentNode ;
					}
				}

				break ;

			case 'block_contents' :
				if ( this.StartBlock )
					this.SetStart( this.StartBlock, 1 ) ;
				else
				{
					// Get the start node for the current range.
					oNode = this._Range.startContainer ;

					// If it is an element, get the current child node for the range (in the offset).
					// If the offset node is not available, the the first one.
					if ( oNode.nodeType == 1 )
					{
						if ( !( oNode = oNode.childNodes[ this._Range.startOffset ] ) )
							oNode = oNode.firstChild ;
					}

					// Not able to defined the current position.
					if ( !oNode )
						return ;

					// We must look for the left boundary, relative to the range
					// start, which is limited by a block element.
					while ( true )
					{
						oSibling = oNode.previousSibling ;

						if ( !oSibling )
						{
							// Continue if we are not yet in the block limit (inside a <b>, for example).
							if ( oNode.parentNode != this.StartBlockLimit )
								oNode = oNode.parentNode ;
							else
								break ;
						}
						else if ( oSibling.nodeType != 1 || !(/^(?:P|DIV|H1|H2|H3|H4|H5|H6|ADDRESS|PRE|OL|UL|LI|DT|DE)$/).test( oSibling.nodeName.toUpperCase() ) )
						{
							// Continue if the sibling is not a block tag.
							oNode = oSibling ;
						}
						else
							break ;
					}

					this._Range.setStartBefore( oNode ) ;
				}

				if ( this.EndBlock )
					this.SetEnd( this.EndBlock, 2 ) ;
				else
				{
					oNode = this._Range.endContainer ;
					if ( oNode.nodeType == 1 )
						oNode = oNode.childNodes[ this._Range.endOffset ] || oNode.lastChild ;

					if ( !oNode )
						return ;

					// We must look for the right boundary, relative to the range
					// end, which is limited by a block element.
					while ( true )
					{
						oSibling = oNode.nextSibling ;

						if ( !oSibling )
						{
							// Continue if we are not yet in the block limit (inside a <b>, for example).
							if ( oNode.parentNode != this.EndBlockLimit )
								oNode = oNode.parentNode ;
							else
								break ;
						}
						else if ( oSibling.nodeType != 1 || !(/^(?:P|DIV|H1|H2|H3|H4|H5|H6|ADDRESS|PRE|OL|UL|LI|DT|DE)$/).test( oSibling.nodeName.toUpperCase() ) )
						{
							// Continue if the sibling is not a block tag.
							oNode = oSibling ;
						}
						else
							break ;
					}

					this._Range.setEndAfter( oNode ) ;
				}

				this._UpdateElementInfo() ;
			break ;											// @Packager.Remove.Start

			default :
				throw( 'Invalid unit "' + unit + '"' ) ;	// @Packager.Remove.End
		}
	},

	SplitBlock : function()
	{
		if ( !this._Range )
			this.MoveToSelection() ;

		// The selection boundaries must be in the same "block limit" element.
		if ( this.StartBlockLimit == this.EndBlockLimit )
		{
			// Get the current blocks.
			var eStartBlock		= this.StartBlock ;
			var eEndBlock		= this.EndBlock ;

			if ( FCKConfig.EnterMode != 'br' )
			{
				if ( !eStartBlock )
				{
					eStartBlock = this.FixBlock( true ) ;
					eEndBlock	= this.EndBlock ;	// FixBlock may have fixed the EndBlock too.
				}

				if ( !eEndBlock )
					eEndBlock = this.FixBlock( false ) ;
			}

			var bIsStartOfBlock	= ( eStartBlock != null && this.CheckStartOfBlock() ) ;
			var bIsEndOfBlock	= ( eEndBlock != null && this.CheckEndOfBlock() ) ;

			// Delete the current selection.
			if ( !this.CheckIsEmpty() )
				this.DeleteContents() ;

			if ( eStartBlock && eEndBlock && eStartBlock == eEndBlock )
			{
				if ( bIsStartOfBlock )
				{
					this.MoveToPosition( eStartBlock, 3 ) ;
					eStartBlock = null ;
				}
				else if ( bIsEndOfBlock )
				{
					this.MoveToPosition( eEndBlock, 4 ) ;
					eEndBlock = null ;
				}
				else
				{
					// Extract the contents of the block from the selection point to the end of its contents.
					this.SetEnd( eStartBlock, 2 ) ;
					var eDocFrag = this.ExtractContents() ;
					FCKDomTools.TrimNode( eDocFrag.RootNode ) ;

					// Duplicate the block element after it.
					eEndBlock = eStartBlock.cloneNode( false ) ;

					// Place the extracted contents in the duplicated block.
					eDocFrag.AppendTo( eEndBlock ) ;

					FCKDomTools.InsertAfterNode( eStartBlock, eEndBlock ) ;

					this.MoveToPosition( eStartBlock, 4 ) ;
				}
			}

			if ( FCKBrowserInfo.IsGecko )
			{
				// In Gecko, the last child node must be a bogus <br>.
				FCKTools.AppendBogusBr( eStartBlock ) ;
				FCKTools.AppendBogusBr( eEndBlock ) ;
			}

			return {
				PreviousBlock	: eStartBlock,
				NextBlock		: eEndBlock,
				WasStartOfBlock : bIsStartOfBlock,
				WasEndOfBlock	: bIsEndOfBlock
			} ;
		}

		return null ;
	},

	// Transform a block without a block tag in a valid block (orphan text in the body or td, usually).
	FixBlock : function( isStart )
	{
		// Bookmark the range so we can restore it later.
		var oBookmark = this.CreateBookmark() ;

		// Collapse the range to the requested ending boundary.
		this.Collapse( isStart ) ;

		// Expands it to the block contents.
		this.Expand( 'block_contents' ) ;

		// Create the fixed block.
		var oFixedBlock = this.Window.document.createElement( FCKConfig.EnterMode ) ;

		// Move the contents of the temporary range to the fixed block.
		this.ExtractContents().AppendTo( oFixedBlock ) ;
		FCKDomTools.TrimNode( oFixedBlock ) ;

		// Insert the fixed block into the DOM.
		this.InsertNode( oFixedBlock ) ;

		// Move the range back to the bookmarked place.
		this.MoveToBookmark( oBookmark ) ;

		return oFixedBlock ;
	},

	Release : function( preserveWindow )
	{
		if ( !preserveWindow )
			this.Window = null ;

		this.StartNode = null ;
		this.StartContainer = null ;
		this.StartBlock = null ;
		this.StartBlockLimit = null ;
		this.EndNode = null ;
		this.EndContainer = null ;
		this.EndBlock = null ;
		this.EndBlockLimit = null ;
		this._Range = null ;
	},

	CheckHasRange : function()
	{
		return ( this._Range && true ) ;
	},

	_CheckIsParagraphBoundary : function( node )
	{
		if ( node.nodeType == 1 )
		{
			var tagName = node.tagName.toLowerCase() ;
			return ! ( FCKListsLib.InlineNonEmptyElements[tagName] || tagName == 'img' ) ;
		}
		return false ;
	},

	_GenerateParagraphRange : function( paragraphList, targetWindow, startNode, endNode )
	{
		if ( ! startNode || ! endNode )
			return ;
		var range = new FCKDomRange( targetWindow ) ;
		range._Range = new FCKW3CRange( targetWindow.document ) ;
		if ( startNode.nodeName.toLowerCase() == 'br' )
			range._Range.setStartBefore( startNode ) ;
		else
			range._Range.setStart( startNode, 0 ) ;
		if ( endNode.nodeName.toLowerCase() == 'br' )
			range._Range.setEndBefore( endNode ) ;
		else
			range._Range.setEnd( endNode, endNode.nodeType == 1 ? endNode.childNodes.length : endNode.nodeValue.length ) ;
		range._UpdateElementInfo() ;
		paragraphList.push( range ) ;
	},

	GetSelectedParagraphs : function()
	{
		this.MoveToSelection() ;

		var startNode = this._Range.startContainer ;
		var endNode = this._Range.endContainer ;
		var startOffset = this._Range.startOffset ;
		var endOffset = this._Range.endOffset ;
		if ( startNode.childNodes && startNode.childNodes[startOffset] )
			startNode = startNode.childNodes[startOffset] ;
		if ( endNode.childNodes && endNode.childNodes[endOffset] )
			endNode = endNode.childNodes[endOffset] ;

		// Get the starting point of the selection's paragraph.
		var paragraphStartNode = startNode ;
		while ( paragraphStartNode && ! this._CheckIsParagraphBoundary( paragraphStartNode ) )
		{
			var candidate = null ;
			if ( paragraphStartNode.previousSibling )
			{
				if ( ! this._CheckIsParagraphBoundary( paragraphStartNode.previousSibling ) )
					candidate = paragraphStartNode.previousSibling ;
				while ( candidate && candidate.lastChild && ! this._CheckIsParagraphBoundary( candidate.lastChild ) )
					candidate = candidate.lastChild ;
			}
			else
			{
				if ( ! this._CheckIsParagraphBoundary( paragraphStartNode.parentNode ) )
					candidate = paragraphStartNode.parentNode ;
			}

			if ( candidate )
				paragraphStartNode = candidate ;
			else
				break ;
		}

		// Get the ending point of the selection's paragraph.
		var paragraphEndNode = endNode ;
		while ( paragraphEndNode && ! this._CheckIsParagraphBoundary( paragraphEndNode ) )
		{
			var candidate = null ;
			if ( paragraphEndNode.firstChild )
			{
				if ( ! this._CheckIsParagraphBoundary( paragraphEndNode.firstChild ) )
					candidate = paragraphEndNode.firstChild ;
			}
			else if ( paragraphEndNode.nextSibling )
			{
				if ( ! this._CheckIsParagraphBoundary( paragraphEndNode.nextSibling ) )
					candidate = paragraphEndNode.nextSibling ;
			}
			else
			{
				var ancestor = paragraphEndNode.parentNode ;
				while ( ancestor )
				{
					if ( this._CheckIsParagraphBoundary( ancestor ) )
						break ;
					if ( ancestor.nextSibling )
					{
						if ( this._CheckIsParagraphBoundary( ancestor.nextSibling ) )
							break ;
						candidate = ancestor.nextSibling ;
						break ;
					}
					else
						ancestor = ancestor.parentNode ;
				}
			}

			if ( candidate )
				paragraphEndNode = candidate ;
			else
				break ;
		}

		// Break up the range between paragraphStartNode and paragraphEndNode into paragraphs represented by ranges.
		var retval = [] ;
		var currentStart = paragraphStartNode ;
		var currentEnd = currentStart ;

		// Each iteration advances the position by one node in a DFS tree walk.
		while ( currentEnd != paragraphEndNode )
		{
			// 1. if we come across a <br> node, save a new paragraph
			// 2. if we come across a block element boundary, save a new paragraph
			// 3. set currentStart to null after saving a new paragraph
			// 4. set currentStart to currentEnd if currentStart is null and currentEnd is not boundary node
			if ( currentStart == null && currentEnd.nodeType == 3 )
			{
				// Ignore normal whitespaces (i.e. not including &nbsp; or other unicode whitespaces) after a block node.
				if ( currentEnd.nodeValue.search( /^[\r\n\t ]+$/ ) == 0 )
				{
					var prevNode = currentEnd.previousSibling ;
					if ( prevNode )
					{
						var prevTag = String( prevNode.tagName ).toLowerCase() ;
						if ( ! ( FCKListsLib.BlockElements[prevTag] || FCKListsLib.NonEmptyBlockElements[prevTag] ) )
							currentStart = currentEnd ;
					}
				}
				else if ( currentEnd.nodeValue.length > 0 )
					currentStart = currentEnd ;
			}

			if ( currentEnd.firstChild )
			{
				if ( this._CheckIsParagraphBoundary( currentEnd.firstChild ) )
				{
					this._GenerateParagraphRange( retval, this.Window, currentStart, currentEnd ) ;
					currentStart = null ;
				}
				currentEnd = currentEnd.firstChild ;
			}
			else if ( currentEnd.nextSibling )
			{
				if ( this._CheckIsParagraphBoundary( currentEnd.nextSibling ) )
				{
					this._GenerateParagraphRange( retval, this.Window, currentStart, currentEnd ) ;
					currentStart = null ;
				}
				currentEnd = currentEnd.nextSibling ;
			}
			else
			{
				var ancestor = currentEnd.parentNode ;
				while ( ancestor )
				{
					if ( this._CheckIsParagraphBoundary( ancestor ) )
					{
						this._GenerateParagraphRange( retval, this.Window, currentStart, currentEnd ) ;
						currentStart = null ;
					}
					if ( ancestor.nextSibling )
					{
						if ( this._CheckIsParagraphBoundary( ancestor.nextSibling ) )
						{
							this._GenerateParagraphRange( retval, this.Window, currentStart, currentEnd ) ;
							currentStart = null ;
						}
						currentEnd = ancestor.nextSibling ;
						break ;
					}
					else
						ancestor = ancestor.parentNode ;
				}
			}
		}
		// Record the final range as well.
		if ( currentStart == null && currentEnd.nodeType == 3 )
			currentStart = currentEnd ;
		this._GenerateParagraphRange( retval, this.Window, currentStart, currentEnd ) ;

		return retval ;
	},

	GetTerminalNodes : function()
	{
		var startContainer = this._Range.startContainer ;
		var endContainer = this._Range.endContainer ;
		var startNode = startContainer.nodeType == 1 ? startContainer.childNodes[this._Range.startOffset] : startContainer ;
		var endNode = endContainer.nodeType == 1 ? endContainer.childNodes[this._Range.endOffset] : endContainer ;
		return { 
			'startContainer' : startContainer, 
			'startOffset' : this._Range.startOffset,
			'endCotnainer' : endContainer,
			'endOffset' : this._Range.endOffset,
			'startNode' : startNode,
			'endNode' : endNode
		} ;
	}
} ;
