using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Configuration;
using VEPROMS.CSLA.Library;
//using Csla;
using DevComponents;
using DevComponents.DotNetBar;
using DevComponents.DotNetBar.Rendering;
using VEPROMS.Properties;
using Volian.Controls.Library;
using DescriptiveEnum;
using Volian.Base.Library;
using Volian.Print.Library;

[assembly: log4net.Config.XmlConfigurator(Watch = true)]

namespace VEPROMS
{
	enum PropPgStyle { Button = 1, Tab = 2, Grid = 3 };

	public partial class frmVEPROMS : DevComponents.DotNetBar.Office2007RibbonForm
	{
		#region Log4Net
		private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
		#endregion
		#region PropertiesVariables
		private bool _panelExpandedChanging = false;
		Color _CommentTitleBckColor;
		DocVersionInfo _SelectedDVI = null;
		StepTabPanel _SelectedStepTabPanel = null;
		public FindReplace dlgFindReplace = null;
		public VlnSpellCheck SpellChecker = null;

		public StepTabPanel SelectedStepTabPanel
		{
			get
			{
				return _SelectedStepTabPanel;
			}
			set
			{
				_SelectedStepTabPanel = value;
				if (value == null) // DSO Tab Panel
				{
					dlgFindReplace.Visible = false; // Find/Replace dialog should not be visable for DSO tab panels
					if (tc.SelectedDisplayTabItem != null && tc.SelectedDisplayTabItem.MyItemInfo != null)  // 2nd part is for unassociated libdocs
						SelectedDVI = tc.SelectedDisplayTabItem.MyItemInfo.ActiveParent.ActiveParent as DocVersionInfo;
					else
						SelectedDVI = null;
				}
				else // Step Tab Panel
				{
					// The following line was broken into separate lines because a NullReferenceError was occuring.
					// Now we should be able to tell what is wrong by which line causes the Null Reference Error
					// RHM 20101217
					//SelectedDVI = value.MyStepPanel.MyProcedureItemInfo.MyProcedure.ActiveParent as DocVersionInfo;
					StepPanel stepPanel = value.MyStepPanel;
					ItemInfo itemInfo = stepPanel.MyProcedureItemInfo;
					ProcedureInfo procedureInfo = itemInfo.MyProcedure;
					SelectedDVI = procedureInfo.ActiveParent as DocVersionInfo;
					// Remove it first, if it wasn't set, this doesn't do anything, but if it was set, you don't want
					// multiple events because the print dialog will be displayed for each time the event was added.
					_SelectedStepTabPanel.MyStepTabRibbon.PrintRequest -= new StepTabRibbonEvent(MyStepTabRibbon_PrintRequest);
					_SelectedStepTabPanel.MyStepTabRibbon.PrintRequest += new StepTabRibbonEvent(MyStepTabRibbon_PrintRequest);
			}
		}
		}
		
		public DocVersionInfo SelectedDVI
		{
			get { return _SelectedDVI; }
			set
			{
				if (_SelectedDVI != value)
				{
					_SelectedDVI = value;
					_SelectedROFst = null;
				}
				InitiateSearch(false);
			}
		}
		// TODO: Should the following be an info
		// For the initial release, we are assuming there will be only one rofst fro a docversion.  Changes
		// will be needed here if more than 1.
		private ROFstInfo _SelectedROFst;
		public ROFstInfo SelectedROFst
		{
			get
			{
				if (_SelectedROFst == null && SelectedDVI != null)
				{
					if (SelectedDVI.DocVersionAssociationCount <= 0)
					{
						MessageBox.Show("There is no Referenced Object (RO) data for this procedure set. Use the Properties for the set to define the RO data.");
						return null;
					}
					_SelectedROFst = SelectedDVI.DocVersionAssociations[0].MyROFst;
				}
				return _SelectedROFst;
			}
			set { _SelectedROFst = value; }
		}
		#endregion
		public frmVEPROMS()
		{
			if (Properties.Settings.Default.UpdateSettings)
			{
				Properties.Settings.Default.Upgrade();
				Properties.Settings.Default.UpdateSettings = false;
				Properties.Settings.Default.Save();
			}
			// cleanup from previous run:
			Volian.Base.Library.TmpFile.RemoveAllTmps();

			if (VlnSettings.DebugMode)
			{
				//use local data (for development/debug mode)
				if (Environment.MachineName == "RMARK-PC")
					VEPROMS.CSLA.Library.Database.ConnectionName = "VEPROMS_RMARK_DEBUG";
                else if (Environment.UserName.ToUpper() == "BODINE")
                    VEPROMS.CSLA.Library.Database.ConnectionName = "VEPROMS_BODINE_DEBUG";
                else
					VEPROMS.CSLA.Library.Database.ConnectionName = "VEPROMS_LOCAL";
			}
			else
			{
				// use server data (default)
				// - except for the volian laptop and Rich's Demo version where we need to use local data
				if (Environment.MachineName == "RMARK-PC")
					VEPROMS.CSLA.Library.Database.ConnectionName = "VEPROMS_RMARK_DEMO";
                else if (Environment.UserName.ToUpper() == "BODINE")
                    VEPROMS.CSLA.Library.Database.ConnectionName = "VEPROMS_BODINE_DEMO";
                else
					VEPROMS.CSLA.Library.Database.ConnectionName = "VEPROMS_LOCAL";
			}
			InitializeComponent();

			// When creating an XY Plot, a System.Drawing.Graphics is needed and it requires a form.  Use the main
			// form.
			if (VlnSettings.DebugMode)
			{
				MSWordToPDF.DebugStatus = 1;
				MSWordToPDF.OverrideColor = Color.Red;
			}
			else
			{
				MSWordToPDF.DebugStatus = 0;
				MSWordToPDF.OverrideColor = Color.Transparent;
			}
			MSWordToPDF.FormForPlotGraphics = this;

			// set the color of the ribbon
			RibbonPredefinedColorSchemes.ChangeOffice2007ColorTable((eOffice2007ColorScheme)Settings.Default.SystemColor);

			// LATER: get the user setting to control what is displayed for each tree node
			//  The logic is in the ToString() functions in FolderExt.cs and DocVersionExt.cs
			//the GetFolder(1) function will read in the frist node (using ToString() to assign node text)

			// Get the saved Tree Node Diplay settings
			//if (Settings.Default["UseNameOnTreeNode"])
			//{
			//}
			//if (Settings.Default["UseTitleOnTreeNode"])
			//{ 
			//}
			cmbFont.DataSource = FontFamily.Families;
			cmbFont.DisplayMember = "Name";
			cmbFont.SelectedIndex = -1;
			string[] parameters = System.Environment.CommandLine.Split(" ".ToCharArray());
			foreach (string parameter in parameters)
			{
				if (parameter.StartsWith("/DB="))
					Database.SelectedDatabase = parameter.Substring(4);
			}
			if (Properties.Settings.Default["DefaultDB"] != string.Empty)
				Database.LastDatabase = Properties.Settings.Default.DefaultDB;
			if (!FormatInfo.HasLatestChanges())
				throw new Exception("Inconsistent Formats");
			if (!ItemAuditInfo.IsChangeManagerVersion())
				throw new Exception("Inconsistent Data");
			if (Database.LastDatabase != Database.SelectedDatabase)
			{
				Properties.Settings.Default.MRIList = null;
				Properties.Settings.Default.DefaultDB = Database.SelectedDatabase;
				Properties.Settings.Default.Save();
			}
			DateTime dtSunday = DateTime.Now.AddDays(-((int)DateTime.Now.DayOfWeek));
			ChangeLogFileName("LogFileAppender", Database.SelectedDatabase + " " + dtSunday.ToString("yyyyMMdd") + " ErrorLog.txt");
			_MyLog.InfoFormat("\r\nSession Beginning\r\n<===================== User: {0}/{1} Started {2} =====================>"
				, Environment.UserDomainName,Environment.UserName, DateTime.Now.ToString("dddd MMMM d, yyyy h:mm:ss tt"));
			VETreeNode tn = VETreeNode.GetFolder(1);
			tv.Nodes.Add(tn);
			tv.NodePSI += new vlnTreeViewPSIEvent(tv_NodePSI);
			tv.NodeOpenProperty += new vlnTreeViewPropertyEvent(tv_NodeOpenProperty);
			tv.NodeSelect += new Volian.Controls.Library.vlnTreeViewEvent(tv_NodeSelect);
			tv.NodeNew += new vlnTreeViewEvent(tv_NodeNew);
			tv.OpenItem += new vlnTreeViewItemInfoEvent(tv_OpenItem);
			tv.DeleteItemInfo += new vlnTreeViewItemInfoDeleteEvent(tv_DeleteItemInfo);
			tv.InsertItemInfo += new vlnTreeViewItemInfoInsertEvent(tv_InsertItemInfo);
			tv.NodeInsert += new vlnTreeViewEvent(tv_NodeInsert);
			tv.PasteItemInfo += new vlnTreeViewItemInfoPasteEvent(tv_PasteItemInfo);
			tc.ItemPaste += new StepPanelItemPastedEvent(tc_ItemPasted);
			displayHistory.HistorySelectionChanged += new DisplayHistoryEvent(displayHistory_HistorySelectionChanged);
			_CommentTitleBckColor = epAnnotations.TitleStyle.BackColor1.Color;
			if (!btnAnnoDetailsPushPin.Checked)
				epAnnotations.Expanded = false;
			infoPanel.Expanded = false;
			toolsPanel.Expanded = false;
			displayTags.Visible = false;
			ribbonControl1.ExpandedChanged += new EventHandler(ribbonControl1_ExpandedChanged);
			dlgFindReplace = new FindReplace();
			SpellChecker = new VlnSpellCheck();
			displaySearch1.PrintRequest += new DisplaySearchEvent(displaySearch1_PrintRequest);
			displayHistory.ChronologyPrintRequest += new DisplayHistoryReportEvent(displayHistory_ChronologyPrintRequest);
			displayHistory.SummaryPrintRequest += new DisplayHistoryReportEvent(displayHistory_SummaryPrintRequest);
			displayHistory.AnnotationRestored += new AnnotationRestoredHandler(displayHistory_AnnotationRestored);
			this.Activated += new EventHandler(frmVEPROMS_Activated);
			VlnSettings.StepTypeToolType = Settings.Default.StepTypeToolTip;
			displayLibDocs.PrintRequest += new DisplayLibDocEvent(displayLibDocs_PrintRequest);
			ContentInfo.InfoChanged += new ContentInfoEvent(RefreshDisplayHistory);
			AnnotationInfo.InfoChanged += new AnnotationInfoEvent(RefreshDisplayHistory);
			ItemInfo.InfoRestored += new ItemInfoEvent(RefreshDisplayHistory);
			ItemInfo.ItemDeleted += new ItemInfoEvent(RefreshDisplayHistory);
			tv.PrintProcedure += new vlnTreeViewEvent(tv_PrintProcedure);
			tv.PrintAllProcedures += new vlnTreeViewEvent(tv_PrintAllProcedures);
			tv.ApproveProcedure += new vlnTreeViewEvent(tv_ApproveProcedure);
			tv.ApproveAllProcedures += new vlnTreeViewEvent(tv_ApproveAllProcedures);
			tv.ApproveSomeProcedures += new vlnTreeViewEvent(tv_ApproveSomeProcedures);
			tv.ReportAllProceduresInconsistencies += new vlnTreeViewEvent(tv_ReportAllProceduresInconsistencies);
			tv.ViewPDF += new vlnTreeViewPdfEvent(tv_ViewPDF);
		}

