using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using VEPROMS.CSLA.Library;
using VEPROMS.Properties;
using DevComponents.DotNetBar;
using DevComponents.DotNetBar.Controls;
using Volian.Controls.Library;
using DescriptiveEnum;
using System.IO;

namespace VEPROMS
{
	public partial class frmSectionProperties : DevComponents.DotNetBar.Office2007Form
	{
		private string _DefaultFormatName = null;
		private string _DefaultNumColumns = null;
		private string _DefaultPaginationStyle = null;
		private string _DefaultPrintSize = null;
		private bool _Initializing;
		private SectionConfig _SectionConfig;
    private Document _DocumentToDelete = null;
		private StepTabRibbon _MyStepTabRibbon;
		private bool _isStepSection = true;
		private bool _hasSectionCheckoffDefault = false;
		private bool _isDefaultStepSection = false;

		public frmSectionProperties(SectionConfig sectionConfig)
		{
			_SectionConfig = sectionConfig;
			InitializeComponent();
			btnGeneral.PerformClick(); // always start with General tab or button
			ItemInfo ii = ItemInfo.Get(_SectionConfig.MySection.ItemID);
			//if (sectionConfig.Number.Length > 0)
			//    this.Text = string.Format("{0}  {1} Properties", sectionConfig.Number, sectionConfig.Title);
			//else
			//    this.Text = string.Format("{0} Properties", sectionConfig.Title);
			if (sectionConfig.Number.Length > 0)
				this.Text = string.Format("{0}  {1} Properties", ii.DisplayNumber, ii.DisplayText);
			else
				this.Text = string.Format("{0} Properties", ii.DisplayText);
			ppSectTitleStpRTB.Font = ppSectTitleStpRTB.FormatFont = new System.Drawing.Font("Microsoft Sans Serif", 10F);
			ppSectTitleStpRTB.FieldToEdit = E_FieldToEdit.Text;
			ppSectTitleStpRTB.BorderStyle = BorderStyle.Fixed3D;
			ppSectTitleStpRTB.MyItemInfo = ii;
			ppSectTitleStpRTB.RefreshDisplay(true);
			ppSectNumberStpRTB.Font = this.ppSectNumberStpRTB.FormatFont = new System.Drawing.Font("Microsoft Sans Serif", 10F);
			ppSectNumberStpRTB.FieldToEdit = E_FieldToEdit.Number;
			ppSectNumberStpRTB.BorderStyle = BorderStyle.Fixed3D;
			ppSectNumberStpRTB.MyItemInfo = ii;
			ppSectNumberStpRTB.RefreshDisplay(true);
			_MyStepTabRibbon = new StepTabRibbon();
			//_MyStepTabRibbon.Dock = System.Windows.Forms.DockStyle.Top;
			//_MyStepTabRibbon.Location = new System.Drawing.Point(0, 0);
			_MyStepTabRibbon.Name = "displayTabRibbon1";
			_MyStepTabRibbon.Visible = false;

			// if creating a new section, enable the StepSect and WordSect radio buttons
			rbStepSect.Enabled = rbWordSect.Enabled =  !(ii.HasWordContent || ii.HasStepContent);

			// if this is an auto table of contents (mydocstyle == null if new section, so must check for that first)
			if (ii.IsAutoTOCSection)
			{
				rbWordSect.Checked = true;
				rbStepSect.Enabled = false;
				rbWordSect.Enabled = false;
				_isStepSection = false;
			}

			// if this has already been set to be a step section, i.e. HasStepContent, disable the libdoc tab
			// also disable if there is no word content yet - the user may want to change from step type to
			// word type, as long as there is no content yet.
			if (ii.HasStepContent || !ii.HasWordContent) tcpLibDoc.Enabled = false;
			if (ii.HasWordContent) _isStepSection = false;
		}

		private void btnSectPropOK_Click(object sender, EventArgs e)
		{
			sectionConfigBindingSource.EndEdit();
			
			// Save Default settings for User
			//
			// Save whether we should display the default values on this property page
			Settings.Default.ShowDefaultSectionProp = ppCbShwDefSettings.Checked;
			Settings.Default.Save();
			// save the type based on selection.
			_SectionConfig.MySection.MyContent.Type = ((DocStyle)ppCmbxStyleSectionType.SelectedItem).Index + 10000;

			// save any changes to checkoffs.  The bindings were added to the designer, but the 'save' was
			// hanging, so they're being done here.
			PlantFormat pf = _SectionConfig.MyFormat != null ? _SectionConfig.MyFormat.PlantFormat : _SectionConfig.MyDefaultFormat.PlantFormat;
			CheckOffList chkoffList = pf.FormatData.ProcData.CheckOffData.CheckOffList;
			CheckOffHeaderList chkoffHeaderList = pf.FormatData.ProcData.CheckOffData.CheckOffHeaderList;
			if (ppGpbxSignoffCheckoff.Enabled && (chkoffList != null && chkoffList.MaxIndex > 1)
				&& (ppCmbxCheckoffType.SelectedIndex != _SectionConfig.Section_CheckoffListSelection - (_hasSectionCheckoffDefault? 1:0)))
				_SectionConfig.Section_CheckoffListSelection = ppCmbxCheckoffType.SelectedIndex + (_hasSectionCheckoffDefault? 1:0);
			if (ppCmbxCheckoffHeading.Enabled && chkoffHeaderList != null && chkoffHeaderList.MaxIndex > 1)
				_SectionConfig.Section_CheckoffHeaderSelection = ppCmbxCheckoffHeading.SelectedIndex;

			if (ppCmbxSectPagination.SelectedValue == null)
				_SectionConfig.Section_Pagination = (SectionConfig.SectionPagination)Enum.Parse(typeof(SectionConfig.SectionPagination), _DefaultPaginationStyle);
			else
				_SectionConfig.Section_Pagination = (SectionConfig.SectionPagination)ppCmbxSectPagination.SelectedValue;
			_SectionConfig.MySection.MyContent.Config = _SectionConfig.ToString();
				_SectionConfig.MySection.MyContent.DTS = DateTime.Now;
				_SectionConfig.MySection.MyContent.UserID = Volian.Base.Library.VlnSettings.UserID;
				Section mySection = _SectionConfig.MySection.Save();
			SaveText(ppSectNumberStpRTB); // save the section number
			SaveText(ppSectTitleStpRTB); // save the section title
			FinishSectionSave(mySection); // this will also create an empty Word Doc if this is a word section
			// if there was a document to delete, do it.
			if (_DocumentToDelete != null)
			{
				Document.Delete(_DocumentToDelete.DocID);
				_DocumentToDelete = null;
			}
			mySection.Dispose();

			// if this section is now the 'DefaultStepSection', clear all others  (only 1 section can have
			// this property set - it is used when printing page numbers with 'WithSteps' numbering sequence.
			if (!_isDefaultStepSection && ppCbDefaultStepSection.Checked)
			{
				foreach (SectionInfo si in  _SectionConfig.MySection.MySectionInfo.MyProcedure.Sections)
				{
					SectionConfig sc = si.MyConfig as SectionConfig;
					if (si.ItemID != _SectionConfig.MySection.ItemID && sc!=null && sc.Section_OriginalSteps == "Y")
					{
						using (Section ssav = si.Get())
						{
							ssav.SectionConfig.Section_OriginalSteps = "N";
							ssav.Save();
							ItemInfo.Refresh(ssav);
						}
					}
				}
				// also need to set the procedure's config sectionstart to the selected section
				// if it is not set:
				using (Procedure p = Procedure.Get(_SectionConfig.MySection.MySectionInfo.MyProcedure.ItemID))
				{
					if (p.ProcedureConfig.SectionStart != _SectionConfig.MySection.MySectionInfo.ItemID.ToString())
					{
						p.ProcedureConfig.SectionStart = _SectionConfig.MySection.MySectionInfo.ItemID.ToString();
						p.Save();
						ItemInfo.Refresh(p);
					}
				}

			}
			// Saving of enhanced data:  Only need to save if the form_load determined that this may have enhanced & radio type
			// boxes were enabled:
			if (_isStepSection && checkEnhancedSettings && rbEnhLnkContents.Enabled)
			{
				// get string that should be used for "LnkEnh"
				string type = rbEnhLnkTitle.Checked ? "T" : rbEnhLnkNo.Checked ? "N" : "Y";
				if (_SectionConfig.Section_LnkEnh != type) 
				{
					// note that the enhanced section will get created and linked from vlntreeview (to keep the code 
					// consistent between the way procedures and sections are done).
					using (Section ssav = Section.Get(_SectionConfig.MySection.ItemID))
					{
						ssav.SectionConfig.Section_LnkEnh = type;
						ssav.Save();
						ItemInfo.Refresh(ssav);
					}
				}
			}
			this.DialogResult = DialogResult.OK;
			this.Close();
		}
		public void SaveText(StepRTB myStepRTB)
		{
			if (myStepRTB.ReadOnly) return;
			if (!myStepRTB.ActiveMode) return;
			if (!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();
			}
		}
		//private static void FinishSectionSave(Section section)
		private void FinishSectionSave(Section section)
		{
			ItemInfo sectinfo = ItemInfo.Get(section.ItemID);

			// need to find out if this is a word document type section & if it is, create a new word doc.
			bool isWordSect = true;
			int sectype = (int)sectinfo.MyContent.Type - 10000;
			PlantFormat pf = sectinfo.ActiveFormat.PlantFormat;
			foreach (DocStyle ds in pf.DocStyles.DocStyleListActive)
			{
				if (ds.Index == sectype)
				{
					isWordSect = !ds.IsStepSection;
					break;
				}
			}
			if (isWordSect && !sectinfo.HasWordContent && !sectinfo.IsAutoTOCSection &&
				(!sectinfo.IsPlacekeeperSection || (sectinfo.IsPlacekeeperSection && !ppCbPlaceKeeper.Checked)))
			{
				using (Content cont = Content.Get(sectinfo.MyContent.ContentID))
				{
					Byte[] tstbyte = System.Text.Encoding.Default.GetBytes("");
					Document doc = Document.MakeDocument(null, tstbyte, null, null,".DOCX"); // RTF Caused B2016-196 Changed to DOCX for default
					Entry entry = cont.MyEntry;
					entry.MyDocument = Document.Get(doc.DocID);
					cont.Save();
				}
			}
		}
		private void btnSectPropCancel_Click(object sender, EventArgs e)
		{
            _DocumentToDelete = null;
			sectionConfigBindingSource.CancelEdit();
			DialogResult = DialogResult.Cancel;
			this.Close();
		}

