/******************************************************************************
 * GODSMain.cs 
 * 
 * <Copyright and License> 
 * 
 * This file is part of GODS, a package for annotating medical images. 
 * 
 * Copyright (C) 2004 
 * Xuedong Chen 
 * Heri Mariwa 
 * Kimmy (Hsiang-ling) Lin 
 * Rui Yu 
 * 
 * This program is free software; you can redistribute it and/or 
 * modify it under the terms of the GNU General Public License 
 * as published by the Free Software Foundation; either version 2 
 * of the License, or (at your option) any later version. 
 * 
 * This program is distributed in the hope that it will be useful, 
 * but WITHOUT ANY WARRANTY; without even the implied warranty of 
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
 * GNU General Public License for more details. 
 * 
 * You should have received a copy of the GNU General Public License 
 * along with this program; if not, write to the Free Software 
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. 
 *  
 * For further questions about this file, please send email to 
 * gods@cs.umb.edu or visit us at http://gods.sourceforge.net.  
 ******************************************************************************/

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Drawing.Imaging;
using Microsoft.Win32;

namespace GODS
{
	using DBHandler;
	using ScreenCapture;
	using MarkData;
	using MarkConfig;
	
	/// <summary>
	/// Summary description for Form1.
	/// </summary>
	public class GODSMain : System.Windows.Forms.Form, ScreenCaptureRequester
	{
		public static int RECENT_IMAGE_NUM = 5;
		public static string ExecDir = null;
		public static string defaultImageDir = null;
		public static string ImageDir = null;
		public static string ConfigFile;
		public static string DefaultImagePath; // will be initialized after the config file is read after startup
		public static Bitmap DefaultImage; // will be initialized after the DefaultImagePath is initialized
		public static GODSDBManager dbManager = null;
		public static MarkSetHandler marksetHandler = null;
		public static AnnoForm ActiveAnnoForm = null;
		public static bool showSaveConfirmDlg = true;
		public static MarkCategory currCategory;
		public static MarkSet currMarkSet;
		public static MarkSetConfiguration markConfigForm = null;
	    public static GODSMain application = null;
		private static string regKey = null;
		private static string origImgFolder = null;
		private static string imgFolder = null;
		private static string imgExt = null;
		private bool showMarkForm = true;

		public MarkForm markForm;
		private Point markFormLocation;
		private BrowseForm browseForm;
		private SearchForm searchForm;
		private Config config;
		private ArrayList categories;

		private System.Windows.Forms.ToolBar toolBar1;
		private System.Windows.Forms.Button btnLoad;
		private System.Windows.Forms.Button btnExit;
		private System.Windows.Forms.Label label1;
		private System.Windows.Forms.ComboBox cBxCategory;
		private System.Windows.Forms.Button btnBrowse;
		private System.Windows.Forms.NotifyIcon captureNotify;
		private System.Windows.Forms.ContextMenu captureCtxMenu;
		private System.Windows.Forms.MenuItem rectangleItem;
		private System.Windows.Forms.MenuItem squareItem;
		private System.Windows.Forms.MenuItem fileMItem;
		private System.Windows.Forms.MenuItem saveMItem;
		private System.Windows.Forms.MenuItem exitMItem;
		private System.Windows.Forms.MenuItem viewMItem;
		private System.Windows.Forms.MenuItem showMFormMItem;
		private System.Windows.Forms.MenuItem toolsMItem;
		private System.Windows.Forms.MenuItem markConfigMItem;
		private System.Windows.Forms.MainMenu mainMenu;
		private System.Windows.Forms.OpenFileDialog openFileDialog;
		private System.Windows.Forms.MenuItem helpMItem;
		private System.Windows.Forms.MenuItem abtMItem;
		private System.Windows.Forms.MenuItem manMItem;
		private System.Windows.Forms.MenuItem fileMenuSep1;
		private System.Windows.Forms.MenuItem prefMItem;
		private System.Windows.Forms.Button btnNew;
		private System.Windows.Forms.MenuItem refreshMFormMItem;
		private System.Windows.Forms.MenuItem menuItem1;
		private System.Windows.Forms.ComboBox cbxFileList;
		private System.ComponentModel.IContainer components;