		private void MakeDatabaseChanges()
		{
			// September 2012:	Decided to store roimages as zipped.  Any previous data may not have them zipped.
			//					Check the top folders config to see, and if needed, zip them:
			ROImageInfo.CompressAllExistingImages += new ROImageInfoCompressionEvent(ROImageInfo_CompressAllExistingImages);
			ROImageInfo.ZipImages();
			ROImageInfo.CompressAllExistingImages -= new ROImageInfoCompressionEvent(ROImageInfo_CompressAllExistingImages);

		}

		void ROImageInfo_CompressAllExistingImages(object sender, ROImageInfoCompressionEventArgs args)
		{
			switch (args.Type)
			{
				case ROImageCompressionEventType.Complete:
					ProgBarText = "Compressing Complete";
					break;
				case ROImageCompressionEventType.Initialize:
					ProgBarMax = args.Total;
					ProgBarText = "Compressing RO Images";
					break;
				case ROImageCompressionEventType.Update:
					ProgBarValue = args.Current;
					ProgBarText = args.FileName;
					break;
				default:
					break;
			}
		}
		static string _ErrorLogFileName;

		public static string ErrorLogFileName
		{
			get { return frmVEPROMS._ErrorLogFileName; }
			set { frmVEPROMS._ErrorLogFileName = value; }
		}
		static bool ChangeLogFileName(string AppenderName, string NewFilename)
		{
			log4net.Repository.ILoggerRepository RootRep;
			RootRep = log4net.LogManager.GetRepository();
			foreach (log4net.Appender.IAppender iApp in RootRep.GetAppenders())
			{
				if (iApp.Name.CompareTo(AppenderName) == 0
				&& iApp is log4net.Appender.FileAppender)
				{
					log4net.Appender.FileAppender fApp = (log4net.Appender.FileAppender)iApp;
					string folderPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
					fApp.File = folderPath + @"\VEPROMS\" + NewFilename;
					ErrorLogFileName = fApp.File;
					fApp.ActivateOptions();
					return true; // Appender found and name changed to NewFilename
				}
			}
			return false;
		}
		void tv_ViewPDF(object sender, vlnTreeViewPdfArgs args)
		{
			byte[] buffer;
			if (args.MyWatermark != string.Empty)
				buffer = PromsPrinter.WatermarkPDF(args.MyBuffer, args.MyWatermark);
			else
				buffer = args.MyBuffer;
			string fileName = Volian.Base.Library.VlnSettings.TemporaryFolder + "\\" + args.MyFilename;
			FileStream fs = new FileStream(fileName, FileMode.Create);
			fs.Write(buffer, 0, buffer.Length);
			fs.Close();
			System.Diagnostics.Process.Start(fileName);
		}

		void displayHistory_AnnotationRestored(AnnotationInfo restoredAnnotationInfo, ItemInfo currentItem)
		{
			ctrlAnnotationDetails.UpdateAnnotationGrid(currentItem);
		}

		void tv_ReportAllProceduresInconsistencies(object sender, vlnTreeEventArgs args)
		{
			DocVersionInfo dvi = (args.Node as VETreeNode).VEObject as DocVersionInfo;
			if (dvi == null) return;
			this.Cursor = Cursors.WaitCursor;
			ItemInfoList iil = ItemInfoList.GetAllInconsistencies(dvi.VersionID);
			Volian.Print.Library.PDFConsistencyCheckReport rpt = new Volian.Print.Library.PDFConsistencyCheckReport(Volian.Base.Library.VlnSettings.TemporaryFolder + @"\AllInconsistencies.pdf", iil);
			rpt.BuildAllReport(dvi);
			this.Cursor = Cursors.Default;
		}

		void tv_ApproveSomeProcedures(object sender, vlnTreeEventArgs args)
		{
			DocVersionInfo dvi = (args.Node as VETreeNode).VEObject as DocVersionInfo;
			if (dvi == null) return;
			tc.SaveCurrentEditItem();
			dlgApproveProcedure dlg = new dlgApproveProcedure(dvi, true);
			dlg.ShowDialog(this);
			displayHistory.RefreshList();
		}

		void tv_ApproveAllProcedures(object sender, vlnTreeEventArgs args)
		{
			DocVersionInfo dvi = (args.Node as VETreeNode).VEObject as DocVersionInfo;
			if (dvi == null) return;
			tc.SaveCurrentEditItem();
			dlgApproveProcedure dlg = new dlgApproveProcedure(dvi);
			dlg.ShowDialog(this);
			displayHistory.RefreshList();
		}

		void tv_ApproveProcedure(object sender, vlnTreeEventArgs args)
		{
			ProcedureInfo pi = (args.Node as VETreeNode).VEObject as ProcedureInfo;
			if (pi == null) return;
			tc.SaveCurrentEditItem(pi);
			dlgApproveProcedure dlg = new dlgApproveProcedure(pi);
			dlg.ShowDialog(this);
			displayHistory.RefreshList();
		}

		void tv_PrintAllProcedures(object sender, vlnTreeEventArgs args)
		{
			DocVersionInfo dvi = (args.Node as VETreeNode).VEObject as DocVersionInfo;
			if (dvi == null) return;
			tc.SaveCurrentEditItem();
			DlgPrintProcedure prnDlg = new DlgPrintProcedure(dvi);
			prnDlg.Show();
		}
		void tv_PrintProcedure(object sender, vlnTreeEventArgs args)
		{
			ProcedureInfo pi = (args.Node as VETreeNode).VEObject as ProcedureInfo;
			if (pi == null) return;
			tc.SaveCurrentEditItem(pi);
			DlgPrintProcedure prnDlg = new DlgPrintProcedure(pi);
			prnDlg.Show();
		}
		void RefreshDisplayHistory(object sender)
		{
			displayHistory.RefreshChangeList();
		}
		void displayHistory_HistorySelectionChanged(object sender, DisplayHistoryEventArgs args)
		{
			tc.OpenItem(ItemInfo.Get(args.ItemID));
		}
		void displayHistory_SummaryPrintRequest(object sender, DisplayHistoryReportEventArgs args)
		{
			Volian.Print.Library.PDFChronologyReport myChronoRpt = new Volian.Print.Library.PDFChronologyReport(args.ReportTitle, args.ProcedureInfo, args.AuditList, args.AnnotationList);
			myChronoRpt.BuildSummary();
		}
		void displayHistory_ChronologyPrintRequest(object sender, DisplayHistoryReportEventArgs args)
		{
			Volian.Print.Library.PDFChronologyReport myChronoRpt = new Volian.Print.Library.PDFChronologyReport(args.ReportTitle, args.ProcedureInfo, args.AuditList, args.AnnotationList);
			myChronoRpt.BuildChronology();
		}
		DialogResult tv_NodePSI(object sender, vlnTreeEventArgs args)
		{
			VETreeNode vNode = (VETreeNode)args.Node;
			IVEDrillDownReadOnly veObj = vNode.VEObject;
			ProcedureInfo myProc = veObj as ProcedureInfo;
			frmPSI fpsi = new frmPSI(myProc);
			return fpsi.ShowDialog();
		}
		/// <summary>
		/// Activate tmrTreeView so that the newly created Step recieves focus
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="args"></param>
		void tv_NodeInsert(object sender, vlnTreeEventArgs args)
		{
			tmrTreeView.Enabled = true;
		}
		void frmVEPROMS_Activated(object sender, EventArgs e)
		{
			if (ActiveControl == tc) tc.HideCaret();
			// refresh anything that pertains to external files or programs:

			// if ro.fst was 'updated' from the roeditor, enable the update ro.fst values on
			// the steptabribbon.
			if (SelectedStepTabPanel!=null && SelectedStepTabPanel.MyStepTabRibbon != null)
				SelectedStepTabPanel.MyStepTabRibbon.SetUpdRoValBtn(SelectedStepTabPanel.MyStepTabRibbon.NewerRoFst());
		}
		void MyStepTabRibbon_PrintRequest(object sender, StepTabRibbonEventArgs args)
		{
			ProcedureInfo pi = args.Proc as ProcedureInfo;
			if (pi == null) return;
			DlgPrintProcedure prnDlg = new DlgPrintProcedure(pi);
			prnDlg.Show();
		}
		void displaySearch1_PrintRequest(object sender, DisplaySearchEventArgs args)
		{
			Volian.Print.Library.PDFReport myReport = new Volian.Print.Library.PDFReport(args.ReportTitle, args.TypesSelected, args.MyItemInfoList,
				Volian.Base.Library.VlnSettings.TemporaryFolder + @"\searchresults.pdf");
			if (args.SearchString != null) 
				myReport.SearchString = args.SearchString;
			myReport.Build();
		}

