// Copyright(C) 2003 Daisuke Arai <darai@users.sourceforge.jp>
// Copyright(C) 2004-2008, 2010 panacoran <panacoran@users.sourceforge.jp>
// 
// This program is part of Protra.
//
// Protra 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 3 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, see <http://www.gnu.org/licenses/>.
// 
// $Id: MainForm.cs 283 2010-03-05 22:15:12Z panacoran $

using System;
using System.Drawing;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using System.Xml;
using Protra.Controls;
using Protra.Dialogs;
using Protra.Lib;
using Protra.Lib.Controls;
using Protra.Lib.Db;
using Protra.Lib.Dialogs;

namespace Protra
{
    /// <summary>
    /// アプリケーションのメインフォームです。
    /// </summary>
    public class MainForm : System.Windows.Forms.Form
    {
        /// <summary>
        /// 最前面のウィンドウをセットします。
        /// </summary>
        [DllImport("user32.dll")]
        private static extern int SetForegroundWindow(int hwnd);

        /// <summary>
        /// オプション
        /// </summary>
        private Option option = new Option();
        /// <summary>
        /// 通常のサイズ
        /// </summary>
        private Rectangle normalBounds;

        private System.Windows.Forms.MainMenu mainMenu;
        private System.Windows.Forms.MenuItem menuItemData;
        private System.Windows.Forms.MenuItem menuItemPriceUpdate;
        private System.Windows.Forms.MenuItem menuItemPriceDelete;
        private System.Windows.Forms.MenuItem menuItemChart;
        private System.Windows.Forms.MenuItem menuItemAddFavoriteBrand;
        private System.Windows.Forms.MenuItem menuItemChartSep1;
        private System.Windows.Forms.MenuItem menuItemDailyChart;
        private System.Windows.Forms.MenuItem menuItemWeeklyChart;
        private System.Windows.Forms.MenuItem menuItemTool;
        private System.Windows.Forms.MenuItem menuItemPtSim;
        private System.Windows.Forms.MenuItem menuItemToolSep1;
        private System.Windows.Forms.MenuItem menuItemOption;
        private System.Windows.Forms.MenuItem menuItemHelp;
        private System.Windows.Forms.MenuItem menuItemMan;
        private System.Windows.Forms.MenuItem menuItemVersion;
        private System.Windows.Forms.Panel panelLeft;
        private System.Windows.Forms.TabControl tabControlBrand;
        private System.Windows.Forms.TabPage tabPageBrand;
        private System.Windows.Forms.TabPage tabPageFavoriteBrand;
        private Protra.Controls.BrandTreeView treeViewBrand;
        private System.Windows.Forms.ListBox listBoxFavoriteBrand;
        private System.Windows.Forms.ListView listViewPriceInfo;
        private System.Windows.Forms.ColumnHeader columnHeader1;
        private System.Windows.Forms.ColumnHeader columnHeader2;
        private System.Windows.Forms.Splitter splitterPanelAndChart;
        private System.Windows.Forms.Splitter splitterBrandAndInfo;
        private Protra.Controls.ChartPanel chartPanel;
        private System.Windows.Forms.ToolBar toolBar;
        private System.Windows.Forms.ToolBarButton toolBarButtonPriceUpdate;
        private System.Windows.Forms.ToolBarButton toolBarButtonSep1;
        private System.Windows.Forms.ToolBarButton toolBarButtonDailyChart;
        private System.Windows.Forms.ToolBarButton toolBarButtonWeeklyChart;
        private System.Windows.Forms.ToolBarButton toolBarSep2;
        private System.Windows.Forms.ToolBarButton toolBarButtonPtSim;
        private System.Windows.Forms.ToolBarButton toolBarSep3;
        private System.Windows.Forms.ImageList imageListToolBar;
        private System.Windows.Forms.HScrollBar hScrollBarChart;
        private System.Windows.Forms.TextBox textBoxCode;
        private System.Windows.Forms.Button buttonSearch;
        private System.Windows.Forms.Label labelCode;

        /// <summary>
        /// 必要なデザイナ変数です。
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// コンストラクタ
        /// </summary>
        public MainForm()
        {
            //
            // Windows フォーム デザイナ サポートに必要です。
            //
            InitializeComponent();

            //
            // チャートパネルの初期化。
            //
            chartPanel.HScrollBar = hScrollBarChart;
            chartPanel.ChartNum = option.ChartNum;
            chartPanel.ChartForeColor = option.ChartForeColor;
            chartPanel.ChartBackColor = option.ChartBackColor;
            chartPanel.UseDifferentChart = option.UseDifferentChart;
            chartPanel.DrawLastWeek = option.DrawLastWeek;
        }

