using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;


using System.Drawing;
using System.Collections.Generic;
using ceTe.DynamicPDF;
using ReportVS;
using ceTe.DynamicPDF.Merger;
using LogFilePDF;

public partial class archivioDocumenti : System.Web.UI.Page
{
    static string prevPage = String.Empty;
    private DataTable dtDg;
    public static bool b_sortCommand = true;
    public static string ordinamentoGriglia = string.Empty;

    public string codNSG;
    public string codMandato;
    //public int    tpReport = 1;              //e' la tipologia corrente di Report. Puo' variare a seconda del valore selezionato dalla ListBox
    public string codiceRete;
    public string codicePB;
    public string pathNav;
    public string utente;
    public string recordsCancellati;
    public string recordsDaCancellare;
    public string recordsArchiviati;
    public string recordsDaArchiviare;
    public int idCliente;
    public static DateTime dayA = new DateTime();
    public static DateTime dayDa = new DateTime();
    // private string tipologiaReportExt;
    //private HttpCookie ck_tipologiaReport = new HttpCookie("tipologiaReport");
    private string lastUsedCF;
    private bool justOneCustomer = true;

    private string dayDaQ;
    private string dayAQ;
    private string rsd;
    private string rsp;
    private string nomeQ;
    private string cognomeQ;
    //variabile per gestione accesso archivio documenti
    private bool utenteHD_US;
    //variabile per tenere traccia del fatto che un report sia periodico oppure no
    DataTable hashPeriodico;