		void displayLibDocs_PrintRequest(object sender, DisplayLibDocEventArgs args)
		{
			Volian.Print.Library.PDFReport myReport = new Volian.Print.Library.PDFReport(args.ReportTitle, args.LibDocList, Volian.Base.Library.VlnSettings.TemporaryFolder + @"\LibDocUsage.pdf");
			myReport.Build();
		}

		bool tv_InsertItemInfo(object sender, vlnTreeItemInfoInsertEventArgs args)
		{
			// Don't select the newly created Step.  This will be handled by tmrTreeView
			return tc.InsertRTBItem(args.MyItemInfo, args.StepText, args.InsertType, args.FromType, args.Type, false);
		}
		private bool tv_DeleteItemInfo(object sender, vlnTreeItemInfoEventArgs args)
		{
			if (displayHistory.MyEditItem != null && displayHistory.MyItemInfo.MyProcedure.ItemID == args.MyItemInfo.ItemID)
				displayHistory.MyEditItem = null;
			return tc.DeleteRTBItem(args.MyItemInfo);
			//if (si == null) return false;
			//si.RemoveItem();
			//return true;
		}
		private bool tv_PasteItemInfo(object sender, vlnTreeItemInfoPasteEventArgs args)
		{
			return tc.PasteRTBItem(args.MyItemInfo, args.CopyStartID, args.PasteType, (int)args.Type);
		}
		private void frmVEPROMS_FormClosing(object sender, FormClosingEventArgs e)
		{
			// Save the location and size of the VE-PROMS appication for this user
			if (this.WindowState == FormWindowState.Normal)
			{
				Settings.Default.Location = this.Location;
				Settings.Default.Size = this.Size;
			}
			Settings.Default.WindowState = this.WindowState;
			Settings.Default.QATItems = ribbonControl1.QatLayout;
			SaveMRU();
			//Settings.Default.Save();
		}
		private void frmVEPROMS_Load(object sender, EventArgs e)
		{
			//string debugMode = ConfigurationManager.AppSettings["Debug"];
			//VlnSettings.DebugMode = bool.Parse(debugMode); // set debug for the Volian.Controls.Library
			// get the saved location and size of the VE-PROMS appication for this user
			if (Settings.Default["Location"] != null) this.Location = Settings.Default.Location;
			if (Settings.Default["Size"] != null) this.Size = Settings.Default.Size;
			if (Settings.Default["WindowState"] != null) this.WindowState = Settings.Default.WindowState;
			if (Settings.Default.SaveTreeviewExpanded)epProcedures.Expanded = Settings.Default.TreeviewExpanded;
			if (Settings.Default["QATItems"] != null) ribbonControl1.QatLayout = Settings.Default.QATItems;
			
			// See if any database 'changes' need done and do them:
			MakeDatabaseChanges();

			_MyMRIList = MostRecentItemList.GetMRILst((System.Collections.Specialized.StringCollection)(Properties.Settings.Default["MRIList"]));
			_MyMRIList.AfterRemove += new ItemInfoEvent(_MyMRIList_AfterRemove);
			SetupMRU();
			if (epProcedures.Expanded && _MyMRIList.Count > 0)
			{
				tv.AdjustTree(_MyMRIList[0].MyItemInfo.MyProcedure);
				tv.SelectedNode.Expand();
				SetCaption(tv.SelectedNode as VETreeNode);
			}
			displaySearch1.SetupAnnotationSearch(ctrlAnnotationDetails, tc);
			AnnotationTypeInfoList.ListChanged += new AnnotationTypeInfoListEvent(AnnotationTypeInfoList_ListChanged);
			ctrlAnnotationDetails.SetupAnnotations(displaySearch1);
			SetupButtons();
			displayBookMarks.MyDisplayTabControl = tc;		// allows bookmark selection to bring up steps/docs
			office2007StartButton1.MouseDown +=new MouseEventHandler(office2007StartButton1_MouseDown);
			//displayRO.EnabledChanged += new EventHandler(displayRO_EnabledChanged);
			tc.Enter += new EventHandler(tc_Enter);
			tc.Leave += new EventHandler(tc_Leave);
			tc.ToggleRibbonExpanded += new DisplayTabControlEvent(tc_ToggleRibbonExpanded);
			this.Deactivate += new EventHandler(frmVEPROMS_Deactivate);
			if (VlnSettings.DemoMode) StepRTB.MyFontFamily = GetFamily("Bookman Old Style");
			displaySearch1.Enter += new EventHandler(displaySearch1_Enter);
			displayHistory.Enter += new EventHandler(displayHistory_Enter);
			ctrlAnnotationDetails.Enter += new EventHandler(ctrlAnnotationDetails_Enter);
			Application.DoEvents();
			if (RunningNewRevision && ShowEULA() != DialogResult.OK)
			{
				Timer tmrShutDown = new Timer();
				tmrShutDown.Interval = 250;
				tmrShutDown.Tick += new EventHandler(tmrShutDown_Tick);
				tmrShutDown.Enabled = true;
			}
			else
				RunAutomatic();
			// Shutoff UpdateFormats for Production Mode
			if (Volian.Base.Library.VlnSettings.ProductionMode)
				btnAdmin.Visible = false;
		}
		void tmrShutDown_Tick(object sender, EventArgs e)
		{
			(sender as Timer).Enabled = false;
			this.Close();
		}
		private DialogResult ShowEULA()
		{
			string eulaFile = string.Format(@"\{0}", VlnSettings.EULAfile);
			string strEULA = System.Environment.CurrentDirectory + eulaFile;
			frmViewTextFile ViewFile = new frmViewTextFile(strEULA, RichTextBoxStreamType.PlainText);
			ViewFile.Text = "End-User License Agreement";
			ViewFile.ButtonText = "Agree";
			if (ViewFile.ShowDialog() == DialogResult.OK)
			{
				System.Version ver = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
				string thisVersion = ver.Major.ToString() + "." + ver.Minor.ToString();
				Properties.Settings.Default.LastVersion = thisVersion;
				return DialogResult.OK;
			}
			return DialogResult.Cancel;
		}
		private bool RunningNewRevision
		{
			get
			{
				string lastVersion = Properties.Settings.Default.LastVersion;
				System.Version ver = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
				string thisVersion = ver.Major.ToString() + "." + ver.Minor.ToString();
				return thisVersion != lastVersion;
			}
		}
		void displayHistory_Enter(object sender, EventArgs e)
		{
			tc.HideCaret();
		}
		void AnnotationTypeInfoList_ListChanged()
		{
			displaySearch1.SetupAnnotationSearch(ctrlAnnotationDetails, tc);
			ctrlAnnotationDetails.SetupAnnotations(displaySearch1);
		}
		private void RunAutomatic()
		{
			string[] parameters = System.Environment.CommandLine.Split(" ".ToCharArray());
			bool ranAuto = false;
			foreach (string parameter in parameters)
			{
				if(parameter.StartsWith("/P="))
				{
					string[] dvstrs = parameter.Substring(3).Split(",".ToCharArray());
					foreach (string dvstr in dvstrs)
					{
						DocVersionInfo dvi = DocVersionInfo.Get(int.Parse(dvstr));
						if (dvi != null)
						{
							DlgPrintProcedure prnDlg = new DlgPrintProcedure(dvi,true);
							prnDlg.ShowDialog();
							//prnDlg.FormClosed += new FormClosedEventHandler(prnDlg_FormClosed);
							//while (!_RunNext) Application.DoEvents();
							ranAuto = true;
						}
					}
				}
			}
			if(ranAuto) this.Close();
		}
		private bool _RunNext = false;
		//void prnDlg_FormClosed(object sender, FormClosedEventArgs e)
		//{
		//  _RunNext = true;
		//}
		private FontFamily GetFamily(string name)
		{
			foreach (FontFamily ff in FontFamily.Families)
				if (ff.Name == name) return ff;
			return null;
		}
		void tc_ToggleRibbonExpanded(object sender, EventArgs args)
		{
			Volian.Base.Library.vlnStackTrace.ShowStackLocal("tc_ToggleRibbonExpanded {0}", ribbonControl1.Expanded);
			ribbonControl1.Expanded = !ribbonControl1.Expanded;
		}
		void frmVEPROMS_Deactivate(object sender, EventArgs e)
		{
			tc.HideCaret(); // Hide the pseudo cursor (caret)
		}
		void tc_Leave(object sender, EventArgs e)
		{
			tc.ShowCaret();// Show the pseudo cursor (caret)
		}
		void tc_Enter(object sender, EventArgs e)
		{
			tc.HideCaret();// Hide the pseudo cursor (caret)
		}
		void displaySearch1_Enter(object sender, EventArgs e)
		{
			tc.HideCaret();// Hide the pseudo cursor (caret)
		}
		void ctrlAnnotationDetails_Enter(object sender, EventArgs e)
		{
			tc.HideCaret();// Hide the pseudo cursor (caret)
		}
		//void displayRO_EnabledChanged(object sender, EventArgs e)
		//{
		//  Console.WriteLine("here");
		//}
		void _MyMRIList_AfterRemove(object sender)
		{
			SetupMRU();
		}
		private void SetupButtons()
		{
			if (!VlnSettings.DebugMode)
			{
				lblItemID.Visible = false;
				btnItemInfo.Visible = false;
				cmbFont.Visible = false;
				btnEditItem.Visible = false;
				lblResolution.Visible = false;
			}
		}
		#region MRU
		private MostRecentItemList _MyMRIList;
		private void SetupMRU()
		{
			icRecentDocs.SubItems.Clear();
			if (_MyMRIList.Count > 0)
			{
				LabelItem lblItem = new LabelItem();
				lblItem.Text = "Recent Documents:";
				icRecentDocs.SubItems.Add(lblItem);
				//icRecentDocs.SubItems.Add();
				for (int i = 0; i < _MyMRIList.Count; i++)
				{
					MostRecentItem mri = _MyMRIList[i];
					ButtonItem btnItem = new ButtonItem();
					string menuTitle = mri.MenuTitle.Replace("\u2011", "-");
					if (i < 9)
						btnItem.Text = string.Format("<b>&{0}.</b> {1}", i + 1, menuTitle);
					else
						btnItem.Text = string.Format("   {1}", i + 1, menuTitle);
					btnItem.Tag = mri.ItemID;
					btnItem.Tooltip = mri.ToolTip;
					btnItem.Click += new EventHandler(btnItem_Click);
					icRecentDocs.SubItems.Add(btnItem);
				}
			}
		}