        /// <summary>
        /// 使用されているリソースに後処理を実行します。
        /// </summary>
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (components != null)
                {
                    components.Dispose();
                }
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code
        /// <summary>
        /// デザイナ サポートに必要なメソッドです。このメソッドの内容を
        /// コード エディタで変更しないでください。
        /// </summary>
        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm));
            this.splitterPanelAndChart = new System.Windows.Forms.Splitter();
            this.mainMenu = new System.Windows.Forms.MainMenu(this.components);
            this.menuItemData = new System.Windows.Forms.MenuItem();
            this.menuItemPriceUpdate = new System.Windows.Forms.MenuItem();
            this.menuItemPriceDelete = new System.Windows.Forms.MenuItem();
            this.menuItemChart = new System.Windows.Forms.MenuItem();
            this.menuItemAddFavoriteBrand = new System.Windows.Forms.MenuItem();
            this.menuItemChartSep1 = new System.Windows.Forms.MenuItem();
            this.menuItemDailyChart = new System.Windows.Forms.MenuItem();
            this.menuItemWeeklyChart = new System.Windows.Forms.MenuItem();
            this.menuItemTool = new System.Windows.Forms.MenuItem();
            this.menuItemPtSim = new System.Windows.Forms.MenuItem();
            this.menuItemToolSep1 = new System.Windows.Forms.MenuItem();
            this.menuItemOption = new System.Windows.Forms.MenuItem();
            this.menuItemHelp = new System.Windows.Forms.MenuItem();
            this.menuItemMan = new System.Windows.Forms.MenuItem();
            this.menuItemVersion = new System.Windows.Forms.MenuItem();
            this.panelLeft = new System.Windows.Forms.Panel();
            this.tabControlBrand = new System.Windows.Forms.TabControl();
            this.tabPageBrand = new System.Windows.Forms.TabPage();
            this.treeViewBrand = new Protra.Controls.BrandTreeView();
            this.tabPageFavoriteBrand = new System.Windows.Forms.TabPage();
            this.listBoxFavoriteBrand = new System.Windows.Forms.ListBox();
            this.splitterBrandAndInfo = new System.Windows.Forms.Splitter();
            this.listViewPriceInfo = new System.Windows.Forms.ListView();
            this.columnHeader1 = new System.Windows.Forms.ColumnHeader();
            this.columnHeader2 = new System.Windows.Forms.ColumnHeader();
            this.toolBar = new System.Windows.Forms.ToolBar();
            this.toolBarButtonPriceUpdate = new System.Windows.Forms.ToolBarButton();
            this.toolBarButtonSep1 = new System.Windows.Forms.ToolBarButton();
            this.toolBarButtonDailyChart = new System.Windows.Forms.ToolBarButton();
            this.toolBarButtonWeeklyChart = new System.Windows.Forms.ToolBarButton();
            this.toolBarSep2 = new System.Windows.Forms.ToolBarButton();
            this.toolBarButtonPtSim = new System.Windows.Forms.ToolBarButton();
            this.toolBarSep3 = new System.Windows.Forms.ToolBarButton();
            this.imageListToolBar = new System.Windows.Forms.ImageList(this.components);
            this.chartPanel = new Protra.Controls.ChartPanel();
            this.hScrollBarChart = new System.Windows.Forms.HScrollBar();
            this.labelCode = new System.Windows.Forms.Label();
            this.textBoxCode = new System.Windows.Forms.TextBox();
            this.buttonSearch = new System.Windows.Forms.Button();
            this.panelLeft.SuspendLayout();
            this.tabControlBrand.SuspendLayout();
            this.tabPageBrand.SuspendLayout();
            this.tabPageFavoriteBrand.SuspendLayout();
            this.SuspendLayout();
            // 
            // splitterPanelAndChart
            // 
            this.splitterPanelAndChart.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
            this.splitterPanelAndChart.Location = new System.Drawing.Point(180, 28);
            this.splitterPanelAndChart.Name = "splitterPanelAndChart";
            this.splitterPanelAndChart.Size = new System.Drawing.Size(3, 499);
            this.splitterPanelAndChart.TabIndex = 3;
            this.splitterPanelAndChart.TabStop = false;
            // 
            // mainMenu
            // 
            this.mainMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
            this.menuItemData,
            this.menuItemChart,
            this.menuItemTool,
            this.menuItemHelp});
            // 
            // menuItemData
            // 
            this.menuItemData.Index = 0;
            this.menuItemData.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
            this.menuItemPriceUpdate,
            this.menuItemPriceDelete});
            this.menuItemData.Text = "データ(&D)";
            // 
            // menuItemPriceUpdate
            // 
            this.menuItemPriceUpdate.Index = 0;
            this.menuItemPriceUpdate.Shortcut = System.Windows.Forms.Shortcut.CtrlU;
            this.menuItemPriceUpdate.Text = "株価データ更新(&U)";
            this.menuItemPriceUpdate.Click += new System.EventHandler(this.menuItemPriceUpdate_Click);
            // 
            // menuItemPriceDelete
            // 
            this.menuItemPriceDelete.Index = 1;
            this.menuItemPriceDelete.Text = "株価データを削除(&D)...";
            this.menuItemPriceDelete.Click += new System.EventHandler(this.menuItemPriceDelete_Click);
            // 
            // menuItemChart
            // 
            this.menuItemChart.Index = 1;
            this.menuItemChart.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
            this.menuItemAddFavoriteBrand,
            this.menuItemChartSep1,
            this.menuItemDailyChart,
            this.menuItemWeeklyChart});
            this.menuItemChart.Text = "チャート(&C)";
            // 
            // menuItemAddFavoriteBrand
            // 
            this.menuItemAddFavoriteBrand.Index = 0;
            this.menuItemAddFavoriteBrand.Shortcut = System.Windows.Forms.Shortcut.CtrlA;
            this.menuItemAddFavoriteBrand.Text = "お気に入りに追加(&A)";
            this.menuItemAddFavoriteBrand.Click += new System.EventHandler(this.menuItemAddFavoriteBrand_Click);
            // 
            // menuItemChartSep1
            // 
            this.menuItemChartSep1.Index = 1;
            this.menuItemChartSep1.Text = "-";
            // 
            // menuItemDailyChart
            // 
            this.menuItemDailyChart.Checked = true;
            this.menuItemDailyChart.Index = 2;
            this.menuItemDailyChart.RadioCheck = true;
            this.menuItemDailyChart.Shortcut = System.Windows.Forms.Shortcut.CtrlD;
            this.menuItemDailyChart.Text = "日足(&D)";
            this.menuItemDailyChart.Click += new System.EventHandler(this.menuItemDailyChart_Click);
            // 
            // menuItemWeeklyChart
            // 
            this.menuItemWeeklyChart.Index = 3;
            this.menuItemWeeklyChart.RadioCheck = true;
            this.menuItemWeeklyChart.Shortcut = System.Windows.Forms.Shortcut.CtrlW;
            this.menuItemWeeklyChart.Text = "週足(&W)";
            this.menuItemWeeklyChart.Click += new System.EventHandler(this.menuItemWeeklyChart_Click);
            // 
            // menuItemTool
            // 
            this.menuItemTool.Index = 2;
            this.menuItemTool.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
            this.menuItemPtSim,
            this.menuItemToolSep1,
            this.menuItemOption});
            this.menuItemTool.Text = "ツール(&T)";
            // 
            // menuItemPtSim
            // 
            this.menuItemPtSim.Index = 0;
            this.menuItemPtSim.Text = "PtSimの起動(&S)";
            this.menuItemPtSim.Click += new System.EventHandler(this.menuItemPtSim_Click);
            // 
            // menuItemToolSep1
            // 
            this.menuItemToolSep1.Index = 1;
            this.menuItemToolSep1.Text = "-";
            // 
            // menuItemOption
            // 
            this.menuItemOption.Index = 2;
            this.menuItemOption.Text = "オプション(&O)...";
            this.menuItemOption.Click += new System.EventHandler(this.menuItemOption_Click);
            // 
            // menuItemHelp
            // 
            this.menuItemHelp.Index = 3;
            this.menuItemHelp.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
            this.menuItemMan,
            this.menuItemVersion});
            this.menuItemHelp.Text = "ヘルプ(&H)";
            // 
            // menuItemMan
            // 
            this.menuItemMan.Index = 0;
            this.menuItemMan.Shortcut = System.Windows.Forms.Shortcut.F1;
            this.menuItemMan.Text = "マニュアル(&M)";
            this.menuItemMan.Click += new System.EventHandler(this.menuItemMan_Click);
            // 
            // menuItemVersion
            // 
            this.menuItemVersion.Index = 1;
            this.menuItemVersion.Text = "バージョン情報(&V)";
            this.menuItemVersion.Click += new System.EventHandler(this.menuItemVersion_Click);
            // 
            // panelLeft
            // 
            this.panelLeft.Controls.Add(this.tabControlBrand);
            this.panelLeft.Controls.Add(this.splitterBrandAndInfo);
            this.panelLeft.Controls.Add(this.listViewPriceInfo);
            this.panelLeft.Dock = System.Windows.Forms.DockStyle.Left;
            this.panelLeft.Location = new System.Drawing.Point(0, 28);
            this.panelLeft.Name = "panelLeft";
            this.panelLeft.Size = new System.Drawing.Size(180, 499);
            this.panelLeft.TabIndex = 1;
            // 
            // tabControlBrand
            // 
            this.tabControlBrand.Controls.Add(this.tabPageBrand);
            this.tabControlBrand.Controls.Add(this.tabPageFavoriteBrand);
            this.tabControlBrand.Dock = System.Windows.Forms.DockStyle.Fill;
            this.tabControlBrand.Location = new System.Drawing.Point(0, 0);
            this.tabControlBrand.Name = "tabControlBrand";
            this.tabControlBrand.SelectedIndex = 0;
            this.tabControlBrand.Size = new System.Drawing.Size(180, 360);
            this.tabControlBrand.TabIndex = 0;
            // 
            // tabPageBrand
            // 
            this.tabPageBrand.Controls.Add(this.treeViewBrand);
            this.tabPageBrand.Location = new System.Drawing.Point(4, 21);
            this.tabPageBrand.Name = "tabPageBrand";
            this.tabPageBrand.Size = new System.Drawing.Size(172, 335);
            this.tabPageBrand.TabIndex = 0;
            this.tabPageBrand.Text = "銘柄リスト";
            // 
            // treeViewBrand
            // 
            this.treeViewBrand.Dock = System.Windows.Forms.DockStyle.Fill;
            this.treeViewBrand.HideSelection = false;
            this.treeViewBrand.Location = new System.Drawing.Point(0, 0);
            this.treeViewBrand.Name = "treeViewBrand";
            this.treeViewBrand.Size = new System.Drawing.Size(172, 335);
            this.treeViewBrand.TabIndex = 0;
            this.treeViewBrand.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.treeViewBrand_AfterSelect);
            // 
            // tabPageFavoriteBrand
            // 
            this.tabPageFavoriteBrand.Controls.Add(this.listBoxFavoriteBrand);
            this.tabPageFavoriteBrand.Location = new System.Drawing.Point(4, 21);
            this.tabPageFavoriteBrand.Name = "tabPageFavoriteBrand";
            this.tabPageFavoriteBrand.Size = new System.Drawing.Size(172, 335);
            this.tabPageFavoriteBrand.TabIndex = 1;
            this.tabPageFavoriteBrand.Text = "お気に入り";
            // 
            // listBoxFavoriteBrand
            // 
            this.listBoxFavoriteBrand.Dock = System.Windows.Forms.DockStyle.Fill;
            this.listBoxFavoriteBrand.ItemHeight = 12;
            this.listBoxFavoriteBrand.Location = new System.Drawing.Point(0, 0);
            this.listBoxFavoriteBrand.Name = "listBoxFavoriteBrand";
            this.listBoxFavoriteBrand.Size = new System.Drawing.Size(172, 328);
            this.listBoxFavoriteBrand.Sorted = true;
            this.listBoxFavoriteBrand.TabIndex = 0;
            this.listBoxFavoriteBrand.SelectedIndexChanged += new System.EventHandler(this.listBoxFavoriteBrand_SelectedIndexChanged);
            this.listBoxFavoriteBrand.KeyDown += new System.Windows.Forms.KeyEventHandler(this.listBoxFavoriteBrand_KeyDown);
            // 
            // splitterBrandAndInfo
            // 
            this.splitterBrandAndInfo.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
            this.splitterBrandAndInfo.Dock = System.Windows.Forms.DockStyle.Bottom;
            this.splitterBrandAndInfo.Location = new System.Drawing.Point(0, 360);
            this.splitterBrandAndInfo.Name = "splitterBrandAndInfo";
            this.splitterBrandAndInfo.Size = new System.Drawing.Size(180, 3);
            this.splitterBrandAndInfo.TabIndex = 1;
            this.splitterBrandAndInfo.TabStop = false;
            // 
            // listViewPriceInfo
            // 
            this.listViewPriceInfo.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
            this.columnHeader1,
            this.columnHeader2});
            this.listViewPriceInfo.Dock = System.Windows.Forms.DockStyle.Bottom;
            this.listViewPriceInfo.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.None;
            this.listViewPriceInfo.Location = new System.Drawing.Point(0, 363);
            this.listViewPriceInfo.Name = "listViewPriceInfo";
            this.listViewPriceInfo.Size = new System.Drawing.Size(180, 136);
            this.listViewPriceInfo.TabIndex = 1;
            this.listViewPriceInfo.UseCompatibleStateImageBehavior = false;
            this.listViewPriceInfo.View = System.Windows.Forms.View.Details;
            // 
            // columnHeader2
            // 
            this.columnHeader2.Width = 100;
            // 
            // toolBar
            // 
            this.toolBar.Appearance = System.Windows.Forms.ToolBarAppearance.Flat;
            this.toolBar.Buttons.AddRange(new System.Windows.Forms.ToolBarButton[] {
            this.toolBarButtonPriceUpdate,
            this.toolBarButtonSep1,
            this.toolBarButtonDailyChart,
            this.toolBarButtonWeeklyChart,
            this.toolBarSep2,
            this.toolBarButtonPtSim,
            this.toolBarSep3});
            this.toolBar.DropDownArrows = true;
            this.toolBar.ImageList = this.imageListToolBar;
            this.toolBar.Location = new System.Drawing.Point(0, 0);
            this.toolBar.Name = "toolBar";
            this.toolBar.ShowToolTips = true;
            this.toolBar.Size = new System.Drawing.Size(790, 28);
            this.toolBar.TabIndex = 0;
            this.toolBar.ButtonClick += new System.Windows.Forms.ToolBarButtonClickEventHandler(this.toolBar_ButtonClick);
            // 
            // toolBarButtonPriceUpdate
            // 
            this.toolBarButtonPriceUpdate.ImageIndex = 0;
            this.toolBarButtonPriceUpdate.Name = "toolBarButtonPriceUpdate";
            this.toolBarButtonPriceUpdate.ToolTipText = "株価データ更新";
            // 
            // toolBarButtonSep1
            // 
            this.toolBarButtonSep1.Name = "toolBarButtonSep1";
            this.toolBarButtonSep1.Style = System.Windows.Forms.ToolBarButtonStyle.Separator;
            // 
            // toolBarButtonDailyChart
            // 
            this.toolBarButtonDailyChart.ImageIndex = 1;
            this.toolBarButtonDailyChart.Name = "toolBarButtonDailyChart";
            this.toolBarButtonDailyChart.Pushed = true;
            this.toolBarButtonDailyChart.ToolTipText = "日足";
            // 
            // toolBarButtonWeeklyChart
            // 
            this.toolBarButtonWeeklyChart.ImageIndex = 2;
            this.toolBarButtonWeeklyChart.Name = "toolBarButtonWeeklyChart";
            this.toolBarButtonWeeklyChart.ToolTipText = "週足";
            // 
            // toolBarSep2
            // 
            this.toolBarSep2.Name = "toolBarSep2";
            this.toolBarSep2.Style = System.Windows.Forms.ToolBarButtonStyle.Separator;
            // 
            // toolBarButtonPtSim
            // 
            this.toolBarButtonPtSim.ImageIndex = 3;
            this.toolBarButtonPtSim.Name = "toolBarButtonPtSim";
            this.toolBarButtonPtSim.ToolTipText = "PtSimの起動";
            // 
            // toolBarSep3
            // 
            this.toolBarSep3.Name = "toolBarSep3";
            this.toolBarSep3.Style = System.Windows.Forms.ToolBarButtonStyle.Separator;
            // 
            // imageListToolBar
            // 
            this.imageListToolBar.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageListToolBar.ImageStream")));
            this.imageListToolBar.TransparentColor = System.Drawing.Color.Transparent;
            this.imageListToolBar.Images.SetKeyName(0, "");
            this.imageListToolBar.Images.SetKeyName(1, "");
            this.imageListToolBar.Images.SetKeyName(2, "");
            this.imageListToolBar.Images.SetKeyName(3, "");
            // 
            // chartPanel
            // 
            this.chartPanel.Dock = System.Windows.Forms.DockStyle.Fill;
            this.chartPanel.Location = new System.Drawing.Point(183, 28);
            this.chartPanel.Name = "chartPanel";
            this.chartPanel.Size = new System.Drawing.Size(607, 484);
            this.chartPanel.TabIndex = 7;
            // 
            // hScrollBarChart
            // 
            this.hScrollBarChart.Dock = System.Windows.Forms.DockStyle.Bottom;
            this.hScrollBarChart.Enabled = false;
            this.hScrollBarChart.Location = new System.Drawing.Point(183, 512);
            this.hScrollBarChart.Name = "hScrollBarChart";
            this.hScrollBarChart.Size = new System.Drawing.Size(607, 15);
            this.hScrollBarChart.TabIndex = 8;
            // 
            // labelCode
            // 
            this.labelCode.Location = new System.Drawing.Point(116, 8);
            this.labelCode.Name = "labelCode";
            this.labelCode.Size = new System.Drawing.Size(76, 16);
            this.labelCode.TabIndex = 3;
            this.labelCode.Text = "コード/銘柄名";
            // 
            // textBoxCode
            // 
            this.textBoxCode.Location = new System.Drawing.Point(192, 4);
            this.textBoxCode.Name = "textBoxCode";
            this.textBoxCode.Size = new System.Drawing.Size(72, 19);
            this.textBoxCode.TabIndex = 4;
            this.textBoxCode.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.textBoxCode_KeyPress);
            // 
            // buttonSearch
            // 
            this.buttonSearch.FlatStyle = System.Windows.Forms.FlatStyle.Popup;
            this.buttonSearch.Image = ((System.Drawing.Image)(resources.GetObject("buttonSearch.Image")));
            this.buttonSearch.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
            this.buttonSearch.Location = new System.Drawing.Point(268, 4);
            this.buttonSearch.Name = "buttonSearch";
            this.buttonSearch.Size = new System.Drawing.Size(56, 20);
            this.buttonSearch.TabIndex = 5;
            this.buttonSearch.Text = "検索";
            this.buttonSearch.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            this.buttonSearch.Click += new System.EventHandler(this.buttonSearch_Click);
            // 
            // MainForm
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 12);
            this.ClientSize = new System.Drawing.Size(790, 527);
            this.Controls.Add(this.buttonSearch);
            this.Controls.Add(this.textBoxCode);
            this.Controls.Add(this.labelCode);
            this.Controls.Add(this.chartPanel);
            this.Controls.Add(this.hScrollBarChart);
            this.Controls.Add(this.splitterPanelAndChart);
            this.Controls.Add(this.panelLeft);
            this.Controls.Add(this.toolBar);
            this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
            this.Menu = this.mainMenu;
            this.Name = "MainForm";
            this.Text = "Protra";
            this.Load += new System.EventHandler(this.MainForm_Load);
            this.SizeChanged += new System.EventHandler(this.MainForm_SizeChanged);
            this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.MainForm_FormClosing);
            this.LocationChanged += new System.EventHandler(this.MainForm_LocationChanged);
            this.panelLeft.ResumeLayout(false);
            this.tabControlBrand.ResumeLayout(false);
            this.tabPageBrand.ResumeLayout(false);
            this.tabPageFavoriteBrand.ResumeLayout(false);
            this.ResumeLayout(false);
            this.PerformLayout();

        }
        #endregion

        /// <summary>
        /// 環境設定ファイルを読み込みます。
        /// </summary>
        private void EnvRead()
        {
            ConfigFile configFile = new ConfigFile("ptenv");
            try
            {
                configFile.Read();
            }
            catch
            {
                return;
            }
            try
            {
                // フォーム
                this.Width = int.Parse(configFile["Width"]);
                this.Height = int.Parse(configFile["Height"]);
                if (bool.Parse(configFile["Maximized"]))
                    this.WindowState = FormWindowState.Maximized;
                this.panelLeft.Width = int.Parse(configFile["PanelLeftWidth"]);
                this.listViewPriceInfo.Height =
                    int.Parse(configFile["TextBoxPriceInfoHeight"]);
                // チャート
                for (int i = 0; i < option.ChartNum; i++)
                {
                    if (configFile["ChartHeight" + i.ToString()] == null)
                        continue;
                    chartPanel.ChartBoxes[i].Height =
                        int.Parse(configFile["ChartHeight" + i.ToString()]);
                    if (configFile["ChartFile" + i.ToString()] == null)
                        continue;
                    chartPanel.ChartBoxes[i].DailyProgramFile =
                        Path.Combine(Global.DirChart, configFile["ChartFile" + i.ToString()]);
                    string weeklyFile = configFile["WeeklyChartFile" + i.ToString()];
                    if (weeklyFile != null)
                        chartPanel.ChartBoxes[i].WeeklyProgramFile =
                            Path.Combine(Global.DirChart, weeklyFile);
                }
                if (int.Parse(configFile["ChartMode"]) == 1)
                    this.menuItemWeeklyChart.PerformClick();
                // お気に入り
                for (int i = 0; ; i++)
                {
                    string val = configFile["FavoriteBrandId" + i.ToString()];
                    if (val == null)
                        break;
                    Brand brand = BrandTable.GetRecord(int.Parse(val));
                    if (brand != null)
                        this.listBoxFavoriteBrand.Items.Add(new FavoriteBrandItem(brand));
                }
            }
            catch {
                using (var dialog = new ApplicationError()) {
                    dialog.ErrorMessage = "設定ファイルが壊れています:\n" + configFile.Filename;
                    dialog.ShowDialog();
                }
            }
        }

        private string StripChartDirName(string path)
        {
            if (path == null)
                return null;
            return path.Substring(Global.DirChart.Length + 1, path.Length - Global.DirChart.Length - 1);
        }

        /// <summary>
        /// 環境設定ファイルを書き込みます。
        /// </summary>
        private void EnvWrite()
        {
            ConfigFile configFile = new ConfigFile("ptenv");
            // フォーム
            configFile["Width"] = normalBounds.Width.ToString();
            configFile["Height"] = normalBounds.Height.ToString();
            configFile["Maximized"] =
                (this.WindowState == FormWindowState.Maximized).ToString();
            configFile["PanelLeftWidth"] = this.panelLeft.Width.ToString();
            configFile["TextBoxPriceInfoHeight"] = this.listViewPriceInfo.Height.ToString();
            // チャート
            int mode = this.menuItemDailyChart.Checked ? 0 : 1;
            configFile["ChartMode"] = mode.ToString();
            for (int i = 0; i < option.ChartNum; i++)
            {
                configFile["ChartFile" + i.ToString()] =
                    StripChartDirName(chartPanel.ChartBoxes[i].DailyProgramFile);
                configFile["WeeklyChartFile" + i.ToString()] =
                    StripChartDirName(chartPanel.ChartBoxes[i].WeeklyProgramFile);
                configFile["ChartHeight" + i.ToString()] = chartPanel.ChartBoxes[i].Height.ToString();
            }
            // お気に入り
            int num = 0;
            foreach (FavoriteBrandItem item in this.listBoxFavoriteBrand.Items)
                configFile["FavoriteBrandId" + num++.ToString()] = item.Brand.Id.ToString();
            configFile.Write();
        }

        /// <summary>
        /// 株価情報をセットします。
        /// </summary>
        /// <param name="prices">株価データ</param>
        private void SetListViewPriceInfo(Price[] prices)
        {
            if (prices == null || prices.Length == 0)
            {
                this.listViewPriceInfo.Items.Clear();
                return;
            }

            Price p = prices[prices.Length - 1];
            ListViewItem[] items = new ListViewItem[9];
            items[0] = new ListViewItem(new string[] { "コード", p.Brand.Code.ToString() });
            items[1] = new ListViewItem(new string[] { "市場", p.Brand.Market.Name });
            items[2] = new ListViewItem(new string[] { "銘柄名", p.Brand.Name });
            items[3] = new ListViewItem(new string[] { "日付", p.Date.ToString("yyyy/MM/dd") });
            items[4] = new ListViewItem(new string[] { "始値", p.Open.ToString() });
            items[5] = new ListViewItem(new string[] { "高値", p.High.ToString() });
            items[6] = new ListViewItem(new string[] { "安値", p.Low.ToString() });
            items[7] = new ListViewItem(new string[] { "終値", p.Close.ToString() });
            items[8] = new ListViewItem(new string[] { "出来高", p.Volume.ToString() });
            this.listViewPriceInfo.Items.Clear();
            this.listViewPriceInfo.Items.AddRange(items);
        }

        /// <summary>
        /// アプリケーションのメイン エントリ ポイントです。
        /// </summary>
        [STAThread]
        static void Main()
        {
            Process cps = Process.GetCurrentProcess();
            Process[] ps = Process.GetProcessesByName(cps.ProcessName);
            if (ps.Length > 1)
            {
                int i = 0;
                if (ps[0].Id == cps.Id)
                    i = 1;
                SetForegroundWindow(ps[i].MainWindowHandle.ToInt32());
                return;
            }

            Application.Run(new MainForm());
        }

        private void MainForm_Load(object sender, System.EventArgs e)
        {
            this.treeViewBrand.Initialize();

            // 初期サイズの保存
            normalBounds = this.Bounds;

            // 環境設定ファイルの読み込み
            EnvRead();
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            EnvWrite();
        }

        private void MainForm_LocationChanged(object sender, System.EventArgs e)
        {
            // 通常の状態ならサイズを保存
            if (this.WindowState == FormWindowState.Normal)
                normalBounds = this.Bounds;
        }

        private void MainForm_SizeChanged(object sender, System.EventArgs e)
        {
            // 通常の状態ならサイズを保存
            if (this.WindowState == FormWindowState.Normal)
                normalBounds = this.Bounds;
        }

        private void menuItemSearchedBrand_Click(object sender, System.EventArgs e)
        {
            MenuItemWithObject menuItem = (MenuItemWithObject)sender;
            Brand brand = (Brand)menuItem.Object;
            listBoxFavoriteBrand.SelectedItem = null;
            treeViewBrand.SelectedNode = null;
            chartPanel.SelectedBrand = brand;
            SetListViewPriceInfo(chartPanel.Prices);
        }

        private void menuItemPriceUpdate_Click(object sender, System.EventArgs e)
        {
            PriceUpdateDialog updateDialog = new PriceUpdateDialog(option);
            updateDialog.ShowDialog();

            if (chartPanel.SelectedBrand != null)
            {
                chartPanel.UpdatePrices();
                SetListViewPriceInfo(chartPanel.Prices);
            }
            else
                this.treeViewBrand.Initialize();
        }

        private void menuItemPriceDelete_Click(object sender, System.EventArgs e)
        {
            InputDateDialog dialog = new InputDateDialog();
            dialog.Message = "指定した日付以降のデータを削除します。";
            dialog.Value = PriceTable.MaxDate();
            dialog.ShowDialog();
            if (dialog.DialogResult != DialogResult.OK)
                return;
            this.Cursor = Cursors.WaitCursor;
            Application.DoEvents();
            PriceTable.Delete(dialog.Value);
            this.Cursor = Cursors.Default;
            chartPanel.UpdatePrices();
            SetListViewPriceInfo(chartPanel.Prices);
        }

        private void menuItemDailyChart_Click(object sender, System.EventArgs e)
        {
            this.menuItemDailyChart.Checked = true;
            this.menuItemWeeklyChart.Checked = false;
            this.toolBarButtonDailyChart.Pushed = true;
            this.toolBarButtonWeeklyChart.Pushed = false;
            chartPanel.ChartMode = 0;
            SetListViewPriceInfo(chartPanel.Prices);
        }

        private void menuItemWeeklyChart_Click(object sender, System.EventArgs e)
        {
            this.menuItemDailyChart.Checked = false;
            this.menuItemWeeklyChart.Checked = true;
            this.toolBarButtonDailyChart.Pushed = false;
            this.toolBarButtonWeeklyChart.Pushed = true;
            chartPanel.ChartMode = 1;
            SetListViewPriceInfo(chartPanel.Prices);
        }

        private void menuItemAddFavoriteBrand_Click(object sender, System.EventArgs e)
        {
            object item = new FavoriteBrandItem(chartPanel.SelectedBrand);
            if (!this.listBoxFavoriteBrand.Items.Contains(item))
                this.listBoxFavoriteBrand.Items.Add(item);
        }

        private void menuItemPtSim_Click(object sender, System.EventArgs e)
        {
            string path = Path.Combine(Global.DirApp, "PtSim.exe");
            Process.Start(path);
        }

        private void menuItemOption_Click(object sender, System.EventArgs e)
        {
            Form dialog = new OptionDialog(option);
            DialogResult result = dialog.ShowDialog(this);
            if (result == DialogResult.OK)
            {
                chartPanel.ChartNum = option.ChartNum;
                chartPanel.ChartForeColor = option.ChartForeColor;
                chartPanel.ChartBackColor = option.ChartBackColor;
                chartPanel.DrawLastWeek = option.DrawLastWeek;
                chartPanel.UseDifferentChart = option.UseDifferentChart;
            }
        }

        private void menuItemMan_Click(object sender, System.EventArgs e)
        {
            Process.Start(Global.PathMan);
        }

        private void menuItemVersion_Click(object sender, System.EventArgs e)
        {
            Form dialog = new VersionDialog();
            dialog.ShowDialog(this);
        }

        private void toolBar_ButtonClick(object sender, System.Windows.Forms.ToolBarButtonClickEventArgs e)
        {
            if (e.Button == this.toolBarButtonPriceUpdate)
                this.menuItemPriceUpdate.PerformClick();
            else if (e.Button == this.toolBarButtonDailyChart)
                this.menuItemDailyChart.PerformClick();
            else if (e.Button == this.toolBarButtonWeeklyChart)
                this.menuItemWeeklyChart.PerformClick();
            else if (e.Button == this.toolBarButtonPtSim)
                this.menuItemPtSim.PerformClick();
        }

        private void treeViewBrand_AfterSelect(object sender, System.Windows.Forms.TreeViewEventArgs e)
        {
            Brand brand = this.treeViewBrand.SelectedBrand;
            if (brand != null)
            {
                listBoxFavoriteBrand.SelectedItem = null;
                chartPanel.SelectedBrand = brand;
                SetListViewPriceInfo(chartPanel.Prices);
            }
        }

        private void listBoxFavoriteBrand_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
        {
            int index = this.listBoxFavoriteBrand.SelectedIndex;
            if (e.KeyData == Keys.Delete && index != -1)
            {
                this.listBoxFavoriteBrand.Items.RemoveAt(index);
                if (index < this.listBoxFavoriteBrand.Items.Count)
                    this.listBoxFavoriteBrand.SelectedIndex = index;
                else if (this.listBoxFavoriteBrand.Items.Count > 0)
                    this.listBoxFavoriteBrand.SelectedIndex = index - 1;
            }
        }

        private void listBoxFavoriteBrand_SelectedIndexChanged(object sender, System.EventArgs e)
        {
            treeViewBrand.SelectedNode = null;
            object item = this.listBoxFavoriteBrand.SelectedItem;
            if (item == null)
            {
                chartPanel.SelectedBrand = null;
                SetListViewPriceInfo(null);
                return;
            }
            Brand brand = ((FavoriteBrandItem)item).Brand;
            chartPanel.SelectedBrand = brand;
            SetListViewPriceInfo(chartPanel.Prices);
        }

        private void buttonSearch_Click(object sender, System.EventArgs e)
        {
            if (textBoxCode.Text == "")
                return;
            Brand[] brands;
            try
            {
                brands = BrandTable.GetRecords(int.Parse(textBoxCode.Text));
            }
            catch (FormatException)
            {

                brands = BrandTable.GetRecords(textBoxCode.Text);
            }
            ContextMenu contextMenu = new ContextMenu();
            foreach (Brand brand in brands)
            {
                MenuItemWithObject menuItem = new MenuItemWithObject();
                menuItem.Text = brand.Market.Name + " " + brand.Code + " " + brand.Name;
                menuItem.Object = brand;
                menuItem.Click += new EventHandler(menuItemSearchedBrand_Click);
                contextMenu.MenuItems.Add(menuItem);
            }
            contextMenu.Show(this.buttonSearch, new Point(0, this.buttonSearch.Height));
        }

        private void textBoxCode_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13)
            {
                buttonSearch_Click(sender, new EventArgs());
                e.Handled = true;
            }
        }
    }
}