    //------------------------------------------------------------------------------------------
    protected void Page_Load(object sender, System.EventArgs e)
    {
        utenteHD_US = GetUtenteAutorizzato.getAccessoPortaleAutorizzato();
        // ***** 18/12/2008 Paolo Giovanetti modifiche accesso archivio documenti *****
        prevPage = Request.UrlReferrer.ToString();

        //Caricamento combobox della tipologia report
        if (!Page.IsPostBack)
        {
            DataTable dt = getTipologiaReport();
            //DataRow[] result = dt.Select("tpReport = 8");
            //foreach (DataRow row in result)
            //    dt.Rows.Remove(row);
            ddl_Modello.DataSource = dt;
            ddl_Modello.DataTextField = "DescrizioneEstesa";
            ddl_Modello.DataValueField = "TpReport";
            ddl_Modello.DataBind();

            ddl_Modello.Items.Insert(0, new ListItem(string.Empty, "0"));
        }

        if (utenteHD_US)
        {
            if (!IsPostBack)
            {

                // sezione A: TODO
                txb_Rete.Enabled = false;
                txb_CodicePB.Enabled = false;
                txb_ClienteCF.Enabled = false;
                txb_ClienteCognome.Enabled = false;
                txb_ClienteNome.Enabled = false;
                txb_mandato.Enabled = true;
                txb_ClienteNSG.Enabled = true;
                ddl_Modello.Enabled = false;
                txt_contratto.Enabled = false;

                DatiHDUS datiHDUS = GetUtenteAutorizzato.getDatiHDUS();
                txb_Rete.Text = datiHDUS.Rete;
                txb_CodicePB.Text = datiHDUS.CodicePB;
                txb_ClienteCF.Text = datiHDUS.CodiceFiscale;
                txb_ClienteCognome.Text = datiHDUS.CognomeCliente;
                txb_ClienteNome.Text = datiHDUS.NomeCliente;

                txt_contratto.Text = datiHDUS.CodiceContratto;
                ListItem lsTipoReport = ddl_Modello.Items.FindByValue(datiHDUS.TipoReport);
                if (lsTipoReport != null)
                    ddl_Modello.Items.FindByValue(datiHDUS.TipoReport).Selected = true;
                else
                    ddl_Modello.ClearSelection();
                // sezione B: TODO

                // sezione C: Solo report di diagnosi e di monitoraggio -> rimuovo gli altri due
                ddl_Modello.Items.Remove(ddl_Modello.Items.FindByValue("2")); //Report di Pianificazione
                ddl_Modello.Items.Remove(ddl_Modello.Items.FindByValue("3")); //Report di Proposta
                //TODO: controllare ricerca senza selezione

                // sezione D: l'utente pu� accedere alle sole stampe definitive (lucchetto chiuso)
                chk_RicercaStampeDefinitive.Checked = true;
                chk_RicercaStampeDefinitive.Enabled = false;
                chk_RicercaStampeProvvisorie.Visible = false;
                btn_EliminaSelezionati.Visible = false;
                btn_Archivia.Visible = false;
                Image2.Visible = false;
                ddl_Modello.SelectedIndex = 0;
                if (lsTipoReport != null)
                    fillDG(Request.QueryString.Get("codcliente"));
                //string command = "parent.document.getElementById('TOP').src = parent.document.getElementById('TOP').src";
                ////    "alert(parent.document.getElementById('TOP').src);parent.document.getElementById('TOP').src='blank.aspx';alert(parent.document.getElementById('TOP').src);parent.document.getElementById('TOP').src='..\top.aspx';alert(parent.document.getElementById('TOP').src);";
                //    //?ReteHD='" + datiHDUS.Rete + "'&CodiceFiscaleHD='" + datiHDUS.CodiceFiscale;
                ////parent.document.getElementById('CENTER').src='ArchivioDocumenti.aspx

                //ClientScript.RegisterClientScriptBlock(typeof(string), "pppppp", "<script language=\"javascript\" type=\"text/javascript\">" + "\n" + "<!--" + "\n" + command + "\n" + "//-->" + "\n" + "</script>"); 

            }
            string command = "SimpleContextMenu.setup({'preventDefault':true, 'preventForms':false});SimpleContextMenu.attach('container', 'CM1');";
            ClientScript.RegisterClientScriptBlock(typeof(string), "pppppp", "<script language=\"javascript\" type=\"text/javascript\">" + "\n" + "<!--" + "\n" + command + "\n" + "//-->" + "\n" + "</script>");

            // ***** Fine 18/12/2008 Paolo Giovanetti modifiche accesso archivio documenti *****
        }
        else
        {
            HomePage.Visible = false;
            ////lettura del valore UTENTE dal cookie

            pathNav = Request.QueryString.Get("pathNav");
            recordsCancellati = Request.QueryString.Get("deleted");
            recordsDaCancellare = Request.QueryString.Get("toBeDeleted");
            recordsArchiviati = Request.QueryString.Get("archived");
            recordsDaArchiviare = Request.QueryString.Get("toBeArchived");

            codNSG = Request.QueryString.Get("codcliente");
            codiceRete = Request.QueryString.Get("tipoRete");
            codicePB = Request.QueryString.Get("codPB");
            utente = codiceRete + codicePB;

            if (!Page.IsPostBack)
            {
                //10/03/2009
                txb_Rete.Enabled = false;
                txb_CodicePB.Enabled = false;

                txb_Rete.Text = Request.QueryString.Get("tipoRete");
                txb_CodicePB.Text = Request.QueryString.Get("codPB");

                string[] txb_ClienteNSGSplittato = Request.QueryString.Get("codcliente").Trim().Split(Convert.ToChar("@"));
                if (txb_ClienteNSGSplittato.Length == 2)
                {
                    txb_ClienteNSG.Text = txb_ClienteNSGSplittato[0];
                    txb_mandato.Text = txb_ClienteNSGSplittato[1];
                }
                else
                {
                    txb_ClienteNSG.Text = Request.QueryString.Get("codcliente");
                    txb_mandato.Visible = false;
                    lbl_mandato.Visible = false;
                }

                if (Request.QueryString.Get("codcliente").Trim() == "")
                {
                    //Vuol dire che � solo pb in ricerca quindi abilito cognome nome nsg mandato
                    txb_ClienteCognome.Enabled = true;
                    txb_ClienteNome.Enabled = true;
                    txb_ClienteNSG.Enabled = true;
                    txb_mandato.Visible = true;
                    lbl_mandato.Visible = true;
                    txb_mandato.Enabled = true;
                }
                else
                {
                    txb_ClienteCognome.Enabled = false;
                    txb_ClienteNome.Enabled = false;
                    txb_ClienteNSG.Enabled = false;
                    txb_mandato.Enabled = false;
                }

                dayAQ = Request.QueryString.Get("dayA");
                dayDaQ = Request.QueryString.Get("dayDa");
                rsd = Request.QueryString.Get("rsd");
                rsp = Request.QueryString.Get("rsp");
                nomeQ = Request.QueryString.Get("nome");
                cognomeQ = Request.QueryString.Get("cognome");

                ddl_Modello.SelectedValue = Request.QueryString.Get("tpReport");

                if (dayAQ != null && dayAQ != "") this.txb_a.Text = dayAQ;
                if (dayDaQ != null && dayDaQ != "") this.txb_da.Text = dayDaQ;
                if (rsd != null && rsd != "") this.chk_RicercaStampeDefinitive.Checked = Convert.ToBoolean(rsd);
                if (rsp != null && rsp != "") this.chk_RicercaStampeProvvisorie.Checked = Convert.ToBoolean(rsp);
                if (nomeQ != null && nomeQ != "") this.txb_ClienteNome.Text = nomeQ;
                if (cognomeQ != null && cognomeQ != "") this.txb_ClienteCognome.Text = cognomeQ;

                string codiceReteAgente = codiceRete + codicePB;

                // rileggo solo se sono non sono stati archiviati o eliminati alcuni report.
                // questo perche nel btn_Archivia_Click e nel btn_EliminaSelezionati_Click viene fatto un redirect alla pagian stessa.
                Cliente cliente = null;
                bool AccessoNoSessioneAutorizzato = false;
                if (Request.QueryString.Get("CODPB") != null && !Request.QueryString.Get("CODPB").Trim().Equals("") &&
                          Request.QueryString.Get("TIPORETE") != null && !Request.QueryString.Get("TIPORETE").Trim().Equals("") &&
                          (Request.QueryString.Get("CODCLIENTE") == null || Request.QueryString.Get("CODCLIENTE").Trim().Equals(""))
                        )
                { AccessoNoSessioneAutorizzato = true; }

                if (!AccessoNoSessioneAutorizzato)
                    cliente = Cliente.getCliente(codiceReteAgente, codNSG);

                if (cliente != null)
                {
                    if (cliente.Definizione == Cliente.TipoDefinizione.Fiduciaria)
                    {
                        this.Label3.Text = "Cognome/Codice fiduciante";
                        this.Label5.Text = "Cod. fiscale / P. IVA";
                        this.txb_ClienteCF.Text = cliente.PIVAFiduciaria;
                        this.txb_ClienteCognome.Text = cliente.Cognome + " - " + cliente.CodiceMandatoFiduciaria;
                    }
                    else
                    {
                        this.txb_ClienteCognome.Text = cliente.Cognome.ToString();
                        this.txb_ClienteCF.Text = codNSG;
                    }
                    this.txb_ClienteNome.Text = cliente.Nome.ToString().Replace("$", "");
                }
                AggiungiParametriDiRicercaInSessione();
                fillDG(codNSG);
                if (Request.QueryString["indicePagina"] != null)
                {
                    cambiaPagina(int.Parse(Request.QueryString["indicePagina"]));
                }
            }
        }

        switch (Request.QueryString.Get("operation"))
        {
            case "DOCUMENTDELETED":
                this.lbl_Message.Text = "Cancellati " + recordsCancellati + " documenti sui " + recordsDaCancellare + " da cancellare.";
                break;

            case "DOCUMENTARCHIVED":
                this.lbl_Message.Text = "Archiviati " + recordsArchiviati + " documenti sui " + recordsDaArchiviare + " da archiviare.";
                break;
        }

        if ((txb_ClienteCognome.Text.Length >= 31 && txb_ClienteNome.Text.Length != 0) && txb_ClienteCognome.Text.Contains(","))
        {
            // Caso COINTESTATARIO (Nome va a capo sul Cognome)
            txb_ClienteCognome.Text = (txb_ClienteCognome.Text.Length == 31) ?
                txb_ClienteCognome.Text + " " + txb_ClienteNome.Text :
                txb_ClienteCognome.Text + txb_ClienteNome.Text;
            txb_ClienteCognome.Width = 500;
            txb_ClienteNome.Text = "";
            txb_ClienteCognome.Enabled = false;
            txb_ClienteNome.Visible = false;
            Label4.Visible = false;
        }
    }


    /// <summary>
    /// Recupera attraverso sp_getTipologiaReport le tipologie dei report.
    /// </summary>
    /// <returns></returns>
    private DataTable getTipologiaReport()
    {
        DataTable dtTipologiaReport = DataAccess.ExecuteDataTableStoredProcedure(DBProvider.SqlServer, "sp_getTipologiaReport", null);
        return dtTipologiaReport;
    }

    private void dg_SortCommand(object source, System.Web.UI.WebControls.DataGridSortCommandEventArgs e)
    {
        if (b_sortCommand)
        {
            ordinamentoGriglia = e.SortExpression + " DESC";
            b_sortCommand = false;
        }
        else
        {
            ordinamentoGriglia = e.SortExpression + " ASC";
            b_sortCommand = true;
        }

        //dg.DataSource = GetData(this.txb_ClienteCF.Text, ordinamentoGriglia);
        //dg.DataBind();
        Ricerca(0, ordinamentoGriglia);


    }
    //------------------------------------------------------------------------------------------
    public void dg_PageIndex(object source, System.Web.UI.WebControls.DataGridPageChangedEventArgs e)
    {
        //codNSG = this.txb_ClienteCF.Text;
        //dg.CurrentPageIndex = e.NewPageIndex;
        //dg.DataSource = GetData(codNSG, ordinamentoGriglia);
        //dg.DataBind();
        Ricerca(e.NewPageIndex, "");

        //cambiaPagina(e.NewPageIndex);
    }
    //------------------------------------------------------------------------------------------