		void btnItem_Click(object sender, EventArgs e)
		{
			ButtonItem btnItem = (ButtonItem)sender;
			MostRecentItem mri = _MyMRIList.Add((int)(btnItem.Tag));
			//SaveMRU();
			SetupMRU();
			if (mri != null) tc.OpenItem(mri.MyItemInfo);
		}
		private void SaveMRU()
		{
			Properties.Settings.Default.MRIList = _MyMRIList.ToSettings();
			Properties.Settings.Default.TreeviewExpanded = epProcedures.Expanded;
			Properties.Settings.Default.Save();
		}
		#endregion
		#region Tree View
		/// <summary>
		/// Get the selected tree node's properties
		/// </summary>
		/// <param name="node">VETreeNode</param>
		bool SetupNodes(VETreeNode node)
		{
			if (_MyMRIList.Add(node.VEObject) != null)
				SetupMRU();
			#region Sample Display Table Code
			// display an exiting table in that rtf grid thing
			//if ((_LastStepInfo.MyContent.Type == 20007) || (_LastStepInfo.MyContent.Type == 20009))
			//{
			//   //MessageBox.Show("Source Grid");
			//   //frmTable newtable1 = new frmTable(_LastStepInfo.MyContent.Text);
			//   //newtable1.ShowDialog();
			//   //MessageBox.Show("IGrid");
			//   //frmIGrid newtable2 = new frmIGrid(_LastStepInfo.MyContent.Text);
			//   //newtable2.ShowDialog();
			//   //MessageBox.Show("GridView"); //standard Visual Studio Control
			//   //frmGridView newtable3 = new frmGridView(_LastStepInfo.MyContent.Text);
			//   //newtable3.ShowDialog();
			//   MessageBox.Show("FlexCell");
			//   frmFlexCell newtable4 = new frmFlexCell(_LastStepInfo.MyContent.Text);
			//   newtable4.ShowDialog();
			//}
			#endregion
			ItemInfo ii = node.VEObject as ItemInfo;
			if (ii != null) tc.OpenItem(ii);
			SetCaption(node);
			return (ii != null);	// return if successful on opening item in step editor or word
		}
		// The following code is used to setup the user interface depending on what
		// is selected on the tree view (see vlnTreeView.cs)
		void tv_NodeNew(object sender, vlnTreeEventArgs args)
		{
			VETreeNode vNode = (VETreeNode)args.Node;
			IVEDrillDownReadOnly veObj = vNode.VEObject;
			SectionInfo mySection = veObj as SectionInfo;
			if (mySection != null && mySection.MyContent.MyEntry != null)
			{
				// if it is a word section, find the DisplayTabItem;
				DisplayTabItem tabItem = tc.GetProcDisplayTabItem(mySection);
				if(tabItem != null)tabItem.MyStepTabPanel.MyStepPanel.Reset();
			}
			// Don't select the newly created Step.  This will be handled by tmrTreeView
			//SetupNodes((VETreeNode)args.Node);
		}
		private void tv_NodeSelect(object sender, vlnTreeEventArgs args)
		{
			SetupNodes((VETreeNode)args.Node);
		}
		private void SetCaption(VETreeNode tn)
		{
			StringBuilder caption = new StringBuilder();
			string sep = string.Empty;
			while (tn != null)
			{
				if (tn.VEObject.GetType() == typeof(FolderInfo) || tn.VEObject.GetType() == typeof(DocVersionInfo))
				{
					//caption.Append(sep + tn.Text);
					caption.Insert(0, tn.Text + sep);
					sep = " - ";
				}
				tn = (VETreeNode)tn.Parent;
			}
			this.Text = caption.ToString();
		}
		void tv_OpenItem(object sender, vlnTreeItemInfoEventArgs args)
		{
			tc.OpenItem(args.MyItemInfo);
		}
		/// <summary>
		/// When the treeview is clicked - a timer is set
		/// This is done because the focus is returned to the treeview after the click event
		/// This approach did not work and was replaced with the code below.
		/// The problem was that each time the treeview was clicked, the last selected node
		/// was opened again, or the edit window was repositioned.
		/// If the item was deleted and another treenode expanded, the click to expand the
		/// node would cause the deleted node to be selected.
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		//private void tv_Click(object sender, EventArgs e)
		//{
		//tv.Enabled = false;
		//tmrTreeView.Enabled = true;
		//}
		/// <summary>
		/// This opens nodes if the mouse is within the bounds of a node.
		/// By using the timer, the focus can be passed to the edit window.
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		void tv_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
		{
			if (e.Button != MouseButtons.Right)
			{
				Point newPoint = new Point(e.X, e.Y);
				VETreeNode tn = tv.GetNodeAt(newPoint) as VETreeNode;
				// Check to make sure that a node has been selected and 
				// that the mouse is within the bounds of the node.
				if (tn != null && tn.Bounds.Left < newPoint.X)
				{
					tv.SelectedNode = tn;
					tv.Enabled = false;
					tmrTreeView.Enabled = true;
				}
				else
				{
					if (tn != null && tn.Bounds.Left < newPoint.X + 30)
						return;
					if (tc.SelectedDisplayTabItem != null && tc.SelectedDisplayTabItem.SelectedItemInfo != null)
					{
						tv.AdjustTree(tc.SelectedDisplayTabItem.SelectedItemInfo);
						tc.SelectedDisplayTabItem.Focus();
						SetCaption(tv.SelectedNode as VETreeNode);
					}
				}
			}
		}
		/// <summary>
		/// This event is fired from the timer after the treeview click event completes
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void tmrTreeView_Tick(object sender, EventArgs e)
		{
			bool giveTvFocus = true;
			tmrTreeView.Enabled = false; // Timer has now fired
			VETreeNode tn = tv.SelectedNode as VETreeNode;
			if (tn != null) giveTvFocus = !SetupNodes(tn);
			tv.Enabled = true;
			if (giveTvFocus) tv.Focus();
		}
		private void tv_BeforeExpand(object sender, TreeViewCancelEventArgs e)
		{
			VETreeNode tn = ((VETreeNode)e.Node);
			tn.LoadingChildrenDone += new VETreeNodeEvent(tn_LoadingChildrenDone);
			tn.LoadingChildrenMax += new VETreeNodeEvent(tn_LoadingChildrenMax);
			tn.LoadingChildrenValue += new VETreeNodeEvent(tn_LoadingChildrenValue);
			tn.LoadingChildrenSQL += new VETreeNodeEvent(tn_LoadingChildrenSQL);
			tn.LoadChildren(true);
		}
		#region Property Page and Grid
		DialogResult tv_NodeOpenProperty(object sender, vlnTreePropertyEventArgs args)
		{
			this.Cursor = Cursors.WaitCursor;
			DialogResult dr = DialogResult.Cancel;
			if ((int)Settings.Default["PropPageStyle"] == (int)PropPgStyle.Grid)
			{
				frmPropGrid propGrid = new frmPropGrid(args.ConfigObject, args.Title);
				dr = propGrid.ShowDialog();
			}
			else
			{
				if (args.FolderConfig != null)
				{
					frmFolderProperties frmfld = new frmFolderProperties(args.FolderConfig);
					dr = frmfld.ShowDialog();
				}
				else if (args.DocVersionConfig != null)
				{
					frmVersionsProperties frmver = new frmVersionsProperties(args.DocVersionConfig);
					dr = frmver.ShowDialog();
				}
				else if (args.ProcedureConfig != null)
				{
					frmProcedureProperties frmproc = new frmProcedureProperties(args.ProcedureConfig);
					dr = frmproc.ShowDialog();
				}
				else if (args.SectionConfig != null)
				{
					//// If this is a word document, close any edit sessions...
					//ItemInfo ii = null;
					//using (Section tmp = args.SectionConfig.MySection)
					//{
					//    ii = ItemInfo.Get(tmp.ItemID);
					//    if (!ii.IsStepSection) tc.CloseWordItem(ii);
					//}

					frmSectionProperties frmsec = new frmSectionProperties(args.SectionConfig);
					dr = frmsec.ShowDialog();
					if (dr == DialogResult.OK && displayLibDocs.LibDocList != null)
					{
						displayLibDocs.LibDocListFillIn(tc);

					}
				}
			}
			this.Cursor = Cursors.Default;
			return dr;
		}
		#endregion
		#endregion
		#region ColorStuff
		/// <summary>
		/// Get a System.Drawing.Color from an Argb or color name
		/// </summary>
		/// <param name="strColor">Color Name or "[(alpha,)red,green,blue]"</param>
		/// <returns></returns>
		private static Color cGetColor(string strColor)
		{
			// This was copied from frmFolderProperties.CS
			Color rtnColor;
			if (strColor == null || strColor.Equals(""))
				rtnColor = Color.White;
			else
			{
				if (strColor[0] == '[')
				{
					string[] parts = strColor.Substring(1, strColor.Length - 2).Split(",".ToCharArray());
					int parts_cnt = 0;
					foreach (string s in parts)
					{
						parts[parts_cnt] = parts[parts_cnt].TrimStart(' '); // remove preceeding blanks
						parts_cnt++;
					}
					if (parts_cnt == 3)
						rtnColor = Color.FromArgb(Int32.Parse(parts[0]), Int32.Parse(parts[1]), Int32.Parse(parts[2]));
					else
						rtnColor = Color.FromArgb(Int32.Parse(parts[0].Substring(2)), Int32.Parse(parts[1].Substring(2)), Int32.Parse(parts[2].Substring(2)), Int32.Parse(parts[3].Substring(2)));
				}
				else rtnColor = Color.FromName(strColor);
			}
			return rtnColor;
		}
		//private void SetupEditorColors(DisplayPanel vlnCSLAPanel1, TabPage pg)
		//{
		//  // setup color
		//  if (_LastFolderInfo == null)
		//  {
		//    // user didn't select a FolderInfo type of node.
		//    // walk up the tree to find the first FolderInfo node type
		//    VETreeNode tn = (VETreeNode)(tv.SelectedNode);
		//    while (tn != null && tn.VEObject.GetType() != typeof(FolderInfo))
		//      tn = (VETreeNode)tn.Parent;
		//    _LastFolderInfo = (FolderInfo)(tn.VEObject);
		//    _LastFolder = _LastFolderInfo.Get();
		//  }

