using System;
using System.Collections.Specialized;
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.Text.RegularExpressions;
using System.Diagnostics;

namespace Baza_Reklam
{
    public partial class OrderDetails : Form
    {
        SLOWNIKDataSet.Kursy_WalutRow kurs;

        //zmienna wyłączająca obsługę zdarzeń, gdy formularz jest ukryty
        private bool obslugaZdarzen;

        //zmienna ustawiana na TRUE przy wznawianiu lub dodawnaniu nowego zamówienia
        private bool nowyRekord;
        private bool bylyZmiany;
        private bool juzSieUkazaloWgazecie;
        private double maksymalnyRabat = (double)0.3;

        //numery reklam dla nowych zamówień       
        StringDictionary numeryReklam = new StringDictionary();

        private static OrderDetails orderDetails;

        public static OrderDetails getOrderDetails()
        {
            if (orderDetails == null)
            {
                orderDetails = new OrderDetails();
            }

            return orderDetails;
        }

        private ErrorProvider errProvider;

        // przechowuje id aktualnie wyświetlanej reklamy
        private int reklamaId;

        // przechowuje id klienta , którego dotyczy aktualnie wyświetlana reklama
        private int customerId;


        Baza_Reklam.REKLAMADataSetTableAdapters.zmianyEmisjiTableAdapter
            zmianyEmisjiTableAdapter = new Baza_Reklam.REKLAMADataSetTableAdapters.zmianyEmisjiTableAdapter();

        //private event ZmianaParametrowZamowienia 

        private OrderDetails()
        {
            InitializeComponent();

            this.rEKLAMADataSet.UKAZE_SIE_W_NR.Constraints.Remove("FAKTURY_UKAZE_SIE_W_NR");

            errProvider = new ErrorProvider();

            // funckje formatujące Decimal <-> %
            rABATTextBox.DataBindings[0].Format += new ConvertEventHandler(DecimalToProcent);
            rABATTextBox.DataBindings[0].Parse += new ConvertEventHandler(ProcentToDecimal);

            pROCENT_PROWIZJITextBox.DataBindings[0].Format += new ConvertEventHandler(DecimalToProcent);
            pROCENT_PROWIZJITextBox.DataBindings[0].Parse += new ConvertEventHandler(ProcentToDecimal);

            pVATComboBox.DataBindings[0].Format += new ConvertEventHandler(DecimalToProcent);
            pVATComboBox.DataBindings[0].Parse += new ConvertEventHandler(ProcentToDecimal);

            rEKLAMADataSet.UKAZE_SIE_W_NR.TableNewRow += nowaEmisja;

            nAZWY_MODULOWTableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;
            gRZBIETYTableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;
            pROMOCJETableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;
            lISTA_TYPOW_REKLAMYTableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;
            lISTA_TYTULOWTableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;
            kursy_WalutTableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;
            rEKLAMATableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;
            uKAZE_SIE_W_NRTableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;
            rEKLAMA_STRONATableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;
            reklama_Info_DodTableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;
            aGENCITableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;
            ogl_dzialyTableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;
            ogl_rozdzialyTableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;
            zmianyEmisjiTableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;

            this.nAZWY_MODULOWTableAdapter.Fill(this.sLOWNIKDataSet.NAZWY_MODULOW);
            this.gRZBIETYTableAdapter.Fill(this.sLOWNIKDataSet.GRZBIETY);
            this.pROMOCJETableAdapter.Fill(this.sLOWNIKDataSet.PROMOCJE);

            if (User.getUser().St_kierownik || User.getUser().St_produkcja)
            {
                this.lISTA_TYPOW_REKLAMYTableAdapter.Fill(this.sLOWNIKDataSet.LISTA_TYPOW_REKLAMY);
            }
            else
            {
                this.lISTA_TYPOW_REKLAMYTableAdapter.FillByBezBezplatnych(this.sLOWNIKDataSet.LISTA_TYPOW_REKLAMY);
            }
            this.lISTA_TYTULOWTableAdapter.Fill(this.sLOWNIKDataSet.LISTA_TYTULOW);
            this.aGENCITableAdapter.FillByAktywny(this.sLOWNIKDataSet.AGENCI);
            this.ogl_dzialyTableAdapter.Fill(this.sLOWNIKDataSet.ogl_dzialy);
            this.ogl_rozdzialyTableAdapter.Fill(this.sLOWNIKDataSet.ogl_rozdzialy);

            usunToolStripMenuItem.Click += usunEmisje;
            anulujToolStripMenuItem.Click += anulujEmisje;
            zmienToolStripMenuItem.Click += zmienEmisje;

            walutyComboBox.SelectedIndex = 0;
        }

        private void OrderDetails_Load(object sender, EventArgs e)
        {
            wyroznienie_exportedCheckBox.Enabled = User.getUser().St_produkcja;
        }

        /// <summary>
        /// Filtruje moduły i grzbiety wg tytułu gazety.
        /// </summary>
        private void tYTULComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (obslugaZdarzen)
            {
                if (tYTULComboBox.SelectedValue != null)
                {
                    this.nAZWYMODULOWBindingSource.Filter = "tytul='" + tYTULComboBox.SelectedValue.ToString() + "'";
                    this.iD_REKLAMYTextBox.Text = (nowyRekord) ? this.numeryReklam[tYTULComboBox.SelectedValue.ToString()] : this.iD_REKLAMYTextBox.Text;
                    this.gRZBIETYBindingSource.Filter = "Nazwa like '%" + tYTULComboBox.SelectedValue.ToString() + "%'";
                    int i = lISTATYTULOWBindingSource.Find("SYMB", tYTULComboBox.SelectedValue);
                    this.maksymalnyRabat = Convert.ToDouble(((DataRowView)lISTATYTULOWBindingSource.List[i])["max_rabat"]);

                    DataRowView row = (DataRowView)lISTATYTULOWBindingSource.Current;
                    this.ogl_dzialyBindingSource.Filter = "TYTUL=" + row["id"].ToString();

                    switch (tYTULComboBox.SelectedValue.ToString())
                    {
                        case "AMT":
                            this.ogl_dzialyBindingSource.Filter = "TYTUL='2'";
                            break;
                        case "GS":
                            this.ogl_dzialyBindingSource.Filter = "TYTUL='1'";
                            break;
                        case "AGRO":
                            this.ogl_dzialyBindingSource.Filter = "TYTUL='7'";
                            break;
                        case "adMot":
                            this.ogl_dzialyBindingSource.Filter = "TYTUL='6'";
                            break;
                        default:
                            this.ogl_dzialyBindingSource.Filter = "";
                            break;
                    }
                }
            }
        }

