using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.Collections;
using System.IO;
using System.Threading;
using System.Xml;
namespace OutlookExpress_V1._._
{
    public partial class LeftGrid : Form
    {
        ArrayList attachments;
        ArrayList popAttachmentsIndex;
        Pop3Client pop = null;
        string email = "";
        int msg_id = 0;
        private ArrayList ContactList;
        private ListSortDirection prevSortDirection = ListSortDirection.Ascending;
        private string View;
        private int prevColIndex = 1;
        ArrayList attached_file_names;
        private int maxMail = 0;
        private string PSN = "";
        private string SSN = "";
        private string PP = "";
        private string SP = "";
        private string UN = "";
        private string PW = "";
        private int indexItem = 0;
        private string SelectedFolder = "PersonalFolder.xml";
        public LeftGrid()
        {
            InitializeComponent();
            this.attachments = new ArrayList();
            this.popAttachmentsIndex = new ArrayList();
            this.attached_file_names = new ArrayList();
        }

        private void showAll()
        {
            MailView.Visible = true;
            ContactView.Visible = true;
            CalenderView.Visible = true;
            NotesView.Visible = true;
            TaskView.Visible = true;
        }
        private void HideAll()
        {
            MailView.Visible = false;
            ContactView.Visible = false;
            CalenderView.Visible = false;
            NotesView.Visible = false;
            TaskView.Visible = false;
            calanderControl1.Visible = false;
            calanderControl2.Visible = false;
            calanderControl3.Visible = false;
            calanderControl4.Visible = false;
            calanderControl5.Visible = false;
            calanderControl6.Visible = false;
            calanderControl7.Visible = false;
        }

        private void LeftGrid_Load(object sender, EventArgs e)
        {
            GetMailServerSetting();
            ConnectEmails();
            HideAll();
            fillInboxList();
            arrangeByFromToolStripMenuItem_Click(sender, e);
            btnTasks_Click(sender, e);
        }

        private void btnMails_Click(object sender, EventArgs e)
        {
            HideAll();
            MailView.Visible = true;
            MailView.Dock = DockStyle.Fill;
            toolSelectedItem.Text = btnMails.Text;
            LoadFolder();
        }

        private void btnCalender_Click(object sender, EventArgs e)
        {
            HideAll();
            CalenderView.Visible = true;
            CalenderView.Dock = DockStyle.Top;
            calanderControl1.Visible = false;
            calanderControl1.Dock = DockStyle.Top;
            calanderControl2.Visible = false;
            calanderControl2.Dock = DockStyle.Top;
            calanderControl3.Visible = false;
            calanderControl3.Dock = DockStyle.Top;
            calanderControl4.Visible = false;
            calanderControl4.Dock = DockStyle.Top;
            calanderControl5.Visible = false;
            calanderControl5.Dock = DockStyle.Top;
            calanderControl6.Visible = false;
            calanderControl6.Dock = DockStyle.Top;
            calanderControl7.Visible = false;
            calanderControl7.Dock = DockStyle.Top;
            toolSelectedItem.Text = btnCalender.Text;
            LoadCalander();
        }

        private void btnTasks_Click(object sender, EventArgs e)
        {
            HideAll();
            CalenderView.Visible = false;
            CalenderView.Dock = DockStyle.Top;
            calanderControl1.Visible = false;
            calanderControl1.Dock = DockStyle.Top;
            calanderControl2.Visible = false;
            calanderControl2.Dock = DockStyle.Top;
            calanderControl3.Visible = false;
            calanderControl3.Dock = DockStyle.Top;
            calanderControl4.Visible = false;
            calanderControl4.Dock = DockStyle.Top;
            calanderControl5.Visible = false;
            calanderControl5.Dock = DockStyle.Top;
            calanderControl6.Visible = false;
            calanderControl6.Dock = DockStyle.Top;
            calanderControl7.Visible = false;
            calanderControl7.Dock = DockStyle.Top;
            toolSelectedItem.Text = btnTasks.Text;
            LoadCalander();
        }

        private void btnNotes_Click(object sender, EventArgs e)
        {
            HideAll();
            NotesView.Visible = true;
            NotesView.Dock = DockStyle.Fill;
            toolSelectedItem.Text = btnNotes.Text;
            LoadNotes();
        }

        private void btnContact_Click(object sender, EventArgs e)
        {
            HideAll();
            ContactView.Visible = true;
            ContactView.Dock = DockStyle.Fill;
            toolSelectedItem.Text = btnContact.Text;
            LoadContact();
        }

        private void toolUpArrow_Click(object sender, EventArgs e)
        {
            HideAll();
        }

        private void newToolStripButton_Click(object sender, EventArgs e)
        {
            SendMail sm = new SendMail();
            sm.Show(this);
        }