		//  if ((_LastFolderInfo.FolderConfig.Color_editbackground != null) && !(_LastFolderInfo.FolderConfig.Color_editbackground.Equals("")))
		//  {
		//    vlnCSLAPanel1.ActiveColor = cGetColor(_LastFolderInfo.FolderConfig.Color_editbackground);
		//  }
		//  if ((_LastFolderInfo.FolderConfig.Default_BkColor != null) && !(_LastFolderInfo.FolderConfig.Default_BkColor.Equals("")))
		//  {
		//    vlnCSLAPanel1.InactiveColor = _LastFolderInfo.FolderConfig.Default_BkColor;
		//    vlnCSLAPanel1.TabColor = vlnCSLAPanel1.InactiveColor;
		//    vlnCSLAPanel1.PanelColor = vlnCSLAPanel1.InactiveColor;
		//    pg.BackColor = vlnCSLAPanel1.InactiveColor;
		//  }
		//}
		#endregion
		#region Table Insert Sample Code
		// TODO: for tables
		//private void btnInsTable_Click(object sender, EventArgs e)
		//{
		//    Point loc = btnInsTable.DisplayRectangle.Location;
		//    loc.X += 300;
		//    int top = this.Top + (btnInsTable.Size.Height * 2);
		//    TablePickerDlg(sender, e, loc, top);
		//}

		//private void TablePickerDlg(object sender, EventArgs e, Point loc, int top)
		//{
		//    Accentra.Controls.TablePicker tp = new Accentra.Controls.TablePicker();
		//    tp.Location = loc;
		//    tp.Top += top;
		//    tp.Show();
		//    while (tp.Visible)
		//    {
		//        Application.DoEvents();
		//        System.Threading.Thread.Sleep(0);
		//    }
		//    // This was used to display a dialog containing a table grid
		//    // using a product called Source Grid - was for demo purposes only
		//    //
		//    //if (!tp.Cancel)
		//    //{
		//    //   frmTable newtable = new frmTable(tp.SelectedRows, tp.SelectedColumns);
		//    //   newtable.Show();
		//    //}
		//}
		#endregion
		#region Progress Bar

		/// <summary>
		/// Used for the status bar in the lower left corner of the main screen
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="args"></param>
		void tn_LoadingChildrenSQL(object sender, VETreeNodeEventArgs args)
		{
			ProgBarText = "Loading SQL";
		}

		/// <summary>
		/// Used for the status bar in the lower left corner of the main screen
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="args"></param>
		void tn_LoadingChildrenValue(object sender, VETreeNodeEventArgs args)
		{
			ProgBarValue = args.Value;
		}

		/// <summary>
		/// Used for the status bar in the lower left corner of the main screen
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="args"></param>
		void tn_LoadingChildrenMax(object sender, VETreeNodeEventArgs args)
		{
			ProgBarMax = args.Value;
			ProgBarText = "Loading...";
		}

		/// <summary>
		/// Used for the status bar in the lower left corner of the main screen
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="args"></param>
		void tn_LoadingChildrenDone(object sender, VETreeNodeEventArgs args)
		{
			if (VlnSettings.DebugMode)
				ProgBarText = args.Info + " Seconds";
			else
				ProgBarText = "";
		}

		public int ProgBarMax
		{
			get { return bottomProgBar.Maximum; }
			set { bottomProgBar.Maximum = value; }
		}

		public int ProgBarValue
		{
			get { return bottomProgBar.Value; }
			set { bottomProgBar.Value = value; }
		}

		public string ProgBarText
		{
			get { return bottomProgBar.Text; }
			set
			{
				bottomProgBar.TextVisible = true;
				bottomProgBar.Text = value;
			}
		}

		#endregion
		#region Find/Replace and Search

		/// <summary>
		/// Find/Replace button on the ribbon
		/// Display the Find/Replace dialog
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		//private void btnFindRplDlg_Click_1(object sender, EventArgs e)
		//{
		//    FindReplace frmFindRepl = new FindReplace();
		//    frmFindRepl.Show();
		//}

		/// <summary>
		/// Global Search button on the ribbon
		/// Opens the Information Pannel and selects the Results tab
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		//private void btnGlbSrch_Click(object sender, EventArgs e)
		//{
		//    toolsPanel.Expanded = true;
		//    toolsTabs.SelectedTab = toolstabResults;
		//}

		#endregion
		#region Similar Steps

		/// <summary>
		/// Similar Steps button on the ribbon
		/// Opens the Information Pannel and selects the Results tab
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void btnSimStps_Click(object sender, EventArgs e)
		{
			//infoPanel.Expanded = true;
			//infoTabs.SelectedTab = toolstabResults;
			//btnSimStpsRslt.Checked = true;
		}

		#endregion
		#region Help/About

		/// <summary>
		/// About button on the ribbon
		/// Display the About dialog
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void btnAbout_Click(object sender, EventArgs e)
		{
			AboutVEPROMS about = new AboutVEPROMS();
			about.ShowDialog();
		}

		/// <summary>
		/// Volian Web button on the ribbon
		/// display the Volian web site on a pop up form
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void btnVlnWeb_Click(object sender, EventArgs e)
		{
			VlnWeb veWWW = new VlnWeb();
			veWWW.Show();
		}

		#endregion
		#region Ribbon
		/// <summary>
		/// This Opens the treeView or opens the selected item in the TreeView
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void btnOpen_Click(object sender, EventArgs e)
		{
			if (!epProcedures.Expanded) // If panel not expanded - expand it.
			{
				epProcedures.Expanded = true;
				if (tv.Nodes.Count > 0 && tv.SelectedNode == null)
					tv.SelectedNode = tv.Nodes[0];
				tv.Focus();
			}
			else
			{
				// TODO: DeleteMe
				//VETreeNode tn = (VETreeNode)(tv.SelectedNode);
				tv.OpenNode();
			}
		}
		private void btnNew_Click(object sender, EventArgs e)
		{
			if (!epProcedures.Expanded) return;
			VETreeNode vtn = tv.SelectedNode as VETreeNode;
			if (vtn == null) return;				// nothing was selected.
			if (btnNew.SubItems.Count > 0) return;	// submenu will be displayed
			vtn.Expand();

			// Determine type of 'new' based on tree node's object type.  The
			// only options here are those that would not have created, based on
			// containers, a submenu (see the office2007buttonstartbutton1_click code)
			FolderInfo fi = vtn.VEObject as FolderInfo;
			if (fi != null)
			{
				tv.tv_NodeNew(vlnTreeView.MenuSelections.Folder);
				return;
			}

			DocVersionInfo dvi = vtn.VEObject as DocVersionInfo;
			if (dvi != null)
			{
				tv.tv_NodeNew(vlnTreeView.MenuSelections.Procedure);
				return;
			}

			// All other types are handled with sub-menus.

		}

