using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Reflection;
using DotSpatial.Data;
using System.Xml;
using System.IO;

namespace SMAT_CE
{
    public partial class Main : FormBase
    {
        private string _baseFormTitle = "";

        public Main()
        {
            try
            {
                InitializeComponent();
                Language.Localization.Load(this, Language.Localization.CurrentLanguage);

                if (Language.Localization.CurrentLanguage == "en")
                    this.englishToolStripMenuItem.Checked = true;
                else
                    this.chineseToolStripMenuItem.Checked = true;

                _baseFormTitle = AssemblyTitle;
                //_baseFormTitle = this.Text + " " + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString().Substring(0, 4);//Version:0.20
                bool showOnlyChina= System.Configuration.ConfigurationManager.AppSettings["ShowOnlyChina"] == "T";
                if (showOnlyChina)
                {
                    tsmiUSA.Visible = !showOnlyChina;
                }
                if (LanguageOld.IsSMATChina || Language.Localization.CurrentLanguage == "zh"|| showOnlyChina)
                {
                    this.Text = "SMAT-China " + CommonClass.versionSMATChina;
                    tsbtnLanguage.Text = "China";
                    LanguageOld.IsSMATChina = true;                  
                }
                else
                {
                    this.Text = "SMAT-CE " + CommonClass.VersionNumber;//AssemblyTitle
                }
                //XmlDocument doc = new XmlDocument();
                //doc.Load(Application.ExecutablePath + ".config");
                bool includeChina = false;
                bool includeTaiwan = false;
                bool includeSSIA = false;
                bool includeLanguage = false;
                //XmlNode node = doc.SelectSingleNode(@"//add[@key='IncludeChina']");
                //if (node != null)
                //{
                //    XmlElement ele = (XmlElement)node;
                //    ele = (XmlElement)node;
                //    string isShow = ele.GetAttribute("value");
                //    includeChina = isShow == "T" ? true : false;
                //}
                //node = doc.SelectSingleNode(@"//add[@key='IncludeTaiwan']");
                //if (node != null)
                //{
                //    XmlElement ele = (XmlElement)node;
                //    ele = (XmlElement)node;
                //    string isShow = ele.GetAttribute("value");
                //    includeTaiwan = isShow == "T" ? true : false;
                //}
                //node = doc.SelectSingleNode(@"//add[@key='ShowSSIA']");
                //if (node != null)
                //{
                //    XmlElement ele = (XmlElement)node;
                //    ele = (XmlElement)node;
                //    string isShow = ele.GetAttribute("value");
                //    this.tsbtnSingleAssessment.Visible = isShow == "T" ? true : false;
                //}
                string strPath = "";
                initConfig(ref includeChina, ref includeTaiwan, ref includeSSIA, ref strPath, ref includeLanguage);
                //BetaVersion，需要隐藏SSIA module
                this.tsbtnSingleAssessment.Visible = !CommonClass.BetaVersion && includeSSIA&&!LanguageOld.IsSMATChina;//== "T" ? true : false;
                this.tsbtnLanguage.Visible = (includeChina || includeTaiwan);
                this.tsmiChina.Visible = includeChina;
                this.tsmiTaiwan.Visible = includeTaiwan;
                this.toolStripButton1.Visible = includeLanguage;
                tsbtnBenMAP.Visible = !CommonClass.BetaVersion;//BetaVersion，需要隐藏BenMAP module
                tsbtnLanguage.Visible = !CommonClass.BetaVersion;//BetaVersion，需要隐藏China case
                tsmiOptions.Visible = !CommonClass.BetaVersion;
                if (Language.Localization.CurrentLanguage == "zh")
                {
                    tsbtnSingleAssessment.Visible = false;
                    tsmiDailyPM.Visible = false;
                    tsmiVisibility.Visible = false;
                    tsbtnBenMAP.Visible = false;
                    this.Size = new Size(1024,768);
                }
            }
            catch (Exception ex)
            {
                CommonClass.LogError(ex);
            }

        }

