private void Delete()
        {
            Page.Validate();

            if (Page.IsValid)
            {
                // Delete
                int workId = Int32.Parse(hdfWorkId.Value);
                RehabAssessmentSectionDetails rehabAssessmentSectionDetails = new RehabAssessmentSectionDetails(rehabAssessmentTDS);
                rehabAssessmentSectionDetails.Delete(workId);

                RehabAssessmentLateralDetails rehabAssessmentLateralDetails = new RehabAssessmentLateralDetails(rehabAssessmentTDS);
                rehabAssessmentLateralDetails.DeleteAll(workId);

                RehabAssessmentWorkDetails rehabAssessmentWorkDetails = new RehabAssessmentWorkDetails(rehabAssessmentTDS);
                rehabAssessmentWorkDetails.Delete(workId);

                // Update databse
                UpdateDatabase();

                // Store datasets
                Session["rehabAssessmentTDS"] = rehabAssessmentTDS;

                // Redirect
                string url = "";
                url = "./ra_navigator2.aspx?source_page=ra_delete.aspx&client_id=" + hdfCurrentClientId.Value + "&project_id=" + hdfCurrentProjectId.Value + GetNavigatorState() + "&update=yes";
                Response.Redirect(url);
            }
        }
        // ////////////////////////////////////////////////////////////////////////
        // EVENTS
        //
        protected void Page_Load(object sender, EventArgs e)
        {
            // Register client scripts
            this.RegisterClientScripts();

            if (!IsPostBack)
            {
                // Security check
                if (!(Convert.ToBoolean(Session["sgLFS_CWP_REHABASSESSMENT_VIEW"]) && Convert.ToBoolean(Session["sgLFS_CWP_REHABASSESSMENT_DELETE"])))
                {
                    Response.Redirect("./../../error_page.aspx?error=" + "You are not authorized to view this page. Contact your system administrator.");
                }

                // Validate query string
                if (((string)Request.QueryString["source_page"] == null) || ((string)Request.QueryString["client_id"] == null) || ((string)Request.QueryString["project_id"] == null))
                {
                    Response.Redirect("./../../error_page.aspx?error=" + "Invalid query string in ra_delete.aspx");
                }

                // Tag Page
                TagPage();

                // Prepare initial data
                // ... for client
                int currentClientId = Int32.Parse(hdfCurrentClientId.Value.ToString());
                int companyId = Int32.Parse(hdfCompanyId.Value);
                CompaniesGateway companiesGateway = new CompaniesGateway();
                companiesGateway.LoadByCompaniesId(currentClientId, companyId);
                lblTitleClientName.Text = "Client: " + companiesGateway.GetName(currentClientId);

                // ... for project
                int currentProjectId = Int32.Parse(hdfCurrentProjectId.Value.ToString());
                ProjectGateway projectGateway = new ProjectGateway();
                projectGateway.LoadByProjectId(currentProjectId);
                string name = projectGateway.GetName(currentProjectId);
                if (name.Length > 23) name = name.Substring(0, 20) + "...";
                lblTitleProjectName.Text = " > Project: " + name + " (" + projectGateway.GetProjectNumber(currentProjectId) + ") > Selected Sections";

                // If coming from
                // ... ra_navigator2.aspx
                if (Request.QueryString["source_page"] == "ra_navigator2.aspx")
                {
                    StoreNavigatorState();
                    ViewState["update"] = "no";

                    rehabAssessmentTDS = new RehabAssessmentTDS();

                    int workId = Int32.Parse(hdfWorkId.Value);

                    RehabAssessmentSectionDetails rehabAssessmentSectionDetails = new RehabAssessmentSectionDetails(rehabAssessmentTDS);
                    rehabAssessmentSectionDetails.LoadByWorkId(workId, companyId);

                    RehabAssessmentWorkDetails rehabAssessmentWorkDetails = new RehabAssessmentWorkDetails(rehabAssessmentTDS);
                    rehabAssessmentWorkDetails.LoadByWorkId(workId, companyId);

                    RehabAssessmentLateralDetails rehabAssessmentLateralDetails = new RehabAssessmentLateralDetails(rehabAssessmentTDS);
                    rehabAssessmentLateralDetails.LoadAllByWorkId(workId, companyId);

                    // Store dataset
                    Session["rehabAssessmentTDS"] = rehabAssessmentTDS;
                }

                // ... ra_summary.aspx
                if (Request.QueryString["source_page"] == "ra_summary.aspx")
                {
                    StoreNavigatorState();
                    ViewState["update"] = Request.QueryString["update"];

                    // Restore dataset
                    rehabAssessmentTDS = (RehabAssessmentTDS)Session["rehabAssessmentTDS"];
                }
            }
            else
            {
                // Restore datasets
                rehabAssessmentTDS = (RehabAssessmentTDS)Session["rehabAssessmentTDS"];
            }
        }
        protected void grdLaterals_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            Page.Validate("AddLateralsUpdate");
            if (Page.IsValid)
            {
                if (((DropDownList)grdLaterals.Rows[e.RowIndex].Cells[2].FindControl("ddlLiveEdit")).Visible == true)
                {
                    Page.Validate("AddLateralsUpdateSpecial");
                }

                if (Page.IsValid)
                {
                    int lateral = int.Parse(((Label)grdLaterals.Rows[e.RowIndex].Cells[1].FindControl("lblLateral")).Text.Trim());
                    string lateralId = ((TextBox)grdLaterals.Rows[e.RowIndex].Cells[2].FindControl("tbxLateralIdEdit")).Text.Trim();
                    string clientLateralId = ((TextBox)grdLaterals.Rows[e.RowIndex].Cells[2].FindControl("tbxClientLateralIdEdit")).Text.Trim();
                    string size = ((TextBox)grdLaterals.Rows[e.RowIndex].Cells[2].FindControl("tbxSizeEdit")).Text.Trim();

                    // Load material
                    string material = "";
                    material = ((DropDownList)grdLaterals.Rows[e.RowIndex].Cells[2].FindControl("ddlMaterialEdit")).SelectedValue.ToString().Trim();

                    // Load lateral state
                    string live = "";
                    if (((TextBox)grdLaterals.Rows[e.RowIndex].Cells[2].FindControl("tbxJlLive")).Visible == true)
                    {
                        live = "Live";
                    }
                    else
                    {
                        if (((DropDownList)grdLaterals.Rows[e.RowIndex].Cells[2].FindControl("ddlLiveEdit")).Visible == true)
                        {
                            live = ((DropDownList)grdLaterals.Rows[e.RowIndex].Cells[2].FindControl("ddlLiveEdit")).SelectedValue.Trim();
                        }
                    }

                    string videoDistance = ((TextBox)grdLaterals.Rows[e.RowIndex].Cells[2].FindControl("tbxVideoDistanceEdit")).Text.Trim();
                    string clockPosition = ((TextBox)grdLaterals.Rows[e.RowIndex].Cells[2].FindControl("tbxClockPositionEdit")).Text.Trim();
                    string distanceToCentre = ((TextBox)grdLaterals.Rows[e.RowIndex].Cells[2].FindControl("tbxDistanceToCentreEdit")).Text.Trim();
                    string timeOpened = ((TextBox)grdLaterals.Rows[e.RowIndex].Cells[2].FindControl("tbxTimeOpenedEdit")).Text.Trim();

                    // Reverse Setup calculation
                    string reverseSetup = "";

                    if (videoDistance != "")
                    {
                        Distance videoLength = new Distance(tbxVideoLength.Text.Trim());
                        Distance videoDistanceD = new Distance(videoDistance);
                        Distance reverseSetupD = videoLength - videoDistanceD;

                        switch (videoDistanceD.DistanceType)
                        {
                            case 1:
                                reverseSetup = reverseSetupD.ToStringInEng1();
                                break;
                            case 2:
                                reverseSetup = reverseSetupD.ToStringInEng2();
                                break;
                            case 3:
                                reverseSetup = reverseSetupD.ToStringInEng3();
                                break;
                            case 4:
                                reverseSetup = reverseSetupD.ToStringInMet1();
                                break;
                            case 5:
                                reverseSetup = reverseSetupD.ToStringInMil1();
                                break;
                        }
                    }

                    DateTime? reinstate = null;
                    if (((RadDatePicker)grdLaterals.Rows[e.RowIndex].Cells[2].FindControl("tkrdpReinstateEdit")).SelectedDate.HasValue)
                    {
                        reinstate = ((RadDatePicker)grdLaterals.Rows[e.RowIndex].Cells[2].FindControl("tkrdpReinstateEdit")).SelectedDate.Value;
                    }

                    string comments = ((TextBox)grdLaterals.Rows[e.RowIndex].Cells[2].FindControl("tbxCommentsEdit")).Text.Trim();
                    bool inProject = true;
                    bool inFll = true;
                    bool inJl = ((CheckBox)grdLaterals.Rows[e.RowIndex].Cells[2].FindControl("cbxJlEdit")).Checked;
                    string connectionType = ""; connectionType = ((DropDownList)grdLaterals.Rows[e.RowIndex].Cells[2].FindControl("ddlConnectionTypeEdit")).SelectedValue;
                    string mn = ""; mn = ((TextBox)grdLaterals.Rows[e.RowIndex].Cells[2].FindControl("tbxMnEdit")).Text.Trim();
                    string clientInspectionNo = ((TextBox)grdLaterals.Rows[e.RowIndex].Cells[2].FindControl("tbxClientInspectionNoEdit")).Text.Trim();
                    DateTime? v1Inspection = null;
                    if (((RadDatePicker)grdLaterals.Rows[e.RowIndex].Cells[2].FindControl("tkrdpV1InspectionEdit")).SelectedDate.HasValue)
                    {
                        v1Inspection = ((RadDatePicker)grdLaterals.Rows[e.RowIndex].Cells[2].FindControl("tkrdpV1InspectionEdit")).SelectedDate.Value;
                    }
                    bool requiredRoboticPrep = ((CheckBox)grdLaterals.Rows[e.RowIndex].Cells[2].FindControl("ckbxRequiresRoboticPrepEdit")).Checked;

                    DateTime? requiredRoboticPrepDate = null;
                    if (((RadDatePicker)grdLaterals.Rows[e.RowIndex].Cells[2].FindControl("tkrdpRequiresRoboticPrepDateEdit")).SelectedDate.HasValue)
                    {
                        requiredRoboticPrepDate = ((RadDatePicker)grdLaterals.Rows[e.RowIndex].Cells[2].FindControl("tkrdpRequiresRoboticPrepDateEdit")).SelectedDate.Value;
                    }

                    bool holdClientIssue = ((CheckBox)grdLaterals.Rows[e.RowIndex].Cells[2].FindControl("ckbxHoldClientIssueEdit")).Checked;
                    bool holdLFSIssue = ((CheckBox)grdLaterals.Rows[e.RowIndex].Cells[2].FindControl("ckbxHoldLFSIssueEdit")).Checked;
                    bool lineLateral = inJl;
                    string flange = ((DropDownList)grdLaterals.Rows[e.RowIndex].Cells[2].FindControl("ddlFlangeEdit")).SelectedValue;

                    bool dyeTestReq = ((CheckBox)grdLaterals.Rows[e.RowIndex].Cells[2].FindControl("ckbxDyeTestReqEdit")).Checked;
                    DateTime? dyeTestComplete = null;
                    if (((RadDatePicker)grdLaterals.Rows[e.RowIndex].Cells[2].FindControl("tkrdpDyeTestCompleteEdit")).SelectedDate.HasValue)
                    {
                        dyeTestComplete = ((RadDatePicker)grdLaterals.Rows[e.RowIndex].Cells[2].FindControl("tkrdpDyeTestCompleteEdit")).SelectedDate.Value;
                    }

                    string contractYear = ((TextBox)grdLaterals.Rows[e.RowIndex].Cells[2].FindControl("tbxContractYearEdit")).Text.Trim();

                    // Update
                    RehabAssessmentLateralDetails lateralModel = new RehabAssessmentLateralDetails(rehabAssessmentTDS);
                    lateralModel.Update(lateral, lateralId, size, material, live, videoDistance, clockPosition, distanceToCentre, timeOpened, reverseSetup, reinstate, comments, inProject, clientLateralId, inFll, inJl, connectionType, mn, clientInspectionNo, v1Inspection, requiredRoboticPrep, requiredRoboticPrepDate, holdClientIssue, holdLFSIssue, lineLateral, flange, dyeTestReq, dyeTestComplete, contractYear);

                    tbxLaterals.Text = lateralModel.GetTotalLaterals().ToString();
                    tbxLiveLaterals.Text = lateralModel.GetLiveLaterals().ToString();

                    // Store dataset
                    Session["rehabAssessmentTDS"] = rehabAssessmentTDS;

                    // Update JL lateral issues
                    FLLateralsSave(lateralId, requiredRoboticPrep, requiredRoboticPrepDate, holdClientIssue, holdLFSIssue, dyeTestReq, dyeTestComplete, contractYear);
                }
                else
                {
                    e.Cancel = true;
                }
            }
            else
            {
                e.Cancel = true;
            }
        }
        // ////////////////////////////////////////////////////////////////////////
        // EVENTS
        //
        protected void Page_Load(object sender, EventArgs e)
        {
            // Register client scripts
            this.RegisterClientScripts();

            bool isFromTabClick = false;

            if (!IsPostBack)
            {
                if (!isFromTabClick)
                {
                    // Security check
                    if (!(Convert.ToBoolean(Session["sgLFS_CWP_REHABASSESSMENT_VIEW"]) && Convert.ToBoolean(Session["sgLFS_CWP_REHABASSESSMENT_EDIT"])))
                    {
                        Response.Redirect("./../../error_page.aspx?error=" + "You are not authorized to view this page. Contact your system administrator.");
                    }

                    // Validate query string
                    if (((string)Request.QueryString["source_page"] == null) || ((string)Request.QueryString["client_id"] == null) || ((string)Request.QueryString["project_id"] == null) || ((string)Request.QueryString["asset_id"] == null) || ((string)Request.QueryString["active_tab"] == null))
                    {
                        Response.Redirect("./../../error_page.aspx?error=" + "Invalid query string in ra_edit.aspx");
                    }

                    // Tag Page
                    TagPage();

                    // Prepare initial data
                    Session.Remove("raAddLateralsNewDummy");
                    Session.Remove("materialInformationTDS");

                    materialInformationTDS = new MaterialInformationTDS();

                    // If coming from
                    int companyId = Int32.Parse(hdfCompanyId.Value.Trim());
                    int currentProjectId = Int32.Parse(hdfCurrentProjectId.Value.ToString());
                    int assetId = Int32.Parse(hdfAssetId.Value.Trim());
                    int workId = Int32.Parse(hdfWorkId.Value.Trim());
                    int workIdFll = Int32.Parse(hdfWorkIdFll.Value.Trim());
                    string workType = hdfWorkType.Value;

                    // ... ra_navigator2.aspx
                    if (Request.QueryString["source_page"] == "ra_navigator2.aspx")
                    {
                        StoreNavigatorState();
                        ViewState["update"] = "no";

                        // ... Set initial tab
                        if ((string)Session["dialogOpenedRa"] != "1")
                        {
                            hdfActiveTab.Value = Request.QueryString["active_tab"];

                            rehabAssessmentTDS = new RehabAssessmentTDS();

                            RehabAssessmentSectionDetails rehabAssessmentSectionDetails = new RehabAssessmentSectionDetails(rehabAssessmentTDS);
                            rehabAssessmentSectionDetails.LoadByWorkId(workId, companyId);

                            RehabAssessmentWorkDetails rehabAssessmentWorkDetails = new RehabAssessmentWorkDetails(rehabAssessmentTDS);
                            rehabAssessmentWorkDetails.LoadByWorkId(workId, companyId);

                            RehabAssessmentLateralDetails rehabAssessmentLateralDetails = new RehabAssessmentLateralDetails(rehabAssessmentTDS);
                            rehabAssessmentLateralDetails.LoadForEdit(workIdFll, assetId, companyId, currentProjectId);
                        }
                        else
                        {
                            hdfActiveTab.Value = (string)Session["activeTabRa"];

                            // Restore dataset
                            rehabAssessmentTDS = (RehabAssessmentTDS)Session["rehabAssessmentTDS"];
                        }

                        // Store dataset
                        Session["rehabAssessmentTDS"] = rehabAssessmentTDS;
                    }

                    // ... ra_summary.aspx or ra_edit.aspx
                    if ((Request.QueryString["source_page"] == "ra_summary.aspx") || (Request.QueryString["source_page"] == "ra_edit.aspx"))
                    {
                        StoreNavigatorState();
                        ViewState["update"] = Request.QueryString["update"];

                        // ... Set initial tab
                        if ((string)Session["dialogOpenedRa"] != "1")
                        {
                            hdfActiveTab.Value = Request.QueryString["active_tab"];
                        }
                        else
                        {
                            hdfActiveTab.Value = (string)Session["activeTabRa"];
                        }

                        if (ViewState["update"].ToString().Trim() == "yes")
                        {
                            rehabAssessmentTDS = new RehabAssessmentTDS();

                            RehabAssessmentSectionDetails rehabAssessmentSectionDetails = new RehabAssessmentSectionDetails(rehabAssessmentTDS);
                            rehabAssessmentSectionDetails.LoadByWorkId(workId, companyId);

                            RehabAssessmentWorkDetails rehabAssessmentWorkDetails = new RehabAssessmentWorkDetails(rehabAssessmentTDS);
                            rehabAssessmentWorkDetails.LoadByWorkId(workId, companyId);

                            RehabAssessmentLateralDetails rehabAssessmentLateralDetails = new RehabAssessmentLateralDetails(rehabAssessmentTDS);
                            rehabAssessmentLateralDetails.LoadForEdit(workIdFll, assetId, companyId, currentProjectId);

                            // Store dataset
                            Session["rehabAssessmentTDS"] = rehabAssessmentTDS;
                        }

                        // Restore dataset
                        rehabAssessmentTDS = (RehabAssessmentTDS)Session["rehabAssessmentTDS"];
                    }

                    // Prepare initial data
                    lblMissingData.Visible = false;

                    // Set initial tab
                    int activeTab = Int32.Parse(hdfActiveTab.Value);
                    tcRaDetails.ActiveTabIndex = activeTab;

                    // ... for client
                    int currentClientId = Int32.Parse(hdfCurrentClientId.Value.ToString());
                    CompaniesGateway companiesGateway = new CompaniesGateway();
                    companiesGateway.LoadByCompaniesId(currentClientId, companyId);
                    lblTitleClientName.Text = "Client: " + companiesGateway.GetName(currentClientId);

                    // ... for project
                    ProjectGateway projectGateway = new ProjectGateway();
                    projectGateway.LoadByProjectId(currentProjectId);
                    string name = projectGateway.GetName(currentProjectId);
                    if (name.Length > 23) name = name.Substring(0, 20) + "...";
                    lblTitleProjectName.Text = " > Project: " + name + " (" + projectGateway.GetProjectNumber(currentProjectId) + ") > Selected Section";

                    // ... Data for current work
                    LoadRehabAssessmentData(currentProjectId, assetId, companyId);

                    // Databind
                    Page.DataBind();
                    ((DropDownList)grdLaterals.FooterRow.FindControl("ddlNewMaterial")).SelectedIndex = 0;

                    // For usmh, dsmh autocomplete
                    string provinceId_ = "0"; if (hdfProvinceId.Value != "") provinceId_ = hdfProvinceId.Value;
                    string countyId_ = "0"; if (hdfCountyId.Value != "") countyId_ = hdfCountyId.Value;
                    string cityId_ = "0"; if (hdfCityId.Value != "") cityId_ = hdfCityId.Value;

                    aceUsmh.ContextKey = hdfCountryId.Value + "," + provinceId_ + "," + countyId_ + "," + cityId_ + "," + hdfCompanyId.Value;
                    aceDsmh.ContextKey = hdfCountryId.Value + "," + provinceId_ + "," + countyId_ + "," + cityId_ + "," + hdfCompanyId.Value;

                    // Load Materials
                    MaterialInformationGateway materialInformationGateway = new MaterialInformationGateway(materialInformationTDS);
                    materialInformationGateway.LoadAllByAssetId(assetId, companyId);

                    materialInformation = materialInformationTDS.MaterialInformation;
                    Session["materialInformationTDS"] = materialInformationTDS;
                }
            }
            else
            {
                // Restore datasets
                rehabAssessmentTDS = (RehabAssessmentTDS)Session["rehabAssessmentTDS"];
                flatSectionJlTDSForRA = (FlatSectionJlTDS)Session["flatSectionJlTDSForRA"];
                materialInformationTDS = (MaterialInformationTDS)Session["materialInformationTDS"];
                materialInformation = materialInformationTDS.MaterialInformation;

                // Set initial tab
                int activeTab = Int32.Parse(hdfActiveTab.Value);
                tcRaDetails.ActiveTabIndex = activeTab;
            }
        }
        protected void cvMeasuredFromMH_ServerValidate(object source, ServerValidateEventArgs args)
        {
            int assetId = Int32.Parse(hdfAssetId.Value);
            int companyId = Int32.Parse(hdfCompanyId.Value);
            int workId = Int32.Parse(hdfWorkIdFll.Value);
            int workIdFll = Int32.Parse(hdfWorkIdFll.Value);
            int currentProjectId = Int32.Parse(hdfCurrentProjectId.Value.ToString());

            RehabAssessmentLateralDetails raLateralDetails = new RehabAssessmentLateralDetails();
            raLateralDetails.LoadForEdit(workIdFll, assetId, companyId, currentProjectId);

            if (raLateralDetails.Table.Rows.Count > 0)
            {
                args.IsValid = true;
            }
            else
            {
                if (ddlM1DataMeasuredFromMh.SelectedValue == "")
                {
                    args.IsValid = false;
                }
                else
                {
                    args.IsValid = true;
                }
            }
        }
        protected void grdLaterals_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            // Laterals Gridview, if the gridview is edition mode
            if (grdLaterals.EditIndex >= 0)
            {
                grdLaterals.UpdateRow(grdLaterals.EditIndex, true);
            }

            // Delete laterals
            int lateral = int.Parse(((Label)grdLaterals.Rows[e.RowIndex].Cells[1].FindControl("lblLateral")).Text);
            RehabAssessmentLateralDetails model = new RehabAssessmentLateralDetails(rehabAssessmentTDS);

            // Delete lateral
            model.Delete(lateral);

            tbxLaterals.Text = model.GetTotalLaterals().ToString();
            tbxLiveLaterals.Text = model.GetLiveLaterals().ToString();

            // Store dataset
            Session["rehabAssessmentTDS"] = rehabAssessmentTDS;
        }
        protected void cvLateralId_ServerValidate(object source, ServerValidateEventArgs args)
        {
            RehabAssessmentLateralDetails model = new RehabAssessmentLateralDetails(rehabAssessmentTDS);

            // Initialize
            CustomValidator cvLateralId = (CustomValidator)source;
            args.IsValid = true;

            // Verify in this step
            if (model.ExistsByLateralId(args.Value))
            {
                cvLateralId.Text = "Duplicated lateral. (you already have this lateral here)";
                args.IsValid = false;
            }
        }
        protected void cvLateralsMaxNumber_ServerValidate(object source, ServerValidateEventArgs args)
        {
            // Get Measured From Mh value
            int assetId = Int32.Parse(hdfAssetId.Value);
            int companyId = Int32.Parse(hdfCompanyId.Value);
            int workId = Int32.Parse(hdfWorkId.Value);
            int workIdFll = Int32.Parse(hdfWorkIdFll.Value);
            int currentProjectId = Int32.Parse(hdfCurrentProjectId.Value.ToString());
            string measuredFromMh = "";

            RehabAssessmentLateralDetails raLateralDetails = new RehabAssessmentLateralDetails();
            raLateralDetails.LoadForEdit(workIdFll, assetId, companyId, currentProjectId);

            if (raLateralDetails.Table.Rows.Count > 0)
            {
                measuredFromMh = "USMH";
            }
            else
            {
                measuredFromMh = ddlM1DataMeasuredFromMh.SelectedValue;
            }

            // Generate increment
            RehabAssessmentLateralDetails rehabAssessmentLateraldetails = new RehabAssessmentLateralDetails(rehabAssessmentTDS);

            if (measuredFromMh == "USMH" || measuredFromMh == "")
            {
                if (rehabAssessmentLateraldetails.GetMaxLateralId2() == "A[") args.IsValid = false; else args.IsValid = true;
            }
            else
            {
                if (measuredFromMh == "DSMH")
                {
                    if (rehabAssessmentLateraldetails.GetMinLateralId2() == "@") args.IsValid = false; else args.IsValid = true;
                }
            }
        }
        private void GrdRaAddLateralsNewAdd()
        {
            if (ValidateLateralFooter())
            {
                Page.Validate("AddLateralsAdd");
                if (Page.IsValid)
                {
                    string size = ((TextBox)grdLaterals.FooterRow.FindControl("tbxNewSize")).Text.Trim();
                    string material = ((DropDownList)grdLaterals.FooterRow.FindControl("ddlNewMaterial")).SelectedValue.ToString().Trim();
                    string live = ((DropDownList)grdLaterals.FooterRow.FindControl("ddlNewLive")).SelectedValue.Trim();
                    string videoDistance = ((TextBox)grdLaterals.FooterRow.FindControl("tbxNewVideoDistance")).Text.Trim();
                    string clockPosition = ((TextBox)grdLaterals.FooterRow.FindControl("tbxNewClockPosition")).Text.Trim();
                    string distanceToCentre = ((TextBox)grdLaterals.FooterRow.FindControl("tbxNewDistanceToCentre")).Text.Trim();
                    string timeOpened = "";
                    DateTime? reinstate = null;
                    string comments = ((TextBox)grdLaterals.FooterRow.FindControl("tbxNewComments")).Text.Trim();

                    // Reverse Setup calculation
                    string reverseSetup = "";
                    if (videoDistance != "")
                    {
                        Distance videoDistanceD = new Distance(videoDistance);
                        Distance videoLength = new Distance(tbxVideoLength.Text.Trim());

                        Distance reverseSetupD = videoLength - videoDistanceD;
                        switch (videoDistanceD.DistanceType)
                        {
                            case 1:
                                reverseSetup = reverseSetupD.ToStringInEng1();
                                break;
                            case 2:
                                reverseSetup = reverseSetupD.ToStringInEng2();
                                break;
                            case 3:
                                reverseSetup = reverseSetupD.ToStringInEng3();
                                break;
                            case 4:
                                reverseSetup = reverseSetupD.ToStringInMet1();
                                break;
                            case 5:
                                reverseSetup = reverseSetupD.ToStringInMil1();
                                break;
                        }
                    }

                    bool inProject = true;
                    bool inFll = true;
                    bool inJl = ((CheckBox)grdLaterals.FooterRow.FindControl("cbxNewJl")).Checked;

                    int companyId = Int32.Parse(hdfCompanyId.Value);
                    string lateralId = GetLateralIdIncrement();
                    string clientLateralId = ((TextBox)grdLaterals.FooterRow.FindControl("tbxNewClientLateralId")).Text.Trim();
                    string connectionType = ""; connectionType = ((DropDownList)grdLaterals.FooterRow.FindControl("ddlNewConnectionType")).SelectedValue;
                    string mn = ((TextBox)grdLaterals.FooterRow.FindControl("tbxNewMn")).Text.Trim();
                    string clientInspectionNo = ((TextBox)grdLaterals.FooterRow.FindControl("tbxNewClientInspectionNo")).Text.Trim();
                    DateTime? v1Inspection = null; if (((RadDatePicker)grdLaterals.FooterRow.FindControl("tkrdpNewV1Inspection")).SelectedDate.HasValue) v1Inspection = ((RadDatePicker)grdLaterals.FooterRow.FindControl("tkrdpNewV1Inspection")).SelectedDate.Value;
                    bool requiresRoboticPrep = ((CheckBox)grdLaterals.FooterRow.FindControl("ckbxRequiresRoboticPrepNew")).Checked;
                    DateTime? requiresRoboticPrepDate = null;
                    if (((RadDatePicker)grdLaterals.FooterRow.FindControl("tkrdpRequiresRoboticPrepDateNew")).SelectedDate.HasValue)
                    {
                        requiresRoboticPrepDate = ((RadDatePicker)grdLaterals.FooterRow.FindControl("tkrdpRequiresRoboticPrepDateNew")).SelectedDate.Value;
                    }

                    bool holdClientIssue = ((CheckBox)grdLaterals.FooterRow.FindControl("ckbxHoldClientIssueNew")).Checked;
                    bool holdLFSIssue = ((CheckBox)grdLaterals.FooterRow.FindControl("ckbxHoldLFSIssueNew")).Checked;
                    bool lineLateral = inJl;
                    string flange = ((DropDownList)grdLaterals.FooterRow.FindControl("ddlFlangeNew")).SelectedValue;
                    bool dyeTestReq = ((CheckBox)grdLaterals.FooterRow.FindControl("ckbxDyeTestReqNew")).Checked;
                    DateTime? dyeTestComplete = null; if (((RadDatePicker)grdLaterals.FooterRow.FindControl("tkrdpDyeTestCompleteNew")).SelectedDate.HasValue) dyeTestComplete = ((RadDatePicker)grdLaterals.FooterRow.FindControl("tkrdpDyeTestCompleteNew")).SelectedDate.Value;
                    string contractYear =((TextBox)grdLaterals.FooterRow.FindControl("tbxNewContractYear")).Text.Trim();

                    // Insert
                    RehabAssessmentLateralDetails model = new RehabAssessmentLateralDetails(rehabAssessmentTDS);
                    model.Insert(videoDistance, clockPosition, distanceToCentre, timeOpened, reverseSetup, reinstate, comments, lateralId, size, material, false, companyId, inProject, live, clientLateralId, inFll, inJl, connectionType, mn, clientInspectionNo, v1Inspection, requiresRoboticPrep, requiresRoboticPrepDate, holdClientIssue, holdLFSIssue, lineLateral, flange, dyeTestReq, dyeTestComplete, contractYear);

                    // Store datasets
                    Session.Remove("raAddLateralsNewDummy");
                    Session["rehabAssessmentTDS"] = rehabAssessmentTDS;
                    grdLaterals.DataBind();
                    grdLaterals.PageIndex = grdLaterals.PageCount - 1;

                    tbxLaterals.Text = model.GetTotalLaterals().ToString();
                    tbxLiveLaterals.Text = model.GetLiveLaterals().ToString();
                }
            }
        }
        private void UpdateDatabase()
        {
            // Get ids & location
            int projectId = Int32.Parse(hdfCurrentProjectId.Value.Trim());
            ProjectGateway projectGateway = new ProjectGateway();
            projectGateway.LoadByProjectId(projectId);

            Int64 countryId = projectGateway.GetCountryID(projectId);
            Int64? provinceId = null; if (projectGateway.GetProvinceID(projectId).HasValue) provinceId = (Int64)projectGateway.GetProvinceID(projectId);
            Int64? countyId = null; if (projectGateway.GetCountyID(projectId).HasValue) countyId = (Int64)projectGateway.GetCountyID(projectId);
            Int64? cityId = null; if (projectGateway.GetCityID(projectId).HasValue) cityId = (Int64)projectGateway.GetCityID(projectId);

            string workType = hdfWorkType.Value.Trim();
            int companyId = Int32.Parse(hdfCompanyId.Value);
            int workId = Int32.Parse(hdfWorkId.Value);
            int workIdFll = Int32.Parse(hdfWorkIdFll.Value);
            int sectionAssetId = Int32.Parse(hdfAssetId.Value);

            bool isNewMeasuredFromDsmh = false;

            RehabAssessmentLateralDetails raLateralDetails = new RehabAssessmentLateralDetails();
            raLateralDetails.LoadForEdit(workIdFll, sectionAssetId, companyId, projectId);

            if (raLateralDetails.Table.Rows.Count == 0)
            {
                if (ddlM1DataMeasuredFromMh.SelectedValue == "DSMH")
                {
                    isNewMeasuredFromDsmh = true;
                    RehabAssessmentLateralDetails raaLateralDetails = new RehabAssessmentLateralDetails(rehabAssessmentTDS);
                    raaLateralDetails.ModifyLateralId();
                }
            }

            DB.Open();
            DB.BeginTransaction();
            try
            {
                // Save lateral details
                bool roboticPrepCompleted = ckbxPrepDataRoboticPrepCompleted.Checked;
                DateTime? roboticPrepCompletedCompleted = null; if (tkrdpPrepDataRoboticPrepCompletedDate.SelectedDate.HasValue) roboticPrepCompletedCompleted = tkrdpPrepDataRoboticPrepCompletedDate.SelectedDate.Value;

                RehabAssessmentLateralDetails rehabAssessmentLateralDetails = new RehabAssessmentLateralDetails(rehabAssessmentTDS);
                rehabAssessmentLateralDetails.Save(workIdFll, projectId, sectionAssetId, countryId, provinceId, countyId, cityId, tbxVideoLength.Text.Trim(), companyId, isNewMeasuredFromDsmh, roboticPrepCompleted, roboticPrepCompletedCompleted);

                // Save section details
                RehabAssessmentSectionDetails rehabAssessmentSectionDetails = new RehabAssessmentSectionDetails(rehabAssessmentTDS);
                rehabAssessmentSectionDetails.Save(countryId, provinceId, countyId, cityId, projectId, companyId);

                // Save work details
                RehabAssessmentWorkDetails rehabAssessmentWorkDetails = new RehabAssessmentWorkDetails(rehabAssessmentTDS);
                rehabAssessmentWorkDetails.Save(countryId, provinceId, countyId, cityId, projectId, companyId, sectionAssetId);

                // Save material details
                string newMaterial = ddlM1DataMaterial.SelectedValue;

                if (ddlM1DataMaterial.SelectedIndex > 0)
                {
                    LfsAssetSewerLateralGateway lfsAssetSewertLateralGateway = new LfsAssetSewerLateralGateway(null);
                    if (!lfsAssetSewertLateralGateway.IsUsedInMaterials(sectionAssetId, newMaterial, companyId))
                    {
                        MaterialInformation materialInformation = new MaterialInformation(materialInformationTDS);
                        materialInformation.Save(companyId);
                    }
                }

                DB.CommitTransaction();

                // Store datasets
                rehabAssessmentTDS.AcceptChanges();
                Session["rehabAssessmentTDS"] = rehabAssessmentTDS;

                materialInformationTDS.AcceptChanges();
                Session["materialInformationTDS"] = materialInformationTDS;
            }
            catch (Exception ex)
            {
                DB.RollbackTransaction();

                string url = string.Format("./../../error_page.aspx?error={0}", ex.Message.Replace('\n', ' '));
                Response.Redirect(url);
            }
        }
        private string GetLateralIdIncrement()
        {
            // Get Measured From Mh value
            int assetId = Int32.Parse(hdfAssetId.Value);
            int companyId = Int32.Parse(hdfCompanyId.Value);
            int workId = Int32.Parse(hdfWorkId.Value);
            int workIdFll = Int32.Parse(hdfWorkIdFll.Value);
            int currentProjectId = Int32.Parse(hdfCurrentProjectId.Value.ToString());
            string measuredFromMh = "";

            RehabAssessmentLateralDetails raLateralDetails = new RehabAssessmentLateralDetails();
            raLateralDetails.LoadForEdit(workIdFll, assetId, companyId, currentProjectId);

            if (raLateralDetails.Table.Rows.Count > 0)
            {
                measuredFromMh = "USMH";
            }
            else
            {
                measuredFromMh = ddlM1DataMeasuredFromMh.SelectedValue;
            }

            // Generate increment
            string lateralIdIncrement = "";
            RehabAssessmentLateralDetails rehabAssessmentLateraldetails = new RehabAssessmentLateralDetails(rehabAssessmentTDS);

            if (measuredFromMh == "USMH" || measuredFromMh == "")
            {
                lateralIdIncrement = rehabAssessmentLateraldetails.GetMaxLateralId2();
            }
            else
            {
                if (measuredFromMh == "DSMH")
                {
                    lateralIdIncrement =rehabAssessmentLateraldetails.GetMinLateralId2();
                }
            }

            return "RA-"+lateralIdIncrement;
        }
        private bool Apply()
        {
            // Validate data
            bool validData = true;

            validData = ValidatePage();

            if (validData)
            {
                // Save Lateral data
                GrdRaAddLateralsNewAdd();

                // Save data
                int companyId = Int32.Parse(hdfCompanyId.Value);
                int assetId = Int32.Parse(hdfAssetId.Value);
                int workId = Int32.Parse(hdfWorkId.Value);
                int workIdFll = Int32.Parse(hdfWorkIdFll.Value);
                int currentProjectId = Int32.Parse(hdfCurrentProjectId.Value.ToString());

                // Get Section Details
                // ... RehabAssessmentSectionDetails data
                string newStreet = ""; if (tbxStreet.Text != "") newStreet = tbxStreet.Text.Trim();
                string newUsmh = ""; if (tbxUSMH.Text != "") newUsmh = tbxUSMH.Text.Trim();
                string newDsmh = ""; if (tbxDSMH.Text != "") newDsmh = tbxDSMH.Text.Trim();
                string newMapSize = ""; if (tbxMapSize.Text != "") newMapSize = tbxMapSize.Text.Trim();
                string newSize = ""; if (tbxConfirmedSize.Text != "") newSize = tbxConfirmedSize.Text.Trim();
                string newThickness = ""; if (ddlThickness.SelectedValue != "") newThickness = ddlThickness.SelectedValue;
                string newMapLength = ""; if (tbxMapLength.Text != "") newMapLength = tbxMapLength.Text.Trim();

                string newSteelTapeThroughSewer = "";
                string newLength = "";
                if (tbxM1DataSteelTapeThroughSewer.Text != "")
                {
                    newSteelTapeThroughSewer = tbxM1DataSteelTapeThroughSewer.Text.Trim();
                    newLength = tbxM1DataSteelTapeThroughSewer.Text.Trim();
                }

                int? newLaterals = null; if (tbxLaterals.Text != "") newLaterals = Int32.Parse(tbxLaterals.Text.Trim());
                int? newLiveLaterals = null; if (tbxLiveLaterals.Text != "") newLiveLaterals = Int32.Parse(tbxLiveLaterals.Text.Trim());

                // Get m1 data
                // ... assetSewerSection data
                string newUsmhDepth = ""; if ((tbxM1DataUsmhDepth.Text != "") && (tbxUSMH.Text != "")) newUsmhDepth = tbxM1DataUsmhDepth.Text.Trim();
                string newDsmhDepth = ""; if ((tbxM1DataDsmhDepth.Text != "") && (tbxDSMH.Text != "")) newDsmhDepth = tbxM1DataDsmhDepth.Text.Trim();

                // ... lfsAssetSewerSection data
                string newUsmhMouth12 = ""; if ((tbxM1DataUsmhMouth12.Text != "") && (tbxUSMH.Text != "")) newUsmhMouth12 = tbxM1DataUsmhMouth12.Text.Trim();
                string newUsmhMouth1 = ""; if ((tbxM1DataUsmhMouth1.Text != "") && (tbxUSMH.Text != "")) newUsmhMouth1 = tbxM1DataUsmhMouth1.Text.Trim();
                string newUsmhMouth2 = ""; if ((tbxM1DataUsmhMouth2.Text != "") && (tbxUSMH.Text != "")) newUsmhMouth2 = tbxM1DataUsmhMouth2.Text.Trim();
                string newUsmhMouth3 = ""; if ((tbxM1DataUsmhMouth3.Text != "") && (tbxUSMH.Text != "")) newUsmhMouth3 = tbxM1DataUsmhMouth3.Text.Trim();
                string newUsmhMouth4 = ""; if ((tbxM1DataUsmhMouth4.Text != "") && (tbxUSMH.Text != "")) newUsmhMouth4 = tbxM1DataUsmhMouth4.Text.Trim();
                string newUsmhMouth5 = ""; if ((tbxM1DataUsmhMouth5.Text != "") && (tbxUSMH.Text != "")) newUsmhMouth5 = tbxM1DataUsmhMouth5.Text.Trim();
                string newDsmhMouth12 = ""; if ((tbxM1DataDsmhMouth12.Text != "") && (tbxDSMH.Text != "")) newDsmhMouth12 = tbxM1DataDsmhMouth12.Text.Trim();
                string newDsmhMouth1 = ""; if ((tbxM1DataDsmhMouth1.Text != "") && (tbxDSMH.Text != "")) newDsmhMouth1 = tbxM1DataDsmhMouth1.Text.Trim();
                string newDsmhMouth2 = ""; if ((tbxM1DataDsmhMouth2.Text != "") && (tbxDSMH.Text != "")) newDsmhMouth2 = tbxM1DataDsmhMouth2.Text.Trim();
                string newDsmhMouth3 = ""; if ((tbxM1DataDsmhMouth3.Text != "") && (tbxDSMH.Text != "")) newDsmhMouth3 = tbxM1DataDsmhMouth3.Text.Trim();
                string newDsmhMouth4 = ""; if ((tbxM1DataDsmhMouth4.Text != "") && (tbxDSMH.Text != "")) newDsmhMouth4 = tbxM1DataDsmhMouth4.Text.Trim();
                string newDsmhMouth5 = ""; if ((tbxM1DataDsmhMouth5.Text != "") && (tbxDSMH.Text != "")) newDsmhMouth5 = tbxM1DataDsmhMouth5.Text.Trim();
                string newGeneralSubArea = ""; if (tbxGeneralSubArea.Text != "") newGeneralSubArea = tbxGeneralSubArea.Text.Trim();

                // ... assetSewerMH Data
                string newUsmhAddress = ""; if (tbxM1DataUsmhAddress.Text != "") newUsmhAddress = tbxM1DataUsmhAddress.Text.Trim();
                string newDsmhAddress = ""; if (tbxM1DataDsmhAddress.Text != "") newDsmhAddress = tbxM1DataDsmhAddress.Text.Trim();

                // Update section details
                RehabAssessmentSectionDetails rehabAssessmentSectionDetails = new RehabAssessmentSectionDetails(rehabAssessmentTDS);
                rehabAssessmentSectionDetails.Update(workId, assetId, newStreet, newMapSize, newSize, newMapLength, newLength, newLaterals, newLiveLaterals, newUsmhDepth, newDsmhDepth, newSteelTapeThroughSewer, newUsmhMouth12, newUsmhMouth1, newUsmhMouth2, newUsmhMouth3, newUsmhMouth4, newUsmhMouth5, newDsmhMouth12, newDsmhMouth1, newDsmhMouth2, newDsmhMouth3, newDsmhMouth4, newDsmhMouth5, newUsmh, newDsmh, newUsmhAddress, newDsmhAddress, newGeneralSubArea, newThickness);

                // Get GeneralData
                // ... FullLengthLining Data
                string newGeneralClientId = ""; if (tbxGeneralClientId.Text != "") newGeneralClientId = tbxGeneralClientId.Text.Trim();

                // ... Rehab Assessment Data
                DateTime? newPreFlushDate = null; if (tkrdpGeneralPreFlushDate.SelectedDate.HasValue) newPreFlushDate = tkrdpGeneralPreFlushDate.SelectedDate.Value;
                DateTime? newPreVideoDate = null; if (tkrdpGeneralPreVideoDate.SelectedDate.HasValue) newPreVideoDate = tkrdpGeneralPreVideoDate.SelectedDate.Value;

                // ... Prep Data
                int? newPrepDataCXIsRemoved = null; if (tbxPrepDataCXIsRemoved.Text != "") newPrepDataCXIsRemoved = Int32.Parse(tbxPrepDataCXIsRemoved.Text.Trim());
                DateTime? newPrepDataP1Date = null; if (tkrdpPrepDataP1Date.SelectedDate.HasValue) newPrepDataP1Date = tkrdpPrepDataP1Date.SelectedDate.Value;
                bool newRoboticPrepCompleted = ckbxPrepDataRoboticPrepCompleted.Checked;
                DateTime? newRoboticPrepCompletedDate = null; if (tkrdpPrepDataRoboticPrepCompletedDate.SelectedDate.HasValue) newRoboticPrepCompletedDate = tkrdpPrepDataRoboticPrepCompletedDate.SelectedDate.Value;
                bool newP1Completed = ckbxPrepDataP1Completed.Checked;

                // ... M1 Data
                DateTime? newM1Date = null; if (tkrdpM1DataM1Date.SelectedDate.HasValue) newM1Date = tkrdpM1DataM1Date.SelectedDate.Value;
                string newMeasurementsTakenBy = ""; if (tbxM1DataMeasurementsTakenBy.Text != "") newMeasurementsTakenBy = tbxM1DataMeasurementsTakenBy.Text.Trim();
                string newTrafficControl = ddlM1DataTrafficControl.SelectedValue;
                string newSiteDetails = ""; if (ddlM1DataSiteDetails.SelectedValue != "(Select)") newSiteDetails = ddlM1DataSiteDetails.SelectedValue;
                bool newPipeSizeChange = ckbxM1DataPipeSizeChange.Checked;
                bool newStandardByPass = ckbxM1DataStandardBypass.Checked;
                string newStandardBypassComments = ""; if (tbxM1DataStandardBypassComments.Text != "") newStandardBypassComments = tbxM1DataStandardBypassComments.Text.Trim();
                string newTrafficControlDetails = ""; if (tbxM1DataTrafficControlDetails.Text != "") newTrafficControlDetails = tbxM1DataTrafficControlDetails.Text.Trim();
                string newMaterial = ddlM1DataMaterial.SelectedValue;
                string newMeasurementType = ddlM1DataMeasurementType.SelectedValue;
                string newMeasuredFromMh = ""; if (tbxM1DataMeasuredFromMh.Visible) newMeasuredFromMh = tbxM1DataMeasuredFromMh.Text; else newMeasuredFromMh = ddlM1DataMeasuredFromMh.SelectedValue;
                string newVideoDoneFromMh = ""; if (tbxM1DataVideoDoneFromMh.Visible) newVideoDoneFromMh = tbxM1DataVideoDoneFromMh.Text; else newVideoDoneFromMh = ddlM1DataVideoDoneFromMh.SelectedValue;
                string newVideoDoneToMh = ""; if (tbxM1DataVideoDoneToMh.Visible) newVideoDoneToMh = tbxM1DataVideoDoneToMh.Text; else newVideoDoneToMh = ddlM1DataVideoDoneToMh.SelectedValue;
                string newAccessType = ""; if (ddlM1DataAccessType.SelectedValue != "(Select)") newAccessType = ddlM1DataAccessType.SelectedValue;

                // ... M2 Data (Video Length)
                string newVideoDistanceM2 = tbxVideoLength.Text.Trim();

                // ... Update work details
                RehabAssessmentWorkDetails rehabAssessmentWorkDetails = new RehabAssessmentWorkDetails(rehabAssessmentTDS);
                rehabAssessmentWorkDetails.Update(workId, workIdFll, newGeneralClientId, newPrepDataP1Date, newM1Date, newPrepDataCXIsRemoved, newRoboticPrepCompleted, newRoboticPrepCompletedDate, newMeasurementsTakenBy, newTrafficControl, newSiteDetails, newPipeSizeChange, newStandardByPass, newStandardBypassComments, newTrafficControlDetails, newMaterial, newMeasurementType, newMeasuredFromMh, newVideoDoneFromMh, newVideoDoneToMh, newVideoDistanceM2, newPreVideoDate, newPreFlushDate, newAccessType, newP1Completed);

                if (ddlM1DataMaterial.SelectedIndex > 0)
                {
                    LfsAssetSewerLateralGateway lfsAssetSewertLateralGateway = new LfsAssetSewerLateralGateway(null);
                    if (!lfsAssetSewertLateralGateway.IsUsedInMaterials(assetId, newMaterial, companyId))
                    {
                        MaterialInformation model = new MaterialInformation(materialInformationTDS);
                        model.Insert(assetId, newMaterial, DateTime.Now, false, companyId, false);
                    }
                }

                // Store datasets
                Session["rehabAssessmentTDS"] = rehabAssessmentTDS;
                Session["materialInformationTDS"] = materialInformationTDS;

                // Update database
                UpdateDatabase();

                // Restore datasets
                rehabAssessmentTDS = (RehabAssessmentTDS)Session["rehabAssessmentTDS"];

                rehabAssessmentSectionDetails.LoadByWorkId(workId, companyId);
                rehabAssessmentWorkDetails.LoadByWorkId(workId, companyId);

                int newWorkIdFll = GetWorkId(currentProjectId, assetId, "Full Length Lining", companyId);
                hdfWorkIdFll.Value = GetWorkId(currentProjectId, assetId, "Full Length Lining", companyId).ToString();

                rehabAssessmentTDS.LateralDetails.Clear();
                RehabAssessmentLateralDetails rehabAssessmentLateralDetails = new RehabAssessmentLateralDetails(rehabAssessmentTDS);
                rehabAssessmentLateralDetails.LoadForEdit(newWorkIdFll, assetId, companyId, currentProjectId);
                grdLaterals.DataBind();

                // ... Store dataset
                Session["rehabAssessmentTDS"] = rehabAssessmentTDS;

                ViewState["update"] = "yes";
            }

            return validData;
        }
        protected void tbxVideoLength_TextChanged(object sender, EventArgs e)
        {
            int workId = Int32.Parse(hdfWorkId.Value);
            int assetId = Int32.Parse(hdfAssetId.Value);
            string videoLength = tbxVideoLength.Text.Trim();

            // Update reverse setup
            RehabAssessmentLateralDetails rehabAssessmentLateralDetails = new RehabAssessmentLateralDetails(rehabAssessmentTDS);
            rehabAssessmentLateralDetails.UpdateLengthReverseSetup(workId, assetId, videoLength);

            // Store dataset
            Session["rehabAssessmentTDS"] = rehabAssessmentTDS;

            for (int i = 0; i < grdLaterals.Rows.Count; i++)
            {
                if ((grdLaterals.Rows[i].RowType == DataControlRowType.DataRow) && ((grdLaterals.Rows[i].RowState == DataControlRowState.Normal) || (grdLaterals.Rows[i].RowState == (DataControlRowState.Normal | DataControlRowState.Alternate))))
                {
                    // Reverse Setup calculation
                    string videoDistance = ((TextBox)grdLaterals.Rows[i].Cells[2].FindControl("tbxVideoDistance")).Text.Trim();
                    string reverseSetup = "";
                    if (videoDistance != "")
                    {
                        Distance videoLengthD = new Distance(tbxVideoLength.Text.Trim());
                        Distance videoDistanceD = new Distance(videoDistance);
                        Distance reverseSetupD = videoLengthD - videoDistanceD;

                        switch (videoDistanceD.DistanceType)
                        {
                            case 1:
                                reverseSetup = reverseSetupD.ToStringInEng1();
                                break;
                            case 2:
                                reverseSetup = reverseSetupD.ToStringInEng2();
                                break;
                            case 3:
                                reverseSetup = reverseSetupD.ToStringInEng3();
                                break;
                            case 4:
                                reverseSetup = reverseSetupD.ToStringInMet1();
                                break;
                            case 5:
                                reverseSetup = reverseSetupD.ToStringInMil1();
                                break;
                        }
                    }

                    ((TextBox)grdLaterals.Rows[i].Cells[2].FindControl("tbxReverseSetup")).Text = reverseSetup;
                }
            }
        }
        protected void Page_PreRender(object sender, EventArgs e)
        {
            // Set active toolbar
            mForm8 master = (mForm8)this.Master;
            master.ActiveToolbar = "eSewers";

            // For error message
            hdfErrorFieldList.Value = "";

            // For Video Done From MH and Measured From MH
            int companyId = Int32.Parse(hdfCompanyId.Value);
            int assetId = Int32.Parse(hdfAssetId.Value);
            int workId = Int32.Parse(hdfWorkId.Value);
            int workIdFll = Int32.Parse(hdfWorkIdFll.Value);
            int currentProjectId = Int32.Parse(hdfCurrentProjectId.Value.ToString());

            RehabAssessmentWorkDetailsGateway raWorkDetailsGateway = new RehabAssessmentWorkDetailsGateway();
            raWorkDetailsGateway.LoadByWorkId(workId, companyId);
            RehabAssessmentLateralDetails raLateralDetails = new RehabAssessmentLateralDetails();
            raLateralDetails.LoadForEdit(workIdFll, assetId, companyId, currentProjectId);

            if (Int32.Parse(tbxLaterals.Text) > 0)
            {
                ddlM1DataVideoDoneFromMh.Visible = false;
                tbxM1DataVideoDoneFromMh.Visible = true;
                tbxM1DataVideoDoneFromMh.Text = ddlM1DataVideoDoneFromMh.SelectedValue;

                ddlM1DataVideoDoneToMh.Visible = false;
                tbxM1DataVideoDoneToMh.Visible = true;
                tbxM1DataVideoDoneToMh.Text = ddlM1DataVideoDoneToMh.SelectedValue;

                ddlM1DataMeasuredFromMh.Visible = false;
                tbxM1DataMeasuredFromMh.Visible = true;
                tbxM1DataMeasuredFromMh.Text = ddlM1DataMeasuredFromMh.SelectedValue;

                btnClear.Visible = false;
            }
            else
            {
                ddlM1DataVideoDoneFromMh.Visible = true;
                tbxM1DataVideoDoneFromMh.Visible = false;

                ddlM1DataVideoDoneToMh.Visible = true;
                tbxM1DataVideoDoneToMh.Visible = false;

                ddlM1DataMeasuredFromMh.Visible = true;
                tbxM1DataMeasuredFromMh.Visible = false;

                btnClear.Visible = true;
            }

            // For materials
            // ... Load material for m1
            MaterialInformationGateway materialInformationGateway = new MaterialInformationGateway();
            materialInformationGateway.LoadLastMaterialByAssetId(assetId, companyId);

            if (materialInformationGateway.Table.Rows.Count > 0)
            {
                ddlM1DataMaterial.SelectedValue = materialInformationGateway.GetLastMaterialType(assetId);
            }

            // Hide or show the Old CWP ID field
            if (tbxOldCwpId.Text == "")
            {
                lblOldCwpId.Visible = false;
                tbxOldCwpId.Visible = false;
            }

            if (tbxFlowOrderId.Text == "")
            {
                LoadRehabAssessmentData(currentProjectId, assetId, companyId);
            }
        }
        // ////////////////////////////////////////////////////////////////////////
        // EVENTS
        //
        protected void Page_Load(object sender, EventArgs e)
        {
            // Register client scripts
            this.RegisterClientScripts();

            if (!IsPostBack)
            {
                // Security check
                if (!(Convert.ToBoolean(Session["sgLFS_CWP_REHABASSESSMENT_VIEW"]) && Convert.ToBoolean(Session["sgLFS_CWP_REHABASSESSMENT_EDIT"])))
                {
                    Response.Redirect("./../../error_page.aspx?error=" + "You are not authorized to view this page. Contact your system administrator.");
                }

                // Validate query string
                if (((string)Request.QueryString["source_page"] == null) || ((string)Request.QueryString["client_id"] == null) || ((string)Request.QueryString["project_id"] == null))
                {
                    Response.Redirect("./../../error_page.aspx?error=" + "Invalid query string in ra_summary.aspx");
                }

                // Tag Page
                TagPage();

                Session.Remove("raAddLateralsNewDummy");

                // If coming from
                int companyId = Int32.Parse(hdfCompanyId.Value.Trim());
                int currentProjectId = Int32.Parse(hdfCurrentProjectId.Value.ToString());
                int assetId = Int32.Parse(hdfAssetId.Value.Trim());
                string workType = hdfWorkType.Value;
                int workId = Int32.Parse(hdfWorkId.Value);

                // ... ra_navigator2.aspx
                if (Request.QueryString["source_page"] == "ra_navigator2.aspx")
                {
                    StoreNavigatorState();
                    ViewState["update"] = "no";

                    // Set initial tab
                    if ((string)Session["dialogOpenedRa"] != "1")
                    {
                        rehabAssessmentTDS = new RehabAssessmentTDS();

                        RehabAssessmentSectionDetails rehabAssessmentSectionDetails = new RehabAssessmentSectionDetails(rehabAssessmentTDS);
                        rehabAssessmentSectionDetails.LoadByWorkId(workId, companyId);

                        RehabAssessmentWorkDetails rehabAssessmentWorkDetails = new RehabAssessmentWorkDetails(rehabAssessmentTDS);
                        rehabAssessmentWorkDetails.LoadByWorkId(workId, companyId);

                        int workIdFll = GetWorkId(currentProjectId, assetId, "Full Length Lining", companyId);
                        RehabAssessmentLateralDetails rehabAssessmentLateralDetails = new RehabAssessmentLateralDetails(rehabAssessmentTDS);
                        rehabAssessmentLateralDetails.LoadForEdit(workIdFll, assetId, companyId, currentProjectId);

                        hdfActiveTab.Value = Request.QueryString["active_tab"];
                    }
                    else
                    {
                        hdfActiveTab.Value = (string)Session["activeTabRa"];

                        // Restore dataset
                        rehabAssessmentTDS = (RehabAssessmentTDS)Session["rehabAssessmentTDS"];
                    }

                    tcRaDetails.ActiveTabIndex = Int32.Parse(hdfActiveTab.Value);

                    // Store dataset
                    Session["rehabAssessmentTDS"] = rehabAssessmentTDS;
                }

                // ... ra_delete.aspx or ra_edit.aspx
                if ((Request.QueryString["source_page"] == "ra_delete.aspx") || (Request.QueryString["source_page"] == "ra_edit.aspx"))
                {
                    StoreNavigatorState();
                    ViewState["update"] = Request.QueryString["update"];

                    // Restore dataset
                    rehabAssessmentTDS = (RehabAssessmentTDS)Session["rehabAssessmentTDS"];

                    // ... Set initial tab
                    if ((string)Session["dialogOpenedRa"] != "1")
                    {
                        hdfActiveTab.Value = Request.QueryString["active_tab"];
                    }
                    else
                    {
                        hdfActiveTab.Value = (string)Session["activeTabRa"];
                    }

                    tcRaDetails.ActiveTabIndex = Int32.Parse(hdfActiveTab.Value);
                }

                // Prepare initial data
                // ... for client
                int currentClientId = Int32.Parse(hdfCurrentClientId.Value.ToString());

                CompaniesGateway companiesGateway = new CompaniesGateway();
                companiesGateway.LoadByCompaniesId(currentClientId, companyId);
                lblTitleClientName.Text = "Client: " + companiesGateway.GetName(currentClientId);

                // ... for project
                ProjectGateway projectGateway = new ProjectGateway();
                projectGateway.LoadByProjectId(currentProjectId);
                string name = projectGateway.GetName(currentProjectId);
                if (name.Length > 23) name = name.Substring(0, 20) + "...";
                lblTitleProjectName.Text = " > Project: " + name + " (" + projectGateway.GetProjectNumber(currentProjectId) + ") > Selected Section";

                // ... Data for current work
                LoadRehabAssessmentData(currentProjectId, assetId, companyId);

                // Databind
                Page.DataBind();
            }
            else
            {
                // Restore datasets
                rehabAssessmentTDS = (RehabAssessmentTDS)Session["rehabAssessmentTDS"];

                // Set initial tab
                int activeTab = Int32.Parse(hdfActiveTab.Value);
                tcRaDetails.ActiveTabIndex = activeTab;
            }
        }