using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using VEPROMS.CSLA.Library;
namespace Volian.Controls.Library
{
	#region Enums
	public enum ExpandingStatus : int
	{
		No = 0,
		Expanding = 1,
		Colapsing = 2,
		Hiding = 4,
		Showing = 8,
		Done = 16
	}
	#endregion
	public partial class RTBItem : EditItem
	{
		#region Private Fields
		public Label MyLabel
		{ get { return lblTab; } }
		/// 
		/// Used to connect the RichTextBox with the menus and toolbars
		/// 
		public override StepRTB MyStepRTB
		{
			get { return _MyStepRTB; }
		}
		public override int TableWidth { get { return (int)GetTableWidth(_MyStepRTB.Font, MyItemInfo.MyContent.Text, true); } }
		/// 
		/// The left edge of the Tab
		/// 
		public override int ItemLeft
		{
			get { return Left + lblTab.Left; }
			set { Left = value - lblTab.Left; }
		}
		/// 
		/// The Location of the Tab
		/// 
		public override Point ItemLocation
		{
			get { return new Point(Location.X + lblTab.Left, Location.Y); }
			set { Location = new Point(value.X - lblTab.Left, value.Y); }
		}
		/// 
		/// Width of the Tab and RTB
		/// 
		public override int ItemWidth
		{
			get { return Width - lblTab.Left; }
			set
			{
				Width = CheckOffMargin + RTBMargin + value + lblTab.Left;
			}
		}
		/// 
		/// Width of the RichTextBox
		/// 
		public override int ContentWidth
		{
			get { return _MyStepRTB.Width; }
			set
			{
				//Width = value + lblTab.Left + lblTab.Width;
				Width = value + lblTab.Left + lblTab.Width + (this.Right - MyStepRTB.Right);
			}
		}
		public override int BorderWidth { get { return (_MyStepRTB.Width - _MyStepRTB.ClientRectangle.Width); } }
		/// 
		/// Location of the RichTextBox
		/// 
		public override Point ContentLocation
		{
			get { return new Point(Location.X + _MyStepRTB.Left, Location.Y); }
			set { Location = new Point(value.X - _MyStepRTB.Left, value.Y); }
		}
		/// 
		/// Left edge of the RichTextBox
		/// 
		public override int ContentLeft
		{
			get { return Left + _MyStepRTB.Left; }
		}
		/// 
		/// Returns the status of the vlnExpander unless it is in the process of expanding or collapsing
		/// If it is colapsing it returns false
		/// If it is expanding it returns true
		/// 
		public override bool Expanded
		{
			get
			{
				return !Colapsing && (MyExpandingStatus != ExpandingStatus.No || _MyvlnExpander.Expanded);
			}
			set
			{
				_MyvlnExpander.Expanded = value;
			}
		}
		#endregion
		#region IEditItem
		override public void AdjustTableWidthAndLocation()
		{
			_MyStepRTB.Font = MyStepData.Font.WindowsFont;
			ItemWidth = (int)GetTableWidth(_MyStepRTB.Font, MyItemInfo.MyContent.Text, true);
			ItemLocation = new Point(50, _MyParentEditItem.Bottom);
			ItemLocation = TableLocation(_MyParentEditItem, MyStepSectionLayoutData, ItemWidth);
		}
		override public void SetToolTip(string tip)
		{
			DevComponents.DotNetBar.SuperTooltipInfo tpi = new DevComponents.DotNetBar.SuperTooltipInfo("", "", tip, null, null, DevComponents.DotNetBar.eTooltipColor.Lemon);
			_MyToolTip.MinimumTooltipSize = new Size(0, 24);
			_MyToolTip.TooltipDuration = 3;
			_MyToolTip.SetSuperTooltip(MyStepRTB, tpi);
		}
		public override void RefreshContent()
		{
			MyStepRTB.RefreshDisplay();
			IdentifyMe(false);
			SetExpandAndExpander(MyItemInfo);
		}
		public override void RefreshOrdinal()
		{
			TabFormat = null; // Reset Tab
		}
		/// 
		/// Tab Format used for outputing the Tab
		/// 
		public override string TabFormat
		{
			get
			{
				if (_TabFormat == null) TabFormat = null;  // execute 'set' code.
				return _TabFormat;
			}
			set
			{
				if (MyItemInfo != null)
				{
					ItemInfo.ResetTabString(MyID);
					string tabString = MyItemInfo.IsSection ? MyItemInfo.DisplayNumber.PadRight(MyItemInfo.MyTab.CleanText.Length) : MyItemInfo.MyTab.CleanText;
					//string tabString = /*MyItemInfo.IsSection ? MyItemInfo.DisplayNumber : */ MyItemInfo.MyTab.CleanText;
					lblTab.Text = tabString;
					// calculate the width based upon characters per inch considering user's DPI
					int cpi = MyItemInfo.IsStep ? (int)MyItemInfo.FormatStepData.TabData.Font.CPI : 12;
					// if the tab ends with a single digit & has a '.' before it, add space for the possibility
					// that the number can be two digits, for example... 8.1.9 goes to 8.1.10.  We want
					// the step windows to line up, so the 8.1.9 has one character more space (lastDigitSingle)
					bool lastDigitSingle = Regex.IsMatch(tabString, "^.*[^0-9][0-9] *$");
					lblTab.Width = ((lastDigitSingle ? 1 : 0) + tabString.Length) * MyStepPanel.DPI / cpi;
					Invalidate();
					_MyStepRTB.Left = lblTab.Left + lblTab.Width;
					_MyStepRTB.Width = Width - _MyStepRTB.Left - RTBMargin - CheckOffMargin;
					_TabFormat = value;
				}
			}
		}
		#endregion
		#region Properties
		private int _RTBMargin = 3;
		/// 
		/// Margin between the EditItem and the StepRTB.  Appears on the Right.
		/// Will allow space to draw a Change Bar on the right side of the EditItem.
		/// 
		public int RTBMargin
		{
			get { return _RTBMargin; }
			set { _RTBMargin = value; }
		}
		private int? _CheckOffMargin = null;
		/// 
		/// Margin between the EditItem and the StepRTB.  Appears on the Right.
		/// Will allow space to draw a CheckOff on the right side of the EditItem.
		/// 
		public int CheckOffMargin
		{
			get
			{
				if (_CheckOffMargin == null)
				{
					if (MyItemInfo == null) _CheckOffMargin = 0;
					else
					{
						if (!MyItemInfo.IsStep || !MyItemInfo.SectionHasCheckOffs()) _CheckOffMargin = 0;
						else
						{
							Graphics g = CreateGraphics();
							SizeF sz = g.MeasureString("M", MyItemInfo.FormatStepData.Font.WindowsFont);
							_CheckOffMargin = (int)sz.Width;
						}
					}
				}
				return (int)_CheckOffMargin;
			}
			set { _CheckOffMargin = value; }
		}
		#endregion
		#region Constructors
		public RTBItem(ItemInfo itemInfo, StepPanel myStepPanel, EditItem myParentEditItem, ChildRelation myChildRelation, bool expand)
		{
			//// TIMING: DisplayItem.TimeIt("CSLARTB Top");
			InitializeComponent();// TODO: Performance 25%
			SetupEditItem(itemInfo, myStepPanel, myParentEditItem, myChildRelation, expand, null, false);
			MyStepRTB.TextChanged += new EventHandler(MyStepRTB_TextChanged);
		}
		public RTBItem(ItemInfo itemInfo, StepPanel myStepPanel, EditItem myParentEditItem, ChildRelation myChildRelation, bool expand, EditItem nextEditItem)
		{
			//// TIMING: DisplayItem.TimeIt("CSLARTB Top");
			InitializeComponent();// TODO: Performance 25%
			SetupEditItem(itemInfo, myStepPanel, myParentEditItem, myChildRelation, expand, nextEditItem, false);
			MyStepRTB.TextChanged += new EventHandler(MyStepRTB_TextChanged);
		}
		public RTBItem(ItemInfo itemInfo, StepPanel myStepPanel, EditItem myParentEditItem, ChildRelation myChildRelation, bool expand, bool addFirstChld)
		{
			//// TIMING: DisplayItem.TimeIt("CSLARTB Top");
			InitializeComponent();// TODO: Performance 25%
			SetupEditItem(itemInfo, myStepPanel, myParentEditItem, myChildRelation, expand, null, addFirstChld);
			MyStepRTB.TextChanged += new EventHandler(MyStepRTB_TextChanged);
		}
		//private void SetupRTBItem(ItemInfo itemInfo, StepPanel myStepPanel, EditItem myParentEditItem, ChildRelation myChildRelation, bool expand, EditItem nextEditItem)
		//{
		//    //if (itemInfo.ItemID == 225) _MyStepRTB.Resize += new EventHandler(_MyStepRTB_Resize);
		//    //_MyStepRTB.MyRTBItem = this;
		//    //// TIMING: DisplayItem.TimeIt("CSLARTB InitComp");
		//    BackColor = myStepPanel.PanelColor;
		//    //_MyStepRTB.BackColor = myStepPanel.InactiveColor;
		//    // TODO: Adjust top based upon format
		//    // TODO: Remove Label and just output ident on the paint event
		//    lblTab.Left = 20;
		//    SetupHeader(itemInfo);
		//    this.Paint += new PaintEventHandler(RTBItem_Paint);
		//    this.BackColorChanged += new EventHandler(RTBItem_BackColorChanged);
		//    if (itemInfo != null)
		//    {
		//        ContentType = (int)itemInfo.MyContent.Type;
		//        switch (ContentType / 10000)
		//        {
		//            case 0: // Procedure
		//                _MyStepRTB.Font = myStepPanel.ProcFont;// lblTab.Font = myStepPanel.ProcFont;
		//                lblTab.Font = itemInfo.MyTab.MyFont.WindowsFont;
		//                break;
		//            case 1: // Section
		//                _MyStepRTB.Font = myStepPanel.SectFont;// lblTab.Font = myStepPanel.SectFont;
		//                lblTab.Font = itemInfo.MyTab.MyFont.WindowsFont;
		//                break;
		//            case 2: // Steps
		//                _MyStepRTB.Font = myStepPanel.StepFont;//lblTab.Font = myStepPanel.StepFont;
		//                lblTab.Font = itemInfo.MyTab.MyFont.WindowsFont;
		//                MyStepData = itemInfo.ActiveFormat.PlantFormat.FormatData.StepDataList[ContentType % 10000];
		//                break;
		//        }
		//        //this.Move += new EventHandler(DisplayItem_Move);
		//    }
		//    else
		//    {
		//        if (myStepPanel.MyFont != null) _MyStepRTB.Font = lblTab.Font = myStepPanel.MyFont;
		//    }
		//    if (expand) _MyvlnExpander.ShowExpanded();
		//    MyStepPanel = myStepPanel;
		//    if (itemInfo != null) myStepPanel._LookupEditItems.Add(itemInfo.ItemID, this);
		//    _MyChildRelation = myChildRelation;
		//    if (myParentEditItem != null) RNOLevel = myParentEditItem.RNOLevel;
		//    if (itemInfo != null)
		//    {
		//        //// TIMING: DisplayItem.TimeIt("CSLARTB before _Layout");
		//        MyStepSectionLayoutData = itemInfo.ActiveFormat.MyStepSectionLayoutData;
		//        //// TIMING: DisplayItem.TimeIt("CSLARTB _Layout");
		//        if (myParentEditItem != null)
		//            SeqLevel = myParentEditItem.SeqLevel + ((myChildRelation == ChildRelation.After || myChildRelation == ChildRelation.Before) && itemInfo.IsSequential ? 1 : 0);
		//        //// TIMING: DisplayItem.TimeIt("CSLARTB seqLevel");
		//        MyItemInfo = itemInfo;
		//        MyItemInfo.MyConfig.PropertyChanged += new PropertyChangedEventHandler(MyConfig_PropertyChanged);
		//    }
		//    //// TIMING: DisplayItem.TimeIt("CSLARTB MyItem");
		//    myStepPanel.Controls.Add(this);
		//    switch (myChildRelation)
		//    {
		//        case ChildRelation.After:
		//            AddItem(myParentEditItem, ref myParentEditItem._MyAfterEditItems, nextEditItem);
		//            break;
		//        case ChildRelation.Before:
		//            AddItem(myParentEditItem, ref myParentEditItem._MyBeforeEditItems, nextEditItem);
		//            break;
		//        case ChildRelation.RNO:
		//            RNOLevel = myParentEditItem.RNOLevel + 1;
		//            AddItem(myParentEditItem, ref myParentEditItem._MyRNOEditItems, nextEditItem);
		//            break;
		//        case ChildRelation.None:
		//            break;
		//    }
		//    if (itemInfo != null)
		//    {
		//        if (myChildRelation == ChildRelation.None)
		//        {
		//            if (ContentType == 0 && MyStepSectionLayoutData != null)
		//            {
		//                LastMethodsPush(string.Format("SetupRTBItem {0}", MyID));
		//                Width = MyStepPanel.ToDisplay(MyStepSectionLayoutData.WidT);
		//            }
		//        }
		//    }
		//    //// TIMING: DisplayItem.TimeIt("CSLARTB Parent");
		//    SetText();
		//    //// TIMING: DisplayItem.TimeIt("CSLARTB SetText");
		//    if (itemInfo != null)
		//    {
		//        Name = string.Format("Item-{0}", itemInfo.ItemID);
		//        SetExpandAndExpander(itemInfo);
		//        if (expand && (itemInfo.MyContent.ContentPartCount != 0)) // If it should expand and it can expand
		//            Expand(true);
		//        else
		//            if (myParentEditItem == null)// If it is the top node
		//                if (ContentType >= 20000) // and it is a step - fully expand
		//                    Expand(true);
		//                else // otherwise only expand one level
		//                    Expand(false);
		//    }
		//    //// TIMING: DisplayItem.TimeIt("CSLARTB before Controls Add");
		//    //myStepPanel.Controls.Add(this);
		//    int top = FindTop(0);
		//    if (Top < top)
		//    {
		//        LastMethodsPush("SetupRTBItem");
		//        MyStepPanel.ItemMoving++;
		//        Top = top;
		//        MyStepPanel.ItemMoving--;
		//        LastMethodsPop();
		//    }
		//    _Loading = false;
		//    //// TIMING: DisplayItem.TimeIt("CSLARTB Controls Add");
		//}
		private void SetupHeader()
		{
			SetupHeader(MyItemInfo);
			LastMethodsPush("SetupHeader");
			Height = _MyStepRTB.Height + _MyStepRTB.Top + 7;
			LastMethodsPop();
		}
		void _MyStepRTB_Resize(object sender, EventArgs e)
		{
			if (MyStepPanel != null && this == MyStepPanel.SelectedEditItem)
				ScrollToCenter();
			//MyStepPanel.ScrollControlIntoView(this);
		}
		void MyStepRTB_TextChanged(object sender, EventArgs e)
		{
			if (MyStepPanel != null && this == MyStepPanel.SelectedEditItem)
				ScrollToCenter();
			//MyStepPanel.ScrollControlIntoView(this);
		}
		private Label lblHeader = null;
		private Label lblFooter = null;
		private void SetupHeaderFooter(ref Label lbl, string name, MetaTag mTag)
		{
			if (lbl == null) lbl = new Label();
			lbl.BackColor = System.Drawing.Color.Transparent;
			lbl.Location = new System.Drawing.Point(0, 0);
			lbl.Name = name;
			lbl.Size = new System.Drawing.Size(this.Width, 23);
			lbl.Visible = true;
			lbl.Font = mTag.MyFont.WindowsFont;
			lbl.Text = mTag.CleanText;
			lbl.TextAlign = mTag.Justify;
			this.Controls.Add(lbl);
		}
		#endregion
		#region EventHandlers
		/// 
		/// When the RichTextBox height changes, change the height of the control to match
		/// 
		/// 
		/// 
		private void _MyStepRTB_HeightChanged(object sender, EventArgs args)
		{
			if (this.Height != _MyStepRTB.Height + _MyStepRTB.Top + 7)  // add in 7 to make it look good // + 10)
			{
				LastMethodsPush(string.Format("_StepRTB_HeightChanged {0}", _MyStepRTB.Height));
				this.Height = _MyStepRTB.Height + _MyStepRTB.Top + 7;
				LastMethodsPop();
			}
		}
		/// 
		/// When a RichTextBox is entered, the selected StepRTB is set
		/// 
		/// 
		/// 
		private void _StepRTB_Enter(object sender, EventArgs e)
		{
			if (MyStepPanel.DisplayItemChanging) return;
			//vlnStackTrace.ShowStack("_StepRTB_Enter {0}",this.MyID);
			MyStepPanel.SelectedEditItem = this;
		}
		/// 
		/// Pass the AttachmentClick event to the StepPanel control.
		/// 
		/// 
		/// 
		private void vlnExp_AttachmentClick(object sender, vlnExpanderEventArgs args)
		{
			if (_MyvlnExpander.AutoTOC) return;
			MyStepPanel.OnAttachmentClicked(sender, new StepPanelAttachmentEventArgs(this));
		}
		/// 
		/// Handle the colape event
		/// 
		/// 
		/// 
		private void vlnExp_BeforeColapse(object sender, vlnExpanderEventArgs args)
		{
			Cursor tmp = Cursor.Current;
			Cursor.Current = Cursors.WaitCursor;
			int top = TopMostEditItem.Top;// This doesn't work - this is since the last time it was expanded.
			int topOffset = TopMostEditItem.Top + MyStepPanel.VerticalScroll.Value;
			Colapsing = true;
			// Hide Children
			HideChildren();
			// Adjust Positions
			int topOffsetAfter = TopMostEditItem.Top + MyStepPanel.VerticalScroll.Value;
			ExpandPrefix = topOffset - topOffsetAfter;
			//ExpandSuffix = BottomMostEditItem.Bottom - Bottom;
			if (topOffsetAfter != topOffset)
			{
				LastMethodsPush(string.Format("Colapse {0}", MyID));
				MyStepPanel.ItemMoving++;
				Top += (topOffset - topOffsetAfter);
				MyStepPanel.ItemMoving--;
				LastMethodsPop();
			}
			else
				AdjustLocation();
			BottomMostEditItem.AdjustLocation();
			Colapsing = false;
			Cursor.Current = tmp;
		}
		/// 
		/// Handle the expand event
		/// 
		/// 
		/// 
		private void vlnExp_BeforeExpand(object sender, vlnExpanderEventArgs args)
		{
			Cursor tmp = Cursor.Current;
			Cursor.Current = Cursors.WaitCursor;
			if (!_Loading && MyExpandingStatus == ExpandingStatus.No)
				Expand((ContentType >= 20000) || MyItemInfo.ActiveFormat.MyStepSectionLayoutData.Dev_Format);
			Cursor.Current = tmp;
		}
		/// 
		/// Raises an ItemClick event when the user clicks on the Tab
		/// 
		/// 
		/// 
		private void lblTab_MouseDown(object sender, MouseEventArgs e)
		{
			MyStepPanel.OnItemClick(this, new StepPanelEventArgs(this, e));
		}
		/// 
		/// Handle the LinkGoTO event
		/// 
		/// 
		/// 
		private void _MyStepRTB_LinkGoTo(object sender, StepPanelLinkEventArgs args)
		{
			_MyLog.DebugFormat("_DisplayRTB_LinkGoTo " + args.LinkInfoText);
			MyStepPanel.OnLinkClicked(sender, args);
		}
		void _MyStepRTB_RoInsert(object sender, StepRTBRoEventArgs args)
		{
			MyStepRTB.UpdateStepRtb(args.LinkText, args.ValText);
		}
		/// 
		/// Raise a OnLinkModifyTran event, when the user chooses to Modify a transition
		/// 
		/// 
		/// 
		private void _MyStepRTB_LinkModifyTran(object sender, StepPanelLinkEventArgs args)
		{
			MyStepPanel.OnLinkModifyTran(sender, args);
		}
		/// 
		/// Raise a OnLinkModifyRO event, when the user chooses to modify an RO
		/// 
		/// 
		/// 
		private void _MyStepRTB_LinkModifyRO(object sender, StepPanelLinkEventArgs args)
		{
			MyStepPanel.OnLinkModifyRO(sender, args);
		}
		private void _MyStepRTB_CursorKeyPress(object sender, KeyEventArgs args)
		{
			MyStepPanel.StepCursorKeys(this, args);
		}
		private void _MyStepRTB_CursorMovement(object sender, StepRTBCursorMovementEventArgs args)
		{
			MyStepPanel.CursorMovement(this, args.CursorLocation, args.Key);
		}
		//private void _MyStepRTB_ModeChange(object sender, StepRTBModeChangeEventArgs args)
		//{
		//    MyStepPanel.OnModeChange(sender as StepRTB, args);
		//}
		void _MyStepRTB_SetMenu(object sender, StepRTBMenuEventArgs args)
		{
			if (args.MenuGroup == null)
				MyStepPanel.MyStepTabPanel.MyStepTabRibbon.ClearContextMenu();
			else if (args.MenuGroup == "OpenContextMenu")
				MyStepPanel.MyStepTabPanel.MyStepTabRibbon.SetContextMenu();
			else
				MyStepPanel.MyStepTabPanel.MyStepTabRibbon.SetShortCutContextMenu(args.MenuGroup);
		}
		void _MyStepRTB_AdjustTableWidth(object sender, StepRTBTableWidthEventArgs args)
		{
			//if ((!_MyItemInfo.IsSection && !_MyItemInfo.IsProcedure) && (_MyItemInfo.IsTable || _MyItemInfo.IsFigure))
			if (MyItemInfo.IsTable || MyItemInfo.IsFigure)
			{
				if (args.EditMode)
				{
					// First get ColR
					int colR = MyStepPanel.ToDisplay(MyStepSectionLayoutData.ColRTable, MyItemInfo.ColumnMode);
					// Second get WidS
					int widS = /* _WidthAdjust + borderWidth + */ MyStepPanel.ToDisplay(MyStepSectionLayoutData.WidSTableEdit, MyItemInfo.ColumnMode);
					//int wNew = MyRTBItem.MyStepPanel.ToDisplay(MyRTBItem.MyStepSectionLayoutData.WidT);
					int wNew = 70 + widS + colR * MyItemInfo.ColumnMode;
					if (wNew > ItemWidth)
					{
						ItemWidth = wNew;
						ItemLocation = TableLocation(MyParentEditItem, MyStepSectionLayoutData, wNew);
					}
				}
				else
				{
					int newwidth = (int)GetTableWidth(MyStepRTB.Font, MyStepRTB.Text, false);
					if (ItemWidth != newwidth)
					{
						ItemWidth = newwidth;
						ItemLocation = TableLocation(MyParentEditItem, MyStepSectionLayoutData, newwidth);
					}
				}
			}
		}
		/// 
		/// Calculate TableWidth based upon the the contents
		/// 
		/// 
		/// 
		/// 
		/// 
		private float GetTableWidth(Font myFont, string txt, bool addBorder)
		{
			string[] lines = txt.Split("\n".ToCharArray());
			float max = 0;
			using (Graphics g = this.CreateGraphics())
			{
				PointF pnt = new PointF(0, 0);
				foreach (string line in lines)
				{
					string lineAdj = Regex.Replace(line, @"\\u....\?", "X"); // Replace Special characters
					//line2 = Regex.Replace(line2, @"\\.*? ", ""); // Remove RTF Commands - Really should not be any
					lineAdj = StepRTB.RemoveLinkComments(lineAdj);
					// MeasureString doesn't work properly if the line include graphics characters.
					// So, Measure a string of the same length with 'M's.
					SizeF siz = g.MeasureString("".PadLeft(lineAdj.Length + (addBorder ? 2 : 0), 'M'), myFont, pnt, StringFormat.GenericTypographic);
					float wid = siz.Width;
					if (wid > max)
					{
						max = wid;
					}
				}
			}
			float widLimit = (float)MyStepPanel.ToDisplay(MyStepSectionLayoutData.WidSTableEdit, MyItemInfo.ColumnMode);
			widLimit += (float)MyStepPanel.ToDisplay(MyStepSectionLayoutData.ColS);
			widLimit += (float)MyStepPanel.ToDisplay(MyStepSectionLayoutData.ColRTable, MyItemInfo.ColumnMode);
			max += MyStepPanel.MyStepPanelSettings.TableWidthAdjust;
			return Math.Min(max, widLimit);
		}
		bool _MyStepRTB_IsNotCurrentSelection(object sender, System.EventArgs args)
		{
			return MyStepPanel.SelectedEditItem != this;
		}
		void _MyStepRTB_OpenAnnotations(object sender, System.EventArgs args)
		{
			OpenAnnotations();
		}
		void _MyStepRTB_InsertPgBrk(object sender, System.EventArgs args)
		{
			InsertPgBrk();
		}
		void _MyStepRTB_EnterKeyPressed(object sender, System.Windows.Forms.KeyEventArgs args)
		{
			if (!MyItemInfo.IsTablePart)
			{
				args.Handled = true;
				MyStepPanel.MyStepTabPanel.MyStepTabRibbon.ProcessEnterKey();
			}
		}
		bool _MyStepRTB_CheckClipboard(object sender, System.EventArgs args)
		{
			return CheckClipboard();
		}
		void _MyStepRTB_CopyStep(object sender, System.EventArgs args)
		{
			CopyStep();
		}
		void _MyStepRTB_OpenContextMenu(object sender, StepRTBLocationEventArgs args)
		{
			MyStepPanel.MyStepTabPanel.MyStepTabRibbon.OpenContextMenu(args.Location);
		}
		void _MyStepRTB_DoMouseWheel(object sender, System.Windows.Forms.MouseEventArgs args)
		{
			DoMouseWheel(args);
		}
		void _MyStepRTB_DoSaveContents(object sender, System.EventArgs args)
		{
			SaveContents();
		}
		#endregion
		#region override methods
		public override void RefreshTab()
		{
			TabFormat = null;
			SetupHeader();
		}
		public override void SetFocus()
		{
			MyStepRTB.Focus();
		}
		public override void SaveContents()
		{
			MyStepRTB.Visible = false;
			while (MyStepRTB.Text.Contains("\\"))
			{
				int loc = MyStepRTB.Text.IndexOf("\\");
				MyStepRTB.SelectionStart = loc;
				MyStepRTB.SelectionLength = 1;
				MyStepRTB.SelectedText = "";
			}
			SaveText();
			MyStepRTB.Visible = true;
			SaveConfig();		// This may be redundant
		}
		public void SaveText()
		{
			if (MyStepRTB.ReadOnly) return;
			if (!MyStepRTB.ActiveMode) return;
			if (MyStepRTB.MyItemInfo.MyContent.Number != null && !MyStepRTB.IsDirty && MyStepRTB.Text.Contains("(Resolved Transition Text)") == false) return;
			bool success = MyStepRTB.OrigDisplayText.Save((RichTextBox)MyStepRTB);
			if (success)
			{
				MyStepRTB.FindAllLinks();
				MyStepRTB.OrigRTF = MyStepRTB.Rtf;
				MyStepRTB.ClearUndo();
			}
		}
		//public override void SetBackgroundColor()
		//{
		//    MyStepRTB.SetBackColor();
		//}
		public override void IdentifyMe(bool highlight)
		{
			if (highlight)
				MyStepRTB.BackColor = Color.Gray;
			else
			{
				if (MyStepRTB.Focused) // If active Set BackColor to the active color
					MyStepRTB.BackColor = MyStepPanel.ActiveColor;
				else // Otherwise Set the BackColor to either the InactiveColor or the AnnotationColor
					MyStepRTB.BackColor = MyItemInfo.ItemAnnotationCount == 0 ? MyStepPanel.InactiveColor : MyStepPanel.AnnotationColor;
			}
		}
		/// 
		/// Gets or Sets the ability to expand
		/// 
		public override bool CanExpand
		{
			get { return _MyvlnExpander.Visible; }
			set { _MyvlnExpander.Visible = value; }
		}
		public override void HandleResize()
		{
			if (lblHeader != null) lblHeader.Width = this.Width;
		}
		public override void MatchExpanded()
		{
			if (!_MyvlnExpander.Expanded)
				_MyvlnExpander.ShowExpanded();
		}
		/// 
		/// Sets the focus to this RTBItem and positions the cursor to the begining of the string
		/// 
		public override void ItemSelect()
		{
			// Was getting an Error that _MyStepRTB was Disposed RHM 20101217
			if (!_MyStepRTB.Disposing && !MyStepRTB.Closed)
			{
				_MyStepRTB.Focus();
				_MyStepRTB.Select(0, 0);
			}
			else
			{
				_MyLog.WarnFormat("Attempt to give Focus to Disposed Object {0}", MyID);
			}
			//  if (CanExpand) AutoExpand(); // Expand the item if you can
			ScrollToCenter();
		}
		/// 
		/// Sets the focus to this RTBItem
		/// 
		public override void ItemShow()
		{
			_MyStepRTB.Focus();
			ScrollToCenter();
		}
		public override DialogResult ReplaceText(string rpltxt, string fndstr, bool caseSensitive, bool matchWholeWord, bool reverse, bool prompt, IWin32Window fndrpldlg)
		{
			return MyStepRTB.ReplaceText(rpltxt, fndstr, caseSensitive, matchWholeWord, reverse, prompt, fndrpldlg);
		}
		public override bool FindText(string str, bool caseSensitive, bool matchWholeWord, bool reverse)
		{
			return MyStepRTB.FindText(str, caseSensitive, matchWholeWord, reverse);
		}
		public override void PositionToEnd()
		{
			MyStepRTB.SelectionStart = MyStepRTB.Text.Length;
		}
		public override void PositionToStart()
		{
			return;
		}
		public override string SelectedTextForFind
		{
			get
			{
				StepRTB srtb = MyStepRTB;
				if (srtb.SelectionLength > 0)
				{
					if (srtb.IsSelectionLinked(srtb.SelectionStart, srtb.SelectionLength))
						return srtb.SelectedText.Substring(0, srtb.SelectedText.IndexOf("#Link"));
					else
						return srtb.SelectedText;
				}
				return null;
			}
		}
		public override bool SpellCheckNext()
		{
			return MyStepRTB.SpellCheckNext();
		}
		public override void SetActive()
		{
			MyStepRTB.BackColor = MyStepPanel.ActiveColor;
		}
		public override bool Empty
		{
			get
			{
				//				Console.WriteLine("step rtb is dirty {0} and rtf is {1}", MyStepRTB.IsDirty, MyStepRTB.Rtf);
				//				string txt = MyStepRTB.Text;
				//				Console.WriteLine("step rtb is dirty {0} and rtf is {1}", MyStepRTB.IsDirty, MyStepRTB.Rtf);
				//				return txt == "";
				//return MyStepRTB.IsEmpty;
				return MyStepRTB.Text == "";
			}
			set { MyStepRTB.Text = value ? "" : " "; }
		}
		//public override bool IsEmpty()  // this becomes 'Empty' property, i.e. get/set.
		//{								// for the set, emtpy is following line (= not ==).
		//                                // for not empty - it's code that is in 'MakeNotEmpty'
		//    return MyStepRTB.Text == "";
		//}
		//public override void MakeNotEmpty()
		//{
		//    MyStepRTB.Text = " ";
		//}
		public override void RefreshDisplay(bool activeMode)
		{
			MyStepRTB.VwMode = MyStepPanel.VwMode;
			MyStepRTB.RefreshDisplay(activeMode);
			//MyStepRTB.ViewRTB = !activeMode;
		}
		public override void ToggleEditView(E_ViewMode vwMode)
		{
			SaveContents();
			MyStepRTB.VwMode = vwMode;
			MyStepRTB.RefreshDisplay();
			MyStepRTB.SelectionStart = 0;
			MyStepRTB.SelectionLength = 0;
		}
		public override int TabLeft { get { return lblTab.Left; } set { lblTab.Left = value; } }
		public override Font TabFont { get { return lblTab.Font; } set { lblTab.Font = value; } }
		public override string TabText { get { return lblTab.Text; } }
		public override Point TabLocation { get { return lblTab.Location; } }
		public override Font ContentFont { get { return MyStepRTB.Font; } set { MyStepRTB.Font = value; } }
		public override float ContentTop { get { return MyStepRTB.Top; } }
		public override void SetupHeader(ItemInfo itemInfo)
		{
			lblTab.Top = 3 + ((itemInfo.HasHeader) ? 23 : 0);
			_MyStepRTB.Top = lblTab.Top; // 3 + ((itemInfo.HasHeader) ? 23 : 0);
			//lblTab.Move += new EventHandler(lblTab_Move);
			if (itemInfo.HasHeader)
				SetupHeaderFooter(ref lblHeader, "Header", itemInfo.MyHeader);
			else
			{
				// remove header from screen if it exists:
				this.Controls.Remove(lblHeader);
				lblHeader = null;
			}
		}
		public override void ShowExpanded()
		{
			_MyvlnExpander.ShowExpanded();
		}
		/// 
		/// Sets the Item and as a result the text for the RichTextBox
		/// 
		public override void SetText()
		{
			LastMethodsPush("SetText");
			if (MyItemInfo != null)
			{
				MyStepRTB.MyItemInfo = MyItemInfo;
				MyStepRTB.RefreshDisplay();
				IdentifyMe(false);
			}
			LastMethodsPop();
		}
		public override void SetExpandAndExpander(ItemInfo itemInfo)
		{
			// Don't allow substeps to expand
			switch (ContentType / 10000)
			{
				case 1: // Section can expand
					CanExpand = true;
					// If a word document set the expander to attachment
					_MyvlnExpander.Attachment = !(itemInfo.IsStepSection);
					_MyvlnExpander.AutoTOC = itemInfo.IsAutoTOCSection;
					//OLD: _MyvlnExpander.Attachment = (itemInfo.MyContent.ContentPartCount == 0);
					break;
				case 2: // High level steps with children can expand
					CanExpand = itemInfo.IsHigh && !MyItemInfo.ActiveFormat.MyStepSectionLayoutData.Dev_Format && itemInfo.HasChildren; // TemporaryFormat.IsHigh(item); ;
					break;
				default://Procedures cannot expand, because they automatically expand
					CanExpand = false;
					break;
			}
		}
		public override void SaveCurrentAndContents()
		{
			SaveContents();
		}
		#endregion
	}
}