protected void FVSpese_DataBound(object sender, EventArgs e)
    {
        //      formattta il campo numerico delle spese, nel DB le spese stornate sono negative
        if (Request.QueryString["action"] == "fetch")
        {
            TextBox TBSpese    = (TextBox)FVSpese.FindControl("TBAmount");
            double  SpeseValue = Math.Abs(Convert.ToDouble(TBSpese.Text));
            TBSpese.Text = SpeseValue.ToString();
        }

        if (Request.QueryString["expenses_id"] != null)
        {
            //              Valorizza progetto e attività
            Bind_DDLprogetto();
            Bind_DDLTipoSpesa();
        }
        else // insert
        {
            Bind_DDLprogetto();
            Bind_DDLTipoSpesa();
        }

        //      se livello autorizzativo è inferiore a 4 spegne il campo competenza
        if (!Auth.ReturnPermission("ADMIN", "CUTOFF"))
        {
            Label   LBAccountingDate = (Label)FVSpese.FindControl("LBAccountingDate");
            TextBox TBAccountingDate = (TextBox)FVSpese.FindControl("TBAccountingDate");

            // se display
            LBAccountingDate.Visible = false;
            TBAccountingDate.Visible = false;
        }
    }
    protected void Bind_DDLprogetto()
    {
        DataTable    dtProgettiForzati;
        DropDownList ddlProject = (DropDownList)FVSpese.FindControl("DDLprogetto");

        ddlProject.Items.Clear();

        switch (FVSpese.CurrentMode)
        {
        case FormViewMode.Insert:
        case FormViewMode.Edit:

            dtProgettiForzati = CurrentSession.dtProgettiForzati;

            foreach (DataRow drRow in dtProgettiForzati.Rows)
            {
                ListItem liItem = new ListItem(drRow["DescProgetto"].ToString(), drRow["Projects_Id"].ToString());
                if (drRow["BloccoCaricoSpese"].ToString() != "True")     // solo se carico spese è ammesso
                {
                    ddlProject.Items.Add(liItem);
                }
            }

            break;

        case FormViewMode.ReadOnly:

            ddlProject.DataSource = CurrentSession.dtProgettiTutti;
            break;
        }

        ddlProject.DataTextField  = "DescProgetto";
        ddlProject.DataValueField = "Projects_Id";
        ddlProject.DataBind();

        if (lProject_id != "")
        {
            ddlProject.SelectedValue = lProject_id;
        }

        // se in creazione imposta il default di progetto
        if (FVSpese.CurrentMode == FormViewMode.Insert)
        {
            // prima cerca progetto sul giorno, se non lo trova mette ultimo default
            DataRow drRecord = Database.GetRow("SELECT Projects_id FROM Hours WHERE persons_id = " + CurrentSession.Persons_id + " AND date = " + ASPcompatility.FormatDateDb(Request["date"]), this.Page);

            if (drRecord != null)
            {
                ddlProject.SelectedValue = drRecord["Projects_id"].ToString();
            }
            else
            {
                ddlProject.SelectedValue = (string)Session["ProjectCodeDefault"];
            }
        }
    }
    protected void Bind_DDLTipoSpesa()
    {
        DataTable    dtSpeseForzate = CurrentSession.dtSpeseForzate;
        DropDownList ddlTipoSpesa   = (DropDownList)FVSpese.FindControl("DDLTipoSpesa");
        String       sTipoBonus_sel = "";

        // 08/2014 se viene richiamato da pagina bonus cambia il flag per il biding
        if (lTipoBonus_id > 0)
        {
            sTipoBonus_sel = "";
        }
        else
        {
            sTipoBonus_sel = " AND TipoBonus_Id = 0 ";
        }

        ddlTipoSpesa.Items.Clear();

        // aggiunge gli item con l'attributo per il controllo sull'obligatorietà dei commenti
        foreach (DataRow drRow in dtSpeseForzate.Rows)
        {
            // in INSERT e EDIT non aggiunge le spese di tipo bonus
            if (drRow["TipoBonus_id"].ToString() == "0" || FVSpese.CurrentMode == FormViewMode.ReadOnly)
            {
                ListItem liItem = new ListItem(drRow["descrizione"].ToString(), drRow["ExpenseType_Id"].ToString());
                liItem.Attributes.Add("data-desc-obbligatorio", drRow["TestoObbligatorio"].ToString());
                if (drRow["TestoObbligatorio"].ToString() == "True")
                {
                    liItem.Attributes.Add("data-desc-message", drRow["MessaggioDiErrore"].ToString());
                }
                else
                {
                    liItem.Attributes.Add("data-desc-message", "");
                }

                ddlTipoSpesa.Items.Add(liItem);
            }
        }

        ddlTipoSpesa.DataTextField  = "descrizione";
        ddlTipoSpesa.DataValueField = "ExpenseType_Id";
        ddlTipoSpesa.DataBind();

        if (lExpenseType_id != "")
        {
            ddlTipoSpesa.SelectedValue = lExpenseType_id;
        }

        // se in creazione imposta il default di progetto
        if (FVSpese.CurrentMode == FormViewMode.Insert)
        {
            ddlTipoSpesa.SelectedValue = (string)Session["ExpenseTypeDefault"];
        }
    }
    protected void DDLprogetto_SelectedIndexChanged(object sender, EventArgs e)
    {
        Label LBdate = (Label)FVSpese.FindControl("LBdate");

        DropDownList DDLprogetto = (DropDownList)FVSpese.FindControl("DDLprogetto");

        if (!Database.RecordEsiste("Select hours_id , projects_id from Hours where projects_id= " + DDLprogetto.SelectedValue + " AND date = " + ASPcompatility.FormatDateDb(LBdate.Text), this.Page))
        {
            // non ci sono ore caricate sul progetto, cerca se ci sono altri progetti
            if (!Database.RecordEsiste("Select hours_id , projects_id from Hours where date = " + ASPcompatility.FormatDateDb(LBdate.Text), this.Page))
            {
                ClientScript.RegisterStartupScript(Page.GetType(), "Popup", "$( function () { ShowPopup('" + GetLocalResourceObject("messaggioNonEsisteProgetto") + "'); } );", true);
            }
            else
            {
                ClientScript.RegisterStartupScript(Page.GetType(), "Popup", "$( function () { ShowPopup('" + GetLocalResourceObject("messaggioAltriProgetti") + "'); } );", true);
            }
        }
    }
    protected void DSSpese_Insert_Update(object sender, SqlDataSourceCommandEventArgs e)
    {
        //      Chiamato in aggiornamento e inserimento record rende negativo il valore delle ore
        //      nel caso sia valorizzato il flag storno
        double iCalc = 0;

        CheckBox CBcancel = (CheckBox)FVSpese.FindControl("CBcancel");

        if (CBcancel.Checked)
        {
            iCalc = Convert.ToDouble(e.Command.Parameters["@Amount"].Value) * (-1);
            e.Command.Parameters["@Amount"].Value = iCalc;
        }
        else
        {
            e.Command.Parameters["@Amount"].Value = Convert.ToDouble(e.Command.Parameters["@Amount"].Value);
        }

        //      Forza i valori da passare alla select di insert. essendo le dropdown in
        //      dipendenza non si riesce a farlo tramite un normale bind del controllo

        DropDownList ddlList = (DropDownList)FVSpese.FindControl("DDLprogetto");

        e.Command.Parameters["@Projects_id"].Value = ddlList.SelectedValue;

        DropDownList ddlList1 = (DropDownList)FVSpese.FindControl("DDLTipoSpesa");

        if (ddlList1.SelectedValue != null)
        {
            e.Command.Parameters["@ExpenseType_id"].Value = ddlList1.SelectedValue;
        }

        // Valorizza tipo Bonus se il tipo spesa è di tipo bonus
        DataTable dtTipoSpesa = CurrentSession.dtSpeseForzate;

        DataRow[] dr = dtTipoSpesa.Select("ExpenseType_id =  " + ddlList1.SelectedValue);

        if (dr.Count() == 1)
        {  // dovrebbe essere sempre così
            e.Command.Parameters["@TipoBonus_id"].Value      = Convert.ToInt32(dr[0]["TipoBonus_id"].ToString());
            e.Command.Parameters["@AdditionalCharges"].Value = dr[0]["AdditionalCharges"];
        }
        else
        {
            e.Command.Parameters["@TipoBonus_id"].Value      = 0;
            e.Command.Parameters["@AdditionalCharges"].Value = 0;
        }

        // salva default per select list
        Session["ProjectCodeDefault"]  = ddlList.SelectedValue;
        Session["ExpenseTypeDefault"]  = ddlList1.SelectedValue;
        Session["TipoBonus_IdDefault"] = e.Command.Parameters["@TipoBonus_id"].Value; // usato per spegnere/accendere il campo in insert
        //}

        // solo insert
        if (FVSpese.CurrentMode == FormViewMode.Insert)
        {
            e.Command.Parameters["@persons_id"].Value = CurrentSession.Persons_id;
            Label LBdate = (Label)FVSpese.FindControl("LBdate");
            e.Command.Parameters["@Date"].Value = Convert.ToDateTime(LBdate.Text);
            // Audit
            e.Command.Parameters["@CreatedBy"].Value    = CurrentSession.UserId;
            e.Command.Parameters["@CreationDate"].Value = DateTime.Now;
            // valori manager e società
            e.Command.Parameters["@Company_id"].Value = CurrentSession.Company_id;
            var result = Utilities.GetManagerAndAccountId(Convert.ToInt32(ddlList.SelectedValue));
            e.Command.Parameters["@ClientManager_id"].Value  = result.Item1; // ClientManager_id
            e.Command.Parameters["@AccountManager_id"].Value = result.Item2; // AccountManager_id
        }

        // if in change
        if (FVSpese.CurrentMode == FormViewMode.Edit)
        {
            // Audit
            e.Command.Parameters["@LastModifiedBy"].Value       = CurrentSession.UserId;
            e.Command.Parameters["@LastModificationDate"].Value = DateTime.Now;
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        Auth.CheckPermission("DATI", "SPESE");
        CurrentSession = (TRSession)Session["CurrentSession"]; // recupera oggetto con variabili di sessione

        //      Modo di default è insert, se richiamata con id va in change / display
        if (IsPostBack)
        {
            if (Request.QueryString["action"].ToString() != "new")
            {
                // recupera record per settare default sulle DDL al momento del Bind
                Get_record(Request.QueryString["expenses_id"].ToString());
                Trova_ricevute(Request.QueryString["expenses_id"]);
            }

            return;
        }

        // di default il box revicevute non è visibile
        BoxRicevute.Visible = false;

        //      in caso di update recupera il valore del progetto e attività
        if (Request.QueryString["expenses_id"] != null)
        {
            // recupera record per settare default sulle DDL al momento del Bind
            Get_record(Request.QueryString["expenses_id"].ToString());

            //              disabilita form in caso di cutoff
            Label LBdate = (Label)FVSpese.FindControl("LBdate");

            if (Convert.ToDateTime(LBdate.Text) < CurrentSession.dCutoffDate || lTipoBonus_id > 0)
            {
                FVSpese.ChangeMode(FormViewMode.ReadOnly);
            }
            else
            {
                FVSpese.ChangeMode(FormViewMode.Edit);
            }

            // recupera immagini Ricevute e visualizza box se ce ne sono
            Trova_ricevute(Request.QueryString["expenses_id"]);
        }
        else // insert
        {
            FVSpese.ChangeMode(FormViewMode.Insert);

            Label LBdate = (Label)FVSpese.FindControl("LBdate");
            LBdate.Text = Request.QueryString["date"];

            Label LBperson = (Label)FVSpese.FindControl("LBperson");
            LBperson.Text = (string)CurrentSession.UserName;

            TextBox TBAmount = (TextBox)FVSpese.FindControl("TBAmount");
            if (Convert.ToInt16(Session["TipoBonus_IdDefault"]) > 0)
            {
                TBAmount.Enabled = false;
                TBAmount.Text    = "1";
            }
            else
            {
                TBAmount.Enabled = true;
                TBAmount.Text    = "";
            }
        }
    }