		/// <summary>
		/// Options button on the dialog that appears when the V icon is clicked (top left of application window)
		/// note that the "V icon" is also called the Office 2007 Start Button
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void btnOptions_Click(object sender, EventArgs e)
		{
			frmSysOptions VeSysOpts = new frmSysOptions();
			VeSysOpts.ShowDialog();

		}
		/// <summary>
		/// Exit button on the dialog that appears when the V icon is clicked (top left of application window)
		/// note that the "V icon" is also called the Office 2007 Start Button
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void btnExit_Click(object sender, EventArgs e)
		{
			this.Close();
		}
		#endregion
		#region InfoTabRO
		private void infotabRO_Click(object sender, EventArgs e)
		{
			infoPanel.Expanded = true;
			infoTabs.SelectedTab = infotabRO;
			//if (dtp == null) return;

			displayRO.Mydvi = SelectedDVI;
			displayRO.MyROFST = SelectedROFst;
			displayRO.MyRTB = (SelectedStepTabPanel == null) ? null : SelectedStepTabPanel.MyStepPanel.SelectedEditItem.MyStepRTB;
			displayRO.TabControl = tc;

			displayRO.ProgressBar = bottomProgBar;
		}
		#endregion
		#region InfoTabTransition
		private void infotabTransition_Click(object sender, EventArgs e)
		{
			if (tc == null || tc.SelectedDisplayTabItem == null) return;
			if (SelectedStepTabPanel == null) return;
			displayTransition.MyRTB = SelectedStepTabPanel.MyStepPanel.SelectedEditItem.MyStepRTB;
			//displayTransition.RangeColor = global::VEPROMS.Properties.Settings.Default.TransitionRangeColor;
			displayTransition.CurTrans = null;
		}
		#endregion
		#region InfoTabLibDocs
		private void tabItemLibDocs_Click(object sender, EventArgs e)
		{
			displayLibDocs.RefreshLibDocPanel(tc);
			//displayLibDocs.LibDocListFillIn(tc);
		}
		private void tv_SectionShouldClose(object sender, vlnTreeSectionInfoEventArgs args)
		{
			if (!args.MySectionInfo.IsStepSection) tc.CloseWordItem(args.MySectionInfo, args.IsDeleting);
			else
			{
				if (tc == null) return;
				StepTabPanel tp = tc.GetProcedureTabPanel(args.MySectionInfo as ItemInfo);
				if (tp == null) return;
				DisplayTabItem ti = tp.MyDisplayTabItem;
				tc.CloseTabItem(ti);
			}
		}
		private void tv_WordSectionDeleted(object sender, WordSectionEventArgs args)
		{
			// is it a library document - if so and libdoc panel is visible, update lists on panel.
			if ((!args.MySectionInfo.IsStepSection) && ((args.MySectionInfo.MyContent.MyEntry.MyDocument.LibTitle ?? "") != "") && (toolsPanel.Expanded))
			{
				if (toolsTabs.SelectedTab == tabItemLibDocs)
				{
					displayLibDocs.RefreshLibDocPanel(tc);
				}
			}
		}
		#endregion
		#region InfoTabTags
		private void infotabTags_Click(object sender, EventArgs e)
		{
			infoPanel.Expanded = true;
			infoTabs.SelectedTab = infotabTags;
			displayTags.MyEditItem = (SelectedStepTabPanel == null) ? null : SelectedStepTabPanel.MyStepPanel.SelectedEditItem;
		}
		#endregion
		#region InfoTabBookMarks
		private void infotabBookMarks_Click(object sender, EventArgs e)
		{
			infoPanel.Expanded = true;
			infoTabs.SelectedTab = infotabTags;
			displayTags.MyEditItem = (SelectedStepTabPanel == null) ? null : SelectedStepTabPanel.MyStepPanel.SelectedEditItem;
		}
		#endregion
		#region PanelSupport
		private void tc_WordSectionClose(object sender, WordSectionEventArgs args)
		{
			if (!args.MySectionInfo.IsStepSection) tc.CloseWordItem(args.MySectionInfo);
		}
		private void tc_WordSectionDeleted(object sender, WordSectionEventArgs args)
		{
			// is it a library document - if so and libdoc panel is visible, update lists on panel.
			if ((!args.MySectionInfo.IsStepSection) && ((args.MySectionInfo.MyContent.MyEntry.MyDocument.LibTitle ?? "") != "") && (toolsPanel.Expanded))
			{
				if (toolsTabs.SelectedTab == tabItemLibDocs)
				{
					displayLibDocs.RefreshLibDocPanel(tc);
				}
			}
		}
		private void tc_ItemPasted(object sender, vlnTreeItemInfoPasteEventArgs args)
		{
			// all this needs to do is refresh the libdoc display - if it is visible
			// and the current item is word section, i.e. it may be a lib doc & would
			// require refresh of the lib doc panel.
			if (toolsTabs.SelectedTab == tabItemLibDocs && args.MyItemInfo.IsSection)
			{
				SectionInfo si = args.MyItemInfo as SectionInfo;
				if (si != null && (si.MyContent.MyEntry.MyDocument.LibTitle ?? "") != "") displayLibDocs.RefreshLibDocPanel(tc);
			}
			displayHistory.RefreshChangeList();
		}
		private void tc_PanelTabDisplay(object sender, StepPanelTabDisplayEventArgs args)
		{
			if (args.PanelTabName == "Bookmarks")
			{
				toolsPanel.Expanded = true;
				toolsTabs.SelectedTab = toolsTabBookMarks;
				if (_CurrentItem != null && !dlgFindReplace.Visible) displayBookMarks.AddBookMark(_CurrentItem);
			}
			else if (args.PanelTabName == "Global Search")
			{
				toolsPanel.Expanded = true;
				toolsTabs.SelectedTab = toolstabResults;
			}
			else if (args.PanelTabName == "LibDocs")
			{
				toolsPanel.Expanded = true;
				toolsTabs.SelectedTab = tabItemLibDocs;
				toolsTabs.SelectedTab.PerformClick();
			}
			else if (args.PanelTabName == "Annots")
			{
				epAnnotations.Expanded = true;
			}
			else if (args.PanelTabName == "Change Step Type")
			{
				infoPanel.Expanded = true;
				infoTabs.SelectedTab = infotabTags;
				displayTags.HighlightChangeStep();
			}
			else if (args.PanelTabName == "FndRpl")
			{
				dlgFindReplace.InApproved = (_SelectedDVI != null && _SelectedDVI.VersionType == 127);
				dlgFindReplace.Mydocversion = _SelectedDVI;
				dlgFindReplace.Visible = true;
				dlgFindReplace.MyDisplayBookMarks = displayBookMarks;
			}
			else if (args.PanelTabName == "SpellChecker")
			{
				SpellChecker.DoSpellCheck();
			}
			else if (args.PanelTabName == "DisplayROUpdateROFST")
			{
				_SelectedROFst = null;
				displayRO.MyROFST = SelectedROFst;
				displayRO.RefreshRoTree();
			}
		}
		private void tc_SelectedDisplayTabItemChanged(object sender, EventArgs args)
		{
			// If the current procedure or section in the treeview doesn't match then change the treeview selection.
			//jcb added for error B2012-117
			ItemInfo tvii;
			if (tv.SelectedNode == null)
				tvii = null;
			else
				tvii = ((tv.SelectedNode as VETreeNode).VEObject) as ItemInfo;
			if (tc.SelectedDisplayTabItem == null) return;
			if (tc.SelectedDisplayTabItem.MyItemInfo.IsProcedure)
			{
				if (tvii == null || tvii.IsSection || tc.SelectedDisplayTabItem.MyItemInfo.ItemID != tvii.MyProcedure.ItemID)
					tv.AdjustTree(tc.SelectedDisplayTabItem.MyItemInfo);
			}
			else
			{
				if (tvii == null || tc.SelectedDisplayTabItem.MyItemInfo.ItemID != tvii.ItemID)
					tv.AdjustTree(tc.SelectedDisplayTabItem.MyItemInfo);
			}
			SetCaption(tv.SelectedNode as VETreeNode);
		}
		private void tc_StepPanelModeChange(object sender, StepRTBModeChangeEventArgs args)
		{
			this.lblEditView.Text = args.ViewMode == E_ViewMode.Edit ? "Edit" : "View";
			this.dlgFindReplace.ToggleReplaceTab(args.ViewMode);
		}
		private ItemInfo _CurrentItem = null;
		private StepRTB _LastStepRTB = null;
		private void tc_ItemSelectedChanged(object sender, ItemSelectedChangedEventArgs args)
		{
			if (_LastStepRTB != null && !_LastStepRTB.Disposing && !_LastStepRTB.Closed)
				_LastStepRTB.EditModeChanged -= new StepRTBEvent(_LastStepRTB_EditModeChanged);
			_LastStepRTB = args != null && args.MyEditItem != null ? args.MyEditItem.MyStepRTB : null;
			if (_LastStepRTB != null) _LastStepRTB.EditModeChanged += new StepRTBEvent(_LastStepRTB_EditModeChanged);
			lblEditView.Text = "    ";
			if (args == null)
			{
				_CurrentItem = null;
				ctrlAnnotationDetails.CurrentAnnotation = null;
				ctrlAnnotationDetails.Annotations = null;
				infotabRO.Visible = infotabTransition.Visible = infotabTags.Visible = infotabHistory.Visible = false;
				// When infotabTags is set to InVisible, the matching panel also needs to be set to invisible
				infotabControlPanelTags.Visible = false;
				displayTags.Visible = false;
				SelectedStepTabPanel = null;
				lblItemID.Text = "No Item Selected";
				lblItemID.ForeColor = Color.Yellow;
			}
			else
			{
				lblItemID.Text = string.Format("ItemID = {0}", args.MyItemInfo.ItemID);
				lblItemID.ForeColor = Color.DarkBlue;
				if (_CurrentItem != args.MyItemInfo)
				{
					if (_CurrentItem != null) _CurrentItem.Deleted -= new ItemInfoEvent(_CurrentItem_Deleted);
					_CurrentItem = args.MyItemInfo;
				}
				//vlnStackTrace.ShowStack("enter tc_ItemSelectedChanged {0}", _CurrentItem);
				if (args.MyEditItem == null)
				{
					infotabTransition.Visible = false;
					infotabRO.Visible = true;
					displayRO.MyRTB = null;
					infotabTags.Visible = false;
					displayBookMarks.MyEditItem = null;
					//vlnStackTrace.ShowStack("enter tc_ItemSelectedChanged {0}", _CurrentItem);
				}
				else
				{
					if (args.MyEditItem.MyItemInfo.IsSection || args.MyEditItem.MyItemInfo.IsProcedure)
					{
						infotabRO.Visible = infotabTransition.Visible = false;
						infotabTags.Visible = false;
						displayTags.Visible = false;
					}
					else
					{
						infotabTags.Visible = true;
						if (_LastStepRTB != null)
						{
							infotabRO.Visible = infotabTransition.Visible = true;
							displayRO.Enabled = _LastStepRTB.EditMode || _LastStepRTB.IsRoTable;
							displayTransition.Enabled = _LastStepRTB.EditMode;
						}
						else
							infotabRO.Visible = infotabTransition.Visible = false;
						
						// When infotabTags is set to Visible, the matching panel also needs to be set to visible
						// the other panels will appear as they are selected by the user.
						infotabControlPanelTags.Visible = true;
						displayTags.IsVisible = true;
					}
					infotabHistory.Visible = true;
					// When infotabTags is set to Visible, it is given focus.  The next line returns focus to the StepRTB
					args.MyEditItem.SetFocus();
					displayTransition.MyRTB = args.MyEditItem.MyStepRTB;
					
					displayRO.MyRTB = args.MyEditItem.MyStepRTB;
					displayTags.MyEditItem = args.MyEditItem;
					displayBookMarks.MyEditItem = args.MyEditItem;
					displayHistory.MyEditItem = args.MyEditItem;
					
					displayRO.ProgressBar = bottomProgBar;

					lblEditView.Text = args.MyEditItem.MyStepPanel.VwMode == E_ViewMode.Edit ? "Edit" : "View" ;
					_CurrentItem.Deleted += new ItemInfoEvent(_CurrentItem_Deleted);
					dlgFindReplace.MyEditItem = args.MyEditItem;
					SpellChecker.MyEditItem = args.MyEditItem;
				}
				if (args.MyEditItem != null)
				{
					SelectedStepTabPanel = args.MyEditItem.MyStepPanel.MyStepTabPanel;
					displayRO.ROTypeFilter = SelectedStepTabPanel.MyStepPanel.SelectedEditItem is Volian.Controls.Library.GridItem && (SelectedStepTabPanel.MyStepPanel.SelectedEditItem as Volian.Controls.Library.GridItem).MyFlexGrid.IsRoTable ?
						E_ROValueType.Table : (SelectedStepTabPanel.MyStepPanel.SelectedEditItem.MyItemInfo.IsFigure) ? E_ROValueType.Image : E_ROValueType.Text;
				}
				else
				{
					SelectedDVI = args.MyItemInfo.ActiveParent.ActiveParent as DocVersionInfo;
					displayRO.ROTypeFilter = E_ROValueType.All; // allow all RO types for Word attachments (but fix)
				}
			}
			ctrlAnnotationDetails.UpdateAnnotationGrid(_CurrentItem);
			AnnotationPanelView();
			btnPrint.Enabled = (_CurrentItem != null);
		}

