using System;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Generic;


/// <summary>
/// Gestisce il report di proposta con la versione iniziale basata sul file .xml./// 
/// </summary>
public partial class reportPianificazione : System.Web.UI.Page
{
    private Cliente _cliente;
    public string pathNav;
    private int rowId = 1;
    private int cellId = 1;
    private Table mainTable;
    private TableRow row;
    private CTable tbl;
    private string[] rowStyles;
    private string catName = "";
    private int relativeChildNodeIdx;
    public tvElementsPianificazione[] rowElements = new tvElementsPianificazione[300];
    public string[] indiceSezioneAttiva = new string[300];
    public int totNodesPerElement;
    public int totNodesPerElementNoRadioButtons;
    private int rootParentID;
    public int idReport = 7;              //indica il modello (fixed) COMPLETO di QUESTO report da cui costruire la treeview iniziale
    //private string sUtente;
    public string codiceFiscale;
    public static int tpReportPianificazione = 2;        //valore proprietario (fixed) di QUESTO report //DA VALUTARE!!
    public static int idReportModelloPianificazione = 7; //valore proprietario (fixed) di QUESTO report //DA VALUTARE!!
    public string codiceRete;
    public string codicePB;
    public int lastSavedReportId;
    public static string nomeReportPianificazione = "PIANIFICAZIONE";                   //valore proprietario (fixed) di QUESTO report
    public static string nomeReportBasePianificazione = "Pianificazione base";          //valore proprietario (fixed) di QUESTO report 
    public static string nomeReportCompletoPianificazione = "Pianificazione completo";  //valore proprietario (fixed) di QUESTO report 
    public int reportIdToPass;
    public int reportIdToLoadBack = -1;
    public string endOfjob = "0";
    private string token;
    private string nomeReportPerLabel;
    private string descrizioneReportPerLabel;
    public string ambiente;

    public string[] sectionIDs;
    public int idCounter;
    public string lastReportPrinted;
    public string nomeInizialeReport;
    public string descrizioneInizialeReport;
    public string baseCompleto;
    private bool reportNominativo = false;


    protected void Page_Load(object sender, EventArgs e)
    {
        this.btn_Stampa.Attributes.Add("onclick", "DisableButtons(true);" + ClientScript.GetPostBackEventReference(btn_Stampa, null));

        token = Request.QueryString.Get("token");
        codiceRete = Request.QueryString.Get("tipoRete");
        codicePB = Request.QueryString.Get("codPB");
        ambiente = Request.QueryString.Get("ambiente");
        lastReportPrinted = Request.QueryString.Get("lastReportPrinted");
        nomeInizialeReport = Request.QueryString.Get("nomeInizialeReport");
        descrizioneInizialeReport = Request.QueryString.Get("descrizioneInizialeReport");
        baseCompleto = Request.QueryString.Get("baseCompleto");
        codiceFiscale = Request.QueryString.Get("codCliente");
        pathNav = Request.QueryString.Get("pathNav");
        string loadingReport = Request.QueryString.Get("idReportToLoad");

        _cliente = Cliente.getCliente(codiceRete + codicePB, codiceFiscale);

        tbl = new CTable();
        tbl.LoadDati(codiceFiscale, codicePB, codiceRete);

        this.lbl_message.Text = "";

        if (!Page.IsPostBack)
        {
            #region Nuova gestione privacy

            if (_cliente.SottoscrizioneContrattoSei)
            {
                rbl_Privacy.Items[0].Selected = true;
                rbl_Privacy.Items[0].Enabled = true;
                rbl_Privacy.Items[1].Enabled = true;
            }
            else
            {
                rbl_Privacy.Items[1].Selected = true;
                rbl_Privacy.Items[0].Enabled = false;
                this.lbl_Privacy.Visible = true;
                lbl_Privacy.Text = "La reportistica nominativa pu� essere stampata per i clienti che hanno sottoscritto la consulenza evoluta SEI";
            }

            #endregion

            fillModelli();

            if (loadingReport != null)
            {
                if (loadingReport == "loadBASE")
                {
                    rbl_scelte.Items[0].Selected = true;
                    reportIdToLoadBack = getIdReportBASE_ByReportName();
                }
                else reportIdToLoadBack = Convert.ToInt32(loadingReport);
            }

            if (reportIdToLoadBack == -1) //vuol dire che devo caricare l'ultimo report da modello "salvato"
            {
                reportIdToLoadBack = loadLastSavedUserModel(); //da attivare x sapere quale modello e' stato usato per ultimo da quell'operatore x quel cliente
                reportIdToPass = reportIdToLoadBack;
            }
        }

        string reportName = "";
        if (reportIdToLoadBack != -1)
        {
            reportName = getReportName_ByReportID(reportIdToLoadBack);
        }
        if (reportName != "")
        {
            this.lbl_message.ForeColor = System.Drawing.Color.Black;
            //this.lbl_message.Text = "Nome del REPORT corrente in uso: " + reportName;
            this.lbl_message.Text = "";

            if (reportName == nomeReportBasePianificazione) this.rbl_scelte.Items[0].Selected = true;
            else if (reportName == nomeReportCompletoPianificazione) this.rbl_scelte.Items[1].Selected = true;


            if (nomeReportPerLabel != "Pianificazione base" && nomeReportPerLabel != "Pianificazione completo")
            {
                this.txb_nomeModello.Text = nomeReportPerLabel;
                this.txb_descrizione.Text = descrizioneReportPerLabel;
            }
            //this.txb_descrizione.Text = descrizioneReportPerLabel;
            //this.txb_nomeModello.Text = nomeReportPerLabel;
        }

        initReport();

        if (!Page.IsPostBack)
        {
            if (reportIdToLoadBack > 0 && lastReportPrinted == null)
            {
                this.lbl_message.ForeColor = System.Drawing.Color.Black;
                loadChoosenProfileNew(reportIdToLoadBack, null);

                if (nomeReportPerLabel != "Pianificazione base" && nomeReportPerLabel != "Pianificazione completo")
                {
                    this.txb_nomeModello.Text = nomeReportPerLabel;
                    this.txb_descrizione.Text = descrizioneReportPerLabel;
                }

                if (nomeInizialeReport != null)
                {
                    selezionaModelloNellaCombo(nomeInizialeReport);
                }
                else if (nomeReportPerLabel != null) selezionaModelloNellaCombo(nomeReportPerLabel);

                this.lbl_message.Text = "";
                setControlsOnTV();
            }
            else if (lastReportPrinted != "" && lastReportPrinted != null)
            {
                this.lbl_message.ForeColor = System.Drawing.Color.Black;
                loadChoosenProfileNew(Convert.ToInt32(lastReportPrinted), null);
                this.txb_descrizione.Text = descrizioneInizialeReport;
                this.txb_nomeModello.Text = nomeInizialeReport;

                if (baseCompleto == "1") rbl_scelte.Items[0].Selected = true;
                else if (baseCompleto == "2") rbl_scelte.Items[1].Selected = true;

                if (nomeInizialeReport != "" && nomeInizialeReport != null) selezionaModelloNellaCombo(nomeInizialeReport);

                this.lbl_message.Text = "";
                setControlsOnTV();
            }
            else
            {
                //carico il report di base
                //bool rc = getReportSectionIds_ByName("Diagnosi base");
                this.lbl_message.ForeColor = System.Drawing.Color.Black;
                bool rc = getReportSectionIds_ByNameNew("Pianificazione base");
                rbl_scelte.Items[0].Selected = true;
                this.lbl_message.Text = "";
                setControlsOnTV();
            }
        }

    }
    //=====================================================================
    private void selezionaModelloNellaCombo(string nomeReportPerLabel)
    {
        int x = 0;
        if (nomeReportPerLabel != null)
        {
            foreach (ListItem itm in ddl_Modello.Items)
            {
                if (nomeReportPerLabel.Equals(itm.Text))
                {
                    this.ddl_Modello.Enabled = true;
                    //ddl_Modello.SelectedIndex = itm.Text;
                    ddl_Modello.SelectedIndex = x;

                    rbl_scelte.Items[2].Selected = true;

                    break;
                }
                x++;
            }
        }
    }
    //=======================================================
    private int getIdReportBASE_ByReportName()
    {
        int rc = 0;
        List<Parametro> parametri = new List<Parametro>();
        Parametro parametro = new Parametro();
        parametro.DbType = DbType.String;
        parametro.Value = nomeReportBasePianificazione;
        parametro.ParameterName = "pReportName";
        parametri.Add(parametro);
        DataTable dt = DataAccess.ExecuteDataTableStoredProcedure(DBProvider.SqlServer, "sp_getReportID_ByReportName", parametri);
        if (dt.Rows.Count > 0) rc = (int)dt.Rows[0]["IdReport"];
        return rc;
    }
    //=======================================================
    private string getReportName_ByReportID(int idRep)
    {
        string rc = "";
        List<Parametro> parametri = new List<Parametro>();
        Parametro parametro = new Parametro();
        parametro.DbType = DbType.Int32;
        parametro.Value = idRep;
        parametro.ParameterName = "pIdReport";
        parametri.Add(parametro);
        DataTable dt = DataAccess.ExecuteDataTableStoredProcedure(DBProvider.SqlServer, "sp_getReportName_ByReportID", parametri);
        if (dt.Rows.Count > 0)
        {
            rc = dt.Rows[0]["Nome"].ToString();
            nomeReportPerLabel = dt.Rows[0]["nome"].ToString();
            descrizioneReportPerLabel = dt.Rows[0]["descrizione"].ToString();
        }
        return rc;
    }