        #region AssemblyTitle
        public string AssemblyTitle
        {
            get
            {
                object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyTitleAttribute), false);
                if (attributes.Length > 0)
                {
                    AssemblyTitleAttribute titleAttribute = (AssemblyTitleAttribute)attributes[0];
                    if (titleAttribute.Title != "")
                    {
                        return titleAttribute.Title;
                    }
                }
                return System.IO.Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().CodeBase);
            }
        }
        #endregion

        //实例化
        ConfigurationManagement cfg = new ConfigurationManagement();

        /// <summary>
        /// 当前打开的工程
        /// </summary>
        private Form _currentForm = null;
        private void initConfig(ref bool isIncludeChina, ref bool isIncludeTaiWan, ref bool isShowSSIA, ref string strBenMAPPath,ref bool isShowLanguage)
        {
            string strPath = CommonClass.ResultFilePath + @"\SMAT.exe.config";
            if (!File.Exists(strPath))
            {
                if (!Directory.Exists(CommonClass.ResultFilePath))
                {
                    Directory.CreateDirectory(CommonClass.ResultFilePath);
                }

                //File.Copy(Application.ExecutablePath + ".config", strPath);
                FileStream fs = new FileStream(strPath, FileMode.Create);
                StreamWriter sw = new StreamWriter(fs, Encoding.UTF8);
                sw.WriteLine(@"<?xml version=""1.0""?>");
                sw.WriteLine("<configuration>                                                                                          ");
                sw.WriteLine("  <startup>                                                                                              ");
                sw.WriteLine(@"    <supportedRuntime version=""v4.0"" sku="".NETFramework,Version=v4.0"" />                                 ");
                sw.WriteLine("  </startup>                                                                                             ");
                sw.WriteLine("  <appSettings>                                                                                          ");
                sw.WriteLine(@"    <add key=""IncludeChina"" value=""T"" />                                                                 ");
                sw.WriteLine(@"    <add key=""ShowSSIA"" value=""T"" />                                                                     ");
                sw.WriteLine(@"    <add key=""IncludeTaiwan"" value=""F"" />                                                                ");
                sw.WriteLine(@"    <add key=""ShowLanguage"" value=""F"" />                                                                ");
                sw.WriteLine(@"    <add key=""BenMAP-CEpath"" value=""" + Application.StartupPath + @"\..\BenMAP-CE\BenMAP.exe"" /> ");
                sw.WriteLine("  </appSettings>                                                                                         ");
                sw.WriteLine("</configuration>                                                                                         ");
                sw.Flush();
                sw.Close();
                fs.Close();
            }
            string isShow = "T";
            XmlDocument doc = new XmlDocument();
            doc.Load(strPath);//Application.ExecutablePath + ".config");
            XmlNode node = doc.SelectSingleNode(@"//add[@key='IncludeChina']");
            XmlElement ele = (XmlElement)node;
            isShow = ele.GetAttribute("value");
            isIncludeChina = isShow == "T" ? true : false;

            node = doc.SelectSingleNode(@"//add[@key='IncludeTaiwan']");
            ele = (XmlElement)node;
            isShow = ele.GetAttribute("value");
            isIncludeTaiWan = isShow == "T" ? true : false;

            node = doc.SelectSingleNode(@"//add[@key='ShowSSIA']");
            ele = (XmlElement)node;
            isShow = ele.GetAttribute("value");
            isShowSSIA = isShow == "T" ? true : false;

            node = doc.SelectSingleNode(@"//add[@key='BenMAP-CEpath']");
            ele = (XmlElement)node;
            strBenMAPPath = ele.GetAttribute("value");

            node = doc.SelectSingleNode(@"//add[@key='ShowLanguage']");
            if (node == null)
            {
                node = doc.DocumentElement.SelectSingleNode("appSettings");
                ele = doc.CreateElement("add");
                ele.SetAttribute("key", "ShowLanguage");
                ele.SetAttribute("value", "F");
                node.AppendChild(ele);
                doc.Save(strPath);
                isShowLanguage = false;
            }
            else
            {
                ele = (XmlElement)node;
                isShow = ele.GetAttribute("value");
                isShowLanguage = isShow == "T";
            }

            //if (LanguageOld.IsSMATChina)
            //    chkShowSSIA.Enabled = false;
        }
        void LoadForm(Form destForm)
        {
            try
            {
                // 此句必须,否则报错
                destForm.TopLevel = false;
                destForm.ShowIcon = false;
                destForm.ShowInTaskbar = false;
                // 隐藏其标题栏
                destForm.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
                destForm.Dock = DockStyle.Fill;

                pnlMain.Controls.Clear();
                pnlMain.Controls.Add(destForm);
                _currentForm = destForm;
                destForm.Show();
                if (destForm is SMAT_CE && CommonClass.OutputNavigator)
                {
                    (_currentForm as SMAT_CE).setStandardMap();
                }

                //#region Language added by Yangwenwei 

                //if (Language.CurrentLanguage() == "Ch")
                //{
                //    Language.GetLanguagePath();
                //    Dictionary<string, string> dic = new Dictionary<string, string>();
                //    Language.SetDicFromXml(this, dic);
                //    Language.ChangeLanguage(dic, this);
                //}

                //#endregion

            }
            catch (Exception ex)
            {
                CommonClass.LogError(ex);
            }
        }

        //save current scenario
        public bool SaveCurrentScenario()
        {
            try
            {
                string errorTips = "";
                StringBuilder errorTipsBuilder = new StringBuilder("");
                switch (CommonClass.CurrentAnalysis)
                {
                    case enumAnalysis.AnnualPM:
                        if ((CommonClass.CurrentBaseScenario.configuration as AnnualPMAnalysisConfiguration).dataInputA != null)
                        {
                            errorTips = "";
                            errorTips = CommonClass.checkUCDataInputA(CommonClass.CurrentBaseScenario);
                            errorTipsBuilder.Append(errorTips);
                        }
                        break;
                    case enumAnalysis.DailyPM:
                        if ((CommonClass.CurrentBaseScenario.configuration as DailyPMAnalysisConfiguration).dataInputD != null)
                        {
                            errorTips = "";
                            errorTips = CommonClass.checkUCDataInputD(CommonClass.CurrentBaseScenario);
                            errorTipsBuilder.Append(errorTips);
                        }
                        break;
                    case enumAnalysis.Ozone:
                        if ((CommonClass.CurrentBaseScenario.configuration as OzoneAnalysisConfiguration).dataInputO != null)
                        {
                            errorTips = "";
                            errorTips = CommonClass.checkUCDataInputO(CommonClass.CurrentBaseScenario);
                            errorTipsBuilder.Append(errorTips);
                        }
                        break;
                    case enumAnalysis.Visibility:
                        if ((CommonClass.CurrentBaseScenario.configuration as VisibilityAnalysisConfiguration).dataInputV != null)
                        {
                            errorTips = "";
                            errorTips = CommonClass.checkUCDataInputV(CommonClass.CurrentBaseScenario);
                            errorTipsBuilder.Append(errorTips);
                        }
                        break;
                    case enumAnalysis.SSIAAnnualPM:
                        if ((CommonClass.CurrentBaseScenario.configuration as SSIAAnnualPMAnalysisConfiguration).modelInputA != null)
                        {
                            errorTips = "";
                            errorTips = CommonClass.checkSSIAUCModelInputA(CommonClass.CurrentBaseScenario);
                            errorTipsBuilder.Append(errorTips);
                        }
                        if ((CommonClass.CurrentBaseScenario.configuration as SSIAAnnualPMAnalysisConfiguration).monitorInputA != null)
                        {
                            errorTips = "";
                            errorTips = CommonClass.checkSSIAUCModelInputA(CommonClass.CurrentBaseScenario);
                            errorTipsBuilder.Append(errorTips);
                        }
                        break;
                    case enumAnalysis.AnnualPMChina:
                        if ((CommonClass.CurrentBaseScenario.configuration as AnnualPMAnalysisChinaConfiguration).modelDataInputChina != null)
                        {
                            errorTips = "";
                            errorTips = CommonClass.checkPMChinaModelInput(CommonClass.CurrentBaseScenario);
                            errorTipsBuilder.Append(errorTips);
                        }
                        if ((CommonClass.CurrentBaseScenario.configuration as AnnualPMAnalysisChinaConfiguration).monitorDataInputChina != null)
                        {
                            errorTips = "";
                            errorTips = CommonClass.checkPMChinaMonitorInput(CommonClass.CurrentBaseScenario);
                            errorTipsBuilder.Append(errorTips);
                        }
                        if ((CommonClass.CurrentBaseScenario.configuration as AnnualPMAnalysisChinaConfiguration).pm25SpeciesOptionChina != null)
                        {
                            errorTips = "";
                            errorTips = CommonClass.checkPMChinaSpecies(CommonClass.CurrentBaseScenario);
                            errorTipsBuilder.Append(errorTips);
                        }
                        break;
                    case enumAnalysis.OzoneChina:
                        if ((CommonClass.CurrentBaseScenario.configuration as OzoneAnalysisChinaConfiguration).modelDataOzoneChina != null)
                        {
                            errorTips = "";
                            errorTips = CommonClass.checkOzoneChinaModelInput(CommonClass.CurrentBaseScenario);
                            errorTipsBuilder.Append(errorTips);
                        }
                        if ((CommonClass.CurrentBaseScenario.configuration as OzoneAnalysisChinaConfiguration).monitorDataOzoneChina != null)
                        {
                            errorTips = "";
                            errorTips = CommonClass.checkOzoneChinaMonitorInput(CommonClass.CurrentBaseScenario);
                            errorTipsBuilder.Append(errorTips);
                        }
                        break;
                }
                errorTips = errorTipsBuilder.ToString();
                if (errorTips != null && errorTips.Length > 0)
                {
                    MessageBox.Show(errorTips);
                    return false;
                }
                (_currentForm as SMAT_CE).SaveCurrentUCConfiguration();
                SaveFileDialog savefile = new SaveFileDialog();
                savefile.Title = Language.Localization.GetValue("Save project...");
                savefile.InitialDirectory = CommonClass.ResultFilePath + @"\Result\Project";
                savefile.Filter = Language.Localization.GetValue("Project files(*.proj)|*.proj");
                savefile.RestoreDirectory = true;
                switch (CommonClass.CurrentAnalysis)
                {
                    case enumAnalysis.AnnualPM:
                        savefile.FileName = (CommonClass.CurrentBaseScenario.configuration as AnnualPMAnalysisConfiguration).chooseDesiredOutputA.scenarioName;
                        CommonClass.CurrentBaseScenario.configuration.configurationName = (CommonClass.CurrentBaseScenario.configuration as AnnualPMAnalysisConfiguration).chooseDesiredOutputA.scenarioName;
                        break;
                    case enumAnalysis.DailyPM:
                        savefile.FileName = (CommonClass.CurrentBaseScenario.configuration as DailyPMAnalysisConfiguration).chooseDesiredOutputD.scenarioName;
                        CommonClass.CurrentBaseScenario.configuration.configurationName = (CommonClass.CurrentBaseScenario.configuration as DailyPMAnalysisConfiguration).chooseDesiredOutputD.scenarioName;
                        break;
                    case enumAnalysis.Ozone:
                        savefile.FileName = (CommonClass.CurrentBaseScenario.configuration as OzoneAnalysisConfiguration).chooseDesiredOutputO.scenarioName;
                        CommonClass.CurrentBaseScenario.configuration.configurationName = (CommonClass.CurrentBaseScenario.configuration as OzoneAnalysisConfiguration).chooseDesiredOutputO.scenarioName;
                        break;
                    case enumAnalysis.Visibility:
                        savefile.FileName = (CommonClass.CurrentBaseScenario.configuration as VisibilityAnalysisConfiguration).chooseDesiredOutputV.scenarioName;
                        CommonClass.CurrentBaseScenario.configuration.configurationName = (CommonClass.CurrentBaseScenario.configuration as VisibilityAnalysisConfiguration).chooseDesiredOutputV.scenarioName;
                        break;
                    case enumAnalysis.SSIAAnnualPM:
                        savefile.FileName = (CommonClass.CurrentBaseScenario.configuration as SSIAAnnualPMAnalysisConfiguration).analysisOptionA.scenarioName;
                        CommonClass.CurrentBaseScenario.configuration.configurationName = (CommonClass.CurrentBaseScenario.configuration as SSIAAnnualPMAnalysisConfiguration).analysisOptionA.scenarioName;
                        break;
                    case enumAnalysis.AnnualPMChina:
                        savefile.FileName = (CommonClass.CurrentBaseScenario.configuration as AnnualPMAnalysisChinaConfiguration).modelDataInputChina.scenarioName;
                        CommonClass.CurrentBaseScenario.configuration.configurationName = (CommonClass.CurrentBaseScenario.configuration as AnnualPMAnalysisChinaConfiguration).modelDataInputChina.scenarioName;
                        break;
                    case enumAnalysis.OzoneChina:
                        savefile.FileName = (CommonClass.CurrentBaseScenario.configuration as OzoneAnalysisChinaConfiguration).modelDataOzoneChina.scenarioName;
                        CommonClass.CurrentBaseScenario.configuration.configurationName = (CommonClass.CurrentBaseScenario.configuration as OzoneAnalysisChinaConfiguration).modelDataOzoneChina.scenarioName;
                        break;
                }
                if (savefile.ShowDialog() == DialogResult.OK)
                {
                    CommonClass.SaveScenario(CommonClass.CurrentBaseScenario, savefile.FileName);
                    MessageBox.Show("Save project successfully!");
                    return true;
                }
                else
                {
                    this.DialogResult = DialogResult.No;
                    return false;
                }
            }
            catch (Exception ex)
            {
                CommonClass.LogError(ex);
                return false;
            }
        }

        private void Main_Load(object sender, EventArgs e)
        {
            try
            {
                #region 20130118
                if (CommonClass.InputParams != null && CommonClass.InputParams.Count() != 0
                    && CommonClass.InputParams[0].ToLower().Contains(".cfg"))
                {
                    //------------------Batch--------------------------------------
                    CommonClass.IsBatch = true;
                    if (BatchCommonClass.RunBatch(CommonClass.InputParams[0]) == false)
                    {
                        //MessageBox.Show("Batch file is wrong");
                    };
                    //MessageBox.Show("Run batch job successfully !");
                    Environment.Exit(0);
                    return;
                }
                #endregion
                //if (!CommonClass.IsBatch)
                //    WaitShow("Launching SMAT-CE...");
                //加载前先显示首页
                CommonClass.IsBatch = false;
                StartPage form = new StartPage();
                WaitClose();
                DialogResult rtn = form.ShowDialog();
                if (rtn != DialogResult.OK)
                {
                    GC.Collect();
                    Application.Exit();
                    return;
                }
                WaitShow(Language.Localization.GetValue("working..."));
                LoadForm(new SMAT_CE());
                this.ToolStripFile.BackColor = Color.FromArgb(204, 203, 219);
                WaitClose();
            }
            catch (Exception ex)
            {
                WaitClose();
                CommonClass.LogError(ex);
            }
        }

        #region 等待窗口
        //TipForm waitMess = new TipForm();//等待窗体
        TipGIF waitMess = new TipGIF();//等待窗体
        bool sFlog = true;
        //--显示等待窗体 
        private void ShowWaitMess()
        {
            try
            {
                if (!waitMess.IsDisposed)
                {
                    waitMess.ShowDialog();
                }

            }
            catch (System.Threading.ThreadAbortException Err)
            {
                MessageBox.Show(Err.Message);
            }
        }

        //--新开辟一个线程调用 
        public void WaitShow(string msg)
        {
            try
            {
                if (sFlog == true)
                {
                    sFlog = false;
                    waitMess.Msg = msg;
                    waitMess.Title = Language.Localization.GetValue("Tip");
                    System.Threading.Thread upgradeThread = null;
                    upgradeThread = new System.Threading.Thread(new System.Threading.ThreadStart(ShowWaitMess));
                    upgradeThread.Start();
                }
            }
            catch (System.Threading.ThreadAbortException Err)
            {
                MessageBox.Show(Err.Message);
            }
        }
        private delegate void CloseFormDelegate();

        //--关闭等待窗体 
        public void WaitClose()
        {
            //同步到主线程上
            if (waitMess.InvokeRequired)
                waitMess.Invoke(new CloseFormDelegate(DoCloseJob));
            else
                DoCloseJob();
        }

        private void DoCloseJob()
        {
            try
            {
                if (!waitMess.IsDisposed)
                {
                    if (waitMess.Created)
                    {
                        sFlog = true;
                        waitMess.Close();
                    }
                }
            }
            catch (System.Threading.ThreadAbortException Err)
            {
                MessageBox.Show(Err.Message);
            }
        }
        #endregion 等待窗口

        bool SaveProj()
        {
            try
            {
                bool isSave = false;
                switch (CommonClass.CurrentAnalysis)
                {
                    case enumAnalysis.AnnualPM:
                        if ((CommonClass.CurrentBaseScenario.configuration as AnnualPMAnalysisConfiguration).outputChoiceAdvancedA != null || (CommonClass.CurrentBaseScenario.configuration as AnnualPMAnalysisConfiguration).dataInputA != null
                            || (CommonClass.CurrentBaseScenario.configuration as AnnualPMAnalysisConfiguration).speciesFractionOptionsA != null || (CommonClass.CurrentBaseScenario.configuration as AnnualPMAnalysisConfiguration).pm25CalculationOptionsA != null
                            || (CommonClass.CurrentBaseScenario.configuration as AnnualPMAnalysisConfiguration).modelDataOptionsA != null || ((CommonClass.CurrentBaseScenario.configuration as AnnualPMAnalysisConfiguration).chooseDesiredOutputA.doAutomaticallyExtract || (CommonClass.CurrentBaseScenario.configuration as AnnualPMAnalysisConfiguration).chooseDesiredOutputA.doQuarterlyModelData
                            || (CommonClass.CurrentBaseScenario.configuration as AnnualPMAnalysisConfiguration).chooseDesiredOutputA.doSpeciesFraction || (CommonClass.CurrentBaseScenario.configuration as AnnualPMAnalysisConfiguration).chooseDesiredOutputA.doStandardAnalysis
                            || (CommonClass.CurrentBaseScenario.configuration as AnnualPMAnalysisConfiguration).chooseDesiredOutputA.doUsedQuarterlyAvgModelData))
                            isSave = true;
                        break;
                    case enumAnalysis.DailyPM:
                        if ((CommonClass.CurrentBaseScenario.configuration as DailyPMAnalysisConfiguration).outputChoiceAdvancedD != null || (CommonClass.CurrentBaseScenario.configuration as DailyPMAnalysisConfiguration).dataInputD != null
                            || (CommonClass.CurrentBaseScenario.configuration as DailyPMAnalysisConfiguration).speciesFractionOptionsD != null || (CommonClass.CurrentBaseScenario.configuration as DailyPMAnalysisConfiguration).pm25CalculationOptionsD != null
                            || (CommonClass.CurrentBaseScenario.configuration as DailyPMAnalysisConfiguration).modelDataOptionsD != null
                            || ((CommonClass.CurrentBaseScenario.configuration as DailyPMAnalysisConfiguration).chooseDesiredOutputD.doAutomaticallyExtract || (CommonClass.CurrentBaseScenario.configuration as DailyPMAnalysisConfiguration).chooseDesiredOutputD.doQuarterlyPeakModelData
                            || (CommonClass.CurrentBaseScenario.configuration as DailyPMAnalysisConfiguration).chooseDesiredOutputD.doSpeciesFraction || (CommonClass.CurrentBaseScenario.configuration as DailyPMAnalysisConfiguration).chooseDesiredOutputD.doStandardAnalysis))
                            isSave = true;
                        break;
                    case enumAnalysis.Ozone:
                        if ((CommonClass.CurrentBaseScenario.configuration as OzoneAnalysisConfiguration).dataInputO != null || (CommonClass.CurrentBaseScenario.configuration as OzoneAnalysisConfiguration).filteringInterpolationO != null
                            || (CommonClass.CurrentBaseScenario.configuration as OzoneAnalysisConfiguration).rrfSpatialGradientO != null
                            || ((CommonClass.CurrentBaseScenario.configuration as OzoneAnalysisConfiguration).chooseDesiredOutputO.doAutomaticallyExtract || (CommonClass.CurrentBaseScenario.configuration as OzoneAnalysisConfiguration).chooseDesiredOutputO.doBaseOnlyEVNA
                            || (CommonClass.CurrentBaseScenario.configuration as OzoneAnalysisConfiguration).chooseDesiredOutputO.doBaseOnlyVNA || (CommonClass.CurrentBaseScenario.configuration as OzoneAnalysisConfiguration).chooseDesiredOutputO.doDesignValuePeriods || (CommonClass.CurrentBaseScenario.configuration as OzoneAnalysisConfiguration).chooseDesiredOutputO.doMaxDesignValuePeriods
                            || (CommonClass.CurrentBaseScenario.configuration as OzoneAnalysisConfiguration).chooseDesiredOutputO.doFutureOnlyEVNA || (CommonClass.CurrentBaseScenario.configuration as OzoneAnalysisConfiguration).chooseDesiredOutputO.doFutureOnlyVNA
                            || (CommonClass.CurrentBaseScenario.configuration as OzoneAnalysisConfiguration).chooseDesiredOutputO.doNeighborFileSpatial || (CommonClass.CurrentBaseScenario.configuration as OzoneAnalysisConfiguration).chooseDesiredOutputO.doPointEstimatesForecast
                            || (CommonClass.CurrentBaseScenario.configuration as OzoneAnalysisConfiguration).chooseDesiredOutputO.doQuarterlyModelData || (CommonClass.CurrentBaseScenario.configuration as OzoneAnalysisConfiguration).chooseDesiredOutputO.doSpatialFieldEstimates
                            || (CommonClass.CurrentBaseScenario.configuration as OzoneAnalysisConfiguration).chooseDesiredOutputO.doSpatialFieldEstimatesGradAdj))
                            isSave = true;
                        break;
                    case enumAnalysis.Visibility:
                        if ((CommonClass.CurrentBaseScenario.configuration as VisibilityAnalysisConfiguration).dataInputV != null || (CommonClass.CurrentBaseScenario.configuration as VisibilityAnalysisConfiguration).filteringV != null
                            || ((CommonClass.CurrentBaseScenario.configuration as VisibilityAnalysisConfiguration).chooseDesiredOutputV.doAutomaticallyExtract || (CommonClass.CurrentBaseScenario.configuration as VisibilityAnalysisConfiguration).chooseDesiredOutputV.doTemporallyAdjVisibilityLevelsForecast
                            || (CommonClass.CurrentBaseScenario.configuration as VisibilityAnalysisConfiguration).chooseDesiredOutputV.choiceUseModelGridCellatClassIAreaCentroid || (CommonClass.CurrentBaseScenario.configuration as VisibilityAnalysisConfiguration).chooseDesiredOutputV.choiceUseModelGridCellAtMonitor
                            || (CommonClass.CurrentBaseScenario.configuration as VisibilityAnalysisConfiguration).chooseDesiredOutputV.choiceUseNewVersionforIMPROVEAlgorithm || (CommonClass.CurrentBaseScenario.configuration as VisibilityAnalysisConfiguration).chooseDesiredOutputV.choiceUseOldVersionforIMPROVEAlgorithm))
                            isSave = true;
                        break;
                    case enumAnalysis.SSIAAnnualPM:
                        if ((CommonClass.CurrentBaseScenario.configuration as SSIAAnnualPMAnalysisConfiguration).analysisOptionA != null || (CommonClass.CurrentBaseScenario.configuration as SSIAAnnualPMAnalysisConfiguration).modelInputA != null
                            || (CommonClass.CurrentBaseScenario.configuration as SSIAAnnualPMAnalysisConfiguration).monitorInputA != null)
                            isSave = true;
                        break;
                    case enumAnalysis.SSIAOzone:
                        if ((CommonClass.CurrentBaseScenario.configuration as SSIAOzoneAnalysisConfiguration).analysisOptionO != null || (CommonClass.CurrentBaseScenario.configuration as SSIAOzoneAnalysisConfiguration).modelInputO != null
                            || (CommonClass.CurrentBaseScenario.configuration as SSIAOzoneAnalysisConfiguration).monitorInputO != null)
                            isSave = true;
                        break;
                    case enumAnalysis.SSIADeposition:                         //addede by Lijiabin
                        if ((CommonClass.CurrentBaseScenario.configuration as SSIADepositionConfiguration).analysisOptionDep != null || (CommonClass.CurrentBaseScenario.configuration as SSIADepositionConfiguration).modelInputDep != null)
                            isSave = true;
                        break;
                    case enumAnalysis.AnnualPMChina:
                        if ((CommonClass.CurrentBaseScenario.configuration as AnnualPMAnalysisChinaConfiguration).modelDataInputChina != null || (CommonClass.CurrentBaseScenario.configuration as AnnualPMAnalysisChinaConfiguration).monitorDataInputChina != null
                            || (CommonClass.CurrentBaseScenario.configuration as AnnualPMAnalysisChinaConfiguration).pm25SpeciesOptionChina != null)
                            isSave = true;
                        break;
                    case enumAnalysis.OzoneChina:
                        if ((CommonClass.CurrentBaseScenario.configuration as OzoneAnalysisChinaConfiguration).modelDataOzoneChina != null || (CommonClass.CurrentBaseScenario.configuration as OzoneAnalysisChinaConfiguration).monitorDataOzoneChina != null)
                            isSave = true;
                        break;
                }
                return isSave;
            }
            catch
            {
                return false;
            }
        }

        private void tsmiAnnualPM_Click(object sender, EventArgs e)
        {
            try
            {
                if (CommonClass.OutputNavigator == false)
                {
                    bool isSave = SaveProj();
                    DialogResult rtn = DialogResult.No;
                    if (isSave)
                        rtn = MessageBox.Show(Language.Localization.GetValue("Save project?"), Language.Localization.GetValue("Tip"), MessageBoxButtons.YesNo);
                    if (isSave && rtn == DialogResult.Yes)
                    {
                        if (!SaveCurrentScenario()) return;
                    }
                }
                //-----modified by Yangwenwei-----
                if (tsbtnLanguage.Text == "USA")
                    CommonClass.CurrentAnalysis = enumAnalysis.AnnualPM;
                else
                    CommonClass.CurrentAnalysis = enumAnalysis.AnnualPMChina;
                CommonClass.OutputNavigator = false;
                CommonClass.OpenScenario = false;
                CommonClass.IsDataViewerState = false;
                (_currentForm as SMAT_CE).initForm();
            }
            catch (Exception ex)
            {
                CommonClass.LogError(ex);
            }
        }

        private void tsmiDailyPM_Click(object sender, EventArgs e)
        {
            try
            {
                if (CommonClass.OutputNavigator == false)
                {
                    bool isSave = SaveProj();
                    DialogResult rtn = DialogResult.No;
                    if (isSave)
                        rtn = MessageBox.Show(Language.Localization.GetValue("Save project?"), Language.Localization.GetValue("Tip"), MessageBoxButtons.YesNo);
                    if (isSave && rtn == DialogResult.Yes)
                    {
                        if (!SaveCurrentScenario()) return;
                    }
                }
                CommonClass.CurrentAnalysis = enumAnalysis.DailyPM;
                CommonClass.OutputNavigator = false;
                CommonClass.OpenScenario = false;
                CommonClass.IsDataViewerState = false;
                (_currentForm as SMAT_CE).initForm();
            }
            catch (Exception ex)
            {
                CommonClass.LogError(ex);
            }
        }

        private void tsmiOzone_Click(object sender, EventArgs e)
        {
            try
            {
                if (CommonClass.OutputNavigator == false)
                {
                    bool isSave = SaveProj();
                    DialogResult rtn = DialogResult.No;
                    if (isSave)
                        rtn = MessageBox.Show(Language.Localization.GetValue("Save project?"), Language.Localization.GetValue("Tip"), MessageBoxButtons.YesNo);
                    if (isSave && rtn == DialogResult.Yes)
                    {
                        if (!SaveCurrentScenario()) return;
                    }
                }
                //-----modified by Yangwenwei-----
                if (tsbtnLanguage.Text != "USA")
                    CommonClass.CurrentAnalysis = enumAnalysis.OzoneChina;
                else
                    CommonClass.CurrentAnalysis = enumAnalysis.Ozone;
                CommonClass.OutputNavigator = false;
                CommonClass.OpenScenario = false;
                CommonClass.IsDataViewerState = false;
                (_currentForm as SMAT_CE).initForm();
            }
            catch (Exception ex)
            {
                CommonClass.LogError(ex);
            }
        }

        private void tsmiVisibility_Click(object sender, EventArgs e)
        {
            try
            {
                if (CommonClass.OutputNavigator == false)
                {
                    bool isSave = SaveProj();
                    DialogResult rtn = DialogResult.No;
                    if (isSave)
                        rtn = MessageBox.Show(Language.Localization.GetValue("Save project?"), Language.Localization.GetValue("Tip"), MessageBoxButtons.YesNo);
                    if (isSave && rtn == DialogResult.Yes)
                    {
                        if (!SaveCurrentScenario()) return;
                    }
                }
                CommonClass.CurrentAnalysis = enumAnalysis.Visibility;
                CommonClass.OutputNavigator = false;
                CommonClass.OpenScenario = false;
                CommonClass.IsDataViewerState = false;
                (_currentForm as SMAT_CE).initForm();
            }
            catch (Exception ex)
            {
                CommonClass.LogError(ex);
            }
        }

        private void tsmiCreateAScenario_Click(object sender, EventArgs e)
        {
            try
            {
                DialogResult rtn;
                if (CommonClass.OutputNavigator == false)
                {
                    bool isSave = SaveProj();
                    rtn = DialogResult.No;
                    if (isSave)
                        rtn = MessageBox.Show(Language.Localization.GetValue("Save project?"), Language.Localization.GetValue("Tip"), MessageBoxButtons.YesNo);
                    if (isSave && rtn == DialogResult.Yes)
                    {
                        if (!SaveCurrentScenario()) return;
                    }
                }
                ScenarioSelectionscs frm = new ScenarioSelectionscs();
                //Only Annual PM is avaliable for SMAT-China. modified by Yangwenwei
                if (tsbtnLanguage.Text != "USA")
                {
                    frm.rbtnDailyPM.Enabled = false;
                    frm.rbtnVisibility.Enabled = false;
                }
                rtn = frm.ShowDialog();
                if (rtn == DialogResult.OK)
                {
                    CommonClass.OutputNavigator = false;
                    CommonClass.OpenScenario = false;
                    CommonClass.IsDataViewerState = false;
                    CommonClass.IsDataViewerState = false;
                    (_currentForm as SMAT_CE).initForm();
                }
            }
            catch (Exception ex)
            {
                CommonClass.LogError(ex);
            }
        }

        private void tsbtnHomePage_Click(object sender, EventArgs e)
        {
            try
            {
                DialogResult rtn;
                if (CommonClass.OutputNavigator == false)
                {
                    bool isSave = SaveProj();
                    rtn = DialogResult.No;
                    if (isSave)
                        rtn = MessageBox.Show(Language.Localization.GetValue("Save project?"), Language.Localization.GetValue("Tip"), MessageBoxButtons.YesNo);
                    if (isSave && rtn == DialogResult.Yes)
                    {
                        if (!SaveCurrentScenario()) return;
                    }
                    //rtn = MessageBox.Show("Save project?", "Tip", MessageBoxButtons.YesNo);
                    //if (rtn == DialogResult.Yes)
                    //{
                    //    if (!SaveCurrentScenario()) return;
                    //}
                }
                StartPage frm = new StartPage();
                rtn = frm.ShowDialog();
                if (rtn == DialogResult.OK)
                {
                    (_currentForm as SMAT_CE).initForm();
                    if (_currentForm is SMAT_CE && CommonClass.OutputNavigator)
                    {
                        (_currentForm as SMAT_CE).setStandardMap();
                    }
                }
                else
                {
                    frm.Close();
                }
            }
            catch (Exception ex)
            {
                CommonClass.LogError(ex);
            }
        }

        private void Main_FormClosed(object sender, FormClosedEventArgs e)
        {
            try
            {
                GC.Collect();
                Application.Exit();
            }
            catch (Exception ex)
            {
                CommonClass.LogError(ex);
            }
        }

        private void tsmiExit_Click(object sender, EventArgs e)
        {
            try
            {
                GC.Collect();
                Application.Exit();
            }
            catch (Exception ex)
            {
                CommonClass.LogError(ex);
            }
        }

        private void tsmiOpenAScenario_Click(object sender, EventArgs e)
        {
            try
            {
                if (CommonClass.OutputNavigator == false)
                {
                    bool isSave = SaveProj();
                    DialogResult rtn = DialogResult.No;
                    if (isSave) rtn = MessageBox.Show(Language.Localization.GetValue("Save project?"), Language.Localization.GetValue("Tip"), MessageBoxButtons.YesNo);
                    if (isSave && rtn == DialogResult.Yes)
                    {
                        if (!SaveCurrentScenario()) return;
                    }
                }
                OpenFileDialog openfile = new OpenFileDialog();
                openfile.Title = Language.Localization.GetValue("Select project...");
                openfile.InitialDirectory = CommonClass.ResultFilePath + @"\Result\Project";
                openfile.RestoreDirectory = true;
                openfile.Filter = Language.Localization.GetValue("Project files(*.proj)|*.proj");
                if (openfile.ShowDialog() != DialogResult.OK)
                {
                    return;
                }
                //CommonClass.OpenScenario = true;
                //CommonClass.OutputNavigator = false;
                //CommonClass.IsDataViewerState = false;
                //CommonClass.CurrentBaseScenario = CommonClass.LoadScenario(openfile.FileName);
                //CommonClass.FileName = openfile.FileName;
                CommonClass.OpenScenario = false;
                CommonClass.OutputNavigator = true;
                CommonClass.LoadProjectFromStartPageOrAnalysisPage = true;
                CommonClass.IsDataViewerState = false;
                //CommonClass.CurrentBaseScenario = CommonClass.LoadScenario(openfile.FileName);
                CommonClass.FileName = openfile.FileName;
                (_currentForm as SMAT_CE).initForm();
            }
            catch (Exception ex)
            {
                CommonClass.LogError(ex);
            }
        }

        private void tsmiSaveAsrx_Click(object sender, EventArgs e)
        {
            try
            {
                if (CommonClass.OutputNavigator == true) return;
                string errorTips = (_currentForm as SMAT_CE).SaveCurrentUCConfiguration();
                if (errorTips != null && errorTips.Length > 0)
                {
                    MessageBox.Show(errorTips, "Tip", MessageBoxButtons.OK);
                    return;
                }

                SaveFileDialog savefile = new SaveFileDialog();
                savefile.Title = Language.Localization.GetValue("Save project...");
                savefile.InitialDirectory = CommonClass.ResultFilePath + @"\Result\Project";
                savefile.Filter = Language.Localization.GetValue("Project files(*.proj)|*.proj");
                savefile.RestoreDirectory = true;
                switch (CommonClass.CurrentAnalysis)
                {
                    case enumAnalysis.AnnualPM:
                        savefile.FileName = (CommonClass.CurrentBaseScenario.configuration as AnnualPMAnalysisConfiguration).chooseDesiredOutputA.scenarioName;
                        CommonClass.CurrentBaseScenario.configuration.configurationName = (CommonClass.CurrentBaseScenario.configuration as AnnualPMAnalysisConfiguration).chooseDesiredOutputA.scenarioName;
                        break;
                    case enumAnalysis.DailyPM:
                        savefile.FileName = (CommonClass.CurrentBaseScenario.configuration as DailyPMAnalysisConfiguration).chooseDesiredOutputD.scenarioName;
                        CommonClass.CurrentBaseScenario.configuration.configurationName = (CommonClass.CurrentBaseScenario.configuration as DailyPMAnalysisConfiguration).chooseDesiredOutputD.scenarioName;
                        break;
                    case enumAnalysis.Ozone:
                        savefile.FileName = (CommonClass.CurrentBaseScenario.configuration as OzoneAnalysisConfiguration).chooseDesiredOutputO.scenarioName;
                        CommonClass.CurrentBaseScenario.configuration.configurationName = (CommonClass.CurrentBaseScenario.configuration as OzoneAnalysisConfiguration).chooseDesiredOutputO.scenarioName;
                        break;
                    case enumAnalysis.Visibility:
                        savefile.FileName = (CommonClass.CurrentBaseScenario.configuration as VisibilityAnalysisConfiguration).chooseDesiredOutputV.scenarioName;
                        CommonClass.CurrentBaseScenario.configuration.configurationName = (CommonClass.CurrentBaseScenario.configuration as VisibilityAnalysisConfiguration).chooseDesiredOutputV.scenarioName;
                        break;
                    case enumAnalysis.SSIAAnnualPM:
                        savefile.FileName = (CommonClass.CurrentBaseScenario.configuration as SSIAAnnualPMAnalysisConfiguration).analysisOptionA.scenarioName;
                        CommonClass.CurrentBaseScenario.configuration.configurationName = (CommonClass.CurrentBaseScenario.configuration as SSIAAnnualPMAnalysisConfiguration).analysisOptionA.scenarioName;
                        break;
                    //Annual PM China added by Yangwenwei
                    case enumAnalysis.AnnualPMChina:
                        savefile.FileName = (CommonClass.CurrentBaseScenario.configuration as AnnualPMAnalysisChinaConfiguration).modelDataInputChina.scenarioName;
                        CommonClass.CurrentBaseScenario.configuration.configurationName = (CommonClass.CurrentBaseScenario.configuration as AnnualPMAnalysisChinaConfiguration).modelDataInputChina.scenarioName;
                        break;
                }
                if (savefile.ShowDialog() == DialogResult.OK)
                {
                    CommonClass.SaveScenario(CommonClass.CurrentBaseScenario, savefile.FileName);
                    MessageBox.Show(Language.Localization.GetValue("Save project successfully!"));
                }
            }
            catch (Exception ex)
            {
                CommonClass.LogError(ex);
            }
        }

        private void tsmiSaveAsProjx_Click(object sender, EventArgs e)
        {
            try
            {
                SaveFileDialog savefile = new SaveFileDialog();
                savefile.Title = Language.Localization.GetValue("Save project...");
                savefile.InitialDirectory = CommonClass.ResultFilePath + @"\Result\Project";
                savefile.Filter = Language.Localization.GetValue("Project files(*.projx)|*.projx");
                savefile.RestoreDirectory = true;
                savefile.ShowDialog();
            }
            catch (Exception ex)
            {
                CommonClass.LogError(ex);
            }
        }

        private void tsbtnDataViewer_Click(object sender, EventArgs e)
        {
            try
            {
                if (CommonClass.IsDataViewerState)
                {
                    CommonClass.OutputNavigator = true;
                    CommonClass.IsFirstLoadProject = false;
                    CommonClass.OpenScenario = false;
                    (_currentForm as SMAT_CE).initForm();
                    CommonClass.IsDataViewerState = false;
                }
                else
                {
                    if (CommonClass.OutputNavigator == false)
                    {
                        bool isSave = SaveProj();
                        DialogResult rtn = DialogResult.No;
                        if (isSave)
                            rtn = MessageBox.Show(Language.Localization.GetValue("Save project?"), Language.Localization.GetValue("Tip"), MessageBoxButtons.YesNo);
                        if (isSave && rtn == DialogResult.Yes)
                        {
                            if (!SaveCurrentScenario()) return;
                        }
                        //DialogResult rtn = MessageBox.Show("Save project?", "Tip", MessageBoxButtons.YesNo);
                        //if (rtn == DialogResult.Yes)
                        //{
                        //    if (!SaveCurrentScenario()) return;
                        //}
                        //SaveCurrentScenario();
                    }
                    if (CommonClass.CurrentBaseScenario == null)
                    {
                        CommonClass.OutputNavigator = true;
                        CommonClass.IsFirstLoadProject = false;
                        CommonClass.OpenScenario = false;
                        (_currentForm as SMAT_CE).initForm();
                        CommonClass.IsDataViewerState = false;
                    }
                    else
                    {
                        if (CommonClass.CurrentBaseScenario.lstOutput == null)
                        {
                            CommonClass.OutputNavigator = true;
                            CommonClass.IsFirstLoadProject = false;
                            CommonClass.OpenScenario = false;
                            (_currentForm as SMAT_CE).initForm();
                            CommonClass.IsDataViewerState = false;
                            (_currentForm as SMAT_CE).setStandardMap();
                        }
                        else
                        {
                            CommonClass.IsDataViewerState = true;
                            CommonClass.OutputNavigator = true;
                            CommonClass.IsFirstLoadProject = false;
                            CommonClass.OpenScenario = false;
                            (_currentForm as SMAT_CE).initForm();
                            CommonClass.IsDataViewerState = false;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                CommonClass.LogError(ex);
            }
        }

        private void tsbtnMaxViewer_Click(object sender, EventArgs e)
        {
            try
            {
                (_currentForm as SMAT_CE).maxViewer();

            }
            catch (Exception ex)
            {
                CommonClass.LogError(ex);
            }
        }

        private void tsbtnManageSetup_Click(object sender, EventArgs e)
        {
            try
            {
                ManageSetup frm = new ManageSetup();
                frm.ShowDialog();
            }
            catch (Exception ex)
            {
                CommonClass.LogError(ex);
            }
        }

        private void Main_Resize(object sender, EventArgs e)
        {
            try
            {
                if (_currentForm == null)
                {
                    return;
                }
                if ((_currentForm as SMAT_CE).mainMap.ViewExtents.MinX < (_currentForm as SMAT_CE).mainMap.Extent.MinX
                    && (_currentForm as SMAT_CE).mainMap.ViewExtents.MinY < (_currentForm as SMAT_CE).mainMap.Extent.MinY
                    && (_currentForm as SMAT_CE).mainMap.ViewExtents.MaxX > (_currentForm as SMAT_CE).mainMap.Extent.MaxX
                    && (_currentForm as SMAT_CE).mainMap.ViewExtents.MaxY > (_currentForm as SMAT_CE).mainMap.Extent.MaxY)
                {
                    (_currentForm as SMAT_CE).mainMap.ZoomToMaxExtent();
                    return;
                }
                Extent exLast = (_currentForm as SMAT_CE).mainMap.ViewExtents.Clone() as Extent;
                //if ((_currentForm as SMAT_CE).mainMap.Layers.Count == 1)
                //{
                //    if (LanguageOld.IsSMATChina)
                //    {
                //        (_currentForm as SMAT_CE).mainMap.ViewExtents = new Extent()
                //        {
                //            MaxX = 2240183.4290575706,
                //            MaxY = 7050637.3464170638,
                //            MinX = -2658883.752592415,
                //            MinY = 1354047.600312429
                //        };
                //    }
                //    else
                //    {
                //        (_currentForm as SMAT_CE).mainMap.ViewExtents = new Extent()
                //            {
                //                MaxX = 2433867.4804251287,
                //                MaxY = 2157266.7545131817,
                //                MinX = -2465199.7012248561,
                //                MinY = -2251893.708971804
                //            };
                //    }
                //    //mainMap.ViewExtents = mainMap.Extent;
                //}
                //else
                (_currentForm as SMAT_CE).mainMap.ViewExtents = exLast;
                (_currentForm as SMAT_CE).mainMap.Refresh();
            }
            catch (Exception ex)
            {
                CommonClass.LogError(ex);
            }
        }

        private void tsmiAnnualAssessment_Click(object sender, EventArgs e)
        {
            try
            {
                if (CommonClass.OutputNavigator == false)
                {
                    bool isSave = SaveProj();
                    DialogResult rtn = DialogResult.No;
                    if (isSave)
                        rtn = MessageBox.Show(Language.Localization.GetValue("Save project?"), Language.Localization.GetValue("Tip"), MessageBoxButtons.YesNo);
                    if (isSave && rtn == DialogResult.Yes)
                    {
                        if (!SaveCurrentScenario()) return;
                    }
                }
                CommonClass.CurrentAnalysis = enumAnalysis.SSIAAnnualPM;
                CommonClass.OutputNavigator = false;
                CommonClass.OpenScenario = false;
                CommonClass.IsDataViewerState = false;
                (_currentForm as SMAT_CE).initForm();
            }
            catch (Exception ex)
            {
                CommonClass.LogError(ex);
            }
        }

        private void tsmiDailyAssessment_Click(object sender, EventArgs e)
        {
            try
            {
                if (CommonClass.OutputNavigator == false)
                {
                    bool isSave = SaveProj();
                    DialogResult rtn = DialogResult.No;
                    if (isSave)
                        rtn = MessageBox.Show(Language.Localization.GetValue("Save project?"), Language.Localization.GetValue("Tip"), MessageBoxButtons.YesNo);
                    if (isSave && rtn == DialogResult.Yes)
                    {
                        if (!SaveCurrentScenario()) return;
                    }
                }
                CommonClass.CurrentAnalysis = enumAnalysis.SSIADailyPM;
                CommonClass.OutputNavigator = false;
                CommonClass.OpenScenario = false;
                CommonClass.IsDataViewerState = false;
                (_currentForm as SMAT_CE).initForm();
            }
            catch (Exception ex)
            {
                CommonClass.LogError(ex);
            }
        }

        private void tsmiOzoneAssessment_Click(object sender, EventArgs e)
        {
            try
            {
                if (CommonClass.OutputNavigator == false)
                {
                    bool isSave = SaveProj();
                    DialogResult rtn = DialogResult.No;
                    if (isSave)
                        rtn = MessageBox.Show(Language.Localization.GetValue("Save project?"), Language.Localization.GetValue("Tip"), MessageBoxButtons.YesNo);
                    if (isSave && rtn == DialogResult.Yes)
                    {
                        if (!SaveCurrentScenario()) return;
                    }
                }
                CommonClass.CurrentAnalysis = enumAnalysis.SSIAOzone;
                CommonClass.OutputNavigator = false;
                CommonClass.OpenScenario = false;
                CommonClass.IsDataViewerState = false;
                (_currentForm as SMAT_CE).initForm();
            }
            catch (Exception ex)
            {
                CommonClass.LogError(ex);
            }
        }

        private void tsmiDepAssessment_Click(object sender, EventArgs e) //added by Lijiabin
        {
            try
            {
                if (CommonClass.OutputNavigator == false)
                {
                    bool isSave = SaveProj();
                    DialogResult rtn = DialogResult.No;
                    if (isSave)
                        rtn = MessageBox.Show(Language.Localization.GetValue("Save project?"), Language.Localization.GetValue("Tip"), MessageBoxButtons.YesNo);
                    if (isSave && rtn == DialogResult.Yes)
                    {
                        if (!SaveCurrentScenario()) return;
                    }
                }
                CommonClass.CurrentAnalysis = enumAnalysis.SSIADeposition;
                CommonClass.OutputNavigator = false;
                CommonClass.OpenScenario = false;
                CommonClass.IsDataViewerState = false;
                (_currentForm as SMAT_CE).initForm();
            }
            catch (Exception ex)
            {
                CommonClass.LogError(ex);
            }
        }

        //added by Yangwenwei
        private void tsmiUSA_Click(object sender, EventArgs e)
        {
            try
            {
                switch (tsbtnLanguage.Text)
                {

                    case "USA": return;
                    case "China":
                        if (CommonClass.OutputNavigator == false)
                        {
                            bool isSave = SaveProj();
                            DialogResult rtn = DialogResult.No;
                            if (isSave)
                                rtn = MessageBox.Show(Language.Localization.GetValue("Save project?"), Language.Localization.GetValue("Tip"), MessageBoxButtons.YesNo);
                            if (isSave && rtn == DialogResult.Yes)
                            {
                                if (!SaveCurrentScenario()) return;
                            }
                            CommonClass.CurrentAnalysis = enumAnalysis.AnnualPM;
                            CommonClass.OpenScenario = false;
                            CommonClass.IsDataViewerState = false;
                        }
                        tsbtnLanguage.Text = "USA";
                        LanguageOld.IsSMATChina = false;
                        (_currentForm as SMAT_CE).initForm();
                        break;
                }
                //Dictionary<string, string> dic = new Dictionary<string, string>();
                ////Translate Main
                //Language.SetDicFromXml(this, dic);
                //LanguageOld.ChangeLanguage(dic, this);
                //dic.Clear();
                ////Translate SMAT_CE
                //Language.SetDicFromXml(this._currentForm, dic);
                //Language.ChangeLanguage(dic, this._currentForm);
                //dic.Clear();
                #region Show SSIA?
                XmlDocument doc = new XmlDocument();
                doc.Load(CommonClass.ResultFilePath + @"\SMAT.exe.config");//Application.ExecutablePath + ".config");
                XmlNode node = doc.SelectSingleNode(@"//add[@key='ShowSSIA']");
                if (node != null)
                {
                    XmlElement ele = (XmlElement)node;
                    ele = (XmlElement)node;
                    string isShow = ele.GetAttribute("value");
                    //BetaVersion，需要隐藏SSIA module
                    tsbtnSingleAssessment.Visible = !CommonClass.BetaVersion && isShow == "T" ? true : false;
                }
                #endregion
                tsmiDailyPM.Visible = true;
                tsmiVisibility.Visible = true;
            }
            catch (Exception ex)
            {
                CommonClass.LogError(ex);
            }

        }
        //added by Yangwenwei
        private void tsmiChina_Click(object sender, EventArgs e)
        {
            try
            {
                switch (tsbtnLanguage.Text)
                {
                    case "USA":
                        if (CommonClass.OutputNavigator == false)
                        {
                            bool isSave = SaveProj();
                            DialogResult rtn = DialogResult.No;
                            if (isSave)
                                rtn = MessageBox.Show(Language.Localization.GetValue("Save project?"), Language.Localization.GetValue("Tip"), MessageBoxButtons.YesNo);
                            if (isSave && rtn == DialogResult.Yes)
                            {
                                if (!SaveCurrentScenario()) return;
                            }
                            CommonClass.CurrentAnalysis = enumAnalysis.AnnualPMChina;
                            CommonClass.OpenScenario = false;
                            CommonClass.IsDataViewerState = false;
                        }
                        tsbtnLanguage.Text = "China";
                        LanguageOld.IsSMATChina = true;
                        (_currentForm as SMAT_CE).initForm();
                        break;
                    case "China": return;
                }
                tsbtnSingleAssessment.Visible = false;
                tsmiDailyPM.Visible = false;
                tsmiVisibility.Visible = false;
            }
            catch (Exception ex)
            {
                CommonClass.LogError(ex);
            }

        }

        private void tsmiOptions_Click(object sender, EventArgs e)
        {
            try
            {
                Options frm = new Options();
                frm.ShowDialog();
                if (frm.DialogResult == DialogResult.OK)
                {
                    bool includeChina = this.tsbtnLanguage.Visible;
                    bool includeTaiwan = this.tsmiTaiwan.Visible;
                    bool showSSIA = this.tsbtnSingleAssessment.Visible;
                    bool includeLanguage = this.toolStripButton1.Visible;
                    string strPath = "";
                    initConfig(ref includeChina, ref includeTaiwan, ref showSSIA, ref strPath, ref includeLanguage);
                    //XmlDocument doc = new XmlDocument();
                    //doc.Load(Application.ExecutablePath + ".config");
                    //XmlNode node = doc.SelectSingleNode(@"//add[@key='IncludeChina']");
                    //if (node != null)
                    //{
                    //    XmlElement ele = (XmlElement)node;
                    //    ele = (XmlElement)node;
                    //    string isShow = ele.GetAttribute("value");
                    //    includeChina = isShow == "T" ? true : false;
                    //}
                    //node = doc.SelectSingleNode(@"//add[@key='IncludeTaiwan']");
                    //if (node != null)
                    //{
                    //    XmlElement ele = (XmlElement)node;
                    //    ele = (XmlElement)node;
                    //    string isShow = ele.GetAttribute("value");
                    //    includeTaiwan = isShow == "T" ? true : false;
                    //}
                    //node = doc.SelectSingleNode(@"//add[@key='ShowSSIA']");
                    //if (node != null)
                    //{
                    //    XmlElement ele = (XmlElement)node;
                    //    ele = (XmlElement)node;
                    //    string isShow = ele.GetAttribute("value");
                    //    showSSIA = isShow == "T" ? true : false;
                    //}

                    if (((CommonClass.CurrentAnalysis == enumAnalysis.AnnualPMChina || CommonClass.CurrentAnalysis == enumAnalysis.OzoneChina) && !includeChina) || ((CommonClass.CurrentAnalysis == enumAnalysis.SSIAAnnualPM || CommonClass.CurrentAnalysis == enumAnalysis.SSIADailyPM || CommonClass.CurrentAnalysis == enumAnalysis.SSIAOzone) && !showSSIA))
                    {
                        if (CommonClass.OutputNavigator == false)
                        {
                            bool isSave = SaveProj();
                            DialogResult rtn = DialogResult.No;
                            if (isSave)
                                rtn = MessageBox.Show(Language.Localization.GetValue("Save project?"), Language.Localization.GetValue("Tip"), MessageBoxButtons.YesNo);
                            if (isSave && rtn == DialogResult.Yes)
                            {
                                if (!SaveCurrentScenario()) return;
                            }
                        }
                        CommonClass.CurrentAnalysis = enumAnalysis.AnnualPM;
                        CommonClass.OutputNavigator = false;
                        CommonClass.OpenScenario = false;
                        CommonClass.IsDataViewerState = false;
                        tsmiDailyPM.Visible = true;
                        tsmiVisibility.Visible = true;
                        LanguageOld.IsSMATChina = false;
                        tsbtnLanguage.Text = "USA";
                        (_currentForm as SMAT_CE).initForm();
                    }

                    this.tsbtnLanguage.Visible = (includeChina || includeTaiwan);
                    this.tsmiTaiwan.Visible = includeTaiwan;
                    this.tsmiChina.Visible = includeChina;
                    this.toolStripButton1.Visible = includeLanguage;
                    if (!LanguageOld.IsSMATChina)
                        this.tsbtnSingleAssessment.Visible = showSSIA;
                }
            }
            catch (Exception ex)
            {
                CommonClass.LogError(ex);
            }
        }

        private void tsmiBenMAP_annualPM_Click(object sender, EventArgs e)
        {
            try
            {
                if (CommonClass.OutputNavigator == false)
                {
                    bool isSave = SaveProj();
                    DialogResult rtn = DialogResult.No;
                    if (isSave)
                        rtn = MessageBox.Show(Language.Localization.GetValue("Save project?"), Language.Localization.GetValue("Tip"), MessageBoxButtons.YesNo);
                    if (isSave && rtn == DialogResult.Yes)
                    {
                        if (!SaveCurrentScenario()) return;
                    }
                }
                CommonClass.CurrentAnalysis = enumAnalysis.BenMAPAnnualPM;
                CommonClass.OutputNavigator = false;
                CommonClass.OpenScenario = false;
                CommonClass.IsDataViewerState = false;
                (_currentForm as SMAT_CE).initForm();
            }
            catch (Exception ex)
            {
                CommonClass.LogError(ex);
            }
        }

        private void tsmiBenMAP_seasonalOzone_Click(object sender, EventArgs e)
        {
            try
            {
                if (CommonClass.OutputNavigator == false)
                {
                    bool isSave = SaveProj();
                    DialogResult rtn = DialogResult.No;
                    if (isSave)
                        rtn = MessageBox.Show(Language.Localization.GetValue("Save project?"), Language.Localization.GetValue("Tip"), MessageBoxButtons.YesNo);
                    if (isSave && rtn == DialogResult.Yes)
                    {
                        if (!SaveCurrentScenario()) return;
                    }
                }
                CommonClass.CurrentAnalysis = enumAnalysis.BenMAPSeasonalOzone;
                CommonClass.OutputNavigator = false;
                CommonClass.OpenScenario = false;
                CommonClass.IsDataViewerState = false;
                (_currentForm as SMAT_CE).initForm();
            }
            catch (Exception ex)
            {
                CommonClass.LogError(ex);
            }
        }

        private void tsbtnDataErrorChecker_Click(object sender, EventArgs e)
        {
            DataErrorChecking datachecker = new DataErrorChecking();
            datachecker.ShowDialog();
        }

        private void chineseToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.chineseToolStripMenuItem.Checked)
            { return; }
            else
            {
                if (ChangeLanguageMessage())
                {
                    pnlMain.Controls.Clear();
                    Language.Localization.Load(this, "zh");
                    //LoadForm(_currentForm);
                    LoadForm(new SMAT_CE());
                    this.chineseToolStripMenuItem.Checked = true;
                    this.englishToolStripMenuItem.Checked = false;
                }
            }
        }

        private void englishToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.englishToolStripMenuItem.Checked)
            { return; }
            else
            {
                if (ChangeLanguageMessage())
                {
                    pnlMain.Controls.Clear();
                    Language.Localization.Load(this, "en");
                    //LoadForm(_currentForm);
                    LoadForm(new SMAT_CE());

                    this.englishToolStripMenuItem.Checked = true;
                    this.chineseToolStripMenuItem.Checked = false;
                }
            }
        }

        private bool ChangeLanguageMessage()
        {
            string message = Language.Localization.GetValue("Save Current Project?");
            DialogResult rt = MessageBox.Show(message, Language.Localization.GetValue("Tips"), MessageBoxButtons.YesNoCancel, MessageBoxIcon.Information);
            if (rt == DialogResult.Yes)
            {
                #region                   
                    string errorTips = (_currentForm as SMAT_CE).SaveCurrentUCConfiguration();
                    if (errorTips != null && errorTips.Length > 0)
                    {
                        MessageBox.Show(errorTips, "Tip", MessageBoxButtons.OK);
                        return false;
                    }

                    SaveFileDialog savefile = new SaveFileDialog();
                    savefile.Title = Language.Localization.GetValue("Save project...");
                    savefile.InitialDirectory = CommonClass.ResultFilePath + @"\Result\Project";
                    savefile.Filter = Language.Localization.GetValue("Project files(*.proj)|*.proj");
                    savefile.RestoreDirectory = true;
                    switch (CommonClass.CurrentAnalysis)
                    {
                        case enumAnalysis.AnnualPM:
                            savefile.FileName = (CommonClass.CurrentBaseScenario.configuration as AnnualPMAnalysisConfiguration).chooseDesiredOutputA.scenarioName;
                            CommonClass.CurrentBaseScenario.configuration.configurationName = (CommonClass.CurrentBaseScenario.configuration as AnnualPMAnalysisConfiguration).chooseDesiredOutputA.scenarioName;
                            break;
                        case enumAnalysis.DailyPM:
                            savefile.FileName = (CommonClass.CurrentBaseScenario.configuration as DailyPMAnalysisConfiguration).chooseDesiredOutputD.scenarioName;
                            CommonClass.CurrentBaseScenario.configuration.configurationName = (CommonClass.CurrentBaseScenario.configuration as DailyPMAnalysisConfiguration).chooseDesiredOutputD.scenarioName;
                            break;
                        case enumAnalysis.Ozone:
                            savefile.FileName = (CommonClass.CurrentBaseScenario.configuration as OzoneAnalysisConfiguration).chooseDesiredOutputO.scenarioName;
                            CommonClass.CurrentBaseScenario.configuration.configurationName = (CommonClass.CurrentBaseScenario.configuration as OzoneAnalysisConfiguration).chooseDesiredOutputO.scenarioName;
                            break;
                        case enumAnalysis.Visibility:
                            savefile.FileName = (CommonClass.CurrentBaseScenario.configuration as VisibilityAnalysisConfiguration).chooseDesiredOutputV.scenarioName;
                            CommonClass.CurrentBaseScenario.configuration.configurationName = (CommonClass.CurrentBaseScenario.configuration as VisibilityAnalysisConfiguration).chooseDesiredOutputV.scenarioName;
                            break;
                        case enumAnalysis.SSIAAnnualPM:
                            savefile.FileName = (CommonClass.CurrentBaseScenario.configuration as SSIAAnnualPMAnalysisConfiguration).analysisOptionA.scenarioName;
                            CommonClass.CurrentBaseScenario.configuration.configurationName = (CommonClass.CurrentBaseScenario.configuration as SSIAAnnualPMAnalysisConfiguration).analysisOptionA.scenarioName;
                            break;
                        //Annual PM China added by Yangwenwei
                        case enumAnalysis.AnnualPMChina:
                            savefile.FileName = (CommonClass.CurrentBaseScenario.configuration as AnnualPMAnalysisChinaConfiguration).modelDataInputChina.scenarioName;
                            CommonClass.CurrentBaseScenario.configuration.configurationName = (CommonClass.CurrentBaseScenario.configuration as AnnualPMAnalysisChinaConfiguration).modelDataInputChina.scenarioName;
                            break;
                    }
                    if (savefile.ShowDialog() == DialogResult.OK)
                    {
                        CommonClass.SaveScenario(CommonClass.CurrentBaseScenario, savefile.FileName);
                        MessageBox.Show(Language.Localization.GetValue("Save project successfully!"));
                        return true;
                    }
                    else
                    { return false; }
                 #endregion     
                
            }
            else if (rt == DialogResult.No)
                return true;
            else
                return false;
        }

    }
}
