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 Volian.Base.Library;
using Volian.Print.Library;
using System.IO;
using System.Text.RegularExpressions;
using DevComponents.DotNetBar;

namespace VEPROMS
{
	public partial class dlgApproveProcedure : Form
	{
		public event DisplayConsistencyReportEvent ConsistencyPrintRequest;
		private void OnConsistencyPrintRequest(ConsistencyReportArgs args)
		{
			if (ConsistencyPrintRequest != null)
				ConsistencyPrintRequest(this, args);
		}
		private bool CanApprove
		{
			get { return btnApprove2.Enabled;}
			set 
			{
				btnApprove2.Enabled = value;
				tsslStatus.ForeColor = Color.Red;
				tsslStatus.BackColor = Color.Yellow;
				tsslStatus.Text = value ? "" : "Need to correct the Rev Numbers marked with Question Marks";
			}
		}
		private int _ApplicabilityIndex = 0;
		public int ApplicabilityIndex
		{
			get { return _ApplicabilityIndex; }
			set { _ApplicabilityIndex = value; }
		}
		private SessionInfo _MySessionInfo;
		public SessionInfo MySessionInfo
		{
			get { return _MySessionInfo; }
			set 
			{ 
				_MySessionInfo = value;
				_MyApproval.MySessionInfo = _MySessionInfo;
			}
		}
		private ApprovalInfo _MyApproval;
		private bool _CheckForMore = false;
		private DocVersionInfo _MyDocVersion;
		frmVEPROMS _MyFrmVEPROMS = null;
		public frmVEPROMS MyFrmVEPROMS
		{
			get { return _MyFrmVEPROMS; }
			set { _MyFrmVEPROMS = value; }
		}
		public dlgApproveProcedure(DocVersionInfo myDocVersion, frmVEPROMS myFrmVEPROMS)
		{
			MyFrmVEPROMS = myFrmVEPROMS;// Save frmVEPROMS for Import to shutoff SessionPing
			_MyApproval = new ApprovalInfo(myFrmVEPROMS);// Save frmVEPROMS for Import to shutoff SessionPing
			ApplicabilityIndex = myDocVersion.DocVersionConfig.SelectedSlave;
			this.ConsistencyPrintRequest += new DisplayConsistencyReportEvent(dlgApproveProcedure_ConsistencyPrintRequest);
			_MyDocVersion = myDocVersion;
			InitializeComponent();
			FlexGridAddEvents();
			_MyApproval.StatusUpdated += new ApprovalStatusChangeEvent(_MyApproval_StatusUpdated);
			SetupComboBoxes();
			foreach (ProcedureInfo pi in myDocVersion.Procedures)
			{
				pi.MyDocVersion.DocVersionConfig.SelectedSlave = ApplicabilityIndex;
				_MyApproval.AddProcedure(pi);
			}
			SetupMyApproval();
			//pnlApprove.LocationChanged += new EventHandler(Panel_LocationChanged);
			//pnlSelect.LocationChanged += new EventHandler(Panel_LocationChanged);
			pnlApprove.SendToBack();
			this.Width = pnlApprove.Width + this.Width - this.ClientSize.Width;
		}

		private void FlexGridAddEvents()
		{
			//fgProcs.ChangeEdit += new EventHandler(fgProcs_ChangeEdit);
			//Console.WriteLine(fgProcs.ComboBoxEditor.GetType().Name);
			//Console.WriteLine(fgProcs.Editor.GetType().Name);
			//fgProcs.ImeModeChanged += new EventHandler(fgProcs_ImeModeChanged);
			//fgProcs.LeaveEdit += new C1.Win.C1FlexGrid.RowColEventHandler(fgProcs_LeaveEdit);
			//fgProcs.SetupEditor += new C1.Win.C1FlexGrid.RowColEventHandler(fgProcs_SetupEditor);
			//fgProcs.StartEdit += new C1.Win.C1FlexGrid.RowColEventHandler(fgProcs_StartEdit);
			//fgProcs.ValidateEdit += new C1.Win.C1FlexGrid.ValidateEditEventHandler(fgProcs_ValidateEdit);
			fgProcs.ComboCloseUp += new C1.Win.C1FlexGrid.RowColEventHandler(fgProcs_ComboCloseUp);
			//fgProcs.MouseDown += new MouseEventHandler(fgProcs_MouseDown);
			//fgProcs.MouseUp += new MouseEventHandler(fgProcs_MouseUp); 
		}

		void fgProcs_MouseUp(object sender, MouseEventArgs e)
		{
			C1.Win.C1FlexGrid.HitTestInfo hti = fgProcs.HitTest(e.X, e.Y);
			Console.WriteLine("fgProcs_MouseUp X={0},Y={1},Row={2},Col={3}", e.X, e.Y, hti.Row, hti.Column);
		}

		void fgProcs_MouseDown(object sender, MouseEventArgs e)
		{
			C1.Win.C1FlexGrid.HitTestInfo hti = fgProcs.HitTest(e.X, e.Y);
			Console.WriteLine("fgProcs_MouseDown X={0},Y={1},Row={2},Col={3}", e.X, e.Y,hti.Row,hti.Column);
			
		}

		void fgProcs_ComboCloseUp(object sender, C1.Win.C1FlexGrid.RowColEventArgs e)
		{
			Console.WriteLine("fgProcs_ComboCloseUp e.row={0}, fgprocs.mouserow={1}", e.Row, fgProcs.MouseRow);
			if (e.Row == fgProcs.MouseRow)
				return;
			fgProcs_AfterEdit(sender, e);
			//Console.WriteLine("fgProcs_ComboCloseUp row: {0}, col: {1}, val: {2}, etostring: {3}", e.Row, e.Col, fgProcs[e.Row, e.Col], e.ToString());
		}

		void fgProcs_ValidateEdit(object sender, C1.Win.C1FlexGrid.ValidateEditEventArgs e)
		{
			Console.WriteLine("fgProcs_ValidateEdit");
		}

		void fgProcs_StartEdit(object sender, C1.Win.C1FlexGrid.RowColEventArgs e)
		{

			object val = fgProcs[e.Row, e.Col];
			DateTime dt = (DateTime)val;
			if (dt != null)
				dt = dt.AddHours(1);
			fgProcs[e.Row, e.Col] = dt;
			Console.WriteLine("fgProcs_StartEdit val: {0}, dt: {1}",val,dt);
		}

		void fgProcs_SetupEditor(object sender, C1.Win.C1FlexGrid.RowColEventArgs e)
		{
			Console.WriteLine("fgProcs_SetupEditor");
		}

		void fgProcs_LeaveEdit(object sender, C1.Win.C1FlexGrid.RowColEventArgs e)
		{
			object val = fgProcs[e.Row, e.Col];
			DateTime dt = (DateTime)val;
			if (dt != null && dt.Hour != 0)
				dt = dt.AddHours(-1);
			fgProcs[e.Row, e.Col] = dt;
			Console.WriteLine("fgProcs_LeaveEdit val: {0}, dt: {1}, mouserow={2}, mousecol={3}", val, dt,fgProcs.MouseRow,fgProcs.MouseCol);
		}

		void fgProcs_ImeModeChanged(object sender, EventArgs e)
		{
			Console.WriteLine("fgProcs_ImeModeChanged");
		}

