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
{
    private DataTable dtDg;
    public static bool b_sortCommand = true;
    public static string ordinamentoGriglia = string.Empty;

    public string codiceFiscale;
    //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 *****

        //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;
                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(datiHDUS.CodiceFiscale);
                //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");

            codiceFiscale = 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");

                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, codiceFiscale);

                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 = codiceFiscale;
                    }
                    this.txb_ClienteNome.Text = cliente.Nome.ToString().Replace("$", "");
                }

                fillDG(codiceFiscale);
                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;
        }
    }


    /// <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();
    }
    //------------------------------------------------------------------------------------------
    public void dg_PageIndex(object source, System.Web.UI.WebControls.DataGridPageChangedEventArgs e)
    {
        codiceFiscale = this.txb_ClienteCF.Text;
        dg.CurrentPageIndex = e.NewPageIndex;
        dg.DataSource = GetData(codiceFiscale, ordinamentoGriglia);
        dg.DataBind();

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

    private void cambiaPagina(int indicePagina)
    {
        codiceFiscale = 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 DataTable GetData(string codFiscale)
    {
        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 (ddl_Modello.SelectedValue != "0")
        {
            parametro = new Parametro();
            parametro.DbType = DbType.Int32;
            parametro.Value = Convert.ToInt32(ddl_Modello.SelectedValue);
            parametro.ParameterName = "tpReport";
            parametri.Add(parametro);
        }

        //// ***** 18/12/2008 Paolo Giovanetti modifiche accesso archivio documenti *****
        //if (ddl_Modello.SelectedValue == "0" && utenteHD_US)
        //{
        //    parametro = new Parametro();
        //    parametro.DbType = DbType.Int32;
        //    parametro.Value = 1;
        //    parametro.ParameterName = "tpReportHD_US";
        //    parametri.Add(parametro);
        //}

        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;
        // ***** fine 18/12/2008 Paolo Giovanetti modifiche accesso archivio documenti *****

        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.Trim().Length > 0)
            if (codFiscale.Contains("@") && txb_ClienteCognome.Text.Contains("-"))
                parametro.Value = (this.txb_ClienteCognome.Text.Split('-'))[0].Trim();
            else
                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.Trim().Length > 0)
            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.Add(ungiorno);
        }
        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);

        parametro = new Parametro();
        parametro.DbType = DbType.Boolean;
        parametro.Value = this.chk_RicercaStampedaRichiedere.Checked;
        parametro.ParameterName = "flagStorico";
        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 = "";
        DataTable dtDg = GetData(codFiscale);
        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 = codiceFiscale;
        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 + ",'" + codiceFiscale + "')";
            }
            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;
            }


            readData(null);
            if (justOneCustomer == true)
            {
                lastUsedCF = dg.Items[0].Cells[12].Text;
                if (codiceFiscale != lastUsedCF && lastUsedCF != string.Empty)
                    codiceFiscale = 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=" + codiceFiscale + "&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;
            }

            readData(null);
            if (justOneCustomer == true)
            {
                lastUsedCF = dg.Items[0].Cells[12].Text;
                if (codiceFiscale != lastUsedCF && lastUsedCF != string.Empty)
                    codiceFiscale = 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=" + codiceFiscale + "&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, codiceFiscale).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)
    {
        string rc = checkTypedData();
        ordinamentoGriglia = string.Empty;
        codiceFiscale = txb_ClienteCF.Text;

        if (rc == "")
        {
            dg.DataSource = null;
            dg.DataBind();
            if (txb_ClienteCF.Text.Length == 11)
                fillDG(Request.QueryString.Get("codcliente"));
            else
                fillDG(txb_ClienteCF.Text);
        }
        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 = "";
        }
    }

    //------------------------------------------------------------------------------------------
    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; }
    }
}