using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Text.RegularExpressions;

namespace Baza_Reklam
{
    public partial class ClientsForm : Form
    {
        private int Panel1Height = 380;
        private int splitConteiner1Height = 230;

        //zmienna pomocnicza do kontroli clientsDataGridView_CellLeave
        private bool dodajKlienta = false;
        
        //obiekty wykorzytywane przy wyszukiwaniu
        private SqlDataAdapter sqlDataAdapter;
        private SqlCommand command;
        private string query = "select top 2000 K.* from KLIENCI K ";

        //sigleton
        private static ClientsForm clientsForm;
        
        public static ClientsForm getClientsForm(MDIBazaReklam parent)
        {
            if (clientsForm == null)
            {
                clientsForm = new ClientsForm(parent);               
            }
            return clientsForm;
        }

        private ClientsForm(MDIBazaReklam parent)
        {
            InitializeComponent();

            this.MdiParent = parent;

            //podmiana connstringa
            this.kL_1TableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;
            this.kL_2TableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;
            this.kL_3TableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;
            this.kL_KLIENCITableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;
            this.kLIENCI_OSOBY_DO_KONTAKTUTableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;
            this.kLIENCITableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;
            this.kONTAKTYTableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;
            this.zestawienieFakturTableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;
            this.rEKLAMATableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;
            this.fakturA_DETAILSTableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;
            this.fAKTURYTableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;
            this.shedulerTableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;
            this.oFERTY_MAINTableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;
            this.aGENCITableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;
            this.kLIENCI_TYTULTableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;
            //this.li
            
            SqlConnection conn = new SqlConnection(ConnString.getConnString().Value);
            
            this.command = new SqlCommand();
            this.command.CommandType = CommandType.Text;
            this.command.Connection = conn;
            
            this.sqlDataAdapter = new SqlDataAdapter();
            this.sqlDataAdapter.SelectCommand = command;

            //dodanie obrazkow do drzewka w zakladce KLASYFIKACJA KLIENTA
            ImageList imageList = new ImageList();
            imageList.Images.Add(Baza_Reklam.Properties.Resources.bullet_ball_glass_green);
            imageList.Images.Add(Baza_Reklam.Properties.Resources.bullet_ball_glass_red);
            klasyfikacjaTreeView.ImageList = imageList;
            klasyfikacjaTreeView.ImageIndex = 0;
            klasyfikacjaTreeView.SelectedImageIndex = 1;
            
            //generuje piersze węzły w drzewie
            generateNodes();

            //ustawia uprawnienia
            uprawnienia();

            //dodaje podpowiedzi do buttonow
            podpowiedzi();
      }

        private void ClientsForm_Load(object sender, EventArgs e)
        {
             this.WindowState = FormWindowState.Maximized;

            //bez tego zakładki ZAMÓWIENIA i FAKTURY po wzięciu programu do paska i ponownym pokazaniu
            //rozjezdzaja sie...
            zamowieniaSplitContainer.Panel2MinSize = 200;            
            fakturySplitContainer.Panel1MinSize = 180;

            /*
            //pobiera listy agentów i agencji do wyszukiwania - toolstrip nie obsluguje databindings
            command.CommandText = "select ID_AGENCJI,Symbol from dbo.AGENCJE where aktywna = 1";
            command.Connection.Open();
            SqlDataReader reader = command.ExecuteReader();
            while (reader.Read())
            {
                agencjaToolStripComboBox.Items.Add(reader.GetValue(1).ToString());
            }
            command.Connection.Close();

            command.CommandText = "select Symbol from dbo.AGENCI where aktywny=1 order by Symbol";
            command.Connection.Open();
            reader = command.ExecuteReader();
            while (reader.Read())
            {
                agentToolStripComboBox.Items.Add(reader.GetValue(0).ToString());
            //    userNameComboBox.Items.Add(reader.GetValue(0).ToString());
            }
            command.Connection.Close();
            */

            DBBindings.bindujAgencje(agencjaToolStripComboBox);
            DBBindings.bindujAgentow(agentToolStripComboBox);
            agencjaToolStripComboBox.SelectedIndexChanged += new EventHandler(agencjaToolStripComboBox_SelectedIndexChanged);
  
            this.aGENCITableAdapter.Fill(this.sLOWNIKDataSet.AGENCI);
          //  if (User.getUser().St_kierownik)
          //  {

            if (!ConnString.getConnString().Value.Contains("truck"))
            {
                if (!User.getUser().St_kierownik)
                {
                    aGENCIBindingSource.Filter = "aktywny=1 AND id_agencji=" + User.getUser().IdAgencji;
                }
            }
            else if (!User.getUser().St_kierownik)
            {
                aGENCIBindingSource.Filter = "aktywny=1 AND id_agencji=" + User.getUser().IdAgencji;
            }
          

            //pobiera pierwsze wezly w drzewku z klasyfikacji
            //klasyfikacjaWezlyGlowne();
            DBBindings.dodajKlasyfikacjePoziom1(klasyfikacjaTreeView);

            SLOWNIKDataSetTableAdapters.LISTA_TYTULOWTableAdapter ta = new SLOWNIKDataSetTableAdapters.LISTA_TYTULOWTableAdapter();
            ta.Connection.ConnectionString = ConnString.getConnString().Value;
            tytulyListBox.DataSource = ta.GetData();
            tytulyListBox.DisplayMember = "SYMB";
            tytulyListBox.ValueMember = "SYMB";

        }

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

                DataRowView row = (DataRowView)this.kLIENCIBindingSource.Current;
                int customerId = Int32.Parse(row["CustomerId"].ToString());

                switch (tabControl2.SelectedTab.Name)
                {
                    case "daneKlientaTab":
                        groupBox1.Enabled = kLIENCIBindingSource.List.Count == 0 ? false : true;
                        groupBox2.Enabled = kLIENCIBindingSource.List.Count == 0 ? false : true;
                        groupBox3.Enabled = kLIENCIBindingSource.List.Count == 0 ? false : true;
                        groupBox4.Enabled = kLIENCIBindingSource.List.Count == 0 ? false : true;
                        groupBox5.Enabled = kLIENCIBindingSource.List.Count == 0 ? false : true;
                        tabControl1.Enabled = kLIENCIBindingSource.List.Count == 0 ? false : true;
                        this.kLIENCI_TYTULTableAdapter.FillByCustomerId(this.rEKLAMADataSet.KLIENCI_TYTUL, customerId);
                        break;
                    case "zamowieniaTab":
                        this.rEKLAMADataSet.REKLAMA.Clear();
                        this.rEKLAMATableAdapter.FillByCustomerId(this.rEKLAMADataSet.REKLAMA, customerId);
                        this.zamDataGridView.Sort(dATAZAMÓWIENIADataGridViewTextBoxColumn, ListSortDirection.Descending);
                        this.zamDataGridView.Refresh();
                        break;
                    case "fakturyTab":
                        this.rEKLAMADataSet.FAKTURY.Clear();
                        this.zestawienieFakturTableAdapter.FillByCustomerID(this.rEKLAMADataSet.ZestawienieFaktur, customerId);
                        this.fakturyDataGridView.Refresh();
                        break;
                    case "klasyfikacjaTabPage":
                        this.rEKLAMADataSet.KL_KLIENCI.Clear();
                        kL_KLIENCITableAdapter.ClearBeforeFill = true;
                        kL_KLIENCITableAdapter.FillByCustomerId(rEKLAMADataSet.KL_KLIENCI, customerId);
                        kL_1TableAdapter.Fill(sLOWNIKDataSet.KL_1);
                        kL_2TableAdapter.Fill(sLOWNIKDataSet.KL_2);
                        kL_3TableAdapter.Fill(sLOWNIKDataSet.KL_3);
                        break;
                    case "kontaktyTabPage":
                        this.rEKLAMADataSet.KONTAKTY.Clear();
                        this.kONTAKTYTableAdapter.FillByCustomerId(this.rEKLAMADataSet.KONTAKTY, customerId);
                        groupBox7.Enabled = kONTAKTYBindingSource.List.Count == 0 ? false : true;
                        break;
                    case "osobyDoKontaktuTabPage":
                        this.rEKLAMADataSet.KLIENCI_OSOBY_DO_KONTAKTU.Clear();
                        this.kLIENCI_OSOBY_DO_KONTAKTUTableAdapter.FillByCustomerId(this.rEKLAMADataSet.KLIENCI_OSOBY_DO_KONTAKTU, customerId);
                        groupBox6.Enabled = kLIENCI_OSOBY_DO_KONTAKTUBindingSource.List.Count == 0 ? false : true;
                        break;
                    case "doZalatwienia":
                        this.rEKLAMADataSet.sheduler.Clear();
                        this.shedulerTableAdapter.FillByCustomerId(this.rEKLAMADataSet.sheduler, customerId);
                        groupBox15.Enabled = shedulerBindingSource.List.Count == 0 ? false : true;
                        break;
                    case "ofertyTabPage":
                        this.rEKLAMADataSet.OFERTY_MAIN.Clear();
                        this.oFERTY_MAINTableAdapter.FillByCustomerId(this.rEKLAMADataSet.OFERTY_MAIN, customerId);
                        break;
                    default:
                        break;
                }

                if (((REKLAMADataSet.KLIENCIRow)row.Row).IsCountryNull())
                {
                    countryComboBox.SelectedIndex = -1;
                }
                               
