using System;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
using Baza_Reklam.Classes;
using Baza_Reklam.Classes.Helpers;
using Baza_Reklam.Classes.Interfaces;

namespace Baza_Reklam
{
    public partial class OrdersForm : Form, IForm
    {
        private static OrdersForm orderForm;
        private readonly SqlDataAdapter sqlDataAdapter;
        private readonly SqlCommand command;

        bool commandExecuted;

        /// <summary>
        /// Do każdego filtrowania musi być dodany warunek  (r.SZER * r.WYS)<>0 !!!
        /// </summary>
        private const string query = " SELECT TOP 1000 R.*, O.OD, O.DO, DATEPART(year, NR.DATA_W), DATEPART(month, NR.DATA_W)," +
                                     " NR.DATA_W AS '1emisja', A.Symbol AS agencja, (r.[CENA JEDN] - r.[RABAT WARTOŚĆ]) / r.SZER * r.WYS AS [CENA MODUŁU],NM.CENA_MIN, NM.CENA, K.firstname, Z.idZamowienia " +
                                     " FROM dbo.AGENCI A2 JOIN dbo.AGENCJE A ON A.Id_agencji = A2.ID_AGENCJI " +
                                     " RIGHT JOIN REKLAMA R ON A2.Symbol = R.[SYMBOL AKWIZYTORA] " +
                                     " LEFT JOIN dbo.VIEW_REKLAMA_OD_DO O ON R.ReklamaID = O.ReklamaId" +
                                     " LEFT JOIN NR ON R.TYTUŁ = NR.TYT AND O.OD = NR.NRW " +
                                     " LEFT OUTER JOIN [NAZWY MODUŁÓW] NM ON r.MOD_TYP = NM.MOD_TYP AND r.[Tytuł] = NM.Tytul" +
                                     " LEFT OUTER JOIN dbo.KLIENCI AS K ON R.customerId=K.CustomerId " +
                                     " LEFT OUTER JOIN dbo.Zamowienia AS Z ON R.idZamowienia=Z.idZamowienia ";

        protected REKLAMADataSet.ReklamyZestawienieRow Reklama
        {
            get
            {
                if (reklamyZestawienieBindingSource.Current == null) return null;
                DataRowView row = (DataRowView)reklamyZestawienieBindingSource.Current;

                return (REKLAMADataSet.ReklamyZestawienieRow)row.Row;
            }
        }


        public static OrdersForm getOrderForm(MDIBazaReklam parent)
        {
            if (orderForm == null)
            {
                orderForm = new OrdersForm(parent);
            }
            return orderForm;
        }

        private OrdersForm(Form parent)
        {
            InitializeComponent();

            MdiParent = parent;

            reklamaTableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;
            reklamyZestawienieTableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;
            fAKTURYTableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;
            kONTATableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;
            kLIENCITableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;
            pROMOCJETableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;

            SqlConnection conn = new SqlConnection(ConnString.getConnString().Value);

            command = new SqlCommand();
            command.CommandType = CommandType.Text;
            command.CommandText = query;
            command.Connection = conn;

            sqlDataAdapter = new SqlDataAdapter();
            sqlDataAdapter.SelectCommand = command;

            InitToolStrip(szukajToolStrip);

            generateNodes();

            zatwierdzoneNiezaplaconeColumns();
        }

        private void OrdersForm_Load(object sender, EventArgs e)
        {
            pROMOCJETableAdapter.Fill(sLOWNIKDataSet.PROMOCJE);
            kONTATableAdapter.FillByIdAgencji(sLOWNIKDataSet.KONTA, User.Instance().IdAgencji);
            WindowState = FormWindowState.Maximized;


            DBBindings.bindujAgencje(agencjaToolStripComboBox);
            DBBindings.bindujAgentow(agentToolStripComboBox);
            DBBindings.bindujTytuly(tytToolStripComboBox);
            DBBindings.bindujTypyReklam(typToolStripComboBox);
            DBBindings.BindujPromocje((ComboBox)cbPromocje.Control, sLOWNIKDataSet.PROMOCJE);
        }

        private static void InitToolStrip(ToolStrip toolStrip)
        {
            ToolStripLabel toolStripLabel = new ToolStripLabel("DR");
            toolStripLabel.ToolTipText = "Zatwierdzone do druku";
            toolStrip.Items.Insert(15, toolStripLabel);
            toolStrip.Items.Insert(16, new ToolStripControlHost(new CheckBox(), "DRCheckBox"));

            toolStripLabel = new ToolStripLabel("FW");
            toolStripLabel.ToolTipText = "Wystawiona faktura";
            toolStrip.Items.Insert(17, toolStripLabel);
            toolStrip.Items.Insert(18, new ToolStripControlHost(new CheckBox(), "FWCheckBox"));

            toolStripLabel = new ToolStripLabel("KZ");
            toolStripLabel.ToolTipText = "Kierownik zatwierdził";
            toolStrip.Items.Insert(19, toolStripLabel);
            toolStrip.Items.Insert(20, new ToolStripControlHost(new CheckBox(), "KZCheckBox"));

            toolStripLabel = new ToolStripLabel("WYR");
            toolStripLabel.ToolTipText = "Wyróżnienie";
            toolStrip.Items.Insert(21, toolStripLabel);
            toolStrip.Items.Insert(22, new ToolStripControlHost(new CheckBox(), "WyrCheckBox"));

            toolStripLabel = new ToolStripLabel("BZ");
            toolStripLabel.ToolTipText = "Bez zamówienia";
            toolStrip.Items.Insert(23, toolStripLabel);
            toolStrip.Items.Insert(24, new ToolStripControlHost(new CheckBox(), "BZCheckBox"));

            ((CheckBox)((ToolStripControlHost)toolStrip.Items["DRCheckBox"]).Control).ThreeState = true; //Zatwierdzone do druku
            ((CheckBox)((ToolStripControlHost)toolStrip.Items["FWCheckBox"]).Control).ThreeState = true; //Wystawiona faktura
            ((CheckBox)((ToolStripControlHost)toolStrip.Items["KZCheckBox"]).Control).ThreeState = true; //Kierownik zatwierdził
            ((CheckBox)((ToolStripControlHost)toolStrip.Items["WyrCheckBox"]).Control).ThreeState = true; //Wyróżnienie
            ((CheckBox)((ToolStripControlHost)toolStrip.Items["BZCheckBox"]).Control).ThreeState = true; //Bez zamówienia

            ResetCheckBoxes(toolStrip);
        }