    private int loadLastSavedUserModel()
    {
        int rc = 0;
        int idCliente = _cliente.IdCliente_SEIReport;
        List<Parametro> parametri = new List<Parametro>();
        Parametro parametro = new Parametro();
        parametro.DbType = DbType.Int32;
        parametro.Value = idReportModelloPianificazione;
        parametro.ParameterName = "pIdReportModello";
        parametri.Add(parametro);

        parametro = new Parametro();
        parametro.DbType = DbType.String;
        if ((_cliente.CodiceRete + _cliente.CodicePB).Length > 0)
            parametro.Value = _cliente.CodiceRete + _cliente.CodicePB;
        else
            parametro.Value = System.DBNull.Value;
        parametro.ParameterName = "pUtente";
        parametri.Add(parametro);

        parametro = new Parametro();
        parametro.DbType = DbType.Int32;
        parametro.Value = tpReportPianificazione;
        parametro.ParameterName = "pTpReport";
        parametri.Add(parametro);

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

        DataTable dt = DataAccess.ExecuteDataTableStoredProcedure(DBProvider.SqlServer, "sp_getLastSavedUserModelNew", parametri);
        if (dt.Rows.Count > 0)
        {
            rc = Convert.ToInt32(dt.Rows[0]["IdReport"].ToString());
            nomeReportPerLabel = dt.Rows[0]["nome"].ToString();
            descrizioneReportPerLabel = dt.Rows[0]["descrizione"].ToString();
        }

        return rc;
    }