    private void cambiaPagina(int indicePagina)
    {
        codNSG = this.txb_ClienteCF.Text;
        //fillDG(codiceFiscale);

        dg.CurrentPageIndex = indicePagina;

        dg.DataBind();
    }

    private DataTable GetData(string codFiscale, string order)
    {
        DataTable dt = null;

        dt = GetData(codFiscale);
        DataView dv = new DataView(dt);
        dv.Sort = order;
        dt = dv.ToTable("Table");
        return dt;
    }


    private void AggiungiParametriDiRicercaInSessione()
    {
        if ((Session["RD_RitornoDaLog"] != null) || (Session["RD_RitornoDaNote"] != null))
        {
            //visualizzo come da prima della chiamata
            Session.Remove("RD_RitornoDaLog");
            Session.Remove("RD_RitornoDaNote");
        }
        else
        {
            //if (this.txb_ClienteCognome.Text.Trim().Length > 0)
            //    if (codNSG.Contains("@") && txb_ClienteCognome.Text.Contains("-"))
            //        Session.Add("RD_ClienteCognome", this.txb_ClienteCognome.Text.Split('-')[0].Trim());
            //    else
            //        Session.Add("RD_ClienteCognome", this.txb_ClienteCognome.Text);
            //else
            //    Session.Remove("RD_ClienteCognome");

            //if (this.txb_ClienteNome.Text.Trim().Length > 0)
            //    Session.Add("RD_ClienteNome", this.txb_ClienteNome.Text);
            //else
            //    Session.Remove("RD_ClienteNome");

            if (ddl_Modello.SelectedValue != "0")
                Session.Add("RD_tpReport", ddl_Modello.SelectedValue);
            else
                Session.Remove("RD_tpReport");

            if (utente != null)
                Session.Add("RD_utente", utente);
            else
                Session.Remove("RD_utente");

            if (this.txb_mandato.Text != "")
                Session.Add("RD_codMandato", this.txb_mandato.Text);
            else
                Session.Remove("RD_codMandato");

            if (this.txb_ClienteNSG.Text != "")
                Session.Add("RD_codNSG", this.txb_ClienteNSG.Text);
            else
                Session.Remove("RD_codNSG");

            if (this.txb_da.Text != "")
                Session.Add("RD_dataDa", this.txb_da.Text);
            else
                Session.Remove("RD_dataDa");

            if (this.txb_a.Text != "")
            {
                dayA = Convert.ToDateTime(this.txb_a.Text);
                TimeSpan ungiorno = new TimeSpan(1, 0, 0, 0);
                Session.Add("RD_dataA", dayA.Add(ungiorno));
            }
            else
                Session.Remove("RD_dataA");

            if (this.chk_RicercaStampeProvvisorie.Checked)
                Session.Add("RD_flagArchiviato", false);
            else if (this.chk_RicercaStampeDefinitive.Checked)
                Session.Add("RD_flagArchiviato", true);
            else
                Session.Remove("RD_flagArchiviato");

            Session.Add("RD_flagStorico", this.chk_RicercaStampedaRichiedere.Checked);
        }
    }

    private DataTable GetData(string codNSG)
    {
        List<Parametro> parametri = new List<Parametro>();

        Parametro parametro;
        // se dalla combo tipologia modello non � stato selezionato nulla, 
        // il parametro "tpReport" non viene passato alla stored per il recupero dati
        if (Session["RD_tpReport"] != null)
        {
            parametro = new Parametro();
            parametro.DbType = DbType.Int32;
            parametro.Value = Convert.ToInt32(Session["RD_tpReport"]);
            parametro.ParameterName = "tpReport";
            parametri.Add(parametro);
        }

        #region
        //parametro = new Parametro();
        //parametro.DbType = DbType.AnsiString;
        //if (string.IsNullOrEmpty(this.txt_contratto.Text))
        //    parametro.Value = DBNull.Value;
        //else
        //    parametro.Value = this.txt_contratto.Text;
        //parametro.ParameterName = "codiceContratto";
        //parametri.Add(parametro);


        //parametro = new Parametro();
        //parametro.DbType = DbType.Int32;
        //parametro.ParameterName = "tpReportHD_US";
        //parametri.Add(parametro);
        //if (utenteHD_US)
        //    parametro.Value = 1;
        //else
        //    parametro.Value = 0;
        #endregion

        parametro = new Parametro();
        parametro.DbType = DbType.String;
        if (utente != null)
            parametro.Value = Session["RD_utente"];
        else
            parametro.Value = System.DBNull.Value;
        parametro.ParameterName = "utente";
        parametri.Add(parametro);

        parametro = new Parametro();
        parametro.DbType = DbType.String;
        if (Session["RD_codNSG"] != null)
            parametro.Value = Session["RD_codNSG"];
        else
            parametro.Value = System.DBNull.Value;
        parametro.ParameterName = "codNSG";
        parametri.Add(parametro);

        parametro = new Parametro();
        parametro.DbType = DbType.String;
        if (Session["RD_ClienteCognome"] != null)
            parametro.Value = Session["RD_ClienteCognome"];
        else
            parametro.Value = System.DBNull.Value;
        parametro.ParameterName = "cognome";
        parametri.Add(parametro);

        parametro = new Parametro();
        parametro.DbType = DbType.String;
        if (Session["RD_ClienteNome"] != null)
            parametro.Value = Session["RD_ClienteNome"];
        else
            parametro.Value = System.DBNull.Value;
        parametro.ParameterName = "nome";
        parametri.Add(parametro);

        parametro = new Parametro();
        parametro.DbType = DbType.DateTime;
        if (Session["RD_dataDa"] != null)
        {
            dayDa = Convert.ToDateTime(Session["RD_dataDa"]);
            parametro.Value = dayDa;
        }
        else
            parametro.Value = System.DBNull.Value;
        parametro.ParameterName = "dataDa";
        parametri.Add(parametro);

        parametro = new Parametro();
        parametro.DbType = DbType.DateTime;
        if (Session["RD_dataA"] != null)
        {
            parametro.Value = Session["RD_dataA"];
        }
        else
            parametro.Value = System.DBNull.Value;
        parametro.ParameterName = "dataA";
        parametri.Add(parametro);

        parametro = new Parametro();
        parametro.DbType = DbType.Boolean;
        if (Session["RD_flagArchiviato"] != null)
            parametro.Value = Session["RD_flagArchiviato"];
        else
            parametro.Value = System.DBNull.Value;
        parametro.ParameterName = "flagArchiviato";
        parametri.Add(parametro);

        parametro = new Parametro();
        parametro.DbType = DbType.Boolean;
        parametro.Value = Session["RD_flagStorico"];
        parametro.ParameterName = "flagStorico";
        parametri.Add(parametro);

        parametro = new Parametro();
        parametro.DbType = DbType.String;
        if (Session["RD_codMandato"] != null)
            parametro.Value = Session["RD_codMandato"];
        else
            parametro.Value = System.DBNull.Value;
        parametro.ParameterName = "codman";
        parametri.Add(parametro);

        DataTable dtDgData = DataAccess.ExecuteDataTableStoredProcedure(DBProvider.SqlServer, "sp_getAllDocumentsByFilters_new", parametri);

        hashPeriodico = dtDgData;

        return dtDgData;

    }


