using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Net;
using System.Runtime.ConstrainedExecution;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
using DevExpress.XtraBars;
using DevExpress.XtraBars.ColorPick.Popup;
using DevExpress.XtraEditors;
using DevExpress.XtraTab;
using DevExpress.XtraTreeList;
using DevExpress.XtraTreeList.Nodes;
using PXP.Crawler.API;
using PXP.Crawler.API.Controls;
using PXP.Crawler.API.Designers.Controls;
using PXP.Crawler.API.Model;
using PXP.Crawler.API.Utils;
using PXP.Crawler.API.Data;
using PXP.Crawler.Forms.Edit;
using ScintillaNET;

namespace PXP.Crawler.Forms
{
    public partial class MainXtraForm : DevExpress.XtraEditors.XtraForm
    {
        #region Constructor

        public MainXtraForm()
        {
            InitializeComponent();
        }

        #endregion

        #region Variables

        private StringFormat nodesCatStringFormat = new StringFormat(StringFormatFlags.NoWrap) { Alignment = StringAlignment.Near, LineAlignment = StringAlignment.Center};
        private DataView nodesDataView;

        #endregion

        #region Menu Events

        private void exitBarButtonItem_ItemClick(object sender, ItemClickEventArgs e)
        {
            Close();
        }
        private void aboutBarButtonItem_ItemClick(object sender, ItemClickEventArgs e)
        {
            XtraMessageBox.Show("PXP Crawler\n\n\tVersion: 0.1 Alpha\n\tDeveloped by: \tPixel Design d.o.o.\n\t\t\t\t\t\t\t\tDubrovnik, Croatia\n\n\tContact:\t\t\t  info@pixeldesign.hr\n\tWeb:\t\t\t\t   www.pixeldesign.hr", "PXP Crawler", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        #endregion

        #region Methods

        public void Log(string msg, string type = "info")
        {
            outputRichTextBox.SuspendLayout();

            if (outputRichTextBox.TextLength > 0)
                outputRichTextBox.AppendText("\n");

            int ssp = outputRichTextBox.TextLength;
            string addSt = DateTime.Now.ToString("hh:mm:ss.f") + " (" + type + ")";
            outputRichTextBox.AppendText(addSt);
            outputRichTextBox.SelectionStart = ssp;
            outputRichTextBox.SelectionLength = addSt.Length;
            outputRichTextBox.SelectionFont = outputPanel.Font;
            outputRichTextBox.SelectionColor = Color.PaleGoldenrod;
            ssp = outputRichTextBox.TextLength;
            

            string rtStr = " > " + msg;
            
            outputRichTextBox.AppendText(rtStr);
            
            outputRichTextBox.SelectionStart = ssp;
            outputRichTextBox.SelectionLength = outputRichTextBox.TextLength - ssp;
            outputRichTextBox.SelectionFont = outputRichTextBox.Font;
            outputRichTextBox.SelectionColor = outputRichTextBox.ForeColor;

            outputRichTextBox.SelectionLength = 0;
            outputRichTextBox.SelectionStart = outputRichTextBox.TextLength - 1;

            outputRichTextBox.ScrollToCaret();
            
            outputRichTextBox.ResumeLayout();
        }

        public void UpdateNodesTree()
        {
            nodesDataSet.Clear();
            PluginManager pm = Program.plugMan;
            foreach (string catName in pm.GetCategoryNames())
            {
                NodesDataSet.CategoriesRow rcatRow = nodesDataSet.Categories.AddCategoriesRow(catName);

                int imInd = -1;//nodesImageCollection.Images.IndexOf(nodesImageCollection.Images["category"]);
                NodesDataSet.NodesRow catRow = nodesDataSet.Nodes.AddNodesRow(null, catName, imInd, null, 0, rcatRow);
                
                SortedDictionary<string, NodeInfo> nodeTypes = pm.GetCategoryTypes(catName);
                foreach (string nodeTypeName in nodeTypes.Keys)
                {
                    NodeInfo nInfo = nodeTypes[nodeTypeName];
                    int ntImgInd = nodesImageCollection.Images.Add(nInfo.Icon.Image, nInfo.Icon.ImageName);
                    NodesDataSet.NodesRow nTypeRow = nodesDataSet.Nodes.AddNodesRow(catRow, nInfo.Name, ntImgInd, nInfo, 1, rcatRow);
                }
            }

            if (nodesDataView == null)
            {
                nodesDataView = new DataView(nodesDataSet.Nodes);
                nodesDataView.Sort = "Name";
                nodesTreeList.DataSource = nodesDataView;
                nodesTreeList.ExpandAll();
            }



            if (nodesTreeList.Nodes.Count > 0)
            {
                nodesTreeList.ExpandAll();
                nodesTreeList.FocusedNode = nodesTreeList.Nodes[0].Nodes[0];
            }
        }

        #endregion

        #region Form Events

        private void nodesTreeList_BeforeFocusNode(object sender, BeforeFocusNodeEventArgs e)
        {
            if (e.Node != null)
            {
                byte nodeType = Convert.ToByte(e.Node.GetValue(colType));
                if (nodeType == 0)
                {
                    if (e.Node.Nodes.Count > 0)
                    {
                        e.CanFocus = false;
                        e.Node.ExpandAll();
                        nodesTreeList.FocusedNode = e.Node.Nodes[0];
                    }
                }
            }
            else
            {

            }
        }


        private void nodesTreeList_BeforeDragNode(object sender, BeforeDragNodeEventArgs e)
        {
            byte nodeType = Convert.ToByte(e.Node.GetValue(colType));
            if (nodeType == 1)
            {
                e.CanDrag = true;
            }
            else
            {
                e.CanDrag = false;
            }

        }

        private void nodesTreeList_DragOver(object sender, DragEventArgs e)
        {
            TreeListNode dragNode = e.Data.GetData(typeof(TreeListNode)) as TreeListNode;
            e.Effect = DragDropEffects.None;

        }

        private void nodesTreeList_CalcNodeDragImageIndex(object sender, CalcNodeDragImageIndexEventArgs e)
        {
            e.ImageIndex = -1;
        }

        private void debugInfoBarButtonItem_DownChanged(object sender, ItemClickEventArgs e)
        {
            ProjectDesignerControl.EnableDebug = viewDebugInfoBarButtonItem.Down;
            if (ActiveMdiChild is ProjectXtraForm)
            {
                ProjectXtraForm projForm = (ProjectXtraForm)ActiveMdiChild;
                foreach (XtraTabPage pTabPage in projForm.pagesXtraTabControl.TabPages)
                {
                    if (pTabPage.Tag is ProjectItem)
                    {
                        ProjectItem pi = (ProjectItem)pTabPage.Tag;
                        if (pi.Type == ProjectItem.ProjectItemType.Program)
                        {
                            pTabPage.Invalidate(true);
                        }
                    }
                }
            }
        }

        private void outputDockPanel_CustomButtonClick(object sender, DevExpress.XtraBars.Docking2010.ButtonEventArgs e)
        {
            if (e.Button.Properties.Caption == "Clear")
            {
                outputRichTextBox.Text = "";
            }
        }

        private void MainXtraForm_Activated(object sender, EventArgs e)
        {
            if (Program.splashForm != null)
            {
                if (!splashCloseTimer.Enabled)
                {
                    splashCloseTimer.Enabled = true;
                }
            }
        }

        private void splashCloseTimer_Tick(object sender, EventArgs e)
        {
            Program.splashForm.Dispose();
            Program.splashForm = null;

            splashCloseTimer.Enabled = false;
        }

        private void nodesTreeList_CustomDrawNodeImages(object sender, CustomDrawNodeImagesEventArgs e)
        {
            byte nodeType = Convert.ToByte(e.Node.GetValue(colType));
            if (nodeType == 1)
            {
                e.Handled = true;
                Rectangle imRect = e.SelectRect;
                imRect.Width = 24;
                imRect.Height = 24;
                
                e.Graphics.DrawImage(nodesImageCollection.Images[e.SelectImageIndex], imRect, new Rectangle(new Point(), nodesImageCollection.ImageSize), GraphicsUnit.Pixel);
            }
        }

        private void nodesTreeList_CalcNodeHeight(object sender, CalcNodeHeightEventArgs e)
        {
            byte nodeType = Convert.ToByte(e.Node.GetValue(colType));
            if (nodeType == 1)
            {
                e.NodeHeight = 24;
            }
            else
            {
                e.NodeHeight = 24;
            }
        }

        private void nodesTreeList_CustomDrawNodeCell(object sender, DevExpress.XtraTreeList.CustomDrawNodeCellEventArgs e)
        {
            if (e.Column == colName)
            {

                byte nodeType = Convert.ToByte(e.Node.GetValue(colType));
                if (nodeType == 0)
                {
                    e.Handled = true;
                    //e.Graphics.FillRectangle(Brushes.Gray, e.Bounds);
                    e.Graphics.DrawString(e.CellText, nodesTreeList.Appearance.HeaderPanel.Font, Brushes.White, e.Bounds, nodesCatStringFormat);
                }
                else if (nodeType == 1)
                {
                    e.Handled = true;

                    e.Graphics.DrawString(e.CellText, e.Appearance.Font, Brushes.White, e.Bounds, nodesCatStringFormat);                    
                }
            }
        }


        private void nodeFilterTextEdit_TextChanged(object sender, EventArgs e)
        {
            nodesDataView.RowFilter = "Name LIKE '%" + nodeFilterTextEdit.Text + "%' OR Type = 0";
            nodesTreeList.ExpandAll();
            //nodesTreeList.ApplyFindFilter(nodeFilterTextEdit.Text.Trim());
        }

        private string fileToOpen = "";
        private string defaultDockLayoutXML = "";

        private void MainXtraForm_Load(object sender, EventArgs e)
        {            
            UpdateNodesTree();

            saveProjectFileDialog.InitialDirectory = Program.projectsPath;

            StringBuilder sb = new StringBuilder();
            StringWriter sw = new StringWriter(sb);



            if (!File.Exists("main_default_layout.xml"))
                dockManager.SaveToXml("main_default_layout.xml");

            if (File.Exists(Program.exePath + "main_layout.xml"))
            {                
                dockManager.RestoreFromXml(Program.exePath + "main_layout.xml");
            }

            string currProjPath = Program.exePath + "current_project.pxcproj";
            if (File.Exists(currProjPath))
            {
                fileToOpen = currProjPath;
                fileOpenBarButtonItem.PerformClick();
                /*Project project = Project.LoadFromFile(currProjPath);
                ProjectXtraForm projForm = new ProjectXtraForm(project);
                projForm.filePath = currProjPath;
                projForm.MdiParent = this;
                projForm.PopupMenu = projectPopupMenu;
                projForm.Show();*/
            }
            else
            {
                newProjectBarButtonItem.PerformClick();                
            }

            RestoreRegexTools();
        }

        private void xtraTabbedMdiManager_SelectedPageChanged(object sender, EventArgs e)
        {
            editProjectBarSubItem.Enabled = (ActiveMdiChild != null & ActiveMdiChild is ProjectXtraForm);
            editProjectToolbarBarSubItem.Enabled = editProjectBarSubItem.Enabled;
            editProjectPreferencesBarButtonItem.Enabled = editProjectBarSubItem.Enabled; fileCloseBarButtonItem.Enabled = ActiveMdiChild != null;

            fileSaveBarButtonItem.Enabled = false;
            if (ActiveMdiChild is EditXtraForm)
            {
                EditXtraForm eForm = (EditXtraForm) ActiveMdiChild;fileSaveBarButtonItem.Enabled = eForm.CanSave;
                deleteBarButtonItem.Enabled = eForm.CanDelete;
            }
            saveAsBarButtonItem.Enabled = fileSaveBarButtonItem.Enabled;
        }

        private void MainXtraForm_KeyDown(object sender, KeyEventArgs e)
        {
            if (!e.Control & !e.Alt & !e.Shift)
            {
                if (ActiveControl != null)
                {
                    if (!ActiveControl.Name.StartsWith("filter"))
                    {
                        if (e.KeyCode == Keys.Escape)
                        {
                            Close();
                        }
                    }
                }
                else
                {
                    Close();
                }
            }
        
            ProjectDesignerControl.ctrlDown = e.Control;
            ProjectDesignerControl.altDown = e.Alt;
            ProjectDesignerControl.shiftDown = e.Shift;
        }

        private void MainXtraForm_KeyUp(object sender, KeyEventArgs e)
        {
            ProjectDesignerControl.ctrlDown = e.Control;
            ProjectDesignerControl.altDown = e.Alt;
            ProjectDesignerControl.shiftDown = e.Shift;
        }

        private void explorerDockPanel_VisibilityChanged(object sender, DevExpress.XtraBars.Docking.VisibilityChangedEventArgs e)
        {
            viewExplorerBarButtonItem.Down = explorerDockPanel.Visible;
        }

        private void nodesDockPanel_VisibilityChanged(object sender, DevExpress.XtraBars.Docking.VisibilityChangedEventArgs e)
        {
            viewNodesBarButtonItem.Down = nodesDockPanel.Visible;
        }

        private void viewExplorerBarButtonItem_DownChanged(object sender, ItemClickEventArgs e)
        {
            if (viewExplorerBarButtonItem.Down != explorerDockPanel.Visible)
                explorerDockPanel.Visible = viewExplorerBarButtonItem.Down;
        }

        private void viewNodesBarButtonItem_DownChanged(object sender, ItemClickEventArgs e)
        {
            if (viewNodesBarButtonItem.Down != nodesDockPanel.Visible)
                nodesDockPanel.Visible = viewNodesBarButtonItem.Down;
        }

        private void viewRegexToolsBarButtonItem_DownChanged(object sender, ItemClickEventArgs e)
        {
            if (viewRegexToolsBarButtonItem.Down != regexToolsDockPanel.Visible)
            {
                regexToolsDockPanel.Visible = viewRegexToolsBarButtonItem.Down;
            }
        }  

        #endregion

        #region Bar Events

        private void newProjectBarButtonItem_ItemClick(object sender, ItemClickEventArgs e)
        {
            ProjectXtraForm projForm = new ProjectXtraForm();
            projForm.MdiParent = this;
            projForm.PopupMenu = projectPopupMenu;
            projForm.Show();
            projForm.projectDesignerControl.addProgramBarButtonItem.PerformClick();
        }

        private void fileCloseBarButtonItem_ItemClick(object sender, ItemClickEventArgs e)
        {
            ActiveMdiChild.Dispose();
        }

        private void fileOpenBarButtonItem_ItemClick(object sender, ItemClickEventArgs e)
        {
            //try
            //{
                string ofPath = fileToOpen;
                
                if (ofPath.Length == 0)
                {
                    if (projectOpenFileDialog.ShowDialog(this) == DialogResult.OK)
                    {
                        ofPath = projectOpenFileDialog.FileName;
                    }
                }
                if (ofPath.Length > 0)
                {
                    Project project = Project.LoadFromFile(ofPath);
                    ProjectXtraForm projForm = new ProjectXtraForm(project);
                    
                    if (fileToOpen.Length == 0)
                        projForm.filePath = ofPath;

                    projForm.MdiParent = this;
                    projForm.PopupMenu = projectPopupMenu;
                    projForm.Show();
                    ofPath = "";
                }
                fileToOpen = "";
           // }
            //catch (Exception exc)
            //{
             //   XtraMessageBox.Show("Error: " + exc.Message, "Open project", MessageBoxButtons.OK, MessageBoxIcon.Error);
            //}
            

        }

        private void fileSaveBarButtonItem_ItemClick(object sender, ItemClickEventArgs e)
        {
            EditXtraForm edForm = (EditXtraForm) ActiveMdiChild;
            if (ActiveMdiChild is ProjectXtraForm)
            {
                if (edForm.filePath.Length == 0)
                {
                    ProjectXtraForm pForm = (ProjectXtraForm) edForm;
                    saveProjectFileDialog.FileName = pForm.project.Name + ".pxcproj";
                    if (saveProjectFileDialog.FileName.StartsWith("_"))
                    {edForm.DoSave(Program.projectsPath + "\\" + saveProjectFileDialog.FileName);
                    }
                    else
                    {
                        if (saveProjectFileDialog.ShowDialog(this) == DialogResult.OK)
                        {
                            edForm.DoSave(saveProjectFileDialog.FileName);
                        }                        
                    }

                }
                else
                {
                    edForm.DoSave(edForm.filePath);
                }
            }
        }

        private void saveAsBarButtonItem_ItemClick(object sender, ItemClickEventArgs e)
        {
            EditXtraForm edForm = (EditXtraForm)ActiveMdiChild;
            if (ActiveMdiChild is ProjectXtraForm)
            {
                if (saveProjectFileDialog.ShowDialog(this) == DialogResult.OK)
                {
                    edForm.DoSave(saveProjectFileDialog.FileName);
                }
            }
        }

        #endregion

        #region Settings

        private Point settLocation = new Point();
        private Size settSize = new Size();
        private FormWindowState settWindowState = FormWindowState.Normal;

        public bool ViewRegexTools
        {
            get { return regexToolsDockPanel.Visible; }
            set { viewRegexToolsBarButtonItem.Down = value; }
        }

        public bool ViewDebugInfo
        {
            get
            {
                return viewDebugInfoBarButtonItem.Down;
            }
            set
            {
                viewDebugInfoBarButtonItem.Down = value;
            }
        }

        public Point SettLocation
        {
            get
            {
                return settLocation;
            }
            set
            {
                settLocation = value;
                Location = value;
            }
        }

        public Size SettSize
        {
            get { return settSize; }
            set
            {
                settSize = value;
                Size = value;
            }
        }

        public FormWindowState SettWindowState
        {
            get { return settWindowState; }
            set
            {
                settWindowState = value;
                WindowState = value;
            }
        }

        private void MainXtraForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            /*foreach (Form mdiForm in MdiChildren)
            {
                if (mdiForm is ProjectXtraForm)
                {
                    ProjectXtraForm pxForm = (ProjectXtraForm) mdiForm;
                    pxForm.project.SaveToFile(Program.exePath + "current_project.pxcproj");
                    break;
                }
            }*/

            Program.sett.SaveControl(this, new string[]
            {
                "SettLocation",
                "SettSize",
                "SettWindowState",                
                "ViewDebugInfo",
                "ViewRegexTools"
            });
            Program.sett.Save(Program.exePath + "settings.xml");

            dockManager.SaveLayoutToXml(Program.exePath + "main_layout.xml");

            if (nodesCatStringFormat != null)
            {
                nodesCatStringFormat.Dispose();
                nodesCatStringFormat = null;
            }

            if (nodesDataView != null)
            {
                nodesTreeList.DataSource = null;
                if (nodesDataView.IsInitialized)
                {
                    nodesDataView.Dispose();                    
                }
                nodesDataView = null;
            }
        }

        protected override void OnMove(EventArgs e)
        {
            base.OnMove(e);
            if (WindowState == FormWindowState.Normal)
                settLocation = Location;
            if (WindowState != FormWindowState.Minimized)
                settWindowState = WindowState;            
        }

        protected override void OnSizeChanged(EventArgs e)
        {
            base.OnSizeChanged(e);
            if (WindowState == FormWindowState.Normal)
                settSize = Size;
            if (WindowState != FormWindowState.Minimized)
                settWindowState = WindowState;
        }

        #endregion

        #region WndProc

        protected override unsafe void WndProc(ref Message m)
        {

            if (m.Msg == (int)Win32.WindowsMessage.COPYDATA)
            {
                Win32.COPYDATASTRUCT data = (Win32.COPYDATASTRUCT)m.GetLParam(typeof(Win32.COPYDATASTRUCT));
                string str = new string((char*)(data.lpData), 0, data.cbData / 2);
                string[] strp = str.Split(';');
                if (strp.Length > 0)
                {
                    if (strp[0] == "add")
                    {
                        string addType = strp[1];
                        string addPath = strp[2];

                        
                    }
                }
                m.Result = new IntPtr(Win32.TRUE);
            }
            else
            {
                base.WndProc(ref m);
            }
        }

        #endregion

        private void timeUpdateTimer_Tick(object sender, EventArgs e)
        {
            timeBarStaticItem.Caption = DateTime.Now.ToString("hh:mm:ss");
        }

        private void outputDockPanel_Click(object sender, EventArgs e)
        {

        }

        private void viewResetLayoutBarButtonItem_ItemClick(object sender, ItemClickEventArgs e)
        {
            dockManager.RestoreFromXml("main_default_layout.xml");
        }

        private void errorsUserControl_ErrorRowClick(object sender, ErrorsDataSet.ErrorsRow eRow)
        {
            ProjectXtraForm myProjForm = null;
            ProjectItem cpItem = (ProjectItem) eRow.ProjectItem;
            CompilerError cErr = (CompilerError) eRow.CompilerError;
            foreach (Form cf in MdiChildren)
            {
                if (cf is ProjectXtraForm)
                {
                    ProjectXtraForm cpForm = (ProjectXtraForm) cf;
                    if (cpForm.project == cpItem.Project)
                    {
                        myProjForm = cpForm;
                        break;
                    }
                }
            }

            if (myProjForm != null)
            {
                myProjForm.Activate();
                myProjForm.projectDesignerControl_OpenItem(myProjForm, new ProjectItemEventArgs(cpItem));
                
                XtraTabPage tPage = myProjForm.pagesXtraTabControl.SelectedTabPage;
                if (tPage != null)
                {
                    ProjectItem pi = (ProjectItem) tPage.Tag;
                    if (pi.Type == ProjectItem.ProjectItemType.Script)
                    {
                        CodeEditorControl ceCont = (CodeEditorControl) tPage.Controls[0];
                        ceCont.Focus();
                        ceCont.AddErrorLine(cErr.Line - 1, cErr.Column, cErr.ErrorText, true);
                        
                    }
                }

                if (myProjForm.pagesXtraTabControl.SelectedTabPage != null)
                {
                    ProjectItem spItem = (ProjectItem) myProjForm.pagesXtraTabControl.SelectedTabPage.Tag;
                    if (spItem.Type == ProjectItem.ProjectItemType.Script)
                    {
                        myProjForm.pagesXtraTabControl.SelectedTabPage.Controls[0].Focus();
                    }
                }
            }            
        }


        private void regexToolsDockPanel_CustomButtonClick(object sender, DevExpress.XtraBars.Docking2010.ButtonEventArgs e)
        {
            if (e.Button.Properties.Caption == "Add")
            {
                XtraTabPage rtTabPage = new XtraTabPage();
                rtTabPage.Text = "RegEx Tool";
                RegexToolControl rtCont = new RegexToolControl();
                rtCont.Dock = DockStyle.Fill;
                rtTabPage.Controls.Add(rtCont);
                regexXtraTabControl.TabPages.Add(rtTabPage);
                regexXtraTabControl.SelectedTabPage = rtTabPage;
                rtCont.Run += rtCont_Run;
                SaveRegexTools();
            }
            else if (e.Button.Properties.Caption == "Remove")
            {
                if (regexXtraTabControl.SelectedTabPage != null)
                {
                    XtraTabPage sTabPage = regexXtraTabControl.SelectedTabPage;
                    regexXtraTabControl.TabPages.Remove(sTabPage);
                    sTabPage.Dispose();
                }
            }
        }

        void rtCont_Run(object sender, EventArgs e)
        {
            SaveRegexTools();
        }

        public void SaveRegexTools()
        {
            XmlDocument xDoc = new XmlDocument();
            xDoc.AppendChild(xDoc.CreateXmlDeclaration("1.0", "utf-8", "yes"));

            XmlElement rtsEl = xDoc.CreateElement("regex_tools");
            xDoc.AppendChild(rtsEl);

            foreach (XtraTabPage rtTabPage in regexXtraTabControl.TabPages)
            {
                RegexToolControl rtCont = (RegexToolControl) rtTabPage.Controls[0];
                XmlElement rtEl = Misc.CreateAppendXmlElement(rtsEl, "regex_tool");
                rtEl.SetAttribute("multi_line", rtCont.multilineCheckEdit.Checked.ToString());
                rtEl.SetAttribute("expr", WebUtility.HtmlEncode(rtCont.exprTextEdit.Text));
                rtEl.SetAttribute("src", System.Net.WebUtility.HtmlEncode(rtCont.srcRichTextBox.Text));
            }

            xDoc.Save("regex_tools.xml");
        }

        public void RestoreRegexTools()
        {            
            if (File.Exists("regex_tools.xml"))
            {
                XmlDocument xDoc = new XmlDocument();
                xDoc.Load("regex_tools.xml");

                XmlElement rtsEl = xDoc["regex_tools"];
                foreach (XmlElement rtEl in rtsEl.ChildNodes)
                {
                    XtraTabPage rtTabPage = new XtraTabPage();
                    rtTabPage.Text = "RegEx Tool";
                    RegexToolControl rtCont = new RegexToolControl();
                    rtCont.Dock = DockStyle.Fill;
                    rtTabPage.Controls.Add(rtCont);
                    rtCont.exprTextEdit.Text = WebUtility.HtmlDecode(rtEl.GetAttribute("expr"));
                    rtCont.srcRichTextBox.Text = WebUtility.HtmlDecode(rtEl.GetAttribute("src"));
                    rtCont.multilineCheckEdit.Checked =
                        bool.Parse(Null.StringFromDBNull(rtEl.GetAttribute("multi_line"), "False", true));
                    regexXtraTabControl.TabPages.Add(rtTabPage);
                    regexXtraTabControl.SelectedTabPage = rtTabPage;
                    rtCont.Run += rtCont_Run;                    
                }
            }
        }
    }
}