protected void btnSaveExpense_Click(object sender, EventArgs e)
        {
            Claim claim = null;
            Claim myClaim = null;
            ClaimExpense claimExpense = null;
            AdjusterMaster adjuster = null;
            CarrierInvoiceProfile CarrierInvoice = null;

            int clientID = SessionHelper.getClientId();
            int userID = SessionHelper.getUserId();
            int claimID = SessionHelper.getClaimID();
            int myAdjusterID = 0;
            int profileID = 0;
            int expenseTypeID = 0;
            int id = 0;

            Page.Validate("expense");
            if (!Page.IsValid)
                return;

            id = Convert.ToInt32(ViewState["ClaimExpenseID"]);

            ClaimManager cm = new ClaimManager();
            myClaim = cm.Get(claimID);

            try
            {
                expenseTypeID = Convert.ToInt32(ddlExpenseType.SelectedValue);

                using (TransactionScope scope = new TransactionScope())
                {
                    using (ClaimExpenseManager repository = new ClaimExpenseManager())
                    {
                        if (id == 0) {
                            claimExpense = new ClaimExpense();
                            claimExpense.ClaimID = claimID;
                        }
                        else {
                            claimExpense = repository.Get(id);
                        }

                        // populate fields
                        if(txtExpenseAmount.Visible == false)
                        {
                            var x = Session["multiplier"].ToString();

                            double expenseAmount = Convert.ToDouble(x) * Convert.ToDouble(txtExpenseQty.ValueDecimal); //newOC 10/7/14
                            claimExpense.ExpenseAmount = Convert.ToDecimal(expenseAmount);

                            decimal d = Convert.ToDecimal(expenseAmount);
                            //Session["EmailAmount"] = "$" + Math.Round(d, 2);
                            Session["EmailAmount"] = String.Format("{0:0.00}", expenseAmount);
                           // Session["EmailAmount"] = expenseAmount;
                        }
                        else
                        {
                            claimExpense.ExpenseAmount = txtExpenseAmount.ValueDecimal;
                        }
                        claimExpense.ExpenseDate = txtExpenseDate.Date;
                        claimExpense.ExpenseDescription = txtExpenseDescription.Text.Trim();
                        claimExpense.ExpenseTypeID = expenseTypeID;
                        claimExpense.IsReimbursable = cbxExpenseReimburse.Checked;
                        claimExpense.UserID = userID;
                        claimExpense.AdjusterID = Convert.ToInt32(hf_expenseAdjusterID.Value);
                        claimExpense.ExpenseQty = txtExpenseQty.ValueDecimal;
                        claimExpense.InternalComments = txtMyComments.Text.Trim();
                        claimExpense.Billed = false;
                       // claimExpense.IsBillable = cbIsBillable.Checked;
                        // save expense
                        claimExpense = repository.Save(claimExpense);
                    }

                    // update diary entry
                    ClaimComment diary = new ClaimComment();
                    diary.ClaimID = claimID;
                    diary.CommentDate = DateTime.Now;
                    diary.UserId = userID;
                    diary.CommentText = string.Format("Expense: {0}, Description: {1}, Date: {2:MM/dd/yyyy}, Amount: {3:N2}, Adjuster: {4} Qty: {5:N2}",
                                                ddlExpenseType.SelectedItem.Text,
                                                claimExpense.ExpenseDescription,
                                                claimExpense.ExpenseDate,
                                                claimExpense.ExpenseAmount,
                                                txtExpenseAdjuster.Text,
                                                claimExpense.ExpenseQty
                                                );
                    ClaimCommentManager.Save(diary);

                    // 2014-05-02 apply rule
                    using (SpecificExpenseTypePerCarrier ruleEngine = new SpecificExpenseTypePerCarrier())
                    {
                        claim = new Claim();
                        claim.ClaimID = claimID;
                        RuleException ruleException = ruleEngine.TestRule(clientID, claim, expenseTypeID);

                        if (ruleException != null) {
                            ruleException.UserID = Core.SessionHelper.getUserId();
                            ruleEngine.AddException(ruleException);
                            CheckSendMail(ruleException);
                        }
                    }
                    myAdjusterID = Convert.ToInt32(claimExpense.AdjusterID); //Convert.ToInt32(myClaim.AdjusterID);
                    //EMAIL ADJUSTER OC 10/22/2014
                    if (myAdjusterID != 0 || myAdjusterID != null)
                    {
                        adjuster = AdjusterManager.GetAdjusterId(myAdjusterID);
                    }
                    if (cbEmailAdjuster.Checked == true)
                    {
                        try
                        {
                            notifyAdjuster(adjuster, claimExpense, myClaim);

                        }
                        catch (Exception ex)
                        {
                            lblMessage.Text = "Unable to send email to adjuster";
                            lblMessage.CssClass = "error";
                        }
                    }
                    //EMAIL CLIENT CONTACT OC 10/22/2014
                    if (cbEmailClient.Checked == true) //Dont need to check if invoice Pro ID is empty becuase to get to this point, one has to exist already
                    {
                        if (Session["ComingFromAllClaims"] != null) //if the user got here straight from the all claims screen
                        {
                            profileID = Convert.ToInt32(Session["CarrierInvoiceID"]);
                        }
                        else//coming from claim detail page
                        {
                            profileID = Convert.ToInt32(Session["InvoiceProfileID"]);
                        }
                        CarrierInvoice = CarrierInvoiceProfileManager.Get(profileID);
                        try
                        {
                              notifyClientContact(CarrierInvoice, claimExpense, myClaim, adjuster);
                        }
                        catch (Exception ex)
                        {
                            lblMessage.Text = "Unable to send email to client contact";
                            lblMessage.CssClass = "error";
                        }

                    }
                    //EMAIL TO WHOMEVER OC 10/22/2014
                    if (txtEmailTo.Text != "")
                    {

                        try
                        {
                             notifySpecifiedUser(adjuster, claimExpense, myClaim);
                        }
                        catch (Exception ex)
                        {
                            lblMessage.Text = "Unable to send email to adjuster";
                            lblMessage.CssClass = "error";
                        }
                    }

                    // complete transaction
                    scope.Complete();
                }

                lblMessage.Text = "Expense saved successfully.";
                lblMessage.CssClass = "ok";

                // refresh grid
                gvExpense.DataSource = loadExpenses(claimID);
                gvExpense.DataBind();

                // keep edit form active
                lbtnNewExpense_Click(null, null);
                lblAmount.Text = "";
                lblAmount.Visible = false;
                txtExpenseAmount.Visible = true;
            }
            catch (Exception ex) {
                Core.EmailHelper.emailError(ex);

                lblMessage.Text = "Unable to save claim expense.";
                lblMessage.CssClass = "error";
            }
        }
        private void processClaimExpenses(int claimID, CarrierInvoiceProfile invoiceProfile, int invoiceID)
        {
            CarrierInvoiceProfileFeeItemized profileTEFee = null;
            List<ClaimExpense> claimExpenses = null;
            decimal lineTotal = 0;
            decimal quantity = 0;
            decimal operand = 0;
            decimal expenseAmount = 0;
            decimal rateAmount = 0;
            string serviceDescription = null;
            string serviceComments = null;
            bool billed = true;
            // get TE services for claim entered by adjuster
            using (ClaimExpenseManager repositiory = new ClaimExpenseManager())
            {
                claimExpenses = repositiory.GetExpenseForInvoice(claimID);
            }

            if (claimExpenses != null && claimExpenses.Count > 0)
            {
                foreach (ClaimExpense claimExpense in claimExpenses)
                {
                    rateAmount = 0;
                    int claimExpenseID = claimExpense.ClaimExpenseID;
                    profileTEFee = (from x in invoiceProfile.CarrierInvoiceProfileFeeItemized
                                 where x.ExpenseTypeID == claimExpense.ExpenseTypeID
                                 select x
                                 ).FirstOrDefault();

                    if (profileTEFee != null)
                    {
                        // use override from invoice profile
                        serviceDescription = claimExpense.ExpenseType.ExpenseName;// profileTEFee.ExpenseType == null ? string.Empty : profileTEFee.ExpenseType.ExpenseDescription;
                        serviceComments = claimExpense.ExpenseDescription; // profileTEFee.ItemDescription;
                        operand = profileTEFee.LogicalOperatorOperand ?? 0;
                        billed = claimExpense.Billed.Value;
                        rateAmount = profileTEFee.ItemRate; //claimExpense.ExpenseAmount;
                        quantity = Convert.ToDecimal(claimExpense.ExpenseQty);
                        Session["ExpAmount"] = claimExpense.ExpenseAmount;
                        if ((profileTEFee.LogicalOperator ?? 0) > 0 && operand > 0)
                        {
                            quantity = claimExpense.ExpenseQty ?? 0;
                            expenseAmount = claimExpense.ExpenseAmount;

                            switch (profileTEFee.LogicalOperator)
                            {
                                case 1:		// =
                                    //if (expenseAmount > 0 && expenseAmount == operand) {
                                    //	rateAmount = profileTEFee.ItemRate;
                                    //	expenseAmount = quantity * rateAmount;
                                    //}
                                    //else if (quantity > 0 && quantity == operand) {
                                    //	rateAmount = profileTEFee.ItemRate;
                                    //	expenseAmount = quantity * rateAmount;
                                    //}
                                    break;

                                case 2:		// <
                                case 3:		// <=
                                    if (expenseAmount > 0 && expenseAmount <= operand)
                                    {
                                        quantity = 1;
                                        rateAmount = profileTEFee.ItemRate;
                                    }
                                    else if (quantity > 0 && quantity <= operand) {
                                        rateAmount = profileTEFee.ItemRate; //;
                                    }
                                    break;

                                case 4:		// >
                                case 5:		// >=
                                    if (expenseAmount > 0 && expenseAmount >= operand)
                                    {
                                        quantity = 1;
                                        rateAmount = operand;
                                    }
                                    else if (quantity > 0 && quantity >= operand)
                                    {
                                        quantity = quantity - operand;
                                        rateAmount = profileTEFee.ItemRate;
                                    }
                                    break;

                                default:
                                    quantity = 1;
                                    rateAmount = profileTEFee.ItemRate; //claimExpense.ExpenseAmount;
                                    break;
                            }
                            if (billed == false)
                            {
                                insertDetailLine(invoiceID, serviceDescription, quantity, rateAmount, claimExpense.ExpenseDate, serviceComments);
                                using (ClaimExpenseManager myRepositiory = new ClaimExpenseManager())
                                {
                                    ClaimExpense myClaimExpense = myRepositiory.Get(claimExpenseID);
                                    myClaimExpense.Billed = true;
                                    myRepositiory.Save(myClaimExpense);
                                }
                            }

                        }
                        else if (profileTEFee.ItemRate > 0)
                        {
                            // no condition specified
                            quantity = claimExpense.ExpenseQty ?? 1;

                            rateAmount = profileTEFee.ItemRate;

                            lineTotal = expenseAmount;
                            if (billed == false)
                            {
                                insertDetailLine(invoiceID, serviceDescription, quantity, rateAmount, claimExpense.ExpenseDate, serviceComments);
                                using (ClaimExpenseManager myRepositiory = new ClaimExpenseManager())
                                {
                                    ClaimExpense myClaimExpense = myRepositiory.Get(claimExpenseID);
                                    myClaimExpense.Billed = true;
                                    myRepositiory.Save(myClaimExpense);
                                }
                            }

                        }
                        else if (profileTEFee.ItemPercentage > 0)
                        {
                        }
                    }
                    else
                    {
                        // no override found
                        serviceDescription = claimExpense.ExpenseType.ExpenseDescription;

                        serviceComments = claimExpense.ExpenseDescription;

                        quantity = claimExpense.ExpenseQty ?? 1;

                        rateAmount = claimExpense.ExpenseAmount;
                        if (billed == false)
                        {
                            insertDetailLine(invoiceID, serviceDescription, quantity, rateAmount,  claimExpense.ExpenseDate, serviceComments);
                            using (ClaimExpenseManager myRepositiory = new ClaimExpenseManager())
                            {
                                ClaimExpense myClaimExpense = myRepositiory.Get(claimExpenseID);
                                myClaimExpense.Billed = true;
                                myRepositiory.Save(myClaimExpense);
                            }
                        }

                    }
                }
            }
        }
        public static string SaveClaimExpense(string expenseType, string insurerClaimId, string insurerName, int claimAdjusterId, string adjusterComapnyName, string updatedby, string commentNote, string emailTo, int carrierID, int claimID, string recipientId, string claimAdjuster, string expenseTypeName, string carrier, string idOf, string expenseQty, string expenseAmount, string expenseDate, string reimbrance)
        {
            string json = "";
            Claim objclaim = null;
            AdjusterMaster objAdjusterMaster = null;
            Leads objLeads = null;
            ClaimComment comment = null;
            ClaimExpense claimExpense = null;
            CRM.Data.Entities.LeadPolicy objLeadPolicy = null;
            int userID = SessionHelper.getUserId();
            int leadID = 0;
            int policyId = 0;
            try
            {
                using (TransactionScope scope = new TransactionScope())
                {
                    using (ClaimManager repository = new ClaimManager())
                    {
                        objclaim = new Claim();
                        objclaim.ClaimID = claimID;

                        objclaim.InsurerClaimNumber = insurerClaimId;
                        //objclaim.CarrierID = carrierID;
                        objclaim.AdjusterID = claimAdjusterId;
                        // objclaim.StatusUpdatedBy = updatedby;
                        repository.UpdateClaimStatus(objclaim);

                        // AdjusterMaster
                        objAdjusterMaster = new AdjusterMaster();
                        objAdjusterMaster.AdjusterId = claimAdjusterId;
                        //objAdjusterMaster.CompanyName = AdjusterComapnyName;
                        repository.UpdateAdjusterName(objAdjusterMaster);

                        //leads
                        leadID = repository.GetPolicyId(claimID);
                        objLeads = new Leads();
                        objLeads.LeadId = leadID;
                        objLeads.InsuredName = insurerName;
                        repository.UpdateInsurerName(objLeads);
                        //save carrier id in Lead policy
                        policyId = repository.GetLeadPolicyId(claimID);
                        objLeadPolicy = new Data.Entities.LeadPolicy();
                        objLeadPolicy.Id = policyId;
                        objLeadPolicy.CarrierID = carrierID;
                        repository.UpdateCarrierId(objLeadPolicy);

                        //add expense
                        ClaimExpenseManager objClaimExpenseManager = new ClaimExpenseManager();
                        claimExpense = new ClaimExpense();
                        claimExpense.ClaimID = claimID;
                        if (!string.IsNullOrEmpty(expenseAmount))
                        {
                            claimExpense.ExpenseAmount = Convert.ToDecimal(expenseAmount);
                        }
                        if (!string.IsNullOrEmpty(expenseDate))
                        {
                            claimExpense.ExpenseDate = Convert.ToDateTime(expenseDate);
                        }
                        claimExpense.ExpenseDescription = commentNote.Trim();
                        claimExpense.ExpenseTypeID = Convert.ToInt32(expenseType);
                        if (reimbrance == "1")
                        {
                            claimExpense.IsReimbursable = true;
                        }
                        else
                        {
                            claimExpense.IsReimbursable = false;
                        }

                        claimExpense.UserID = userID;
                        claimExpense.AdjusterID = Convert.ToInt32(claimAdjusterId);
                        if (!string.IsNullOrEmpty(expenseQty))
                        {
                            claimExpense.ExpenseQty = Convert.ToDecimal(expenseQty);
                        }
                        objClaimExpenseManager.Save(claimExpense);

                        //claim comment for add notes
                        comment = new ClaimComment();
                        comment.ClaimID = claimID;
                        comment.IsActive = true;
                        comment.UserId = Core.SessionHelper.getUserId();
                        comment.CommentDate = DateTime.Now;
                        comment.ActivityType = "Add Expense";
                        comment.CommentText = string.Format("Expense: {0}, Description: {1}, Date: {2:MM/dd/yyyy}, Amount: {3:N2}, Adjuster: {4} Qty: {5:N2}",
                                                 expenseTypeName,
                                                 commentNote.Trim(),
                                                 Convert.ToDateTime(expenseDate),
                                                 expenseAmount,
                                                 claimAdjuster,
                                                 expenseQty
                                                 );
                        ClaimCommentManager.Save(comment);

                    }
                    scope.Complete();
                }
                string[] recipId = recipientId.Split(',');
                string recipientEmailId = string.Empty;

                string[] IdofTable = idOf.Split(',');
                int index2 = 0;
                for (int index = 0; index < recipId.Length; index++)
                {
                    index2 = 0;
                    int.TryParse(recipId[index], out index2);
                    if (IdofTable[index] == "c")
                    {

                        Contact objContact = ContactManager.Get(index2);
                        if (!string.IsNullOrEmpty(objContact.Email))
                        {
                            if (recipientEmailId == "")
                            {
                                recipientEmailId = objContact.Email;
                            }
                            else
                            {
                                recipientEmailId = recipientEmailId + "," + objContact.Email;
                            }
                        }
                    }
                    else
                    {

                        AdjusterMaster objAdjuster = AdjusterManager.GetAdjusterId(index2);

                        if (!string.IsNullOrEmpty(objAdjuster.email))
                        {
                            if (recipientEmailId == "")
                            {
                                recipientEmailId = objAdjuster.email;
                            }
                            else
                            {
                                recipientEmailId = recipientEmailId + "," + objAdjuster.email;
                            }
                        }

                    }
                }
                SendExpenseEmail(expenseType, insurerClaimId, insurerName, claimAdjusterId, adjusterComapnyName, updatedby, commentNote, "", carrierID, claimID, recipientEmailId, claimAdjuster, expenseTypeName, carrier, recipId, IdofTable, expenseQty, expenseAmount, expenseDate, reimbrance);
                json = "Expense add successfully";

            }
            catch (Exception ex)
            {
                Core.EmailHelper.emailError(ex);
            }

            return json;
        }