var FCKUndo = new Object() ;

FCKUndo.SavedData = new Array() ;
FCKUndo.CurrentIndex = -1 ;

FCKUndo.SaveUndoStep = function()
{
	// Shrink the array to the current level.
	FCKUndo.SavedData = FCKUndo.SavedData.slice( 0, FCKUndo.CurrentIndex + 1 ) ;

	// Get the Actual HTML.
	var sHtml = FCK.EditorDocument.body.innerHTML ;

	// Cancel operation if the new step is identical to the previous one.
	if ( FCKUndo.CurrentIndex >= 0 && sHtml == FCKUndo.SavedData[ FCKUndo.CurrentIndex ][0] )
		return ;

	// If we reach the Maximun number of undo levels, we must remove the first
	// entry of the list shifting all elements.
	if ( FCKUndo.CurrentIndex + 1 >= FCKConfig.MaxUndoLevels )
		FCKUndo.SavedData.shift() ;
	else
		FCKUndo.CurrentIndex++ ;

	// Get the actual selection.
	var sBookmark ;
	if ( FCK.EditorDocument.selection.type == 'Text' )
		sBookmark = FCK.EditorDocument.selection.createRange().getBookmark() ;

	// Save the new level in front of the actual position.
	FCKUndo.SavedData[ FCKUndo.CurrentIndex ] = [ sHtml, sBookmark ] ;

	FCK.Events.FireEvent( "OnSelectionChange" ) ;
}

FCKUndo.Undo = function()
{
	if ( FCKUndo.CurrentIndex > 0 )
	{
		// If it is the first step.
		if ( FCKUndo.CurrentIndex == ( FCKUndo.SavedData.length - 1 ) )
		{
			// Save the actual state for a possible "Redo" call.
			FCKUndo.SaveUndoStep() ;
		}

		// Go a step back.
		FCKUndo._ApplyUndoLevel( --FCKUndo.CurrentIndex ) ;

		FCK.Events.FireEvent( "OnSelectionChange" ) ;
	}
}

FCKUndo.Redo = function()
{
	if ( FCKUndo.CurrentIndex < ( FCKUndo.SavedData.length - 1 ) )
	{
		// Go a step forward.
		FCKUndo._ApplyUndoLevel( ++FCKUndo.CurrentIndex ) ;

		FCK.Events.FireEvent( "OnSelectionChange" ) ;
	}
}

FCKUndo._ApplyUndoLevel = function(level)
{
	var oData = FCKUndo.SavedData[ level ] ;

	// Update the editor contents with that step data.
	FCK.EditorDocument.body.innerHTML = oData[0] ;

	if ( oData[1] ) 
	{
		var oRange = FCK.EditorDocument.selection.createRange() ;
		oRange.moveToBookmark( oData[1] ) ;
		oRange.select() ;
	}
}