    private void fillModelli()
    {
        this.ddl_Modello.Items.Clear();
        List<Parametro> parametri = new List<Parametro>();
        Parametro parametro = new Parametro();
        parametro.ParameterName = "pIdReportModello";
        parametro.Value = idReportModelloPianificazione;
        parametro.DbType = DbType.Int32;
        parametri.Add(parametro);

        parametro = new Parametro();
        parametro.ParameterName = "pUtente";
        if ((_cliente.CodiceRete + _cliente.CodicePB).Length > 0)
            parametro.Value = _cliente.CodiceRete + _cliente.CodicePB;
        else
            parametro.Value = System.DBNull.Value;
        parametro.DbType = DbType.String;
        parametri.Add(parametro);

        DataTable dt = DataAccess.ExecuteDataTableStoredProcedure(DBProvider.SqlServer, "sp_getReport_ByUtenteAndModello", parametri);

        ddl_Modello.Items.Add("Selezione Modelli");

        if (dt.Rows.Count > 0)
        {

            foreach (DataRow dr in dt.Rows)
            {
                string nome = dr["Nome"].ToString();
                if (nome.IndexOf("LAST USED CONFIG") == -1)
                {
                    ListItem li = new ListItem(dr["Nome"].ToString(), dr["IdReport"].ToString());
                    this.ddl_Modello.Items.Add(li);
                }
            }
            //string nome = dt.Rows[0]["Nome"].ToString();
            //if (nome.IndexOf("LAST USED CONFIG") == -1)
            //{
            //    ListItem li = new ListItem(dt.Rows[0]["Nome"].ToString(), dt.Rows[0]["IdReport"].ToString());
            //    this.ddl_Modello.Items.Add(li);
            //}
        }
    }
    //==================================================
    private void PopulateNodes(DataTable dt, int currentDepthLevel)
    {
        string[][] rowAttributes;
        string[][] cellAttributes;
        string completeExpandCommand = "";
        string completeCheckBoxCommand = "";
        int cellsPerRow = 0;
        int maxCells = 7;                   //numero massimo di colonne della tv
        foreach (DataRow dr in dt.Rows)
        {
            //valori delle righe da agganciare alla table
            int parentid = Convert.ToInt32(dr["IdSezione"]);
            int isMandatory = 0;
            if (dr["IsMandatory"] != System.DBNull.Value)
            {
                isMandatory = Convert.ToInt32(dr["IsMandatory"]);
            }

            int isBold = 0;
            if (dr["IsBold"] != System.DBNull.Value)
            {
                isBold = Convert.ToInt32(dr["IsBold"]);
            }

            int numberOfChildren = Convert.ToInt32((dr["childnodecount"]));
            string idPadre = dr["IdSezionePadre"].ToString();

            string descrizione = dr["Descrizione"].ToString();
            string tpSezione = dr["TpSezione"].ToString();
            string nomeControlloGruppo = dr["NomeControlloGruppo"].ToString();
            string isDefault = dr["isDefault"].ToString(); //indica se il radio button e' checked o meno.
            if (isDefault == "") isDefault = "false";
            int idSezione = Convert.ToInt32(dr["idSezione"]);
            string internalSectionCode = dr["internalSectionCode"].ToString();

            ////patch per disabilitazione PRIVACY
            //if (this.rbl_Privacy.Items[0].Selected == true) privacy = "1";
            //else privacy = "0";
            //dt.Columns["IdReport"].DefaultValue = reportIdToPass;

            //if (internalSectionCode == "ESNOCL" && privacy == "0")
            //{
            //    isMandatory = 1;
            //}
            //if (internalSectionCode == "COINGL" && privacy == "0")
            //{
            //    isMandatory = 1;
            //}
            ////end of patch

            //memorizzo i dati del controllo "chiave" della n-esima riga
            rowElements[rowId - 1].descrizione = descrizione;
            rowElements[rowId - 1].tipoControllo = tpSezione;
            rowElements[rowId - 1].idSezione = idSezione;

            if (numberOfChildren > 0) //se ha dei figli...
            {
                rowAttributes = tbl.setRowAttributes(null, null);

                //solo i livelli "root" devono essere espandibili epertanto solo per questi attivo la routine che crea il javascript per aprire e chiudere.
                if (idPadre == "")
                {
                    relativeChildNodeIdx = 0;
                    rootParentID = parentid;
                    completeExpandCommand = prepareOpenCloseJavascriptCommand(parentid);
                    row = tbl.addRowToTable(mainTable, "r" + rowId.ToString(), rowStyles[0], rowAttributes);
                }
                else  //aggiungo la categoria
                {
                    catName = "cat" + rootParentID.ToString() + relativeChildNodeIdx++;
                    row = tbl.addRowToTable(mainTable, catName, rowStyles[1], rowAttributes);
                }

                //aggiungo celle vuote se serve per l'allineamento
                for (int p = 1; p < currentDepthLevel; p++)
                {
                    cellAttributes = tbl.setCellAttributes("empty", "0", null);
                    tbl.addCellToRowThenToTable(mainTable, row, "c" + rowId.ToString() + cellId++.ToString(), null, cellAttributes, null, null, null, null, false, 0, null, 0, 0);
                    cellsPerRow++;
                }

                //un oggetto "root" ha SEMPRE il checkbox
                //if (idPadre == "")                        //SE vuoi che SOLO i "root" comandino le checkbox figli scommenta questa istruzione...
                //{
                completeCheckBoxCommand = prepareCheckBoxJavascriptCommand(parentid, idSezione);
                //}
                cellAttributes = tbl.setCellAttributes("parentCheckbox", "0", completeCheckBoxCommand);

                //rowElements[rowId - 1].nomeControllo = "cxb" + cxbId.ToString();
                rowElements[rowId - 1].nomeControllo = "cxb" + idSezione.ToString();

                //string ctrlName = "cxb" + cxbId++.ToString();
                string ctrlName = "cxb" + idSezione.ToString();

                tbl.addCellToRowThenToTable(mainTable, row, "c" + rowId.ToString() + cellId++.ToString(), null, cellAttributes, "checkbox", null, ctrlName, ctrlName, Convert.ToBoolean(isDefault), isMandatory, internalSectionCode, tpReportPianificazione, 0);
                cellsPerRow++;
            }
            else
            {
                //la categoria e' una label che serve in fase di apertura/chiusura
                catName = "cat" + rootParentID.ToString() + relativeChildNodeIdx++;

                rowAttributes = tbl.setRowAttributes("expandibleRow", catName);
                row = tbl.addRowToTable(mainTable, null, rowStyles[1], rowAttributes);
                completeCheckBoxCommand = prepareCheckBoxJavascriptCommand(parentid, idSezione);

                ////questa cella blank "rimpiazza" l'assenza della casella col "+"
                //cellAttributes = tbl.setCellAttributes("empty", "0", null);
                //tbl.addCellToRowThenToTable(mainTable, row, "c" + rowId.ToString() + cellId++.ToString(), null, cellAttributes, null, null, null, null, false, 0, null, 0, 0);
                //cellsPerRow++;

                if (currentDepthLevel == 1)
                {
                    cellAttributes = tbl.setCellAttributes("empty", "0", null);
                    tbl.addCellToRowThenToTable(mainTable, row, "c" + rowId.ToString() + cellId++.ToString(), null, cellAttributes, null, null, null, null, false, 0, null, 0, 0);
                    cellsPerRow++;
                }
                //aggiungo celle vuote se serve per l'allineamento
                for (int p = 1; p < currentDepthLevel; p++)
                {
                    cellAttributes = tbl.setCellAttributes("empty", "0", null);
                    tbl.addCellToRowThenToTable(mainTable, row, "c" + rowId.ToString() + cellId++.ToString(), null, cellAttributes, null, null, null, null, false, 0, null, 0, 0);
                    cellsPerRow++;
                }

                //aggiungo celle specializzate tipo checkboxes o radiobuttons
                switch (tpSezione)
                {
                    case "1"://checkbox
                        completeCheckBoxCommand = prepareCheckBoxJavascriptCommand(parentid, idSezione);
                        cellAttributes = tbl.setCellAttributes("childCheckbox", "0", completeCheckBoxCommand);
                        //cellAttributes = tbl.setCellAttributes("childCheckbox", "0", null);
                        //rowElements[rowId - 1].nomeControllo = "cxb" + cxbId.ToString();
                        rowElements[rowId - 1].nomeControllo = "cxb" + idSezione.ToString();
                        //string ctrlName = "cxb" + cxbId++.ToString();
                        string ctrlName = "cxb" + idSezione.ToString();
                        tbl.addCellToRowThenToTable(mainTable, row, "c" + rowId.ToString() + cellId++.ToString(), null, cellAttributes, "checkbox", null, ctrlName, ctrlName, Convert.ToBoolean(isDefault), isMandatory, internalSectionCode, tpReportPianificazione, 0);
                        cellsPerRow++;
                        break;
                    case "2"://radiobutton
                        bool isChecked = false;
                        if (isDefault == "1") isChecked = true;
                        cellAttributes = tbl.setCellAttributes("childRadioButton", "0", null);
                        //rowElements[rowId - 1].nomeControllo = "rb" + rbId.ToString();
                        rowElements[rowId - 1].nomeControllo = "rb" + idSezione.ToString();
                        //tbl.addCellToRowThenToTable(mainTable, row, "c" + rowId.ToString() + cellId++.ToString(), null, cellAttributes, "radiobutton", null, nomeControlloGruppo, "rb" + rbId++.ToString(), isChecked, 0, internalSectionCode, tpReportPianificazione);
                        tbl.addCellToRowThenToTable(mainTable, row, "c" + rowId.ToString() + cellId++.ToString(), null, cellAttributes, "radiobutton", null, nomeControlloGruppo, "rb" + idSezione.ToString(), isChecked, 0, internalSectionCode, tpReportPianificazione, 0);
                        cellsPerRow++;
                        break;
                }
            }
            cellsPerRow++;
            int colspan = maxCells - cellsPerRow;

            //aggiungo la descrizione che e' sempre l'ultima cella
            //se e' una label metto lo stile corretto. comuunque qui si puo' customizzare la cella
            string cssStyle = null;
            if (tpSezione == "3") cssStyle = rowStyles[3];
            else if (tpSezione == "0") cssStyle = rowStyles[0];
            //else if (tpSezione == "1") cssStyle = rowStyles[1];
            else cssStyle = rowStyles[3];

            cellAttributes = tbl.setCellAttributes("text", colspan.ToString(), null);
            tbl.addCellToRowThenToTable(mainTable, row, "c" + rowId.ToString() + cellId++.ToString(), descrizione, cellAttributes, "testo", cssStyle, null, null, false, 0, internalSectionCode, tpReportPianificazione, isBold);

            if (idPadre == "") //solo se e' un oggetto della root va espanso...
            {
                cellAttributes = tbl.setCellAttributes("expandible", "0", completeExpandCommand);
                tbl.addCellToRowThenToTable(mainTable, row, "c" + rowId.ToString() + cellId++.ToString(), "&nbsp;-", cellAttributes, null, null, null, null, false, 0, null, 0, 0);
                cellsPerRow++;
            }
            else //inserisco cella vuota
            {
                cellAttributes = tbl.setCellAttributes("empty", "0", null);
                tbl.addCellToRowThenToTable(mainTable, row, "c" + rowId.ToString() + cellId++.ToString(), null, cellAttributes, null, null, null, null, false, 0, null, 0, 0);
                cellsPerRow++;
            }


            //fine riga: reset delle variabili relative alla riga
            cellsPerRow = 0;
            rowId++;
            cellId = 1;

            //routine ricorsiva che esamina i figli dell'n-esimo padre
            if (numberOfChildren > 0)  //dati dei figli...
            {
                PopulateSubLevel(parentid, currentDepthLevel);
            }
        }
    }
    //-------------------------------------------------------------------------
    private string prepareCheckBoxJavascriptCommand(int parentid, int idSezione)
    {
        sectionIDs = null;
        idCounter = 0;
        sectionIDs = new string[100];

        countNodes(parentid);

        string command;
        // per ogni nuova riga che ha figli devo preparare il comando relativo alla gestione dei checkbox

        int k = idSezione;

        command = "javascript:ActivateCheck(cxb" + k.ToString() + ","; //inserisco il padre dei checkbox
        k++;

        for (int j = 0; j < totNodesPerElementNoRadioButtons; j++)
        {
            //command += "cxb" + j.ToString() + ",";
            command += "cxb" + sectionIDs[j] + ",";
        }

        command = command.Remove(command.LastIndexOf(","));
        command += ");";

        totNodesPerElement = 0;
        totNodesPerElementNoRadioButtons = 0;
        return command;
    }
    //------------------------------------------------------------------------
    private string prepareOpenCloseJavascriptCommand(int parentid)
    {
        sectionIDs = null;
        idCounter = 0;
        sectionIDs = new string[100];

        countNodes(parentid);

        string command;
        // per ogni nuova riga che ha figli devo preparare il comando di apertura/chiusura nodi
        // quindi devo sapere quanti nodi "figli" ha un dato padre...
        command = "javascript:";
        for (int k = 0; k < totNodesPerElement; k++)
        {
            command += "EspandiRacchiudi(this,'cat" + rootParentID.ToString() + k.ToString() + "');";
        }
        totNodesPerElement = 0;
        totNodesPerElementNoRadioButtons = 0;
        return command;
    }
    //-------------------------------------------------------------------------
    private void countNodes(int parentID)
    {

        List<Parametro> parametri = new List<Parametro>();
        Parametro parametro = new Parametro();
        parametro.DbType = DbType.Int32;
        parametro.Value = parentID;
        parametro.ParameterName = "pID";
        parametri.Add(parametro);

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

        DataTable dt = DataAccess.ExecuteDataTableStoredProcedure(DBProvider.SqlServer, "sp_getTVElements_ByParentID", parametri);

        totNodesPerElement += dt.Rows.Count;
        totNodesPerElementNoRadioButtons += dt.Rows.Count;

        foreach (DataRow dr in dt.Rows)
        {
            //solo i radiobuttons hanno valorizzato questo campo e devo escludere anche le labels
            if (dr["NomeControlloGruppo"].ToString() != "" || dr["TpSezione"].ToString() == "3")
            {
                totNodesPerElementNoRadioButtons--;
            }

            if (dr["TpSezione"].ToString() != "3" && dr["TpSezione"].ToString() != "2")
            {
                sectionIDs[idCounter++] = dr["IdSezione"].ToString();
            }

            int numberOfChildren = Convert.ToInt32((dr["childnodecount"]));

            if (numberOfChildren > 0)
            {
                int innerPID = Convert.ToInt32(dr["IdSezione"]);
                countNodes(innerPID);
            }
        }
    }
    //------------------------------------------------------------------------
    private void PopulateSubLevel(int parentid, int currentDepthLevel)
    {
        currentDepthLevel++;  //indica il livello di profondita' relativo del nodo corrente

        List<Parametro> parametri = new List<Parametro>();
        Parametro parametro = new Parametro();
        parametro.DbType = DbType.Int32;
        parametro.Value = parentid;
        parametro.ParameterName = "pID";
        parametri.Add(parametro);

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

        DataTable dt = DataAccess.ExecuteDataTableStoredProcedure(DBProvider.SqlServer, "sp_getTVElements_ByParentID", parametri);


        PopulateNodes(dt, currentDepthLevel);

    }
    //==================================================
    private void initReport()
    {
        int maxStyles = 10;      //indica il massimo numero di stili (CssClass) associabili alla singola riga (row)
        string[][] tableAttributes;

        //row styles
        rowStyles = new string[maxStyles];
        rowStyles[0] = "stateTitle";
        rowStyles[1] = "lblSchede";
        rowStyles[2] = "lblLabels";
        rowStyles[3] = "lblTestoDescrizione";

        tbl = new CTable();   //THE TABLE object 

        if (codiceFiscale == null || codiceFiscale == "")
        {
            HttpCookie ck_codiceFiscale = new HttpCookie("codiceFiscale");
            ck_codiceFiscale = System.Web.HttpContext.Current.Request.Cookies["codiceFiscale"];
            if (ck_codiceFiscale != null) codiceFiscale = ck_codiceFiscale.Value.ToString();
        }

        if (token == null || token == "")
        {
            HttpCookie ck_token = new HttpCookie("token");
            ck_token = System.Web.HttpContext.Current.Request.Cookies["token"];

            if (ck_token != null) token = ck_token.Value.ToString();
        }

        //set variabili per abilitare pulsanti
        //tbl.Pianif_CustomerIsProspect = tbl.Pianificazione_CustomerIsProspect(codiceFiscale, codiceRete + codicePB);
        //tbl.Pianif_CustomerIsProspectAndHasNoWalletByOtherInstitutes = tbl.Pianificazione_CustomerIsProspectAndHasNoWalletByOtherInstitutes(codiceFiscale, codiceRete + codicePB);
        tbl.LoadDati(codiceFiscale, codicePB, codiceRete);
        tbl.Pianif_CustomerHasNoPianificazione = tbl.CustomerHasNoPianificazione();
        tbl.Pianif_CustomerHasNoRischio = tbl.Pianificazione_CustomerHasNoRischio(codiceFiscale, codicePB, codiceRete, token);
        tbl.Pianif_CustomerHasNoWalletAtAll = tbl.Pianificazione_CustomerHasNoWalletAtAll();
        tbl.Pianif_CustomerHasNoBFWallet = tbl.Pianificazione_CustomerHasNoBFWallet();
        tbl.Pianif_CustomerHasNoPiramideModello = tbl.Pianificazione_CustomerHasNoPiramideModello();
        tbl.Pianif_CustomerHaSoloCCPressoBF = tbl.Pianificazione_CustomerHaSoloCCPressoBF();
        tbl.Pianif_CustomerHaPianificazioneRISERVA = tbl.Pianificazione_CustomerHaPianificazioneRISERVA();
        tbl.Pianif_CustomerHaPianificazioneINVESTIMENTO = tbl.Pianificazione_CustomerHaPianificazioneINVESTIMENTO();

        reportNominativo = this.rbl_Privacy.Items[0].Selected ? true : false;

        tableAttributes = tbl.setTableAttributes();
        mainTable = tbl.createTable("mainTable", tableAttributes);

        List<Parametro> parametri = new List<Parametro>();
        Parametro parametro = new Parametro();
        parametro.DbType = DbType.Int32;
        parametro.Value = idReport;
        parametro.ParameterName = "idReport";
        parametri.Add(parametro);

        DataTable dt = DataAccess.ExecuteDataTableStoredProcedure(DBProvider.SqlServer, "sp_getTVElements", parametri);

        int currentDepthLevel = 1;
        PopulateNodes(dt, currentDepthLevel);

        Page.Controls.Add(mainTable);
        pnl_tv.Controls.Add(mainTable);
    }
    //==================================================
    protected void btn_Salva_Click(object sender, EventArgs e)
    {
        int idReport;
        bool rc = false;

        if (txb_nomeModello.Text == "")
        {
            this.lbl_message.ForeColor = System.Drawing.Color.Red;
            this.lbl_message.Text = "Attenzione. Immettere il nome del modello da salvare.";
        }
        else if (txb_nomeModello.Text.ToUpper() == "BASE" || txb_nomeModello.Text.ToUpper() == "COMPLETO")
        {
            this.lbl_message.ForeColor = System.Drawing.Color.Red;
            this.lbl_message.Text = "Attenzione. Non � possibile salvare un modello con questo nome, cambiare nome e riprovare con il salvataggio.";
        }
        else
        {
            string nomeModello = txb_nomeModello.Text;
            nomeModello = nomeModello.Trim();

            int idCliente = _cliente.IdCliente_SEIReport;
            idReport = scriviNuovoModelloReportIntoDB(nomeModello, idCliente);

            //aggiungo il cookie con ReportToPass 
            if (idReport != 0)
            {
                HttpCookie ck_reportIdToPass = new HttpCookie("reportIdToPass");
                ck_reportIdToPass.Value = idReport.ToString();
                Response.Cookies.Add(ck_reportIdToPass);
            }

            fillModelli();

            //deletePreviousLastConfigRecordsFromDB(idReport);

            if (idReport != -1)
            {
                CheckBox crtlCheckBox;
                RadioButton ctrlRadio;
                //int idx = 1;

                foreach (tvElementsPianificazione elem in rowElements)
                {
                    if (elem.descrizione == null) break;

                    if (elem.tipoControllo == "1" || elem.tipoControllo == "0") //checkbox
                    {
                        crtlCheckBox = (CheckBox)this.mainTable.FindControl(elem.nomeControllo);
                        if (crtlCheckBox.Checked == true)
                            rc = scriviDettaglioSezioniDelReportIntoDB(elem.idSezione, idReport);
                        if (rc) break;
                        //else idx++;
                    }
                    else if (elem.tipoControllo == "2")
                    {
                        ctrlRadio = (RadioButton)this.mainForm.FindControl(elem.nomeControllo);
                        if (ctrlRadio.Checked == true)
                            rc = scriviDettaglioSezioniDelReportIntoDB(elem.idSezione, idReport);
                        if (rc) break;
                        //else idx++;
                    }
                    else if (elem.tipoControllo == "3") //labels
                    {
                        //idx++;
                    }
                }
            }
            else this.lbl_message.Text = "Errore nel salvataggio del modello " + nomeModello + ".";

            if (!rc)
            {
                this.lbl_message.ForeColor = System.Drawing.Color.Black;
                this.lbl_message.Text = "Il Modello " + nomeModello + " e' stato salvato correttamente.";
            }
            else this.lbl_message.Text = "Errore nel salvataggio del modello " + nomeModello + ".";

            selezionaModelloNellaCombo(nomeModello);
        }
    }
    //===========================================================================
    private bool scriviDettaglioSezioniDelReportIntoDB(int idSezione, int idReport)
    {
        List<Parametro> parametri = new List<Parametro>();
        Parametro parametro = new Parametro();
        parametro.DbType = DbType.Int32;
        parametro.Value = idSezione;
        parametro.ParameterName = "idSezione";
        parametri.Add(parametro);

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

        parametro = new Parametro();
        parametro.DbType = DbType.String;
        parametro.Value = _cliente.CodiceRete + _cliente.CodicePB;
        parametro.ParameterName = "utente";
        parametri.Add(parametro);

        int rc = DataAccess.ExecuteNonQueryStoredProcedure(DBProvider.SqlServer, "sp_insertCustomSezioniReport", parametri);

        return false;
    }
    //========================================================
    private int scriviNuovoModelloReportIntoDB(string reportName, int idCliente)
    {
        int rc = -1;

        List<Parametro> parametri = new List<Parametro>();

        Parametro parametro = new Parametro();
        parametro.DbType = DbType.String;
        parametro.Value = reportName;
        parametro.ParameterName = "nome";
        parametri.Add(parametro);

        parametro = new Parametro();
        parametro.DbType = DbType.String;
        parametro.Value = this.txb_descrizione.Text;
        parametro.ParameterName = "descrizione";
        parametri.Add(parametro);

        parametro = new Parametro();
        parametro.DbType = DbType.Boolean;
        parametro.Value = false;
        parametro.ParameterName = "flgModello";
        parametri.Add(parametro);

        parametro = new Parametro();
        parametro.DbType = DbType.Int16;
        parametro.Value = idReportModelloPianificazione;
        parametro.ParameterName = "idReportModello";
        parametri.Add(parametro);

        parametro = new Parametro();
        parametro.DbType = DbType.Int16;
        parametro.Value = tpReportPianificazione;
        parametro.ParameterName = "tpReport";
        parametri.Add(parametro);

        parametro = new Parametro();
        parametro.DbType = DbType.String;
        parametro.Value = _cliente.CodiceRete + _cliente.CodicePB;
        parametro.ParameterName = "utente";
        parametri.Add(parametro);

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

        parametro = new Parametro();
        parametro.DbType = DbType.Int16;
        parametro.Value = rbl_Privacy.SelectedIndex;
        parametro.ParameterName = "Privacy";
        parametri.Add(parametro);

        rc = DataAccess.ExecuteNonQueryStoredProcedure(DBProvider.SqlServer, "sp_insertNewReportModelNew", parametri);

        return rc;
    }