		/// <summary>
		/// Use the ParentLookup to grab the default values
		///  - set the watermark property (where applicable) of the control with that value
		///  - set the default setting labels with that value
		/// ** the default setting labels appear when the Show Default Values checkbox is checked by the user.
		/// </summary>
		private void FindDefaultValues()
		{
			_SectionConfig.ParentLookup = true;
			// Get the default format name
			_DefaultFormatName = _SectionConfig.DefaultFormatSelection;
			SetupDefault(_DefaultFormatName, ppLblFormatDefault, ppCmbxFormat);
			//if (_DefaultFormatName != null && !(_DefaultFormatName.Equals("")))
			//{
			//    string defName = string.Format("{0}", _DefaultFormatName);
			//    ppLblFormatDefault.Text = defName;
			//    ppCmbxFormat.WatermarkText = defName;
			//}
			SectionConfig.SectionColumnMode sc = _SectionConfig.Section_ColumnMode;
			_DefaultNumColumns = sc.ToString();
			SetupDefault(EnumDescConverter.GetEnumDescription(sc), ppLblDefaultNumColumns, ppCmbxNumColumns);
			SectionConfig.SectionPagination sp = _SectionConfig.Section_Pagination;
			//Console.WriteLine("{0}, {1}, default pagination", _SectionConfig.MySection.DisplayNumber, sp);
			_DefaultPaginationStyle = sp.ToString();
			SetupDefault(EnumDescConverter.GetEnumDescription(sp), ppLblDefPaginationStyle, ppCmbxSectPagination);
			//_DefaultPrintSize = _SectionConfig.Section_AttachmentPrintSize.ToString();
			//SetupDefault(EnumDescConverter.GetEnumDescription(_SectionConfig.Section_AttachmentPrintSize), ppLblDefaultPrintSize, ppCmbxAccPgPrintSize);

		_SectionConfig.ParentLookup = false;
		}