    protected void fillDG(string codFiscale)
    {
        //// Nel caso in cui il cliente � una fiduciaria imposto il codiceFiscale come FF@CodiceMandatoFiduciaria 
        //if (codFiscale.Contains("@"))
        //{
        //    string codiceMandato = "";
        //    int pos = codFiscale.LastIndexOf("@");
        //    codiceMandato = codFiscale.Substring(pos + 1, codFiscale.Length - (pos + 1));
        //    codFiscale = "FF@" + codiceMandato;
        //}

        this.lbl_Message.Text = "";
        //int _numeroRighe = StampaDG();

        DataTable dtDg = GetData(Request.QueryString.Get("codcliente"));

        // ANOMALIA 529
        //foreach (DataRow dr in dtDg.Rows)
        //{
        //    string cognome = dr["Cognome"].ToString();
        //    string nome = dr["Nome"].ToString();
        //    if ((dr["Cognome"].ToString().Length != 0))
        //    {
        //        if (dr["Nome"].ToString().Contains("-"))
        //            dr["Nominativo"] = dr["Cognome"].ToString();
        //        else
        //            if (dr[11].ToString().Contains("@"))
        //            dr["Nominativo"] = dr["Cognome"].ToString() + " " + dr["Nome"].ToString();
        //        else
        //            dr["Nominativo"] = dr["Nome"].ToString() + " " + dr["Cognome"].ToString();
        //    }
        //    else
        //    {
        //        var cliente = Cliente.getCliente(dr["Rete"].ToString() + dr["CodicePB"], dr["codNSG"].ToString());
        //        if ((cliente.Cognome.Length >= 32 && cliente.Nome.ToString().Length != 0) && cliente.Cognome.Contains(","))
        //            dr["Nominativo"] = cliente.Cognome + cliente.Nome;
        //        else
        //            dr["Nominativo"] = cliente.Nome + " " + cliente.Cognome;
        //    }
        //}

        foreach (DataRow dr in dtDg.Rows)
        {
            string cognome = dr["Cognome"].ToString();
            string nome = dr["Nome"].ToString();
            if(cognome != "")
            { 
                if ((cognome.Length >= 31 && nome.Length != 0) && (cognome.Contains(",") || nome.Contains(",")))
                    dr["Nominativo"] = cognome + ((cognome.Length == 31) ? " " + nome : nome);
                else
                {
                    if (nome.Contains("-"))
                        dr["Nominativo"] = cognome;
                    else
                        if (dr[11].ToString().Contains("@"))
                        dr["Nominativo"] = cognome + " " + nome;
                    else
                        dr["Nominativo"] = nome + " " + cognome;
                }
            }

        }

        dg.CurrentPageIndex = 0;
        dg.DataSource = dtDg;
        dg.DataBind();
        dg.Visible = true;

        this.lbl_Message.ForeColor = System.Drawing.Color.Black;
        this.lbl_Message.Text = "Sono stati trovati " + dtDg.Rows.Count + " documenti con il criterio di ricerca prescelto.";
    }
    //=======================================================================
    private int getClienteFromCodFiscale(string codFiscale)
    {
        List<Parametro> parametri = new List<Parametro>();
        Parametro codiceCliente = new Parametro();
        codiceCliente.DbType = DbType.String;
        codiceCliente.Value = codNSG;
        codiceCliente.ParameterName = "codiceFiscale";
        parametri.Add(codiceCliente);

        return (Int32)DataAccess.ExecuteScalarStoredProcedure(DBProvider.SqlServer, "sp_getIdClienteFromCodFiscale", parametri);

    }