        private void grzbietComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (obslugaZdarzen)
            {
                if ((int)grzbietComboBox.SelectedValue == 9)
                {
                    this.iD_REKLAMYTextBox.Text = (nowyRekord) ? this.numeryReklam["slaski"] : this.iD_REKLAMYTextBox.Text;
                }
                else
                {
                    this.iD_REKLAMYTextBox.Text = (nowyRekord) ? this.numeryReklam[tYTULComboBox.SelectedValue.ToString()] : this.iD_REKLAMYTextBox.Text;
                }
            }
        }

        private void anulujButton_Click(object sender, EventArgs e)
        {
            if (nowyRekord)
            {
                //usuwa dodany wczesniej do bazy wiersz    
                if (rEKLAMABindingSource.Current != null)
                {
                    rEKLAMABindingSource.RemoveCurrent();
                    rEKLAMABindingSource.EndEdit();
                    rEKLAMATableAdapter.Update(this.rEKLAMADataSet.REKLAMA);
                }
            }
            else
            {
                //usuwa zmiany w zleceniu           
                rEKLAMADataSet.REKLAMA.RejectChanges();
                rEKLAMADataSet.UKAZE_SIE_W_NR.RejectChanges();
            }

            this.obslugaZdarzen = false;
            liczbaEmisjiLabel.Text = "-";

            this.DialogResult = bylyZmiany ? DialogResult.OK : DialogResult.Cancel;
        }

        /// <summary>
        /// Zapisuje zmiany w wierszu oraz dodaje rekordy do "UKAZE SIE W NR" i "InfoDod"
        /// </summary>
        private void dodajButton_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;

            this.Validate();
            rEKLAMABindingSource.EndEdit();

            DataRowView row = (DataRowView)rEKLAMABindingSource.Current;
            
            /*
            if (!(brutto_EuroTextBox.Text != "0" ^ walutyComboBox.SelectedIndex == -1))
            {
                MessageBox.Show("Popraw walutę!");
                this.Cursor = Cursors.Default;
                return;
            }*/

            if (wyroznienieCheckBox.Checked ^ Convert.ToDecimal(row["wyroznienie_kwota"]) != 0)
            {
                MessageBox.Show("Została zmieniona opcja wyróżnienia. Zamówienie należy ponownie przeliczyć");
                this.Cursor = Cursors.Default;
                return;
            }

            row["USERID"] = User.getUser().Login;

            rEKLAMAUKAZESIEWNRBindingSource.EndEdit();
            rEKLAMAReklamaInfoDodBindingSource.EndEdit();

            //MessageBox.Show(rEKLAMAUKAZESIEWNRBindingSource.List.Count.ToString() + " " + rEKLAMADataSet.UKAZE_SIE_W_NR.Count.ToString());

            this.rEKLAMATableAdapter.Update(this.rEKLAMADataSet.REKLAMA);
            this.uKAZE_SIE_W_NRTableAdapter.Update(this.rEKLAMADataSet.UKAZE_SIE_W_NR);
            this.reklama_Info_DodTableAdapter.Update(this.rEKLAMADataSet.Reklama_Info_Dod);
            this.zmianyEmisjiTableAdapter.Update(this.rEKLAMADataSet.zmianyEmisji);
            MessageBox.Show("Zmiany zapisane");

            zmiany();

            nowyRekord = false;
            bylyZmiany = true;
            //this.obslugaZdarzen = false;

            this.Cursor = Cursors.Default;
        }

        private void sZERTextBox_Validating(object sender, CancelEventArgs e)
        {
            if (!sZERTextBox.Text.Equals(""))
            {
                if (!Regex.IsMatch(sZERTextBox.Text, "^[0-8]{1}$", RegexOptions.IgnoreCase))
                {
                    e.Cancel = true;

                    errProvider.SetError((Control)sender, "1-8");
                    return;
                }

            }
            errProvider.SetError((Control)sender, "");
        }

        private void wYSTextBox_Validating(object sender, CancelEventArgs e)
        {
            if (!sZERTextBox.Text.Equals(""))
            {
                if (!Regex.IsMatch(sZERTextBox.Text, "^[0-8]{1}$", RegexOptions.IgnoreCase))
                {
                    e.Cancel = true;

                    errProvider.SetError((Control)sender, "1-8");
                    return;
                }

            }
            errProvider.SetError((Control)sender, "");
        }

        private void promocjaComboBox_TextChanged(object sender, EventArgs e)
        {
            if (obslugaZdarzen)
            {
                if (promocjaComboBox.Text == "")
                {
                    if (rEKLAMABindingSource.Current != null)
                    {
                        DataRowView row = (DataRowView)rEKLAMABindingSource.Current;
                        row["PROMOCJA"] = DBNull.Value;
                        rEKLAMABindingSource.EndEdit();
                    }
                }
            }
        }

        private void zATWIERDZONO_DO_DRUKUCheckBox_Click(object sender, EventArgs e)
        {
            if (zATWIERDZONO_DO_DRUKUCheckBox.Checked)
            {
                if (rEKLAMABindingSource.Current != null)
                {
                    DataRowView row = (DataRowView)rEKLAMABindingSource.Current;

                    sprawdzBledy();

                    if (!User.getUser().St_kierownik)
                    {
                        if (Convert.ToDouble(row["rabat"]) > this.maksymalnyRabat)
                        {
                            MessageBox.Show("Rabat wyższy niż " + this.maksymalnyRabat.ToString("P") + ". Zamówienie musi być zatwierdzone do druku przez kierownika");
                            zATWIERDZONO_DO_DRUKUCheckBox.CheckState = CheckState.Unchecked;
                        }

                        if (nAZWYMODULOWBindingSource.Current != null)
                        {
                            DataRowView r = (DataRowView)nAZWYMODULOWBindingSource.Current;
                            //decimal cenaJedn = Convert.ToDecimal(row["CENA JEDN"]);
                            decimal cenaMinMod = Convert.ToDecimal(r["CENA_MIN"]);

                            decimal cenaJedn = Convert.ToDecimal(row["NETTO"]) / (Convert.ToDecimal(row["SZER"]) * Convert.ToDecimal(row["WYS"]) * Convert.ToDecimal(row["KROTNOŚĆ"]));
                            cenaJedn = Math.Round(cenaJedn, 2);

                            if (cenaJedn < cenaMinMod)
                            {
                                MessageBox.Show("Cena modułu niższa niż cena cennikowa. Zamówienie musi być zatwierdzone do druku przez kierownika");
                                zATWIERDZONO_DO_DRUKUCheckBox.CheckState = CheckState.Unchecked;
                            }
                        }

                        string typ = Convert.ToString(row["typ"]);
                        if ((typ == "BEZPŁATNA") || (typ == "BARTER") || (typ == "REKLAMACJA"))
                        {
                            MessageBox.Show("Zamówienie musi być zatwierdzone do druku przez kierownika");
                            zATWIERDZONO_DO_DRUKUCheckBox.CheckState = CheckState.Unchecked;
                        }
                    }
                }
            }
        }

        private void pROCENT_PROWIZJITextBox_Leave(object sender, EventArgs e)
        {
            rEKLAMABindingSource.EndEdit();
        }
        
        /// <summary>
        /// Blokuje część formuklarze w zależności od stanu zamówienia i praw użytkownika...
        /// </summary>
        private void OrderDetails_Shown(object sender, EventArgs e)
        {
            // BindingSource sa resetowane, by ustawily sie wszytskie filtry
            kurs = null;

            obslugaZdarzen = true;

            tYTULComboBox.SelectedIndex = -1;
            rEKLAMABindingSource.ResetBindings(false);
            
            mOD_TYPComboBox.SelectedIndex = -1;
            rEKLAMABindingSource.ResetBindings(false);
            
            ogl_dzialComboBox.SelectedIndex = -1;
            rEKLAMABindingSource.ResetBindings(false);
            
            ogl_rozdzialComboBox.SelectedIndex = -1;
            rEKLAMABindingSource.ResetBindings(false);
            
            blokowanieZrealizowanychEmisji();
            zmiany();
            init();
        }

        private void ukazeSieDataGridView_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            if (rEKLAMAUKAZESIEWNRBindingSource.Current != null)
            {
                rEKLAMAUKAZESIEWNRBindingSource.RemoveCurrent();
            }
            blokowanieZrealizowanychEmisji();
        }

        private void ukazeSieDataGridView_Leave(object sender, EventArgs e)
        {
            Validate();

            rEKLAMAUKAZESIEWNRBindingSource.EndEdit();

            liczbaEmisjiLabel.Text = rEKLAMAUKAZESIEWNRBindingSource.List.Count.ToString();

            if (rEKLAMABindingSource.Current != null)
            {
                DataRowView row = (DataRowView)rEKLAMABindingSource.Current;

                if (row["ID_FAKTURY"] == DBNull.Value)
                {
                    kROTNOSCTextBox.Text = rEKLAMAUKAZESIEWNRBindingSource.List.Count.ToString();
                }
            }
        }

        /// <summary>
        /// Blokuje emisje,które już się ukazały.
        /// </summary>
        private void blokowanieZrealizowanychEmisji()
        {
            //  ukazeSieDataGridView.Enabled = true; 
            foreach (DataGridViewRow r in ukazeSieDataGridView.Rows)
            {
                REKLAMADataSet.UKAZE_SIE_W_NRRow em =
                    (REKLAMADataSet.UKAZE_SIE_W_NRRow)((DataRowView)r.DataBoundItem).Row;

                //anulowana
                if (em.status == 2)
                {
                    r.ReadOnly = true;
                    r.DefaultCellStyle.ForeColor = Color.Red;
                }
                
                foreach (DataGridViewRow s in ukazaloSieDataGridView.Rows)
                {
                    if (em.Nr_Wydania.ToString() == s.Cells["NR_WYDANIA"].Value.ToString())
                    {
                        r.ReadOnly = true;
                        r.DefaultCellStyle.BackColor = Color.MintCream;
                        this.juzSieUkazaloWgazecie = true;
                        break;
                    }
                }
            }

        }
        

        public void zablokujGroupBoxa(GroupBox g)
        {
            foreach (Control c in g.Controls)
            {
                if (c is TextBox)
                {
                    ((TextBox)c).ReadOnly = true;
                }

                if (c is ComboBox)
                {
                    ((ComboBox)c).Enabled = false;
                }
            }
        }

        public void odblokujGroupBoxa(GroupBox g)
        {
            foreach (Control c in g.Controls)
            {
                if (c is TextBox)
                {
                    ((TextBox)c).ReadOnly = false;
                }

                if (c is ComboBox)
                {
                    ((ComboBox)c).Enabled = true;
                }
            }
        }

        /// <summary>
        /// Blokuje kontrolki związane z danymi zamówienia
        /// </summary>
        private void zablokujGroupBoxy()
        {
            zablokujGroupBoxa(groupBox1);

            if (!(User.getUser().St_produkcja | User.getUser().St_kierownik))
            {
                zablokujGroupBoxa(groupBox2);
            }
            zablokujGroupBoxa(groupBox3);
            zablokujGroupBoxa(groupBox4);

            //lokalizacje można zmieniać
            sTRONATextBox.ReadOnly = false;

        }

        /// <summary>
        /// Odblokuje kontrolki związane z danymi zamówienia
        /// </summary>
        private void odblokujGroupBoxy()
        {
            odblokujGroupBoxa(groupBox1);
            odblokujGroupBoxa(groupBox2);
            odblokujGroupBoxa(groupBox3);
            odblokujGroupBoxa(groupBox4);
        }

        /// <summary>
        /// Buduje nr zamowienia dla danego handlowca
        /// </summary>
        private string nrRek(string symAgenta, string tagAgenta)
        {
            if (User.getUser().St_handlowiec)
            {
                string nr = Baza_Reklam.Utils.numerNowejReklamy(symAgenta, tagAgenta).ToString();
                switch (nr.Length)
                {
                    case 1:
                        nr = tagAgenta + "00" + nr + "_00";
                        break;
                    case 2:
                        nr = tagAgenta + "0" + nr + "_00";
                        break;
                    case 3:
                        nr = tagAgenta + nr + "_00";
                        break;
                }
                return nr;
            }
            return "";
        }

        /// <summary>
        /// Sprawdza poprawność zamówienia... pewnie niekompletnie
        /// </summary>
        private void sprawdzBledy()
        {
            if (ogl_dzialComboBox.SelectedValue == null)
            {
                MessageBox.Show("Wybierz dział.");
                zATWIERDZONO_DO_DRUKUCheckBox.CheckState = CheckState.Unchecked;
                return;
            }


            if (mOD_TYPComboBox.Text == "")
            {
                MessageBox.Show("Wybierz rodzaj modułu.");
                zATWIERDZONO_DO_DRUKUCheckBox.CheckState = CheckState.Unchecked;
                return;
            }

            string grzbiet = grzbietComboBox.Text;
            string tytul = tYTULComboBox.Text;

            if (grzbiet == "")
            {
                MessageBox.Show("Wybierz grzbiet.");
                zATWIERDZONO_DO_DRUKUCheckBox.CheckState = CheckState.Unchecked;
                return;
            }
            else
            {
                if (!grzbiet.Contains(tytul))
                {
                    MessageBox.Show("Wybierz poprawny grzbiet.");
                    zATWIERDZONO_DO_DRUKUCheckBox.CheckState = CheckState.Unchecked;
                    return;
                }
            }

            //lokalizacja
            if (sTRONATextBox.Text == "")
            {
                MessageBox.Show("Podaj lokalizację.");
                zATWIERDZONO_DO_DRUKUCheckBox.CheckState = CheckState.Unchecked;
                return;
            }

            if (rEKLAMAUKAZESIEWNRBindingSource.List.Count == 0)
            {
                MessageBox.Show("Brak wyznaczonych emisji.");
                zATWIERDZONO_DO_DRUKUCheckBox.CheckState = CheckState.Unchecked;
                return;
            }
        }

        /// <summary>
        /// Przelicza wartość zamówienia.
        /// </summary>
        private void przelicz()
        {
            DataRowView row = (DataRowView)rEKLAMABindingSource.Current;

            if ((row["KROTNOŚĆ"] != null) && (row["CENA JEDN"] != null) && (row["VAT"] != null)
              && (row["PROCENT PROWIZJI"] != null) && (row["RABAT"] != null)
              && (row["SZER"] != null) && (row["WYS"] != null))
            {
                int szer = Convert.ToInt32(row["SZER"]);
                int wys = Convert.ToInt32(row["WYS"]);
                int krotnosc = Convert.ToInt32(row["KROTNOŚĆ"]);

                if (krotnosc == 0)
                {
                    MessageBox.Show("Ilość emisji równa się  0");
                    return;
                }

                decimal cenaJednostkowa = Convert.ToDecimal(row["CENA JEDN"]);
                decimal vatProcent = Convert.ToDecimal(row["VAT"]);
                decimal prowizjaProcent = Convert.ToDecimal(row["PROCENT PROWIZJI"]);
                decimal rabatProcent = Convert.ToDecimal(row["RABAT"]);


                //rabatWartosc
                decimal rabatWartosc = rabatProcent * cenaJednostkowa;
                rabatWartosc = Math.Round(rabatWartosc, 2);

                //netto
                decimal netto = (cenaJednostkowa - rabatWartosc) * krotnosc;
                netto = Math.Round(netto, 2);

                nettoBezBOTextBox.Text = String.Format("{0:C}", netto);

                //cena modulu
                decimal cenaModulu = netto / (szer * wys * krotnosc);
                cenaModulu = Math.Round(cenaModulu, 2);

                if (Convert.ToBoolean(row["wyroznienie"]) == true)
                {
                    row["wyroznienie_procent"] = 0.15M;
                    decimal kwotaWyroznienia = Math.Round(netto * 0.15M, 2);
                    row["wyroznienie_kwota"] = kwotaWyroznienia;
                    netto = netto + kwotaWyroznienia;
                }
                else
                {
                    row["wyroznienie_procent"] = 0;
                    row["wyroznienie_kwota"] = 0;
                }

                //vatWartosc
                decimal vatWartosc = vatProcent * netto;
                vatWartosc = Math.Round(vatWartosc, 2);

                //brutto
                decimal brutto = netto + vatWartosc;
                brutto = Math.Round(brutto, 2);

                //prowizja
                decimal prowizjaWartosc = prowizjaProcent * netto;
                prowizjaWartosc = Math.Round(prowizjaWartosc, 2);

                cenaModuluLabel.Text = String.Format("{0:C}", cenaModulu);
                row["RABAT WARTOŚĆ"] = rabatWartosc.ToString();
                row["NETTO"] = netto.ToString();
                row["BRUTTO"] = brutto.ToString();
                row["PVAT"] = vatWartosc.ToString();
                row["PROWIZJA"] = prowizjaWartosc.ToString();

                rEKLAMABindingSource.EndEdit();
            }

        }

        /// <summary>
        /// Przelicza kwotę w złotówkach na wybraną walutę.
        /// </summary>
        private void przeliczNaWalute(SLOWNIKDataSet.Kursy_WalutRow kurs)
        {
            if (rEKLAMABindingSource.Current != null)
            {
                DataRowView row = (DataRowView)rEKLAMABindingSource.Current;

                if (row["BRUTTO"] != DBNull.Value)
                {

                    decimal brutto = Convert.ToDecimal(row["BRUTTO"]);
                    brutto = Math.Round(brutto, 2);

                    // waluty
                    row["waluta_tabela_nr"] = kurs.Numer_Tabeli;
                    row["waluta_Przelicznik"] = kurs.przelicznik;
                    row["waluta_kurs_z_dnia"] = kurs.Data_Publikacji;
                    row["Brutto_Euro_Miano"] = kurs.Kod_Waluty;
                        
                    //zmiana kursu dla poznania
                    if (User.getUser().IdAgencji == 6)
                    {
                        row["waluta_kurs"] = kurs.Kurs_Sredni_Poznan;
                        row["Brutto_Euro"] = Math.Round(brutto / Convert.ToDecimal(kurs.Kurs_Sredni_Poznan) * Convert.ToInt32(kurs.przelicznik), 2);
                    }
                    else
                    {
                        row["waluta_kurs"] = kurs.Kurs_Sredni;
                        row["Brutto_Euro"] = Math.Round(brutto / Convert.ToDecimal(kurs.Kurs_Sredni) * Convert.ToInt32(kurs.przelicznik), 2);
                    }

                    // zmiana domyślnego konta do faktury dla EUR
                    if (User.getUser().IdAgencji != 4 & (row["Brutto_Euro_Miano"].ToString() == "EUR"))
                    {
                        if (User.getUser().IdAgencji == 1223940396 | User.getUser().IdAgencji == 1223940398)
                        {
                            row["FAKTURA ID KONTA"] = 3;
                        }
                        else
                        {
                            row["FAKTURA ID KONTA"] = 5;
                        }
                    }

                    rEKLAMABindingSource.EndEdit();
                }
            }
        }

        /// <summary>
        /// Przelicza kwotę w walucie na złotówki.
        /// </summary>
        private void przeliczWaluteNaZlotowki(SLOWNIKDataSet.Kursy_WalutRow kurs)
        {
            DataRowView row = (DataRowView)rEKLAMABindingSource.Current;

            if (row["Brutto_Euro"] != DBNull.Value)
            {
                // waluty
                row["waluta_tabela_nr"] = kurs.Numer_Tabeli;
                row["waluta_Przelicznik"] = kurs.przelicznik;
                row["waluta_kurs"] = kurs.Kurs_Sredni;
                row["waluta_kurs_z_dnia"] = kurs.Data_Publikacji;
                row["Brutto_Euro_Miano"] = kurs.Kod_Waluty;

                //zmiana kursu dla poznania
                if (User.getUser().IdAgencji == 6)
                {
                    row["waluta_kurs"] = kurs.Kurs_Sredni_Poznan;
                }
             
                int szer = Convert.ToInt32(row["SZER"]);
                int wys = Convert.ToInt32(row["WYS"]);
                int krotnosc = Convert.ToInt32(row["KROTNOŚĆ"]);

                if (krotnosc == 0)
                {
                    MessageBox.Show("Ilość emisji równa się  0");
                    return;
                }

                decimal vatProcent = Convert.ToDecimal(row["VAT"]);
                decimal prowizjaProcent = Convert.ToDecimal(row["PROCENT PROWIZJI"]);
                decimal rabatProcent = Convert.ToDecimal(row["RABAT"]);

                //przeliczanie z waluty na zlotowki   
                decimal brutto = Math.Round(Convert.ToDecimal(row["Brutto_Euro"]) * Convert.ToDecimal(row["waluta_kurs"]) / Convert.ToInt32(row["waluta_Przelicznik"]), 2);

                decimal netto = brutto / (1 + vatProcent);
                netto = Math.Round(netto, 2);

                decimal nettoZBO = netto;

                if (Convert.ToBoolean(row["wyroznienie"]) == true)
                {
                    row["wyroznienie_procent"] = 0.15M;
                    decimal nettoBezBO = Math.Round(netto / 1.15M, 2);
                    row["wyroznienie_kwota"] = Math.Round(netto - nettoBezBO, 2);
                    netto = nettoBezBO;
                }
                else
                {
                    row["wyroznienie_procent"] = 0;
                    row["wyroznienie_kwota"] = 0;
                }

                nettoBezBOTextBox.Text = String.Format("{0:C}", netto);

                decimal vatWartosc = vatProcent * nettoZBO;
                vatWartosc = Math.Round(vatWartosc, 2);

                decimal prowizjaWartosc = prowizjaProcent * nettoZBO;
                prowizjaWartosc = Math.Round(prowizjaWartosc, 2);

                decimal rabatWartosc = netto * rabatProcent / (krotnosc * (1 - rabatProcent));
                rabatWartosc = Math.Round(rabatWartosc, 2);

                decimal cenaJednostkowa = (netto / (decimal)krotnosc) + rabatWartosc;
                cenaJednostkowa = Math.Round(cenaJednostkowa, 2);

                //cena modulu
                decimal cenaModulu = netto / (szer * wys * krotnosc);
                cenaModulu = Math.Round(cenaModulu, 2);

                cenaModuluLabel.Text = String.Format("{0:C}", cenaModulu);
                row["RABAT WARTOŚĆ"] = rabatWartosc.ToString();
                row["NETTO"] = nettoZBO.ToString();
                row["BRUTTO"] = brutto.ToString();
                row["PVAT"] = vatWartosc.ToString();
                row["PROWIZJA"] = prowizjaWartosc.ToString();
                row["CENA JEDN"] = cenaJednostkowa.ToString();


                // zmiana domyślnego konta do faktury dla EUR
                if (User.getUser().IdAgencji != 4 & (row["Brutto_Euro_Miano"].ToString() == "EUR"))
                {
                    if (User.getUser().IdAgencji == 1223940396 | User.getUser().IdAgencji == 1223940398)
                    {
                        row["FAKTURA ID KONTA"] = 3;
                    }
                    else
                    {
                        row["FAKTURA ID KONTA"] = 5;
                    }
                }

                rEKLAMABindingSource.EndEdit();

            }
        }

        public void dodajNoweZamowienie(int custId, string kodKlienta)
        {           
            this.nowyRekord = true;
            this.bylyZmiany = false;
            this.juzSieUkazaloWgazecie = false;

            this.numeryReklam.Clear();

            string nr;
            foreach (DataRowView r in lISTATYTULOWBindingSource.List)
            {
                nr = nrRek(User.getUser().Symbol_agenta, r["SYMB2"].ToString().Trim() + User.getUser().Kod_agenta);
                this.numeryReklam.Add((string)r["SYMB"], nr);
            }
            //autosalon śląski
            nr = nrRek(User.getUser().Symbol_agenta, "G" + User.getUser().Kod_agenta);
            this.numeryReklam.Add("slaski", nr);

            this.rEKLAMADataSet.REKLAMA.Clear();
            this.rEKLAMADataSet.UKAZE_SIE_W_NR.Clear();
            this.rEKLAMADataSet.Reklama_Info_Dod.Clear();

            this.customerId = custId;

            DataView datatable = (DataView)this.rEKLAMABindingSource.List;
            DataRowView row = datatable.AddNew();
           
            row["CustomerId"] = this.customerId;
            row["DATA ZAMÓWIENIA"] = DateTime.Now;
            row["nick name"] = kodKlienta;
            if (Utils.czyKlientMaNrVIES(this.customerId))
            {
                row["VAT"] = 0;
            }

            if (User.getUser().St_handlowiec | User.getUser().St_subhandlowiec)
            {
                row["symbol akwizytora"] = User.getUser().Symbol_agenta;
                row["ID Reklamy"] = this.numeryReklam["AMT"];

                //Katowice
                if (User.getUser().IdAgencji == 4)
                {
                    row["customerId_Sub"] = 678;
                }

                //Poznan
                if (User.getUser().IdAgencji == 6)
                {
                    row["customerId_Sub"] = 18845;
                }
            }

            row["USERID"] = User.getUser().Login;

            Validate();
          
            rEKLAMABindingSource.EndEdit();
            rEKLAMATableAdapter.Update(rEKLAMADataSet.REKLAMA);
            rEKLAMABindingSource.MoveLast();
        }

        public void pokazSzczegolyZamowienia(int rekId)
        {
            this.nowyRekord = false;
            this.bylyZmiany = false;
            this.reklamaId = rekId;

            this.rEKLAMATableAdapter.ClearBeforeFill = true;
            this.rEKLAMATableAdapter.FillByReklamaId(this.rEKLAMADataSet.REKLAMA, reklamaId);
            this.reklama_Info_DodTableAdapter.FillByReklamaId(this.rEKLAMADataSet.Reklama_Info_Dod, reklamaId);
            this.rEKLAMA_STRONATableAdapter.FillByReklamaId(this.rEKLAMADataSet.REKLAMA_STRONA, this.reklamaId);
            this.uKAZE_SIE_W_NRTableAdapter.FillByReklamaId(this.rEKLAMADataSet.UKAZE_SIE_W_NR, this.reklamaId);
        }

        public void wznowZamowienie(int rekId)
        {
            this.nowyRekord = true;
            this.bylyZmiany = false;
            this.juzSieUkazaloWgazecie = false;

            REKLAMADataSet.REKLAMADataTable old = this.rEKLAMATableAdapter.GetDataByReklamaId(rekId);
            DataRow oldRow = old.Rows[0];

            this.rEKLAMADataSet.REKLAMA.Clear();
            this.rEKLAMADataSet.UKAZE_SIE_W_NR.Clear();
            this.rEKLAMADataSet.Reklama_Info_Dod.Clear();

            DataView datatable = (DataView)this.rEKLAMABindingSource.List;
            DataRowView newRow = datatable.AddNew();

            this.customerId = Convert.ToInt32(oldRow["CustomerID"]);

            newRow["CustomerID"] = oldRow["CustomerID"];
            newRow["DATA ZAMÓWIENIA"] = DateTime.Now;
            newRow["SYMBOL AKWIZYTORA"] = oldRow["SYMBOL AKWIZYTORA"];
            newRow["ID REKLAMY"] = oldRow["ID REKLAMY"];
            newRow["TYTUŁ"] = oldRow["TYTUŁ"];
            newRow["TYP"] = oldRow["TYP"];
            newRow["NICK NAME"] = oldRow["NICK NAME"];
            newRow["SZER"] = oldRow["SZER"];
            newRow["WYS"] = oldRow["WYS"];
            newRow["MOD_TYP"] = oldRow["MOD_TYP"];
            newRow["KROTNOŚĆ"] = oldRow["KROTNOŚĆ"];
            newRow["ODSTĘP"] = oldRow["ODSTĘP"];
            newRow["KOLOR"] = oldRow["KOLOR"];
            newRow["RABAT"] = oldRow["RABAT"];
            newRow["CENA JEDN"] = oldRow["CENA JEDN"];
            newRow["VAT"] = oldRow["VAT"];
            newRow["PROCENT PROWIZJI"] = oldRow["PROCENT PROWIZJI"];
            newRow["PROMOCJA"] = oldRow["PROMOCJA"];
            newRow["GRZBIET"] = oldRow["GRZBIET"];
            newRow["STRONA"] = oldRow["STRONA"];
            newRow["customerId_Sub"] = oldRow["customerId_Sub"];
            newRow["ogl_dzial"] = oldRow["ogl_dzial"];
            newRow["ogl_rozdzial"] = oldRow["ogl_rozdzial"];

            //zmiana numerka
            try
            {
                string starySym = newRow["Id reklamy"].ToString();
                string symPart1 = starySym.Substring(0, starySym.Length - 2);
                string symPart2 = starySym.Substring(starySym.Length - 2, 2);
                int nowyNr = Int32.Parse(symPart2);
                nowyNr++;
                switch (nowyNr.ToString().Length)
                {
                    case 1:
                        newRow["Id reklamy"] = symPart1 + "0" + nowyNr.ToString();
                        break;
                    default:
                        newRow["Id reklamy"] = symPart1 + nowyNr.ToString();
                        break;
                }
            }
            catch (Exception e1)
            {
                newRow["Id reklamy"] = oldRow["Id reklamy"];
            }

            this.numeryReklam.Clear();
            string nr;
            foreach (DataRowView r in lISTATYTULOWBindingSource.List)
            {
                nr = nrRek(User.getUser().Symbol_agenta, r["SYMB2"].ToString().Trim() + User.getUser().Kod_agenta);
                this.numeryReklam.Add((string)r["SYMB"], nr);
            }
            //autosalon śląski
            nr = nrRek(User.getUser().Symbol_agenta, "G" + User.getUser().Kod_agenta);
            this.numeryReklam.Add("slaski", nr);

            Validate();

            rEKLAMABindingSource.EndEdit();
            rEKLAMATableAdapter.Update(rEKLAMADataSet.REKLAMA);
           // rEKLAMABindingSource.MoveLast();
        }

        private void dataGridView1_RowLeave(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                DataRowView rowView = dataGridView1[e.ColumnIndex, e.RowIndex].OwningRow.DataBoundItem as DataRowView;

                if ((rowView != null) && rowView.IsNew)
                {
                    rowView["Data"] = DateTime.Now;
                }
            }
            catch (Exception e1)
            {
                throw e1;
            }

            dataGridView1.Refresh();
        }

        private void dataGridView1_Leave(object sender, EventArgs e)
        {
            this.dataGridView1.EndEdit();

            Validate();

            this.rEKLAMAReklamaInfoDodBindingSource.EndEdit();
        }

        private void OrderDetails_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (nowyRekord)
            {
                if (rEKLAMABindingSource.Current != null)
                {
                    rEKLAMABindingSource.RemoveCurrent();
                    rEKLAMABindingSource.EndEdit();
                    rEKLAMATableAdapter.Update(this.rEKLAMADataSet.REKLAMA);
                }

            }
            else
            {
                //usuwa zmiany w zleceniu           
                rEKLAMADataSet.REKLAMA.RejectChanges();
                rEKLAMADataSet.UKAZE_SIE_W_NR.RejectChanges();
            }

            this.obslugaZdarzen = false;
            liczbaEmisjiLabel.Text = "-";
            this.nettoBezBOTextBox.Clear();
            this.kurs = null;
            this.DialogResult = bylyZmiany ? DialogResult.OK : DialogResult.Cancel;
        }

        /// <summary>
        /// Koloruje formularz, blokuje pola etc.
        /// </summary>
        private void zmiany()
        {
            if (this.rEKLAMABindingSource.Current != null)
            {
                DataRowView reklamRow = (DataRowView)this.rEKLAMABindingSource.Current;

                bool zablokujProwizje = Convert.ToBoolean(reklamRow["zablokuj_prowizje"]);
                bool zatwiedzonoDoDruku = reklamRow["ZATWIERDZONO DO DRUKU"] == DBNull.Value ? false : Convert.ToBoolean(reklamRow["ZATWIERDZONO DO DRUKU"]);
                bool kierownikZatwierdzil = reklamRow["kier_zatwierdzil"] == DBNull.Value ? false : Convert.ToBoolean(reklamRow["kier_zatwierdzil"]);
                bool rabatPonad30 = (bool)(Convert.ToDouble(reklamRow["rabat"]) > this.maksymalnyRabat);
                bool wystawionoFakture = reklamRow["FAKTURA WYSTAWIONO"] == DBNull.Value ? false : Convert.ToBoolean(reklamRow["FAKTURA WYSTAWIONO"]);

                //blokowanie prowizji
                pROWIZJATextBox.ReadOnly = zablokujProwizje;
                pROCENT_PROWIZJITextBox.ReadOnly = zablokujProwizje;

                //oznaczenie ZD
                ZDpanel.BackColor = zatwiedzonoDoDruku ? Color.LightGreen : Color.Red;
                
                //UPRAWnienia
                kier_notatkaTextBox.ReadOnly = !User.getUser().St_kierownik;
                kier_zatwierdzilCheckBox.Enabled = User.getUser().St_kierownik;
                zablokuj_prowizjeCheckBox.Enabled = User.getUser().St_kierownik;

                if (!User.getUser().St_kierownik)
                {
                    cENA_JEDNTextBox.ReadOnly = zatwiedzonoDoDruku;
                    rABATTextBox.ReadOnly = zatwiedzonoDoDruku;

                    if (wystawionoFakture)
                    {
                        zablokujGroupBoxy();
                    }
                    else
                    {
                        odblokujGroupBoxy();
                    }
                }

                blokowanieZrealizowanychEmisji();
            }
        }

        private void ukazeSieDataGridView_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Control && e.KeyCode == Keys.C)
            {
                if (this.ukazeSieDataGridView.GetCellCount(DataGridViewElementStates.Selected) > 0)
                {
                    try
                    {
                        // Add the selection to the clipboard.
                        Clipboard.SetDataObject(
                            this.ukazeSieDataGridView.GetClipboardContent());
                    }
                    catch (System.Runtime.InteropServices.ExternalException)
                    {

                    }
                }
            }

            if (e.Control && e.KeyCode == Keys.V)
            {
                Validate();

                rEKLAMAUKAZESIEWNRBindingSource.EndEdit();

                //czy user ma uprawnienia do dodawania wierszy
                if (ukazeSieDataGridView.AllowUserToAddRows)
                {
                    char[] rowSplitter = { '\r', '\n' };
                    char[] columnSplitter = { '\t' };

                    IDataObject dataInClipboard = Clipboard.GetDataObject();
                    string stringInClipboard = (string)dataInClipboard.GetData(DataFormats.Text);

                    string[] rowsInClipboard = stringInClipboard.Split(rowSplitter, StringSplitOptions.RemoveEmptyEntries);

                    string nrWydania = "0";

                    for (int iRow = 0; iRow < rowsInClipboard.Length; iRow++)
                    {
                        string[] valuesInRow = rowsInClipboard[iRow].Split(columnSplitter);

                        for (int i = 0; i <= valuesInRow.Length - 1; i++)
                        {
                            if (valuesInRow[i] != "")
                            {
                                nrWydania = valuesInRow[i];

                                try
                                {
                                    DataView datatable = (DataView)this.rEKLAMAUKAZESIEWNRBindingSource.List;
                                    DataRowView row = datatable.AddNew();
                                    row["Nr Wydania"] = nrWydania;

                                    rEKLAMAUKAZESIEWNRBindingSource.EndEdit();
                                }
                                catch (Exception e1)
                                {
                                    Debugger.Log(0, "ttt", e1.Message);
                                }
                            }
                        }
                    }
                }
            }
        }

        private void ogl_dzialComboBox_SelectedValueChanged(object sender, EventArgs e)
        {
            if (obslugaZdarzen)
            {
                if ((ogl_dzialComboBox.SelectedValue != null) && (lISTATYTULOWBindingSource.Current != null))
                {
                    DataRowView row = (DataRowView)lISTATYTULOWBindingSource.Current;
                    string filter = "dzial=" + ogl_dzialComboBox.SelectedValue.ToString();

                    switch (tYTULComboBox.SelectedValue.ToString())
                    {
                        case "AMT":
                            filter += " AND TYTUŁ='2'";
                            break;
                        case "GS":
                            filter += " AND TYTUŁ='1'";
                            break;
                        case "AGRO":
                            filter += " AND TYTUŁ='7'";
                            break;
                        case "adMot":
                            filter += " AND TYTUŁ='6'";
                            break;
                        default:
                            break;
                    }

                    oglrozdzialyBindingSource.Filter = filter;

                    DataRowView Rekrow = (DataRowView)rEKLAMABindingSource.Current;

                    if (Rekrow["ogl_rozdzial"] == DBNull.Value)
                    {
                        ogl_rozdzialComboBox.SelectedIndex = -1;
                        ogl_rozdzialComboBox.SelectedIndex = -1;
                    }
                }
            }
        }

        private void EmailButton_Click(object sender, EventArgs e)
        {
            StringBuilder tresc = new StringBuilder();

            tresc.Append("Potwierdzamy przyjęcie podpisanego zamówienia na publikację reklamy w ");

            if (tYTULComboBox.Text != "adMoto")
            {
                tresc.Append(" gazecie \"" + tYTULComboBox.Text + "\"");
            }
            else
            {
                tresc.Append(" portalu internetowym " + tYTULComboBox.Text);
            }

            tresc.Append(" o wartości " + bRUTTOTextBox.Text + ".");
            //String.Format("{0:P}", cevent.Value);

            tresc.AppendLine("");
            tresc.AppendLine("Reklamy zostaną wyemitowane zgodnie z umową w wydaniu(-ach) nr: \n");

            foreach (DataGridViewRow r in ukazeSieDataGridView.Rows)
            {
                if (r.Cells["nrWydaniaDataGridViewTextBoxColumn"].Value != null)
                {
                    tresc.Append(r.Cells["nrWydaniaDataGridViewTextBoxColumn"].Value.ToString() + ", ");
                }
            }

            tresc.Remove(tresc.Length - 2, 1);

            tresc.AppendLine(" w/w tytułu i udokumentowane fakturą VAT przesłaną na wskazany adres.");

            MailForm mf = new MailForm(Utils.customerId(this.reklamaId), "Potwierdzenie złożenia zamówienia " + iD_REKLAMYTextBox.Text, "", tresc.ToString());

            mf.ShowDialog();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            ogl_rozdzialComboBox.SelectedIndex = -1;
            ogl_rozdzialComboBox.SelectedIndex = -1;
        }

        private void kalendarzButton_Click(object sender, EventArgs e)
        {
            if (tYTULComboBox.SelectedValue != null)
            {
                // nie moze byc Copy() bo moze zawierac wiersza do skasowania
                REKLAMADataSet.UKAZE_SIE_W_NRDataTable table =
                    (REKLAMADataSet.UKAZE_SIE_W_NRDataTable)
                    this.rEKLAMADataSet.UKAZE_SIE_W_NR.Copy();

                REKLAMADataSet.REKLAMARow reklama = (REKLAMADataSet.REKLAMARow)
                    ((DataRowView)(this.rEKLAMABindingSource.Current)).Row;

                KalendarzEmisji kalendarz =
                    new KalendarzEmisji(tYTULComboBox.SelectedValue.ToString(), reklama, table);

                if (kalendarz.ShowDialog() == DialogResult.OK)
                {
                    DataRow[] rows = kalendarz.Emisje.Select("1=1", "[nr wydania] asc");
                    // this.rEKLAMADataSet.UKAZE_SIE_W_NR.Clear();
                    for (int i = 0; i < rows.Length; i++)
                    {
                        if (rEKLAMADataSet.UKAZE_SIE_W_NR.FindByID(
                            Convert.ToDecimal(rows[i]["id"])) == null)
                        {
                            this.rEKLAMADataSet.UKAZE_SIE_W_NR.ImportRow(
                                (REKLAMADataSet.UKAZE_SIE_W_NRRow)rows[i]);
                        }
                    }

                    kalendarz.Close();

                    ukazeSieDataGridView.EndEdit();
                    rEKLAMAUKAZESIEWNRBindingSource.EndEdit();

                    // int il = this.rEKLAMADataSet.UKAZE_SIE_W_NR.Count;
                    int il = ukazeSieDataGridView.Rows.Count;
                    this.kROTNOSCTextBox.Text = il.ToString();
                    this.liczbaEmisjiLabel.Text = il.ToString();
                    rEKLAMABindingSource.EndEdit();

                    PrzeliczCaleZamowienie();
                }
            }
        }

        private void nowaEmisja(object sender, DataTableNewRowEventArgs e)
        {
            ((REKLAMADataSet.UKAZE_SIE_W_NRRow)e.Row).dataDodania = DateTime.Today;
        }

        private void ukazeSieDataGridView_CellContextMenuStripNeeded(object sender, DataGridViewCellContextMenuStripNeededEventArgs e)
        {
            DataGridViewRow clickedRow = ukazeSieDataGridView.Rows[e.RowIndex];

            if (!ukazeSieDataGridView.SelectedRows.Contains(clickedRow))
            {
                e.ContextMenuStrip = null;
                return;
            }

            zmienToolStripMenuItem.Visible = true;
            usunToolStripMenuItem.Visible = true;
            anulujToolStripMenuItem.Visible = false;

            if (ukazeSieDataGridView.SelectedRows.Count == 1)
            {
                if (clickedRow.Selected)
                {
                    if (clickedRow.DefaultCellStyle.BackColor == Color.MintCream)
                    {
                        zmienToolStripMenuItem.Visible = false;
                        usunToolStripMenuItem.Visible = false;
                        anulujToolStripMenuItem.Visible = false;

                        e.ContextMenuStrip = emisjeContextMenuStrip;
                        return;
                    }

                    DataRowView emisja = (DataRowView)ukazeSieDataGridView.Rows[e.RowIndex].DataBoundItem;
                    REKLAMADataSet.UKAZE_SIE_W_NRRow emisjaRow = (REKLAMADataSet.UKAZE_SIE_W_NRRow)emisja.Row;

                    if (emisjaRow.zafakturowana)
                    {
                        zmienToolStripMenuItem.Visible = true;
                        usunToolStripMenuItem.Visible = false;
                        anulujToolStripMenuItem.Visible = true;

                        e.ContextMenuStrip = emisjeContextMenuStrip;
                        return;
                    }
                }
            }
                
            else if (ukazeSieDataGridView.SelectedRows.Count > 1)
            {
                zmienToolStripMenuItem.Visible = false;
                usunToolStripMenuItem.Visible = true;
                anulujToolStripMenuItem.Visible = false;

                foreach (DataGridViewRow r in ukazeSieDataGridView.SelectedRows)
                {
                    if (r.DefaultCellStyle.BackColor == Color.MintCream)
                    {
                        usunToolStripMenuItem.Visible = false;
                        break;
                    }

                    if (Convert.ToBoolean(((DataRowView)r.DataBoundItem)["zafakturowana"]) == true)
                    {
                        usunToolStripMenuItem.Visible = false;
                        break;
                    }
                }

                e.ContextMenuStrip = emisjeContextMenuStrip;
                return;
            }

            e.ContextMenuStrip = emisjeContextMenuStrip;
                 
        }

        public void usunEmisje(object sender, EventArgs e)
        {
            foreach (DataGridViewRow r in ukazeSieDataGridView.SelectedRows)
            {
                ukazeSieDataGridView.Rows.Remove(r);
            }

            ukazeSieDataGridView.EndEdit();
            rEKLAMAUKAZESIEWNRBindingSource.EndEdit();

           // int il = this.rEKLAMADataSet.UKAZE_SIE_W_NR.Count;
            int il = ukazeSieDataGridView.Rows.Count;
            this.kROTNOSCTextBox.Text = il.ToString();
            this.liczbaEmisjiLabel.Text = il.ToString();
            rEKLAMABindingSource.EndEdit();

            PrzeliczCaleZamowienie();

        }

        private void anulujEmisje(object sender, EventArgs e)
        {
            if (ukazeSieDataGridView.CurrentCell != null)
            {
                DataGridViewRow r1 = ukazeSieDataGridView.CurrentCell.OwningRow;

                REKLAMADataSet.UKAZE_SIE_W_NRRow row = (REKLAMADataSet.UKAZE_SIE_W_NRRow)(((DataRowView)r1.DataBoundItem).Row);

                row.status = 2;
                row.dataAnulowania = DateTime.Now;
            }
        }

        private void zmienEmisje(object sender, EventArgs e)
        {
            if (tYTULComboBox.SelectedValue != null)
            {
                REKLAMADataSet.UKAZE_SIE_W_NRDataTable table =
                (REKLAMADataSet.UKAZE_SIE_W_NRDataTable)
                this.rEKLAMADataSet.UKAZE_SIE_W_NR.Copy();

                REKLAMADataSet.REKLAMARow reklama = (REKLAMADataSet.REKLAMARow)
                 ((DataRowView)(this.rEKLAMABindingSource.Current)).Row;

                KalendarzEmisji kalendarz = new KalendarzEmisji(
                    tYTULComboBox.SelectedValue.ToString(),
                    reklama,
                    table,
                    (short)ukazeSieDataGridView.CurrentCell.Value);

                if (kalendarz.ShowDialog() == DialogResult.OK)
                {
                    if (ukazeSieDataGridView.CurrentCell != null)
                    {
                        DataGridViewRow r1 = ukazeSieDataGridView.CurrentCell.OwningRow;
                        REKLAMADataSet.UKAZE_SIE_W_NRRow row = (REKLAMADataSet.UKAZE_SIE_W_NRRow)(((DataRowView)r1.DataBoundItem).Row);

                        if (row.zafakturowana && (row.Nr_Wydania != kalendarz.NowaEmisja))
                        {
                            rEKLAMADataSet.zmianyEmisji.AddzmianyEmisjiRow(row, row.Nr_Wydania, kalendarz.NowaEmisja, DateTime.Now);
                        }

                        row.Nr_Wydania = kalendarz.NowaEmisja;
                        kalendarz.Close();        
                        
                        row.EndEdit();
                        this.rEKLAMADataSet.UKAZE_SIE_W_NR.EndInit();
                        this.rEKLAMAUKAZESIEWNRBindingSource.ResetBindings(false);
                    }
                }
            }
        }
             

        private void ukazeSieDataGridView_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            if (ukazaloSieDataGridView.Rows.Count > 0)
            {
                tYTULComboBox.Enabled = false;
            }
            else
            {
                tYTULComboBox.Enabled = true;
            }
        }

        private void ukazeSieDataGridView_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            blokowanieZrealizowanychEmisji();
        }

        private void walutyComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (obslugaZdarzen)
            {
                if (walutyComboBox.SelectedIndex != -1)
                {
                    kurs = PobierzKurs(walutyComboBox.SelectedItem.ToString());
                    PrzeliczCaleZamowienie();
                }
            }
        }

        private void PrzeliczCaleZamowienie()
        {
            DataRowView row = (DataRowView)rEKLAMABindingSource.Current;
            REKLAMADataSet.REKLAMARow reklama = (REKLAMADataSet.REKLAMARow)row.Row;

            if (walutyComboBox.SelectedIndex != 0)
            {
                 if (reklama.IsBrutto_EuroNull()){
                     reklama.Brutto_Euro = 0;
                     reklama.EndEdit();
                 }
           
                if (kurs != null)
                {
                    przeliczWaluteNaZlotowki(kurs);
                }
                else
                {
                    kurs = PobierzKurs(walutyComboBox.SelectedItem.ToString());

                    if (kurs == null)
                    {
                        MessageBox.Show("Wystąpił błąd!");
                    }
                    else
                    {
                        przeliczWaluteNaZlotowki(kurs);
                    }
                }
            }
            else
            {
              if (row["id_faktury"] == DBNull.Value)
                {
                    row["waluta_tabela_nr"] = DBNull.Value;
                    row["waluta_Przelicznik"] = DBNull.Value;
                    row["waluta_kurs"] = DBNull.Value;
                    row["waluta_kurs_z_dnia"] = DBNull.Value;
                    row["Brutto_Euro"] = DBNull.Value;
                    row["Brutto_Euro_Miano"] = DBNull.Value;
                    row["FAKTURA ID KONTA"] = 1;

                    rEKLAMABindingSource.EndEdit();
                    przelicz();
                }
                else
                {
                    MessageBox.Show("Faktura została już wystawiona!");
                }
            }
        }

        private SLOWNIKDataSet.Kursy_WalutRow PobierzKurs(string kodWaluty)
        {          
            SLOWNIKDataSet.Kursy_WalutDataTable kursy = kursy_WalutTableAdapter.GetDataByDataPublikacji(
                kodWaluty, DateTime.Today);

            if (kursy.Count == 0)
            {
                return null;
            }
            else
            {
                return kursy[0];
            }
        }
          
        private void brutto_EuroTextBox_Leave(object sender, EventArgs e)
        {
            rEKLAMABindingSource.EndEdit();
            PrzeliczCaleZamowienie();
        }

        private void rABATTextBox_Leave(object sender, EventArgs e)
        {
            rEKLAMABindingSource.EndEdit();
            PrzeliczCaleZamowienie();
        }

        private void pVATComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            rEKLAMABindingSource.EndEdit();
            PrzeliczCaleZamowienie();
        }

        private void cENA_JEDNTextBox_Leave(object sender, EventArgs e)
        {
            rEKLAMABindingSource.EndEdit();
            PrzeliczCaleZamowienie();
        }

        private void wyroznienieCheckBox_Click(object sender, EventArgs e)
        {
            this.rEKLAMABindingSource.EndEdit();
            PrzeliczCaleZamowienie();
      
        }

        /// <summary>
        /// formatowanie do decimal -> %
        /// </summary>
        private void DecimalToProcent(object sender, ConvertEventArgs cevent)
        {
            if (Convert.ToDecimal(cevent.Value) > 1)
            {
                //  cevent.Value = Convert.ToDecimal(cevent.Value) / 100;
            }
            cevent.Value = String.Format("{0:P}", cevent.Value);
        }

        /// <summary>
        /// formatowanie do % -> decimal
        /// </summary>
        private void ProcentToDecimal(object sender, ConvertEventArgs cevent)
        {
            string pom = cevent.Value.ToString();
            if (cevent.Value.ToString().EndsWith("%"))
            {
                pom = cevent.Value.ToString().Substring(0, cevent.Value.ToString().Length - 1);
            }
            decimal p = Decimal.Parse(pom) / 100;
            cevent.Value = p.ToString();
        }
   
       private void init()
        {
            if (rEKLAMABindingSource.Current != null)
            {
                DataRowView row = (DataRowView)rEKLAMABindingSource.Current;
                REKLAMADataSet.REKLAMARow reklama = (REKLAMADataSet.REKLAMARow)row.Row;
                //wyliczona cena modulu
                double szer = reklama.SZER;
                double wys = reklama.WYS;
                int krotnosc = reklama.KROTNOŚĆ;
                double cenaJednostkowa = reklama.CENA_JEDN;
                double vatProcent = reklama.VAT;
                double prowizjaProcent = reklama.PROCENT_PROWIZJI;
                double rabatProcent = reklama.RABAT;
                double rabatWartosc = rabatProcent * cenaJednostkowa;
                double netto = (cenaJednostkowa - rabatWartosc) * krotnosc;
                double cenaModulu;
                if ((szer * wys * krotnosc) != 0)
                {
                    cenaModulu = netto / (szer * wys * krotnosc);
                    cenaModuluLabel.Text = String.Format("{0:C}", cenaModulu);
                }
                else
                {
                    cenaModuluLabel.Text = "---";
                }

                liczbaEmisjiLabel.Text = this.rEKLAMADataSet.UKAZE_SIE_W_NR.Rows.Count.ToString();

                this.obslugaZdarzen = false;
                if (!reklama.IsBrutto_Euro_MianoNull())
                {
                    walutyComboBox.SelectedItem = reklama.Brutto_Euro_Miano;
                }
                else
                {
                    walutyComboBox.SelectedIndex = 0; //PLN
                }
                this.obslugaZdarzen = true;
            }
        }
    }
}