		/// <summary>
		/// Set the watermark and default label
		/// </summary>
		/// <param name="defaultText">The default text</param>
		/// <param name="lbl">Label that displays the current default when view defaults is set</param>
		/// <param name="cmboEx">Combo box with a watermark property</param>
		private static void SetupDefault(string defaultText, Label lbl, ComboBoxEx cmbo)
		{
			if (defaultText != null && !(defaultText.Equals("")))
			{
				string deftext = string.Format("{0}", defaultText);
				lbl.Text = deftext;
				cmbo.WatermarkText = deftext;
			}
		}
		private bool checkEnhancedSettings = false;
		private void frmSectionProperties_Load(object sender, EventArgs e)
		{
			_Initializing = true;
			sectionConfigBindingSource.DataSource = _SectionConfig;

			ppCmbxFormat.DataSource = null;
			ppCmbxFormat.DisplayMember = "FullName";
			ppCmbxFormat.ValueMember = "FullName";
			ppCmbxFormat.DataSource = FormatInfoList.SortedFormatInfoList;
			if (_SectionConfig.FormatSelection != null)
				ppCmbxFormat.SelectedValue = _SectionConfig.FormatSelection;
			else
				ppCmbxFormat.SelectedIndex = -1;
			// Get the saved settings for this user
			//
			// Get setting telling us whether to display the default values on this property page
			ppCbShwDefSettings.Checked = (Settings.Default["ShowDefaultSectionProp"] != null) ? Settings.Default.ShowDefaultSectionProp : false;

			// Get the User's property page style "PropPageStyle" (this is a system wide user setting)
			// 1 - Button Dialog (default)
			// 2 - Tab Dialog
			if ((int)Settings.Default["PropPageStyle"] == (int)PropPgStyle.Tab)
			{
				tcSectionProp.TabsVisible = true;
				panSectBtns.Visible = false;
				this.Width -= panSectBtns.Width;
			}

			// Get the default values for the property page information
			FindDefaultValues();
			ppCmbxSectPagination.DataSource = EnumDetail<SectionConfig.SectionPagination>.Details();
			ppCmbxSectPagination.DisplayMember = "Description";
			ppCmbxSectPagination.SelectedValueChanged -= new EventHandler(ppCmbxSectPagination_SelectedValueChanged);
			ppCmbxSectPagination.ValueMember = "EValue";
			ppCmbxSectPagination.SelectedIndex = -1;
			SectionConfig.SectionPagination sp = _SectionConfig.Section_Pagination;
			if (!(sp.ToString().Equals(_DefaultPaginationStyle)) && _isStepSection)
			{
				ppBtnDefaultPaginationStyle.Visible = true;
				ppCmbxSectPagination.SelectedValue = sp;
			}
			else
				ppBtnDefaultPaginationStyle.Visible = false;

			//Console.WriteLine("{0}, {1}, current pagination", _SectionConfig.MySection.DisplayNumber, ppCmbxSectPagination.SelectedValue);
			ppCmbxSectPagination.SelectedValueChanged += new EventHandler(ppCmbxSectPagination_SelectedValueChanged);

			ppCmbxNumColumns.DataSource = EnumDetail<SectionConfig.SectionColumnMode>.Details();
			ppCmbxNumColumns.DisplayMember = "Description";
			ppCmbxNumColumns.SelectedValueChanged -= new EventHandler(ppCmbxNumColumns_SelectedValueChanged);
			ppCmbxNumColumns.ValueMember = "EValue";
			ppCmbxNumColumns.SelectedIndex = -1;
			SectionConfig.SectionColumnMode sc = _SectionConfig.Section_ColumnMode;
			if (!(sc.ToString().Equals(_DefaultNumColumns)) && _isStepSection)
			{
				ppBtnDefaultNumColumns.Visible = true;
				ppCmbxNumColumns.SelectedValue = sc;
			}
			else
				ppBtnDefaultNumColumns.Visible = false;
			ppCmbxNumColumns.SelectedValueChanged += new EventHandler(ppCmbxNumColumns_SelectedValueChanged);

			//ppCmbxAccPgPrintSize.DataSource = EnumDetail<SectionConfig.AttPrintSize>.Details();
			//ppCmbxAccPgPrintSize.DisplayMember = "Description";
			//ppCmbxAccPgPrintSize.ValueMember = "Evalue";
			//ppCmbxAccPgPrintSize.SelectedIndex = -1;

			if (!_isStepSection)
				ppCmbxLibDocFill();

			// check type of section from document styles to determine if the stepsection checkbox should
			// be checked.  
			//int secindx = (int)_SectionConfig.SectionType;
			//// find the index for the document style to determine whether this is a step or word section.
			PlantFormat pf = _SectionConfig.MyFormat != null ? _SectionConfig.MyFormat.PlantFormat : _SectionConfig.MyDefaultFormat.PlantFormat;
			//for (int i = 0; i < pf.DocStyles.DocStyleList.Count; i++)
			//{
			//    if (pf.DocStyles.DocStyleList[i].Index == secindx)
			//        rbStepSect.Checked = pf.DocStyles.DocStyleList[i].IsStepSection; _SectionConfig.MySection.
			//}

			// set the StepSect radio button based on _isStepSection to ensure the proper section types are available
			rbStepSect.Checked = _isStepSection;
			// set up some of the format tab:
			SetupPpCmbxSectionType();
			ShowAvailableOptionsForSectionType();

			// set the section level configs:
			ppCbEditableData.Checked = (_SectionConfig.SubSection_Edit == "Y");
			ppCbAutoIndent.Checked = (pf.FormatData.SectData.UseMetaSections && _SectionConfig.SubSection_AutoIndent == "Y");

			// if this section has subsections:
			// show the editable data check box. If showing 'editable data', the procedures steps are 
			//    shown in editor (tree view & editor) & printed before any subsections. If not showing 
			//    'editable data', the steps are not shown in editor or print.
			// show the automatic indent checkbox.  
			ppCbEditableData.Enabled = _SectionConfig.MySection.MySectionInfo.Sections != null && _SectionConfig.MySection.MySectionInfo.Sections.Count > 0;
			ppCbEditableData.Visible = _isStepSection; // only display if we are on a step editor section
			//ppCbAutoIndent.Enabled = _SectionConfig.MySection.MySectionInfo.Sections != null && _SectionConfig.MySection.MySectionInfo.Sections.Count > 0;
			ppCbAutoIndent.Enabled = pf.FormatData.SectData.UseMetaSections;
			ppCbAutoIndent.Visible = _isStepSection; // only display if we are on a step editor section

			// Check for the print section num/title config item to determine whether that checkbox should
			// be checked.
			ppCbPrnSecNumTitle.Enabled = _isStepSection;//true; // pf.FormatData.SectData.UseMetaSections;
			//ppCbPrnSecNumTitle.Checked = ppCbPrnSecNumTitle.Enabled && _SectionConfig.Section_PrintHdr != "N";
			ppCbPrnSecNumTitle.Checked = (_isStepSection && _SectionConfig.Section_PrintHdr != "N");
			ppCbPrnSecNumTitle.Visible = _isStepSection; // only display if we are on a step editor section

			// check if format has automated table of contents, if so, check if config flag is set that this
			// section should be included.
			ppCbIncTOC.Enabled = false;
			gpTOC.Visible = false;
			if ((pf.FormatData.PurchaseOptions & E_PurchaseOptions.AutoTableOfContents) == E_PurchaseOptions.AutoTableOfContents && _SectionConfig.MySection.MyContent.Text.ToUpper() != "TABLE OF CONTENTS")
			{
				ppCbIncTOC.Enabled = true;
				ppCbIncTOC.Checked = _SectionConfig.Section_TOC == "Y";
				if (_SectionConfig.MySection.MySectionInfo.MyDocStyle.IncludeInTOC)
				{
					ppCbIncTOC.Text = "Exclude from Table of Contents";
					gpTOC.Visible = !ppCbIncTOC.Checked; // show grouping box if including on auto TOC
				}
				else
				{
					ppCbIncTOC.Text = "Include in Table of Contents";
					gpTOC.Visible = ppCbIncTOC.Checked; // show grouping box if including on auto TOC
				}
			}
			if (!_SectionConfig.MySection.MySectionInfo.IsStepSection)
				cbKeepWordDocMargins.Checked = _SectionConfig.Section_WordMargin == "Y";
			if ((pf.FormatData.PurchaseOptions & E_PurchaseOptions.AutoPlacekeeper) == E_PurchaseOptions.AutoPlacekeeper)
			{
				ppCbPlaceKeeper.Text = "Include In Placekeeper";
				ppCbPlaceKeeper.Enabled = _isStepSection;
				if (!_isStepSection && (_SectionConfig.MySection.MySectionInfo.MyDocStyle.StructureStyle.Style & E_DocStructStyle.Placekeeper) == E_DocStructStyle.Placekeeper)
				{
					//ppCbPlaceKeeper.Text = "Auto Generate Placekeeper";
					//ppCbPlaceKeeper.Enabled = true;
					ppCbPlaceKeeper.Enabled = false;
				}
				if (ppCbPlaceKeeper.Enabled) ppCbPlaceKeeper.Checked = _SectionConfig.Section_Placekeeper == "Y";
			}
			if (pf.FormatData.SectData.PrintPhoneList)
			{
				ppCbPhoneList.Enabled = true;
				ppCbPhoneList.Checked = _SectionConfig.Section_PhoneList == "Y";
			}

			// Handle Default Step Section.  First, this checkbox is only visible if it is
			// a step section & it is the highest level (top, right below procedures).
			ppCbDefaultStepSection.Visible = false;
			if (_isStepSection && _SectionConfig.MySection.MySectionInfo.MyActiveParent.IsProcedure) // B2016-280 - use MyActiveParent because MyParent was sometimes null
			{
				ppCbDefaultStepSection.Visible = true;
				ppCbDefaultStepSection.Checked = _SectionConfig.Section_OriginalSteps == "Y";
				// Use checkbox text to clarify what is case for this section, i.e. is it already
				// the default or can it be set.  Note that this is used when printing of page numbers
				// that use the 'WithSteps' numbering sequence.
				if (_SectionConfig.Section_OriginalSteps == "Y")
				{
					ppCbDefaultStepSection.Text = "This is Default Step Section";
					_isDefaultStepSection = true;
				}
				else
					ppCbDefaultStepSection.Text = "Make this the Default Step Section";
			}

			// if the parent has enhanced documents (and is not an enhanced document, i.e. the test
			// ed.Type != 0 proves that) put up the group panel on the automation tab that allows for setting of 
			// link types (none, title only, content). The radio buttons are only enabled if the section is 
			// NEW (determined by the 'LnkEnh' being empty).
			if (_isStepSection)
			{
				ProcedureInfo pi = ProcedureInfo.Get(_SectionConfig.MySection.MySectionInfo.MyProcedure.ItemID);
				ProcedureConfig picfg = pi.MyConfig as ProcedureConfig;
				bool hasEnh = false;
				if (picfg.MyEnhancedDocuments != null && picfg.MyEnhancedDocuments.Count > 0)
				{
					foreach (EnhancedDocument ed in picfg.MyEnhancedDocuments)
					{
						if (ed.Type != 0)
						{
							checkEnhancedSettings = true;
							hasEnh = true;
							break;
						}
					}
					if (hasEnh)
					{
						grpLnkEnh.Visible = true;
						if (_SectionConfig.Section_LnkEnh == null || _SectionConfig.Section_LnkEnh == "" || _SectionConfig.Section_LnkEnh == "Y")
							rbEnhLnkContents.Checked = true;
						else if (_SectionConfig.Section_LnkEnh == "N")
							rbEnhLnkNo.Checked = true;
						else  // "T" for title:
							rbEnhLnkTitle.Checked = true;
						rbEnhLnkContents.Enabled = rbEnhLnkNo.Enabled = rbEnhLnkTitle.Enabled = (_SectionConfig.Section_LnkEnh == null || _SectionConfig.Section_LnkEnh == "");
					}
					else
						grpLnkEnh.Visible = false;
				}
				else
					grpLnkEnh.Visible = false;
			}
			else
			{
				// for word docs, no enhanced controls should be visible:
				grpLnkEnh.Visible = false;
			}
			_Initializing = false;
			//_InitialIndex = ppCmbxFormat.SelectedIndex;
		}
		int _InitialIndex = -2;