		public GODSMain()
		{
			//
			// Required for Windows Form Designer support
			//

			InitializeComponent();

			this.initAllStatic();
			// load default image from the config file
			this.config = new Config();
			this.checkImageFolder();
			GODS.GODSMain.DefaultImage = ImageUtil.getBitmapFromFile(GODS.GODSMain.DefaultImagePath);
			this.loadRecentImageFiles();
			this.browseForm = new BrowseForm(this);
			this.searchForm = new SearchForm();
			this.setupMarkForm();
			this.markFormLocation = this.markForm.Location;
			this.setupOpenFileDialog();
			this.loadCategories();
			this.Closing += new CancelEventHandler(GODSMain_Closing);
            GODSMain.application =  this;
		}

		private void checkImageFolder()
		{
			if (GODSMain.ImageDir == null || GODSMain.ImageDir.Trim().Equals("")) 
			{
				GODSMain.ImageDir = GODSMain.defaultImageDir;
			}
			string oimagePath = GODSMain.ImageDir+@"\oimage";
			string aimagePath = GODSMain.ImageDir+@"\aimage";

			if (!System.IO.Directory.Exists(GODSMain.ImageDir))
				System.IO.Directory.CreateDirectory(GODSMain.ImageDir);
			if (!System.IO.Directory.Exists(oimagePath))
				System.IO.Directory.CreateDirectory(oimagePath);
			if (!System.IO.Directory.Exists(aimagePath))
				System.IO.Directory.CreateDirectory(aimagePath);
		}

		private void loadRecentImageFiles()
		{
			this.cbxFileList.Items.Clear();
			this.cbxFileList.Items.AddRange(this.config.RecentImages.ToArray());
			this.cbxFileList.SelectedIndex = 0;
		}