        private static void ResetCheckBoxes(ToolStrip toolStrip)
        {
            foreach (object item in toolStrip.Items)
            {
                if (item is ToolStripControlHost && ((ToolStripControlHost)item).Control is CheckBox)
                    ((CheckBox)((ToolStripControlHost)item).Control).CheckState = CheckState.Indeterminate;
            }
        }

        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (e.Node != null)
            {
                command.CommandType = CommandType.Text;
                command.CommandText = query;
                command.Parameters.Clear();

                switch (e.Node.Level)
                {
                    case 0:
                        break;
                    case 1:
                        switch (e.Node.Parent.Name)
                        {
                            case "Tytuly":
                                try
                                {
                                    Cursor = Cursors.WaitCursor;

                                    zatwierdzoneNiezaplaconeColumns();
                                    rEKLAMADataSet.ReklamyZestawienie.Clear();
                                    command.CommandText +=
                                        " where R.[Tytuł]=@tytul aND (r.SZER * r.WYS)<>0 order by R.[DATA ZAMÓWIENIA] desc";
                                    command.Parameters.AddWithValue("@tytul", e.Node.Name);
                                    sqlDataAdapter.Fill(rEKLAMADataSet.ReklamyZestawienie);
                                }
                                catch (Exception ex)
                                {
                                    Logger.LogException(ex, User.Instance().Login, DateTime.Now);
                                }
                                finally
                                {
                                    commandExecuted = true;
                                    reklamaDataGridView.Refresh();
                                    Cursor = Cursors.Default;
                                }

                                break;
                            case "ZmodyfikowaneDzisiaj":

                                try
                                {
                                    Cursor = Cursors.WaitCursor;

                                    zatwierdzoneNiezaplaconeColumns();
                                    rEKLAMADataSet.ReklamyZestawienie.Clear();
                                    command.CommandText +=
                                        "  where A.symbol=@agencja AND [DATA OSTATNIEJ MODYFIKACJI]>@dzis aND [DATA OSTATNIEJ MODYFIKACJI]< @jutro AND (r.SZER * r.WYS)<>0 order by R.[DATA ZAMÓWIENIA] desc";
                                    command.Parameters.AddWithValue("@agencja", e.Node.Text);
                                    command.Parameters.AddWithValue("@dzis", DateTime.Today.ToShortDateString());
                                    command.Parameters.AddWithValue("@jutro",
                                                                    DateTime.Today.AddDays(1).ToShortDateString());
                                    sqlDataAdapter.Fill(rEKLAMADataSet.ReklamyZestawienie);
                                }
                                catch (Exception ex)
                                {
                                    Logger.LogException(ex, User.Instance().Login, DateTime.Now);
                                }
                                finally
                                {
                                    commandExecuted = true;
                                    reklamaDataGridView.Refresh();
                                    Cursor = Cursors.Default;
                                }

                                break;
                            case "DodaneDzisiaj":

                                try
                                {
                                    Cursor = Cursors.WaitCursor;

                                    zatwierdzoneNiezaplaconeColumns();
                                    rEKLAMADataSet.ReklamyZestawienie.Clear();
                                    command.CommandText +=
                                        "  where A.symbol=@agencja AND [DATA ZAMÓWIENIA]>@dzis aND [DATA ZAMÓWIENIA]<@jutro AND (r.SZER * r.WYS)<>0 order by R.[DATA ZAMÓWIENIA] desc";
                                    command.Parameters.AddWithValue("@agencja", e.Node.Text);
                                    command.Parameters.AddWithValue("@dzis", DateTime.Today.ToShortDateString());
                                    command.Parameters.AddWithValue("@jutro",
                                                                    DateTime.Today.AddDays(1).ToShortDateString());
                                    sqlDataAdapter.Fill(rEKLAMADataSet.ReklamyZestawienie);
                                }
                                catch (Exception ex)
                                {
                                    Logger.LogException(ex, User.Instance().Login, DateTime.Now);
                                }
                                finally
                                {
                                    commandExecuted = true;
                                    reklamaDataGridView.Refresh();
                                    Cursor = Cursors.Default;
                                }

                                break;
                            case "MojeZamowienia":

                                switch (e.Node.Name)
                                {
                                    default:

                                        try
                                        {
                                            Cursor = Cursors.WaitCursor;

                                            zatwierdzoneNiezaplaconeColumns();
                                            rEKLAMADataSet.ReklamyZestawienie.Clear();
                                            command.CommandText +=
                                                " where R.[symbol akwizytora]=@agent AND R.[Tytuł]=@tytul aND (r.SZER * r.WYS)<>0 order by R.[DATA ZAMÓWIENIA] desc";
                                            command.Parameters.AddWithValue("@agent", User.Instance().Symbol_agenta);
                                            command.Parameters.AddWithValue("@tytul", e.Node.Name);
                                            sqlDataAdapter.Fill(rEKLAMADataSet.ReklamyZestawienie);
                                        }
                                        catch (Exception ex)
                                        {
                                            Logger.LogException(ex, User.Instance().Login, DateTime.Now);
                                        }
                                        finally
                                        {
                                            commandExecuted = true;
                                            reklamaDataGridView.Refresh();
                                            Cursor = Cursors.Default;
                                        }

                                        break;
                                }
                                break;
                            case "Bledy":
                                switch (e.Node.Name)
                                {
                                    case "BledyWreklamach":

                                        try
                                        {
                                            Cursor = Cursors.WaitCursor;
                                            zatwierdzoneNiezaplaconeColumns();
                                            rEKLAMADataSet.ReklamyZestawienie.Clear();
                                            command.CommandText +=
                                                "WHERE ((r.MOD_TYP LIKE 'GS%' AND r.[TYTUŁ] LIKE 'AMT%') OR  (r.MOD_TYP LIKE 'AMT%' AND " +
                                                "r.[TYTUŁ] LIKE 'GS%') OR (r.TYP = 'PŁATNA' AND r.NETTO = 0) OR (r.TYP = 'BEZPŁATNA' AND r.NETTO > 0)) " +
                                                " aND (r.SZER * r.WYS)<>0 ORDER BY R.[DATA ZAMÓWIENIA] DESC";
                                            sqlDataAdapter.Fill(rEKLAMADataSet.ReklamyZestawienie);

                                        }
                                        catch (Exception ex)
                                        {
                                            Logger.LogException(ex, User.Instance().Login, DateTime.Now);
                                        }
                                        finally
                                        {
                                            commandExecuted = true;
                                            reklamaDataGridView.Refresh();
                                            Cursor = Cursors.Default;
                                        }

                                        break;
                                    case "PowtorzeniaReklam":

                                        try
                                        {
                                            Cursor = Cursors.WaitCursor;
                                            zatwierdzoneNiezaplaconeColumns();
                                            rEKLAMADataSet.ReklamyZestawienie.Clear();
                                            command.CommandText +=
                                                "WHERE R.[ID REKLAMY] in (select [ID REKLAMY] from (SELECT [ID REKLAMY]," +
                                                "COUNT([ID REKLAMY]) AS NumOccurrences FROM dbo.REKLAMA GROUP BY [ID REKLAMY] " +
                                                "HAVING ( COUNT([ID REKLAMY]) > 1 ) )  as d) AND datediff(month,R.[DATA ZAMÓWIENIA],getdate()) <= 3  ORDER BY R.[DATA ZAMÓWIENIA] DESC";
                                            sqlDataAdapter.Fill(rEKLAMADataSet.ReklamyZestawienie);

                                        }
                                        catch (Exception ex)
                                        {
                                            Logger.LogException(ex, User.Instance().Login, DateTime.Now);
                                        }
                                        finally
                                        {
                                            commandExecuted = true;
                                            reklamaDataGridView.Refresh();
                                            Cursor = Cursors.Default;
                                        }

                                        break;
                                    case "Moduly":
                                        try
                                        {
                                            Cursor = Cursors.WaitCursor;
                                            zatwierdzoneNiezaplaconeColumns();
                                            rEKLAMADataSet.ReklamyZestawienie.Clear();
                                            command.CommandText =
                                                command.CommandText.Replace(
                                                    "(r.[CENA JEDN] - r.[RABAT WARTOŚĆ]) / r.SZER * r.WYS AS [CENA MODUŁU]",
                                                    "0");
                                            command.CommandText +=
                                                "WHERE (r.SZER =0 or r.WYS=0) and year(R.[DATA ZAMÓWIENIA])>=2007  ORDER BY R.[DATA ZAMÓWIENIA] DESC";
                                            sqlDataAdapter.Fill(rEKLAMADataSet.ReklamyZestawienie);
                                        }
                                        catch (Exception ex)
                                        {
                                            Logger.LogException(ex, User.Instance().Login, DateTime.Now);
                                        }
                                        finally
                                        {
                                            commandExecuted = true;
                                            reklamaDataGridView.Refresh();
                                            Cursor = Cursors.Default;
                                        }

                                        break;
                                    default:
                                        break;
                                }
                                break;
                            case "AnalizaCenyModulu":
                                switch (e.Node.Name)
                                {
                                    case "ZaTani50":

                                        try
                                        {
                                            Cursor = Cursors.WaitCursor;
                                            analizaCenyModuluColumns();
                                            rEKLAMADataSet.ReklamyZestawienie.Clear();
                                            command.CommandText +=
                                                "WHERE (R.SZER * R.WYS <> 0) AND (((R.[CENA JEDN] - R.[RABAT WARTOŚĆ]) " +
                                                "/ (R.SZER * R.WYS))<NM.[CENA]/2) AND datediff(month,R.[DATA ZAMÓWIENIA],getdate()) <= 3  ORDER BY R.[DATA ZAMÓWIENIA] DESC";
                                            sqlDataAdapter.Fill(rEKLAMADataSet.ReklamyZestawienie);

                                        }
                                        catch (Exception ex)
                                        {
                                            Logger.LogException(ex, User.Instance().Login, DateTime.Now);
                                        }
                                        finally
                                        {
                                            commandExecuted = true;
                                            reklamaDataGridView.Refresh();
                                            Cursor = Cursors.Default;
                                        }

                                        break;
                                    case "ZaTani30":

                                        try
                                        {
                                            Cursor = Cursors.WaitCursor;

                                            analizaCenyModuluColumns();
                                            rEKLAMADataSet.ReklamyZestawienie.Clear();
                                            command.CommandText +=
                                                "WHERE (R.SZER * R.WYS <> 0) AND (((R.[CENA JEDN] - R.[RABAT WARTOŚĆ]) " +
                                                "/ (R.SZER * R.WYS))<NM.[CENA_MIN]) AND datediff(month,R.[DATA ZAMÓWIENIA],getdate()) <= 3  ORDER BY R.[DATA ZAMÓWIENIA] DESC";
                                            sqlDataAdapter.Fill(rEKLAMADataSet.ReklamyZestawienie);
                                        }
                                        catch (Exception ex)
                                        {
                                            Logger.LogException(ex, User.Instance().Login, DateTime.Now);
                                        }
                                        finally
                                        {
                                            commandExecuted = true;
                                            reklamaDataGridView.Refresh();
                                            Cursor = Cursors.Default;
                                        }

                                        break;
                                    case "ZaDrogi":

                                        try
                                        {
                                            Cursor = Cursors.WaitCursor;
                                            analizaCenyModuluColumns();
                                            rEKLAMADataSet.ReklamyZestawienie.Clear();
                                            command.CommandText +=
                                                "WHERE (R.SZER * R.WYS <> 0) AND (((R.[CENA JEDN] - R.[RABAT WARTOŚĆ]) " +
                                                "/( R.SZER * R.WYS))>NM.[CENA]) AND datediff(month,R.[DATA ZAMÓWIENIA],getdate()) <= 3  ORDER BY R.[DATA ZAMÓWIENIA] DESC";
                                            sqlDataAdapter.Fill(rEKLAMADataSet.ReklamyZestawienie);
                                        }
                                        catch (Exception ex)
                                        {
                                            Logger.LogException(ex, User.Instance().Login, DateTime.Now);
                                        }
                                        finally
                                        {
                                            commandExecuted = true;
                                            reklamaDataGridView.Refresh();
                                            Cursor = Cursors.Default;
                                        }

                                        break;
                                    default:
                                        break;
                                }
                                break;
                            default:
                                break;
                        }
                        break;
                    case 2:
                        switch (e.Node.Parent.Parent.Name)
                        {
                            case "Tytuly":

                                try
                                {
                                    Cursor = Cursors.WaitCursor;
                                    zatwierdzoneNiezaplaconeColumns();
                                    rEKLAMADataSet.ReklamyZestawienie.Clear();
                                    command.CommandText +=
                                        " where R.[Tytuł]=@tytul and datepart(year,NR.DATA_W)=@rok aND (r.SZER * r.WYS)<>0 order by R.[DATA ZAMÓWIENIA] desc";
                                    command.Parameters.AddWithValue("@tytul", e.Node.Parent.Name);
                                    command.Parameters.AddWithValue("@rok", e.Node.Name);
                                    sqlDataAdapter.Fill(rEKLAMADataSet.ReklamyZestawienie);

                                }
                                catch (Exception ex)
                                {
                                    Logger.LogException(ex, User.Instance().Login, DateTime.Now);
                                }
                                finally
                                {
                                    commandExecuted = true;
                                    reklamaDataGridView.Refresh();
                                    Cursor = Cursors.Default;
                                }

                                break;
                            case "MojeZamowienia":
                                try
                                {
                                    Cursor = Cursors.WaitCursor;
                                    zatwierdzoneNiezaplaconeColumns();
                                    rEKLAMADataSet.ReklamyZestawienie.Clear();
                                    command.CommandText +=
                                        " where R.[symbol akwizytora]=@agent AND R.[Tytuł]=@tytul and datepart(year,NR.DATA_W)=@rok aND (r.SZER * r.WYS)<>0 order by R.[DATA ZAMÓWIENIA] desc";
                                    command.Parameters.AddWithValue("@agent", User.Instance().Symbol_agenta);
                                    command.Parameters.AddWithValue("@tytul", e.Node.Parent.Name);
                                    command.Parameters.AddWithValue("@rok", e.Node.Name);
                                    sqlDataAdapter.Fill(rEKLAMADataSet.ReklamyZestawienie);
                                }
                                catch (Exception ex)
                                {
                                    Logger.LogException(ex, User.Instance().Login, DateTime.Now);
                                }
                                finally
                                {
                                    commandExecuted = true;
                                    reklamaDataGridView.Refresh();
                                    Cursor = Cursors.Default;
                                }

                                break;
                            case "KoniecEmisji":

                                try
                                {
                                    Cursor = Cursors.WaitCursor;

                                    zatwierdzoneNiezaplaconeColumns();
                                    rEKLAMADataSet.ReklamyZestawienie.Clear();
                                    command.CommandText +=
                                        " where R.[Tytuł]=@tytul and O.DO=@nrWyd aND (r.SZER * r.WYS)<>0 order by R.[DATA ZAMÓWIENIA] desc";
                                    command.Parameters.AddWithValue("@tytul", e.Node.Parent.Name);
                                    command.Parameters.AddWithValue("@nrWyd", e.Node.Name);
                                    sqlDataAdapter.Fill(rEKLAMADataSet.ReklamyZestawienie);
                                }
                                catch (Exception ex)
                                {
                                    Logger.LogException(ex, User.Instance().Login, DateTime.Now);
                                }
                                finally
                                {
                                    commandExecuted = true;
                                    reklamaDataGridView.Refresh();
                                    Cursor = Cursors.Default;
                                }

                                break;
                            case "ZmodyfikowaneDzisiaj":

                                try
                                {
                                    Cursor = Cursors.WaitCursor;
                                    zatwierdzoneNiezaplaconeColumns();
                                    rEKLAMADataSet.ReklamyZestawienie.Clear();
                                    command.CommandText +=
                                        " where R.[symbol akwizytora]=@agent aND [DATA OSTATNIEJ MODYFIKACJI]>@dzis aND [DATA OSTATNIEJ MODYFIKACJI]< @jutro AND (r.SZER * r.WYS)<>0 order by R.[DATA ZAMÓWIENIA] desc";
                                    command.Parameters.AddWithValue("@agent", e.Node.Name);
                                    command.Parameters.AddWithValue("@dzis", DateTime.Today.ToShortDateString());
                                    command.Parameters.AddWithValue("@jutro",
                                                                    DateTime.Today.AddDays(1).ToShortDateString());
                                    sqlDataAdapter.Fill(rEKLAMADataSet.ReklamyZestawienie);
                                }
                                catch (Exception ex)
                                {
                                    Logger.LogException(ex, User.Instance().Login, DateTime.Now);
                                }
                                finally
                                {
                                    commandExecuted = true;
                                    reklamaDataGridView.Refresh();
                                    Cursor = Cursors.Default;
                                }

                                break;
                            case "DodaneDzisiaj":

                                try
                                {
                                    Cursor = Cursors.WaitCursor;

                                    zatwierdzoneNiezaplaconeColumns();
                                    rEKLAMADataSet.ReklamyZestawienie.Clear();
                                    command.CommandText +=
                                        " where R.[symbol akwizytora]=@agent aND [DATA ZAMÓWIENIA]>@dzis aND [DATA ZAMÓWIENIA]<@jutro AND (r.SZER * r.WYS)<>0 order by R.[DATA ZAMÓWIENIA] desc";
                                    command.Parameters.AddWithValue("@agent", e.Node.Name);
                                    command.Parameters.AddWithValue("@dzis", DateTime.Today.ToShortDateString());
                                    command.Parameters.AddWithValue("@jutro",
                                                                    DateTime.Today.AddDays(1).ToShortDateString());
                                    sqlDataAdapter.Fill(rEKLAMADataSet.ReklamyZestawienie);
                                }
                                catch (Exception ex)
                                {
                                    Logger.LogException(ex, User.Instance().Login, DateTime.Now);
                                }
                                finally
                                {
                                    commandExecuted = true;
                                    reklamaDataGridView.Refresh();
                                    Cursor = Cursors.Default;
                                }

                                break;
                            case "AnalizaCenyModulu":
                                switch (e.Node.Parent.Name)
                                {
                                    case "ZaTani50":

                                        try
                                        {
                                            Cursor = Cursors.WaitCursor;
                                            analizaCenyModuluColumns();
                                            rEKLAMADataSet.ReklamyZestawienie.Clear();
                                            command.CommandText +=
                                                "WHERE (R.SZER * R.WYS <> 0) AND (((R.[CENA JEDN] - R.[RABAT WARTOŚĆ]) " +
                                                "/ (R.SZER * R.WYS))<NM.[CENA]/2) AND A.symbol=@agencja AND datediff(month,R.[DATA ZAMÓWIENIA],getdate()) <= 3  ORDER BY R.[DATA ZAMÓWIENIA] DESC";
                                            command.Parameters.AddWithValue("@agencja", e.Node.Text);
                                            sqlDataAdapter.Fill(rEKLAMADataSet.ReklamyZestawienie);
                                        }
                                        catch (Exception ex)
                                        {
                                            Logger.LogException(ex, User.Instance().Login, DateTime.Now);
                                        }
                                        finally
                                        {
                                            commandExecuted = true;
                                            reklamaDataGridView.Refresh();
                                            Cursor = Cursors.Default;
                                        }

                                        break;
                                    case "ZaTani30":


                                        try
                                        {
                                            Cursor = Cursors.WaitCursor;
                                            analizaCenyModuluColumns();
                                            rEKLAMADataSet.ReklamyZestawienie.Clear();
                                            command.CommandText +=
                                                "WHERE (R.SZER * R.WYS <> 0) AND (((R.[CENA JEDN] - R.[RABAT WARTOŚĆ]) " +
                                                "/ (R.SZER * R.WYS))<NM.[CENA_MIN]) AND A.symbol=@agencja AND datediff(month,R.[DATA ZAMÓWIENIA],getdate()) <= 3  ORDER BY R.[DATA ZAMÓWIENIA] DESC";
                                            command.Parameters.AddWithValue("@agencja", e.Node.Text);
                                            sqlDataAdapter.Fill(rEKLAMADataSet.ReklamyZestawienie);
                                        }
                                        catch (Exception ex)
                                        {
                                            Logger.LogException(ex, User.Instance().Login, DateTime.Now);
                                        }
                                        finally
                                        {
                                            commandExecuted = true;
                                            reklamaDataGridView.Refresh();
                                            Cursor = Cursors.Default;
                                        }

                                        break;
                                    case "ZaDrogi":


                                        try
                                        {
                                            Cursor = Cursors.WaitCursor;

                                            analizaCenyModuluColumns();
                                            rEKLAMADataSet.ReklamyZestawienie.Clear();
                                            command.CommandText +=
                                                "WHERE (R.SZER * R.WYS <> 0) AND (((R.[CENA JEDN] - R.[RABAT WARTOŚĆ]) " +
                                                "/( R.SZER * R.WYS))>NM.[CENA]) AND A.symbol=@agencja AND datediff(month,R.[DATA ZAMÓWIENIA],getdate()) <= 3  ORDER BY R.[DATA ZAMÓWIENIA] DESC";
                                            command.Parameters.AddWithValue("@agencja", e.Node.Text);
                                            sqlDataAdapter.Fill(rEKLAMADataSet.ReklamyZestawienie);
                                        }
                                        catch (Exception ex)
                                        {
                                            Logger.LogException(ex, User.Instance().Login, DateTime.Now);
                                        }
                                        finally
                                        {
                                            commandExecuted = true;
                                            reklamaDataGridView.Refresh();
                                            Cursor = Cursors.Default;
                                        }

                                        break;

                                    default:
                                        break;
                                }
                                break;
                            default:
                                break;
                        }
                        break;

                    case 3:
                        switch (e.Node.Parent.Parent.Parent.Name)
                        {
                            case "Tytuly":


                                try
                                {
                                    Cursor = Cursors.WaitCursor;

                                    zatwierdzoneNiezaplaconeColumns();
                                    rEKLAMADataSet.ReklamyZestawienie.Clear();
                                    command.CommandText +=
                                        " where R.[Tytuł]=@tytul and datepart(year,NR.DATA_W)=@rok and datepart(month,NR.DATA_W)=@miesiac aND (r.SZER * r.WYS)<>0 order by R.[DATA ZAMÓWIENIA] desc";
                                    command.Parameters.AddWithValue("@tytul", e.Node.Parent.Parent.Name);
                                    command.Parameters.AddWithValue("@rok", e.Node.Parent.Name);
                                    command.Parameters.AddWithValue("@miesiac", e.Node.Name);
                                    sqlDataAdapter.Fill(rEKLAMADataSet.ReklamyZestawienie);
                                }
                                catch (Exception ex)
                                {
                                    Logger.LogException(ex, User.Instance().Login, DateTime.Now);
                                }
                                finally
                                {
                                    commandExecuted = true;
                                    reklamaDataGridView.Refresh();
                                    Cursor = Cursors.Default;
                                }

                                break;
                            case "MojeZamowienia":


                                try
                                {
                                    Cursor = Cursors.WaitCursor;

                                    zatwierdzoneNiezaplaconeColumns();
                                    rEKLAMADataSet.ReklamyZestawienie.Clear();
                                    command.CommandText +=
                                        " where R.[symbol akwizytora]=@agent AND R.[Tytuł]=@tytul and datepart(year,NR.DATA_W)=@rok and datepart(month,NR.DATA_W)=@miesiac aND (r.SZER * r.WYS)<>0 order by R.[DATA ZAMÓWIENIA] desc";
                                    command.Parameters.AddWithValue("@agent", User.Instance().Symbol_agenta);
                                    command.Parameters.AddWithValue("@tytul", e.Node.Parent.Parent.Name);
                                    command.Parameters.AddWithValue("@rok", e.Node.Parent.Name);
                                    command.Parameters.AddWithValue("@miesiac", e.Node.Name);
                                    sqlDataAdapter.Fill(rEKLAMADataSet.ReklamyZestawienie);
                                }
                                catch (Exception ex)
                                {
                                    Logger.LogException(ex, User.Instance().Login, DateTime.Now);
                                }
                                finally
                                {
                                    commandExecuted = true;
                                    reklamaDataGridView.Refresh();
                                    Cursor = Cursors.Default;
                                }

                                break;
                            case "AnalizaCenyModulu":
                                switch (e.Node.Parent.Parent.Name)
                                {
                                    case "ZaTani50":


                                        try
                                        {
                                            Cursor = Cursors.WaitCursor;
                                            analizaCenyModuluColumns();
                                            rEKLAMADataSet.ReklamyZestawienie.Clear();
                                            command.CommandText +=
                                                "WHERE (R.SZER * R.WYS <> 0) AND (((R.[CENA JEDN] - R.[RABAT WARTOŚĆ]) " +
                                                "/ (R.SZER * R.WYS))<NM.[CENA]/2) AND A.symbol=@agencja AND  R.[symbol akwizytora]=@agent AND datediff(month,R.[DATA ZAMÓWIENIA],getdate()) <= 3  ORDER BY R.[DATA ZAMÓWIENIA] DESC";
                                            command.Parameters.AddWithValue("@agencja", e.Node.Parent.Text);
                                            command.Parameters.AddWithValue("@agent", e.Node.Name);
                                            sqlDataAdapter.Fill(rEKLAMADataSet.ReklamyZestawienie);
                                        }
                                        catch (Exception ex)
                                        {
                                            Logger.LogException(ex, User.Instance().Login, DateTime.Now);
                                        }
                                        finally
                                        {
                                            commandExecuted = true;
                                            reklamaDataGridView.Refresh();
                                            Cursor = Cursors.Default;
                                        }

                                        break;
                                    case "ZaTani30":


                                        try
                                        {
                                            Cursor = Cursors.WaitCursor;
                                            analizaCenyModuluColumns();
                                            rEKLAMADataSet.ReklamyZestawienie.Clear();
                                            command.CommandText +=
                                                "WHERE (R.SZER * R.WYS <> 0) AND (((R.[CENA JEDN] - R.[RABAT WARTOŚĆ]) " +
                                                "/ (R.SZER * R.WYS))<NM.[CENA_MIN]) AND A.symbol=@agencja AND  R.[symbol akwizytora]=@agent AND datediff(month,R.[DATA ZAMÓWIENIA],getdate()) <= 3  ORDER BY R.[DATA ZAMÓWIENIA] DESC";
                                            command.Parameters.AddWithValue("@agencja", e.Node.Parent.Text);
                                            command.Parameters.AddWithValue("@agent", e.Node.Name);
                                            sqlDataAdapter.Fill(rEKLAMADataSet.ReklamyZestawienie);
                                        }
                                        catch (Exception ex)
                                        {
                                            Logger.LogException(ex, User.Instance().Login, DateTime.Now);
                                        }
                                        finally
                                        {
                                            commandExecuted = true;
                                            reklamaDataGridView.Refresh();
                                            Cursor = Cursors.Default;
                                        }

                                        break;
                                    case "ZaDrogi":


                                        try
                                        {
                                            Cursor = Cursors.WaitCursor;

                                            analizaCenyModuluColumns();
                                            rEKLAMADataSet.ReklamyZestawienie.Clear();
                                            command.CommandText +=
                                                "WHERE (R.SZER * R.WYS <> 0) AND (((R.[CENA JEDN] - R.[RABAT WARTOŚĆ]) " +
                                                "/( R.SZER * R.WYS))>NM.[CENA]) AND A.symbol=@agencja AND  R.[symbol akwizytora]=@agent AND datediff(month,R.[DATA ZAMÓWIENIA],getdate()) <= 3  ORDER BY R.[DATA ZAMÓWIENIA] DESC";
                                            command.Parameters.AddWithValue("@agencja", e.Node.Parent.Text);
                                            command.Parameters.AddWithValue("@agent", e.Node.Name);
                                            sqlDataAdapter.Fill(rEKLAMADataSet.ReklamyZestawienie);
                                        }
                                        catch (Exception ex)
                                        {
                                            Logger.LogException(ex, User.Instance().Login, DateTime.Now);
                                        }
                                        finally
                                        {
                                            commandExecuted = true;
                                            reklamaDataGridView.Refresh();
                                            Cursor = Cursors.Default;
                                        }

                                        break;

                                    default:
                                        break;
                                }
                                break;
                            default:
                                break;
                        }
                        break;
                    default:
                        break;
                }
            }
        }

