/*
 * 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 ==
 *
 * Implementation for the "Insert/Remove Ordered/Unordered List" commands.
 */

var FCKListCommand = function( name )
{
	this.Name = name ;
}

FCKListCommand.prototype = 
{
	GetState : function()
	{
		return FCK.GetNamedCommandState( this.Name ) ;
	},

	Execute : function()
	{
		if ( FCKBrowserInfo.IsIE && this.GetState() == FCK_TRISTATE_OFF )
		{
			// IE does not split selected <br> tags when it is making lists. (See #428)
			// So, pre-split the blocks for IE.
			var range = new FCKDomRange( FCK.EditorWindow ) ;
			range.MoveToSelection() ;
			var startNode = range._Range.startContainer ;
			var endNode = range._Range.endContainer ;
			if ( startNode.nodeType == 1 )
			{
				if ( startNode.firstChild )
				{
					if ( startNode.childNodes.length <= range._Range.startOffset )
						startNode = startNode.lastChild ;
					else
						startNode = startNode.childNodes[ range._Range.startOffset ] ;
				}
			}
			if ( endNode.nodeType == 1 )
			{
				if ( endNode.firstChild )
				{
					if ( endNode.childNodes.length <= range._Range.endOffset )
						endNode = endNode.lastChild ;
					else
						endNode = endNode.childNodes[ range._Range.endOffset ] ;
				}
			}

			var brNodes = [] ;
			var curNode = startNode ;
			while ( curNode && curNode != endNode )
			{
				if ( curNode.nodeType == 1 && curNode.tagName.toLowerCase() == 'br' )
					brNodes.push( curNode ) ;
				curNode = FCKTools.GetNextNode( curNode ) ;
			}

			for ( var i = brNodes.length - 1 ; i >= 0 ; i-- )
			{
				range.SetStart( brNodes[i], 3 ) ;
				range.SetEnd( brNodes[i], 3 ) ;
				brNodes[i].parentNode.removeChild( brNodes[i] ) ;
				range.SplitBlock() ;
			}

			range.SetStart( startNode, 1 ) ;
			range.SetEnd( endNode, 4 ) ;
			range.Select() ;
		}
		FCK.ExecuteNamedCommand( this.Name ) ;
	}
};