		private void initAllStatic()
		{
			regKey = @"Software\Microsoft\Windows\CurrentVersion\App Paths\GODS2.exe";
			string dir;
			RegistryKey hklm, godsKey;

			// fix the current directory
			hklm = Registry.LocalMachine;
			if (hklm != null && (godsKey = hklm.OpenSubKey(regKey, false)) != null) 
			{
				dir = godsKey.GetValue("").ToString();
				GODSMain.ExecDir = dir.Replace("GODS2.exe", "");
			}
			else // set to default directory
			{
				GODSMain.ExecDir = System.Environment.CurrentDirectory + @"\";
			}

			ConfigFile = "GODSConfig.xml";
			dbManager = new GODSDBManager();
			marksetHandler = new MarkSetHandler();
			markConfigForm = null;
			
			origImgFolder = @"oimage\";
			imgFolder = @"aimage\";
			defaultImageDir = GODSMain.ExecDir + @"GODSImage";
			imgExt = @".bmp";
		}

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if (components != null) 
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		#region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.components = new System.ComponentModel.Container();
			System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(GODSMain));
			this.mainMenu = new System.Windows.Forms.MainMenu();
			this.fileMItem = new System.Windows.Forms.MenuItem();
			this.saveMItem = new System.Windows.Forms.MenuItem();
			this.fileMenuSep1 = new System.Windows.Forms.MenuItem();
			this.exitMItem = new System.Windows.Forms.MenuItem();
			this.viewMItem = new System.Windows.Forms.MenuItem();
			this.showMFormMItem = new System.Windows.Forms.MenuItem();
			this.refreshMFormMItem = new System.Windows.Forms.MenuItem();
			this.toolsMItem = new System.Windows.Forms.MenuItem();
			this.markConfigMItem = new System.Windows.Forms.MenuItem();
			this.prefMItem = new System.Windows.Forms.MenuItem();
			this.helpMItem = new System.Windows.Forms.MenuItem();
			this.abtMItem = new System.Windows.Forms.MenuItem();
			this.manMItem = new System.Windows.Forms.MenuItem();
			this.menuItem1 = new System.Windows.Forms.MenuItem();
			this.toolBar1 = new System.Windows.Forms.ToolBar();
			this.btnLoad = new System.Windows.Forms.Button();
			this.btnExit = new System.Windows.Forms.Button();
			this.label1 = new System.Windows.Forms.Label();
			this.cBxCategory = new System.Windows.Forms.ComboBox();
			this.openFileDialog = new System.Windows.Forms.OpenFileDialog();
			this.btnBrowse = new System.Windows.Forms.Button();
			this.captureNotify = new System.Windows.Forms.NotifyIcon(this.components);
			this.captureCtxMenu = new System.Windows.Forms.ContextMenu();
			this.rectangleItem = new System.Windows.Forms.MenuItem();
			this.squareItem = new System.Windows.Forms.MenuItem();
			this.btnNew = new System.Windows.Forms.Button();
			this.cbxFileList = new System.Windows.Forms.ComboBox();
			this.SuspendLayout();
			// 
			// mainMenu
			// 
			this.mainMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
																					 this.fileMItem,
																					 this.viewMItem,
																					 this.toolsMItem,
																					 this.helpMItem,
																					 this.menuItem1});
			// 
			// fileMItem
			// 
			this.fileMItem.Index = 0;
			this.fileMItem.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
																					  this.saveMItem,
																					  this.fileMenuSep1,
																					  this.exitMItem});
			this.fileMItem.Text = "File";
			// 
			// saveMItem
			// 
			this.saveMItem.Enabled = false;
			this.saveMItem.Index = 0;
			this.saveMItem.Text = "Save";
			this.saveMItem.Click += new System.EventHandler(this.saveMItem_Click);
			// 
			// fileMenuSep1
			// 
			this.fileMenuSep1.Index = 1;
			this.fileMenuSep1.Text = "-";
			// 
			// exitMItem
			// 
			this.exitMItem.Index = 2;
			this.exitMItem.Text = "Exit";
			this.exitMItem.Click += new System.EventHandler(this.exitMItem_Click);
			// 
			// viewMItem
			// 
			this.viewMItem.Index = 1;
			this.viewMItem.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
																					  this.showMFormMItem,
																					  this.refreshMFormMItem});
			this.viewMItem.Text = "View";
			// 
			// showMFormMItem
			// 
			this.showMFormMItem.Index = 0;
			this.showMFormMItem.Text = "Hide Marks";
			this.showMFormMItem.Click += new System.EventHandler(this.showMFormMItem_Click);
			// 
			// refreshMFormMItem
			// 
			this.refreshMFormMItem.Index = 1;
			this.refreshMFormMItem.Text = "Refresh";
			this.refreshMFormMItem.Click += new System.EventHandler(this.refreshMFormMItem_Click);
			// 
			// toolsMItem
			// 
			this.toolsMItem.Index = 2;
			this.toolsMItem.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
																					   this.markConfigMItem,
																					   this.prefMItem});
			this.toolsMItem.Text = "Tools";
			// 
			// markConfigMItem
			// 
			this.markConfigMItem.Index = 0;
			this.markConfigMItem.Text = "Edit Mark Set";
			this.markConfigMItem.Click += new System.EventHandler(this.markConfigMItem_Click);
			// 
			// prefMItem
			// 
			this.prefMItem.Index = 1;
			this.prefMItem.Text = "Preference";
			this.prefMItem.Click += new System.EventHandler(this.prefMItem_Click);
			// 
			// helpMItem
			// 
			this.helpMItem.Index = 3;
			this.helpMItem.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
																					  this.abtMItem,
																					  this.manMItem});
			this.helpMItem.Text = "Help";
			// 
			// abtMItem
			// 
			this.abtMItem.Index = 0;
			this.abtMItem.Text = "About";
			this.abtMItem.Click += new System.EventHandler(this.abtMItem_Click);
			// 
			// manMItem
			// 
			this.manMItem.Index = 1;
			this.manMItem.Text = "Manual";
			this.manMItem.Click += new System.EventHandler(this.manMItem_Click);
			// 
			// menuItem1
			// 
			this.menuItem1.Index = 4;
			this.menuItem1.Text = "";
			// 
			// toolBar1
			// 
			this.toolBar1.DropDownArrows = true;
			this.toolBar1.Location = new System.Drawing.Point(0, 0);
			this.toolBar1.Name = "toolBar1";
			this.toolBar1.ShowToolTips = true;
			this.toolBar1.Size = new System.Drawing.Size(792, 42);
			this.toolBar1.TabIndex = 0;
			// 
			// btnLoad
			// 
			this.btnLoad.BackColor = System.Drawing.SystemColors.ControlDark;
			this.btnLoad.Location = new System.Drawing.Point(352, 8);
			this.btnLoad.Name = "btnLoad";
			this.btnLoad.Size = new System.Drawing.Size(56, 23);
			this.btnLoad.TabIndex = 1;
			this.btnLoad.Text = "Load";
			this.btnLoad.Click += new System.EventHandler(this.btnLoad_Click);
			// 
			// btnExit
			// 
			this.btnExit.BackColor = System.Drawing.SystemColors.ControlDark;
			this.btnExit.Location = new System.Drawing.Point(688, 8);
			this.btnExit.Name = "btnExit";
			this.btnExit.Size = new System.Drawing.Size(56, 23);
			this.btnExit.TabIndex = 3;
			this.btnExit.Text = "Exit";
			this.btnExit.Click += new System.EventHandler(this.exitMItem_Click);
			// 
			// label1
			// 
			this.label1.BackColor = System.Drawing.SystemColors.Control;
			this.label1.Location = new System.Drawing.Point(8, 13);
			this.label1.Name = "label1";
			this.label1.Size = new System.Drawing.Size(56, 16);
			this.label1.TabIndex = 4;
			this.label1.Text = "Category";
			// 
			// cBxCategory
			// 
			this.cBxCategory.Location = new System.Drawing.Point(64, 10);
			this.cBxCategory.Name = "cBxCategory";
			this.cBxCategory.Size = new System.Drawing.Size(121, 21);
			this.cBxCategory.TabIndex = 5;
			this.cBxCategory.SelectedIndexChanged += new System.EventHandler(this.cBxCategory_SelectedIndexChanged);
			// 
			// btnBrowse
			// 
			this.btnBrowse.BackColor = System.Drawing.SystemColors.ControlDark;
			this.btnBrowse.Location = new System.Drawing.Point(280, 8);
			this.btnBrowse.Name = "btnBrowse";
			this.btnBrowse.Size = new System.Drawing.Size(56, 23);
			this.btnBrowse.TabIndex = 8;
			this.btnBrowse.Text = "Browse";
			this.btnBrowse.Click += new System.EventHandler(this.btnBrowse_Click);
			// 
			// captureNotify
			// 
			this.captureNotify.ContextMenu = this.captureCtxMenu;
			this.captureNotify.Icon = ((System.Drawing.Icon)(resources.GetObject("captureNotify.Icon")));
			this.captureNotify.Text = "Capture";
			this.captureNotify.Visible = true;
			this.captureNotify.DoubleClick += new System.EventHandler(this.captureNotify_DoubleClick);
			// 
			// captureCtxMenu
			// 
			this.captureCtxMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
																						   this.rectangleItem,
																						   this.squareItem});
			// 
			// rectangleItem
			// 
			this.rectangleItem.Index = 0;
			this.rectangleItem.Text = "Rectangle";
			this.rectangleItem.Click += new System.EventHandler(this.rectangleItem_Click);
			// 
			// squareItem
			// 
			this.squareItem.Index = 1;
			this.squareItem.Text = "Square";
			this.squareItem.Click += new System.EventHandler(this.squareItem_Click);
			// 
			// btnNew
			// 
			this.btnNew.BackColor = System.Drawing.SystemColors.ControlDark;
			this.btnNew.Location = new System.Drawing.Point(208, 8);
			this.btnNew.Name = "btnNew";
			this.btnNew.Size = new System.Drawing.Size(56, 23);
			this.btnNew.TabIndex = 10;
			this.btnNew.Text = "New";
			this.btnNew.Click += new System.EventHandler(this.btnNew_Click);
			// 
			// cbxFileList
			// 
			this.cbxFileList.Location = new System.Drawing.Point(424, 9);
			this.cbxFileList.Name = "cbxFileList";
			this.cbxFileList.Size = new System.Drawing.Size(248, 21);
			this.cbxFileList.TabIndex = 12;
			// 
			// GODSMain
			// 
			this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
			this.BackColor = System.Drawing.SystemColors.AppWorkspace;
			this.ClientSize = new System.Drawing.Size(792, 557);
			this.Controls.Add(this.cbxFileList);
			this.Controls.Add(this.btnNew);
			this.Controls.Add(this.btnBrowse);
			this.Controls.Add(this.cBxCategory);
			this.Controls.Add(this.label1);
			this.Controls.Add(this.btnExit);
			this.Controls.Add(this.btnLoad);
			this.Controls.Add(this.toolBar1);
			this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
			this.IsMdiContainer = true;
			this.Menu = this.mainMenu;
			this.Name = "GODSMain";
			this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
			this.Text = "GODS";
			this.WindowState = System.Windows.Forms.FormWindowState.Maximized;
			this.ResumeLayout(false);

		}
		#endregion

		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main() 
		{
			Application.Run(new GODSMain());
		}

		/// <summary>
		/// The current mark category of the application
		/// </summary>
		public string CurrentCategory
		{
			get
			{
				return this.cBxCategory.SelectedText;
			}
		}

		/// <summary>
		/// Set the selected AnnoForm to be the current active form.
		/// </summary>
		/// <param name="annoForm"></param>
		public void setActiveAnnoForm(AnnoForm annoForm)
		{
			//GODS.GODSMain.ActiveAnnoForm = annoForm;
			annoForm.Focus();
		}

		// set up the file filter for the dialog
		private void setupOpenFileDialog()
		{
			this.openFileDialog = new OpenFileDialog();
			this.openFileDialog.Multiselect = false;
			this.openFileDialog.Filter = "image files (*.jpg;*.bmp;*.gif)|*.jpg;*.bmp;*.gif";
		}

		private void setupMarkForm()
		{
			this.markForm = new MarkForm();
			this.markForm.MdiParent = this;
			this.markForm.Show();
		}

		// only called once during application startup
		private void loadCategories()
		{
			this.categories = GODS.GODSMain.marksetHandler.Categories;
			if(categories != null && categories.Count >0)
			{
				GODS.GODSMain.currCategory = GODS.GODSMain.marksetHandler.getCategory("Breast Imaging");
				this.cBxCategory.Items.Clear();
				this.cBxCategory.Items.AddRange(this.categories.ToArray());
				this.cBxCategory.SelectedIndex = 0;
			}
		}

		private void btnBrowse_Click(object sender, System.EventArgs e)
		{
			this.browseForm.ShowDialog();
		}

		#region Image Capturing EventHandlers

		// set the double clicking default to capturing rectangle shape
		private void captureNotify_DoubleClick(object sender, System.EventArgs e)
		{
			rectangleItem_Click(null, null);	
		}

		private void rectangleItem_Click(object sender, System.EventArgs e)
		{
			ScreenCaptureTransparentForm screenCaptureForm = new ScreenCaptureTransparentForm(this, Shapes.rectangle);
			screenCaptureForm.Show();
		}

		private void squareItem_Click(object sender, System.EventArgs e)
		{
			ScreenCaptureTransparentForm screenCaptureForm = new ScreenCaptureTransparentForm(this, Shapes.square);
			screenCaptureForm.Show();
		}

		#endregion

		/// <summary>
		/// API method for ScreenCapture. 
		/// </summary>
		/// <param name="image"></param>
		/// <param name="rect"></param>
		/// <param name="captureForm"></param>
		public void LoadCapturedImage(Bitmap image, Rectangle rect, Form captureForm)
		{
			captureForm.Close();
			this.ResumeLayout();

			// Activate the main application form.
			this.Activate();
			Bitmap bmpImage = image.Clone(rect, PixelFormat.Format32bppArgb);
			DiagnosticImage dImage = new AnyImage(bmpImage);
			ImageData imageData = this.prepareImageData(image, rect, false);
			
			if (imageData != null) 
			{
				AnnoForm annoForm = this.createAnnoForm(imageData, dImage);
				annoForm.Show();
			}

			// Set the WindowState to normal if the form is minimized.
			if (this.WindowState == FormWindowState.Minimized)
				this.WindowState = FormWindowState.Normal;
			this.BringToFront();
		}
		public bool isRelativePath(string path)
		{
			if(path[0] == '.')
			{
				return true;
			}
			return false;
		}
		// called when browsing/searching ends up with opening the record
		protected internal bool activateAnnoForm(int imageID)
		{
			Form[] forms = this.MdiChildren;
			AnnoForm annoForm;
			// start from 1 because the first mdichild is the mark form
			for (int i = 1; i < forms.Length; i++) 
			{
				annoForm = (AnnoForm) forms[i];
				if(imageID==annoForm.getImageId())
				{
					annoForm.Activate();
				    return true;
				}
			}
			return false;
		}
		// called when browsing/searching ends up with opening the record
		protected internal void LoadFromDB(ImageData imageData)
		{
			string path = imageData.OrigImgPath;
			if(isRelativePath(path))
				path = GODSMain.ExecDir + @"\" +path;
			Bitmap oImage = ImageUtil.getBitmapFromFile(path);
			Bitmap bmpImage = oImage.Clone(imageData.ImageRectangle, PixelFormat.Format32bppArgb);

			DiagnosticImage dImage;
			if (imageData.OrigImgPath.Equals(GODS.GODSMain.DefaultImagePath))
				dImage = new BreastSketchImage(bmpImage);
			else
				dImage = new AnyImage(bmpImage);
			if ((GODS.GODSMain.currMarkSet!=null)&&(GODS.GODSMain.currMarkSet.MarkSetID != imageData.MarkSetID))
			{ 
				int i = 0;
				foreach (MarkSet markset in GODS.GODSMain.currCategory.Marksets)
				{
					if(markset.MarkSetID==imageData.MarkSetID)
					{
						markForm.loadMarkset(i);
					    break;
					}
					i++;
				}
			}
			AnnoForm annoForm = this.createAnnoForm(imageData, dImage);
			annoForm.ReloadMarks();
			annoForm.Show();
		}

		// load arbitrary image. create a AnyImage as the DiagnosticImage
		private void btnLoad_Click(object sender, System.EventArgs e)
		{
			if (this.cbxFileList.SelectedIndex == this.config.RecentImages.Count-1) //new image
			{
				int lastIndex = this.config.RecentImages.Count-2;
				if (this.openFileDialog.ShowDialog() == DialogResult.OK)
				{
					if (this.config.RecentImages.Count == GODS.GODSMain.RECENT_IMAGE_NUM+1)
						this.config.RecentImages.RemoveAt(lastIndex);
					this.config.RecentImages.Insert(0, this.openFileDialog.FileName);
					this.loadRecentImageFiles();
					this.loadImage();
				}
			}
			else if (this.cbxFileList.SelectedIndex != 0) // move it up to the most recent
			{
				string file = (string) this.cbxFileList.SelectedItem;
				this.config.RecentImages.RemoveAt(this.cbxFileList.SelectedIndex);
				this.config.RecentImages.Insert(0, file);
				this.loadRecentImageFiles();
				this.loadImage();
			}
			else 
			{
				this.loadImage();
			}
		}

		private void loadImage()
		{
			Bitmap image = ImageUtil.getBitmapFromFile((string)this.config.RecentImages[0]);
			Rectangle rect = new Rectangle(0, 0, image.Width, image.Height);
			DiagnosticImage dImage = new AnyImage(image);
			ImageData imageData = this.prepareImageData(image, rect, false);
			if (imageData != null) 
			{
				AnnoForm annoForm = this.createAnnoForm(imageData, dImage);
				annoForm.Show();
			}
		}

		// load the default image as the DiagnosticImage
		private void btnNew_Click(object sender, System.EventArgs e)
		{
			Rectangle rect = new Rectangle(0, 0, GODS.GODSMain.DefaultImage.Width, GODS.GODSMain.DefaultImage.Height);
			Bitmap bmpImage = GODS.GODSMain.DefaultImage.Clone(rect, PixelFormat.Format32bppArgb);
			DiagnosticImage dImage = new BreastSketchImage(bmpImage);
			ImageData imageData = this.prepareImageData(null, rect, true);
			if (imageData != null) 
			{
				AnnoForm annoForm = this.createAnnoForm(imageData, dImage);
				annoForm.Show();
			}
		}

		// help create a ImageData object for the AnnoForm
		private ImageData prepareImageData(Image oImage, Rectangle rect, bool isDefaultImg)
		{
			ImageData imageData = null;
			InfoForm infoForm = new InfoForm();
			infoForm.ShowDialog();
			if (infoForm.Result)
			{
				string mrn = infoForm.MRN;
				DateTime imageDate = infoForm.ImageDate;
				string dateString = imageDate.ToString().Replace("/", "_").Replace(" ","_").Replace(":","_");
				string origImgPath;
				if (isDefaultImg)
				{
					origImgPath = GODS.GODSMain.DefaultImagePath;
				}
				else
				{
					origImgPath = 
						GODS.GODSMain.ImageDir + @"\" + GODS.GODSMain.origImgFolder + 
						infoForm.MRN + "_" + dateString + "_ORIG" + GODS.GODSMain.imgExt;
					oImage.Save(origImgPath, ImageFormat.Bmp);
				}
				string annoImgPath = 
					GODS.GODSMain.ImageDir + @"\" + GODS.GODSMain.imgFolder + mrn + "_" + 
					dateString + GODS.GODSMain.imgExt;
				int marksetID = GODS.GODSMain.currMarkSet.MarkSetID;
				DateTime lastUpdateDate = DateTime.Now;
				string reason = "";
				imageData =  new ImageData(-1, mrn, marksetID, this.CurrentCategory, annoImgPath,
					origImgPath, rect, "", reason, false, imageDate, lastUpdateDate, false);
			}
			infoForm.cleanup();
			return imageData;
		}

		private AnnoForm createAnnoForm(ImageData imgData, DiagnosticImage dImage)
		{
			AnnoForm annoForm = new GODS.AnnoForm(this, imgData, dImage);
			annoForm.Text = "" + imgData.Mrn;
			annoForm.MdiParent = this;
			if (GODS.GODSMain.ActiveAnnoForm != null)
			{
				Point loc = GODS.GODSMain.ActiveAnnoForm.Location;
				annoForm.Location = new Point(loc.X + 20, loc.Y + 20);
			}
			else
			{
				//annoForm.Location = new Point(Screen.GetBounds(Bounds).Width/3 , Screen.GetBounds(Bounds).Height/9);
				annoForm.Location = new Point(annoForm.Location.X + this.markForm.Width+10, annoForm.Location.Y);
			}
			this.setActiveAnnoForm(annoForm);
			return annoForm;
		}

		private string copyOriginalImage(string src)
		{
			string dir = System.IO.Directory.GetParent(src).FullName;
			string file = src.Remove(0, dir.Length+1);
			string dest = GODS.GODSMain.ImageDir + @"\" + GODS.GODSMain.origImgFolder + file;
			if (!System.IO.File.Exists(dest))
				System.IO.File.Copy(src, dest, false);
			return dest;
		}

		private void showMFormMItem_Click(object sender, System.EventArgs e)
		{
			if (this.showMarkForm) 
			{
				this.markFormLocation = this.markForm.Location;
				this.markForm.Hide();
				this.showMFormMItem.Text = "Show marks";
				this.showMarkForm = false;
			}
			else
			{
				this.markForm.Show();
				this.markForm.Location = this.markFormLocation;
				this.showMFormMItem.Text = "Hide marks";
				this.showMarkForm = true;
			}
		}

		private void prefMItem_Click(object sender, System.EventArgs e)
		{
			(new PreferenceDlg(GODS.GODSMain.showSaveConfirmDlg, GODS.GODSMain.DefaultImagePath)).ShowDialog(this);
		}

		private void exitMItem_Click(object sender, System.EventArgs e)
		{
			this.Close(); // Will trigger GODSMain_Closing()
		}

		private void GODSMain_Closing(object sender, CancelEventArgs e)
		{
			// Implicitly closing all its mdichildren before closing itself.
			// If one of the mdichild cancel the closing, the e.Cancel == true
			if (!e.Cancel) 
			{
				config.SaveConfig();
				Application.Exit();
			}	
		}

	
		private void markConfigMItem_Click(object sender, System.EventArgs e)
		{
			//want markConfig form to show what's DB
			//if(GODS.GODSMain.markConfigForm == null)
			//{
				GODS.GODSMain.markConfigForm = new MarkSetConfiguration();
			//}
			GODS.GODSMain.markConfigForm.ShowDialog();
		}

		public void reloadMarkForm()
		{
			GODS.GODSMain.marksetHandler.loadAllCategories();
			loadCategories();
			
		}
		public void updateMarkForm(int markSetID, ArrayList marks)
		{
			// change the category and mark set if different
			if (GODS.GODSMain.currMarkSet != null)
			{
				if (GODS.GODSMain.currMarkSet.MarkSetID == markSetID) 
				{
					this.markForm.loadMarksetWithID(markSetID);
					this.markForm.updateMarkForm(GODS.GODSMain.currMarkSet, marks);
				}
				else
				{
					MarkSet ms = null;
					// will make ms point to the target markset if found
					if ((ms = this.findMarkset(markSetID)) != null) 
					{
						this.cBxCategory.SelectedIndex = this.categories.IndexOf(ms.Category); // changes GODS.GODSMain.currCategory too
						this.markForm.updateMarkForm(ms, marks);
					}
				}
			}
		}

		private MarkSet findMarkset(int markSetID)
		{
			MarkSet ms = null;
			foreach (MarkCategory cat in this.categories)
			{
				if ((ms = cat.getMarkSet(markSetID)) != null) 
				{
					return ms;
				}
			}
			return null;
		}

		private void cBxCategory_SelectedIndexChanged(object sender, System.EventArgs e)
		{
			GODS.GODSMain.currCategory = (MarkCategory) this.cBxCategory.SelectedItem;
			this.markForm.loadMarkset(0);
			GODS.GODSMain.currMarkSet = (MarkSet) GODS.GODSMain.currCategory.Marksets[0];
		}

		private void refreshMFormMItem_Click(object sender, System.EventArgs e)
		{
			this.reloadMarkForm();
		}

//		private void btnSearch_Click(object sender, System.EventArgs e)
//		{
//			this.searchForm.ShowDialog();
//		}

		private void abtMItem_Click(object sender, System.EventArgs e)
		{
			MessageBox.Show(this,
				"GODS 2.0 Alpha" +"\n" +
				"Copyright c 2005 GODS Team at UMass Boston. All rights reserved.\n\n"+
				"Contact\t: gods@cs.umb.edu\n" +
				"WWW\t: http://gods.sourceforge.net",
				"About GODS");
		}

		private void manMItem_Click(object sender, System.EventArgs e)
		{
			//Help.ShowHelp(this, GODSMain.ExecDir + "gods2hlp.chm");
			string helpfile = GODSMain.ExecDir+"gods2.hlp";
			Help.ShowHelp(this,helpfile);
		}

		private void saveMItem_Click(object sender, System.EventArgs e)
		{
		
		}
	}
}