        private void ppCmbxLibDocFill()
        {
			bool sav_Initializing = _Initializing;
            _Initializing = true;
			bool isLib = false;
			// Only show the Convert To DocX button for non-library MS Word Sections
			if (_SectionConfig.MySection.MyContent.MyEntry!=null && _SectionConfig.MySection.MyContent.MyEntry.MyDocument!=null && (_SectionConfig.MySection.MyContent.MyEntry.MyDocument.LibTitle != null) && (_SectionConfig.MySection.MyContent.MyEntry.MyDocument.LibTitle != "")) isLib = true;
			if (isLib)
			{
				ppBtnConvertToDocX.Visible = false; // Don't allow save as DOCX for libraries documents
				ppBtnCvrtToLibDoc.Text = "Convert this Section To A Non-Library Document";
				lblLibraryDocument.Text = "Library Document";
				superTooltip1.SetSuperTooltip(this.ppBtnCvrtToLibDoc, new DevComponents.DotNetBar.SuperTooltipInfo("Convert To Non-Library Document", "", "This button will convert the current section from a library document to a non-library document",
								null, null, DevComponents.DotNetBar.eTooltipColor.Gray, true, false, new System.Drawing.Size(250, 76)));
			}
			else
			{
				// Only show the Convert To DocX button for RTF MS Word Sections
				if (_SectionConfig.MySection.MyContent.MyEntry.MyDocument != null && _SectionConfig.MySection.MyContent.MyEntry.MyDocument.FileExtension == ".RTF")
				{
					ItemInfo ii = ItemInfo.Get(_SectionConfig.MySection.ItemID);
					if (!ii.IsAutoTOCSection) // Only show the Convert To DocX button for non-Auto Table Of Contents Section
						this.ppBtnConvertToDocX.Visible = true; // Only allow save as DocX for normal word sections when the existing text is RTF.
				}
				else
					this.ppBtnConvertToDocX.Visible = false;
				if (_SectionConfig.MySection.MyContent.MyEntry.MyDocument == null)
					ppBtnCvrtToLibDoc.Visible = false;
				else
				{
					ppBtnCvrtToLibDoc.Text = "Convert this to a Library Document";
					lblLibraryDocument.Text = "Select Library Document";
					superTooltip1.SetSuperTooltip(this.ppBtnCvrtToLibDoc, new DevComponents.DotNetBar.SuperTooltipInfo("Convert To Library Document button", "", "This button will convert the current section to a library document, allowing it t" +
						"o be shared with other procedures.", null, null, DevComponents.DotNetBar.eTooltipColor.Gray, true, false, new System.Drawing.Size(250, 76)));
				}
			}

            DocumentInfoList LibDocList = DocumentInfoList.GetLibraries(true);
			int selindx = -1;
			ppCmbxLibDoc.Items.Clear();
            for (int i = 0; i < LibDocList.Count; i++)
            {
                ppCmbxLibDoc.Items.Add(LibDocList[i].DocumentTitle);
                // see if this lib doc should be the selected index?
				if (isLib && (LibDocList[i].DocID == _SectionConfig.MySection.MyContent.MyEntry.MyDocument.DocID)) selindx  = i;
            }
			if (selindx > -1) ppCmbxLibDoc.SelectedIndex = selindx;
			_Initializing = sav_Initializing;
        }

		#region General tab

		/// <summary>
		/// This is the General button used on the button interface design
		/// </summary>
		/// <param name="sender">object</param>
		/// <param name="e">EventArgs</param>
		private void btnGeneral_Click(object sender, EventArgs e)
		{
			ProcessButtonClick(tiGeneral, btnGeneral);
		}

		#endregion

		#region Format tab
		/// <summary>
		/// This is the Format button used on the button interface design
		/// </summary>
		/// <param name="sender">object</param>
		/// <param name="e">EventArgs</param>
		private void btnFormat_Click(object sender, EventArgs e)
		{
			ProcessButtonClick(tiFormat, btnFormat);
			if (_InitialIndex < -1) _InitialIndex = ppCmbxFormat.SelectedIndex; // save the current format selection (happens here when current section is set to the default format)
		}