    #region Web Form Designer generated code
    override protected void OnInit(EventArgs e)
    {
        //
        // CODEGEN: This call is required by the ASP.NET Web Form Designer.
        //
        InitializeComponent();
        base.OnInit(e);
    }

    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {
        this.dg.PageIndexChanged += new System.Web.UI.WebControls.DataGridPageChangedEventHandler(this.dg_PageIndex);
        this.dg.SortCommand += new System.Web.UI.WebControls.DataGridSortCommandEventHandler(this.dg_SortCommand);
        this.dg.ItemDataBound += new System.Web.UI.WebControls.DataGridItemEventHandler(this.dg_ItemDataBound);

    }
    #endregion
    //------------------------------------------------------------------------------------------
    private void dg_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
    {
        //se lo stato e' "archiviato" non e' possibile operare sul record
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            object fieldRichiestaInoltrata;
            Int16 statoBottoneRichiedi = 0;
            DataRowView drv = (DataRowView)e.Item.DataItem;

            if (Convert.ToBoolean(e.Item.Cells[2].Text))
            {
                ((CheckBox)e.Item.FindControl("chk")).Visible = false;
            }

            //Recupero controlli HTML immagine ed ancora al documento:
            System.Web.UI.HtmlControls.HtmlAnchor linkDocumento = ((System.Web.UI.HtmlControls.HtmlAnchor)e.Item.Cells[11].FindControl("linkDocumento"));
            System.Web.UI.HtmlControls.HtmlImage imglinkDocumento = ((System.Web.UI.HtmlControls.HtmlImage)e.Item.Cells[11].FindControl("imgLinkDocumento"));

            if (e.Item.Cells[15].Text == "0")
            {
                //Download del documento gi� disponibile.
                imglinkDocumento.Src = "Images/PDF-Icon.jpg";
                linkDocumento.Title = "Clicca per vedere il documento";
                linkDocumento.HRef = "javascript:showPdf(" + e.Item.Cells[4].Text + "," + e.Item.Cells[16].Text + ",'" + codNSG + "')";
            }
            else
            {
                fieldRichiestaInoltrata = DataBinder.Eval(e.Item.DataItem, "RichiestaInoltrata");
                if (fieldRichiestaInoltrata != System.DBNull.Value)
                {
                    statoBottoneRichiedi = Convert.ToInt16(fieldRichiestaInoltrata);
                }

                if (statoBottoneRichiedi.Equals(0))
                {
                    //Richiesta di un documento non ancora disponibile.
                    imglinkDocumento.Src = "Images/richiediDoc.jpg";
                    linkDocumento.Title = "Clicca per richiedere il documento";
                    linkDocumento.HRef = "richiediDocumenti.aspx?Nominativo=" + e.Item.Cells[6].Text + "&dtCreazione=" + e.Item.Cells[8].Text + "&identificativo=" +
                                                                                                          e.Item.Cells[4].Text + "&rete=" + e.Item.Cells[17].Text + "&codfis=" + e.Item.Cells[14].Text + "&pb=" + e.Item.Cells[5].Text +
                                                                                                          "&Tipo=" + e.Item.Cells[7].Text +
                                                                                                          "&token=" + Request.QueryString.Get("token") +
                                                                                                          "&checkPrivacy=" + Request.QueryString.Get("checkPrivacy") +
                                                                                                          "&pathNav=" + Request.QueryString.Get("pathNav") +
                                                                                                          "&ambiente=" + Request.QueryString.Get("ambiente") + "";
                }
                else
                {
                    //Richiesta gi� in corso.
                    imglinkDocumento.Src = "Images/richiediDoc_disabilitata.jpg";
                    linkDocumento.Title = "Recupero documento in corso";
                    linkDocumento.HRef = "";
                    imglinkDocumento.Attributes.Add("onmouseover", "this.style.cursor='wait';");
                    imglinkDocumento.Attributes.Add("onmouseout", "this.style.cursor='default';");
                }

                e.Item.ForeColor = System.Drawing.Color.Gray;
            }

            if (utenteHD_US)
            {
                e.Item.Attributes.Add("oncontextmenu", "javascript:ShowContextMenu(" + e.Item.ItemIndex + "," + e.Item.Cells[4].Text + ",1,'" + txb_Rete.Text.Trim() + "','" + txb_ClienteCF.Text.Trim() + "');");
            }
        }
    }
    //------------------------------------------------------------------------------------------
    protected bool checkIfAtLeastOneItemClicked()
    {
        bool rc = false;
        for (int i = 0; i < dg.Items.Count; i++)
        {
            if (((CheckBox)dg.Items[i].FindControl("chk")).Checked == true)
            {
                rc = true;
                break;
            }
        }
        return rc;
    }

    //=====================================================================
    protected void btn_EliminaSelezionati_Click(object sender, EventArgs e)
    {
        this.lbl_Message.Text = "";
        bool rc = checkIfAtLeastOneItemClicked();

        if (rc)//almeno 1 item deputato alla cancellazione....
        {
            int docToDelete;
            int idRepository;
            int deleted = 0;
            int itemsToDelete = 0;

            //conto il numero dei modelli da cancellare
            for (int i = 0; i < dg.Items.Count; i++)
            {
                if (((CheckBox)dg.Items[i].FindControl("chk")).Checked == true && ((CheckBox)dg.Items[i].FindControl("chk")).Visible == true)
                {
                    itemsToDelete++;
                }
            }

            for (int i = 0; i < dg.Items.Count; i++)
            {
                if (((CheckBox)dg.Items[i].FindControl("chk")).Checked == true)
                {
                    docToDelete = Convert.ToInt32(dg.Items[i].Cells[4].Text);  //campo nascosto con l'ID del Report da cancellare
                    idRepository = Convert.ToInt32(dg.Items[i].Cells[16].Text);  //campo nascosto con l'ID del Report da cancellare
                    int retCode = deleteDocumentFromDB(docToDelete, idRepository);
                    if (retCode != -1)
                    {
                        deleted++;
                    }
                }
            }
            if (deleted == itemsToDelete)
            {
                lbl_Message.ForeColor = System.Drawing.Color.Black;
            }

            Response.Redirect(prevPage);
            readData(codNSG);
            if (justOneCustomer == true)
            {
                lastUsedCF = dg.Items[0].Cells[12].Text;
                if (codNSG != lastUsedCF && lastUsedCF != string.Empty)
                    codNSG = lastUsedCF;
                justOneCustomer = false;
            }
            //else
            //{
            //    codiceFiscale = "";
            //}

            string tipoDoc = dg.Items[0].Cells[6].Text;

            if (tipoDoc != null && tipoDoc != "")
            {
                HttpCookie ck_tipologiaReport = new HttpCookie("tipologiaReport");
                ck_tipologiaReport.Value = tipoDoc.ToUpper();
                Response.Cookies.Add(ck_tipologiaReport);
            }

            //Response.Redirect("archivioDocumenti.aspx?codiceFiscale=" + codiceFiscale + "&codiceRete=" + codiceRete + "&codicePB=" + codicePB + "&pathNav=" + pathNav + "&tpReport=" + tpReport + "&utente=" + utente + "&deleted=" + deleted + "&toBeDeleted=" + itemsToDelete + "&operation=DOCUMENTDELETED" + "&dayDa=" + txb_da.Text + "&dayA=" + txb_a.Text + "&rsd=" + this.chk_RicercaStampeDefinitive.Checked.ToString() + "&rsp=" + chk_RicercaStampeProvvisorie.Checked.ToString() + "&cognome=" + txb_ClienteCognome.Text + "&nome=" + txb_ClienteNome.Text);
            //Response.Redirect("archivioDocumenti.aspx?codiceFiscale=" + codiceFiscale + "&codiceRete=" + codiceRete + "&codicePB=" + codicePB + "&pathNav=" + pathNav + "&tpReport=" + ddl_Modello.SelectedValue + "&utente=" + utente + "&deleted=" + deleted + "&toBeDeleted=" + itemsToDelete + "&operation=DOCUMENTDELETED" + "&dayDa=" + txb_da.Text + "&dayA=" + txb_a.Text + "&rsd=" + this.chk_RicercaStampeDefinitive.Checked.ToString() + "&rsp=" + chk_RicercaStampeProvvisorie.Checked.ToString() + "&cognome=" + txb_ClienteCognome.Text + "&nome=" + txb_ClienteNome.Text);
            //Response.Redirect("archivioDocumenti.aspx?codCliente=" + codNSG + "&tipoRete=" + codiceRete + "&codPB=" + codicePB + "&pathNav=" + pathNav + "&tpReport=" + ddl_Modello.SelectedValue + "&utente=" + utente + "&deleted=" + deleted + "&toBeDeleted=" + itemsToDelete + "&operation=DOCUMENTDELETED" + "&dayDa=" + txb_da.Text + "&dayA=" + txb_a.Text + "&rsd=" + this.chk_RicercaStampeDefinitive.Checked.ToString() + "&rsp=" + chk_RicercaStampeProvvisorie.Checked.ToString() + "&cognome=" + txb_ClienteCognome.Text + "&nome=" + txb_ClienteNome.Text);

        }
        else
        {
            //this.lbl_Message.Text = "Attenzione. Selezionare almeno un DOCUMENTO da cancellare.";
        }
    }
    //=====================================================================
    private int deleteDocumentFromDB(int iddocument, int idrepository)
    {
        List<Parametro> parametri = new List<Parametro>();
        Parametro parametro = new Parametro();
        parametro.ParameterName = "idDocument";
        parametro.Value = iddocument;
        parametro.DbType = DbType.Int32;
        parametri.Add(parametro);


        parametro = new Parametro();
        parametro.ParameterName = "idRepository";
        parametro.Value = idrepository;
        parametro.DbType = DbType.Int32;
        parametri.Add(parametro);


        return DataAccess.ExecuteNonQueryStoredProcedure(DBProvider.SqlServer, "sp_deleteDocumentFromDB_ByIdDocument", parametri);

    }
    //=====================================================================
    protected void btn_Archivia_Click(object sender, EventArgs e)
    {
        this.lbl_Message.Text = "";
        bool rc = checkIfAtLeastOneItemClicked();

        if (rc)//almeno 1 item deputato alla archiviazione....
        {
            int docToArchive;
            int archived = 0;
            int itemsToArchive = 0;
            string tipoReport = "";
            //conto il numero dei modelli da cancellare
            for (int i = 0; i < dg.Items.Count; i++)
            {
                if (((CheckBox)dg.Items[i].FindControl("chk")).Checked == true && ((CheckBox)dg.Items[i].FindControl("chk")).Visible == true)
                {
                    itemsToArchive++;
                }
            }

            for (int i = 0; i < dg.Items.Count; i++)
            {
                if (((CheckBox)dg.Items[i].FindControl("chk")).Checked == true)
                {
                    docToArchive = Convert.ToInt32(dg.Items[i].Cells[4].Text);  //campo nascosto con l'ID del Report da archiviare
                    tipoReport = dg.Items[i].Cells[7].Text.ToUpper();
                    int retCode = archiveDocumentIntoDB(docToArchive, tipoReport);
                    if (retCode != -1)
                    {
                        //VALERIO 10/03/2009 Aggancio il log
                        GestoreLogPDF gl = new GestoreLogPDF(docToArchive);
                        gl.scriviLog(EventLog.CambioStato_UnlockedLocked);
                        //
                        archived++;
                    }
                }
            }
            if (archived == itemsToArchive)
            {
                lbl_Message.ForeColor = System.Drawing.Color.Black;
            }
            Response.Redirect(prevPage);
            readData(null);
            if (justOneCustomer == true)
            {
                lastUsedCF = dg.Items[0].Cells[12].Text;
                if (codNSG != lastUsedCF && lastUsedCF != string.Empty)
                    codNSG = lastUsedCF;
                justOneCustomer = false;
            }
            //else
            //{
            //    codiceFiscale = "";
            //}

            string tipoDoc = dg.Items[0].Cells[6].Text;
            if (tipoDoc != null && tipoDoc != "")
            {
                HttpCookie ck_tipologiaReport = new HttpCookie("tipologiaReport");
                ck_tipologiaReport.Value = tipoDoc.ToUpper();
                Response.Cookies.Add(ck_tipologiaReport);
            }

            Response.Redirect("archivioDocumenti.aspx?codcliente=" + codNSG + "&tipoRete=" + codiceRete + "&codPB=" + codicePB + "&pathNav=" + pathNav + "&tpReport=" + ddl_Modello.SelectedValue + "&utente=" + utente + "&archived=" + archived + "&toBeArchived=" + itemsToArchive + "&operation=DOCUMENTARCHIVED" + "&dayDa=" + txb_da.Text + "&dayA=" + txb_a.Text + "&rsd=" + this.chk_RicercaStampeDefinitive.Checked.ToString() + "&rsp=" + chk_RicercaStampeProvvisorie.Checked.ToString() + "&cognome=" + txb_ClienteCognome.Text + "&nome=" + txb_ClienteNome.Text);
        }
        else
        {
            //this.lbl_Message.Text = "Attenzione. Selezionare almeno un DOCUMENTO da ARCHIVIARE.";
        }
    }
    //=====================================================================
    private int archiveDocumentIntoDB(int docToArchive, string tipoReport)
    {
        //SOLO SE IL CLIENTE E' CONTRATTUALIZZATO

        //CTable tbl = new CTable(codiceFiscale, codicePB, codiceRete);
        //bool clienteConContrattoSEI = tbl.CustomerHasNoContrattoSEI(codicePB, codiceFiscale, codiceRete);

        bool clienteConContrattoSEI = Cliente.getCliente(codiceRete + codicePB, codNSG).SottoscrizioneContrattoSei;

        int result = -1;
        DocumentPDF documentPDF = new DocumentPDF();
        //PRIMA RECUPERO IL FILE PDF POI LO RIELABORO APPLICANDO LA PATCH PER CAMBIAMENTO DISCLAIMAR
        //VALERIO 10/03/2009
        //Applico la patch dei disclaimer a tutti i report per i quali il cliente � CONTRATTUALIZZATO
        //if ((tipoReport == "DIAGNOSI") && (clienteConContrattoSEI) && (WebConfigParameter.getParameter("GestioneDisclaimerC6") == "SI")){
        if (clienteConContrattoSEI && (WebConfigParameter.getParameter("GestioneDisclaimerC6") == "SI"))
        {
            result = documentPDF.patchAndArchive(docToArchive);
        }
        else
        {
            result = documentPDF.archive(docToArchive);
        }
        return result;
    }
    //=====================================================================

    protected void btn_Ricerca_Click(object sender, EventArgs e)
    {
        Ricerca(0, "");
    }

    private void Ricerca(int _pageIndex, string ordinamentoGriglia)
    {
        string rc = checkTypedData();
        //ordinamentoGriglia = string.Empty;
        //codNSG = txb_ClienteCF.Text;
        string nomeCliente = txb_ClienteNome.Text.ToUpper();
        string cognomeCliente = txb_ClienteCognome.Text.ToUpper();
        string codNSG = txb_ClienteNSG.Text.ToUpper();
        //string mandato = txb_mandato.Text.ToUpper();
        DateTime dataDa;
        DateTime dataA;
        Boolean daRimuovere;
        int _conteggio=0;

        if (rc == "")
        {
            AggiungiParametriDiRicercaInSessione();

            dg.DataSource = null;
            dg.DataBind();
            if (codNSG.Length == 11)
                fillDG(Request.QueryString.Get("codcliente"));
            else
            {
                this.lbl_Message.Text = "";
                DataTable dtDg = GetData(Request.QueryString.Get("codcliente"));
                for (int i = dtDg.Rows.Count - 1; i >= 0; i--)
                {
                    daRimuovere = false;
                    DataRow dr = dtDg.Rows[i];
                    Cliente cliente = Cliente.getCliente(dr["Rete"].ToString() + dr["CodicePB"], dr["codNSG"].ToString());
                    string cognome = dr["Cognome"].ToString();
                    string nome = dr["Nome"].ToString();

                    if (cognome == "")
                        daRimuovere = true;

                    if (cognome != "" && daRimuovere == false)
                    {
                        //FC Aggiunta gestione Cointestazione 
                        if ((cognomeCliente.Length >= 31 && cognomeCliente.Length != 0) && cognomeCliente.Contains(","))
                        {
                            if ((!cognome.Contains(cognomeCliente) && cognomeCliente != "") && (nomeCliente != "" && !(nome.Contains(nomeCliente))) )
                                daRimuovere = true;

                        }
                        else {
                            if (!cognome.Contains(cognomeCliente) && cognomeCliente != "")
                                daRimuovere = true;
                        }

                        
                    }

                    if (nome != "" && daRimuovere == false)
                    {
                        if (nomeCliente != "" && !(nome.Contains(nomeCliente)))
                            daRimuovere = true;
                    }

                    if (txb_da.Text.ToUpper() != "" && !daRimuovere)
                    {
                        dataDa = Convert.ToDateTime(txb_da.Text.ToUpper());
                        if (Convert.ToDateTime(dr["DtCreazione"]) < dataDa)
                            daRimuovere = true;
                    }
                    //  ANOMALIA INSERIMENTO MANDATO
                    //if (mandato != "" && dr[17] != mandato && !daRimuovere)
                    //{
                    //    daRimuovere = true;
                    //}

                    if (txb_a.Text.ToUpper() != "" && !daRimuovere)
                    {
                        dataA = Convert.ToDateTime(txb_a.Text.ToUpper());
                        if (Convert.ToDateTime(dr["DtCreazione"]) > dataA)
                            daRimuovere = true;
                    }

                    if (daRimuovere)
                        dr.Delete();
                    else
                    {
                        _conteggio++;
                        if ((cognome.Length >= 32 && nome.Length != 0) && (cognome.Contains(",") || nome.Contains(",")))
                            dr["Nominativo"] = cognome + nome;
                        else
                        {
                            if (nome.Contains("-"))
                                dr["Nominativo"] = cognome;
                            else
                                if (dr[11].ToString().Contains("@"))
                                dr["Nominativo"] = cognome + " " + nome;
                            else
                                dr["Nominativo"] = nome + " " + cognome;
                        }
                        //if ((dr["Cognome"].ToString().Length != 0))
                        //{
                        //    if (dr["Nome"].ToString().Contains("-"))
                        //        dr["Nominativo"] = dr["Cognome"].ToString();
                        //    else
                        //        if (dr[11].ToString().Contains("@"))
                        //        dr["Nominativo"] = dr["Cognome"].ToString() + " " + dr["Nome"].ToString();
                        //    else
                        //        dr["Nominativo"] = dr["Nome"].ToString() + " " + dr["Cognome"].ToString();
                        //}
                        //else
                        //{
                        //    if ((cliente.Cognome.Length >= 32 && cliente.Nome.ToString().Length != 0) && cliente.Cognome.Contains(","))
                        //        dr["Nominativo"] = cliente.Cognome + cliente.Nome;
                        //    else
                        //        dr["Nominativo"] = cliente.Nome + " " + cliente.Cognome;
                        //}
                    }
                }

                dg.CurrentPageIndex = _pageIndex;
                if (ordinamentoGriglia != "")
                {
                    DataView dv = new DataView(dtDg);
                    dv.Sort = ordinamentoGriglia;
                    dtDg = dv.ToTable("Table");
                }

                dg.DataSource = dtDg;
                dg.DataBind();
                dg.Visible = true;
                

                this.lbl_Message.ForeColor = System.Drawing.Color.Black;
                this.lbl_Message.Text = "Sono stati trovati " + _conteggio + " documenti con il criterio di ricerca prescelto.";
            }
        }
        else
        {
            this.lbl_Message.ForeColor = System.Drawing.Color.Red;
            this.lbl_Message.Text = rc;
        }
    }

    //=====================================================================

    private string checkTypedData()
    {
        string rc = "";
        bool rcode;

        Validation vld = new Validation();

        if (this.txb_ClienteCF.Text != "")
        {
            //if (txb_ClienteCF.Text.Length != 11)
            //    rcode = vld.IsValidCF(this.txb_ClienteCF.Text);
            //else
            //    rcode = true;
            //if (!rcode) rc = "Attenzione. Codice Fiscale NON valido.";
        }

        if (this.txb_da.Text != "")
        {
            rcode = vld.IsData(this.txb_da.Text);
            if (!rcode) rc = "Attenzione. Data di inizio periodo NON valida.";
        }

        if (this.txb_a.Text != "")
        {
            rcode = vld.IsData(this.txb_a.Text);
            if (!rcode) rc = "Attenzione. Data di fine periodo NON valida.";
        }

        if (this.txb_a.Text != "" && this.txb_da.Text != "" && rc == "")
        {
            if (Convert.ToDateTime(this.txb_a.Text) < Convert.ToDateTime(this.txb_da.Text))
            {
                rc = "Attenzione. Data di fine periodo inferiore alla data di inizio periodo.";
            }
        }

        return rc;
    }
    //=====================================================================
    protected void imgCalendar_Da_Click(object sender, ImageClickEventArgs e)
    {
        this.cldSF_da.Visible = !this.cldSF_da.Visible;
        this.cldSF_a.Visible = false;
    }
    //======================================================================
    protected void imgCalendar_a_Click(object sender, ImageClickEventArgs e)
    {
        this.cldSF_a.Visible = !this.cldSF_a.Visible;
        this.cldSF_da.Visible = false;
    }
    //======================================================================
    protected void cldSF_da_SelectionChanged(object sender, EventArgs e)
    {
        dayDa = this.cldSF_da.SelectedDate;
        this.txb_da.Text = this.cldSF_da.SelectedDate.ToShortDateString();
        this.cldSF_da.Visible = false;
    }
    //======================================================================
    protected void cldSF_a_SelectionChanged(object sender, EventArgs e)
    {
        dayA = this.cldSF_a.SelectedDate;
        this.txb_a.Text = this.cldSF_a.SelectedDate.ToShortDateString();
        this.cldSF_a.Visible = false;
    }
    //======================================================================
    protected void chk_RicercaStampeDefinitive_CheckedChanged(object sender, EventArgs e)
    {
        // this.chk_RicercaStampeProvvisorie.Checked = !this.chk_RicercaStampeDefinitive.Checked;
        if (this.chk_RicercaStampeDefinitive.Checked)
        {
            if (this.chk_RicercaStampeProvvisorie.Checked) this.chk_RicercaStampeProvvisorie.Checked = false;
            if (this.chk_RicercaStampedaRichiedere.Checked) this.chk_RicercaStampedaRichiedere.Checked = false;
        }
    }
    //=======================================================================
    protected void chk_RicercaStampeProvvisorie_CheckedChanged(object sender, EventArgs e)
    {
        //this.chk_RicercaStampeDefinitive.Checked = !this.chk_RicercaStampeProvvisorie.Checked;
        if (this.chk_RicercaStampeProvvisorie.Checked)
        {
            if (this.chk_RicercaStampeDefinitive.Checked) this.chk_RicercaStampeDefinitive.Checked = false;
            if (this.chk_RicercaStampedaRichiedere.Checked) this.chk_RicercaStampedaRichiedere.Checked = false;
        }

    }
    //=======================================================================
    protected void btn_Azzera_Click(object sender, EventArgs e)
    {
        if (utenteHD_US)
        {
            this.txb_da.Text = "";
            this.txb_a.Text = "";
        }
        else
        {
            this.chk_RicercaStampeDefinitive.Checked = false;
            this.chk_RicercaStampeProvvisorie.Checked = false;
            this.txb_da.Text = "";
            this.txb_a.Text = "";
            this.txb_ClienteCognome.Text = "";
            this.txb_ClienteNome.Text = "";
            this.txb_ClienteCF.Text = "";
            this.cldSF_a.SelectedDate = new DateTime(1, 1, 1);
            this.cldSF_da.SelectedDate = new DateTime(1, 1, 1);
            this.ddl_Modello.SelectedIndex = 0;
            this.lbl_Message.Text = "";
        }
        AggiungiParametriDiRicercaInSessione();
        btn_Ricerca_Click(sender, e);
    }

    //------------------------------------------------------------------------------------------
    protected void readData(string codFiscale)
    {

        //check se ho un trovato 1 gruppo di clienti o 1 solo, in questo caso ho 1 CF valido
        List<Parametro> parametri = new List<Parametro>();
        Parametro parametro = new Parametro();
        parametro.DbType = DbType.Int32;
        parametro.Value = Convert.ToInt32(ddl_Modello.SelectedValue);
        parametro.ParameterName = "tpReport";
        parametri.Add(parametro);

        parametro = new Parametro();
        parametro.DbType = DbType.String;
        if (utente != null) parametro.Value = utente;
        else parametro.Value = System.DBNull.Value;
        parametro.ParameterName = "utente";
        parametri.Add(parametro);

        parametro = new Parametro();
        parametro.DbType = DbType.String;

        if (codFiscale != null && codFiscale != "")
            parametro.Value = codFiscale;
        else if (this.txb_ClienteCF.Text != "")
            parametro.Value = this.txb_ClienteCF.Text;
        else
            parametro.Value = System.DBNull.Value;

        parametro.ParameterName = "codiceFiscale";
        parametri.Add(parametro);

        parametro = new Parametro();
        parametro.DbType = DbType.String;
        if (this.txb_ClienteCognome.Text != null) parametro.Value = this.txb_ClienteCognome.Text;
        else parametro.Value = System.DBNull.Value;
        parametro.ParameterName = "cognome";
        parametri.Add(parametro);

        parametro = new Parametro();
        parametro.DbType = DbType.String;
        if (this.txb_ClienteNome.Text != null) parametro.Value = this.txb_ClienteNome.Text;
        else parametro.Value = System.DBNull.Value;
        parametro.ParameterName = "nome";
        parametri.Add(parametro);

        parametro = new Parametro();
        parametro.DbType = DbType.DateTime;
        if (this.txb_da.Text != "")
        {
            dayDa = Convert.ToDateTime(this.txb_da.Text);
            parametro.Value = dayDa;
        }
        else
            parametro.Value = System.DBNull.Value;
        parametro.ParameterName = "dataDa";
        parametri.Add(parametro);

        parametro = new Parametro();
        parametro.DbType = DbType.DateTime;
        if (this.txb_a.Text != "")
        {
            dayA = Convert.ToDateTime(this.txb_a.Text);
            TimeSpan ungiorno = new TimeSpan(1, 0, 0, 0);
            parametro.Value = dayA;
        }
        else
            parametro.Value = System.DBNull.Value;
        parametro.ParameterName = "dataA";
        parametri.Add(parametro);

        parametro = new Parametro();
        parametro.DbType = DbType.Boolean;
        if (this.chk_RicercaStampeProvvisorie.Checked)
            parametro.Value = false;
        else if (this.chk_RicercaStampeDefinitive.Checked)
            parametro.Value = true;
        else
            parametro.Value = System.DBNull.Value;
        parametro.ParameterName = "flagArchiviato";
        parametri.Add(parametro);

        DataTable dtDg = DataAccess.ExecuteDataTableStoredProcedure(DBProvider.SqlServer, "sp_getAllDocumentsByFilters_new", parametri);

        //justOneCustomer
        string lastCustomer = "";
        string customer = "";

        if (dtDg.Rows.Count > 0)
        {
            customer = dtDg.Rows[0]["Cognome"].ToString();
            foreach (DataRow dr in dtDg.Rows)
            {
                lastCustomer = dr["Cognome"].ToString();
                if (lastCustomer != customer)
                {
                    justOneCustomer = false;
                    break;
                }
                else
                {
                    customer = lastCustomer;
                }
            }
        }
    }

    protected void HomePage_Click(object sender, EventArgs e)
    {
        Response.Redirect("RicercaHD.aspx");
    }

    protected void chk_RicercaStampedaRichiedere_CheckedChanged(object sender, EventArgs e)
    {
        if (this.chk_RicercaStampedaRichiedere.Checked)
        {
            if (this.chk_RicercaStampedaRichiedere.Checked)
            {
                if (this.chk_RicercaStampeDefinitive.Checked) this.chk_RicercaStampeDefinitive.Checked = false;
                if (this.chk_RicercaStampeProvvisorie.Checked) this.chk_RicercaStampeProvvisorie.Checked = false;
            }
        }
    }

    private string __;

    public string _
    {
        get { return __; }
        set { __ = value; }
    }
}