                this.Cursor = Cursors.Default;
            }
        }

        private void tabControl2_SelectedIndexChanged(object sender, EventArgs e)
        {               
            if (tabControl2.SelectedTab.Name != "daneKlientaTab")
            {
                dodajToolStripButton.Enabled = false;
                zapiszDaneToolStripButton.Enabled = false;
                usunToolStripButton.Enabled = false;
            }
            else {
                dodajToolStripButton.Enabled = true;
                zapiszDaneToolStripButton.Enabled = true;
                usunToolStripButton.Enabled = true;
            }

            if (this.kLIENCIBindingSource.Current != null)
            {
                this.Cursor = Cursors.WaitCursor;

                DataRowView row = (DataRowView)this.kLIENCIBindingSource.Current;
                int customerId = Int32.Parse(row["CustomerId"].ToString());

                switch (tabControl2.SelectedTab.Name)
                {
                    case "daneKlientaTab":
                        groupBox1.Enabled = kLIENCIBindingSource.List.Count == 0 ? false : true;
                        groupBox2.Enabled = kLIENCIBindingSource.List.Count == 0 ? false : true;
                        groupBox3.Enabled = kLIENCIBindingSource.List.Count == 0 ? false : true;
                        groupBox4.Enabled = kLIENCIBindingSource.List.Count == 0 ? false : true;
                        groupBox5.Enabled = kLIENCIBindingSource.List.Count == 0 ? false : true;
                        tabControl1.Enabled = kLIENCIBindingSource.List.Count == 0 ? false : true;
                        this.kLIENCI_TYTULTableAdapter.FillByCustomerId(this.rEKLAMADataSet.KLIENCI_TYTUL,customerId);        
                        break;
                    case "zamowieniaTab":
                        this.rEKLAMADataSet.REKLAMA.Clear();
                        this.rEKLAMATableAdapter.FillByCustomerId(this.rEKLAMADataSet.REKLAMA, customerId);
                        this.zamDataGridView.Sort(dATAZAMÓWIENIADataGridViewTextBoxColumn, ListSortDirection.Descending);
                        this.zamDataGridView.Refresh();
                        break;
                    case "fakturyTab":
                        this.rEKLAMADataSet.FAKTURY.Clear();
                        this.zestawienieFakturTableAdapter.FillByCustomerID(this.rEKLAMADataSet.ZestawienieFaktur, customerId);
                        this.fakturyDataGridView.Refresh();
                        break;
                    case "klasyfikacjaTabPage":
                        this.rEKLAMADataSet.KL_KLIENCI.Clear();
                        kL_KLIENCITableAdapter.ClearBeforeFill = true;
                        kL_KLIENCITableAdapter.FillByCustomerId(rEKLAMADataSet.KL_KLIENCI, customerId);
                        kL_1TableAdapter.Fill(sLOWNIKDataSet.KL_1);
                        kL_2TableAdapter.Fill(sLOWNIKDataSet.KL_2);
                        kL_3TableAdapter.Fill(sLOWNIKDataSet.KL_3);
                        break;                       
                    case "kontaktyTabPage":
                        this.rEKLAMADataSet.KONTAKTY.Clear();
                        this.kONTAKTYTableAdapter.FillByCustomerId(this.rEKLAMADataSet.KONTAKTY, customerId);
                        groupBox7.Enabled = kONTAKTYBindingSource.List.Count == 0 ? false : true;
                        break;
                    case "osobyDoKontaktuTabPage":
                        this.rEKLAMADataSet.KLIENCI_OSOBY_DO_KONTAKTU.Clear();
                        this.kLIENCI_OSOBY_DO_KONTAKTUTableAdapter.FillByCustomerId(this.rEKLAMADataSet.KLIENCI_OSOBY_DO_KONTAKTU, customerId);
                        groupBox6.Enabled = kLIENCI_OSOBY_DO_KONTAKTUBindingSource.List.Count == 0 ? false : true;
                        break;
                    case "doZalatwienia":
                        this.rEKLAMADataSet.sheduler.Clear();
                        this.shedulerTableAdapter.FillByCustomerId(this.rEKLAMADataSet.sheduler, customerId);
                        groupBox15.Enabled = shedulerBindingSource.List.Count == 0 ? false : true;
                        break;
                    case "ofertyTabPage":
                        this.rEKLAMADataSet.OFERTY_MAIN.Clear();
                        this.oFERTY_MAINTableAdapter.FillByCustomerId(this.rEKLAMADataSet.OFERTY_MAIN, customerId);
                        break;                        
                    default:
                        break;
                }
                this.Cursor = Cursors.Default;
            }

        }

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

                /*
                OrderDetails od = new OrderDetails();
                od.pokazSzczegolyZamowienia(idRek);
                DialogResult result = od.ShowDialog();
                */

                OrderDetails.getOrderDetails().pokazSzczegolyZamowienia(idRek);

                if (OrderDetails.getOrderDetails().ShowDialog() == DialogResult.OK)
                {
                    this.rEKLAMADataSet.REKLAMA.Clear();
                    this.rEKLAMATableAdapter.FillByCustomerId(this.rEKLAMADataSet.REKLAMA, custId);
                }
            }
        }

        private void nowaButton_Click(object sender, EventArgs e)
        {
            if (kLIENCIBindingSource.Current != null)
            {
                DataRowView row = (DataRowView)this.kLIENCIBindingSource.Current;
                REKLAMADataSet.KLIENCIRow klient = (REKLAMADataSet.KLIENCIRow)row.Row;

                if (klient.IskodKlientaNull())
                {
                    MessageBox.Show("Uzupełnij kod klienta");
                    return;
                }

                OrderDetails.getOrderDetails().dodajNoweZamowienie(klient.CustomerID, klient.kodKlienta);

                if (OrderDetails.getOrderDetails().ShowDialog() == DialogResult.OK)
                {
                    this.rEKLAMADataSet.REKLAMA.Clear();
                    this.rEKLAMATableAdapter.FillByCustomerId(this.rEKLAMADataSet.REKLAMA,klient.CustomerID);
                }
            }
        }

        private void usunButton_Click(object sender, EventArgs e)
        {
            if (rEKLAMABindingSource.Current != null)
            {
                bool ok = MessageBox.Show("Czyna pewno chcesz usunąć zlecenie?", "", MessageBoxButtons.YesNo) == DialogResult.Yes ? true : false;

                DataRowView row = (DataRowView)rEKLAMABindingSource.Current;
                if (row["id_faktury"] != DBNull.Value)
                {
                    MessageBox.Show("Wystawiono już fakturę.Nie można usunąć zlecenia.");
                    return;
                }

                if (row["ZATWIERDZONO DO DRUKU"] != DBNull.Value)
                {
                    if (Convert.ToBoolean(row["ZATWIERDZONO DO DRUKU"]))
                    {
                        MessageBox.Show("Zamówienie zatwierdzone do druku.Nie można usunąć zlecenia.");
                        return;
                    }
                }

                if (row["ZAPŁACONO"] != DBNull.Value)
                {
                    if (Convert.ToBoolean(row["ZAPŁACONO"]))
                    {
                        MessageBox.Show("Zamówienie zapłacone.Nie można usunąć zlecenia.");
                        return;
                    }
                }

                if (ok)
                {
                    int idRek = Int32.Parse(row["reklamaId"].ToString());
                    this.rEKLAMABindingSource.RemoveCurrent();
                    this.rEKLAMATableAdapter.Update(this.rEKLAMADataSet.REKLAMA);

                    SqlCommand command = new SqlCommand("DELETE FROM [UKAŻE SIĘ W NR] WHERE (ReklamaId = @rekID)");
                    command.Parameters.AddWithValue("@rekID", idRek);
                    command.Connection = new SqlConnection(ConnString.getConnString().Value);

                    command.Connection.Open();
                    try
                    {
                        command.ExecuteNonQuery();
                    }
                    catch (Exception e1)
                    {
                        MessageBox.Show(e1.Message);
                    }
                    command.Connection.Close();
                }
            }
        }

        private void wnowButton_Click(object sender, EventArgs e)
        {            
            if (rEKLAMABindingSource.Current != null)
            {                
                DataRowView row = (DataRowView)rEKLAMABindingSource.Current;
                int idRek = Int32.Parse(row["reklamaId"].ToString());
                int custId = Int32.Parse(row["customerId"].ToString());
                
                OrderDetails.getOrderDetails().wznowZamowienie(idRek);

                /*
                OrderDetails od = new OrderDetails();
                od.wznowZamowienie(idRek);
                DialogResult result = od.ShowDialog();*/

                if (OrderDetails.getOrderDetails().ShowDialog() == DialogResult.OK) 
                {
                    this.rEKLAMADataSet.REKLAMA.Clear();
                    this.rEKLAMATableAdapter.FillByCustomerId(this.rEKLAMADataSet.REKLAMA, custId);
                }
            }            
        }

        private void usunToolStripButton_Click(object sender, EventArgs e)
        {
            if (kLIENCIBindingSource.Current != null)
            {
                DataRowView row = (DataRowView)this.kLIENCIBindingSource.Current;
                int custId = Int32.Parse(row["CustomerId"].ToString());
                              
                if (kLIENCI_OSOBY_DO_KONTAKTUTableAdapter.GetDataByCustomerId(custId).Count != 0
                    || rEKLAMATableAdapter.GetDataByCustomerId(custId).Count != 0
                    || kL_KLIENCITableAdapter.GetDataByCustomerId(custId).Count !=0)
                {
                    if (MessageBox.Show("Są inne dane związane z klientem! Usunac klienta?", "", MessageBoxButtons.YesNo,
                          MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        kLIENCIBindingSource.RemoveCurrent();
                        kLIENCIBindingSource.EndEdit();
                        this.kLIENCITableAdapter.Update(this.rEKLAMADataSet.KLIENCI);
                        MessageBox.Show("Dane usunięto");
                    }
                }
                else {
                    kLIENCIBindingSource.RemoveCurrent();
                    kLIENCIBindingSource.EndEdit();
                    this.kLIENCITableAdapter.Update(this.rEKLAMADataSet.KLIENCI);
                    MessageBox.Show("Dane usunięto");                    
                }

                groupBox1.Enabled = kLIENCIBindingSource.List.Count == 0 ? false : true;
                groupBox2.Enabled = kLIENCIBindingSource.List.Count == 0 ? false : true;
                groupBox3.Enabled = kLIENCIBindingSource.List.Count == 0 ? false : true;
                groupBox4.Enabled = kLIENCIBindingSource.List.Count == 0 ? false : true;
                groupBox5.Enabled = kLIENCIBindingSource.List.Count == 0 ? false : true;
                tabControl1.Enabled = kLIENCIBindingSource.List.Count == 0 ? false : true;  
            }
        }

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

                this.sqlDataAdapter.SelectCommand = command;

                switch (e.Node.Level)
                {
                    case 0:
                        switch (e.Node.Name)
                        {
                            case "MoiKlienci":
                                this.Cursor = Cursors.WaitCursor;

                                this.rEKLAMADataSet.KLIENCI.Clear();
                                command.CommandText += " where K.UserName=@agent order by data desc";
                                command.Parameters.AddWithValue("@agent", User.getUser().Symbol_agenta);
                                sqlDataAdapter.Fill(this.rEKLAMADataSet.KLIENCI);
                                clientsDataGridView.Refresh();

                                this.Cursor = Cursors.Default;
                                break;                          
                            default:
                                break;
                        }
                        break;
                    case 1:
                        switch (e.Node.Parent.Name)
                        {
                            case "MoiKlienci":
                                switch (e.Node.Name)
                                {
                                    case "Aktywni":

                                        this.Cursor = Cursors.WaitCursor;

                                        this.rEKLAMADataSet.KLIENCI.Clear();
                                        command.CommandText += " where K.UserName=@agent AND K.Aktywny=1 order by K.data desc";
                                        command.Parameters.AddWithValue("@agent", User.getUser().Symbol_agenta);
                                        sqlDataAdapter.Fill(this.rEKLAMADataSet.KLIENCI);
                                        clientsDataGridView.Refresh();

                                        this.Cursor = Cursors.Default;
                                        break;
                                    case "Nieaktywni":

                                        this.Cursor = Cursors.WaitCursor;

                                        this.rEKLAMADataSet.KLIENCI.Clear();
                                        command.CommandText += " where K.UserName=@agent AND K.Aktywny=0 order by K.data desc";
                                        command.Parameters.AddWithValue("@agent", User.getUser().Symbol_agenta);
                                        sqlDataAdapter.Fill(this.rEKLAMADataSet.KLIENCI);
                                        clientsDataGridView.Refresh();

                                        this.Cursor = Cursors.Default;
                                        break;
                                    default:
                                        break;
                                }
                                break;
                            case "Biura":
                                this.Cursor = Cursors.WaitCursor;

                                this.rEKLAMADataSet.KLIENCI.Clear();
                                command.CommandText += " left join dbo.AGENCI A on K.UserName = A.Symbol where A.Id_agencji = @idAgencji";
                                command.Parameters.AddWithValue("@idAgencji", e.Node.Name);
                                sqlDataAdapter.Fill(this.rEKLAMADataSet.KLIENCI);
                                clientsDataGridView.Refresh();

                                this.Cursor = Cursors.Default;
                                break;
                            case "Niesklasyfikowani":
                                this.Cursor = Cursors.WaitCursor;

                                this.rEKLAMADataSet.KLIENCI.Clear();
                                command.CommandText += " left join KL_KLIENCI K2 on K.CustomerID = K2.Customerid  left join dbo.AGENCI A";
                                command.CommandText += " on K.UserName = A.Symbol where K2.ID_KL_KLIENCI is null  AND A.Id_agencji = @idAgencji";
                                command.Parameters.AddWithValue("@idAgencji", e.Node.Name);
                                sqlDataAdapter.Fill(this.rEKLAMADataSet.KLIENCI);
                                clientsDataGridView.Refresh();

                                this.Cursor = Cursors.Default;
                                break;
                            case "NiesklasyfikowaniT":
                                this.Cursor = Cursors.WaitCursor;

                                this.rEKLAMADataSet.KLIENCI.Clear();
                                command.CommandText += " left join KLIENCI_TYTUL KT on K.customerId = KT.customerId left join dbo.AGENCI A";
                                command.CommandText += " on K.UserName = A.Symbol where K.aktywny=1 AND KT.id_klienci_tytul is null  AND A.Id_agencji = @idAgencji";
                                command.Parameters.AddWithValue("@idAgencji", e.Node.Name);
                                sqlDataAdapter.Fill(this.rEKLAMADataSet.KLIENCI);
                                clientsDataGridView.Refresh();

                                this.Cursor = Cursors.Default;
                                break;
                            case "Klasyfikacja":
                                wyszukiwaniePoKlasyfikacji(e);
                                break;
                            default:
                                break;
                        }
                        break;
                    case 2:
                        if (e.Node.Parent.Parent.Name == "Klasyfikacja")
                        {
                            wyszukiwaniePoKlasyfikacji(e);
                        }
                        else
                        {
                            switch (e.Node.Parent.Parent.Name)
                            {
                                case "Niesklasyfikowani":
                                    this.Cursor = Cursors.WaitCursor;

                                    this.rEKLAMADataSet.KLIENCI.Clear();
                                    command.CommandText += " left join KL_KLIENCI K2 on K.CustomerID = K2.Customerid  left join dbo.AGENCI A";
                                    command.CommandText += " on K.UserName = A.Symbol where K2.ID_KL_KLIENCI is null  AND A.Symbol = @symAgenta";
                                    command.Parameters.AddWithValue("@symAgenta", e.Node.Name);
                                    sqlDataAdapter.Fill(this.rEKLAMADataSet.KLIENCI);
                                    clientsDataGridView.Refresh();

                                    this.Cursor = Cursors.Default;
                                    break;
                                case "NiesklasyfikowaniT":
                                    this.Cursor = Cursors.WaitCursor;

                                    this.rEKLAMADataSet.KLIENCI.Clear();
                                    command.CommandText += " left join KLIENCI_TYTUL KT on K.customerId = KT.customerId left join dbo.AGENCI A";
                                    command.CommandText += " on K.UserName = A.Symbol where K.aktywny=1 AND KT.id_klienci_tytul is null  AND A.Symbol = @symAgenta";
                                    command.Parameters.AddWithValue("@symAgenta", e.Node.Name);
                                    sqlDataAdapter.Fill(this.rEKLAMADataSet.KLIENCI);
                                    clientsDataGridView.Refresh();

                                    this.Cursor = Cursors.Default;
                                    break;
                            }
                        }
                        break;
                    case 3:
                        if (e.Node.Parent.Parent.Parent.Name == "Klasyfikacja")
                        {
                            wyszukiwaniePoKlasyfikacji(e);
                        }
                        else
                        {
                            switch (e.Node.Parent.Name)
                            {
                                case "Agenci":
                                    this.Cursor = Cursors.WaitCursor;

                                    this.rEKLAMADataSet.KLIENCI.Clear();
                                    command.CommandText += " where UserName=@agent";
                                    command.Parameters.AddWithValue("@agent", e.Node.Name);
                                    sqlDataAdapter.Fill(this.rEKLAMADataSet.KLIENCI);
                                    clientsDataGridView.Refresh();

                                    this.Cursor = Cursors.Default;
                                    break;
                                case "BrakKontaktu":
                                    this.Cursor = Cursors.WaitCursor;

                                    this.rEKLAMADataSet.KLIENCI.Clear();
                                    command.CommandText += "left join dbo.KONTAKTY K2 on K.CustomerId = K2.CustomerID " +
                                        "left join dbo.AGENCI A on K.UserName = A.Symbol " +
                                        "group by K.CustomerID, K.FirstName, K.LastName, K.OrganizationName, " +
                                        "K.Address, K.City, K.State, K.PostalCode, K.Country, K.Nip, K.ContactName, K.PhoneNumber, K.FaxNumber," +
                                        "K.Note, K.data, K.Adres_Fkatura, K.Adres_Kor, K.Platnik_VAT, K.Aktywny,  " +
                                        "K.Email, K.UserName, K.Last_Modify, K.Modify_User, K.http, K.VIES, K.regon, K.krs, K.osw_nr,K.osw_wazne_do,K.Old_ID, K.NipKraj, A.Id_agencji " +
                                        "HAVING datediff(day,max(K2.data),getdate()) > @param1 AND datediff(day,max(K2.data),getdate()) <@param2 " +
                                        "AND A.Id_agencji = @idAgencji order by datediff(day,max(K2.data),getdate()) desc";
                                    command.Parameters.AddWithValue("@idAgencji", e.Node.Parent.Parent.Name);
                                    command.Parameters.AddWithValue("@param1", e.Node.Name);

                                    if (e.Node.NextNode != null)
                                    {
                                        command.Parameters.AddWithValue("@param2", e.Node.NextNode.Name);
                                    }
                                    else
                                    {
                                        command.Parameters.AddWithValue("@param2", "9999");
                                    }

                                    sqlDataAdapter.Fill(this.rEKLAMADataSet.KLIENCI);
                                    clientsDataGridView.Refresh();

                                    this.Cursor = Cursors.Default;
                                    break;
                                case "Klasyfikacja":
                                    wyszukiwaniePoKlasyfikacjiWgAgencji(e, Int32.Parse(e.Node.Parent.Parent.Name));                    
                                    break;
                                default:
                                    break;
                            }
                        }
                        break;
                    case 4:
                       if (e.Node.Parent.Parent.Name == "Klasyfikacja")
                        {
                            wyszukiwaniePoKlasyfikacjiWgAgencji(e, Int32.Parse(e.Node.Parent.Parent.Parent.Name));
                        }                     
                        break;
                    case 5:
                        if (e.Node.Parent.Parent.Parent.Name == "Klasyfikacja")
                        {
                            wyszukiwaniePoKlasyfikacjiWgAgencji(e, Int32.Parse(e.Node.Parent.Parent.Parent.Parent.Name));
                        }                     
                        break;
                    default:
                        break;
                }
            }
        }
        
        private void szukajToolStripButton_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;

            SqlConnection conn = new SqlConnection(ConnString.getConnString().Value);      
   
            SqlCommand command = new SqlCommand();
            command.CommandType = CommandType.Text;
            command.Connection = conn;
            command.CommandText = "select top 2000 K.* from klienci K where 1=1 ";
            command.Parameters.Clear();
            
            if (agencjaToolStripComboBox.Text.Trim() != "")
            {
                command.CommandText = "select  top 2000 K.* from klienci K left join dbo.AGENCI A on K.UserName = A.Symbol left join " +
                " dbo.AGENCJE A2 on A.ID_AGENCJI = A2.Id_agencji where 1=1 AND A2.Symbol=@agencja ";
                command.Parameters.AddWithValue("@agencja", agencjaToolStripComboBox.Text.Trim());
            }

            if (nazwaToolStripTextBox.Text.Trim() != "")
            {
                command.CommandText = command.CommandText +
                    "AND (K.[firstname] like '%' + @nazwa + '%' " +
                    "OR K.[lastname] like '%' + @nazwa + '%' " +
                    "OR K.[organizationname] like '%' + @nazwa + '%') ";
                command.Parameters.AddWithValue("@nazwa", nazwaToolStripTextBox.Text.Trim());                
            }

            if (ulicaToolStripTextBox.Text.Trim() != "")
            {
                command.CommandText = command.CommandText + "AND K.[address] like '%' + @ulica + '%' ";
                command.Parameters.AddWithValue("@ulica", ulicaToolStripTextBox.Text.Trim());
            }

            if (kodToolStripTextBox.Text.Trim() != "")
            {
                command.CommandText = command.CommandText + "AND K.[postalCode] like '%' + @kod + '%' ";
                command.Parameters.AddWithValue("@kod", kodToolStripTextBox.Text.Trim());
            }

            if (miastoToolStripTextBox.Text.Trim() != "")
            {
                command.CommandText = command.CommandText + "AND K.[city] like '%' + @miasto + '%' ";
                command.Parameters.AddWithValue("@miasto", miastoToolStripTextBox.Text.Trim());   
            }

            if (NIPStripTextBox.Text.Trim() != "")
            {
                command.CommandText = command.CommandText + "AND K.[Nip]=@nip ";
                command.Parameters.AddWithValue("@nip", NIPStripTextBox.Text.Trim());
            }

            if (agentToolStripComboBox.Text.Trim() != "")
            {
                command.CommandText = command.CommandText + "AND K.[UserName]=@agent ";
                command.Parameters.AddWithValue("@agent", agentToolStripComboBox.Text.Trim());
            }

            if (panstwoToolStripTextBox.Text.Trim() != "")
            {
                command.CommandText = command.CommandText + "AND K.[country] like '%' + @panstwo + '%' ";
                command.Parameters.AddWithValue("@panstwo", panstwoToolStripTextBox.Text.Trim());
            }

            if (kodKlientaToolStripTextBox.Text.Trim() != "")
            {
                command.CommandText = command.CommandText + "AND K.[kodKlienta] like '%' + @kodKlienta + '%' ";
                command.Parameters.AddWithValue("@kodKlienta", kodKlientaToolStripTextBox.Text.Trim());
            }

            sqlDataAdapter.SelectCommand = command;

            this.rEKLAMADataSet.KLIENCI.Clear();
          
            try
            {
                sqlDataAdapter.Fill(this.rEKLAMADataSet.KLIENCI);
            }
            catch (Exception e1)
            {
                MessageBox.Show(e1.Message);
            }

            this.clientsDataGridView.Refresh();

            treeView1.CollapseAll();
            treeView1.SelectedNode = null;

            this.Cursor = Cursors.Default;
            
        }

        private void fakturaButton_Click(object sender, EventArgs e)
        {
            if (rEKLAMABindingSource.Current != null)
            {
                DataRowView row = (DataRowView)this.rEKLAMABindingSource.Current;
                int idReklamy = Convert.ToInt32(row["reklamaId"]);
                Facturer f = new Facturer(idReklamy);

                if (f.ShowDialog() == DialogResult.OK) {
                    this.rEKLAMADataSet.REKLAMA.Clear();
                    DataRowView r = (DataRowView)this.kLIENCIBindingSource.Current;
                    int customerId = Int32.Parse(r["CustomerId"].ToString());
                    this.rEKLAMATableAdapter.FillByCustomerId(this.rEKLAMADataSet.REKLAMA, customerId);
                    this.zamDataGridView.Sort(dATAZAMÓWIENIADataGridViewTextBoxColumn, ListSortDirection.Descending);
                    this.zamDataGridView.Refresh();                                                          
                }
            }
        }

        private void klButton_Click(object sender, EventArgs e)
        {
            if (kLIENCIBindingSource.Current != null){
                
                if (this.kLKLIENCIBindingSource.Current != null)
                {
                    kLKLIENCIBindingSource.EndEdit();

                    DataRowView row = (DataRowView)this.kLKLIENCIBindingSource.Current;
                    row["username"] = User.getUser().Login;

                    kL_KLIENCITableAdapter.Update(rEKLAMADataSet.KL_KLIENCI);
                    MessageBox.Show("Dane zapisane");
                }
            }        
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (rEKLAMABindingSource.Current != null)
            {
                DataRowView row = (DataRowView)rEKLAMABindingSource.Current;
                int idRek = Int32.Parse(row["reklamaId"].ToString());
                ProjectForm pf = new ProjectForm(idRek);
                pf.ShowDialog();
            }                        
        }

        private void treeView1_AfterExpand(object sender, TreeViewEventArgs e)
        {
            if (e.Node != null)
            {
                TreeNode node;

                switch (e.Node.Level)
                {
                    case 0:
                        switch (e.Node.Name)
                        {
                            case "MoiKlienci":
                                e.Node.Nodes.Clear();

                                node = new TreeNode("Aktywni");
                                node.Name = "Aktywni";
                                treeView1.Nodes["MoiKlienci"].Nodes.Add(node);

                                node = new TreeNode("Nieaktywni");
                                node.Name = "Nieaktywni";
                                treeView1.Nodes["MoiKlienci"].Nodes.Add(node);

                                break;
                            case "Biura":
                                DBBindings.dodajAgencjeDoWezla(e.Node);
                                break;
                            case "Klasyfikacja":
                                DBBindings.dodajKlasyfikacjePoziom1(e.Node);
                                break;
                            case "Niesklasyfikowani":
                                DBBindings.dodajAgencjeDoWezla(e.Node);
                                break;
                            case "NiesklasyfikowaniT":
                                DBBindings.dodajAgencjeDoWezla(e.Node);
                                break;
                            default:
                                break;
                        }
                        break;
                    case 1:                        
                        switch (e.Node.Parent.Name) { 
                            case "MoiKlienci":                                                            
                                break;
                            case "Biura":
                                e.Node.Nodes.Clear();

                                node = new TreeNode("Agenci");
                                node.Name = "Agenci";
                                e.Node.Nodes.Add(node);

                                //dodaje agentow do podwezla Agenci
                                DBBindings.dodajAgentowDoWezla(node, e.Node.Name);

                                node = new TreeNode("Brak kontaktu");
                                node.Name = "BrakKontaktu";
                                e.Node.Nodes.Add(node);                              

                                node = new TreeNode("90 dni");
                                node.Name = "90";
                                e.Node.Nodes["BrakKontaktu"].Nodes.Add(node);

                                node = new TreeNode("300 dni");
                                node.Name = "300";
                                e.Node.Nodes["BrakKontaktu"].Nodes.Add(node);

                                node = new TreeNode("Klasyfikacja");
                                node.Name = "Klasyfikacja";
                                DBBindings.dodajKlasyfikacjePoziom1(node);
                                e.Node.Nodes.Add(node);                             
                                break;
                            case "Klasyfikacja":
                                DBBindings.dodajKlasyfikacjePoziom2(e.Node);
                                break;
                            case "Niesklasyfikowani":
                                DBBindings.dodajAgentowDoWezla(e.Node, e.Node.Name);
                                break;
                            case "NiesklasyfikowaniT":
                                DBBindings.dodajAgentowDoWezla(e.Node, e.Node.Name);
                                break;
                            default:
                                break;
                        }
                        break;
                    case 2:
                         switch (e.Node.Parent.Parent.Name) {
                             case "Klasyfikacja":
                                 DBBindings.dodajKlasyfikacjePoziom3(e.Node);
                                 break;
                             default:
                                 break;
                         }
                        break;
                    case 3:
                        switch (e.Node.Parent.Name)
                        {
                            case "Klasyfikacja":
                                DBBindings.dodajKlasyfikacjePoziom2(e.Node);
                                break;
                            default:
                                break;
                        }
                        break;
                    case 4:
                        switch (e.Node.Parent.Parent.Name)
                        {
                            case "Klasyfikacja":
                                DBBindings.dodajKlasyfikacjePoziom3(e.Node);
                                break;
                            default:
                                break;
                        }
                        break;
                    default:
                        break;
                }
            }
        }
        
        private void clientsDataGridView_CellLeave(object sender, DataGridViewCellEventArgs e)
        {
            if (!dodajKlienta)
            {
                kLIENCIBindingSource.CancelEdit();
            } else {
                dodajKlienta = false;
            }
            
        }

        private void usunFakture_Click(object sender, EventArgs e)
        {            
            if (zestawienieFakturBindingSource.Current != null)
            {
                DataRowView row = (DataRowView)zestawienieFakturBindingSource.Current;

                if (row["id_faktury"] != DBNull.Value)
                {
                    bool ok = MessageBox.Show("Czyna pewno chcesz usunąć fakturę?", "", MessageBoxButtons.YesNo) == DialogResult.Yes ? true : false;

                    if (ok)
                    {
                        this.Cursor = Cursors.WaitCursor;

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

                        int idFaktury = Convert.ToInt32(row["id_faktury"]);

                        //usuwanie faktury
                        SqlCommand command3 = new SqlCommand();
                        command3.CommandText = "delete from faktury where id_faktury = @param ";
                        command3.CommandType = CommandType.Text;
                        command3.Parameters.AddWithValue("@param", idFaktury);

                        command3.Connection = conn;

                        conn.Open();
                        command3.ExecuteNonQuery();
                        conn.Close();
                        
                        //usuwanie pozycji faktury
                        command3 = new SqlCommand();
                        command3.CommandText = "delete from faktura_details where id_faktury = @param ";
                        command3.CommandType = CommandType.Text;
                        command3.Parameters.AddWithValue("@param", idFaktury);

                        command3.Connection = conn;

                        conn.Open();
                        command3.ExecuteNonQuery();
                        conn.Close();

                        //usuniecie informacji o fakturze z tabeli REKLAMA
                        command3.CommandText = "update REKLAMA set ID_FAKTURY = null where ID_FAKTURY = @param ";

                        conn.Open();
                        command3.ExecuteNonQuery();
                        conn.Close();

                        zestawienieFakturBindingSource.RemoveCurrent();

                        this.Cursor = Cursors.Default;
                    }
                }                               
            }  
        }

        private void ukryjToolStripButton_Click(object sender, EventArgs e)
        {
            if (panel1.Visible)
            {
                panel1.Visible = false;
                ukryjToolStripButton.ToolTipText = "Pokaż szczegóły";
                dodajToolStripButton.Enabled = false;
                usunToolStripButton.Enabled = false;
                zapiszDaneToolStripButton.Enabled = false;
            }
            else
            {
                panel1.Visible = true;
                ukryjToolStripButton.ToolTipText = "Ukryj szczegóły";
                dodajToolStripButton.Enabled = true;
                usunToolStripButton.Enabled = true;
                zapiszDaneToolStripButton.Enabled = true;
            }
        }

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

        private void dodajToolStripButton_Click(object sender, EventArgs e)
        {
            dodajKlienta = true;

            kLIENCIBindingSource.EndEdit();

            // pyta o zACHOWANIE zmian przed zalozeniem kolejnego rekordu
            REKLAMADataSet.KLIENCIDataTable changes =
              this.rEKLAMADataSet.KLIENCI.GetChanges(
              DataRowState.Added | DataRowState.Modified)
              as REKLAMADataSet.KLIENCIDataTable;

            if (changes != null)
            {
                if (MessageBox.Show("Czy zapisać zmiany?", "", MessageBoxButtons.YesNo,
                    MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    foreach (DataRow r in changes)
                    {
                        r["Last_Modify"] = DateTime.Now;
                        r["Modify_User"] = User.getUser().Login.ToString();
                    }

                    this.kLIENCITableAdapter.Update(this.rEKLAMADataSet.KLIENCI);
                }
                else
                {
                    this.rEKLAMADataSet.KLIENCI.RejectChanges();
                    daneKlientaTab.Select();
                }
            }
                    

            //dodaje nowy rekord
            DataView datatable = (DataView)this.kLIENCIBindingSource.List;
            DataRowView row = datatable.AddNew();
            row["Last_Modify"] = DateTime.Now;
            row["data"] = DateTime.Now;
            // nie dziala, bo trigger w bazie zmienia
            row["Modify_User"] = User.getUser().Login.ToString();
            row["UserName"] = User.getUser().Login.ToString();

            kLIENCIBindingSource.MoveLast();
            kLIENCIBindingSource.EndEdit();
            tabControl2.SelectedIndex = 0;
            countryComboBox.SelectedIndex = -1;

            groupBox1.Enabled = kLIENCIBindingSource.List.Count == 0 ? false : true;
            groupBox2.Enabled = kLIENCIBindingSource.List.Count == 0 ? false : true;
            groupBox3.Enabled = kLIENCIBindingSource.List.Count == 0 ? false : true;
            groupBox4.Enabled = kLIENCIBindingSource.List.Count == 0 ? false : true;
            groupBox5.Enabled = kLIENCIBindingSource.List.Count == 0 ? false : true;
            tabControl1.Enabled = kLIENCIBindingSource.List.Count == 0 ? false : true;  

        }

        public void pokazKlienta(int customerId) {
            treeView1.SelectedNode = treeView1.Nodes["test"];
            this.rEKLAMADataSet.KLIENCI.Clear();
            this.kLIENCITableAdapter.FillByCustomerId(this.rEKLAMADataSet.KLIENCI, customerId);
            this.clientsDataGridView.Refresh();           
        }

        private void dodajKontaktToolStripButton_Click(object sender, EventArgs e)
        {
            if (kLIENCIBindingSource.Current != null) {

                kONTAKTYBindingSource.EndEdit();
                
                DataRowView row = (DataRowView)this.kLIENCIBindingSource.Current;
                int custId = Int32.Parse(row["CustomerId"].ToString());

                DataView datatable = (DataView)this.kONTAKTYBindingSource.List;
                
                DataRowView r = datatable.AddNew();
                r["customerId"] = custId;
                r["data"] = DateTime.Now;
                r["symbol_agenta"] = User.getUser().Login.ToString();

                kONTAKTYBindingSource.MoveLast();
                kONTAKTYBindingSource.EndEdit();

                groupBox7.Enabled = kONTAKTYBindingSource.List.Count == 0 ? false : true;
               
            }
        }


        private void usunKontaktToolStripButton_Click(object sender, EventArgs e)
        {
            if (this.kONTAKTYBindingSource.Current != null)
            {
                if (MessageBox.Show("Czy na pewno chcesz usunąć rekord?", "", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    kONTAKTYBindingSource.RemoveCurrent();
                    kONTAKTYTableAdapter.Update(rEKLAMADataSet.KONTAKTY);
                    //  MessageBox.Show("Dane usunięte");
                    groupBox7.Enabled = kONTAKTYBindingSource.List.Count == 0 ? false : true;

                }
            }
        }

        private void wplataButton_Click(object sender, EventArgs e)
        {
            if (rEKLAMABindingSource.Current != null) {
                DataRowView row = (DataRowView)this.rEKLAMABindingSource.Current;
                int idReklamy = Convert.ToInt32(row["reklamaId"]);
                int custId = Convert.ToInt32(row["customerId"]);
                PaymentForm p = new PaymentForm(idReklamy);
                if (p.ShowDialog() == DialogResult.OK) {
                    rEKLAMATableAdapter.ClearBeforeFill = true;
                    rEKLAMATableAdapter.FillByCustomerId(this.rEKLAMADataSet.REKLAMA,custId);
                };
            }
        }

        private void zamDataGridView_CellLeave(object sender, DataGridViewCellEventArgs e)
        {      
            rEKLAMABindingSource.CancelEdit();
        }

        private void fakturyDataGridView_CellLeave(object sender, DataGridViewCellEventArgs e)
        {
            zestawienieFakturBindingSource.CancelEdit();
        }

        private void pokFaktureButton_Click(object sender, EventArgs e)
        {
            if (rEKLAMABindingSource.Current != null)
            {               
                DataRowView row = (DataRowView)rEKLAMABindingSource.Current;
                REKLAMADataSet.REKLAMARow reklama = (REKLAMADataSet.REKLAMARow)row.Row;

                if (!reklama.IsID_FAKTURYNull())
                {
                    this.Cursor = Cursors.WaitCursor;

                    int idFaktury = Convert.ToInt32(row["id_faktury"]);

                    FactureViewer fv = new FactureViewer(idFaktury, true, 0);
                    fv.ShowDialog();

                    this.Cursor = Cursors.Default;
                }
                else
                {
                    MessageBox.Show("Nie wystawiono faktury dla zlecenia");
                }
            }
        }

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

                DataRowView row = (DataRowView)rEKLAMABindingSource.Current;
                int idRek = Convert.ToInt32(row["reklamaId"]);
                OrderViewer ov = new OrderViewer(idRek);

                this.Cursor = Cursors.Default;

                ov.ShowDialog();
            }
        }

        private void zapiszDaneToolStripButton_Click(object sender, EventArgs e)
        {
            //zmiana modify user i modify date
            if (this.kLIENCIBindingSource.Current != null)
            {
                kLIENCIBindingSource.EndEdit();
                DataRowView row = (DataRowView)this.kLIENCIBindingSource.Current;
                REKLAMADataSet.KLIENCIRow klient = (REKLAMADataSet.KLIENCIRow)row.Row;
                
                if (!Utils.kodKlientaUnikalny(kodKlientaTextBox.Text, userNameComboBox.Text,klient.CustomerID))
                {
                    MessageBox.Show(
                        String.Format("Dla agenta {0} istnieje klient o kodzie {1}.\nZmień kod klienta",
                        userNameComboBox.Text, kodKlientaTextBox.Text),"",MessageBoxButtons.OK,MessageBoxIcon.Stop);
                    return;
                }

                kLIENCIBindingSource.EndEdit();
                row["Last_Modify"] = DateTime.Now;

                Validate();
                kLIENCIBindingSource.EndEdit();
                kLIENCITableAdapter.Update(rEKLAMADataSet.KLIENCI);
                
                kLIENCI_OSOBY_DO_KONTAKTUBindingSource.EndEdit();
                kLIENCI_OSOBY_DO_KONTAKTUTableAdapter.Update(rEKLAMADataSet.KLIENCI_OSOBY_DO_KONTAKTU);
                MessageBox.Show("Dane zapisane");
            }
        }

        private void zapiszKontaktToolStripButton_Click(object sender, EventArgs e)
        {
            kONTAKTYBindingSource.EndEdit();
            kONTAKTYTableAdapter.Update(rEKLAMADataSet.KONTAKTY);
            MessageBox.Show("Dane zapisane");                
        }

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

                DataRowView row = (DataRowView) rEKLAMABindingSource.Current;
                int reklamaId = Convert.ToInt32(row["reklamaId"]);
                string idReklamy = row["id reklamy"].ToString();

                string tytul;
                int grzbiet;
                string miasto;
                byte staryNowyArchiwum;
                
                Produkcja.argumentyDoSciezki(reklamaId,idReklamy,out tytul, out grzbiet,out miasto,out staryNowyArchiwum);               
               
                string sciezka = Produkcja.GetReklamaFileName(idReklamy,tytul,grzbiet,miasto,staryNowyArchiwum,"jpg");

                this.Cursor = Cursors.Default;

                if (File.Exists(sciezka))
                {
                    System.Diagnostics.Process.Start(sciezka);
                }
                else
                {
                    MessageBox.Show("Nie znaleziono pliku:" + sciezka);
                }   
            }

        }

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

                DataRowView row = (DataRowView)rEKLAMABindingSource.Current;
                
                int reklamaId = Convert.ToInt32(row["reklamaId"]);
                string idReklamy = row["id reklamy"].ToString();
                
                string tytul;
                int grzbiet;
                string miasto;
                byte staryNowyArchiwum;

                Produkcja.argumentyDoSciezki(reklamaId,idReklamy, out tytul, out grzbiet, out miasto, out staryNowyArchiwum);

                string sciezka = Produkcja.GetReklamaFileName(idReklamy, tytul, grzbiet, miasto, staryNowyArchiwum, "eps");
              
                this.Cursor = Cursors.Default;

                if (File.Exists(sciezka))
                {
                    System.Diagnostics.Process.Start(sciezka);
                }
                else
                {
                    MessageBox.Show("Nie znaleziono pliku: " + sciezka);
                }

            }
        }


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

                DataRowView row = (DataRowView)rEKLAMABindingSource.Current;
                int reklamaId = Convert.ToInt32(row["reklamaId"]);
                string idReklamy = row["id reklamy"].ToString();

                string tytul;
                int grzbiet;
                string miasto;
                byte staryNowyArchiwum;

                Produkcja.argumentyDoSciezki(reklamaId,idReklamy, out tytul, out grzbiet, out miasto, out staryNowyArchiwum);

                string sciezka = Produkcja.GetReklamaFileName(idReklamy, tytul, grzbiet, miasto, staryNowyArchiwum, "pdf");

                this.Cursor = Cursors.Default;

                if (File.Exists(sciezka))
                {
                    System.Diagnostics.Process.Start(sciezka);
                }
                else
                {
                    MessageBox.Show("Nie znaleziono pliku: " + sciezka);
                }

            }
        }

        private void clientsDataGridView_Leave(object sender, EventArgs e)
        {
            clientsDataGridView.EndEdit();
        }

        private void kLIENCIBindingSource_CurrentChanged(object sender, EventArgs e)
        {
            wyczyscDaneKlienta();

            if (kLIENCIBindingSource.Current != null) {

                this.Cursor = Cursors.WaitCursor;

                DataRowView row = (DataRowView)kLIENCIBindingSource.Current;
                int custId = Convert.ToInt32(row["customerId"]);
                decimal zal = (decimal)zaleglosciKlienta(custId);
                zalegaTextBox.Text = String.Format("{0:C}", zal);
                if (zal > 0)
                {
                    zalegaTextBox.BackColor = Color.LightYellow;
                    zalegaTextBox.ForeColor = Color.Red;
                }
                else {
                    zalegaTextBox.BackColor = Color.White;
                    zalegaTextBox.ForeColor = Color.Black;
                }

               agencjaLabel.Text = Utils.nazwaAgencji(row["username"].ToString());

               userNameComboBox.Text = row["username"].ToString();
              // userNameComboBox.Enabled = User.getUser().St_kierownik & (Utils.idAgencji(row["username"].ToString()) == User.getUser().IdAgencji);

               if (!ConnString.getConnString().Value.Contains("truck"))
               {
                       userNameComboBox.Enabled = (Utils.idAgencji(row["username"].ToString()) == User.getUser().IdAgencji);
               }
               else if (!User.getUser().St_kierownik)
               {
                   userNameComboBox.Enabled = (Utils.idAgencji(row["username"].ToString()) == User.getUser().IdAgencji);
               }

               if (((REKLAMADataSet.KLIENCIRow)row.Row).IsCountryNull())
               {
                   countryComboBox.SelectedIndex = -1;
               }
               
               this.Cursor = Cursors.Default;
            }
        }

        private void zamDataGridView_Leave(object sender, EventArgs e)
        {
            zamDataGridView.EndEdit();
        }

        private void fakturyDataGridView_Leave(object sender, EventArgs e)
        {
            fakturyDataGridView.EndEdit();
        }

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

            nazwaToolStripTextBox.Text = "";
            ulicaToolStripTextBox.Text = "";
            kodToolStripTextBox.Text = "";
            miastoToolStripTextBox.Text = "";
            NIPStripTextBox.Text = "";
            panstwoToolStripTextBox.Text = "";
            kodToolStripTextBox.Text = string.Empty;

            agencjaToolStripComboBox.SelectedIndex = -1;
            agentToolStripComboBox.Text = "";

            agentToolStripComboBox.SelectedIndex = -1;
            agentToolStripComboBox.Text = "";
        }
       
        private void zestawienieFakturBindingSource_ListChanged(object sender, ListChangedEventArgs e)
        {
            podsumujFaktury();
        }

        private void zapiszOsobeDoKontaktuToolStripButton_Click(object sender, EventArgs e)
        {            
            kLIENCI_OSOBY_DO_KONTAKTUBindingSource.EndEdit();
            kLIENCI_OSOBY_DO_KONTAKTUTableAdapter.Update(rEKLAMADataSet.KLIENCI_OSOBY_DO_KONTAKTU);
            MessageBox.Show("Dane zapisane"); 
        }

        private void dodajOsobeDoKontaktuToolStripButton_Click(object sender, EventArgs e)
        {
            if (kLIENCIBindingSource.Current != null)
            {
                kLIENCI_OSOBY_DO_KONTAKTUBindingSource.EndEdit();

                DataRowView row = (DataRowView)kLIENCIBindingSource.Current;
                int custId = Int32.Parse(row["CustomerId"].ToString());

                DataView datatable = (DataView)kLIENCI_OSOBY_DO_KONTAKTUBindingSource.List;
                DataRowView r = datatable.AddNew();

                kLIENCI_OSOBY_DO_KONTAKTUBindingSource.MoveLast();
                kLIENCI_OSOBY_DO_KONTAKTUBindingSource.EndEdit();

                groupBox6.Enabled = kLIENCI_OSOBY_DO_KONTAKTUBindingSource.List.Count == 0 ? false : true;
            }
        }

        private void usunOsobeDoKontaktuToolStripButton_Click(object sender, EventArgs e)
        {
            if (kLIENCI_OSOBY_DO_KONTAKTUBindingSource.Current != null)
            {
                //int id = Convert.ToInt32(((DataRowView)kLIENCI_OSOBY_DO_KONTAKTUBindingSource.Current)["id_klienci_os_kontakt"]);
                if (MessageBox.Show("Czy na pewno chcesz usunąć rekord?", "", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    kLIENCI_OSOBY_DO_KONTAKTUBindingSource.RemoveCurrent();
                    kLIENCI_OSOBY_DO_KONTAKTUTableAdapter.Update(rEKLAMADataSet.KLIENCI_OSOBY_DO_KONTAKTU);
                }
                 // MessageBox.Show("Dane usunięte");

                groupBox6.Enabled = kLIENCI_OSOBY_DO_KONTAKTUBindingSource.List.Count == 0 ? false : true;
            }
        }

        private void pokazFaktureButton_Click(object sender, EventArgs e)
        {
            if (zestawienieFakturBindingSource.Current != null)
            {
                DataRowView row = (DataRowView)zestawienieFakturBindingSource.Current;
                REKLAMADataSet.ZestawienieFakturRow faktura = (REKLAMADataSet.ZestawienieFakturRow)row.Row;

                this.Cursor = Cursors.WaitCursor;

                if (faktura.DATA_SPRZEDAZY.Year <= 2008)
                {
                    FactureViewer fv = new FactureViewer(faktura.ID_FAKTURY, true, 0);
                    fv.ShowDialog();
                }
                this.Cursor = Cursors.Default;
            }

        }

        private void daneKlientaTab_Leave(object sender, EventArgs e)
        {
            this.kLIENCIBindingSource.EndEdit();

            REKLAMADataSet.KLIENCIDataTable changes =
                this.rEKLAMADataSet.KLIENCI.GetChanges(
                DataRowState.Added | DataRowState.Modified)
                as REKLAMADataSet.KLIENCIDataTable;            

            if (changes != null)
            {
                if (MessageBox.Show("Czy zapisać zmiany?", "", MessageBoxButtons.YesNo,
                    MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    foreach (DataRow r in changes)
                    {
                        r["Last_Modify"] = DateTime.Now;
                        r["Modify_User"] = User.getUser().Login.ToString();
                    }

                    this.kLIENCITableAdapter.Update(this.rEKLAMADataSet.KLIENCI);
                }
                else
                {
                    this.rEKLAMADataSet.KLIENCI.RejectChanges();
                    daneKlientaTab.Select();
                }
            }          
        }

        private void tabControl2_Leave(object sender, EventArgs e)
        {
            kLKLIENCIBindingSource.EndEdit();

            REKLAMADataSet.KL_KLIENCIDataTable changes = rEKLAMADataSet.KL_KLIENCI.GetChanges(
              DataRowState.Added | DataRowState.Modified)
              as REKLAMADataSet.KL_KLIENCIDataTable;

            if (changes != null)
            {
                if (MessageBox.Show("Czy zapisać zmiany?", "", MessageBoxButtons.YesNo,
                    MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    DataRowView row = (DataRowView)this.kLKLIENCIBindingSource.Current;
                    row["username"] = User.getUser().Login;

                    kL_KLIENCITableAdapter.Update(rEKLAMADataSet.KL_KLIENCI);
                }
                else
                {
                    rEKLAMADataSet.KONTAKTY.RejectChanges();
                }
            }
        }

        private void kontaktyTabPage_Leave(object sender, EventArgs e)
        {
            kONTAKTYBindingSource.EndEdit();

            REKLAMADataSet.KONTAKTYDataTable changes = 
                rEKLAMADataSet.KONTAKTY.GetChanges(DataRowState.Added | DataRowState.Modified)
              as REKLAMADataSet.KONTAKTYDataTable;

            if (changes != null)
            {
                if (MessageBox.Show("Czy zapisać zmiany?", "", MessageBoxButtons.YesNo,
                    MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    kONTAKTYTableAdapter.Update(rEKLAMADataSet.KONTAKTY);
                }
                else
                {
                    rEKLAMADataSet.KONTAKTY.RejectChanges();
                }
            }

        }

        private void osobyDoKontaktuTabPage_Leave(object sender, EventArgs e)
        {
            kLIENCI_OSOBY_DO_KONTAKTUBindingSource.EndEdit();

            REKLAMADataSet.KLIENCI_OSOBY_DO_KONTAKTUDataTable changes =
               rEKLAMADataSet.KLIENCI_OSOBY_DO_KONTAKTU.GetChanges(
               DataRowState.Added | DataRowState.Modified)
               as REKLAMADataSet.KLIENCI_OSOBY_DO_KONTAKTUDataTable;

            if (changes != null)
            {
                if (MessageBox.Show("Czy zapisać zmiany?", "", MessageBoxButtons.YesNo,
                    MessageBoxIcon.Question) == DialogResult.Yes)
                {                   
                    kLIENCI_OSOBY_DO_KONTAKTUTableAdapter.Update(rEKLAMADataSet.KLIENCI_OSOBY_DO_KONTAKTU);
                }
                else
                {
                    rEKLAMADataSet.KLIENCI_OSOBY_DO_KONTAKTU.RejectChanges();
                }
            }
        }


        private void doZalatwienia_Leave(object sender, EventArgs e)
        {
            shedulerBindingSource.EndEdit();

            REKLAMADataSet.shedulerDataTable changes = rEKLAMADataSet.sheduler.GetChanges(
                DataRowState.Added | DataRowState.Modified)
                as REKLAMADataSet.shedulerDataTable;

            if (changes != null)
            {
                if (MessageBox.Show("Czy zapisać zmiany?", "", MessageBoxButtons.YesNo,
                    MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    shedulerTableAdapter.Update(rEKLAMADataSet.sheduler);                    
                }
                else
                {
                    rEKLAMADataSet.sheduler.RejectChanges();
                }
            }
        }

        private void klasyfikacjaTreeView_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;
                SqlDataReader reader;
                TreeNode node;

                switch (e.Node.Level)
                {
                    case 0:
                        e.Node.Nodes.Clear();

                        comand.CommandText = "select KL_2,ID_KL_2 from dbo.KL_2 where ID_KL_1=@param  order by KL_2";
                        comand.Parameters.Clear();
                        comand.Parameters.AddWithValue("@param", e.Node.Name);

                        conn.Open();
                        reader = comand.ExecuteReader();
                        while (reader.Read())
                        {
                            node = new TreeNode(reader.GetValue(0).ToString());
                            node.Name = reader.GetValue(1).ToString();
                            node.Nodes.Add(new TreeNode());
                            e.Node.Nodes.Add(node);
                        }
                        conn.Close();
                        break;

                    case 1:
                        e.Node.Nodes.Clear();

                        comand.CommandText = "select KL_3,ID_KL_3 from dbo.KL_3 where ID_KL_1=@param1 and ID_KL_2=@param2  order by KL_3";
                        comand.Parameters.Clear();
                        comand.Parameters.AddWithValue("@param1", e.Node.Parent.Name);
                        comand.Parameters.AddWithValue("@param2", e.Node.Name);

                        conn.Open();
                        reader = comand.ExecuteReader();
                        while (reader.Read())
                        {
                            node = new TreeNode(reader.GetValue(0).ToString());
                            node.Name = reader.GetValue(1).ToString();
                            e.Node.Nodes.Add(node);
                        }
                        conn.Close();

                        break;
                    default:
                        break;
                }
            }
        }

        private void dodKlasKlientaButton_Click(object sender, EventArgs e)
        {
            if (kLIENCIBindingSource.Current == null)
            {
                return;
            }

            if (klasyfikacjaTreeView.SelectedNode == null)
            {
                MessageBox.Show("Wybierz klasyfikację.");
                return;
            }

            DataRowView row = (DataRowView)kLIENCIBindingSource.Current;
            int custId = Int32.Parse(row["CustomerId"].ToString());

            if (klasyfikacjaTreeView.SelectedNode.Level != 2)
            {
                MessageBox.Show("Wybierz klasyfikację szczegółową.");
            }
            else
            {
                TreeNode n = klasyfikacjaTreeView.SelectedNode;
                int kl1 = Convert.ToInt32(n.Parent.Parent.Name);
                int kl2 = Convert.ToInt32(n.Parent.Name);
                int kl3 = Convert.ToInt32(n.Name);

                kL_KLIENCITableAdapter.Insert(kl1, kl2, kl3, custId, User.getUser().Login, DateTime.Now);
                kL_KLIENCITableAdapter.FillByCustomerId(rEKLAMADataSet.KL_KLIENCI, custId);
            }  

        }

        private void usunKlasKlientaButton_Click(object sender, EventArgs e)
        {
            if (kLIENCIBindingSource.Current != null)
            {
                if (kLKLIENCIBindingSource.Current != null)
                {
                    kLKLIENCIBindingSource.RemoveCurrent();
                    kL_KLIENCITableAdapter.Update(rEKLAMADataSet.KL_KLIENCI);
                }
            }
        }

        private void dodajKlButton_Click(object sender, EventArgs e)
        {
            if (klasyfikacjaTreeView.SelectedNode == null) {
                if (klTextBox.Text != "") {                    
                    kL_1TableAdapter.Insert(klTextBox.Text);
                    DBBindings.dodajKlasyfikacjePoziom1(klasyfikacjaTreeView);
                    klTextBox.Clear();
                    klasyfikacjaTreeView.SelectedNode = null;
                    return;
                }               
            }

            switch (klasyfikacjaTreeView.SelectedNode.Level) 
            {
                case 0:
                    if (klTextBox.Text != "")
                    {
                        string node = klasyfikacjaTreeView.SelectedNode.Name;
                        kL_2TableAdapter.Insert(Convert.ToInt32(node), klTextBox.Text);
                        DBBindings.dodajKlasyfikacjePoziom1(klasyfikacjaTreeView);
                        klasyfikacjaTreeView.Nodes[node].Expand();
                        klTextBox.Clear();
                    }              
                    break;
                case 1: 
                    if (klTextBox.Text != "")
                    {
                        string parentNode = klasyfikacjaTreeView.SelectedNode.Parent.Name;
                        string node = klasyfikacjaTreeView.SelectedNode.Name;
                        kL_3TableAdapter.Insert(Convert.ToInt32(parentNode), Convert.ToInt32(node), klTextBox.Text);                    
                        klasyfikacjaTreeView.Nodes[parentNode].Expand();
                        klasyfikacjaTreeView.Nodes[parentNode].Nodes[node].Collapse();
                        klasyfikacjaTreeView.Nodes[parentNode].Nodes[node].Expand();
                        klTextBox.Clear();
                    }       
                    break;
                case 2:
                    MessageBox.Show("Nie można dodac kolejnej podkategorii.");
                    break;
            }
            klasyfikacjaTreeView.SelectedNode = null;
        }

        private void usunKlButton_Click(object sender, EventArgs e)
        {
            string parentParentNode;
            string parentNode;

            if (klasyfikacjaTreeView.SelectedNode != null) {
                switch (klasyfikacjaTreeView.SelectedNode.Level) { 
                    case 0:
                        klasyfikacjaTreeView.SelectedNode.Expand();

                        if (klasyfikacjaTreeView.SelectedNode.Nodes.Count == 0)
                        {
                            kL_1TableAdapter.Delete(Convert.ToInt32(klasyfikacjaTreeView.SelectedNode.Name));

                            DBBindings.dodajKlasyfikacjePoziom1(klasyfikacjaTreeView);                        
                        }
                        else
                        {
                            MessageBox.Show("Nie można usunąć kategorii, jeżeli istnieją podkategorie.");
                        }
                        break;
                    case 1:
                        klasyfikacjaTreeView.SelectedNode.Expand();

                        if (klasyfikacjaTreeView.SelectedNode.Nodes.Count == 0)
                        {
                             parentNode = klasyfikacjaTreeView.SelectedNode.Parent.Name;

                            kL_2TableAdapter.Delete(Convert.ToInt32(klasyfikacjaTreeView.SelectedNode.Name));

                            klasyfikacjaTreeView.Nodes[parentNode].Collapse();
                            klasyfikacjaTreeView.Nodes[parentNode].Expand();
                        }
                        else {
                            MessageBox.Show("Nie można usunąć kategorii, jeżeli istnieją podkategorie.");
                        }
                        break;
                    case 2:
                        parentParentNode = klasyfikacjaTreeView.SelectedNode.Parent.Parent.Name;
                        parentNode = klasyfikacjaTreeView.SelectedNode.Parent.Name;

                        kL_3TableAdapter.Delete(Convert.ToInt32(klasyfikacjaTreeView.SelectedNode.Name));

                        klasyfikacjaTreeView.Nodes[parentParentNode].Nodes[parentNode].Collapse();
                        klasyfikacjaTreeView.Nodes[parentParentNode].Nodes[parentNode].Expand();
                        break;
                }
            }
            klasyfikacjaTreeView.SelectedNode = null;
        }

        private void klasyfikacjaTreeView_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            klasyfikacjaTreeView.SelectedNode = null;
        }

        private void klasyfikacjaDataGridView_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            //MessageBox.Show("Wybrana klasyfikacja klienta nie istnieje.");
        }
        
        /*
        private void klasyfikacjaWezlyGlowne()
        {
            klasyfikacjaTreeView.Nodes.Clear();

            SqlConnection conn = new SqlConnection(ConnString.getConnString().Value);
            SqlCommand comand = new SqlCommand();
            comand.Connection = conn;
            comand.CommandType = CommandType.Text;
            comand.CommandText = "select KL_1,ID_KL_1 from dbo.KL_1  order by KL_1";
            conn.Open();
            TreeNode node;
            TreeNode node2;
            SqlDataReader reader = comand.ExecuteReader();

            while (reader.Read())
            {
                node = new TreeNode(reader.GetValue(0).ToString());
                node.Name = reader.GetValue(1).ToString();
                node.Nodes.Add(new TreeNode());
                klasyfikacjaTreeView.Nodes.Add(node);

                node2 = (TreeNode)node.Clone();
                treeView1.Nodes["Klasyfikacja"].Nodes.Add(node2);
            }
            conn.Close();
        }*/

        private void generateNodes()
        {
            TreeNode node;

            node = new TreeNode("***");
            node.Name = "test";
            treeView1.Nodes.Add(node);

            if (User.getUser().St_handlowiec)
            {
                node = new TreeNode("Moi klienci");
                node.Name = "MoiKlienci";
                node.Nodes.Add(new TreeNode());
                treeView1.Nodes.Add(node);
            }

            node = new TreeNode("Biura");
            node.Name = "Biura";
            node.Nodes.Add(new TreeNode());
            treeView1.Nodes.Add(node);

            node = new TreeNode("Klasyfikacja");
            node.Name = "Klasyfikacja";
            node.Nodes.Add(new TreeNode());        
            treeView1.Nodes.Add(node);

            node = new TreeNode("Niesklasyfikowani");
            node.Name = "Niesklasyfikowani";
            node.Nodes.Add(new TreeNode());
            treeView1.Nodes.Add(node);

            node = new TreeNode("Niesklasyfikowani - tytuły");
            node.Name = "NiesklasyfikowaniT";
            node.Nodes.Add(new TreeNode());
            treeView1.Nodes.Add(node);
        }

        private void podpowiedzi() {
            
            ToolTip toolTip = new ToolTip();

            toolTip.AutoPopDelay = 5000;
            toolTip.InitialDelay = 1000;
            toolTip.ReshowDelay = 500;
            toolTip.ShowAlways = true;

            toolTip.SetToolTip(this.pokazZamButton, "Wydruk zamówienia");
            toolTip.SetToolTip(this.pokFaktureButton, "Wydruk faktury");
            toolTip.SetToolTip(this.dodKlasKlientaButton, "Dodaj klasyfikację klienta");
            toolTip.SetToolTip(this.usunKlasKlientaButton, "Usuń klasyfikację klienta");
            toolTip.SetToolTip(this.usunKlButton, "Usuń nową kategorię");
            toolTip.SetToolTip(this.dodajKlButton, "Dodaj nową kategorię");
            toolTip.SetToolTip(this.openWWWbutton, "Otwórz stronę");
        }

        private void uprawnienia()
        {
            //usuwanie faktury
            usunFakture.Enabled = User.getUser().St_kierownik;
            usunFakture.Visible = false;

            //dodawanie klasyfikacji
            klTextBox.Visible = User.getUser().St_kierownik;
            dodajKlButton.Visible = User.getUser().St_kierownik;
            usunKlButton.Visible = User.getUser().St_kierownik;

            dodajLogoToolStripButton.Enabled = User.getUser().St_kierownik | User.getUser().St_produkcja;
        }

        private void podsumujFaktury()
        {
            if (zestawienieFakturBindingSource.List.Count != 0)
            {
                decimal brutto = Convert.ToDecimal(rEKLAMADataSet.ZestawienieFaktur.Compute("Sum(BRUTTO)", ""));
                decimal zaplata = Convert.ToDecimal(rEKLAMADataSet.ZestawienieFaktur.Compute("Sum(suma_zaplat)", ""));

                bruttoTextBox.Text = String.Format("{0:C}", brutto);
                zaplataTextBox.Text = String.Format("{0:C}", zaplata);
            }
            else
            {
                bruttoTextBox.Clear();
                zaplataTextBox.Clear();
            }
        }

        private decimal zaleglosciKlienta(int customerId)
        {
            decimal zalega = 0;

            SqlCommand command = new SqlCommand();
            command.Connection = new SqlConnection(ConnString.getConnString().Value);
            command.CommandText = "select zalega from dbo.view_klient_winien_ma_zalega where customerid=@custId";
            command.Parameters.AddWithValue("@custId", customerId);

            command.Connection.Open();
            zalega = (decimal)(command.ExecuteScalar() ?? zalega);
            command.Connection.Close();
            return zalega;
        }

        private void openWWWbutton_Click(object sender, EventArgs e)
        {
           string adres = httpTextBox.Text.Trim();

           if (adres != "")
           {
               adres = adres.Contains("http://") ? adres : "http://" + adres;

               if (Uri.IsWellFormedUriString(adres, UriKind.Absolute))
               {
                   System.Diagnostics.ProcessStartInfo n = new System.Diagnostics.ProcessStartInfo();
                   n.CreateNoWindow = false;
                   n.FileName = adres;
                   System.Diagnostics.Process.Start(n);
               }
               else
               {
                   MessageBox.Show("Podany adres jest niepoprawny");
               }
           }
        }

        private void pokZam_Click(object sender, EventArgs e)
        {
            if (zestawienieFakturBindingSource.Current != null)
            {
                DataRowView row = (DataRowView)zestawienieFakturBindingSource.Current;

                if (row["reklamaId"] != DBNull.Value)
                {
                    int idRek = Convert.ToInt32(row["reklamaId"]);
                    
                    OrderDetails.getOrderDetails().pokazSzczegolyZamowienia(idRek);
                    OrderDetails.getOrderDetails().ShowDialog();

                    /*
                    OrderDetails od = new OrderDetails();
                    od.pokazSzczegolyZamowienia(idRek);
                    DialogResult result = od.ShowDialog();*/
                }
            }
        }

        private void dodajSprDoZalatButton_Click(object sender, EventArgs e)
        {
            if (kLIENCIBindingSource.Current != null)
            {
                shedulerBindingSource.EndEdit();

                DataRowView row = (DataRowView)this.kLIENCIBindingSource.Current;
                int custId = Int32.Parse(row["CustomerId"].ToString());

                DataView datatable = (DataView)this.shedulerBindingSource.List;

                DataRowView r = datatable.AddNew();
                r["customerId"] = custId;
                r["CustomerName"] = row["FirstName"].ToString();
                r["Akwizytor"] = User.getUser().Login.ToString();
                r["DataWprowadzenia"] = DateTime.Now;
                r["DataPrzypomnienia"] = DateTime.Now.AddDays(7);

                shedulerBindingSource.MoveLast();
                shedulerBindingSource.EndEdit();

                groupBox15.Enabled = shedulerBindingSource.List.Count == 0 ? false : true;

            }
        }

        private void usunSprDoZalatButton_Click(object sender, EventArgs e)
        {
            if (shedulerBindingSource.Current != null)
            {
                if (MessageBox.Show("Czy na pewno chcesz usunąć rekord?", "", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    shedulerBindingSource.RemoveCurrent();
                    shedulerTableAdapter.Update(rEKLAMADataSet.sheduler);
                    // MessageBox.Show("Dane usunięte");
                    groupBox15.Enabled = shedulerBindingSource.List.Count == 0 ? false : true;
                }
            }
        }

        private void zapiszSprDoZalatButton_Click(object sender, EventArgs e)
        {
            shedulerBindingSource.EndEdit();
            shedulerTableAdapter.Update(rEKLAMADataSet.sheduler);
            MessageBox.Show("Dane zapisane");
        }

        private void wplata2Button_Click(object sender, EventArgs e)
        {
            if (zestawienieFakturBindingSource.Current != null)
            {
                DataRowView row = (DataRowView)this.zestawienieFakturBindingSource.Current;
                int idReklamy = Convert.ToInt32(row["reklamaId"]);
                int custId = Convert.ToInt32(row["ID_NABYWCY"]);
                PaymentForm p = new PaymentForm(idReklamy);
                if (p.ShowDialog() == DialogResult.OK)
                {
                    zestawienieFakturTableAdapter.ClearBeforeFill = true;
                    zestawienieFakturTableAdapter.FillByCustomerID(this.rEKLAMADataSet.ZestawienieFaktur, custId);
                };
            }
        }

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

                DataRowView row = (DataRowView)kLIENCIBindingSource.Current;
                int custId = Convert.ToInt32(row["customerId"]);

                OferForm of = new OferForm(custId, 0, true);


                this.Cursor = Cursors.Default;

                of.ShowDialog();

                this.rEKLAMADataSet.OFERTY_MAIN.Clear();
                this.oFERTY_MAINTableAdapter.FillByCustomerId(this.rEKLAMADataSet.OFERTY_MAIN, custId);
            }                  
        }

        private void edycjaOfertyButton_Click(object sender, EventArgs e)
        {
            if ((kLIENCIBindingSource.Current != null) & (oFERTY_MAINBindingSource.Current != null))
            {
                this.Cursor = Cursors.WaitCursor;

                DataRowView row = (DataRowView)kLIENCIBindingSource.Current;
                int custId = Convert.ToInt32(row["customerId"]);

                DataRowView r = (DataRowView)oFERTY_MAINBindingSource.Current;
                int ofertaId = Convert.ToInt32(r["id_oferty"]);

                OferForm of = new OferForm(custId, ofertaId, false);

                this.Cursor = Cursors.Default;
                
                of.ShowDialog();
            }
        }

        private void ClientsForm_Resize(object sender, EventArgs e)
        {
            if (this.MdiParent != null)
            {
                if (this.MdiParent.WindowState == FormWindowState.Maximized)
                {
                    double h = this.MdiParent.Height;

                    int ph = (int)Math.Floor((65 * h) / 100);

                    panel1.Height = ph;

                }
                else
                {
                    splitContainer1.Height = splitConteiner1Height;
                    panel1.Height = Panel1Height;
                }
            }
        }

        private void przeniesAdresButton_Click(object sender, EventArgs e)
        {
            string[] adres = new string[4];

            adres[0] = firstNameTextBox.Text;
            adres[1] = addressTextBox.Text;
            adres[2] = postalCodeTextBox.Text + " " + cityTextBox.Text;
            adres[3] = stateComboBox.Text + " " + countryComboBox.Text;

            adres_FkaturaTextBox.Lines = adres;
            adres_KorTextBox.Lines = adres;
        }

        private void wyczyscDaneKlienta() {
            this.rEKLAMADataSet.KLIENCI_OSOBY_DO_KONTAKTU.Clear();
            this.rEKLAMADataSet.sheduler.Clear();
            this.rEKLAMADataSet.REKLAMA.Clear();
            this.rEKLAMADataSet.ZestawienieFaktur.Clear();
            this.rEKLAMADataSet.KL_KLIENCI.Clear();
            this.rEKLAMADataSet.KONTAKTY.Clear();
            this.rEKLAMADataSet.OFERTY_MAIN.Clear();

            zalegaTextBox.Clear();
            agencjaLabel.Text = "";
        }

        private void EmailButton_Click(object sender, EventArgs e)
        {

            if ((kLIENCIBindingSource.Current != null) & (oFERTY_MAINBindingSource.Current != null))
            {
                DataRowView row = (DataRowView)kLIENCIBindingSource.Current;
                int custId = Convert.ToInt32(row["customerId"]);

                DataRowView r = (DataRowView)oFERTY_MAINBindingSource.Current;
                int ofertaId = Convert.ToInt32(r["id_oferty"]);

                string temat = "Oferta nr: " + ofertaId + "/" + User.getUser().Kod_agenta.ToUpper() + "/" + DateTime.Today.Year;

                string ofertaFile = @"g:\reklamafiles\oferty\" + r["id_oferty"].ToString() + ".doc";

                if (File.Exists(ofertaFile))
                {
                    MailForm mf = new MailForm(custId, temat ,ofertaFile);
                    mf.ShowDialog();
                }
                else
                {
                    MessageBox.Show("Nie można odnaleźć oferty: " + ofertaFile);
                }

            }         
        }

        private void stateComboBox_Leave(object sender, EventArgs e)
        {
            kLIENCIBindingSource.EndEdit();
        }

        private void countryComboBox_Leave(object sender, EventArgs e)
        {
            kLIENCIBindingSource.EndEdit();
        }

        private void emailToolStripButton_Click(object sender, EventArgs e)
        {
            if (kLIENCIBindingSource.Current != null) 
            {
                DataRowView row = (DataRowView)kLIENCIBindingSource.Current;
                int custId = Convert.ToInt32(row["customerId"]);

                MailForm mf = new MailForm(custId, "", "");
                mf.ShowDialog();    
            }         
        }

        private void smsToolStripButton_Click(object sender, EventArgs e)
        {
            //format +48602315947
            if (kLIENCI_OSOBY_DO_KONTAKTUBindingSource.Current != null)
            {
                DataRowView row = (DataRowView)kLIENCI_OSOBY_DO_KONTAKTUBindingSource.Current;
                string nrTel = row["Tel"].ToString();
                int  customerId = Convert.ToInt32(row["customerId"]);

                nrTel = nrTel.Replace("-", "");
                nrTel = nrTel.Replace(" ", "");
                nrTel = nrTel.Replace("+48", "");

                if ((nrTel.Length == 10) & (nrTel[0] == Char.Parse("0")))
                {
                    nrTel = nrTel.Substring(1, 9);
                }

                if (!Regex.IsMatch(nrTel, "^[1-9]{1}[0-9]{8}"))
                {
                    MessageBox.Show("Podany nr telefony jest z złym formacie. Prawidłowy nr musi być w formacie +48xxxxxxxxx lub 0xxxxxxxxx");
                }
                else
                {
                    SMSform sf = new SMSform("+48" + nrTel, customerId);
                    sf.ShowDialog();
                }
            }
        }

        private void userNameComboBox_TextChanged(object sender, EventArgs e)
        {
            agencjaLabel.Text = Utils.nazwaAgencji(userNameComboBox.Text);
        }


        private void zrobioneToolStripButton_Click(object sender, EventArgs e)
        {
            if (shedulerBindingSource.Current != null)
            {
                DataRowView row = (DataRowView)shedulerBindingSource.Current;
                row["zalatwione"] = false;
                shedulerTableAdapter.Update(rEKLAMADataSet.sheduler);
                shedulerDataGridView.Refresh();
            }
        }

        private void niezrobioneToolStripButton_Click(object sender, EventArgs e)
        {
            if (shedulerBindingSource.Current != null)
            {
                DataRowView row = (DataRowView)shedulerBindingSource.Current;
                row["zalatwione"] = true;
                shedulerTableAdapter.Update(rEKLAMADataSet.sheduler);
                shedulerDataGridView.Refresh();
            }
        }

        private void ECARDbutton_Click(object sender, EventArgs e)
        {
            System.Diagnostics.ProcessStartInfo n = new System.Diagnostics.ProcessStartInfo();
            n.CreateNoWindow = false;
            n.FileName = "http://platnosci.admoto.pl/";
            System.Diagnostics.Process.Start(n);
        }

        private void wyszukiwaniePoKlasyfikacji(TreeViewEventArgs e)
        {            
            SqlCommand commmand = new SqlCommand();
            command.Connection = new SqlConnection(ConnString.getConnString().Value);

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

            switch (e.Node.Level)
            {
                case 1:
                    this.Cursor = Cursors.WaitCursor;
                    this.rEKLAMADataSet.KLIENCI.Clear();
                    command.CommandText = "select distinct top 2000 K.* from KLIENCI K left join KL_KLIENCI K2 on ";
                    command.CommandText += " K.CustomerID = K2.Customerid where K2.ID_KL_1=@idkl1 ";
                    command.Parameters.AddWithValue("@idkl1", e.Node.Name);
                    adapter.Fill(rEKLAMADataSet.KLIENCI);
                    clientsDataGridView.Refresh();
                    this.Cursor = Cursors.Default;
                    break;
                case 2:
                    this.Cursor = Cursors.WaitCursor;
                    this.rEKLAMADataSet.KLIENCI.Clear();
                    command.CommandText = "select distinct top 2000 K.* from KLIENCI K left join KL_KLIENCI K2 on ";
                    command.CommandText += " K.CustomerID = K2.Customerid where K2.ID_KL_1=@idkl1 AND K2.ID_KL_2=@idkl2  ";
                    command.Parameters.AddWithValue("@idkl1", e.Node.Parent.Name);
                    command.Parameters.AddWithValue("@idkl2", e.Node.Name);
                    adapter.Fill(rEKLAMADataSet.KLIENCI);
                    clientsDataGridView.Refresh();
                    this.Cursor = Cursors.Default;
                    break;
                case 3:
                    this.Cursor = Cursors.WaitCursor;
                    this.rEKLAMADataSet.KLIENCI.Clear();
                    command.CommandText = "select distinct top 2000 K.* from KLIENCI K left join KL_KLIENCI K2 on ";
                    command.CommandText += " K.CustomerID = K2.Customerid where K2.ID_KL_1=@idkl1 AND K2.ID_KL_2=@idkl2 AND K2.ID_KL_3=@idkl3";
                    command.Parameters.AddWithValue("@idkl1", e.Node.Parent.Parent.Name);
                    command.Parameters.AddWithValue("@idkl2", e.Node.Parent.Name);
                    command.Parameters.AddWithValue("@idkl3", e.Node.Name);
                    adapter.Fill(rEKLAMADataSet.KLIENCI);
                    clientsDataGridView.Refresh();
                    this.Cursor = Cursors.Default;
                    break;
            }
        }

        private void wyszukiwaniePoKlasyfikacjiWgAgencji(TreeViewEventArgs e, int idAgencji)
        {
            SqlCommand commmand = new SqlCommand();
            command.Connection = new SqlConnection(ConnString.getConnString().Value);

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

            switch (e.Node.Level)
            {
                case 3:
                    this.Cursor = Cursors.WaitCursor;
                    this.rEKLAMADataSet.KLIENCI.Clear();
                    command.CommandText = "select distinct top 2000 K.* from KLIENCI K left join KL_KLIENCI K2 on ";
                    command.CommandText += " K.CustomerID = K2.Customerid ";
                    command.CommandText += " left join dbo.AGENCI A on K.UserName = A.Symbol ";
                    command.CommandText += " where A.Id_agencji = @idAgencji AND K2.ID_KL_1=@idkl1 ";
                    command.Parameters.AddWithValue("@idkl1", e.Node.Name);
                    command.Parameters.AddWithValue("@idAgencji", idAgencji);
                    adapter.Fill(rEKLAMADataSet.KLIENCI);
                    clientsDataGridView.Refresh();
                    this.Cursor = Cursors.Default;
                    break;
                case 4:
                    this.Cursor = Cursors.WaitCursor;
                    this.rEKLAMADataSet.KLIENCI.Clear();
                    command.CommandText = "select distinct top 2000 K.* from KLIENCI K left join KL_KLIENCI K2 on ";
                    command.CommandText += " K.CustomerID = K2.Customerid ";
                    command.CommandText += " left join dbo.AGENCI A on K.UserName = A.Symbol ";
                    command.CommandText += " where A.Id_agencji = @idAgencji AND K2.ID_KL_1=@idkl1 AND K2.ID_KL_2=@idkl2 ";
                    command.Parameters.AddWithValue("@idkl1", e.Node.Parent.Name);
                    command.Parameters.AddWithValue("@idkl2", e.Node.Name);
                    command.Parameters.AddWithValue("@idAgencji", idAgencji);                  
                    adapter.Fill(rEKLAMADataSet.KLIENCI);
                    clientsDataGridView.Refresh();
                    this.Cursor = Cursors.Default;
                    break;
                case 5:
                    this.Cursor = Cursors.WaitCursor;
                    this.rEKLAMADataSet.KLIENCI.Clear();
                    command.CommandText = "select distinct top 2000 K.* from KLIENCI K left join KL_KLIENCI K2 on ";
                    command.CommandText += " K.CustomerID = K2.Customerid ";
                    command.CommandText += " left join dbo.AGENCI A on K.UserName = A.Symbol ";
                    command.CommandText += " where A.Id_agencji = @idAgencji";
                    command.CommandText += " and K2.ID_KL_1=@idkl1 AND K2.ID_KL_2=@idkl2 AND K2.ID_KL_3=@idkl3";
                    command.Parameters.AddWithValue("@idkl1", e.Node.Parent.Parent.Name);
                    command.Parameters.AddWithValue("@idkl2", e.Node.Parent.Name);
                    command.Parameters.AddWithValue("@idkl3", e.Node.Name);
                    command.Parameters.AddWithValue("@idAgencji", idAgencji);                  
                    adapter.Fill(rEKLAMADataSet.KLIENCI);
                    clientsDataGridView.Refresh();
                    this.Cursor = Cursors.Default;
                    break;
            }
        }

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

                DataRowView row = (DataRowView)kLIENCIBindingSource.Current;
                int custId = Convert.ToInt32(row["customerId"]);

                DaneKlientaViewer dnv = new DaneKlientaViewer(custId);
                dnv.ShowDialog();

                this.Cursor = Cursors.Default;
            }
        }

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

            ExcelHandler ex = new ExcelHandler();
            ex.exportToExcel(clientsDataGridView);

            this.Cursor = Cursors.Default;
        }

        private void dodajTytulButton_Click(object sender, EventArgs e)
        {
            if (kLIENCIBindingSource.Current == null)
            {
                return;
            }

            if (tytulyListBox.SelectedValue == null)
            {
                MessageBox.Show("Wybierz tytuł.");
                return;
            }

            DataRowView row = (DataRowView)kLIENCIBindingSource.Current;
            int custId = Int32.Parse(row["CustomerId"].ToString());
           
            this.kLIENCI_TYTULTableAdapter.Insert(tytulyListBox.SelectedValue.ToString(),custId, User.getUser().Login, DateTime.Now);         
            this.kLIENCI_TYTULTableAdapter.FillByCustomerId(this.rEKLAMADataSet.KLIENCI_TYTUL,custId);         
            
        }
    
        private void usunTytulButton_Click(object sender, EventArgs e)
        {
              if (kLIENCITYTULBindingSource.Current != null)
            {
                if (kLIENCITYTULBindingSource.Current != null)
                {
                   this.kLIENCITYTULBindingSource.RemoveCurrent();
                   this.kLIENCI_TYTULTableAdapter.Update(rEKLAMADataSet.KLIENCI_TYTUL);
                }
            }
        

        }

        private void agencjaToolStripComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (((ComboBox)this.agencjaToolStripComboBox.Control).SelectedValue != null)
            {
                ((BindingSource)((ComboBox)this.agentToolStripComboBox.Control).DataSource).Filter = "ID_AGENCJI = " + ((ComboBox)this.agencjaToolStripComboBox.Control).SelectedValue.ToString();
                this.agentToolStripComboBox.SelectedIndex = -1;
                this.agentToolStripComboBox.SelectedIndex = -1;
            }
        }

        private void wstecznyKontaktToolStripButton_Click(object sender, EventArgs e)
        {
            if (Utils.iloscKontaktowAgenta(User.getUser().Login) == 0)
            {
                if (kLIENCIBindingSource.Current != null)
                {
                    kONTAKTYBindingSource.EndEdit();

                    DataRowView row = (DataRowView)this.kLIENCIBindingSource.Current;
                    int custId = Int32.Parse(row["CustomerId"].ToString());

                    DataView datatable = (DataView)this.kONTAKTYBindingSource.List;

                    DataRowView r = datatable.AddNew();
                    r["customerId"] = custId;
                    r["data"] = DateTime.Now.AddMonths(-1);
                    r["symbol_agenta"] = User.getUser().Login.ToString();

                    kONTAKTYBindingSource.MoveLast();
                    kONTAKTYBindingSource.EndEdit();

                    groupBox7.Enabled = kONTAKTYBindingSource.List.Count == 0 ? false : true;
                }
            }
            else
            {
                MessageBox.Show("Nie można dodać kontaktu");
            }
        }

        private void dodajLogoToolStripButton_Click(object sender, EventArgs e)
        {
            if (kLIENCIBindingSource.Current != null)
            {
                DataRowView row = (DataRowView)this.kLIENCIBindingSource.Current;
                int custId = Int32.Parse(row["CustomerId"].ToString());

                LogaKlientowForm logaForm = new LogaKlientowForm(custId);
                logaForm.ShowDialog();                
            }
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            if (kLIENCIBindingSource.Current != null)
            {
                DataRowView row = (DataRowView)this.kLIENCIBindingSource.Current;
                REKLAMADataSet.KLIENCIRow klient = (REKLAMADataSet.KLIENCIRow)row.Row;
              
                ZamowieniaForm zam = new ZamowieniaForm(klient);
                zam.ShowDialog();
            }
        }

    
        
        //dodanie CTR + A do textboxow
        /*
        private void test() {
            foreach (Control c in this.Controls) {
                if (c is TextBox)
                {
                    ((TextBox)c).KeyDown += new KeyEventHandler(obslugaCTR_A);
                }
            }
        }

        private void obslugaCTR_A(object sender, System.Windows.Forms.KeyEventArgs e)
        {
            MessageBox.Show("d");
            if (e.Control && e.KeyCode == Keys.A)
            {
                ((TextBox)sender).SelectAll();
                
            }
        }*/

   }
}