		private void SetupPpCmbxSectionType()
		{
			bool myInit = _Initializing;
			// pf will be the current selected format.  If changing formats, then this will differ from the previously
			// selected.  If the format is being reset to default, selectedindex=-1. If this is a change, we'll need
			// to check that there are enough docstyles to map the selected type of section.
			PlantFormat pf = _SectionConfig.MyFormat != null ? _SectionConfig.MyFormat.PlantFormat : _SectionConfig.MyDefaultFormat.PlantFormat;
			if (!_Initializing && ppCmbxFormat.SelectedIndex >= 0)
				pf = FormatInfoList.SortedFormatInfoList[ppCmbxFormat.SelectedIndex].PlantFormat;
			else if (!_Initializing)    // if the format was changed, it may have been set to default.
				pf = _SectionConfig.MyDefaultFormat.PlantFormat;
			_Initializing = true;
			ppCmbxStyleSectionType.DisplayMember = "Name";
			ppCmbxStyleSectionType.ValueMember = "Index";

			// if this has been defined as a step section, only list step section document styles, if
			// a word section, only list word section styles.
			// Also, if changing the format, check to be sure that the section that is selected will map
			// to something valid in the new format, i.e. a section type of word or step sections exist,
			// index-wise in the new format.
			PlantFormat opf = null;
			int oldSelIndx = -1;
			if (!myInit)
			{
				DocStyleList oldDocStyles = null;
				opf = _SectionConfig.MyFormat != null ? _SectionConfig.MyFormat.PlantFormat : _SectionConfig.MyDefaultFormat.PlantFormat;
				if (pf != opf)
				{
					oldDocStyles = new DocStyleList(null);
					foreach (DocStyle ds in opf.DocStyles.DocStyleListActive)
					{
						if (_isStepSection && ds.IsStepSection)
							oldDocStyles.Add(ds);		// find only step section types
						else if (!_isStepSection && !ds.IsStepSection)
							oldDocStyles.Add(ds);	// find only accessory (MS Word) section types
						if (_SectionConfig.SectionType == ds.Index) oldSelIndx = oldDocStyles.Count - 1;
					}
				}
				if (oldSelIndx < 0) oldSelIndx = 0;
			}
			
			DocStyleList newDocStyles = new DocStyleList(null);
			int selindx = -1;
			foreach (DocStyle nds in pf.DocStyles.DocStyleListActive)
			{
				if (_isStepSection && nds.IsStepSection)
					newDocStyles.Add(nds); // add only step section types
				else if (!_isStepSection && !nds.IsStepSection)
					newDocStyles.Add(nds); // add only accessory (MS Word) section types
				if (_SectionConfig.SectionType == nds.Index) selindx = newDocStyles.Count - 1;
			}
			if (selindx < 0) selindx = 0;
			// if changing format, check for valid type (see comment above)
			if (!myInit && pf != opf)
			{
				if (newDocStyles.Count == 0)
				{
					string msg1 = string.Format("A Page Style for the type of section, {0}, is not available in the new format.  You cannot do this operation.",  _isStepSection? "Step Section": "Word Document");
					MessageBox.Show(msg1, "Cannot change to this format");
					return;
				}
				if (oldSelIndx > newDocStyles.Count)
				{
					string msg = string.Format("Since the format has been changed, the section type was also changed to '{0}'.  Verify that it is appropriate and if not, select a new section type.", newDocStyles.GetDocStyleItem(0).Name);
					MessageBox.Show(msg, "Verify section type");
					selindx = 0;
				}
			}
			ppCmbxStyleSectionType.DataSource = newDocStyles;
			ppCmbxStyleSectionType.SelectedIndex = selindx;
			ppCmbxStyleSectionType.Refresh();
			ppBtnConvertToDocX.Visible = false;// Set the Convert To DocX button to invisible by default

			if (!_isStepSection)
				ppCmbxLibDocFill(); // set the Convert To DocX button to Visible if appropriate
			_Initializing = myInit;
			if (_isStepSection)
				SetupCheckoffsDropdowns();
		}
		private List<CheckOff> SectionPropertyCheckOffList = null;
		private void SetupCheckoffsDropdowns()
		{
			if (!_isStepSection) return; // not needed for accessory pages (word attachments)
			bool myInit = _Initializing;
			_Initializing = true;
			PlantFormat pf = _SectionConfig.MyFormat!=null?_SectionConfig.MyFormat.PlantFormat:_SectionConfig.MyDefaultFormat.PlantFormat;
			CheckOffList chkoffList = pf.FormatData.ProcData.CheckOffData.CheckOffList;
			CheckOffHeaderList chkoffHeaderList = pf.FormatData.ProcData.CheckOffData.CheckOffHeaderList;
			if (chkoffList != null && chkoffList.MaxIndex > 0 &&
				(pf.FormatData.ProcData.CheckOffData.Menu == "Signoff" || chkoffList[0].MenuItem.ToUpper().Equals("{SECTION DEFAULT}")))
			{
				if (SectionPropertyCheckOffList!=null)SectionPropertyCheckOffList.Clear();
				SectionPropertyCheckOffList = new List<CheckOff>();
				// Don't put up the first item in the chkoffList, it is '{Section Default}'.
				_hasSectionCheckoffDefault = false;
				//for (int i = 1; i < chkoffList.Count; i++)
				for (int i = 0; i < chkoffList.MaxIndex; i++)
				{
					if (!chkoffList[i].MenuItem.ToUpper().Equals("{SECTION DEFAULT}"))
						SectionPropertyCheckOffList.Add(chkoffList[i]);
					else
						_hasSectionCheckoffDefault = true;
				}
				ppGpbxSignoffCheckoff.Enabled = true;
				ppCmbxCheckoffType.DataSource = SectionPropertyCheckOffList;
				ppCmbxCheckoffType.SelectedIndex = _SectionConfig.Section_CheckoffListSelection - (_hasSectionCheckoffDefault ? 1 : 0);
			}
			else
			{
				ppGpbxSignoffCheckoff.Enabled = false;
			}
			if (chkoffHeaderList != null && chkoffHeaderList.MaxIndex > 1)
			{
				lblCheckoffHeading.Enabled = true;
				ppCmbxCheckoffHeading.Enabled = true;
				ppCmbxCheckoffHeading.DataSource = chkoffHeaderList;
				ppCmbxCheckoffHeading.SelectedIndex = _SectionConfig.Section_CheckoffHeaderSelection;
			}
			else
			{
				lblCheckoffHeading.Enabled = false;
				ppCmbxCheckoffHeading.Enabled = false;
			}
			_Initializing = myInit;
		}