		void _LastStepRTB_EditModeChanged(object sender, EventArgs args)
		{
			if (_LastStepRTB.EditMode)	// going into edit mode in a cell of the grid.
				displayRO.Enabled = displayTransition.Enabled = _LastStepRTB.EditMode;
			else  // going out of edit mode in a cell of the grid.
			{
				if (this.ActiveControl != tc || (!_LastStepRTB.Parent.Focused && (infotabRO.IsSelected || infotabTransition.IsSelected))) return;
				displayRO.Enabled = displayTransition.Enabled = _LastStepRTB.EditMode;
			}
		}

		void _CurrentItem_Deleted(object sender)
		{
			//displayBookMarks.DeleteItemBookMarkPanel(_CurrentItem);
		}
		#endregion
		#region Annotations
		/// <summary>
		/// Display or hide the Annotation Details panel
		/// </summary>
		private void AnnotationPanelView()
		{
			if (ctrlAnnotationDetails.Annotations != null && ctrlAnnotationDetails.Annotations.Count != 0)
			{
				if (Settings.Default.AutoPopUpAnnotations) //cbAnnotationPopup.Checked
					epAnnotations.Expanded = true;
				else
					epAnnotations.TitleStyle.BackColor1.Color = Color.Yellow;
			}
			else
			{
				if (!btnAnnoDetailsPushPin.Checked)
					epAnnotations.Expanded = false;
				epAnnotations.TitleStyle.BackColor1.Color = _CommentTitleBckColor;
				ctrlAnnotationDetails.AnnotationText = null;
			}
		}
		#endregion
		#region LinkSupport
		private void tc_LinkActiveChanged(object sender, StepPanelLinkEventArgs args)
		{
			// determine if any infotabs are visisble, and if it is the Transition,
			// change the curitem for the transition to the current item.
			if (infoPanel.Expanded == true && infoTabs.SelectedTab == infotabTransition)
			{
				displayTransition.CurTrans = null;
			}
		}
		private void tc_LinkModifyTran(object sender, StepPanelLinkEventArgs args)
		{
			infoPanel.Expanded = true;
			infoTabs.SelectedTab = infotabTransition;
			if (SelectedStepTabPanel == null) return;
			//displayTransition.RangeColor = global::VEPROMS.Properties.Settings.Default.TransitionRangeColor;
			displayTransition.MyRTB = SelectedStepTabPanel.MyStepPanel.SelectedEditItem.MyStepRTB;
			displayTransition.CurTrans = args.MyLinkText.MyTransitionInfo;
		}
		private void tc_LinkModifyRO(object sender, StepPanelLinkEventArgs args)
		{
			infoPanel.Expanded = true;
			infoTabs.SelectedTab = infotabRO;

			if (SelectedStepTabPanel == null) return;
			displayRO.MyROFST = SelectedROFst;
			displayRO.MyRTB = SelectedStepTabPanel.MyStepPanel.SelectedEditItem.MyStepRTB;
			displayRO.CurROLink = args.MyLinkText.MyRoUsageInfo;
			displayRO.ROTypeFilter = SelectedStepTabPanel.MyStepPanel.SelectedEditItem is Volian.Controls.Library.GridItem && (SelectedStepTabPanel.MyStepPanel.SelectedEditItem as Volian.Controls.Library.GridItem).MyFlexGrid.IsRoTable ?
				E_ROValueType.Table : (SelectedStepTabPanel.MyStepPanel.SelectedEditItem.MyItemInfo.IsFigure) ? E_ROValueType.Image: E_ROValueType.Text;
			displayRO.Mydvi = SelectedDVI;
			displayRO.ProgressBar = bottomProgBar;
			displayRO.TabControl = tc;
		}
		#endregion
		#region VButton
		private void office2007StartButton1_Click(object sender, EventArgs e)
		{
			// If the V-Button is clicked, check to see what tree node is s selected
			// to set up the New submenus. The New submenus are dependent on the type of
			// object selected, i.e. folder, docversion, etc.

			// reset in case previous selection changed items.
			btnNew.SubItems.Clear();
			btnNew.Enabled = false;

			VETreeNode vtn = tv.SelectedNode as VETreeNode;
			if (vtn == null) return;
			btnNew.Enabled = true;
			vtn.Expand();

			// Folders can have either folders & docversions, but
			// not a mix.
			FolderInfo fi = vtn.VEObject as FolderInfo;
			if (fi != null)
			{
				if (fi.FolderDocVersionCount > 0)
				{
					btnNew.Enabled = false;
					return;
				}
				// if at top, 'VEPROMS', folder and childfolders below this only
				// option is to create a new (sub)folder, i.e. no submenu items.
				if (fi.ChildFolderCount > 0 && fi.MyParent == null) return;
				//if (fi.ChildFolderCount == 0)			// submenu folders/docversion
				//{
				if (fi.MyParent != null)
				{
					ButtonItem fldbbtn = new ButtonItem("fldbtn", "Folder Before");
					ButtonItem fldabtn = new ButtonItem("fldabtn", "Folder After");
					btnNew.SubItems.Add(fldbbtn);
					btnNew.SubItems.Add(fldabtn);
					fldbbtn.Click += new EventHandler(fldbbtn_Click);
					fldabtn.Click += new EventHandler(fldabtn_Click);
				}
				ButtonItem fldbtn = new ButtonItem("fldbtn", "Folder");
				btnNew.SubItems.Add(fldbtn);
				fldbtn.Click += new EventHandler(fldbtn_Click);
				if (fi.ChildFolderCount == 0)
				{
					ButtonItem dvbtn = new ButtonItem("dvbtn", "Document Version");
					btnNew.SubItems.Add(dvbtn);
					dvbtn.Click += new EventHandler(dvbtn_Click);
				}
				return;
				//}
			}

			// DocVersions can only have procedures, so no sub-menu
			DocVersionInfo dvi = vtn.VEObject as DocVersionInfo;
			if (dvi != null) return;

			// Procedures can have a section added or a new procedure before
			// or after.
			ProcedureInfo pi = vtn.VEObject as ProcedureInfo;
			if (pi != null)
			{
				ButtonItem pbbtn = new ButtonItem("pfbtn", "Procedure Before");
				ButtonItem pabtn = new ButtonItem("pabtn", "Procedure After");
				ButtonItem sctbtn = new ButtonItem("sctbtn", "Section");
				btnNew.SubItems.Add(pbbtn);
				btnNew.SubItems.Add(pabtn);
				btnNew.SubItems.Add(sctbtn);
				pbbtn.Click += new EventHandler(pbbtn_Click);
				pabtn.Click += new EventHandler(pabtn_Click);
				sctbtn.Click += new EventHandler(sctbtn_Click);
				return;
			}

			// Sections can have sections before, after, new subsections & if is
			// a step section, can have steps
			SectionInfo si = vtn.VEObject as SectionInfo;
			if (si != null)
			{
				ButtonItem sbbtn = new ButtonItem("sbbtn", "Section Before");
				ButtonItem sabtn = new ButtonItem("sabtn", "Section After");
				ButtonItem subbtn = new ButtonItem("subbtn", "SubSection");
				btnNew.SubItems.Add(sbbtn);
				btnNew.SubItems.Add(sabtn);
				btnNew.SubItems.Add(subbtn);
				sbbtn.Click += new EventHandler(sbbtn_Click);
				sabtn.Click += new EventHandler(sabtn_Click);
				subbtn.Click += new EventHandler(subbtn_Click);
				if (si.IsStepSection)
				{
					ButtonItem stpbtn = new ButtonItem("stpbtn", "New Step");
					btnNew.SubItems.Add(stpbtn);
					stpbtn.Click += new EventHandler(stpbtn_Click);
				}
				return;
			}

			// Steps can have steps before or after only.
			StepInfo stpi = vtn.VEObject as StepInfo;
			if (stpi != null)
			{
				ButtonItem stpbbtn = new ButtonItem("stpbbtn", "New Step Before");
				ButtonItem stpabtn = new ButtonItem("stpabtn", "New Step After");
				btnNew.SubItems.Add(stpbbtn);
				btnNew.SubItems.Add(stpabtn);
				stpbbtn.Click += new EventHandler(stpbbtn_Click);
				stpabtn.Click += new EventHandler(stpabtn_Click);
				return;
			}
		}

		void fldabtn_Click(object sender, EventArgs e)
		{
			tv.tv_NodeNew(vlnTreeView.MenuSelections.FolderAfter);
		}

		void fldbbtn_Click(object sender, EventArgs e)
		{
			tv.tv_NodeNew(vlnTreeView.MenuSelections.FolderBefore);
		}

		void stpabtn_Click(object sender, EventArgs e)
		{
			tv.tv_NodeNew(vlnTreeView.MenuSelections.StepAfter);
		}

		void stpbbtn_Click(object sender, EventArgs e)
		{
			tv.tv_NodeNew(vlnTreeView.MenuSelections.StepBefore);
		}

		void subbtn_Click(object sender, EventArgs e)
		{
			tv.tv_NodeNew(vlnTreeView.MenuSelections.Section);
		}

		void sabtn_Click(object sender, EventArgs e)
		{
			tv.tv_NodeNew(vlnTreeView.MenuSelections.SectionAfter);
		}

		void sbbtn_Click(object sender, EventArgs e)
		{
			tv.tv_NodeNew(vlnTreeView.MenuSelections.SectionBefore);
		}