		void fgProcs_ChangeEdit(object sender, EventArgs e)
		{
			Console.WriteLine("fgProcs_ChangeEdit");
		}
		void Panel_LocationChanged(object sender, EventArgs e)
		{
			if (pnlApprove.Location.X == 0 && pnlSelect.Location.X == 0)
				return;
			if (pnlApprove.Location.X == 0)
			{
				chkViewPDF.Visible = false;
				chkSetAllDates.Visible = true;
				if (_MyApproval.MyProcedures.Count == 1)
				{
					this.Text = "Approve " + _MyApproval.MyProcedures[0].ProcInfo.DisplayNumber;
					chkViewPDF.Visible = true;
					chkSetAllDates.Visible = false;
				}
				else if (_MyApproval.MyProcedures.Count == _MyDocVersion.Procedures.Count)
					this.Text = "Approve All Procedures";
				else
					this.Text = "Approve Selected Procedures";
				InitializePanelApprove();
			}
			if (pnlSelect.Location.X == 0)
			{
				this.Text = "Select Procedures To Approve";
				InitializePanelSelect();
			}
		}
		private void InitializePanelSelect()
		{
			if (clbMore.Items.Count == 0)
			{
				foreach (ProcedureInfo pi in _MyDocVersion.Procedures)
				{
					OwnerInfo oi = OwnerInfo.GetByItemID(pi.ItemID, CheckOutType.Procedure);
					pi.MyDocVersion.DocVersionConfig.SelectedSlave = _MyDocVersion.DocVersionConfig.SelectedSlave;
					if (oi != null && oi.SessionID != MySessionInfo.SessionID)
					{
						string prcNumber = pi.DisplayNumber + string.Format(" Checked out to {0}", oi.SessionUserID);
						clbMore.Items.Add(prcNumber);
					}
					else
						clbMore.Items.Add(pi.DisplayNumber);
					tmpProcedures.Add(pi.DisplayNumber, pi);
				}
			}
			for (int i = 0; i < clbMore.Items.Count; i++)
			{
        ProcedureInfo pi = GetProcedureInfoByKey(clbMore.Items[i].ToString());
				clbMore.SetItemChecked(i, _MyApproval.ProcedureExists(pi));
			}
		}
		private void InitializePanelApprove()
		{
			SetupMyApproval();
		}
		private Dictionary<string, ProcedureInfo> tmpProcedures = new Dictionary<string, ProcedureInfo>();
    private ProcedureInfo GetProcedureInfoByKey(string key)
    {
			if (key.Contains(" Checked out to "))
				key = key.Substring(0, key.IndexOf(" Checked out to "));
			if (tmpProcedures.ContainsKey(key))
        return tmpProcedures[key];
      else
        return tmpProcedures[GetDisplayNumberOnly(key)];
    }
		public dlgApproveProcedure(DocVersionInfo myDocVersion, bool selectSome, frmVEPROMS myFrmVEPROMS)
		{
			MyFrmVEPROMS = myFrmVEPROMS;// Save frmVEPROMS for Import to shutoff SessionPing
			_MyApproval = new ApprovalInfo(myFrmVEPROMS);// Save frmVEPROMS for Import to shutoff SessionPing
			this.ConsistencyPrintRequest += new DisplayConsistencyReportEvent(dlgApproveProcedure_ConsistencyPrintRequest);
			_MyDocVersion = myDocVersion;
			InitializeComponent();
			FlexGridAddEvents();
			_MyApproval.StatusUpdated +=  new ApprovalStatusChangeEvent(_MyApproval_StatusUpdated);
			_CheckForMore = false;
			//pnlApprove.LocationChanged += new EventHandler(Panel_LocationChanged);
			//pnlSelect.LocationChanged += new EventHandler(Panel_LocationChanged);
			pnlSelect.SendToBack();
			this.Width = pnlSelect.Width + this.Width - this.ClientSize.Width; ;
		}
		public dlgApproveProcedure(ProcedureInfo myProcedure, frmVEPROMS myFrmVEPROMS)
		{
			MyFrmVEPROMS = myFrmVEPROMS;// Save frmVEPROMS for Import to shutoff SessionPing
			_MyApproval = new ApprovalInfo(myFrmVEPROMS);// Save frmVEPROMS for Import to shutoff SessionPing
			this.ConsistencyPrintRequest += new DisplayConsistencyReportEvent(dlgApproveProcedure_ConsistencyPrintRequest);
			_MyDocVersion = myProcedure.MyDocVersion;
			InitializeComponent();
			FlexGridAddEvents();
			SetupComboBoxes();
			_MyApproval.AddProcedure(myProcedure);
			//SetupMyApproval();
			//pnlApprove.LocationChanged += new EventHandler(Panel_LocationChanged);
			//pnlSelect.LocationChanged += new EventHandler(Panel_LocationChanged);
			pnlApprove.SendToBack();
			this.Width = pnlApprove.Width;
		}
		void _MyApproval_StatusUpdated(ApprovalInfo sender, ApprovalMessageArgs e)
		{
			tsslMsg2.Text = e.MyStatus;
			Application.DoEvents();
		}
		private void SetupMyApproval()
		{
			approvalInfoBindingSource.DataSource = _MyApproval;
			//if(_MyApproval.MyProcedures.Count == 1)
			//  lblOldRevNumber.Text = _MyApproval.RevNumber;
			//else if (_MyApproval.MyProcedures.Count > 1)
			//  lblMaxRevNumber1.Text = GetMaxRevNumber();
			_MyApproval.RevType = (revTypeBindingSource.Current as RevType).TypeID;
			_MyApproval.RevStage = (stageInfoBindingSource.Current as StageInfo).StageID;
			approvalInfoBindingSource.ResetBindings(false);
			approvalProcedureBindingSource.DataSource = _MyApproval.MyProcedures;
			approvalProcedureBindingSource.ResetBindings(false);
			//this.ConsistencyPrintRequest -= new DisplayConsistencyReportEvent(dlgApproveProcedure_ConsistencyPrintRequest);
		}
		private string GetMaxRevNumber()
		{
			string mrn = string.Empty;
			foreach (ApprovalProcedure ap in _MyApproval.MyProcedures)
			{
				int k = _MyApproval.FancyShmancyRevCompare(mrn, ap.RevNumber);
				if (k < 0)
					mrn = ap.RevNumber;
			}
			return mrn;
		}
		void dlgApproveProcedure_ConsistencyPrintRequest(object sender, ConsistencyReportArgs args)
		{
			foreach (ProcedureInfo pi in args.MyItems)
				pi.IsSelected = _MyApproval.ProcedureExists(pi);
			PDFConsistencyCheckReport rpt = new PDFConsistencyCheckReport(args.ReportName, args.MyItems);
			rpt.BuildReport();
		}
		private void SetupComboBoxes()
		{
			RevTypes rt = new RevTypes();
			foreach (int i in Enum.GetValues(typeof(Rev_Types)))
			{
				RevType t = new RevType(i, Enum.GetName(typeof(Rev_Types), i));
				if (t.TypeID == 1) // only show first item for now
					rt.Add(t);
			}
			revTypeBindingSource.DataSource = rt;
			stageInfoBindingSource.DataSource = StageInfoList.Get();
		}
		private void btnApprove_Click(object sender, EventArgs e)
		{
			this.Cursor = Cursors.WaitCursor;
			if(!_MyApproval.Approve(new Point(Left,Bottom)))
				this.DialogResult = DialogResult.None;
			this.Cursor = Cursors.Default;
		}
		private void cmbRevisionType_SelectedIndexChanged(object sender, EventArgs e)
		{
			RevType rt = cmbRevisionType2.SelectedItem as RevType;
			_MyApproval.RevType = rt.TypeID;
		}
		private void cmbRevisionStage_SelectedIndexChanged(object sender, EventArgs e)
		{
			StageInfo si = cmbRevisionStage2.SelectedItem as StageInfo;
			_MyApproval.RevStage = si.StageID;
		}
		private void clbMore_ItemCheck(object sender, ItemCheckEventArgs e)
		{
			ProcedureInfo pi = GetProcedureInfoByKey(clbMore.Items[e.Index].ToString());
			OwnerInfo oi = OwnerInfo.GetByItemID(pi.ItemID, CheckOutType.Procedure);
			if (oi != null && oi.SessionID != MySessionInfo.SessionID)
			{
				string msg = string.Format("Cannot select this procedure for approval.\n\n It is checked out to {0}", oi.SessionUserID);
				MessageBox.Show(msg,pi.DisplayNumber);
				e.NewValue = CheckState.Unchecked;
				return;
			}
			if (e.NewValue == CheckState.Checked)
				btnOkay.Enabled = true;
			else
				btnOkay.Enabled = (clbMore.CheckedItems.Count > 1);
			btnCheckMore.Enabled = btnOkay.Enabled;
			btnReportMore.Enabled = false;
		}
		private void btnOkay_Click(object sender, EventArgs e)
		{
			UpdateMyApproval();
			//lbProcs.DataSource = null;
			//lbProcs.DataSource = _MyApproval.MyProcedures;
			//lbProcs.DisplayMember = "DisplayNumber";
			approvalProcedureBindingSource.DataSource = _MyApproval.MyProcedures;
			approvalProcedureBindingSource.ResetCurrentItem();
			pnlApprove.SendToBack();
		}
		private void UpdateMyApproval()
		{
			if (clbMore.CheckedItems.Count == 0)
				pnlApprove.SendToBack();
			SetupComboBoxes();
			for (int i = 0; i < clbMore.Items.Count; i++)
			{
				string xyz = clbMore.Items[i].ToString();
				ProcedureInfo pi = GetProcedureInfoByKey(clbMore.Items[i].ToString());
				if (clbMore.GetItemChecked(i))
				{
					if (!_MyApproval.ProcedureExists(pi))
						_MyApproval.AddProcedure(pi);
				}
				else
				{
					if (_MyApproval.ProcedureExists(pi))
						_MyApproval.DeleteProcedure(pi);
				}
			}
			SetupMyApproval();
		}
		private void btnCheck_Click(object sender, EventArgs e)
		{
			//if (chkCascade1.Checked || chkCascade2.Checked)
			//{
			//  MessageBox.Show("cascade");
			//}
			//else
			//{
				pnlSelect.SendToBack();
				UpdateClbMore();
			//}
		}
		private ItemInfoList _MyItemInfoList;
		private void UpdateClbMore()
		{
			int checkedCount = clbMore.CheckedItems.Count;
			int z =  int.Parse("0" + lblPhase.Text);
			z++;
			lblPhase.Text = z.ToString();
			string oldLabel = lblMore.Text;
			pbMore.Visible = true;
			pbMore.Maximum = _MyApproval.MyProcedures.Count;
			ItemInfoList.ConsistencyCheckUpdated += new ItemInfoListCCEvent(ItemInfoList_ConsistencyCheckUpdated);
			List<ProcedureInfo> myProcs = new List<ProcedureInfo>();
			foreach (ApprovalProcedure ap in _MyApproval.MyProcedures)
				myProcs.Add(ap.ProcInfo);
			_MyItemInfoList = ItemInfoList.GetMoreProcedures(myProcs);
			ItemInfoList.ConsistencyCheckUpdated -= new ItemInfoListCCEvent(ItemInfoList_ConsistencyCheckUpdated);
			lblMore.Text = oldLabel;
			pbMore.Visible = false;
			//clbMore.Items.Clear();
			//tmpProcedures.Clear();
			for (int i = 0; i < clbMore.Items.Count; i++)
			{
				string info = clbMore.Items[i].ToString();
				if(info.Contains(" - ("))
					clbMore.Items[i] = info.Substring(0, info.IndexOf(" - ("));
			}			
			foreach (ProcedureInfo npi in _MyItemInfoList)
			{
				string info = string.Format(npi.MyDifferenceReasons.StartsWith("No ") ? "{0}" : "{0} - ({1})", npi.DisplayNumber, npi.MyDifferenceReasons);
				//checked list box
				//int k = clbMore.Items.Add(info);
				for (int i = 0; i < clbMore.Items.Count; i++)
				{
					if (clbMore.Items[i].ToString().StartsWith(npi.DisplayNumber))
					{
						clbMore.Items[i] = info;
						tmpProcedures[npi.DisplayNumber] = npi;
						if (chkCascade2.Checked || chkCascadeMore.Checked)
							clbMore.SetItemChecked(i, true);
						break;
					}
				}
			}
			Application.DoEvents();
			clbMore.Enabled = btnAll.Enabled = btnClear.Enabled = true;
			//if (clbMore.Items.Count == 0)
			//{
			//  clbMore.Items.Add("None Found");
			//  clbMore.Enabled = btnAll.Enabled = btnClear.Enabled = false;
			//}
			lblMore.Text = string.Format("{0} Procedures, {1} Selected", clbMore.Items.Count, clbMore.CheckedItems.Count);
			btnReportMore.Enabled = true;
			_CheckForMore = true;

			if (chkCascade2.Checked || chkCascadeMore.Checked)
			{
				if (clbMore.CheckedItems.Count > checkedCount)
				{
					//btnAll_Click(btnAll, new EventArgs());
					UpdateMyApproval();
					UpdateClbMore();
				}
				else
					lblPhase.Text = "";
			}
		}
		void ItemInfoList_ConsistencyCheckUpdated(object sender, ItemInfoListCCEventArgs args)
		{
			if (sender != null)
			{
				pbMore.Value = args.MyCount;
				lblMore.Text = args.MyProcedure.DisplayNumber;
			}
			else
			{
				pbMore.Value = pbMore.Maximum;
				lblMore.Text = "Querying Database";
			}
			Application.DoEvents();
		}
		//private void dtiRevisionDate_ValueChanged(object sender, EventArgs e)
		//{
		//  DevComponents.Editors.DateTimeAdv.DateTimeInput dti = sender as DevComponents.Editors.DateTimeAdv.DateTimeInput;
		//}
		private void btnAll_Click(object sender, EventArgs e)
		{
			for (int i = 0; i < clbMore.Items.Count; i++)
				clbMore.SetItemChecked(i, true);
		}
		private void btnClear_Click(object sender, EventArgs e)
		{
			for (int i = 0; i < clbMore.Items.Count; i++)
				clbMore.SetItemChecked(i, false);
		}
		private void btnCancelMore_Click(object sender, EventArgs e)
		{
			if (!_CheckForMore)
			{
				this.Close();
				return;
			}
			//if (_MyApproval.MyProcedures.Count == 1)
			//  pnlOne.SendToBack();
			//else
				pnlApprove.SendToBack();
		}
		//private void tsmiRemove_Click(object sender, EventArgs e)
		//{
		//  ApprovalProcedure ap = approvalProcedureBindingSource.Current as ApprovalProcedure;
		//  _MyApproval.RemoveProcedure(ap.ProcInfo);
		//  approvalProcedureBindingSource.DataSource = _MyApproval.MyProcedures;
		//  approvalProcedureBindingSource.ResetCurrentItem();
		//  //_MyApproval.RemoveProcedure(lbProcs.SelectedItem as ProcedureInfo);
		//  //lbProcs.DataSource = null;
		//  //lbProcs.DataSource = _MyApproval.MyProcedures;
		//  //lbProcs.DisplayMember = "DisplayNumber";
		//}
		private int _LastIndex = -1;
		private void clbMore_MouseMove(object sender, MouseEventArgs e)
		{
			if (_MyApproval.MyProcedures.Count > 0)
			{
				int itemIndex = clbMore.IndexFromPoint(new Point(e.X, e.Y));
				if (itemIndex == -1)
					sttMore.HideTooltip();
				if (itemIndex == _LastIndex)
					return;
				_LastIndex = itemIndex;
				if (itemIndex >= 0)
				{
					if (clbMore.Items[itemIndex] != null)
					{
						SuperTooltipInfo stti = sttMore.GetSuperTooltip(clbMore);
						//string headerText = tmpProcedures[xyz].DisplayNumber;
						//string bodyText = tmpProcedures[xyz].MyDifferencesText;
						stti.HeaderText = GetProcedureInfoByKey(clbMore.Items[itemIndex].ToString()).DisplayNumber;
						stti.BodyText = GetProcedureInfoByKey(clbMore.Items[itemIndex].ToString()).MyDifferencesText;
						stti.FooterVisible = false;
						using (Graphics g = CreateGraphics())
						{
							SizeF sf = g.MeasureString(stti.BodyText, this.Font);
							stti.CustomSize = new Size(10 + sf.ToSize().Width, 0);
						}
						sttMore.ShowTooltip(sender);
						return;
					}
				}
			}
			//sttMore.HideTooltip();
		}
		private string GetDisplayNumberOnly(string s)
		{
			int d = s.IndexOf(" - ");
			if (d > -1)
				s = s.Substring(0, d).Trim();
			return s;
		}
		private void btnCheckMore_Click(object sender, EventArgs e)
		{
			UpdateMyApproval();
			UpdateClbMore();
		}
		private void btnReportMore_Click(object sender, EventArgs e)
		{
			OnConsistencyPrintRequest(new ConsistencyReportArgs(Volian.Base.Library.VlnSettings.TemporaryFolder + @"\MyConsistency.pdf", _MyItemInfoList));
		}
		private void CascadeChecksUpdated(object sender, EventArgs e)
		{
			DevComponents.DotNetBar.Controls.CheckBoxX cb = sender as DevComponents.DotNetBar.Controls.CheckBoxX;
			if (cb != null)
			{
				chkCascade2.Checked = chkCascadeMore.Checked = cb.Checked;
			}
		}
		private void fgProcs_AfterEdit(object sender, C1.Win.C1FlexGrid.RowColEventArgs e)
		{
			ApprovalProcedure ap = approvalProcedureBindingSource.Current as ApprovalProcedure;
			if (e.Col == 1)
			{	//revnumber
				_MyApproval.Refresh();
				approvalInfoBindingSource.ResetBindings(false);
				bool ok = true;
				foreach (ApprovalProcedure app in _MyApproval.MyProcedures)
				{
					ok = ok && !app.RevNumber.Contains(" ?");
				}
				CanApprove = ok;
			}
			if (e.Col == 2)
			{	//revdate
				DateTime dts = DateTime.Parse(fgProcs[e.Row, e.Col].ToString());
				//store mouse row because the popup calendar can goof up the datagrid mouse row
				int fgmr = fgProcs.MouseRow;
				if (e.Row == fgmr && ap.RevDate == dts)
					return;
				if (chkSetAllDates.Checked)
				{
					foreach (ApprovalProcedure app in _MyApproval.MyProcedures)
					{
						app.RevDate = ap.RevDate;
					}
				approvalProcedureBindingSource.ResetBindings(false);
				}
			}
		}
		//private void tsmiAddMore_Click(object sender, EventArgs e)
		//{
		//  pnlSelect.SendToBack();
		//}
		private void btnModifyList_Click(object sender, EventArgs e)
		{
			pnlSelect.SendToBack();
		}