    protected void btn_GestioneModelli_Click(object sender, EventArgs e)
    {

        if (reportIdToPass == 0)
        {
            HttpCookie ck_reportIdToPass = new HttpCookie("reportIdToPass");
            ck_reportIdToPass = System.Web.HttpContext.Current.Request.Cookies["reportIdToPass"];
            if (ck_reportIdToPass != null)
            {
                reportIdToPass = Convert.ToInt32(ck_reportIdToPass.Value);
                Response.Cookies.Add(ck_reportIdToPass);
            }
        }
        nomeInizialeReport = this.txb_nomeModello.Text;
        descrizioneInizialeReport = this.txb_descrizione.Text;
        if (reportIdToPass == 0) reportIdToPass = getIdReport_ByReportName(this.ddl_Modello.SelectedItem.Text);

        reportNominativo = this.rbl_Privacy.Items[0].Selected ? true : false;

        Response.Redirect("archivioModelli.aspx?codCliente=" + codiceFiscale + "&tipoRete=" + codiceRete + "&codPB=" + codicePB + "&pathNav=" + pathNav + "&tpReport=" + tpReportPianificazione + "&utente=" + _cliente.CodiceRete + _cliente.CodicePB + "&caller=" + nomeReportPianificazione + "&idReport=" + reportIdToPass + "&nomeInizialeReport=" + nomeInizialeReport + "&descrizioneInizialeReport=" + descrizioneInizialeReport + "&checkPrivacy=" + reportNominativo + "&token=" + token);
    }
    //=======================================================
    private int getIdReport_ByReportName(string name)
    {
        int rc = 0;
        List<Parametro> parametri = new List<Parametro>();
        Parametro parametro = new Parametro();
        parametro.DbType = DbType.String;
        parametro.Value = name;
        parametro.ParameterName = "pReportName";
        parametri.Add(parametro);
        DataTable dt = DataAccess.ExecuteDataTableStoredProcedure(DBProvider.SqlServer, "sp_getReportID_ByReportName", parametri);
        if (dt.Rows.Count > 0) rc = (int)dt.Rows[0]["IdReport"];
        return rc;
    }
    //==========================================================
    protected void rbl_scelte_SelectedIndexChanged(object sender, EventArgs e)
    {
        this.txb_nomeModello.Text = "";
        this.txb_descrizione.Text = "";

        if (rbl_scelte.SelectedValue == "")
        {
            ddl_Modello.Enabled = true;
        }
        else
        {
            ddl_Modello.Enabled = false;
            ddl_Modello.SelectedIndex = 0;
        }

        bool rc;
        switch (rbl_scelte.SelectedItem.Value)
        {
            case "Completo":
                //load profilo "completo" x quel report (uno x tutti)
                rc = getReportSectionIds_ByNameNew("Pianificazione completo");
                if (!rc)
                {
                    setControlsOnTV();
                    this.lbl_message.ForeColor = System.Drawing.Color.Black;
                    this.lbl_message.Text = "";
                }
                else this.lbl_message.Text = "Attenzione. Errori nel caricamento del modello COMPLETO.";
                break;
            case "Base":
                //load profilo "base" x quel report (uno x tutti)
                rc = getReportSectionIds_ByNameNew("Pianificazione base");
                if (!rc)
                {
                    setControlsOnTV();
                    this.lbl_message.ForeColor = System.Drawing.Color.Black;
                    this.lbl_message.Text = "";
                }
                else this.lbl_message.Text = "Attenzione. Errori nel caricamento del modello BASE.";
                break;
        }
    }
    //==========================================================
    private bool getReportSectionIds_ByNameNew(string nomeReport)
    {
        bool rc = false;
        int repId = 0;
        if (nomeReport == "Pianificazione completo") repId = 7;
        else if (nomeReport == "Pianificazione base") repId = 8;

        List<Parametro> parametri = new List<Parametro>();

        Parametro parametro = new Parametro();
        parametro.DbType = DbType.Int32;
        parametro.Value = repId;
        parametro.ParameterName = "idReport";
        parametri.Add(parametro);

        DataTable dt = DataAccess.ExecuteDataTableStoredProcedure(DBProvider.SqlServer, "sp_getSezioniReport_ByIdReportNew", parametri);

        int idx = 0;

        reportIdToPass = Convert.ToInt32(dt.Rows[0]["idReport"]);
        //aggiungo il cookie con ReportToPass 
        if (reportIdToPass != 0)
        {
            HttpCookie ck_reportIdToPass = new HttpCookie("reportIdToPass");
            ck_reportIdToPass.Value = reportIdToPass.ToString();
            Response.Cookies.Add(ck_reportIdToPass);
        }

        ////patch per la privacy
        //if (this.rbl_Privacy.Items[0].Selected == true) privacy = "1";
        //else privacy = "0";
        //dt.Columns["IdReport"].DefaultValue = reportIdToPass;
        //if (privacy == "0") //aggiungo ESNOCL
        //{
        //    DataRow[] esnocl = dt.Select("internalSectionCode = 'ESNOCL'");
        //    DataRow[] coingl = dt.Select("internalSectionCode = 'COINGL'");

        //    if (esnocl.Length == 0) //se non c'e' aggiungo
        //    {
        //        DataRow esnoclRow = dt.NewRow();

        //        esnoclRow["internalSectionCode"] = "ESNOCL";
        //        esnoclRow["IdSezione"] = "77";     //valore fixed nel DB
        //        dt.Rows.Add(esnoclRow);
        //    }
        //    if (coingl.Length == 0) //se non c'e' aggiungo
        //    {
        //        DataRow coinglRow = dt.NewRow();
        //        coinglRow["internalSectionCode"] = "COINGL";
        //        coinglRow["IdSezione"] = "75";     //valore fixed nel DB
        //        dt.Rows.Add(coinglRow);
        //    }
        //}


        foreach (DataRow dr in dt.Rows) //ricavo l'indice (e' posizionale) del controllo da attivare.
        {
            //isc = dr["internalSectionCode"].ToString();
            //found = enableDisableControl(isc);

            //if (!found) indiceSezioneAttiva[idx++] = dr["IdSezione"].ToString();
            //else found = false;

            indiceSezioneAttiva[idx++] = dr["IdSezione"].ToString();
        }

        return rc;
    }
    //=========================================================
    private bool enableDisableControl(string isc)
    {
        bool found = false;

        if (tbl.Pianif_CustomerHasNoPiramideModello)
        {
            switch (isc)
            {
                case "CFPMPA":
                    found = true;
                    break;
            }
        }


        if (tbl.Pianif_CustomerHasNoBFWallet)
        {
            switch (isc)
            {
                case "DTGPRD":
                case "INCPRF":
                    found = true;
                    break;
            }
        }
        //if (tbl.Pianif_CustomerIsProspect)
        //{
        //    switch (isc)
        //    {
        //        case "CFPMPA":
        //            found = true;
        //            break;
        //    }
        //}
        //if (tbl.Pianif_CustomerIsProspectAndHasNoWalletByOtherInstitutes)
        //{
        //    switch (isc)
        //    {
        //        case "ANRSPF":
        //            found = true;
        //            break;
        //    }
        //}

        if (tbl.Pianif_CustomerHasNoPianificazione)
        {
            switch (isc)
            {
                case "PIANIF":
                case "PNFVRT":
                case "PMPIAN":
                case "CFPMPP":
                case "CFPAPP":
                case "PNFORZ":
                case "INDSNT":
                case "PBEVRC":
                case "INCSCM":
                case "INCSSP":
                case "INSTIN":
                case "DSASSC":
                case "MASSCL":
                case "ASSCLA":
                case "INCSC2":
                case "PBEVR2":
                case "INCSM2":
                case "INCSP2":
                case "INSTI2":
                case "DSASS2":
                case "MASSC2":
                case "ASSCL2":
                    found = true;
                    break;
            }
        }
        if (tbl.Pianif_CustomerHasNoRischio && tbl.Pianif_CustomerHasNoWalletAtAll)
        {
            switch (isc)
            {
                case "ANRSPF":
                    found = true;
                    break;
            }
        }

        if (tbl.Pianif_CustomerHasNoRischio)
        {
            switch (isc)
            {
                case "PRFRSC":
                    found = true;
                    break;
            }
        }

        if (tbl.Pianif_CustomerHasNoWalletAtAll)
        {
            switch (isc)
            {
                case "DIAGNO":
                case "PATCMP":
                case "DTGPRD":
                case "INCPRF":
                    found = true;
                    break;
            }
        }

        return found;
    }
    //==========================================================
    private bool getReportSectionIds_ByName(string nomeReport)
    {
        bool rc = false;
        List<Parametro> parametri = new List<Parametro>();
        Parametro parametro = new Parametro();
        parametro.DbType = DbType.String;
        parametro.Value = nomeReport;
        parametro.ParameterName = "pReportName";
        parametri.Add(parametro);

        DataTable dt = DataAccess.ExecuteDataTableStoredProcedure(DBProvider.SqlServer, "sp_getSezioniReport_ByReportName", parametri);

        int idx = 0;
        reportIdToPass = Convert.ToInt32(dt.Rows[0]["idReport"]);
        foreach (DataRow dr in dt.Rows) //ricavo l'indice (e' posizionale) del controllo da attivare.
        {
            indiceSezioneAttiva[idx++] = dr["IdSezione"].ToString();
        }
        return rc;
    }
    //==========================================================
    protected void btn_Stampa_Click(object sender, EventArgs e)
    {
        bool rcode = checkPianificazioneEnabled(); //verifico la possibilita' di generare la stampa per QUEL cliente

        if (rcode == true)
        {
            bool rc = false;
            //salviamo la configurazione mandata in stampa come "LAST USED CONFIG"
            int idCliente = _cliente.IdCliente_SEIReport;
            if (idCliente != -1)
            {
                idReport = scriviNuovoModelloReportIntoDB("LAST USED CONFIG" + "_" + idCliente.ToString(), idCliente);

                //salvo la ultima configurazione USATA dall'operatore anche se NON salvata in un modello specifico
                if (idReport != -1)
                {
                    CheckBox crtlCheckBox;
                    RadioButton ctrlRadio;
                    bool statusOfCopertina = true;
                    bool escludi = false;
                    //int idx = 1;

                    foreach (tvElementsPianificazione elem in rowElements)
                    {
                        if (elem.descrizione == null) break;

                        if (elem.tipoControllo == "1" || elem.tipoControllo == "0") //checkbox
                        {
                            crtlCheckBox = (CheckBox)this.mainTable.FindControl(elem.nomeControllo);

                            if (elem.nomeControllo == "cxb75" && rbl_Privacy.Items[1].Selected == true) crtlCheckBox.Checked = true;

                            if (elem.nomeControllo == "cxb76") statusOfCopertina = crtlCheckBox.Checked;
                            if (elem.nomeControllo == "cxb77" && !statusOfCopertina) escludi = true;

                            if (elem.nomeControllo == "cxb77" && statusOfCopertina)
                            {
                                if (rbl_Privacy.Items[1].Selected == true) crtlCheckBox.Checked = true;
                            }

                            if (crtlCheckBox.Checked == true && !escludi) rc = scriviDettaglioSezioniDelReportIntoDB(elem.idSezione, idReport);
                            escludi = false;

                            if (rc) break;
                        }
                        else if (elem.tipoControllo == "2")
                        {
                            ctrlRadio = (RadioButton)this.mainForm.FindControl(elem.nomeControllo);
                            if (ctrlRadio.Checked == true)
                                rc = scriviDettaglioSezioniDelReportIntoDB(elem.idSezione, idReport);
                            if (rc) break;
                        }
                        else if (elem.tipoControllo == "3") //labels
                        {
                            //do nothing
                        }
                    }

                    //inizializzo il cookie che segnala la possibilita' di mostrare la pagina di inserimento note (reportStampa.aspx)
                    HttpCookie ck_endOfJob = new HttpCookie("endOfJob");
                    ck_endOfJob.Value = "0";
                    Response.Cookies.Add(ck_endOfJob);

                    #region MODIFICA PER GESTIONE STAMPA e POOL SU CLIENT
                    nomeInizialeReport = this.txb_nomeModello.Text;
                    descrizioneInizialeReport = this.txb_descrizione.Text;

                    if (rbl_scelte.Items[0].Selected == true)
                    {
                        baseCompleto = "1";
                    }
                    else if (rbl_scelte.Items[1].Selected == true)
                    {
                        baseCompleto = "2";
                    }

                    reportNominativo = this.rbl_Privacy.Items[0].Selected ? true : false;

                    string command = "generaPDF(\"Generator.aspx\",\"tipoReport=PIANIFICAZIONE&action=createPianificazione&codicePB=" + codicePB + "&codiceFiscale=" + codiceFiscale + "&token=" + token + "&codiceRete=" + codiceRete + "&idReport=" + idReport + "&ambiente=" + ambiente + "&nomeInizialeReport=" + nomeInizialeReport + "&descrizioneInizialeReport=" + descrizioneInizialeReport + "&baseCompleto=" + baseCompleto + "&checkPrivacy=" + reportNominativo + "\");";

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


                    #endregion FINE MODIFICA PER GESTIONE STAMPA e POOL SU CLIENT

                }
                else this.lbl_message.Text = "Attenzione. Errore nel recupero del codice Cliente.";
            }
        }
        else this.lbl_message.Text = "Attenzione. Non � possibile procedere con la stampa: per il cliente in sessione non � attiva nessuna pianificazione.";
    }