		private void ppBtnDefaultFmt_Click(object sender, EventArgs e)
		{
			bool foundMatch = false;
			bool isWordSection = rbWordSect.Checked;
			FormatInfo dfi = _SectionConfig.MyDefaultFormat;
			// check to see if the default format has a similar document style
			// if it does not, then do not allow the selection of the default format
			foreach (DocStyle ds in dfi.PlantFormat.DocStyles.DocStyleList)
			{
				if (ds.IsStepSection != isWordSection) foundMatch = true;
			}
			if (foundMatch)
			{
				_Initializing = true;
				ppCmbxFormat.SelectedIndex = -1; //reset to the default Format setting
				_Initializing = false;
				SetupPpCmbxSectionType();
			}
			else
			{
				string suffix = "format ";
				if (_DefaultFormatName.ToUpper().Contains("FORMAT")) suffix = "";
				MessageBox.Show(string.Format("{0}\n\n{1}does not support {2} section type", _DefaultFormatName, suffix, isWordSection ? "MS Word" : "Step"), "Incompatible Format", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
			}
		}

		private void ppCmbxFormat_SelectedIndexChanged(object sender, EventArgs e)
		{
			if (_Initializing)
			{
				// determine if the default button and the default description text should visable
				ppBtnDefaultFmt.Visible = !(ppCmbxFormat.SelectedValue == null || ppCmbxFormat.SelectedIndex == -1);
				ppLblFormatDefault.Visible = ppCbShwDefSettings.Checked && ppBtnDefaultFmt.Visible;
				return;
			}
			if (_InitialIndex < -1) _InitialIndex = ppCmbxFormat.SelectedIndex; // save the current format selection (happens here when current section format is not the default section)
			if (ppCmbxFormat.SelectedIndex > -1)  // B2017-016 selectedindex of -1 means the default format was selected
			{
				PlantFormat pf = FormatInfoList.SortedFormatInfoList[ppCmbxFormat.SelectedIndex].PlantFormat;
				// If the selected format does not have a docstyle compatable with the section
				// then reset the format selection back to what it was
				if (!ValidPlantFormat(pf))
				{
					_Initializing = true;
					ppCmbxFormat.SelectedIndex = _InitialIndex; // reset the format selection to what it was
					ppBtnCancel.Focus(); // this will force the property page to refresh
					_Initializing = false;
					return;
				}
			}
			if ((ppCmbxFormat.SelectedIndex != -1) && _DefaultFormatName != null && _DefaultFormatName.Equals(ppCmbxFormat.SelectedValue))
			{
				ppBtnDefaultFmt.Focus();
				ppBtnDefaultFmt.PerformClick();
			}
			// determine if the default button and the default description text should visable
			ppBtnDefaultFmt.Visible = !(ppCmbxFormat.SelectedValue == null || ppCmbxFormat.SelectedIndex == -1);
			ppLblFormatDefault.Visible = ppCbShwDefSettings.Checked && ppBtnDefaultFmt.Visible;
			//if (!didDefault) SetupPpCmbxSectionType();
			SetupPpCmbxSectionType();
		}

		//  This function is used when the user selects different format for a give section.
		//	It will verify that the newly selected format contains a document style (docstyle)
		//	compatable with the that section. (i.e. if the section is a Word section, the selected format has Word section docstyle)
				private bool ValidPlantFormat(PlantFormat pf)
				{
					bool foundMatch = false;
					bool isWordSection = rbWordSect.Checked;
					foreach (DocStyle ds in pf.DocStyles.DocStyleList)
					{
						if (ds.IsStepSection != isWordSection) foundMatch = true;
					}
					if (foundMatch)
						return true; // valid format
					string suffix = "format ";
					if (ppCmbxFormat.SelectedValue.ToString().ToUpper().Contains("FORMAT")) suffix = "";
					MessageBox.Show(string.Format("{0}\n\n{1}does not support {2} section type", ppCmbxFormat.SelectedValue, suffix, isWordSection ? "MS Word" : "Step"), "Incompatible Format", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
					return false;
				}

        private void ppCmbxStyleSectionType_SelectedValueChanged(object sender, EventArgs e)
        {
            if (_Initializing) return;
            if (ppCmbxStyleSectionType.SelectedValue != null)
                _SectionConfig.SectionType = (int)(ppCmbxStyleSectionType.SelectedValue);
        }

		#endregion

		#region Library Document tab

		/// <summary>
		/// This is the Library Document button used on the button interface design
		/// </summary>
		/// <param name="sender">object</param>
		/// <param name="e">EventArgs</param>
		private void btnLibDocs_Click(object sender, EventArgs e)
		{
			ProcessButtonClick(tiLibDoc, btnLibDocs);
		}
		private void ppBtnCvrtToLibDoc_Click(object sender, EventArgs e)
		{
			// Double Check that this is not a step section, if so just return.
			if (_isStepSection) return;
			// If current section is library document, user selected to convert to non-library document.  If
			// this is the case, data from lib doc must be copied to new document and the section must point
			// to id. 
			if (ppBtnCvrtToLibDoc.Text.IndexOf("Non") > 0)        // convert to a 'non' library.
			{
				ItemInfo ii = ItemInfo.Get(_SectionConfig.MySection.ItemID);
				DocumentInfo doclibinfo = ii.MyContent.MyEntry.MyDocument;

				// if just one usage (this one), then just convert this to a non-library document.  If there are more
				// than one usage, make a copy so that the rest of the usages still point to the library document.
				if (doclibinfo.DocumentEntryCount == 1)
					_SectionConfig.MySection.MyContent.MyEntry.MyDocument.LibTitle = null;
				else
				{
					// make new document with 'no' libtitle - use libtitle for the doc title.  Then link this
					// to the item...
					Document doc = Document.MakeDocument(null, doclibinfo.DocContent, doclibinfo.DocAscii, doclibinfo.Config,doclibinfo.FileExtension);
					_SectionConfig.MySection.MyContent.MyEntry.MyDocument = doc;
				}
				ppCmbxLibDoc.Items.Clear();
				ppCmbxLibDoc.WatermarkEnabled = true;
				ppBtnCvrtToLibDoc.Text = "Convert this to a Library Document";
				superTooltip1.SetSuperTooltip(this.ppBtnCvrtToLibDoc, new DevComponents.DotNetBar.SuperTooltipInfo("Convert To Library Document button", "", "This button will convert the current section to a library document, allowing it t" +
						"o be shared with other procedures.", null, null, DevComponents.DotNetBar.eTooltipColor.Gray, true, false, new System.Drawing.Size(250, 76)));
				return;
			}
			// If current section is not a library document, it is either a new section or the user selected the 
			// button to convert it to a library document.  Check for this, if new, just attach to document.  
			else if (_SectionConfig.MySection.MyContent.MyEntry.MyDocument == null)
			{
				// if nothing was selected, give message & return
				if (ppCmbxLibDoc.SelectedIndex == -1)
				{
					MessageBox.Show("Must select a library document");
					return;
				}
				int docid = -1;
				DocumentInfoList LibDocList = DocumentInfoList.GetLibraries(true);
				for (int i = 0; i < LibDocList.Count; i++)
				{
					if (LibDocList[i].LibTitle == (string)ppCmbxLibDoc.Items[ppCmbxLibDoc.SelectedIndex])
					{
						docid = LibDocList[i].DocID;
						break;
					}
				}
				if (docid == -1) return;
				using (Document dc = Document.Get(docid))
				{
					_SectionConfig.MySection.MyContent.MyEntry.MyDocument = dc;
				}
			}
			else
			// if converting to library document, just put 'text' into the 'LibTitle' property (that's what flags
			// it to be a library document.
			{
				_SectionConfig.MySection.MyContent.MyEntry.MyDocument.LibTitle = _SectionConfig.MySection.MyContent.Text;
				// Save now so that it shows up in the library document list in the ppcmbxlibdoc (combo box
				// listing lib docs that is regenerated in ppCmbxLibDocFill)
				_SectionConfig.MySection.MyContent.MyEntry.MyDocument.Save();
				ppCmbxLibDocFill();
				ppCmbxLibDoc.Enabled = false;
			}
			ppBtnCvrtToLibDoc.Text = "Convert this Section To A Non-Library Document";
			lblLibraryDocument.Text = "Library Document";
			superTooltip1.SetSuperTooltip(this.ppBtnCvrtToLibDoc, new DevComponents.DotNetBar.SuperTooltipInfo("Convert To Non-Library Document", "", "This button will convert the current section from a library document to a non-library document",
				null, null, DevComponents.DotNetBar.eTooltipColor.Gray, true, false, new System.Drawing.Size(250, 76)));
		}

		private void ppCmbxLibDoc_SelectedIndexChanged(object sender, EventArgs e)
		{
			if (_Initializing) return;

			// first check if this is a 'new' section - if so, then just return.
			if (_SectionConfig.MySection.MyContent.MyEntry == null) return;
			// see if this was NOT a library document.  If it is not a library document, ask the user if 
			// it should be linked, thus losing the original text/data.
			if (_SectionConfig.MySection.MyContent.MyEntry.MyDocument != null && !(_SectionConfig.MySection.MyContent.MyEntry.MyDocument.LibTitle != ""))
			{
				_SectionConfig.MySection.MyContent.MyEntry.MyDocument = Document.New();
				if (ppCmbxLibDoc.SelectedIndex > -1)
				{
					if (MessageBox.Show("Linking to this library document will cause loss of data to this section.  Do you want to continue?", "Link", MessageBoxButtons.YesNo) == DialogResult.Yes)
					{
						_DocumentToDelete = _SectionConfig.MySection.MyContent.MyEntry.MyDocument;
						DocumentInfoList LibDocList = DocumentInfoList.GetLibraries(true);
						_SectionConfig.MySection.MyContent.MyEntry.MyDocument = Document.Get(LibDocList[ppCmbxLibDoc.SelectedIndex].DocID);
						ppBtnCvrtToLibDoc.Enabled = true;
					}
					else
					{
						ppCmbxLibDoc.SelectedIndex = -1;
						ppBtnCvrtToLibDoc.Enabled = false;
					}
				}

			}
			//else if (_SectionConfig.MySection.MyContent.MyEntry.MyDocument == null)
			//{
			//    // was creating a new document & selected to connect it to a libdoc
			//    _DocumentToDelete = _SectionConfig.MySection.MyContent.MyEntry.MyDocument;
			//}
			else
			{
				// it already is a library document, just change usages...
				DocumentInfoList LibDocList = DocumentInfoList.GetLibraries(true);
				if (ppCmbxLibDoc.SelectedIndex >= 0 && ppCmbxLibDoc.SelectedIndex < LibDocList.Count)
				{
					_SectionConfig.MySection.MyContent.MyEntry.MyDocument = Document.Get(LibDocList[ppCmbxLibDoc.SelectedIndex].DocID);
					ppBtnCvrtToLibDoc.Enabled = true;
				}
				else
				{
					throw new Exception(string.Format("Index Out Of Range Index = {0}, Count = {1}", ppCmbxLibDoc.SelectedIndex, LibDocList.Count));
				}
			}
		}
		#endregion

		#region View Settings tab

		/// <summary>
		/// This is the View Settings button used on the button interface design
		/// </summary>
		/// <param name="sender">object</param>
		/// <param name="e">EventArgs</param>
		private void btnAutomation_Click(object sender, EventArgs e)
		{
			ProcessButtonClick(tiAutomation, btnAutomation);
		}

		#endregion

		#region Generic functions used on this property page

		/// <summary>
		/// Determines what labels (showing default values) are visable on the property pages
		/// </summary>
		private void defaultSettingsVisiblity()
		{
			//ItemInfo ii = ItemInfo.Get(_SectionConfig.MySection.ItemID);
			ppLblDefSettingsInfo.Visible = ppCbShwDefSettings.Checked;
			ppLblFormatDefault.Visible = ppCbShwDefSettings.Checked && ppBtnDefaultFmt.Visible;
			ppLblDefaultNumColumns.Visible = _isStepSection && ppCbShwDefSettings.Checked && ppBtnDefaultNumColumns.Visible;
			ppBtnDefaultNumColumns.Visible = _isStepSection && ppBtnDefaultNumColumns.Visible;  // bug fix B2016-241 something was sometimes setting this to true for Word sections
			ppLblDefPaginationStyle.Visible = _isStepSection && ppCbShwDefSettings.Checked && ppBtnDefaultPaginationStyle.Visible;
			ppBtnDefaultPaginationStyle.Visible = _isStepSection && ppBtnDefaultPaginationStyle.Visible; // bug fix B2016-241 insurence based on DefaultNumColumns sometimes set to true
			//ppLblDefaultPrintSize.Visible = !_isStepSection && ppCbShwDefSettings.Checked && ppBtnDefaultPrintSize.Visible;

		}

		/// <summary>
		/// For the Button Interface property page style, when a button is selected (pressed),
		/// it will remain in the checked state even when a different button is selected.  Thus
		/// we must clear the checked state of the buttons when a button is selected, then set
		/// the newly selected button's state to checked.
		/// </summary>
		private void ClearAllCheckedButtons()
		{
			btnGeneral.Checked = false;
			btnFormat.Checked = false;
			btnLibDocs.Checked = false;
			btnAutomation.Checked = false;
		}

		/// <summary>
		/// Select the corresponding tab and set the button's state to checked
		/// </summary>
		/// <param name="tab">Property Page Tab</param>
		/// <param name="button">Corresponding Property Page Button</param>
		private void ProcessButtonClick(TabItem tab, ButtonX button)
		{
			ClearAllCheckedButtons();
			tcSectionProp.SelectedTab = tab;
			button.Checked = true;
		}

		/// <summary>
		/// This is a generic Enter Event function for use with all of the property page tabs.
		/// Found that the visiblity value of buttons is not recorded until the property page in which it resides is diplayed.
		/// Thus we need to call defaultSettingVisiblity() to check and set visiblity states.
		/// </summary>
		/// <param name="sender"> type object</param>
		/// <param name="e">type EventArgs</param>
		private void tabpage_Enter(object sender, EventArgs e)
		{
			// Show or hide the labels containing the default values
			//if (!_Initializing) // jsj 1-23-2017 was not showing default check upon property page entry
				defaultSettingsVisiblity();
		}
		/// <summary>
		/// Process a change in the combo box selection
		/// </summary>
		/// <param name="cmbx">Combo Box Name</param>
		/// <param name="defstr">string containing default text</param>
		/// <param name="button">button to reset to default value</param>
		/// <param name="deflabel">label containing the default</param>
		private void ProcessCmbxSelectedValueChange(ComboBoxEx cmbx, string defstr, ButtonX button, Label deflabel)
		{
			if ((cmbx.SelectedIndex != -1) && defstr != null && defstr.Equals(cmbx.SelectedValue))
			{
				button.Visible = true;
				button.Focus();
				button.PerformClick();
			}
			button.Visible = (cmbx.SelectedValue != null);
			deflabel.Visible = (ppCbShwDefSettings.Checked) && button.Visible;
		}
		/// <summary>
		/// Process a change in the enum combo box selection
		/// </summary>
		/// <param name="cmbx">Combo Box Name</param>
		/// <param name="defstr">the default enum value</param>
		/// <param name="button">button to reset to default value</param>
		/// <param name="deflabel">label containing the default</param>
		private void ProcessCmbxSelectionEnumChanged(ComboBoxEx cmbx, object enumval, ButtonX button, Label deflabel)
		{
			if ((cmbx.SelectedIndex != -1) &&
				cmbx.SelectedValue.Equals(enumval))
			{
				bool sav_Initializing = _Initializing;
				_Initializing = true;
				button.Visible = true;
				button.Focus();
				button.PerformClick();
				cmbx.SelectedIndex = -1; // This will hide the Default button
				_Initializing = sav_Initializing;
			}
			//button.Visible = ((!_FolderConfig.Name.Equals("VEPROMS")) && (cmbx.SelectedValue != null));
			button.Visible = ((cmbx.SelectedValue != null) && (cmbx.SelectedIndex >= 0));
			deflabel.Visible = ppCbShwDefSettings.Checked && button.Visible;
		}
		#endregion

		private void ppSectNumberStpRTB_Enter(object sender, EventArgs e)
		{
			_MyStepTabRibbon.MyStepRTB = ppSectNumberStpRTB;
		}

		private void ppSectTitleStpRTB_Enter(object sender, EventArgs e)
		{
			_MyStepTabRibbon.MyStepRTB = ppSectTitleStpRTB;
		}

		private void ShowAvailableOptionsForSectionType()
		{
			lblColumns.Visible = _isStepSection;
			ppCmbxNumColumns.Visible = _isStepSection;
			lblPagination.Visible = _isStepSection;
			ppCmbxSectPagination.Visible = _isStepSection;
			//lblPrintSize.Visible = !_isStepSection;
			//ppCmbxAccPgPrintSize.Visible = !_isStepSection;
			ppGpbxSignoffCheckoff.Visible = _isStepSection;
			cbKeepWordDocMargins.Visible = !_isStepSection;
			ppCbDefaultStepSection.Visible = _isStepSection;
		}

		private void rbStepSect_CheckedChanged(object sender, EventArgs e)
		{
			_isStepSection = rbStepSect.Checked;
			rbWordSect.Checked = !rbStepSect.Checked;
			if (!_Initializing)
			{
				SetupPpCmbxSectionType();
				ShowAvailableOptionsForSectionType();
				tcpLibDoc.Enabled = !_isStepSection;
			}
		}

		private void ppCmbxSectPagination_SelectedValueChanged(object sender, EventArgs e)
		{
			SectionConfig.SectionPagination secpgn = (SectionConfig.SectionPagination)Enum.Parse(typeof(SectionConfig.SectionPagination), _DefaultPaginationStyle);
			ProcessCmbxSelectionEnumChanged(ppCmbxSectPagination, secpgn, ppBtnDefaultPaginationStyle, ppLblDefPaginationStyle);
			tcpFormat.Focus();
		}

		private void ppCmbxNumColumns_SelectedValueChanged(object sender, EventArgs e)
		{
			SectionConfig.SectionColumnMode seccols = (SectionConfig.SectionColumnMode)Enum.Parse(typeof(SectionConfig.SectionColumnMode), _DefaultNumColumns);
			ProcessCmbxSelectionEnumChanged(ppCmbxNumColumns, seccols, ppBtnDefaultNumColumns, ppLblDefaultNumColumns);
			tcpFormat.Focus();
		}

		//private void ppCmbxAccPgPrintSize_SelectedValueChanged(object sender, EventArgs e)
		//{
		//    SectionConfig.AttPrintSize attsize = (SectionConfig.AttPrintSize)Enum.Parse(typeof(SectionConfig.AttPrintSize), _DefaultPrintSize);
		//    ProcessCmbxSelectionEnumChanged(ppCmbxAccPgPrintSize, attsize, ppBtnDefaultPrintSize, ppLblDefaultPrintSize);
		//}

		private void ppBtnDefaultPaginationStyle_Click(object sender, EventArgs e)
		{
			// Get the parent setting
			SectionConfig.SectionPagination secpgn = (SectionConfig.SectionPagination)Enum.Parse(typeof(SectionConfig.SectionPagination), _DefaultPaginationStyle);
			// Compare parent setting with current setting
			if (secpgn != _SectionConfig.Section_Pagination)
				_SectionConfig.Section_Pagination = secpgn; // this will force a database update (write)
			ppCmbxSectPagination.SelectedIndex = -1;//reset to the default Section Pagination Style setting
			tcpFormat.Focus();
		}

		private void ppBtnDefaultNumColumns_Click(object sender, EventArgs e)
		{
			// Get the parent setting
			SectionConfig.SectionColumnMode seccols = (SectionConfig.SectionColumnMode)Enum.Parse(typeof(SectionConfig.SectionColumnMode), _DefaultNumColumns);
			// Compare parent setting with current setting
			if (seccols != _SectionConfig.Section_ColumnMode)
				_SectionConfig.Section_ColumnMode = seccols; // this will force a database update (write)
			ppCmbxNumColumns.SelectedIndex = -1;//reset to the default Number of Columns setting
			tcpFormat.Focus();
		}

		private void frmSectionProperties_Shown(object sender, EventArgs e)
		{
			ppSectNumberStpRTB.Focus();
		}

		private void ppCbEditableData_CheckedChanged(object sender, EventArgs e)
		{
			bool isEditable = ppCbEditableData.Checked;
			if (!_Initializing)
				_SectionConfig.SubSection_Edit = isEditable ? "Y" : "N";
		}

		private void ppCbPrnSecNumTitle_CheckedChanged(object sender, EventArgs e)
		{
			bool isEditable = ppCbPrnSecNumTitle.Checked;
			if (!_Initializing)
				_SectionConfig.Section_PrintHdr = isEditable ? "Y" : "N";
		}
		private void ppCbAutoIndent_CheckedChanged(object sender, EventArgs e)
		{
			bool isEditable = ppCbAutoIndent.Checked;
			if (!_Initializing)
				_SectionConfig.SubSection_AutoIndent = isEditable ? "Y" : "N";
		}
		private void ppCbIncTOC_CheckedChanged(object sender, EventArgs e)
		{
			bool isInToc = (_SectionConfig.MySection.MySectionInfo.MyDocStyle.IncludeInTOC) ? !ppCbIncTOC.Checked : ppCbIncTOC.Checked;
			if (!_Initializing)
				_SectionConfig.Section_TOC = ppCbIncTOC.Checked ? "Y" : "N";
			gpTOC.Visible = isInToc;
		}

		private void ppCmbxCheckoffHeading_SelectedIndexChanged(object sender, EventArgs e)
		{
			int selindx = ppCmbxCheckoffHeading.SelectedIndex;
			if (!_Initializing)
				_SectionConfig.Section_CheckoffHeaderSelection = selindx;
		}

		private void cbKeepWordDocMargins_CheckedChanged(object sender, EventArgs e)
		{
			bool doWordMargin = cbKeepWordDocMargins.Checked;
			if (!_Initializing)
				_SectionConfig.Section_WordMargin = doWordMargin ? "Y" : "N";
		}

		private void ppCbPlaceKeeper_CheckedChanged(object sender, EventArgs e)
		{
			if (!_Initializing)
				_SectionConfig.Section_Placekeeper = ppCbPlaceKeeper.Checked ? "Y" : "N";
		}

		private void ppCbPhoneList_CheckedChanged(object sender, EventArgs e)
		{
			if (!_Initializing)
				_SectionConfig.Section_PhoneList = ppCbPhoneList.Checked ? "Y" : "N";
		}

		private void ppCbDefaultStepSection_CheckedChanged(object sender, EventArgs e)
		{
			if (!_Initializing)
			{
				if (!ppCbDefaultStepSection.Checked)
				{
					// If user unchecks this section, i.e. wants to clear it from being 'Default Step Section'
					// just tell user that only 1 section can be the default step section.
					// The way this is supported in code is to only allow the user to check
					// the checkbox if it is not already set.  This is the way the code supported only
					// allowing 1 section to have this flag.
					MessageBox.Show("Only one section can be set as the 'Default Step Section'. To make another section the 'Default Step Section', select the checkbox on the Properties of that section.", "WARNING");
					ppCbDefaultStepSection.Checked = true;
				}
				else
				{
					// Note that this just sets the config item - it does not save it.  Save is 
					// done when the 'OK' button is clicked.  At that time, if this section's
					// Section_OriginalSteps is set, then all other sections will need to have this
					// property cleared (Only 1 section can be the OriginalStep section.
					_SectionConfig.Section_OriginalSteps = ppCbDefaultStepSection.Checked ? "Y" : "N";
				}
			}
		}
		private void ppBtnConvertToDocX_Click(object sender, EventArgs e)
		{
			// Get Document as file
			ItemInfo ii = ItemInfo.Get(_SectionConfig.MySection.ItemID);
			DocumentInfo doclibinfo = ii.MyContent.MyEntry.MyDocument;
			DSOFile myfile = new DSOFile(doclibinfo);
			// When trying to fix this , the update of the document waas causing a CSLA crash so I switched
			// to make document
			//using (Document myDoc = doclibinfo.Get())
			//{
			// Open MSWord App
				LBWordLibrary.LBApplicationClass ap = new LBWordLibrary.LBApplicationClass();
				LBWordLibrary.LBDocumentClass doc = ap.Documents.Open(myfile.FullName);
				string filename = myfile.FullName.ToUpper().Replace(".RTF", ".DOCX");
				doc.SaveAs(filename, LBWordLibrary.LBWdSaveFormat.wdFormatXMLDocument);  // Convert to DocX
				doc.Close();
				ap.Quit();
				FileInfo fi = new FileInfo(filename);
				FileStream fs = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);// B2016-053
				long len = fs.Length;
				byte[] ByteArray = new byte[len];
				int nBytesRead = fs.Read(ByteArray, 0, (int)len);
				fs.Close();
				Document myDoc = Document.MakeDocument(null, ByteArray, doclibinfo.DocAscii, doclibinfo.Config, ".DOCX");
				_SectionConfig.MySection.MyContent.MyEntry.MyDocument = myDoc;
				_SectionConfig.MySection.MyContent.MyEntry.Save();
				//myDoc.DocContent = ByteArray;
				//myDoc.FileExtension = ".DOCX";
				//myDoc.Save();
				fi.Delete();// Cleanup afterwards
				ppBtnConvertToDocX.Visible = false; // Hide the button after the execution is complete.
			//}
		}

		private void ppCmbxFormat_DropDown(object sender, EventArgs e)
		{
			_Initializing = true;
			// C2017-004 - if using the default format, position the dropdown to the default format
			if (ppCmbxFormat.SelectedIndex == -1)
				ppCmbxFormat.SelectedValue = _DefaultFormatName;
			_Initializing = false;
		}

		private void ppCmbxFormat_DropDownClosed(object sender, EventArgs e)
		{
			// upon exit of the dropdown if the default format is selected - click the Default button
			if ((string)(ppCmbxFormat.SelectedValue) == _DefaultFormatName)
			{
				ppBtnDefaultFmt.PerformClick();
				ppCmbxStyleSectionType.Focus();
			}
		}

		//private void ppBtnDefaultPrintSize_Click(object sender, EventArgs e)
		//{
		//    // Get the parent setting
		//    SectionConfig.AttPrintSize attsize = (SectionConfig.AttPrintSize)Enum.Parse(typeof(SectionConfig.AttPrintSize), _DefaultPrintSize);
		//    // Compare parent setting with current setting
		//    if (attsize != _SectionConfig.Section_AttachmentPrintSize)
		//        _SectionConfig.Section_AttachmentPrintSize = attsize; // this will force a database update (write)
		//    ppCmbxAccPgPrintSize.SelectedIndex = -1;//reset to the default Accessory page Print Size setting
		//    tcpFormat.Focus();
		//}
	}
}