        private void toolStripButton6_Click(object sender, EventArgs e)
        {
            szukajToolStrip.Visible = szukajToolStrip.Visible ? false : true;
        }

        private void szukajToolStripButton_Click(object sender, EventArgs e)
        {
            command.CommandText = "sp_GetReklamy";
            command.CommandType = CommandType.StoredProcedure;

            rEKLAMADataSet.ReklamyZestawienie.Clear();

            command.Parameters.Clear();

            if (!string.IsNullOrEmpty(agencjaToolStripComboBox.Text.Trim()))
            {
                command.Parameters.AddWithValue("@agencja", agencjaToolStripComboBox.Text.Trim());
            }

            if (!string.IsNullOrEmpty(agentToolStripComboBox.Text.Trim()))
            {
                command.Parameters.AddWithValue("@agent", agentToolStripComboBox.Text.Trim());
            }

            if (!string.IsNullOrEmpty(symbolToolStripTextBox.Text.Trim()))
            {
                command.Parameters.AddWithValue("@reklama", symbolToolStripTextBox.Text.Trim());
            }

            if (!string.IsNullOrEmpty(rokToolStripTextBox.Text.Trim()))
            {
                int i;
                if (!Int32.TryParse(rokToolStripTextBox.Text.Trim(), out i))
                {
                    MessageBox.Show("Podaj prawidłowy rok.");
                    Cursor = Cursors.Default;
                    return;
                }

                command.Parameters.AddWithValue("@rok", rokToolStripTextBox.Text.Trim());
            }

            if (!string.IsNullOrEmpty(msToolStripTextBox.Text.Trim()))
            {
                int i;
                if (!Int32.TryParse(msToolStripTextBox.Text.Trim(), out i))
                {
                    MessageBox.Show("Podaj prawidłowy miesiąc.");
                    Cursor = Cursors.Default;
                    return;
                }

                command.Parameters.AddWithValue("@ms", msToolStripTextBox.Text.Trim());
            }


            if (tytToolStripComboBox.SelectedIndex != -1)
            {
                command.Parameters.AddWithValue("@tytul", tytToolStripComboBox.Text.Trim());
            }

            if (!string.IsNullOrEmpty(typToolStripComboBox.Text.Trim()))
            {
                command.Parameters.AddWithValue("@typ", typToolStripComboBox.Text.Trim());
            }

            if (!string.IsNullOrEmpty(cbPromocje.Text.Trim()))
            {
                command.Parameters.AddWithValue("@promocja", Convert.ToInt32(((DataRow) cbPromocje.SelectedItem)["Id"]));
            }

            if (((CheckBox) ((ToolStripControlHost) szukajToolStrip.Items["DRCheckBox"]).Control).CheckState ==
                CheckState.Checked)
            {
                command.Parameters.AddWithValue("@zd", true);
            }
            else if (((CheckBox) ((ToolStripControlHost) szukajToolStrip.Items["DRCheckBox"]).Control).CheckState ==
                     CheckState.Unchecked)
            {
                command.Parameters.AddWithValue("@zd", false);
            }

            if (((CheckBox) ((ToolStripControlHost) szukajToolStrip.Items["FWCheckBox"]).Control).CheckState ==
                CheckState.Checked)
            {
                command.Parameters.AddWithValue("@fw", true);
            }
            else if (((CheckBox) ((ToolStripControlHost) szukajToolStrip.Items["FWCheckBox"]).Control).CheckState ==
                     CheckState.Unchecked)
            {
                command.Parameters.AddWithValue("@fw", false);
            }

            if (((CheckBox) ((ToolStripControlHost) szukajToolStrip.Items["KZCheckBox"]).Control).CheckState ==
                CheckState.Checked)
            {
                command.Parameters.AddWithValue("@kz", true);
            }
            else if (((CheckBox) ((ToolStripControlHost) szukajToolStrip.Items["KZCheckBox"]).Control).CheckState ==
                     CheckState.Unchecked)
            {
                command.Parameters.AddWithValue("@kz", false);
            }

            if (((CheckBox) ((ToolStripControlHost) szukajToolStrip.Items["WyrCheckBox"]).Control).CheckState ==
                CheckState.Checked)
            {
                command.Parameters.AddWithValue("@wy", true);
            }
            else if (((CheckBox) ((ToolStripControlHost) szukajToolStrip.Items["WyrCheckBox"]).Control).CheckState ==
                     CheckState.Unchecked)
            {
                command.Parameters.AddWithValue("@wy", false);
            }

            if (((CheckBox) ((ToolStripControlHost) szukajToolStrip.Items["BZCheckBox"]).Control).CheckState ==
                CheckState.Checked)
            {
                command.Parameters.AddWithValue("@bz", true);
            }
            else if (((CheckBox) ((ToolStripControlHost) szukajToolStrip.Items["BZCheckBox"]).Control).CheckState ==
                     CheckState.Unchecked)
            {
                command.Parameters.AddWithValue("@bz", false);
            }

            try
            {
                Cursor = Cursors.WaitCursor;

                sqlDataAdapter.SelectCommand = command;

                sqlDataAdapter.Fill(rEKLAMADataSet.ReklamyZestawienie);
                commandExecuted = true;

                reklamaDataGridView.Refresh();

                treeView1.CollapseAll();
                treeView1.SelectedNode = null;
            }
            catch (Exception ex)
            {
                Logger.LogException(ex, User.Instance().Login, DateTime.Now);
            }
            finally
            {
                Cursor = Cursors.Default;
            }
        }