        private void mailMessageToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SendMail sm = new SendMail();
            sm.Show(this);
        }

        private void contactToolStripMenuItem2_Click(object sender, EventArgs e)
        {
            HideAll();
            ContactView.Visible = true;
            ContactView.Dock = DockStyle.Fill;
            toolSelectedItem.Text = btnContact.Text;
        }

        private void calanderToolStripMenuItem_Click(object sender, EventArgs e)
        {
            HideAll();
            CalenderView.Visible = true;
            CalenderView.Dock = DockStyle.Fill;
            toolSelectedItem.Text = btnCalender.Text;
        }

        private void notesToolStripMenuItem2_Click(object sender, EventArgs e)
        {
            HideAll();
            NotesView.Visible = true;
            NotesView.Dock = DockStyle.Fill;
            toolSelectedItem.Text = btnNotes.Text;
        }

        private void tasksToolStripMenuItem_Click(object sender, EventArgs e)
        {
            HideAll();
            TaskView.Visible = true;
            TaskView.Dock = DockStyle.Fill;
            toolSelectedItem.Text = btnTasks.Text;
        }

        private void mailsToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            HideAll();
            MailView.Visible = true;
            MailView.Dock = DockStyle.Fill;
            toolSelectedItem.Text = btnMails.Text;
        }

        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void toolSendReceive_Click(object sender, EventArgs e)
        {
            frmSendReceive sr = new frmSendReceive();
            sr.Show(this);
        }

        private void toolAddress_Click(object sender, EventArgs e)
        {

        }

        private void newMailMessageToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SendMail sm = new SendMail();
            sm.Show(this);
        }

        private void sendReceiveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmSendReceive sr = new frmSendReceive();
            sr.Show(this);
        }

        private void accountSettingsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AddContact fs = new AddContact();
            fs.ShowDialog(this);
        }

        private void mailsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            HideAll();
            MailView.Visible = true;
            MailView.Dock = DockStyle.Fill;
            toolSelectedItem.Text = btnMails.Text;
        }

        private void calanderToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            HideAll();
            CalenderView.Visible = true;
            CalenderView.Dock = DockStyle.Fill;
            toolSelectedItem.Text = btnCalender.Text;
        }

        private void contactToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            HideAll();
            ContactView.Visible = true;
            ContactView.Dock = DockStyle.Fill;
            toolSelectedItem.Text = btnContact.Text;
        }

        private void notesToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            HideAll();
            NotesView.Visible = true;
            NotesView.Dock = DockStyle.Fill;
            toolSelectedItem.Text = btnNotes.Text;
        }

        private void folderListToolStripMenuItem_Click(object sender, EventArgs e)
        {
            HideAll();
            MailView.Visible = true;
            MailView.Dock = DockStyle.Fill;
            toolSelectedItem.Text = btnMails.Text;
        }
        private void fillInboxList()
        {
            ContactList = new ArrayList();
            DataSet ds = new DataSet();
            DataTable dt = new DataTable();
            ds.ReadXml(@"PersonalFolder.xml");
            dt = ds.Tables[0];

            ContactList = new ArrayList();
            for (int i = 1; i < dt.Rows.Count; i++)
            {
                string s3 = DateTime.Parse(dt.Rows[i][5].ToString().Trim()).ToShortDateString() + " - " + DateTime.Parse(dt.Rows[i][5].ToString().Trim()).ToShortTimeString();
                string s4 = DateTime.Parse(dt.Rows[i][5].ToString().Trim()).ToLongDateString();
                PerlProperties p = new PerlProperties();
                string s = p.GetDateName(s3, s4);
                if (maxMail < int.Parse(dt.Rows[i][0].ToString().Trim()))
                {
                    maxMail = int.Parse(dt.Rows[i][0].ToString().Trim());
                }
                ContactList.Add(new ContactInfo(int.Parse(dt.Rows[i][0].ToString()), dt.Rows[i][1].ToString(), dt.Rows[i][2].ToString(), dt.Rows[i][3].ToString(), dt.Rows[i][4].ToString(), DateTime.Parse(dt.Rows[i][5].ToString().Trim()).ToShortDateString(), DateTime.Parse(dt.Rows[i][5].ToString().Trim()).ToShortTimeString(), dt.Rows[i][6].ToString(), dt.Rows[i][7].ToString(), dt.Rows[i][8].ToString(), dt.Rows[i][9].ToString(), s));
            }
            menuUnboundContactListClick();

        }
        private void menuUnboundContactListClick()
        {
            foreach (ContactInfo obj in ContactList)
            {
                OutlookGridRow row = new OutlookGridRow();
                row.CreateCells(outlookGrid1, obj.Id, obj.To, obj.From, obj.Cc, obj.Subject, obj.Date, obj.Time, obj.Size, obj.Folder, obj.Read, obj.Priority, obj.Days);
                outlookGrid1.Rows.Add(row);
            }
            double l = outlookGrid1.Width * 0.1;
            string m = l.ToString();
            string[] n = m.Split('.');
            int i = int.Parse(n[0]);
            outlookGrid1.Columns[2].Width = i * 3 - 30;
            outlookGrid1.Columns[4].Width = i * 4 - 10;
        }
        private void arrangeByDateToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                DataGridViewCellEventArgs e1 = new DataGridViewCellEventArgs(11, -1);
                outlookGrid1_CellClick(sender, e1);
                toolStripDropDownButton1.Text = "Arranged By " + arrangeByDateToolStripMenuItem.Text;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

        private void arrangeByFromToolStripMenuItem_Click(object sender, EventArgs e)
        {


            DataGridViewCellEventArgs e1 = new DataGridViewCellEventArgs(2, -1);
            outlookGrid1_CellClick(sender, e1);
            toolStripDropDownButton1.Text = "Arranged By " + arrangeByFromToolStripMenuItem.Text;

        }

        private void arrangeByToToolStripMenuItem_Click(object sender, EventArgs e)
        {


            DataGridViewCellEventArgs e1 = new DataGridViewCellEventArgs(1, -1);
            outlookGrid1_CellClick(sender, e1);
            toolStripDropDownButton1.Text = "Arranged By " + arrangeByToToolStripMenuItem.Text;

        }

        private void arrangeBySubjectToolStripMenuItem_Click(object sender, EventArgs e)
        {

            DataGridViewCellEventArgs e1 = new DataGridViewCellEventArgs(4, -1);
            outlookGrid1_CellClick(sender, e1);
            toolStripDropDownButton1.Text = "Arranged By " + arrangeBySubjectToolStripMenuItem.Text;

        }

        private void outlookGrid1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0 && e.ColumnIndex >= 0)
            {

                ListSortDirection direction = ListSortDirection.Ascending;
                if (e.ColumnIndex == prevColIndex) // reverse sort order
                    direction = prevSortDirection == ListSortDirection.Descending ? ListSortDirection.Ascending : ListSortDirection.Descending;
                prevColIndex = e.ColumnIndex;
                prevSortDirection = direction;
                outlookGrid1.GroupTemplate.Column = outlookGrid1.Columns[e.ColumnIndex];
                outlookGrid1.Sort(outlookGrid1.Columns[e.ColumnIndex], direction);
            }


        }

        private void LoadFolder()
        {
            MailView.Nodes.Clear();
            if (!File.Exists("PerlLookUpF.xml"))
            {
                PerlProperties p = new PerlProperties();
                p.CreateFolder();
                try
                {
                    DataSet ds = new DataSet();
                    ds.ReadXml(@"PerlLookUpF.xml");
                    DataTable dt = new DataTable();
                    dt = ds.Tables[0];
                    MailView.Nodes.Add("Personal Folder");
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        MailView.Nodes[0].Nodes.Add(dt.Rows[i][0].ToString());
                    }
                    MailView.Nodes.Add("Archive Folder");
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        MailView.Nodes[1].Nodes.Add(dt.Rows[i][0].ToString());
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            else
            {
                try
                {
                    DataSet ds = new DataSet();
                    ds.ReadXml(@"PerlLookUpF.xml");
                    DataTable dt = new DataTable();
                    dt = ds.Tables[0];
                    MailView.Nodes.Add("Personal Folder");
                    MailView.Nodes[0].ImageIndex = 0;
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        MailView.Nodes[0].Nodes.Add(dt.Rows[i][0].ToString());
                        MailView.Nodes[0].Nodes[i].ImageIndex = i + 1;

                    }
                    MailView.Nodes.Add("Archive Folder");
                    MailView.Nodes[1].ImageIndex = 9;
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        MailView.Nodes[1].Nodes.Add(dt.Rows[i][0].ToString());
                        MailView.Nodes[1].Nodes[i].ImageIndex = i + 1;
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }

            }
            MailView.ExpandAll();
        }

        private void LoadTask()
        {
            TaskView.Nodes.Clear();
            if (!File.Exists("PerlLookUpTask.xml"))
            {
                PerlProperties p = new PerlProperties();
                p.CreateTask();
            }
            try
            {
                DataSet ds = new DataSet();
                ds.ReadXml(@"PerlLookUpTask.xml");
                DataTable dt = new DataTable();
                dt = ds.Tables[0];
                TaskView.Nodes.Add("Today's Task");
                TaskView.Nodes.Add("Future Task");
                TaskView.Nodes.Add("Older Task");
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    DateTime d1 = DateTime.Parse(dt.Rows[i][0].ToString());
                    DateTime d2 = DateTime.Now;
                    TimeSpan d1Tod2 = d1.Subtract(d2);
                    if (d1Tod2.Days == 0)
                    {
                        TaskView.Nodes[0].ForeColor = Color.Red;
                        TaskView.Nodes[0].Nodes.Add("Time: " + dt.Rows[i][1].ToString() + " " + "Detail: " + dt.Rows[i][2].ToString() + " " + "Status: " + dt.Rows[i][3].ToString());
                    }
                    else
                    {


                        if (d1Tod2.Days > 0)
                        {
                            TaskView.Nodes[1].ForeColor = Color.GreenYellow;
                            TaskView.Nodes[1].Nodes.Add("Time: " + dt.Rows[i][1].ToString() + " " + "Detail: " + dt.Rows[i][2].ToString() + " " + "Status: " + dt.Rows[i][3].ToString());
                        }
                        else
                        {
                            TaskView.Nodes[2].ForeColor = Color.Yellow;
                            TaskView.Nodes[2].Nodes.Add("Time: " + dt.Rows[i][1].ToString() + " " + "Detail: " + dt.Rows[i][2].ToString() + " " + "Status: " + dt.Rows[i][3].ToString());
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            TaskView.Nodes[0].Expand();
        }

        private void LoadCalander()
        {
            if (!File.Exists("PerlLookUpTask.xml"))
            {
                PerlProperties p = new PerlProperties();
                p.CreateTask();
            }
            try
            {
                DataSet ds = new DataSet();
                ds.ReadXml(@"PerlLookUpTask.xml");
                DataTable dt = new DataTable();
                dt = ds.Tables[0];
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    DateTime d1 = DateTime.Parse(dt.Rows[i][0].ToString());
                    DateTime d2 = CalenderView.SelectionStart;
                    TimeSpan d1Tod2 = d1.Subtract(d2);
                    if (d1Tod2.Days == 0)
                    {
                        if (calanderControl7.Visible == false)
                        {
                            calanderControl7.SetValue(dt.Rows[i][2].ToString(), "Date: " + d1.ToShortDateString() + " " + "Time: " + d1.ToShortTimeString() + " " + "Status: " + dt.Rows[i][3].ToString());
                            calanderControl7.Visible = true;
                        }
                        else
                        {
                            if (calanderControl6.Visible == false)
                            {
                                calanderControl6.SetValue(dt.Rows[i][2].ToString(), "Date: " + d1.ToShortDateString() + " " + "Time: " + d1.ToShortTimeString() + " " + "Status: " + dt.Rows[i][3].ToString());
                                calanderControl6.Visible = true;
                            }
                            else
                            {
                                if (calanderControl5.Visible == false)
                                {
                                    calanderControl5.SetValue(dt.Rows[i][2].ToString(), "Date: " + d1.ToShortDateString() + " " + "Time: " + d1.ToShortTimeString() + " " + "Status: " + dt.Rows[i][3].ToString());
                                    calanderControl5.Visible = true;
                                }
                                else
                                {
                                    if (calanderControl4.Visible == false)
                                    {
                                        calanderControl4.SetValue(dt.Rows[i][2].ToString(), "Date: " + d1.ToShortDateString() + " " + "Time: " + d1.ToShortTimeString() + " " + "Status: " + dt.Rows[i][3].ToString());
                                        calanderControl4.Visible = true;
                                    }
                                    else
                                    {
                                        if (calanderControl3.Visible == false)
                                        {
                                            calanderControl3.SetValue(dt.Rows[i][2].ToString(), "Date: " + d1.ToShortDateString() + " " + "Time: " + d1.ToShortTimeString() + " " + "Status: " + dt.Rows[i][3].ToString());
                                            calanderControl3.Visible = true;
                                        }
                                        else
                                        {
                                            if (calanderControl2.Visible == false)
                                            {
                                                calanderControl2.SetValue(dt.Rows[i][2].ToString(), "Date: " + d1.ToShortDateString() + " " + "Time: " + d1.ToShortTimeString() + " " + "Status: " + dt.Rows[i][3].ToString());
                                                calanderControl2.Visible = true;
                                            }
                                            else
                                            {
                                                if (calanderControl1.Visible == false)
                                                {
                                                    calanderControl1.SetValue(dt.Rows[i][2].ToString(), "Date: " + d1.ToShortDateString() + " " + "Time: " + d1.ToShortTimeString() + " " + "Status: " + dt.Rows[i][3].ToString());
                                                    calanderControl1.Visible = true;
                                                }
                                                else
                                                {

                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

        private void LoadNotes()
        {
            NotesView.Nodes.Clear();
            if (!File.Exists("PerlLookUpNotes.xml"))
            {
                PerlProperties p = new PerlProperties();
                p.CreateNotes();
            }
            try
            {
                DataSet ds = new DataSet();
                ds.ReadXml(@"PerlLookUpNotes.xml");
                DataTable dt = new DataTable();
                dt = ds.Tables[0];
                for (int i = 0; i < dt.Rows.Count; i++)
                {

                    NotesView.Nodes.Add(dt.Rows[i][0].ToString());

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void LoadContact()
        {
            ContactView.Nodes.Clear();
            if (!File.Exists("PerlLookUpContact.xml"))
            {
                PerlProperties p = new PerlProperties();
                p.CreateContact();
            }
            try
            {
                DataSet ds = new DataSet();
                ds.ReadXml(@"PerlLookUpContact.xml");
                DataTable dt = new DataTable();
                dt = ds.Tables[0];
                for (int i = 0; i < dt.Rows.Count; i++)
                {

                    ContactView.Nodes.Add(dt.Rows[i][0].ToString() + " " + dt.Rows[i][1].ToString());

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void outlookGrid1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void Add_Click(object sender, EventArgs e)
        {
            AddClick();
        }

        private void Update_Click(object sender, EventArgs e)
        {
            UpdateClick();
        }

        private void Refresh_Click(object sender, EventArgs e)
        {
            btnContact_Click(sender, e);
        }

        private void ContactView_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            UpdateClick();
        }
        private void AddClick()
        {
            DataSet ds = new DataSet();
            ds.ReadXml(@"PerlLookUpContact.xml");
            frmContact fc = new frmContact(ds, "Add", 0);
            fc.Show(this);
        }

        private void UpdateClick()
        {
            DataSet ds = new DataSet();
            ds.ReadXml(@"PerlLookUpContact.xml");
            frmContact fc = new frmContact(ds, "Update", ContactView.SelectedNode.Index);
            fc.Show(this);
        }
        private void AddClickTask()
        {
            DataSet ds = new DataSet();
            ds.ReadXml(@"PerlLookUpTask.xml");
            AddTasks fc = new AddTasks(ds, "Add", 0);
            fc.Show(this);
        }

        private void UpdateClickTask()
        {
            DataSet ds = new DataSet();
            ds.ReadXml(@"PerlLookUpTask.xml");
            AddTasks fc = new AddTasks(ds, "Update", 0);
            fc.Show(this);
        }
        private void AddClickNotes()
        {
            DataSet ds = new DataSet();
            ds.ReadXml(@"PerlLookUpNotes.xml");
            AddNotes fc = new AddNotes(ds, "Add", 0);
            fc.Show(this);
        }

        private void UpdateClickNotes()
        {
            DataSet ds = new DataSet();
            ds.ReadXml(@"PerlLookUpNotes.xml");
            AddNotes fc = new AddNotes(ds, "Update", NotesView.SelectedNode.Index);
            fc.Show(this);
        }
        private void TaskAdd_Click(object sender, EventArgs e)
        {
            AddClickTask();
        }

        private void TaskUpdate_Click(object sender, EventArgs e)
        {
            UpdateClickTask();
        }

        private void TaskDelete_Click(object sender, EventArgs e)
        {

        }

        private void TaskRefresh_Click(object sender, EventArgs e)
        {
            btnTasks_Click(sender, e);
        }

        private void NotesAdd_Click(object sender, EventArgs e)
        {
            AddClickNotes();
        }

        private void NotesUpdate_Click(object sender, EventArgs e)
        {
            UpdateClickNotes();
        }

        private void NotesDelete_Click(object sender, EventArgs e)
        {

        }

        private void NotesRefresh_Click(object sender, EventArgs e)
        {
            btnNotes_Click(sender, e);
        }

        private void CalenderView_DateChanged(object sender, DateRangeEventArgs e)
        {
            btnCalender_Click(sender, e);
        }

        private void outlookGrid1_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex > 0 && e.ColumnIndex >= 0)
            {

                try
                {
                    int index = e.RowIndex;
                    index = index + 1;
                    this.email = "";
                    this.msg_id = int.Parse(outlookGrid1.Rows[e.RowIndex].Cells[0].Value.ToString());
                    this.PopMessage.DocumentText = "<html></html>";
                    this.PopAttachments.Items.Clear();
                    this.attached_file_names.Clear();
                    this.popAttachmentsIndex.Clear();
                    FetchEmailCallBack();
                }
                catch
                {
                }
            }
        }
        private void FetchEmailCallBack()
        {
            try
            {
                this.email = this.pop.FetchEmail(this.msg_id);
                this.UpdatePopMessageHeader(this.pop.From, this.pop.To, this.pop.Subject, this.pop.CC, this.pop.Date);

                string content = "";
                string content_type = "";
                string attached_file_name = "";
                bool isHtmlIncluded = false;
                int plain_text_message_section = -1;

                for (int i = 1; i <= this.pop.MailSections; i++)
                {
                    this.pop.GetMailSection(i, ref content, ref content_type, ref attached_file_name);

                    if (content_type.ToLower().Equals("text/html"))
                    {
                        this.WritePopMessage(content);
                        isHtmlIncluded = true;
                    }
                    else if (content_type.ToLower().Equals("base64"))
                    {
                        ListViewItem item = new ListViewItem(attached_file_name);
                        item.ImageIndex = 0;
                        attached_file_names.Add(item);
                        this.popAttachmentsIndex.Add(i);
                    }
                    else if (content_type.ToLower().Equals("text/plain"))
                    {
                        plain_text_message_section = i;
                    }
                }

                this.InsertPopAttachedFileNames(attached_file_names);

                if (isHtmlIncluded == false && plain_text_message_section != -1)
                {
                    this.pop.GetMailSection(plain_text_message_section, ref content, ref content_type, ref attached_file_name);
                    this.WritePopMessage(content);
                }


            }
            catch (Pop3ClientException err)
            {
                MessageBox.Show(this, err.ErrorMessage, "Inbox", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void UpdatePopMessageHeader(string from, string to, string subject, string cc, string date)
        {
            if (this.lstTo.InvokeRequired || this.lblSubject.InvokeRequired || this.lstCC.InvokeRequired)
            {
                UpdatePopMessageHeaderEventHandler obj = new UpdatePopMessageHeaderEventHandler(this.UpdatePopMessageHeader);
                this.Invoke(obj, new object[] { from, to, subject, cc, date });
            }
            else
            {
                lstTo.Text = "";
                lstCC.Text = "";
                lblSubject.Text = subject.Trim();
                string s = to.Trim();
                string s1 = from.Trim();
                string s2 = cc.Trim();
                s = s.Replace("\r\n\t", " ");
                s = s.Substring(0, s.IndexOf("\r\n"));
                s1 = s1.Replace("\n\t", " ");
                if (s2 != "")
                {
                    s2 = s2.Replace("\r\n\t", " ");
                    s2 = s2.Substring(0, s2.IndexOf("\r\n"));
                    string[] a2 = s2.Split(',');
                    lstCC.Text = a2[0];
                    for (int mm = 1; mm <= a2.GetUpperBound(0); mm++)
                    {
                        lstCC.Text = lstCC.Text + "; " + a2[mm];
                    }
                }

                string[] a = s.Split(',');
                lstTo.Text = a[0];
                for (int mn = 1; mn <= a.GetUpperBound(0); mn++)
                {
                    lstTo.Text = lstTo.Text + "; " + a[mn];
                }
                lblFrom.Text = s1;

                lbldate.Text = DateTime.Parse(date.ToString().Trim()).ToLongDateString() + " - " + DateTime.Parse(date).ToLongTimeString();
                if (lstCC.Text == "")
                {
                    lblCC.Visible = false;
                    lstCC.Visible = false;
                }
                else
                {
                    lblCC.Visible = true;
                    lstCC.Visible = true;
                }

            }
        }
        private void WritePopMessage(string content)
        {
            if (this.PopMessage.InvokeRequired)
            {
                WritePopMessageEventHandler obj = new WritePopMessageEventHandler(this.WritePopMessage);
                this.Invoke(obj, new object[] { content });
            }
            else
            {
                this.PopMessage.DocumentText = content.Trim();
            }
        }
        private void ClearPopAttachments()
        {
            if (this.PopAttachments.InvokeRequired)
            {
                ClearPopAttachmentsEventHandler obj = new ClearPopAttachmentsEventHandler(this.ClearPopAttachments);
                this.Invoke(obj, new object[] { });
            }
            else
            {
                this.PopAttachments.Items.Clear();
            }
        }
        private delegate void EnableDisableEventHandler(bool enable);
        private delegate void InboxItemEventHandler(ListViewItem item);
        private delegate void InsertPopAttachedFileNamesEventHandler(ArrayList attached_file_names);
        private void InsertPopAttachedFileNames(ArrayList attached_file_names)
        {
            if (this.outlookGrid1.InvokeRequired)
            {
                InsertPopAttachedFileNamesEventHandler obj = new InsertPopAttachedFileNamesEventHandler(this.InsertPopAttachedFileNames);
                this.Invoke(obj, new object[] { attached_file_names });
            }
            else
            {
                this.PopAttachments.Items.Clear();
                for (int i = 0; i < attached_file_names.Count; i++)
                {
                    this.PopAttachments.Items.Add((ListViewItem)attached_file_names[i]);
                }
            }
        }
        private delegate void ClearPopAttachmentsEventHandler();
        private delegate void WritePopMessageEventHandler(string content);
        private delegate void UpdateStatusBarEventHandler(string text);
        private void UpdateStatusBar(string text)
        {
            if (this.statusStrip.InvokeRequired)
            {
                UpdateStatusBarEventHandler obj = new UpdateStatusBarEventHandler(this.UpdateStatusBar);
                this.Invoke(obj, new object[] { text });
            }
            else
            {
                this.ProgressLabel.Text = text;
            }
        }
        private delegate void UpdatePopMessageHeaderEventHandler(string from, string to, string subject, string cc, string date);
        private void GetMailServerSetting()
        {
            try
            {
                if (File.Exists("PerlLookUpS.xml"))
                {
                    DataSet ds = new DataSet();
                    ds.ReadXml(@"PerlLookUpS.xml");
                    DataTable dt = new DataTable();
                    dt = ds.Tables[0];
                    PSN = dt.Rows[0][0].ToString();
                    PP = dt.Rows[0][1].ToString();
                    SSN = dt.Rows[0][2].ToString();
                    SP = dt.Rows[0][3].ToString();
                    UN = dt.Rows[0][4].ToString();
                    PW = dt.Rows[0][5].ToString();
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private void ConnectEmails()
        {
            try
            {
                Pop3Client pop_client = new Pop3Client();
                pop_client.Pop3Server = PSN;
                pop_client.Pop3Port = Convert.ToInt32(PP);
                pop_client.UserName = UN;
                pop_client.Password = PW;

                pop_client.ConnectionEstablishing += new ConnectEventHandler(this.pop_ConnectionEstablishing);
                pop_client.ConnectionEstablished += new ConnectEventHandler(this.pop_ConnectionEstablished);
                pop_client.AuthenticationBegan += new AuthenticateEventHandler(this.pop_AuthenticationBegan);
                pop_client.AuthenticationFinished += new AuthenticateEventHandler(this.pop_AuthenticationFinished);
                pop_client.StartedDataReceiving += new DataReceivingEventHandler(this.pop_StartedDataReceiving);
                pop_client.EndedDataReceiving += new DataReceivingEventHandler(this.pop_EndedDataReceiving);
                pop_client.Disconnected += new DisconnectEventHandler(this.pop_Disconnected);

                this.pop = pop_client;

                pop_client.Connect();
                pop_client.GetMailBoxDetails();   //it sets the TotalEmails and TotalEmailSize properties
            }
            catch (SmtpClientException err)
            {
                MessageBox.Show(this, err.ErrorMessage, "Inbox", MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.UpdateStatusBar("Inbox");
            }
        }

        private void pop_Disconnected(object sender, string Server)
        {
            if (this.statusStrip.InvokeRequired)
            {
                DisconnectEventHandler discon = new DisconnectEventHandler(this.pop_Disconnected);
                this.Invoke(discon, new object[] { sender, Server });
            }
            else
            {
                this.ProgressLabel.Text = "Disconnected with the pop server \"" + Server + "\"";
                Thread.Sleep(500);
                this.ProgressLabel.Text = "Inbox";
            }
        }

        private void pop_EndedDataReceiving(object sender)
        {
            if (this.statusStrip.InvokeRequired)
            {
                DataReceivingEventHandler data = new DataReceivingEventHandler(this.pop_EndedDataReceiving);
                this.Invoke(data, new object[] { sender });
            }
            else
            {
                this.ProgressLabel.Text = "Email message has received";
            }
        }

        private void pop_StartedDataReceiving(object sender)
        {
            if (this.statusStrip.InvokeRequired)
            {
                DataReceivingEventHandler data = new DataReceivingEventHandler(this.pop_StartedDataReceiving);
                this.Invoke(data, new object[] { sender });
            }
            else
            {
                this.ProgressLabel.Text = "Receiving email message";
            }
        }

        private void pop_AuthenticationFinished(object sender, string userName)
        {
            if (this.statusStrip.InvokeRequired)
            {
                AuthenticateEventHandler auth = new AuthenticateEventHandler(this.pop_AuthenticationFinished);
                this.Invoke(auth, new object[] { sender, userName });
            }
            else
            {
                this.ProgressLabel.Text = "Verification is completed";
            }
        }

        private void pop_AuthenticationBegan(object sender, string userName)
        {
            if (this.statusStrip.InvokeRequired)
            {
                AuthenticateEventHandler auth = new AuthenticateEventHandler(this.pop_AuthenticationBegan);
                this.Invoke(auth, new object[] { sender, userName });
            }
            else
            {
                this.ProgressLabel.Text = "Verifying user name and password";
            }
        }

        private void pop_ConnectionEstablished(object sender, string Server, int Port)
        {
            if (this.statusStrip.InvokeRequired)
            {
                ConnectEventHandler con = new ConnectEventHandler(this.pop_ConnectionEstablished);
                this.Invoke(con, new object[] { sender, Server, Port });
            }
            else
            {
                this.ProgressLabel.Text = "Connection is established with the pop server \"" + Server + "\"";
            }
        }

        private void pop_ConnectionEstablishing(object sender, string Server, int Port)
        {
            if (this.statusStrip.InvokeRequired)
            {
                ConnectEventHandler con = new ConnectEventHandler(this.pop_ConnectionEstablishing);
                this.Invoke(con, new object[] { sender, Server, Port });
            }
            else
            {
                this.ProgressLabel.Text = "Connecting to pop server \"" + Server + "\" on port " + Port;
            }
        }
    }
    public class DataRowComparer : IComparer
    {
        ListSortDirection direction;
        int columnIndex;

        public DataRowComparer(int columnIndex, ListSortDirection direction)
        {
            this.columnIndex = columnIndex;
            this.direction = direction;
        }

        #region IComparer Members

        public int Compare(object x, object y)
        {

            DataRow obj1 = (DataRow)x;
            DataRow obj2 = (DataRow)y;
            return string.Compare(obj1[columnIndex].ToString(), obj2[columnIndex].ToString()) * (direction == ListSortDirection.Ascending ? 1 : -1);
        }
        #endregion
    }
    public class ContactInfoComparer : IComparer
    {
        private int propertyIndex;
        ListSortDirection direction;

        public ContactInfoComparer(int propertyIndex, ListSortDirection direction)
        {
            this.propertyIndex = propertyIndex;
            this.direction = direction;
        }

        #region IComparer Members

        public int Compare(object x, object y)
        {
            ContactInfo obj1 = (ContactInfo)x;
            ContactInfo obj2 = (ContactInfo)y;

            switch (propertyIndex)
            {
                case 1:
                    return CompareStrings(obj1.To, obj2.To);
                case 2:
                    return CompareStrings(obj1.From, obj2.From);
                case 3:
                    return CompareStrings(obj1.Cc, obj2.Cc);
                case 4:
                    return CompareStrings(obj1.Subject, obj2.Subject);
                case 5:
                    return CompareStrings(obj1.Date, obj2.Date);
                case 6:
                    return CompareStrings(obj1.Time, obj2.Time);
                case 7:
                    return CompareStrings(obj1.Size, obj2.Size);
                case 8:
                    return CompareStrings(obj1.Folder, obj2.Folder);
                case 9:
                    return CompareStrings(obj1.Read, obj2.Read);
                case 10:
                    return CompareStrings(obj1.Priority, obj2.Priority);
                default:
                    return CompareStrings(obj1.Days, obj2.Days);
            }
        }
        #endregion

        private int CompareStrings(string val1, string val2)
        {
            return string.Compare(val1, val2) * (direction == ListSortDirection.Ascending ? 1 : -1);
        }

        private int CompareDates(DateTime val1, DateTime val2)
        {
            if (val1 > val2) return (direction == ListSortDirection.Ascending ? 1 : -1);
            if (val1 < val2) return (direction == ListSortDirection.Ascending ? -1 : 1);
            return 0;
        }

        private int CompareNumbers(double val1, double val2)
        {
            if (val1 > val2) return (direction == ListSortDirection.Ascending ? 1 : -1);
            if (val1 < val2) return (direction == ListSortDirection.Ascending ? -1 : 1);
            return 0;
        }
    }
    public class ContactInfo
    {
        public ContactInfo()
        {
        }
        public ContactInfo(int id, string to, string from, string cc, string subject, string date, string time, string size, string folder, string read, string priority, string days)
        {
            this.id = id;
            this.to = to;
            this.from = from;
            this.cc = cc;
            this.subject = subject;
            this.date = date;
            this.read = read;
            this.time = time;
            this.size = size;
            this.folder = folder;
            this.priority = priority;
            this.days = days;
        }

        private int id;

        public int Id
        {
            get { return id; }
            set { id = value; }
        }
        private string to;

        public string To
        {
            get { return to; }
            set { to = value; }
        }
        private string from;

        public string From
        {
            get { return from; }
            set { from = value; }
        }
        private string subject;

        public string Subject
        {
            get { return subject; }
            set { subject = value; }
        }
        private string date;

        public string Date
        {
            get { return date; }
            set { date = value; }
        }
        private string cc;

        public string Cc
        {
            get { return cc; }
            set { cc = value; }
        }
        private string read;

        public string Read
        {
            get { return read; }
            set { read = value; }
        }
        private string days;

        public string Days
        {
            get { return days; }
            set { days = value; }
        }
        private string time;

        public string Time
        {
            get { return time; }
            set { time = value; }
        }
        private string size;

        public string Size
        {
            get { return size; }
            set { size = value; }
        }
        private string folder;

        public string Folder
        {
            get { return folder; }
            set { folder = value; }
        }
        private string priority;

        public string Priority
        {
            get { return priority; }
            set { priority = value; }
        }
    }
}