		private void btnIncrement_Click(object sender, EventArgs e)
		{
			StringBuilder sb = new StringBuilder();
			string sep = "Procedures that failed to increment\r\n\r\n";
			foreach (ApprovalProcedure ap in _MyApproval.MyProcedures)
				if (!IncrementRev(ap))
				{
					sb.Append(sep + ap.DisplayNumber);
					sep = "\r\n";
				}
			approvalProcedureBindingSource.ResetBindings(false);
			if (sb.Length > 0)
			{
				sb.AppendLine(); sb.AppendLine();
				sb.AppendLine("These will be marked with a question mark.");
				sb.Append("They need to be corrected before Approval can be run.");
				MessageBox.Show(sb.ToString(), "Increment Failures", MessageBoxButtons.OK, MessageBoxIcon.Warning);
				CanApprove = false;
			}
			else
				CanApprove = true;
		}
		private bool IncrementRev(ApprovalProcedure ap)
		{
			bool rv = true;
			if (Regex.IsMatch(ap.RevNumber, "^[0-9]+$"))
				ap.RevNumber = (int.Parse(ap.RevNumber) + 1).ToString();
			else if (Regex.IsMatch(ap.RevNumber, "^[0-9]*[a-yA-Y]+$"))
			{
				char lastCar = ap.RevNumber[ap.RevNumber.Length - 1];
				lastCar++;
				ap.RevNumber = ap.RevNumber.Substring(0, ap.RevNumber.Length - 1) + lastCar.ToString();
			}
			else if (ap.RevNumber == string.Empty)
				ap.RevNumber = "1";
			else if (Regex.IsMatch(ap.RevNumber, "^[0-9.]+[.][0-9]+$"))
			{
				string[] parts = ap.RevNumber.Split(".".ToCharArray());
				string sep = "";
				string lastPart = parts[parts.Length - 1];
				int w = lastPart.Length;
				lastPart = (int.Parse(lastPart) + 1).ToString();
				//if(w > lastPart.Length)
					lastPart = lastPart.PadLeft(w, '0');
				parts[parts.Length - 1] = lastPart;
				StringBuilder sb = new StringBuilder();
				foreach (string part in parts)
				{
					sb.Append(sep + part);
					sep = ".";
				}
				ap.RevNumber = sb.ToString();
			}
			else if (Regex.IsMatch(ap.RevNumber, "[?]$"))
				rv = false;	//do nothing
			else
			{
				ap.RevNumber += " ?";
				rv = false;
			}
			return rv;
		}
	}
	public class ApprovalProcedure
	{
		private ProcedureInfo _ProcInfo;
		public ProcedureInfo ProcInfo
		{
			get { return _ProcInfo; }
			set { _ProcInfo = value; }
		}
		private string _RevNumber;
		public string RevNumber
		{
			get { return _RevNumber; }
			set
			{
				if (value.Trim() != _RevNumber)
				{
					_RevNumber = value.Trim();
					//_RevDate = DateTime.Now; // commented out for bug fix B2013-012
				}
			}
		}
		private DateTime _RevDate;
		public DateTime RevDate
		{
			get { return _RevDate; }
			set { _RevDate = value; }
		}
		// added RevNumAndDate to handle the use use of the DoRevDate flag
		// this fixes bug B2013-011 where Today's date would print on the approved procedures (Westinghouse data)
		// instead of the the Revision Date assigned to the procedure.
		public string RevNumAndDate
		{
			get
			{
				if (_ProcInfo.ActiveFormat.PlantFormat.FormatData.PrintData.DoRevDate)
					return RevNumber + "/" + RevDate.ToString("M/d/yyyy");
				else
					return RevNumber;
			}
		}
		public string DisplayNumber
		{
			get { return _ProcInfo.DisplayNumber; }
		}
		public override string ToString()
		{
			return string.Format("{0}\t{1}\t{2:M/d/yyyy}", _ProcInfo.DisplayNumber, _RevNumber, _RevDate);
		}
		public ApprovalProcedure(ProcedureInfo proc)
		{
			proc.ProcedureConfig.SelectedSlave = proc.MyDocVersion.DocVersionConfig.SelectedSlave;
			ProcInfo = proc;
			RevNumber = proc.ProcedureConfig.Print_Rev == string.Empty ? "0" : proc.ProcedureConfig.Print_Rev;
			//AppRevDate Change
			//DateTime revdate;
			string sRevDate = proc.ProcedureConfig.Print_RevDate;
			if (sRevDate == string.Empty)
				sRevDate = DateTime.Now.ToString("M/d/y");
			DateTime revDate;
			if (!DateTime.TryParse(sRevDate, out revDate)) revDate = DateTime.Now;
			RevDate = revDate;
			//RevDate = DateTime.Parse(sRevDate);
			//RevDate = DateTime.Parse(proc.ProcedureConfig.Print_RevDate);
			//if (print_revdate == string.Empty && DateTime.TryParse(RevNumber, out revdate))
			//	;
			//else
			//	revdate = DateTime.TryParse(proc.ProcedureConfig.Print_RevDate.Replace("-", "/").Replace("00/", "01/"), out revdate) ? revdate : DateTime.Now;
			//RevDate = revdate;
		}
	}
	public class ApprovalMessageArgs : EventArgs
	{
		public ApprovalMessageArgs(string msg)
		{
			_MyStatus = msg;
		}
		private string _MyStatus;
		public string MyStatus
		{
			get { return _MyStatus; }
			set { _MyStatus = value; }
		}
	}
	public delegate void ApprovalStatusChangeEvent(ApprovalInfo sender, ApprovalMessageArgs e);
	public class ApprovalInfo
	{
		frmVEPROMS _MyFrmVEPROMS = null;
		public frmVEPROMS MyFrmVEPROMS
		{
			get { return _MyFrmVEPROMS; }
			set { _MyFrmVEPROMS = value; }
		}
		public event ApprovalStatusChangeEvent StatusUpdated;
		public void OnStatusUpdated(ApprovalInfo sender, ApprovalMessageArgs e)
		{
			if (StatusUpdated != null)
				StatusUpdated(sender, e);
		}
		private SessionInfo _MySessionInfo;
		public SessionInfo MySessionInfo
		{
			get { return _MySessionInfo; }
			set { _MySessionInfo = value; }
		}
		private int _RevType;
		public int RevType
		{
			get { return _RevType; }
			set { _RevType = value; }
		}
		private string _RevNumber;
		public string RevNumber
		{
			get { return _RevNumber; }
			set { _RevNumber = value; }
		}
		private Nullable<DateTime> _RevDate;
		public Nullable<DateTime> RevDate
		{
			get { return _RevDate == null ? _RevDate : _RevDate.Value; }
			set { _RevDate = value; }
		}
		private int _RevStage;
		public int RevStage
		{
			get { return _RevStage; }
			set { _RevStage = value; }
		}
		private string _RevNote;
		public string RevNote
		{
			get { return _RevNote; }
			set { _RevNote = value; }
		}
		private bool _ViewPDF;
		public bool ViewPDF
		{
			get { return _ViewPDF; }
			set { _ViewPDF = value; }
		}
		private string _MsgNumber;
		public string MsgNumber
		{
			get { return _MsgNumber; }
			set { _MsgNumber = value; }
		}
		private string _MsgDate;
		public string MsgDate
		{
			get { return _MsgDate; }
			set { _MsgDate = value; }
		}
		private bool _CanIncrement;
		public bool CanIncrement
		{
			get { return _CanIncrement; }
			set { _CanIncrement = value; }
		}
		private List<ApprovalProcedure> _MyProcedures;
		public List<ApprovalProcedure> MyProcedures
		{
			get { return _MyProcedures; }
			//set { _MyProcedures = value; }
		}
		public ApprovalInfo(frmVEPROMS myFrmVEPROMS)
		{
			MyFrmVEPROMS = myFrmVEPROMS;// Save frmVEPROMS for Import to shutoff SessionPing
			_MyProcedures = new List<ApprovalProcedure>();
		}
		private static string FormatRev(Match m)
		{
			return "".PadLeft(5 - m.Groups[1].Value.Length, '0') + m.Groups[1].Value;
		}
		public void AddProcedure(ProcedureInfo proc)
		{
			ApprovalProcedure ap = new ApprovalProcedure(proc);
			MyProcedures.Add(ap);
			Refresh();
		}
		public void RemoveProcedure(ProcedureInfo pi)
		{
			ApprovalProcedure apr = null;
			foreach (ApprovalProcedure ap in MyProcedures)
			{
				if (ap.ProcInfo == pi)
				{
					apr = ap;
					break;
				}
			}
			MyProcedures.Remove(apr);
			Refresh();
		}
		public bool ProcedureExists(ProcedureInfo pi)
		{
			foreach (ApprovalProcedure pp in MyProcedures)
			{
				if(pp.ProcInfo.ItemID == pi.ItemID)
					return true;
			}
			return false;
		}
		public void Refresh()
		{
			bool ok = true;
			int rv = 0;
			foreach (ApprovalProcedure ap in MyProcedures)
			{
				ok = ok && int.TryParse(ap.RevNumber, out rv);
			}
			_CanIncrement = ok;
			//if (MyProcedures.Count == 1)
			//{
			//  ProcedureInfo pi = _MyProcedures[0].ProcInfo;
			//  RevNumber = pi.ProcedureConfig.Print_Rev == string.Empty ? "0" : pi.ProcedureConfig.Print_Rev;
			//  DateTime revdate = pi.ProcedureConfig.Print_RevDate == string.Empty ? DateTime.Now : DateTime.TryParse(pi.ProcedureConfig.Print_RevDate, out revdate) ? revdate : DateTime.Now;
			//  RevDate = revdate;
			//  RevNote = string.Empty;
			//  ViewPDF = false;
			//}
			//else if (MyProcedures.Count > 1)
			//{
			//  Regex myRegEx = new Regex("^([0-9]{1,5})");
			//  SortedList<string, ProcedureInfo> printRevs = new SortedList<string, ProcedureInfo>();
			//  SortedList<string, ProcedureInfo> printRevDates = new SortedList<string, ProcedureInfo>();
			//  string printRev = string.Empty;
			//  foreach (ApprovalProcedure pi in MyProcedures)
			//  {
			//    printRev = myRegEx.Replace(pi.RevNumber, new MatchEvaluator(FormatRev));
			//    printRev = printRev == string.Empty ? "0" : printRev;
			//    if (printRev != string.Empty)
			//      if (!printRevs.ContainsKey(printRev))
			//        printRevs.Add(printRev, pi.ProcInfo);
			//    if (pi.RevDate != null)
			//      if (!printRevDates.ContainsKey(pi.RevDate.ToString()))
			//        printRevDates.Add(pi.RevDate.ToString(), pi.ProcInfo);
			//  }
			//  if (printRevs.Count > 1)
			//  {
			//    ProcedureInfo pi = printRevs[printRevs.Keys[printRevs.Count - 1]];
			//    RevNumber = "*";
			//    MsgNumber = "Multiple Revision Numbers found.  Enter asterisk (*) to use current revision numbers or plus sign (+) to increment revision numbers";
			//  }
			//  else if (printRevs.Count == 1)
			//  {
			//    ProcedureInfo pi = printRevs[printRevs.Keys[printRevs.Count - 1]];
			//    RevNumber = pi.ProcedureConfig.Print_Rev;
			//    MsgNumber = string.Empty;
			//  }
			//  if (printRevDates.Count > 1)
			//  {
			//    RevDate = null;
			//    MsgDate = "Multiple Revision Dates found.  Use current revision dates or manually assign revision date by selecting a date";
			//  }
			//  else if (printRevDates.Count == 1)
			//  {
			//    ProcedureInfo pi = printRevDates[printRevDates.Keys[printRevDates.Count - 1]];
			//    RevDate = DateTime.Parse(pi.ProcedureConfig.Print_RevDate);
			//    MsgDate = string.Empty;
			//  }
			//  else if (printRevDates.Count == 0)
			//    RevDate = DateTime.Now;
			//}
		}
		public void DeleteProcedure(ProcedureInfo pi)
		{
			ApprovalProcedure tpi = null;
			foreach (ApprovalProcedure pii in MyProcedures)
			{
				if (pii.ProcInfo.ItemID == pi.ItemID)
					tpi = pii;
			}
			if (tpi != null)
			{
				MyProcedures.Remove(tpi);
				Refresh();
			}
		}
		public bool CanApprove
		{
			get { return _RevType > 0 && _RevNumber != string.Empty && _RevStage > 0; }
		}
		public int FancyShmancyRevCompare(string s1, string s2)
		{
			if (s1 == s2)
				return 0;
			while (s1 != string.Empty && s2 != string.Empty)
			{
				//look for numbers
				Match m1 = Regex.Match(s1, "^[0-9]+");
				Match m2 = Regex.Match(s2, "^[0-9]+");
				if (m1.Length > 0 && m2.Length > 0)
				{
					int i1 = int.Parse(m1.Value);
					int i2 = int.Parse(m2.Value);
					if (i1 < i2)
						return -1;
					if (i1 > i2)
						return 1;
					s1 = s1.Substring(m1.Length);
					s2 = s2.Substring(m2.Length);
				}
				else
				{
					if (m1.Length > 0)
						return 1;
					if (m2.Length > 0)
						return -1;
				}
				//look for letters
				m1 = Regex.Match(s1, "^[A-Za-z]+");
				m2 = Regex.Match(s2, "^[A-Za-z]+");
				if (m1.Length > 0 && m2.Length > 0)
				{
					if (m1.Length > m2.Length)
						return 1;
					if (m1.Length < m2.Length)
						return -1;
					int c = m1.Value.CompareTo(m2.Value);
					if (c != 0)
						return c;
					s1 = s1.Substring(m1.Length);
					s2 = s2.Substring(m2.Length);
				}
				else
				{
					if (m1.Length > 0)
						return 1;
					if (m2.Length > 0)
						return -1;
				}
				//look for symbols
				m1 = Regex.Match(s1, "^[^0-9A-Za-z]+");
				m2 = Regex.Match(s2, "^[^0-9A-Za-z]+");
				if (m1.Length > 0 && m2.Length > 0)
				{
					int c = m1.Value.CompareTo(m2.Value);
					if (c != 0)
						return c;
					s1 = s1.Substring(m1.Length);
					s2 = s2.Substring(m2.Length);
				}
				else
				{
					if (m1.Length > 0)
						return 1;
					if (m2.Length > 0)
						return -1;
				}
			}
			return s1.CompareTo(s2);
		}
		public bool Approve(Point location)
		{
			ViewPDF = ViewPDF && MyProcedures.Count == 1;
			StringBuilder sb = new StringBuilder();
			StageInfo nsi = StageInfo.GetJustStage(RevStage);
			foreach (ApprovalProcedure ap in MyProcedures) //spin thru looking for updating current revision
			{
				//RevisionInfo ric = RevisionInfo.GetCurrentByItemID(ap.ProcInfo.ItemID);
				RevisionInfo ric = ap.ProcInfo.MyDocVersion.DocVersionConfig.SelectedSlave > 0 ? RevisionInfo.GetCurrentByItemIDandUnitID(ap.ProcInfo.ItemID,ap.ProcInfo.MyDocVersion.DocVersionConfig.SelectedSlave) : RevisionInfo.GetCurrentByItemID(ap.ProcInfo.ItemID);
				if (ric != null)
				{
					VersionInfo vi = ric.LatestVersion;
					if (ap.RevNumber == ric.RevisionNumber && nsi.IsApproved == 0 && vi.MyStage.IsApproved == 1)
						sb.AppendLine(string.Format("{0} - '{1}'", ap.ProcInfo.DisplayNumber, vi.MyStage.Name));
				}
			}
			if (sb.Length > 0)
			{
				sb.Insert(0, string.Format("The following procedures will be reverted to '{0}'\r\n\r\n", nsi.Name));
				sb.AppendLine("\r\nThis will restore change bars and summary of change results!");
				sb.AppendLine("\r\nIf you do not want this to occur, answer No to this dialog \r\nand then change the revision number to create a new revision.");
				sb.Append(string.Format("\r\nAre you sure you want to revert to '{0}'?",nsi.Name));
				if (MessageBox.Show(sb.ToString(),string.Format("Revert to {0}",nsi.Name),MessageBoxButtons.YesNo,MessageBoxIcon.Stop) == DialogResult.No)
					return false;
			}
			foreach (ApprovalProcedure ap in MyProcedures)
			{
				ProcedureInfo pi = ap.ProcInfo;
				OnStatusUpdated(this, new ApprovalMessageArgs(string.Format("Processing {0}", pi.DisplayNumber)));
				string summaryPDF = string.Format(@"{0}\{1} Summary of Changes.pdf", VlnSettings.TemporaryFolder, pi.PDFNumber);
				string pdfTmp = string.Format(@"{0}.pdf", pi.PDFNumber);
				string pdfPath = string.Format(@"{0}\{1}", VlnSettings.TemporaryFolder, pdfTmp);
				if (!TryToDelete(summaryPDF)) break;
				if (!TryToDelete(pdfPath)) break;
				RevisionInfo ric = pi.MyDocVersion.DocVersionConfig.SelectedSlave > 0 ? RevisionInfo.GetCurrentByItemIDandUnitID(pi.ItemID, pi.MyDocVersion.DocVersionConfig.SelectedSlave) : RevisionInfo.GetCurrentByItemID(pi.ItemID);
//				RevisionInfo rip = RevisionInfo.GetPreviousByItemID(pi.ItemID);
				DateTime myDTS = pi.DTS;
				string cbDTS = (pi.MyConfig as ProcedureConfig).Print_ChangeBarDate;
				if ((cbDTS ?? "") != "")
					myDTS = DateTime.Parse(cbDTS);
				if (ric != null && ap.RevNumber == ric.RevisionNumber && ric.LatestVersion.MyStage.IsApproved == 1)
				{
					myDTS = ric.MyConfig.History_StartDate;
					//UpdateProcedureDTS(pi, myDTS);
				}
				if (ric != null && ap.RevNumber != ric.RevisionNumber && ric.LatestVersion.MyStage.IsApproved == 1)
				{
					myDTS = ric.DTS;
//					myDTS = DateTime.Parse(pi.ProcedureConfig.Print_RevDate);
				}
				Revision revision = null;
				if (ap.ProcInfo.MyDocVersion.DocVersionConfig.SelectedSlave > 0)
				{
					revision = Revision.GetByItemIDAndRevisionNumberAndUnitID(pi.ItemID, ap.RevNumber, ap.ProcInfo.MyDocVersion.DocVersionConfig.SelectedSlave);
					if (revision == null)
					{
						RevisionConfig cfg = new RevisionConfig();
						cfg.History_StartDate = myDTS;	// pi.DTS;
						cfg.Applicability_Index = ap.ProcInfo.MyDocVersion.DocVersionConfig.SelectedSlave;
						//cfg.Save();
						revision = Revision.MakeRevision(pi.ItemID, RevType, ap.RevNumber, ap.RevDate, RevNote, cfg.ToString(), DateTime.Now, Volian.Base.Library.VlnSettings.UserID);
						//					revision.MyConfig.History_StartDate = pi.DTS;
						//					revision.MyConfig.Save();
						//					revision = revision.Save();
					}
					else if (revision.Notes != RevNote || revision.RevisionDate != ap.RevDate)
					{
						//C2016-036 - Inform the user that an existing approved version will be replaced
						if (MessageBox.Show("Replace Existing Revision " + ap.RevNumber + "\r\n\r\nChange the Rev Number to create a new revision.", "Replace Existing", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
							return false;
						revision.Notes = RevNote;
						revision.RevisionDate = ap.RevDate;
						revision = revision.Save();
					}
				}
				else
				{
					revision = Revision.GetByItemIDAndRevisionNumber(pi.ItemID, ap.RevNumber);
					if (revision == null)
					{
						RevisionConfig cfg = new RevisionConfig();
						cfg.History_StartDate = pi.DTS;
						//cfg.Save();
						revision = Revision.MakeRevision(pi.ItemID, RevType, ap.RevNumber, ap.RevDate, RevNote, cfg.ToString(), DateTime.Now, Volian.Base.Library.VlnSettings.UserID);
						//					revision.MyConfig.History_StartDate = pi.DTS;
						//					revision.MyConfig.Save();
						//					revision = revision.Save();
					}
					else if (revision.Notes != RevNote || revision.RevisionDate != ap.RevDate)
					{
						//C2016-036 - Inform the user that an existing approved version will be replaced
						if (MessageBox.Show("Replace Existing Revision " + ap.RevNumber + "\r\n\r\nChange the Rev Number to create a new revision.", "Replace Existing", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
							return false;
						revision.Notes = RevNote;
						revision.RevisionDate = ap.RevDate;
						revision = revision.Save();
					}
				}
				byte[] summaryBuf = null;
				//B2017-149 Allow the user to choose if they want the Summary of Changes report created during the approval process
				if (MessageBox.Show("Do you want to save the Summary of Changes along with the Approved PDF?", "Create Summary of Changes", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
					summaryBuf = CreateSummary(ref pi, summaryPDF, myDTS);
				DateTime currentDTS = DateTime.Now;
				Check check = Check.MakeCheck(revision, Stage.GetJustStage(RevStage), RevisionInfo.BuildRevisionChecks(pi), currentDTS, VlnSettings.UserID);
				//make pdf with promsprinter and get byte stream
				// Moved to end so that Item and Content are saved at the same time
				//UpdateProcedureConfig(pi, ap.RevNumber, ap.RevDate, myDTS);
				string waterMark = Stage.GetJustStage(RevStage).IsApproved > 0 ? null : Stage.GetJustStage(RevStage).Name;
				//ProcedureInfo myproc = pi;
				//frmPDFStatusForm frm = new frmPDFStatusForm(myproc, ap.RevNumber, /* revdate change: ap.RevDate.ToString("MM/dd/yyyy") ,*/ waterMark, false, false, ViewPDF, true, VlnSettings.TemporaryFolder, new ChangeBarDefinition(pi.MyDocVersion.MyConfig as DocVersionConfig, pi.ActiveFormat), pdfTmp, location);
				//myproc.ChangeBarDate = myDTS;
				frmPDFStatusForm frm = new frmPDFStatusForm(pi, ap.RevNumAndDate, /* revdate change: ap.RevDate.ToString("MM/dd/yyyy") ,*/ waterMark, false, false, ViewPDF, true, VlnSettings.TemporaryFolder, new ChangeBarDefinition(pi.MyDocVersion.MyConfig as DocVersionConfig, pi.ActiveFormat), pdfTmp, location, pi.MyDocVersion.DocVersionConfig.Print_AddBlankPagesWhenUsingDuplexFoldouts, true,"",false,false);
				frm.AllowAllWatermarks = true;
				frm.CloseWhenDone = !ViewPDF;
				frm.DocReplace = new Dictionary<int, byte[]>(); // will hold the Word Attachments with resolved ROs
				frm.ShowDialog();
				//if (ap.ProcInfo.MyDocVersion.DocVersionConfig.SelectedSlave > 0)
				//{
				//  using (ProcedureInfo myproc = ProcedureInfo.GetItemAndChildrenByUnit(pi.ItemID, 0, ap.ProcInfo.MyDocVersion.DocVersionConfig.SelectedSlave))
				//  {
				//    //frmPDFStatusForm frm = new frmPDFStatusForm(myproc, ap.RevNumber, /* revdate change: ap.RevDate.ToString("MM/dd/yyyy") ,*/ waterMark, false, false, ViewPDF, true, VlnSettings.TemporaryFolder, new ChangeBarDefinition(pi.MyDocVersion.MyConfig as DocVersionConfig, pi.ActiveFormat), pdfTmp, location);
				//    myproc.ChangeBarDate = myDTS;
				//    frmPDFStatusForm frm = new frmPDFStatusForm(myproc, ap.RevNumAndDate, /* revdate change: ap.RevDate.ToString("MM/dd/yyyy") ,*/ waterMark, false, false, ViewPDF, true, VlnSettings.TemporaryFolder, new ChangeBarDefinition(pi.MyDocVersion.MyConfig as DocVersionConfig, pi.ActiveFormat), pdfTmp, location);
				//    frm.AllowAllWatermarks = true;
				//    frm.CloseWhenDone = !ViewPDF;
				//    frm.ShowDialog();
				//  }
				//}
				//else
				//{
				//  using (ProcedureInfo myproc = ProcedureInfo.GetItemAndChildren(pi.ItemID))
				//  {
				//    //frmPDFStatusForm frm = new frmPDFStatusForm(myproc, ap.RevNumber, /* revdate change: ap.RevDate.ToString("MM/dd/yyyy") ,*/ waterMark, false, false, ViewPDF, true, VlnSettings.TemporaryFolder, new ChangeBarDefinition(pi.MyDocVersion.MyConfig as DocVersionConfig, pi.ActiveFormat), pdfTmp, location);
				//    myproc.ChangeBarDate = myDTS;
				//    frmPDFStatusForm frm = new frmPDFStatusForm(myproc, ap.RevNumAndDate, /* revdate change: ap.RevDate.ToString("MM/dd/yyyy") ,*/ waterMark, false, false, ViewPDF, true, VlnSettings.TemporaryFolder, new ChangeBarDefinition(pi.MyDocVersion.MyConfig as DocVersionConfig, pi.ActiveFormat), pdfTmp, location);
				//    frm.AllowAllWatermarks = true;
				//    frm.CloseWhenDone = !ViewPDF;
				//    frm.ShowDialog();
				//  }
				//}
				FileInfo pdfFile = new FileInfo(pdfPath);
				FileStream fs = pdfFile.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
				byte[] buf = new byte[pdfFile.Length];
				fs.Read(buf, 0, buf.Length);
				fs.Close();
				VEPROMS.CSLA.Library.Version version = VEPROMS.CSLA.Library.Version.MakeVersion(revision, Stage.GetJustStage(RevStage), buf, summaryBuf, currentDTS, VlnSettings.UserID);
				StageInfo si = StageInfo.GetJustStage(RevStage);
				int selectedSlave = pi.MyDocVersion.DocVersionConfig.SelectedSlave;
				pi.MyDocVersion.DocVersionConfig.SelectedSlave = 0;
				if (si.IsApproved == 1)
				{
					dlgExportImport dlg = new dlgExportImport("Export", pi, MyFrmVEPROMS); // "true tell export to convert ROs and Transitions to text
					dlg.DocReplace = frm.DocReplace;  // this tells approval to prepare an export file with resolved transitions and ROs, word sections are saved with resolved ROs during approval PDF creation and saved in DocReplace
					System.Xml.XmlDocument xd = new System.Xml.XmlDocument();
					dlg.ExportItem(xd, pi, "procedure");
					frm.DocReplace = dlg.DocReplace = null;
					version.ApprovedXML = xd.OuterXml;
					version.Save();
					dlg.Dispose();
					UpdateProcedureConfig(pi, ap.RevNumber, ap.RevDate, DateTime.Now, selectedSlave);

					// Clear the change bar override for this procedure:
					pi.ClearChangeBarOverrides();
				}
				else
					UpdateProcedureConfig(pi, ap.RevNumber, ap.RevDate, myDTS, selectedSlave);
				//UpdateProcedureDTS(pi, DateTime.Now);
				pi.MyDocVersion.DocVersionConfig.SelectedSlave = selectedSlave;
			}
			return true;
		}

		private byte[] CreateSummary(ref ProcedureInfo pi, string summaryPDF, DateTime myDTS)
		{
			//B2017-149 Added error handler so that the code will not crash if the Summary of Change report fails
			try
			{
				ContentAuditInfoList cail;
				AnnotationAuditInfoList aail;
				if (pi.MyDocVersion.DocVersionConfig.SelectedSlave > 0)
				{
					pi = ProcedureInfo.GetItemAndChildrenByUnit(pi.ItemID, 0, pi.MyDocVersion.DocVersionConfig.SelectedSlave);
					pi.ChangeBarDate = myDTS;
					cail = ContentAuditInfoList.GetSummaryByUnit(pi.ItemID, pi.ItemID, false, pi.MyDocVersion.DocVersionConfig.SelectedSlave, pi.ChangeBarDate);
					aail = AnnotationAuditInfoList.GetChronologyByUnit(pi.ItemID, pi.ItemID, pi.MyDocVersion.DocVersionConfig.SelectedSlave, pi.ChangeBarDate);
				}
				else
				{
					if (pi.ActiveFormat.PlantFormat.FormatData.TransData.UseTransitionModifier)
						pi = ProcedureInfo.GetItemAndChildrenByUnit(pi.ItemID, 0, pi.MyDocVersion.DocVersionConfig.SelectedSlave);
					else
						pi = ProcedureInfo.GetItemAndChildren(pi.ItemID);
					pi.ChangeBarDate = myDTS;
					cail = ContentAuditInfoList.GetSummary(pi.ItemID, pi.ItemID, false, pi.ChangeBarDate);
					aail = AnnotationAuditInfoList.GetChronology(pi.ItemID, pi.ItemID, pi.ChangeBarDate);
				}
				Volian.Print.Library.PDFChronologyReport myChronoRpt = new Volian.Print.Library.PDFChronologyReport(summaryPDF, pi, cail, aail);
				myChronoRpt.BuildSummary(ViewPDF);
				FileInfo pdfFile1 = new FileInfo(summaryPDF);
				FileStream fs1 = pdfFile1.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
				byte[] summaryBuf = new byte[pdfFile1.Length];
				fs1.Read(summaryBuf, 0, summaryBuf.Length);
				fs1.Close();
				return summaryBuf;
			}
			catch (Exception ex)
			{
				while (!(ex is System.Data.SqlClient.SqlException) && ex.InnerException != null)
					ex = ex.InnerException;
				MessageBox.Show(ex.Message +"\r\n\r\nApproval will continue without the Summary of Change Report", ex.GetType().Name + " while trying to create Summary of Changes." , MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
				return null;
			}
		}
		private bool TryToDelete(string pdfFile)
		{
			int cntr = 0;
			while (File.Exists(pdfFile))
			{
				try
				{
					File.Delete(pdfFile);
					return true;
				}
				catch
				{
					cntr++;
					StringBuilder sb = new StringBuilder();
					sb.AppendLine("Could not create");
					sb.AppendLine();
					sb.AppendLine(pdfFile + ".");
					sb.AppendLine();
					sb.AppendLine("If it is open, close and retry.");
					if (cntr >= 3)
					{
						sb.Insert(0, "PAY ATTENTION!!!\r\n\r\n");
						sb.AppendLine("\r\n\r\nFIRST CLOSE IT, THEN PRESS THE OK BUTTON!!!");
					}
					if(MessageBox.Show(sb.ToString(), "Error on CreatePdf", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) != DialogResult.OK)
						return false;
					Application.DoEvents();
				}
			}
			return true;
		}

		private void UpdateProcedureDTS(ProcedureInfo pi, DateTime dts)
		{
			using (Item itm = Item.Get(pi.ItemID))
			{
				itm.DTS = dts;
				itm.Save();
			}
		}
		private void UpdateProcedureConfig(ProcedureInfo procedureInfo, string revNumber, DateTime revDate, DateTime dts, int selectedSlave)
		{
			ProcedureConfig pc = procedureInfo.MyConfig as ProcedureConfig;
			if (pc == null) return;
			pc.SelectedSlave = selectedSlave;
			pc.Print_Rev = revNumber;
			//AppRevDate Change
			pc.Print_RevDate = revDate.ToString("MM/dd/yyyy");
			pc.Print_ChangeBarDate = dts.ToString("MM/dd/yyyy HH:mm:ss");
			using (Item itm = Item.Get(procedureInfo.ItemID))
			{
				itm.MyContent.Config = pc.ToString();
				//itm.DTS = dts;
				itm.UserID = Volian.Base.Library.VlnSettings.UserID;
				itm.Save();
			}

		}
	}
	public class RevType
	{
		private int _TypeID;
		public int TypeID
		{
			get { return _TypeID; }
			set { _TypeID = value; }
		}
		private string _TypeName;
		public string TypeName
		{
			get { return _TypeName; }
			set { _TypeName = value; }
		}
		public RevType(int i, string s)
		{
			_TypeID = i;
			_TypeName = s;
		}
	}
	public class RevTypes : List<RevType>
	{
	}
	public delegate void DisplayConsistencyReportEvent(object sender, ConsistencyReportArgs args);
	public class ConsistencyReportArgs : EventArgs
	{
		private string _ReportName;
		public string ReportName
		{
			get { return _ReportName; }
			set { _ReportName = value; }
		}
		private ItemInfoList _MyItems;
		public ItemInfoList MyItems
		{
			get { return _MyItems; }
			set { _MyItems = value; }
		}
		public ConsistencyReportArgs(string reportName, ItemInfoList myItems)
		{
			_ReportName = reportName;
			_MyItems = myItems;
		}
	}
}