		void stpbtn_Click(object sender, EventArgs e)
		{
			tv.tv_NodeNew(vlnTreeView.MenuSelections.Step);
		}

		void sctbtn_Click(object sender, EventArgs e)
		{
			tv.tv_NodeNew(vlnTreeView.MenuSelections.Section);
		}

		void pabtn_Click(object sender, EventArgs e)
		{
			tv.tv_NodeNew(vlnTreeView.MenuSelections.ProcedureAfter);
		}

		void pbbtn_Click(object sender, EventArgs e)
		{
			tv.tv_NodeNew(vlnTreeView.MenuSelections.ProcedureBefore);
		}

		void dvbtn_Click(object sender, EventArgs e)
		{
			tv.tv_NodeNew(vlnTreeView.MenuSelections.DocVersion);
		}

		void fldbtn_Click(object sender, EventArgs e)
		{
			tv.tv_NodeNew(vlnTreeView.MenuSelections.Folder);
		}
		private void btnSave_Click(object sender, EventArgs e)
		{
		}
		#endregion
		#region PanelEvents
		private void infoPanel_Click(object sender, EventArgs e)
		{
			displayTags.MyEditItem = (SelectedStepTabPanel == null) ? null : SelectedStepTabPanel.MyStepPanel.SelectedEditItem;
		}
		//private void tv_SectionShouldClose(object sender, vlnTreeSectionInfoEventArgs args)
		//{
		//    if (!args.MySectionInfo.IsStepSection) tc.CloseWordItem(args.MySectionInfo);
		//}

		private void infotabResults_Click(object sender, EventArgs e)
		{
			toolsPanel.Expanded = true;
			InitiateSearch(true);
		}
		private void InitiateSearch(bool searchFocus)
		{
			if (toolsPanel.Expanded)
			{
				if (displaySearch1.Mydocversion == null)//!displaySearch1.OpenDocFromSearch)
				{
					if (SelectedDVI != null)
					{
						displaySearch1.Mydocversion = SelectedDVI;
						displaySearch1.advTreeStepTypesFillIn();
					}
					displaySearch1.advTreeProcSetsFillIn(searchFocus);
				}
			}
		}

		private void ribbonControl1_ExpandedChanged(object sender, EventArgs e)
		{
			Console.WriteLine("Size {0}", ribbonControl1.Expanded);
			// TODO: Need to send message to all StepTabPanels and tell them to minimize their ribbons.
			tc.RibbonExpanded = ribbonControl1.Expanded;
		}

		private void btnItemInfo_Click(object sender, EventArgs e)
		{
			if (tc.SelectedDisplayTabItem != null && tc.SelectedDisplayTabItem.SelectedItemInfo != null)
			{
				frmPropGrid pg = new frmPropGrid(tc.SelectedDisplayTabItem.SelectedItemInfo, tc.SelectedDisplayTabItem.SelectedItemInfo.Path);
				pg.Show();
			}
			else 
				MessageBox.Show("Select Item First", "Item not selected", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
		}

		private void epAnnotations_Resize(object sender, EventArgs e)
		{
			if (epAnnotations.Expanded && !_panelExpandedChanging)
			{
				// if the height of the panel is smaller than the titleheight+20
				//(due to the user dragging the splitter down), then un-expand the
				// panel and set the height to the titleheight+75
				if (epAnnotations.Size.Height < epAnnotations.TitleHeight + 20)
				{
					Size sz = new Size(epAnnotations.Size.Width, epAnnotations.TitleHeight + 75);
					epAnnotations.Size = sz;
					epAnnotations.Expanded = false;
				}
			}
		}

		private void resizeVerticalExpandedPanel(object sender, EventArgs e)
		{
			ExpandablePanel ep = (ExpandablePanel)sender;
			if (ep.Expanded && !_panelExpandedChanging)
			{
				// if the width of the panel is smaller than the titleheight+20
				//(due to the user dragging the splitter over), then un-expand the
				// panel and set the width to the titleheight+50
				if (ep.Size.Width < ep.TitleHeight + 10)
				{
					Size sz = new Size(ep.TitleHeight + 50, ep.Size.Height);
					ep.Size = sz;
					ep.Expanded = false;
				}
			}
		}

		private void expandPanelExpandedChanging(object sender, ExpandedChangeEventArgs e)
		{
			_panelExpandedChanging = true;
		}

		private void toolsPanel_ExpandedChanged(object sender, ExpandedChangeEventArgs e)
		{
			_panelExpandedChanging = false;
			expandableSplitter4.Enabled = toolsPanel.Expanded;
			if (toolsPanel.Expanded)
				InitiateSearch(true);
		}

		private void epAnnotations_ExpandedChanged(object sender, ExpandedChangeEventArgs e)
		{
			_panelExpandedChanging = false;
			expandableSplitter2.Enabled = epAnnotations.Expanded;
		}

		private void epProcedures_ExpandedChanged(object sender, ExpandedChangeEventArgs e)
		{
			_panelExpandedChanging = false;
			expandableSplitter1.Enabled = epProcedures.Expanded;
		}

		private void infoPanel_ExpandedChanged(object sender, ExpandedChangeEventArgs e)
		{
			_panelExpandedChanging = false;
			expandableSplitter3.Enabled = infoPanel.Expanded;
			// if our active tab is a Word attachment, call the Click even on the RO tab
			// to ensure that the RO FST is loaded.  This fixes a bug where if the first thing you
			// open is a Word attachment, the RO panel would not have the RO's listed.
			if (infoPanel.Expanded && _CurrentItem != null && _CurrentItem.HasWordContent)
				infotabRO_Click(sender, e);
		}
		#endregion

		private void btnShortCuts_Click(object sender, EventArgs e)
		{
			ShortcutLists scListdlg = new ShortcutLists();
			scListdlg.Show();
		}

		private void cmbFont_SelectedIndexChanged(object sender, EventArgs e)
		{
			StepRTB.MyFontFamily = cmbFont.SelectedValue as FontFamily;
		}

		private void btnPrint_Click(object sender, EventArgs e)
		{
			//VETreeNode vtn = tv.SelectedNode as VETreeNode;
			//DocVersionInfo dvi = vtn.VEObject as DocVersionInfo;
			//while (dvi == null)
			//{
			//    vtn = vtn.Parent as VETreeNode;
			//    dvi = vtn.VEObject as DocVersionInfo;
			//}
			//string pnum = DisplayText.StaticStripRtfCommands(this._CurrentItem.MyProcedure.ProcedureConfig.Number).Replace("\\u8209?", "-");
			DlgPrintProcedure prnDlg = new DlgPrintProcedure(this._CurrentItem.MyProcedure);//dvi.DocVersionConfig,pnum);
			prnDlg.Show();
		}

		private void lblResolution_Click(object sender, EventArgs e)
		{
			if (this.WindowState != FormWindowState.Normal)
			{
				this.WindowState = FormWindowState.Normal;
			}
			else if (this.Size.Width != 1280)
			{
				this.Size = new Size(1280, 800);
			}
			else
			{
				this.Size = new Size(1024, 768);
			}
		}

		private void frmVEPROMS_Resize(object sender, EventArgs e)
		{
			lblResolution.Text = string.Format("Resolution {0} x {1}", Size.Width, Size.Height);
		}
		private void office2007StartButton1_MouseDown(object sender, MouseEventArgs e)
		{
			// Refresh the MostRecentlyUsedList
			_MyMRIList.Refresh();
			SetupMRU();
		}

		private void btnEditItem_Click(object sender, EventArgs e)
		{
			frmPropGrid pg = new frmPropGrid(tc.SelectedDisplayTabItem.MyStepTabPanel.SelectedEditItem, "EditItem");
			pg.Show();
		}
		private void btnUpdateFormat_Click(object sender, EventArgs e)
		{
			string tmp = Properties.Settings.Default.FormatPath;
			DirectoryInfo di = null;
			if (tmp != null && tmp !="") di = new DirectoryInfo(Properties.Settings.Default.FormatPath);
			if (((tmp ?? "") == "") || (di != null && (!di.Exists || !File.Exists(di.FullName + @"\fmtall") || !File.Exists(di.FullName + @"\genmacall"))))
			{
				while (((tmp ?? "") == "") || (!di.Exists || !Directory.Exists(di.FullName + @"\fmtall") || !Directory.Exists(di.FullName + @"\genmacall")))
				{
					fbd.Description = "Select folder containing FmtAll and GenMacAll folders to update formats";
					DialogResult dr = fbd.ShowDialog();
					if (dr == DialogResult.Cancel)
					{
						bottomProgBar.Text = "Format Update Cancelled";
						return;
					}
					di = new DirectoryInfo(fbd.SelectedPath);
					tmp = di.FullName;
				}
				Properties.Settings.Default.FormatPath = fbd.SelectedPath;
				Properties.Settings.Default.Save();
			}
			string fmtPath = di.FullName + @"\fmtall";
			string genmacPath = di.FullName + @"\genmacall";
			Format.FormatLoaded += new FormatEvent(Format_FormatLoaded);
			Format.UpdateFormats(fmtPath, genmacPath);
			Format.FormatLoaded -= new FormatEvent(Format_FormatLoaded);
		}

		void Format_FormatLoaded(object sender, FormatEventArgs args)
		{
			bottomProgBar.Text = args.Status;
		}

		private void btnSendErrorLog_Click(object sender, EventArgs e)
		{

			frmSendErrorLog frm = new frmSendErrorLog(Properties.Settings.Default.OutlookEmail, Properties.Settings.Default["SMTPServer"].ToString(), Properties.Settings.Default["SMTPUser"].ToString(),ErrorLogFileName);
			if (frm.ShowDialog(this) == DialogResult.OK)
			{
				Properties.Settings.Default.OutlookEmail = frm.OutlookEmail;
				Properties.Settings.Default.SMTPServer = frm.SMTPServer;
				Properties.Settings.Default.SMTPUser = frm.SMTPUser;
				Properties.Settings.Default.Save();
				MessageBox.Show("PROMS Error Log successfully sent to Volian support");
			}
		}

	}
}