        private void reklamaDataGridView_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (reklamyZestawienieBindingSource.Current != null)
            {
                DataRowView row = (DataRowView)reklamyZestawienieBindingSource.Current;
                int idRek = Int32.Parse(row["reklamaId"].ToString());


                OrderDetails.getOrderDetails().PokazSzczegolyZamowienia(idRek);
                DialogResult result = OrderDetails.getOrderDetails().ShowDialog();

                if (result == DialogResult.OK)
                {
                    rEKLAMADataSet.ReklamyZestawienie.Clear();
                    sqlDataAdapter.Fill(rEKLAMADataSet.ReklamyZestawienie);
                }
            }

        }

        private void treeView1_AfterExpand(object sender, TreeViewEventArgs e)
        {
            if (e.Node != null)
            {
                SqlConnection conn = new SqlConnection(ConnString.getConnString().Value);

                SqlCommand comand = new SqlCommand();
                comand.Connection = conn;
                comand.CommandType = CommandType.Text;

                TreeNode node;
                SqlDataReader reader;

                switch (e.Node.Level)
                {
                    case 0:

                        switch (e.Node.Name)
                        {
                            case "Tytuly":
                                DBBindings.dodajTytulyDoWezla(e.Node);
                                break;
                            case "MojeZamowienia":
                                DBBindings.dodajTytulyDoWezla(e.Node);
                                break;
                            case "KoniecEmisji":
                                DBBindings.dodajTytulyDoWezla(e.Node);
                                break;
                            case "ZmodyfikowaneDzisiaj":
                                DBBindings.dodajAgencjeDoWezla(e.Node);
                                break;
                            case "DodaneDzisiaj":
                                DBBindings.dodajAgencjeDoWezla(e.Node);
                                break;
                            default:
                                break;
                        }

                        break;
                    case 1:
                        switch (e.Node.Parent.Name)
                        {
                            case "KoniecEmisji":
                                e.Node.Nodes.Clear();

                                comand.CommandText =
                                    "select NRW from dbo.NR where DATA_W between @startDate AND @endDate AND tyt = @param";
                                conn.Open();
                                comand.Parameters.Clear();
                                comand.Parameters.AddWithValue("@param", e.Node.Name);
                                comand.Parameters.AddWithValue("@startDate", DateTime.Now.AddDays(-50));
                                comand.Parameters.AddWithValue("@endDate", DateTime.Now.AddDays(50));
                                reader = comand.ExecuteReader();

                                if (reader != null)
                                {
                                    while (reader.Read())
                                    {
                                        node = new TreeNode(reader.GetValue(0).ToString());
                                        node.Name = reader.GetValue(0).ToString();
                                        e.Node.Nodes.Add(node);
                                    }
                                }
                                conn.Close();
                                break;
                            case "ZmodyfikowaneDzisiaj":
                                DBBindings.dodajAgentowDoWezla(e.Node, e.Node.Name);
                                break;
                            case "DodaneDzisiaj":
                                DBBindings.dodajAgentowDoWezla(e.Node, e.Node.Name);
                                break;
                            case "AnalizaCenyModulu":
                                DBBindings.dodajAgencjeDoWezla(e.Node);
                                break;
                            default:
                                e.Node.Nodes.Clear();

                                comand.CommandText =
                                    "select distinct datepart(year,DATA_W) as rok from dbo.NR where TYT=@param order by rok desc";
                                conn.Open();
                                comand.Parameters.Clear();
                                comand.Parameters.AddWithValue("@param", e.Node.Name);
                                reader = comand.ExecuteReader();

                                if (reader != null)
                                {
                                    while (reader.Read())
                                    {
                                        node = new TreeNode(reader.GetValue(0).ToString());
                                        node.Name = reader.GetValue(0).ToString();

                                        for (int i = 1; i <= 12; i++)
                                        {
                                            TreeNode node2 = new TreeNode(i.ToString());
                                            node2.Name = i.ToString();
                                            node.Nodes.Add(node2);
                                        }

                                        e.Node.Nodes.Add(node);
                                    }
                                }
                                conn.Close();
                                break;
                        }
                        break;
                    case 2:
                        switch (e.Node.Parent.Parent.Name)
                        {
                            case "AnalizaCenyModulu":
                                DBBindings.dodajAgentowDoWezla(e.Node, e.Node.Name);
                                break;
                            default:
                                break;
                        }
                        break;
                    default:
                        break;
                }
            }
        }

        private void reklamaDataGridView_CellLeave(object sender, DataGridViewCellEventArgs e)
        {
            reklamyZestawienieBindingSource.CancelEdit();
        }

        /// <summary>
        /// Przechodzi do okna KLIENCI i wyświetla dane klienta związanego z zamówieniem.
        /// </summary>
        private void klientToolStripButton_Click(object sender, EventArgs e)
        {
            REKLAMADataSet.ReklamyZestawienieRow reklama = Reklama;

            if (reklama == null || reklama.IsCustomerIDNull()) return;

            ClientsForm.getClientsForm((MDIBazaReklam)MdiParent).pokazKlienta(reklama.CustomerID);

            Hide();

            ClientsForm.getClientsForm((MDIBazaReklam)MdiParent).Show();
        }

        private void fakturaToolStripButton_Click(object sender, EventArgs e)
        {
            REKLAMADataSet.ReklamyZestawienieRow reklama = Reklama;

            if (reklama == null || AdHelper.IsReklamaNew(reklama)) return;

            Facturer f = new Facturer(reklama.ReklamaID);
            f.ShowDialog();
        }

        private void wplataToolStripButton_Click(object sender, EventArgs e)
        {
            REKLAMADataSet.ReklamyZestawienieRow reklama = Reklama;

            if (reklama == null || reklama.IsID_FAKTURYNull()) return;

            PaymentForm2 p = new PaymentForm2(reklama.ID_FAKTURY);
            p.ShowDialog();
        }

        private void reklamaDataGridView_Leave(object sender, EventArgs e)
        {
            reklamaDataGridView.EndEdit();
        }

        private void kryteriumWyszukiwania_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                szukajToolStripButton.PerformClick();
            }
        }

        private void wyczyscPolaToolStripButton_Click(object sender, EventArgs e)
        {
            rEKLAMADataSet.ReklamyZestawienie.Clear();

            symbolToolStripTextBox.Clear();
            rokToolStripTextBox.Clear();
            msToolStripTextBox.Clear();
            tytToolStripComboBox.SelectedIndex = -1;
            tytToolStripComboBox.Text = "";
            agencjaToolStripComboBox.SelectedIndex = -1;
            agencjaToolStripComboBox.Text = "";
            agentToolStripComboBox.SelectedIndex = -1;
            agentToolStripComboBox.Text = "";
            typToolStripComboBox.SelectedIndex = -1;
            typToolStripComboBox.Text = "";
            cbPromocje.SelectedIndex = -1;

            ResetCheckBoxes(szukajToolStrip);
        }

        private void zamToolStripButton_Click(object sender, EventArgs e)
        {
            if (reklamyZestawienieBindingSource.Current != null)
            {
                DataRowView row = (DataRowView)reklamyZestawienieBindingSource.Current;
                int idRek = Int32.Parse(row["reklamaId"].ToString());

                OrderDetails.getOrderDetails().PokazSzczegolyZamowienia(idRek);
                OrderDetails.getOrderDetails().ShowDialog();
            }
        }

        private void pokazZamToolStripButton_Click(object sender, EventArgs e)
        {
            REKLAMADataSet.ReklamyZestawienieRow reklama = Reklama;

            if (reklama == null || AdHelper.IsReklamaNew(reklama)) return;

            Cursor = Cursors.WaitCursor;

            OrderViewer ov = new OrderViewer(reklama.ReklamaID);

            Cursor = Cursors.Default;

            ov.ShowDialog();
        }

        private void podgladToolStripButton_Click(object sender, EventArgs e)
        {
            REKLAMADataSet.ReklamyZestawienieRow reklama = Reklama;

            if (reklama == null) return;

            if (reklama.IsID_FAKTURYNull())
            {
                MessageBox.Show("Nie wystawiono faktury");
                return;
            }

            Cursor = Cursors.WaitCursor;

            FactureViewer fv = new FactureViewer(reklama.ID_FAKTURY, false, 0);
            fv.ShowDialog();
        }

        private void generateNodes()
        {
            TreeNode node;

            if (User.Instance().IsHandlowiec)
            {
                node = new TreeNode("Moje zamówienia");
                node.Name = "MojeZamowienia";
                node.Nodes.Add(new TreeNode());

                treeView1.Nodes.Add(node);
            }

            node = new TreeNode("Koniec emisji");
            node.Name = "KoniecEmisji";
            node.Nodes.Add(new TreeNode());

            treeView1.Nodes.Add(node);

            node = new TreeNode("Błędy");
            node.Name = "Bledy";
            treeView1.Nodes.Add(node);

            node = new TreeNode("Powtórzenia reklam");
            node.Name = "PowtorzeniaReklam";
            treeView1.Nodes["Bledy"].Nodes.Add(node);

            node = new TreeNode("Błędy w reklamach");
            node.Name = "BledyWreklamach";
            treeView1.Nodes["Bledy"].Nodes.Add(node);

            node = new TreeNode("Moduły");
            node.Name = "Moduly";
            treeView1.Nodes["Bledy"].Nodes.Add(node);


            if (User.Instance().IsKierownik)
            {
                node = new TreeNode("Analiza ceny modułu");
                node.Name = "AnalizaCenyModulu";
                treeView1.Nodes.Add(node);

                node = new TreeNode("Za tani 50%");
                node.Name = "ZaTani50";
                node.Nodes.Add(new TreeNode());
                treeView1.Nodes["AnalizaCenyModulu"].Nodes.Add(node);

                node = new TreeNode("Za tani 30%");
                node.Name = "ZaTani30";
                node.Nodes.Add(new TreeNode());
                treeView1.Nodes["AnalizaCenyModulu"].Nodes.Add(node);

                node = new TreeNode("Za drogi");
                node.Name = "ZaDrogi";
                node.Nodes.Add(new TreeNode());
                treeView1.Nodes["AnalizaCenyModulu"].Nodes.Add(node);
            }

            node = new TreeNode("Zmodyfikowane dzisiaj");
            node.Name = "ZmodyfikowaneDzisiaj";
            node.Nodes.Add(new TreeNode());
            treeView1.Nodes.Add(node);

            node = new TreeNode("Dodane dzisiaj");
            node.Name = "DodaneDzisiaj";
            node.Nodes.Add(new TreeNode());
            treeView1.Nodes.Add(node);
        }

        /// <summary>
        /// Kolumny z zatwierdzonych - niezapłaconych
        /// </summary>
        private void zatwierdzoneNiezaplaconeColumns()
        {
            if (reklamaDataGridView == null) return;

            // ReSharper disable PossibleNullReferenceException
            reklamaDataGridView.Columns["CENA_MODULU"].Visible = false;

            reklamaDataGridView.Columns["CENA_MIN"].Visible = false;
            reklamaDataGridView.Columns["CENA"].Visible = false;
            reklamaDataGridView.Columns["PROCENT_PROWIZJI"].Visible = false;
            reklamaDataGridView.Columns["wYSDataGridViewTextBoxColumn"].Visible = true;
            reklamaDataGridView.Columns["sZERDataGridViewTextBoxColumn"].Visible = true;

            reklamaDataGridView.Columns["tYTUŁDataGridViewTextBoxColumn"].Visible = true;
            reklamaDataGridView.Columns["TYP"].Visible = true;
            reklamaDataGridView.Columns["oDDataGridViewTextBoxColumn"].Visible = true;
            reklamaDataGridView.Columns["emisjaDataGridViewTextBoxColumn"].Visible = true;
            reklamaDataGridView.Columns["FirstName"].Visible = true;
            reklamaDataGridView.Columns["fAKTURANUMERDataGridViewTextBoxColumn"].Visible = true;
            reklamaDataGridView.Columns["dATAOSTATNIEJMODYFIKACJIDataGridViewTextBoxColumn"].Visible = true;
            reklamaDataGridView.Columns["dATAZAPŁATYDataGridViewTextBoxColumn"].Visible = true;
            reklamaDataGridView.Columns["zAPŁACONODataGridViewCheckBoxColumn"].Visible = true;
            reklamaDataGridView.Columns["fAKTURAWYSTAWIONODataGridViewCheckBoxColumn"].Visible = true;
            reklamaDataGridView.Columns["zATWIERDZONODODRUKUDataGridViewCheckBoxColumn"].Visible = true;

            reklamaDataGridView.Columns["iDREKLAMYDataGridViewTextBoxColumn"].Visible = true;
            reklamaDataGridView.Columns["mODTYPDataGridViewTextBoxColumn"].Visible = true;
            reklamaDataGridView.Columns["rABATDataGridViewTextBoxColumn"].Visible = true;
            reklamaDataGridView.Columns["kierzatwierdzilDataGridViewCheckBoxColumn"].Visible = true;
            reklamaDataGridView.Columns["zablokujprowizjeDataGridViewCheckBoxColumn"].Visible = true;
            reklamaDataGridView.Columns["sYMBOLAKWIZYTORADataGridViewTextBoxColumn"].Visible = true;
            reklamaDataGridView.Columns["agencjaDataGridViewTextBoxColumn"].Visible = true;

            reklamaDataGridView.Columns["netto"].Visible = true;
            reklamaDataGridView.Columns["brutto"].Visible = true;
            // ReSharper restore PossibleNullReferenceException
        }

        /// <summary>
        /// Kolumny z analizy ceny modułu
        /// </summary>
        private void analizaCenyModuluColumns()
        {
            if (reklamaDataGridView == null) return;

            // ReSharper disable PossibleNullReferenceException
            reklamaDataGridView.Columns["CENA_MODULU"].Visible = true;
            reklamaDataGridView.Columns["CENA_MIN"].Visible = true;
            reklamaDataGridView.Columns["CENA"].Visible = true;
            reklamaDataGridView.Columns["PROCENT_PROWIZJI"].Visible = true;
            reklamaDataGridView.Columns["emisjaDataGridViewTextBoxColumn"].Visible = true;
            reklamaDataGridView.Columns["TYP"].Visible = true;

            reklamaDataGridView.Columns["tYTUŁDataGridViewTextBoxColumn"].Visible = false;
            reklamaDataGridView.Columns["oDDataGridViewTextBoxColumn"].Visible = false;
            reklamaDataGridView.Columns["FirstName"].Visible = false;
            reklamaDataGridView.Columns["fAKTURANUMERDataGridViewTextBoxColumn"].Visible = false;
            reklamaDataGridView.Columns["dATAOSTATNIEJMODYFIKACJIDataGridViewTextBoxColumn"].Visible = false;
            reklamaDataGridView.Columns["dATAZAPŁATYDataGridViewTextBoxColumn"].Visible = false;
            reklamaDataGridView.Columns["zAPŁACONODataGridViewCheckBoxColumn"].Visible = false;
            reklamaDataGridView.Columns["fAKTURAWYSTAWIONODataGridViewCheckBoxColumn"].Visible = false;
            reklamaDataGridView.Columns["zATWIERDZONODODRUKUDataGridViewCheckBoxColumn"].Visible = false;
            reklamaDataGridView.Columns["wYSDataGridViewTextBoxColumn"].Visible = true;
            reklamaDataGridView.Columns["sZERDataGridViewTextBoxColumn"].Visible = true;

            reklamaDataGridView.Columns["netto"].Visible = false;
            reklamaDataGridView.Columns["brutto"].Visible = false;
            // ReSharper restore PossibleNullReferenceException
        }

        private void odswiezToolStripButton_Click(object sender, EventArgs e)
        {
            if (commandExecuted)
            {
                Cursor = Cursors.WaitCursor;

                rEKLAMADataSet.ReklamyZestawienie.Clear();
                sqlDataAdapter.Fill(rEKLAMADataSet.ReklamyZestawienie);
                reklamaDataGridView.Refresh();

                Cursor = Cursors.Default;
            }

        }

        private void reklamyZestawienieBindingSource_ListChanged(object sender, ListChangedEventArgs e)
        {
            podsumuj();
        }


        /// <summary>
        /// Podsumowuje brutto i netto z wyswietlonych zamowien
        /// </summary>
        private void podsumuj()
        {

            if (reklamyZestawienieBindingSource.List.Count != 0)
            {
                decimal brutto = Convert.ToDecimal(rEKLAMADataSet.ReklamyZestawienie.Compute("Sum(BRUTTO)", ""));
                decimal netto = Convert.ToDecimal(rEKLAMADataSet.ReklamyZestawienie.Compute("Sum(netto)", ""));

                sumaBruttoTextBox.Text = String.Format("{0:C}", brutto);
                sumaNettoTextBox.Text = String.Format("{0:C}", netto);

            }
            else
            {
                sumaBruttoTextBox.Clear();
                sumaNettoTextBox.Clear();
            }
        }

        private void drukujToolStripButton_Click(object sender, EventArgs e)
        {
            PrintDGV.Print_DataGridView(reklamaDataGridView, 50);
        }

        private void zamProToolStripButton_Click(object sender, EventArgs e)
        {
            REKLAMADataSet.ReklamyZestawienieRow reklama = Reklama;

            if (reklama == null) return;

            ProjectForm pf = new ProjectForm(reklama.ReklamaID);
            pf.ShowDialog();
        }

        private void OrdersForm_Shown(object sender, EventArgs e)
        {
            if (User.Instance().IsKierownik)
            {
                agencjaToolStripComboBox.Text = User.Instance().SymbolAgencji;
            }
            else if (User.Instance().IsHandlowiec)
            {
                agentToolStripComboBox.Text = User.Instance().Login;
            }

        }

        private void OrdersForm_Leave(object sender, EventArgs e)
        {

        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            REKLAMADataSet.ReklamyZestawienieRow reklama = Reklama;
            if (reklama == null) return;
            Cursor = Cursors.WaitCursor;
            try
            {
                PdfHelper pdfHelper = new PdfHelper(reklama.ID_REKLAMY);
                if (!pdfHelper.DisplayPdf())
                    MessageBox.Show(pdfHelper.ErrorMessage);
            }
            catch (System.Net.WebException exception)
            {
                PdfHelper.HandleWebException(exception);
            }
            finally
            {
                Cursor = Cursors.Default;
            }
        }

        private void excelToolStripButton_Click(object sender, EventArgs e)
        {
            Cursor = Cursors.WaitCursor;

            ExcelHelper ex = new ExcelHelper();
            ex.Export(reklamaDataGridView);

            Cursor = Cursors.Default;
        }

        private void zamowieniaToolStripButton_Click(object sender, EventArgs e)
        {
            if (reklamyZestawienieBindingSource.Current != null)
            {
                Cursor = Cursors.WaitCursor;

                DataRowView row = (DataRowView)reklamyZestawienieBindingSource.Current;
                REKLAMADataSet.ReklamyZestawienieRow rek = (REKLAMADataSet.ReklamyZestawienieRow)
                    row.Row;
                if (!rek.IsidZamowieniaNull())
                {
                    ZamowieniaForm zam = new ZamowieniaForm(rek.CustomerID, rek.idZamowienia);
                    zam.ShowDialog();
                }
                else
                {
                    ZamowieniaForm zam = new ZamowieniaForm(rek.CustomerID);
                    zam.ShowDialog();
                }

                Cursor = Cursors.Default;
            }
        }

        #region IForm Members

        public void CloseForm()
        {
            orderForm = null;
        }

        #endregion
    }
}