    private bool checkPianificazioneEnabled()
    {
        //HttpCookie ck_codiceFiscale = new HttpCookie("codiceFiscale");
        //ck_codiceFiscale = System.Web.HttpContext.Current.Request.Cookies["codiceFiscale"];
        //if (codiceFiscale == null || codiceFiscale == "")
        //{
        //    if (ck_codiceFiscale != null) codiceFiscale = ck_codiceFiscale.Value.ToString();
        //}
        //DataTable dt = SectionManager.GetDataSection("reportPianificazione_checkPianificazioneEnabled", codicePB, codiceFiscale, codiceRete);
        //return dt.Rows.Count > 0;        
        return !tbl.CustomerHasNoPianificazione();
    }

    private int saveLastUsedConfigIntoDB(int idCliente, int idReport)
    {
        List<Parametro> parametri = new List<Parametro>();
        Parametro parametro = new Parametro();
        parametro.DbType = DbType.Int32;
        parametro.Value = idReport;
        parametro.ParameterName = "idReport";
        parametri.Add(parametro);

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

        return DataAccess.ExecuteNonQueryStoredProcedure(DBProvider.SqlServer, "sp_updateClienteReportLastAccess", parametri);
    }
    //=========================================================================
    protected void ddl_Modello_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddl_Modello.SelectedItem.Text != "Selezione Modelli")
        {
            int idReportSelezionato = Convert.ToInt32(this.ddl_Modello.SelectedItem.Value); //indica l'id del report personalizzato prescelto
            reportIdToPass = idReportSelezionato;

            //aggiungo il cookie con ReportToPass 
            if (reportIdToPass != 0)
            {
                HttpCookie ck_reportIdToPass = new HttpCookie("reportIdToPass");
                ck_reportIdToPass.Value = reportIdToPass.ToString();
                Response.Cookies.Add(ck_reportIdToPass);
            }

            //loadChoosenProfile(idReportSelezionato, null);
            loadChoosenProfileNew(idReportSelezionato, null);
            this.txb_descrizione.Text = descrizioneReportPerLabel;
            this.txb_nomeModello.Text = nomeReportPerLabel;

            setControlsOnTV();
            this.lbl_message.ForeColor = System.Drawing.Color.Black;
            //this.lbl_message.Text = "Modello " + ddl_Modello.SelectedItem.Text + " caricato correttamente";
            this.lbl_message.Text = "";
        }
    }
    //========================================================================
    private void setControlsOnTV()
    {
        CheckBox crtlCheckBox;
        RadioButton ctrlRadio;

        //reset all TV elements
        foreach (tvElementsPianificazione elem in rowElements)
        {
            if (elem.descrizione == null) break;

            if (elem.tipoControllo == "1" || elem.tipoControllo == "0") //checkbox
            {
                crtlCheckBox = (CheckBox)this.mainTable.FindControl(elem.nomeControllo);
                crtlCheckBox.Checked = false;
            }
            else if (elem.tipoControllo == "2")  //radio
            {
                ctrlRadio = (RadioButton)this.mainForm.FindControl(elem.nomeControllo);
                ctrlRadio.Checked = false;
            }
        }

        //set TV elements
        foreach (string elem in indiceSezioneAttiva)
        {
            if (elem == null) break;

            int offset = getOffset();
            int pos = Convert.ToInt32(elem) - offset; //l'array rowElements dovrebbe essere riempito con indici UGUALI all'id della Sezione e non da base 0!

            if (rowElements[pos].tipoControllo == "1" || rowElements[pos].tipoControllo == "0") //checkbox
            {
                crtlCheckBox = (CheckBox)this.mainTable.FindControl(rowElements[pos].nomeControllo);
                crtlCheckBox.Checked = true;
            }
            else if (rowElements[pos].tipoControllo == "2") //radio
            {
                ctrlRadio = (RadioButton)this.mainForm.FindControl(rowElements[pos].nomeControllo);
                ctrlRadio.Checked = true;
            }
        }
    }
    //=====================================================================
    private int getOffset()
    {
        List<Parametro> parametri = new List<Parametro>();
        Parametro parametro = new Parametro();
        parametro.DbType = DbType.Int32;
        parametro.Value = idReport;
        parametro.ParameterName = "pIdReport";
        parametri.Add(parametro);

        return (int)DataAccess.ExecuteScalarStoredProcedure(DBProvider.SqlServer, "sp_getOffset_ByIdReport", parametri);
    }
    //========================================================================
    private void loadChoosenProfileNew(int idReportSelezionato, string pUtente)
    {

        List<Parametro> parametri = new List<Parametro>();

        Parametro parametro = new Parametro();
        parametro.DbType = DbType.Int32;
        parametro.Value = idReportSelezionato;
        parametro.ParameterName = "idReport";
        parametri.Add(parametro);

        DataTable dt = DataAccess.ExecuteDataTableStoredProcedure(DBProvider.SqlServer, "sp_getSezioniReport_ByIdReportNew", parametri);

        ////patch per la privacy
        //if (this.rbl_Privacy.Items[0].Selected == true) privacy = "1";
        //else privacy = "0";
        //dt.Columns["IdReport"].DefaultValue = reportIdToPass;
        //if (privacy == "0") //aggiungo ESNOCL
        //{
        //    DataRow[] esnocl = dt.Select("internalSectionCode = 'ESNOCL'");
        //    DataRow[] coingl = dt.Select("internalSectionCode = 'COINGL'");

        //    if (esnocl.Length == 0) //se non c'e' aggiungo
        //    {
        //        DataRow esnoclRow = dt.NewRow();
        //        esnoclRow["internalSectionCode"] = "ESNOCL";
        //        esnoclRow["IdSezione"] = "77";     //valore fixed nel DB
        //        dt.Rows.Add(esnoclRow);
        //    }
        //    if (coingl.Length == 0) //se non c'e' aggiungo
        //    {
        //        DataRow coinglRow = dt.NewRow();
        //        coinglRow["internalSectionCode"] = "COINGL";
        //        coinglRow["IdSezione"] = "75";     //valore fixed nel DB
        //        dt.Rows.Add(coinglRow);
        //    }
        //}

        int idx = 0;

        foreach (DataRow dr in dt.Rows) //ricavo l'indice (e' posizionale) del controllo da attivare.
        {
            //isc = dr["internalSectionCode"].ToString();
            //found = enableDisableControl(isc);

            //if (!found) indiceSezioneAttiva[idx++] = dr["IdSezione"].ToString();
            //else found = false;

            indiceSezioneAttiva[idx++] = dr["IdSezione"].ToString();
        }

        //recupero il nome del report
        getReportName_ByReportID(idReportSelezionato);
    }
    //========================================================================
    private void loadChoosenProfile(int idReportSelezionato, string pUtente)
    {
        List<Parametro> parametri = new List<Parametro>();

        Parametro parametro = new Parametro();
        parametro.DbType = DbType.Int32;
        parametro.Value = idReportSelezionato;
        parametro.ParameterName = "pIdReport";
        parametri.Add(parametro);

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

        DataTable dt = DataAccess.ExecuteDataTableStoredProcedure(DBProvider.SqlServer, "sp_getSezioniReport_ByIdReport", parametri);

        int idx = 0;
        foreach (DataRow dr in dt.Rows) //ricavo l'indice (e' posizionale) del controllo da attivare.
        {
            indiceSezioneAttiva[idx++] = dr["IdSezione"].ToString();
            nomeReportPerLabel = dr["nome"].ToString();
            descrizioneReportPerLabel = dr["descrizione"].ToString();
        }
    }
    protected void txb_descrizione_TextChanged(object sender, EventArgs e)
    {

    }
    //===========================================================================
    protected void rbl_OnLoad(object sender, EventArgs e)
    {
        rbl_Privacy.Items[0].Attributes.Add("onclick", "privacyDisable();");
        rbl_Privacy.Items[1].Attributes.Add("onclick", "privacyEnable();");
    }
    //=========================================================================
    protected void rbl_Privacy_SelectedIndexChanged(object sender, EventArgs e)
    {


    }


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

        }

    }

    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {

    }
    #endregion

}


//==========================================================================
public struct tvElementsPianificazione
{
    public string nomeControllo;
    public string tipoControllo;
    public string descrizione;
    public int idSezione;

}