private bool Apply()
        {
            // Validate data
            bool validData = true;

            validData = ValidatePage();

            if (validData)
            {
                // Laterals Gridview
                // ... If the gridview is edition mode
                if (grdLaterals.EditIndex >= 0)
                {
                    grdLaterals.UpdateRow(grdLaterals.EditIndex, true);
                }

                // Save Lateral data
                GrdFLAddLateralsNewAdd();

                // Catalysts Gridview
                if (ckbxWetOutDataIncludeWetOutInformation.Checked)
                {
                    // ... If the gridview is edition mode
                    if (grdCatalysts.EditIndex >= 0)
                    {
                        grdCatalysts.UpdateRow(grdCatalysts.EditIndex, true);
                    }

                    // Save Lateral data
                    GrdCatalystsAdd();
                }

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

                // Get Section Details
                // ... FullLengthLiningSectionDetails 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
                FullLengthLiningSectionDetails fullLengthLiningSectionDetails = new FullLengthLiningSectionDetails(fullLengthLiningTDS);
                fullLengthLiningSectionDetails.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
                // ... Ra new data
                DateTime? newPreFlushDate = null;
                if (tkrdpGeneralPreFlushDate.Visible == true)
                {
                    if (tkrdpGeneralPreFlushDate.SelectedDate.HasValue)
                    {
                        newPreFlushDate = tkrdpGeneralPreFlushDate.SelectedDate.Value;
                    }
                }
                else
                {
                    if (tkrdpGeneralPreFlushDateReadOnly.SelectedDate.HasValue)
                    {
                        newPreFlushDate = tkrdpGeneralPreFlushDateReadOnly.SelectedDate.Value;
                    }
                }

                DateTime? newPreVideoDate = null;
                if (tkrdpGeneralPreVideoDate.Visible == true)
                {
                    if (tkrdpGeneralPreVideoDate.SelectedDate.HasValue)
                    {
                        newPreVideoDate = tkrdpGeneralPreVideoDate.SelectedDate.Value;
                    }
                }
                else
                {
                    if (tkrdpGeneralPreVideoDateReadOnly.SelectedDate.HasValue)
                    {
                        newPreVideoDate = tkrdpGeneralPreVideoDateReadOnly.SelectedDate.Value; ;
                    }
                }

                // ... FullLengthLining data
                string newGeneralClientId = ""; if (tbxGeneralClientId.Text != "") newGeneralClientId = tbxGeneralClientId.Text.Trim();
                DateTime? newGeneralProposedLiningDate = null; if (tkrdpGeneralProposedLiningDate.SelectedDate.HasValue) newGeneralProposedLiningDate = tkrdpGeneralProposedLiningDate.SelectedDate.Value;
                DateTime? newGeneralDeadlineLiningDate = null; if (tkrdpGeneralDeadlineLiningDate.SelectedDate.HasValue) newGeneralDeadlineLiningDate = tkrdpGeneralDeadlineLiningDate.SelectedDate.Value;
                DateTime? newGeneralP1Date = null; if (tkrdpPrepDataP1Date.SelectedDate.HasValue) newGeneralP1Date = tkrdpPrepDataP1Date.SelectedDate.Value;
                DateTime? newGeneralM1Date = null; if (tkrdpM1DataM1Date.SelectedDate.HasValue) newGeneralM1Date = tkrdpM1DataM1Date.SelectedDate.Value;
                DateTime? newGeneralM2Date = null; if (tkrdpM2DataM2Date.SelectedDate.HasValue) newGeneralM2Date = tkrdpM2DataM2Date.SelectedDate.Value;
                DateTime? newGeneralInstallDate = null; if (tkrdpInstallDataInstallDate.SelectedDate.HasValue) newGeneralInstallDate = tkrdpInstallDataInstallDate.SelectedDate.Value;
                DateTime? newGeneralFinalVideo = null; if (tkrdpInstallDataFinalVideoDate.SelectedDate.HasValue) newGeneralFinalVideo = tkrdpInstallDataFinalVideoDate.SelectedDate.Value;
                bool newGeneralIssueIdentified = ckbxGeneralIssueIdentified.Checked;
                bool newGeneralLfsIssue = ckbxGeneralLfsIssue.Checked;
                bool newGeneralClientIssue = ckbxGeneralClientIssue.Checked;
                bool newGeneralSalesIssue = ckbxGeneralSalesIssue.Checked;
                bool newGeneralIssueGivenToClient = ckbxGeneralIssueGivenToClient.Checked;
                bool newGeneralIssueResolved = ckbxGeneralIssueResolved.Checked;
                bool newGeneralIssueInvestigation = ckbxGeneralIssueInvestigation.Checked;
                int? newPrepDataCXIsRemoved = null; if (tbxPrepDataCXIsRemoved.Text != "") newPrepDataCXIsRemoved = Int32.Parse(tbxPrepDataCXIsRemoved.Text.Trim());
                bool newRoboticPrepCompleted = ckbxPrepDataRoboticPrepCompleted.Checked;
                DateTime? newRoboticPrepCompletedDate = null; if (tkrdpPrepDataRoboticPrepCompletedDate.SelectedDate.HasValue) newRoboticPrepCompletedDate = tkrdpPrepDataRoboticPrepCompletedDate.SelectedDate.Value;
                bool newP1Completed = ckbxPrepDataP1Completed.Checked;

                // ... WorkFullLengthLiningM1 data
                string newMeasurementsTakenBy = ""; if (tbxM1DataMeasurementsTakenBy.Text != "") newMeasurementsTakenBy = tbxM1DataMeasurementsTakenBy.Text.Trim();
                string newMaterial = ddlM1DataMaterial.SelectedValue;
                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 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;

                // ... ... For header values
                string newVideoLength = tbxVideoLength.Text.Trim();

                // ... WorkFullLengthLiningM2 data
                string newMeasurementTakenByM2 = tbxM2DataMeasurementsTakenBy.Text.Trim();
                bool newDropPipe = ckbxM2DataDropPipe.Checked;
                string newDropPipeInvertDepth = tbxM2DataDropPipeInvertdepth.Text.Trim();
                int? newCappedLaterals = null; if (tbxM2DataCappedLaterals.Text != "") newCappedLaterals = Int32.Parse(tbxM2DataCappedLaterals.Text.Trim());
                string newLineWidthId = ""; if (tbxM2DataLineWidthId.Text != "") newLineWidthId = tbxM2DataLineWidthId.Text.Trim();
                string newHydrantAddress = ""; if (tbxM2DataHydrantAddress.Text != "") newHydrantAddress = tbxM2DataHydrantAddress.Text.Trim();
                string newHydroWireWithin10FtOfInversionMH = ddlM2DataHydroWireWithin10FtOfInversionMh.SelectedValue.Trim();
                string newDistanceToInversionMH = ""; if (tbxM2DataDistanceToInversionMH.Text != "") newDistanceToInversionMH = tbxM2DataDistanceToInversionMH.Text.Trim();
                string newSurfaceGrade = ""; if (ddlM2DataSurfaceGrade.SelectedValue != "(Select)") newSurfaceGrade = ddlM2DataSurfaceGrade.SelectedValue;
                bool newHydroPulley = cbxM2DataHydroPulley.Checked;
                bool newFridgeCart = cbxM2DataFridgeCart.Checked;
                bool newTwoPump = cbxM2DataTwoPump.Checked;
                bool newSixBypass = cbxM2DataSixBypass.Checked;
                bool newScaffolding = cbxM2DataScaffolding.Checked;
                bool newWinchExtension = cbxM2DataWinchExtension.Checked;
                bool newExtraGenerator = cbxM2DataExtraGenerator.Checked;
                bool newGreyCableExtension = cbxM2DataGreyCableExtension.Checked;
                bool newEasementMats = cbxM2DataEasementMats.Checked;
                bool newRampsRequired = cbxM2DataRampsRequired.Checked;
                bool newCameraSkid = cbxM2DataCameraSkid.Checked;

                // ... Update work details
                FullLengthLiningWorkDetails fullLengthLiningWorkDetails = new FullLengthLiningWorkDetails(fullLengthLiningTDS);

                // ... ... If it doen's have wet out information
                if (!ckbxWetOutDataIncludeWetOutInformation.Checked)
                {
                    fullLengthLiningWorkDetails.Update(workId, newGeneralClientId, newGeneralProposedLiningDate, newGeneralDeadlineLiningDate, newGeneralP1Date, newGeneralM1Date, newGeneralM2Date, newGeneralInstallDate, newGeneralFinalVideo, newGeneralIssueIdentified, newGeneralLfsIssue, newGeneralClientIssue, newGeneralSalesIssue, newGeneralIssueGivenToClient, newGeneralIssueResolved, newGeneralIssueInvestigation, newPrepDataCXIsRemoved, newRoboticPrepCompleted, newRoboticPrepCompletedDate, newMeasurementsTakenBy, newMaterial, newTrafficControl, newSiteDetails, newPipeSizeChange, newStandardByPass, newStandardBypassComments, newTrafficControlDetails, newMeasurementType, newMeasuredFromMh, newVideoDoneFromMh, newVideoDoneToMh, newMeasurementTakenByM2, newDropPipe, newDropPipeInvertDepth, newCappedLaterals, newLineWidthId, newHydrantAddress, newHydroWireWithin10FtOfInversionMH, newDistanceToInversionMH, newSurfaceGrade, newHydroPulley, newFridgeCart, newTwoPump, newSixBypass, newScaffolding, newWinchExtension, newExtraGenerator, newGreyCableExtension, newEasementMats, newRampsRequired, newVideoLength, newPreFlushDate, newPreVideoDate, newCameraSkid, newAccessType, newP1Completed);
                }
                else
                {
                    // Wet out data
                    string newLinerTuber = "";
                    int newResinId = 0;
                    decimal newExcessResin = 0;
                    string newPoundsDrums = "";
                    decimal newDrumDiameter = 0;
                    decimal newHoistMaximumHeight = 0;
                    decimal newHoistMinimumHeight = 0;
                    decimal newDownDropTubeLenght = 0;
                    decimal newPumpHeightAboveGround = 0;
                    int newTubeResinToFeltFactor = 0;
                    DateTime newDateOfSheet = DateTime.Now;
                    int newEmployeeID = 0;
                    string newRunDetails = "";
                    string newRunDetails2 = "";
                    DateTime newWetOutDate = DateTime.Now;
                    DateTime? newInstallDate = null;
                    string newInversionThickness = "";
                    Distance lengthToLine = new Distance("0");
                    decimal newLengthToLine = 0;
                    decimal newPlusExtra = 0;
                    decimal newForTurnOffset = 0;
                    decimal newLengthToWetOut = 0;

                    decimal newTubeMaxColdHead = 0;
                    decimal newTubeMaxColdHeadPsi = 0;
                    decimal newTubeMaxHotHead = 0;
                    decimal newTubeMaxHotHeadPsi = 0;
                    decimal newTubeIdealHead = 0;
                    decimal newTubeIdealHeadPsi = 0;

                    decimal newNetResinForTube = 0;
                    decimal newNetResinForTubeUsgals = 0;
                    string newNetResinForTubeDrumsIns = "";
                    decimal newNetResinForTubeLbsFt = 0;
                    decimal newNetResinForTubeUsgFt = 0;

                    int newExtraResinForMix = 0;
                    decimal newExtraLbsForMix = 0;
                    decimal newTotalMixQuantity = 0;
                    decimal newTotalMixQuantityUsgals = 0;
                    string newTotalMixQuantityDrumsIns = "";

                    string newInversionType = "";
                    decimal newDepthOfInversionMH = 0;
                    decimal newTubeForColumn = 0;
                    decimal newTubeForStartDry = 0;
                    decimal newTotalTube = 0;
                    string newDropTubeConnects = "";
                    decimal newAllowsHeadTo = 0;
                    decimal newRollerGap = 0;

                    decimal newHeightNeeded = 0;
                    string newAvailable = "";
                    string newHoistHeight = "";
                    string newCommentsCipp = "";

                    string newResinLabel = "";
                    string newDrumContainsLabel = "";
                    string newLinerTubeLabel = "";
                    string newForLbDrumsLabel = "";
                    string newNetResinLabel = "";
                    string newCatalystLabel = "";

                    if (ckbxWetOutDataIncludeWetOutInformation.Checked)
                    {
                        // .... ... Wet Out Sheet
                        newLinerTuber = ddlWetOutDataLinerTube.SelectedValue;
                        newResinId = Int32.Parse(ddlWetOutDataResins.SelectedValue);
                        newExcessResin = decimal.Round(decimal.Parse(tbxWetOutDataExcessResin.Text), 1);
                        newPoundsDrums = ddlWetOutDataPoundsDrums.SelectedValue;
                        newDrumDiameter = decimal.Round(decimal.Parse(tbxWetOutDataDrumDiameter.Text), 1);
                        newHoistMaximumHeight = decimal.Round(decimal.Parse(tbxWetOutDataHoistMaximumHeight.Text), 0);
                        newHoistMinimumHeight = decimal.Round(decimal.Parse(tbxWetOutDataHoistMinimumHeight.Text), 0);
                        newDownDropTubeLenght = decimal.Round(decimal.Parse(tbxWetOutDataDownDropTubeLength.Text), 0);
                        newPumpHeightAboveGround = decimal.Round(decimal.Parse(tbxWetOutDataPumpHeightAboveGround.Text), 2);
                        newTubeResinToFeltFactor = Int32.Parse(tbxWetOutDataTubeResinToFeltFactor.Text);

                        newDateOfSheet = DateTime.Parse(tbxWetOutDataDateOfSheet.Text);
                        newEmployeeID = Int32.Parse(ddlWetOutDataMadeBy.SelectedValue);

                        foreach (ListItem lst in cbxlSectionId.Items)
                        {
                            if (lst.Selected)
                            {
                                newRunDetails = newRunDetails + lst.Value + ">";
                            }
                        }
                        newRunDetails = newRunDetails.Substring(0, newRunDetails.Length - 1);

                        newRunDetails2 = ddlWetOutDataRunDetails2.SelectedValue;
                        newWetOutDate = (DateTime)tkrdpWetOutDataWetOutDate.SelectedDate;

                        if (tkrdpInstallDataInstallDate.SelectedDate.ToString() != "")
                        {
                            newInstallDate = (DateTime)tkrdpInstallDataInstallDate.SelectedDate;
                        }

                        newInversionThickness = ddlThickness.SelectedValue;
                        lengthToLine = new Distance(tbxWetOutDataLengthToLine.Text);
                        newLengthToLine = decimal.Round(decimal.Parse(lengthToLine.ToStringInEng3()), 1);
                        newPlusExtra = decimal.Round(decimal.Parse(tbxWetOutDataPlusExtra.Text), 0);
                        newForTurnOffset = decimal.Round(decimal.Parse(tbxWetOutDataForTurnOffset.Text), 0);
                        newLengthToWetOut = decimal.Round(decimal.Parse(tbxWetOutDataLengthtToWetOut.Text), 1);

                        newTubeMaxColdHead = decimal.Round(decimal.Parse(tbxWetOutDataTubeMaxColdHead.Text), 1);
                        newTubeMaxColdHeadPsi = decimal.Round(decimal.Parse(tbxWetOutDataTubeMaxColdHeadPSI.Text), 1);
                        newTubeMaxHotHead = decimal.Round(decimal.Parse(tbxWetOutDataTubeMaxHotHead.Text), 1);
                        newTubeMaxHotHeadPsi = decimal.Round(decimal.Parse(tbxWetOutDataTubeMaxHotHeadPSI.Text), 1);
                        newTubeIdealHead = decimal.Round(decimal.Parse(tbxWetOutDataTubeIdealHead.Text), 1);
                        newTubeIdealHeadPsi = decimal.Round(decimal.Parse(tbxWetOutDataTubeIdealHeadPSI.Text), 1);

                        newNetResinForTube = decimal.Round(decimal.Parse(tbxWetOutDataNetResinForTube.Text), 0);
                        newNetResinForTubeUsgals = decimal.Round(decimal.Parse(tbxWetOutDataNetResinForTubeUsgals.Text), 1);
                        newNetResinForTubeDrumsIns = tbxWetOutDataNetResinForTubeDrumsIns.Text;
                        newNetResinForTubeLbsFt = decimal.Round(decimal.Parse(tbxWetOutDataNetResinForTubeLbsFt.Text), 2);
                        newNetResinForTubeUsgFt = decimal.Round(decimal.Parse(tbxWetOutDataNetResinForTubeUsgFt.Text), 3);

                        newExtraResinForMix = Int32.Parse(tbxWetOutDataExtraResinForMix.Text);
                        newExtraLbsForMix = decimal.Round(decimal.Parse(tbxWetOutDataExtraLbsForMix.Text), 2);
                        newTotalMixQuantity = decimal.Round(decimal.Parse(tbxWetOutDataTotalMixQuantity.Text), 0);
                        newTotalMixQuantityUsgals = decimal.Round(decimal.Parse(tbxWetOutDataTotalMixQuantityUsgals.Text), 1);
                        newTotalMixQuantityDrumsIns = tbxWetOutDataTotalMixQuantityDrumsIns.Text;

                        newInversionType = ddlWetOutDataInversionType.SelectedValue;
                        newDepthOfInversionMH = decimal.Round(decimal.Parse(tbxWetOutDataDepthOfInversionMH.Text), 0);
                        newTubeForColumn = decimal.Round(decimal.Parse(tbxWetOutDataTubeForColumn.Text), 0);
                        newTubeForStartDry = decimal.Round(decimal.Parse(tbxWetOutDataTubeForStartDry.Text), 0);
                        newTotalTube = decimal.Round(decimal.Parse(tbxWetOutDataTotalTube.Text), 1);
                        newDropTubeConnects = tbxWetOutDataDropTubeConnects.Text;
                        newAllowsHeadTo = decimal.Round(decimal.Parse(tbxWetOutDataAllowsHeadTo.Text), 0);
                        newRollerGap = decimal.Round(decimal.Parse(tbxWetOutDataRollerGap.Text), 0);

                        newHeightNeeded = decimal.Round(decimal.Parse(tbxWetOutDataHeightNeeded.Text), 0);
                        newAvailable = tbxWetOutDataAvailable.Text;
                        newHoistHeight = tbxWetOutDataHoistHeight.Text;
                        newCommentsCipp = tbxWetOutDataNotes.Text;

                        newResinLabel = lblWetOutDataResinGray.Text;
                        newDrumContainsLabel = lblWetOutDataDrumContainsGray.Text;
                        newLinerTubeLabel = lblWetOutDataLinerTubeGray.Text;
                        newForLbDrumsLabel = lblWetOutDataLbDrumsGrey.Text;
                        newNetResinLabel = lblWetOutDataNetResinGrey.Text;
                        newCatalystLabel = lblWetOutDataCatalystGrey.Text;
                    }

                    // Inversion data
                    string newInversionComment = "";
                    string newPipeType = "";
                    string newPipeCondition = "";
                    string newGroundMoisture = "";
                    decimal newBoilerSize = 0;
                    decimal newPumpTotalCapacity = 0;
                    decimal newLayFlatSize = 0;
                    decimal newLayFlatQuantityTotal = 0;

                    decimal newWaterStartTemp = 0;
                    decimal newTemp1 = 0;
                    decimal newHoldAtT1 = 0;
                    decimal newTempT2 = 0;
                    decimal newCookAtT2 = 0;
                    decimal newCoolDownFor = 0;
                    decimal newCoolToTemp = 0;
                    decimal newDropInPipeRun = 0;
                    decimal newPipeSlopOf = 0;

                    decimal newF45F120 = 0;
                    decimal newHold = 0;
                    decimal newF120F185 = 0;
                    decimal newCookTime = 0;
                    decimal newCoolTime = 0;
                    decimal newAproxTotal = 0;

                    decimal newWaterChangesPerHour = 0;
                    decimal newReturnWaterVelocity = 0;
                    decimal newLayflatBackPressure = 0;
                    decimal newPumpLiftAtIdealHead = 0;
                    decimal newWaterToFillLinerColumn = 0;
                    decimal newWaterPerFit = 0;
                    string newInstallationResults = "";
                    string newInversionLinerTubeLabel = "";
                    string newHeadsIdealLabel = "";
                    string newPumpingAndCirculationLabel = "";

                    if ((ckbxInversionDataIncludeInversionInformation.Checked) && (ckbxWetOutDataIncludeWetOutInformation.Checked))
                    {
                        // .... ... Inversion data
                        newInversionComment = tbxInversionDataCommentsEdit.Text;
                        newPipeType = ddlInversionDataInversionPipeType.SelectedValue;
                        newPipeCondition = ddlInversionDataPipeCondition.SelectedValue;
                        newGroundMoisture = ddlInversionDataGroundMoisture.SelectedValue;
                        newBoilerSize = decimal.Round(decimal.Parse(tbxInversionDataBoilerSize.Text), 0);
                        newPumpTotalCapacity = decimal.Round(decimal.Parse(tbxInversionDataPumpsTotalCapacity.Text), 0);
                        newLayFlatSize = decimal.Round(decimal.Parse(tbxInversionDataLayflatSize.Text), 0);
                        newLayFlatQuantityTotal = decimal.Round(decimal.Parse(tbxInversionDataLayflatQuantityTotal.Text), 0);

                        newWaterStartTemp = decimal.Round(decimal.Parse(tbxInversionDataWaterStartTempTs.Text), 0);
                        newTemp1 = decimal.Round(decimal.Parse(tbxInversionDataTempT1.Text), 0);
                        newHoldAtT1 = decimal.Round(decimal.Parse(tbxInversionDataHoldAtT1For.Text), 1);
                        newTempT2 = decimal.Round(decimal.Parse(tbxInversionDataTempT2.Text), 0);
                        newCookAtT2 = decimal.Round(decimal.Parse(tbxInversionDataCookAtT2For.Text), 0);
                        newCoolDownFor = decimal.Round(decimal.Parse(tbxInversionDataCoolDownFor.Text), 0);
                        newCoolToTemp = decimal.Round(decimal.Parse(tbxInversionDataCoolToTemp.Text), 0);
                        newDropInPipeRun = decimal.Round(decimal.Parse(tbxInversionDataDropInPipeRun.Text), 1);
                        newPipeSlopOf = decimal.Round(decimal.Parse(tbxInversionDataPipeSlopeOf.Text), 2);

                        newF45F120 = decimal.Round(decimal.Parse(tbxInversionData45F120F.Text), 1);
                        newHold = decimal.Round(decimal.Parse(tbxInversionDataHold.Text), 1);
                        newF120F185 = decimal.Round(decimal.Parse(tbxInversionData120F185F.Text), 1);
                        newCookTime = decimal.Round(decimal.Parse(tbxInversionDataCookTime.Text), 1);
                        newCoolTime = decimal.Round(decimal.Parse(tbxInversionDataCoolTime.Text), 1);
                        newAproxTotal = decimal.Round(decimal.Parse(tbxInversionDataAproxTotal.Text), 1);

                        newWaterChangesPerHour = decimal.Round(decimal.Parse(tbxInversionDataWaterChangesPerHour.Text), 2);
                        newReturnWaterVelocity = decimal.Round(decimal.Parse(tbxInversionDataReturnWaterVelocity.Text), 2);
                        newLayflatBackPressure = decimal.Round(decimal.Parse(tbxInversionDataLayflatBackPressure.Text), 1);
                        newPumpLiftAtIdealHead = decimal.Round(decimal.Parse(tbxInversionDataPumpLiftAtIdealHead.Text), 1);
                        newWaterToFillLinerColumn = decimal.Round(decimal.Parse(tbxInversionDataWaterToFillLinerColumn.Text), 0);
                        newWaterPerFit = decimal.Round(decimal.Parse(tbxInversionDataWaterPerFit.Text), 2);
                        newInstallationResults = tbxInversionDataNotesAndInstallationResults.Text;
                        newInversionLinerTubeLabel = lblInversionDataLinerInfoGrey.Text;
                        newHeadsIdealLabel = lblInversionDataHeadsGrey.Text;
                        newPumpingAndCirculationLabel = lblInversionDataPumpingCirculationSubtitle.Text;
                    }

                    // ... Update
                    fullLengthLiningWorkDetails.UpdateWithWetOutInformation(workId, newGeneralClientId, newGeneralProposedLiningDate, newGeneralDeadlineLiningDate, newGeneralP1Date, newGeneralM1Date, newGeneralM2Date, newGeneralInstallDate, newGeneralFinalVideo, newGeneralIssueIdentified, newGeneralLfsIssue, newGeneralClientIssue, newGeneralSalesIssue, newGeneralIssueGivenToClient, newGeneralIssueResolved, newGeneralIssueInvestigation, newPrepDataCXIsRemoved, newRoboticPrepCompleted, newRoboticPrepCompletedDate, newMeasurementsTakenBy, newMaterial, newTrafficControl, newSiteDetails, newPipeSizeChange, newStandardByPass, newStandardBypassComments, newTrafficControlDetails, newMeasurementType, newMeasuredFromMh, newVideoDoneFromMh, newVideoDoneToMh, newMeasurementTakenByM2, newDropPipe, newDropPipeInvertDepth, newCappedLaterals, newLineWidthId, newHydrantAddress, newHydroWireWithin10FtOfInversionMH, newDistanceToInversionMH, newSurfaceGrade, newHydroPulley, newFridgeCart, newTwoPump, newSixBypass, newScaffolding, newWinchExtension, newExtraGenerator, newGreyCableExtension, newEasementMats, newRampsRequired, newVideoLength, newPreFlushDate, newPreVideoDate, newCameraSkid, newLinerTuber, newResinId, newExcessResin, newPoundsDrums, newDrumDiameter, newHoistMaximumHeight, newHoistMinimumHeight, newDownDropTubeLenght, newPumpHeightAboveGround, newTubeResinToFeltFactor, newDateOfSheet, newEmployeeID, newRunDetails, newRunDetails2, newWetOutDate, newInstallDate, newInversionThickness, newLengthToLine, newPlusExtra, newForTurnOffset, newLengthToWetOut, newTubeMaxColdHead, newTubeMaxColdHeadPsi, newTubeMaxHotHead, newTubeMaxHotHeadPsi, newTubeIdealHead, newTubeIdealHeadPsi, newNetResinForTube, newNetResinForTubeUsgals, newNetResinForTubeDrumsIns, newNetResinForTubeLbsFt, newNetResinForTubeUsgFt, newExtraResinForMix, newExtraLbsForMix, newTotalMixQuantity, newTotalMixQuantityUsgals, newTotalMixQuantityDrumsIns, newInversionType, newDepthOfInversionMH, newTubeForColumn, newTubeForStartDry, newTotalTube, newDropTubeConnects, newAllowsHeadTo, newRollerGap, newHeightNeeded, newAvailable, newHoistHeight, newCommentsCipp, newResinLabel, newDrumContainsLabel, newLinerTubeLabel, newForLbDrumsLabel, newNetResinLabel, newCatalystLabel, newInversionComment, newPipeType, newPipeCondition, newGroundMoisture, newBoilerSize, newPumpTotalCapacity, newLayFlatSize, newLayFlatQuantityTotal, newWaterStartTemp, newTemp1, newHoldAtT1, newTempT2, newCookAtT2, newCoolDownFor, newCoolToTemp, newDropInPipeRun, newPipeSlopOf, newF45F120, newHold, newF120F185, newCookTime, newCoolTime, newAproxTotal, newWaterChangesPerHour, newReturnWaterVelocity, newLayflatBackPressure, newPumpLiftAtIdealHead, newWaterToFillLinerColumn, newWaterPerFit, newInstallationResults, newInversionLinerTubeLabel, newHeadsIdealLabel, newPumpingAndCirculationLabel, 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["fullLengthLiningTDS"] = fullLengthLiningTDS;
                Session["materialInformationTDS"] = materialInformationTDS;

                // Update database
                UpdateDatabase();

                // Restore datasets
                fullLengthLiningTDS = (FullLengthLiningTDS)Session["fullLengthLiningTDS"];

                fullLengthLiningSectionDetails.LoadByWorkId(workId, companyId);
                fullLengthLiningWorkDetails.LoadByWorkIdAssetId(workId, assetId, companyId);
                fullLengthLiningTDS.LateralDetails.Clear();
                FullLengthLiningLateralDetails fullLengthLiningLateralDetails = new FullLengthLiningLateralDetails(fullLengthLiningTDS);
                fullLengthLiningLateralDetails.LoadForEdit(workId, assetId, companyId, currentProjectId);
                grdLaterals.DataBind();

                fullLengthLiningTDS.WetOutCatalystsDetails.Clear();
                FullLengthLiningWetOutCatalystsDetails fullLengthLiningWetOutCatalystsDetails = new FullLengthLiningWetOutCatalystsDetails(fullLengthLiningTDS);
                fullLengthLiningWetOutCatalystsDetails.LoadAll(workId, companyId);
                grdCatalysts.DataBind();

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

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

            return validData;
        }
        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 currentProjectId = Int32.Parse(hdfCurrentProjectId.Value.ToString());

            string measuredFromMh = "";

            FullLengthLiningLateralDetails flLateralDetails = new FullLengthLiningLateralDetails();
            flLateralDetails.LoadForEdit(workId, assetId, companyId, currentProjectId);

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

            // Generate increment
            string lateralIdIncrement = "";
            FullLengthLiningLateralDetails fullLengthLiningLateraldetails = new FullLengthLiningLateralDetails(fullLengthLiningTDS);

            if (measuredFromMh == "USMH" || measuredFromMh == "")
            {
                lateralIdIncrement = fullLengthLiningLateraldetails.GetMaxLateralId2();

            }
            else
            {
                if (measuredFromMh == "DSMH")
                {
                    lateralIdIncrement = fullLengthLiningLateraldetails.GetMinLateralId2();
                }
            }

            return "FL-"+lateralIdIncrement;
        }
        protected void Page_PreRender(object sender, EventArgs e)
        {
            // Set active toolbar
            mForm8 master = (mForm8)this.Master;
            master.ActiveToolbar = "eSewers";

            // For error message
            hdfErrorFieldList.Value = "";
            if ((tbxWetOutDataHoistHeight.Text == "OK")|| (tbxWetOutDataHoistHeight.Text == ""))
            {
                lblWetOutDataWarning.Visible = false;
            }
            else
            {
                lblWetOutDataWarning.Visible = true;
            }

            // 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 currentProjectId = Int32.Parse(hdfCurrentProjectId.Value.ToString());

            // set visible VideoDoneFromMh and Measured From and To
            FullLengthLiningWorkDetailsGateway flWorkDetailsGateway = new FullLengthLiningWorkDetailsGateway();
            flWorkDetailsGateway.LoadByWorkIdAssetId(workId, assetId, companyId);

            FullLengthLiningLateralDetails flLateralDetails = new FullLengthLiningLateralDetails();
            flLateralDetails.LoadForEdit(workId, 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 (m1)
            MaterialInformationGateway materialInformationGateway = new MaterialInformationGateway();
            materialInformationGateway.LoadLastMaterialByAssetId(assetId, companyId);

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

            // For PreFlush Date and PreVideo Date
            int projectId = Int32.Parse(hdfCurrentProjectId.Value);
            FullLengthLiningWorkDetailsGateway  fullLengthLiningWorkDetailsGateway = new FullLengthLiningWorkDetailsGateway();
            fullLengthLiningWorkDetailsGateway.LoadByWorkIdAssetId(workId, assetId, companyId);

            int? raProjectId = fullLengthLiningWorkDetailsGateway.GetRaProjectId(workId);
            if ((raProjectId.HasValue) && (raProjectId == projectId))
            {
                // ... if ra data is from the same project
                tkrdpGeneralPreFlushDate.Visible = true;
                tkrdpGeneralPreVideoDate.Visible = true;
                tkrdpGeneralPreFlushDateReadOnly.Visible = false;
                tkrdpGeneralPreVideoDateReadOnly.Visible = false;
            }
            else
            {
                tkrdpGeneralPreFlushDate.Visible = false;
                tkrdpGeneralPreVideoDate.Visible = false;
                tkrdpGeneralPreFlushDateReadOnly.Visible = true;
                tkrdpGeneralPreVideoDateReadOnly.Visible = true;
            }
            // ... if there is no data
            if (tkrdpGeneralPreFlushDate.SelectedDate.HasValue)
            {
                tkrdpGeneralPreFlushDate.Calendar.Enabled = false;
                tkrdpGeneralPreFlushDate.DateInput.ReadOnly = true;
            }
            else
            {
                tkrdpGeneralPreFlushDate.Calendar.Enabled = true;
                tkrdpGeneralPreFlushDate.DateInput.ReadOnly = false;
            }

            if (tkrdpGeneralPreVideoDate.SelectedDate.HasValue)
            {
                tkrdpGeneralPreVideoDate.Calendar.Enabled = false;
                tkrdpGeneralPreVideoDate.DateInput.ReadOnly = true;
            }
            else
            {
                tkrdpGeneralPreVideoDate.Calendar.Enabled = true;
                tkrdpGeneralPreVideoDate.DateInput.ReadOnly = false;
            }

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

            if (tbxFlowSectionId.Text == "")
            {
                LoadFullLengthLiningData(currentProjectId, assetId, companyId);
            }

            // Validate tools
            if (Convert.ToBoolean(Session["sgLFS_CWP_FULLLENGTHLINING_ADMIN"]))
            {
                tkrpbLeftMenuTools.Items[0].Items[1].Visible = true; // Resins option
                tkrpbLeftMenuTools.Items[0].Items[2].Visible = true; // Catalyst option

                tkrdpInstallDataInstallDate.Enabled = true;
                tkrdpInstallDataFinalVideoDate.Enabled = true;
            }
            else
            {
                tkrpbLeftMenuTools.Items[0].Items[1].Visible = false; // Resins option
                tkrpbLeftMenuTools.Items[0].Items[2].Visible = false; // Catalyst option

                tkrdpInstallDataInstallDate.Enabled = false;
                tkrdpInstallDataFinalVideoDate.Enabled = false;
            }
        }
        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 distance from dsmh and reverse setup
            FullLengthLiningLateralDetails fullLengthLiningLateralDetails = new FullLengthLiningLateralDetails(fullLengthLiningTDS);
            fullLengthLiningLateralDetails.UpdateLengthReverseSetup(workId, assetId, videoLength);

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

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

                    reverseSetup = GetDistance(reverseSetup);

                    ((TextBox)grdLaterals.Rows[i].Cells[2].FindControl("tbxReverseSetup")).Text = reverseSetup;
                }
            }
        }
        protected void grdLaterals_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            Page.Validate("AddLateralsEdit");
            if (Page.IsValid)
            {
                if (((DropDownList)grdLaterals.Rows[e.RowIndex].Cells[2].FindControl("ddlLiveEdit")).Visible == true)
                {
                    Page.Validate("AddLateralsEditSpecial");
                }

                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;

                    // 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 = ((CheckBox)grdLaterals.Rows[e.RowIndex].Cells[3].FindControl("cbxInProject")).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();
                    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;
                    string flange = ((DropDownList)grdLaterals.Rows[e.RowIndex].Cells[2].FindControl("ddlFlangeEdit")).SelectedValue;
                    bool lineLateral = ((CheckBox)grdLaterals.Rows[e.RowIndex].Cells[2].FindControl("cbxJlEdit")).Checked; ;
                    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;
                    }

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

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

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

                    // Update JL lateral issues
                    FLLateralsSave(lateralId, requiredRoboticPrep, requiredRoboticPrepDate, holdClientIssue, holdLFSIssue, dyeTestReq, dyeTestComplete);
                }
                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_FULLLENGTHLINING_VIEW"]) && Convert.ToBoolean(Session["sgLFS_CWP_FULLLENGTHLINING_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 fl_edit.aspx");
                    }

                    // Tag Page
                    TagPage();

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

                    materialInformationTDS = new MaterialInformationTDS();

                    // ... for wet out section list
                    AssetSewerSectionList assetSewerSectionList = new AssetSewerSectionList();
                    assetSewerSectionList.LoadAndAddItem(Int32.Parse(hdfCurrentProjectId.Value), hdfWorkType.Value, "-1", "(All)", Int32.Parse(hdfCompanyId.Value));
                    cbxlSectionId.DataSource = assetSewerSectionList.Table;
                    cbxlSectionId.DataValueField = "SectionID";
                    cbxlSectionId.DataTextField = "FlowOrderID";
                    cbxlSectionId.DataBind();

                    cbxlInversionDataSectionId.DataSource = assetSewerSectionList.Table;
                    cbxlInversionDataSectionId.DataValueField = "SectionID";
                    cbxlInversionDataSectionId.DataTextField = "FlowOrderID";
                    cbxlInversionDataSectionId.DataBind();

                    // 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());
                    string workType = hdfWorkType.Value;

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

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

                            fullLengthLiningTDS = new FullLengthLiningTDS();

                            FullLengthLiningSectionDetails fullLengthLiningSectionDetails = new FullLengthLiningSectionDetails(fullLengthLiningTDS);
                            fullLengthLiningSectionDetails.LoadByWorkId(workId, companyId);

                            FullLengthLiningWorkDetails fullLengthLiningWorkDetails = new FullLengthLiningWorkDetails(fullLengthLiningTDS);
                            fullLengthLiningWorkDetails.LoadByWorkIdAssetId(workId, assetId, companyId);

                            FullLengthLiningLateralDetails fullLengthLiningLateralDetails = new FullLengthLiningLateralDetails(fullLengthLiningTDS);
                            fullLengthLiningLateralDetails.LoadForEdit(workId, assetId, companyId, currentProjectId);

                            FullLengthLiningWetOutCatalystsDetails fullLengthLiningWetOutCatalystsDetails = new FullLengthLiningWetOutCatalystsDetails(fullLengthLiningTDS);
                            fullLengthLiningWetOutCatalystsDetails.LoadAll(workId, companyId);
                        }
                        else
                        {
                            hdfActiveTab.Value = (string)Session["activeTabFll"];

                            // Restore datasets
                            fullLengthLiningTDS = (FullLengthLiningTDS)Session["fullLengthLiningTDS"];
                        }

                        // ... Store dataset
                        Session["fullLengthLiningTDS"] = fullLengthLiningTDS;
                    }

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

                        // ... Restore dataset
                        fullLengthLiningTDS = (FullLengthLiningTDS)Session["fullLengthLiningTDS"];

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

                        if (ViewState["update"].ToString().Trim() == "yes")
                        {
                            FullLengthLiningSectionDetails fullLengthLiningSectionDetails = new FullLengthLiningSectionDetails(fullLengthLiningTDS);
                            fullLengthLiningSectionDetails.LoadByWorkId(workId, companyId);

                            FullLengthLiningWorkDetails fullLengthLiningWorkDetails = new FullLengthLiningWorkDetails(fullLengthLiningTDS);
                            fullLengthLiningWorkDetails.LoadByWorkIdAssetId(workId, assetId, companyId);

                            FullLengthLiningLateralDetails fullLengthLiningLateralDetails = new FullLengthLiningLateralDetails(fullLengthLiningTDS);
                            fullLengthLiningLateralDetails.LoadForEdit(workId, assetId, companyId, currentProjectId);

                            FullLengthLiningWetOutCatalystsDetails fullLengthLiningWetOutCatalystsDetails = new FullLengthLiningWetOutCatalystsDetails(fullLengthLiningTDS);
                            fullLengthLiningWetOutCatalystsDetails.LoadAll(workId, companyId);

                            // ... Store dataset
                            Session["fullLengthLiningTDS"] = fullLengthLiningTDS;
                        }
                    }

                    // Prepare initial data
                    lblMissingData.Visible = false;

                    // Set initial tab
                    int activeTab = Int32.Parse(hdfActiveTab.Value);
                    tcFlDetails.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 full length lining work
                    LoadFullLengthLiningData(currentProjectId, assetId, companyId);

                    // Databind
                    Page.DataBind();

                    // Especial load for Run details
                    string runDetails = hdfRunDetails.Value;
                    WorkFullLengthLiningWetOutGateway workFullLengthLiningWetOutGateway = new WorkFullLengthLiningWetOutGateway();
                    workFullLengthLiningWetOutGateway.LoadByWorkId(workId, companyId);

                    // ... Verify if work has cipp information to load run details
                    if (workFullLengthLiningWetOutGateway.Table.Rows.Count > 0)
                    {
                        string[] runDetailsList = runDetails.Split('>');
                        for (int i = 0; i < runDetailsList.Length; i++)
                        {
                            cbxlSectionId.Items.FindByValue(runDetailsList[i]).Selected = true;
                            cbxlInversionDataSectionId.Items.FindByValue(runDetailsList[i]).Selected = true;
                        }
                    }
                    else
                    {
                        if (cbxlSectionId.Items.Count > 1)
                        {
                            cbxlSectionId.Items.FindByValue(runDetails).Selected = true;
                        }
                    }

                    // SelectIndex for grids
                    ((DropDownList)grdLaterals.FooterRow.FindControl("ddlNewMaterial")).SelectedIndex = 0;
                    ((DropDownList)grdCatalysts.FooterRow.FindControl("ddlNameFooter")).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;

                    // Make Wetout tab visible
                    if (ckbxWetOutDataIncludeWetOutInformation.Checked)
                    {
                        pnlVisibleInformation.Visible = true;
                        upnlVisibleInformation.Update();
                    }
                    else
                    {
                        pnlVisibleInformation.Visible = false;
                        upnlVisibleInformation.Update();
                    }

                    // Make inversion tab visible
                    lblInversionDataInversionMissingData.Visible = false;
                    uplInversionDataInversionMissingData.Update();
                    if (ckbxInversionDataIncludeInversionInformation.Checked)
                    {
                        // ... ... visible only if wet out information is provided.
                        if (!ckbxWetOutDataIncludeWetOutInformation.Checked)
                        {
                            pnlInversionVisibleInformation.Visible = false;
                            upnlInversionVisibleInformation.Update();
                        }
                        else
                        {

                            pnlInversionVisibleInformation.Visible = true;
                            upnlInversionVisibleInformation.Update();
                        }
                    }
                    else
                    {
                        pnlInversionVisibleInformation.Visible = false;
                        upnlInversionVisibleInformation.Update();
                    }

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

                    materialInformation = materialInformationTDS.MaterialInformation;
                    Session["materialInformationTDS"] = materialInformationTDS;
                }
            }
            else
            {
                // Restore datasets
                fullLengthLiningTDS = (FullLengthLiningTDS)Session["fullLengthLiningTDS"];
                flatSectionJlTDSForFLL = (FlatSectionJlTDS)Session["flatSectionJlTDSForFLL"];
                materialInformationTDS = (MaterialInformationTDS)Session["materialInformationTDS"];
                materialInformation = materialInformationTDS.MaterialInformation;

                // Set initial tab
                int activeTab = Int32.Parse(hdfActiveTab.Value);
                tcFlDetails.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(hdfWorkId.Value);
            int currentProjectId = Int32.Parse(hdfCurrentProjectId.Value.ToString());

            FullLengthLiningLateralDetails flLateralDetails = new FullLengthLiningLateralDetails();
            flLateralDetails.LoadForEdit(workId, assetId, companyId, currentProjectId);

            if (flLateralDetails.Table.Rows.Count > 0)
            {
                args.IsValid = true;
            }
            else
            {
                if (ddlM1DataMeasuredFromMh.SelectedValue == "")
                {
                    args.IsValid = false;
                }
                else
                {
                    args.IsValid = true;
                }
            }
        }
        private void Delete()
        {
            Page.Validate();

            if (Page.IsValid)
            {
                // Delete full length lining
                int workId = Int32.Parse(hdfWorkId.Value);
                FullLengthLiningSectionDetails fullLengthLiningSectionDetails = new FullLengthLiningSectionDetails(fullLengthLiningTDS);
                fullLengthLiningSectionDetails.Delete(workId);

                FullLengthLiningLateralDetails fullLengthLiningLateralDetails = new FullLengthLiningLateralDetails(fullLengthLiningTDS);
                fullLengthLiningLateralDetails.DeleteAll(workId);

                FullLengthLiningWorkDetails fullLengthLiningWorkDetails = new FullLengthLiningWorkDetails(fullLengthLiningTDS);
                fullLengthLiningWorkDetails.Delete(workId);

                // Update databse
                UpdateDatabase();

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

                // Redirect
                string url = "";
                url = "./fl_navigator2.aspx?source_page=fl_delete.aspx&client_id=" + hdfCurrentClientId.Value + "&project_id=" + hdfCurrentProjectId.Value + GetNavigatorState() + "&update=yes";
                Response.Redirect(url);
            }
        }
        protected void cvLateralId_ServerValidate(object source, ServerValidateEventArgs args)
        {
            FullLengthLiningLateralDetails model = new FullLengthLiningLateralDetails(fullLengthLiningTDS);

            // 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 currentProjectId = Int32.Parse(hdfCurrentProjectId.Value.ToString());

            string measuredFromMh = "";

            FullLengthLiningLateralDetails flLateralDetails = new FullLengthLiningLateralDetails();
            flLateralDetails.LoadForEdit(workId, assetId, companyId, currentProjectId);

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

            // Generate increment
            FullLengthLiningLateralDetails fullLengthLiningLateraldetails = new FullLengthLiningLateralDetails(fullLengthLiningTDS);

            if (measuredFromMh == "USMH" || measuredFromMh == "")
            {
                if (fullLengthLiningLateraldetails.GetMaxLateralId2() == "A[") args.IsValid = false; else args.IsValid = true;

            }
            else
            {
                if (measuredFromMh == "DSMH")
                {
                    if (fullLengthLiningLateraldetails.GetMinLateralId2() == "@") args.IsValid = false; else args.IsValid = true;
                }
            }
        }
        // ////////////////////////////////////////////////////////////////////////
        // EVENTS
        //
        protected void Page_Load(object sender, EventArgs e)
        {
            // Register client scripts
            this.RegisterClientScripts();

            if (!IsPostBack)
            {
                // Security check
                if (!(Convert.ToBoolean(Session["sgLFS_CWP_FULLLENGTHLINING_VIEW"]) && Convert.ToBoolean(Session["sgLFS_CWP_FULLLENGTHLINING_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 fl_summary.aspx");
                }

                // Tag Page
                TagPage();

                Session.Remove("flAddLateralsNewDummy");
                Session.Remove("wetOutCatalystsDetailsDummy");

                // If comming 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);

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

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

                        fullLengthLiningTDS = new FullLengthLiningTDS();

                        FullLengthLiningSectionDetails fullLengthLiningSectionDetails = new FullLengthLiningSectionDetails(fullLengthLiningTDS);
                        fullLengthLiningSectionDetails.LoadByWorkId(workId, companyId);

                        FullLengthLiningWorkDetails fullLengthLiningWorkDetails = new FullLengthLiningWorkDetails(fullLengthLiningTDS);
                        fullLengthLiningWorkDetails.LoadByWorkIdAssetId(workId, assetId, companyId);

                        FullLengthLiningLateralDetails fullLengthLiningLateralDetails = new FullLengthLiningLateralDetails(fullLengthLiningTDS);
                        fullLengthLiningLateralDetails.LoadForEdit(workId, assetId, companyId, currentProjectId);

                        FullLengthLiningWetOutCatalystsDetails fullLengthLiningWetOutCatalystsDetails = new FullLengthLiningWetOutCatalystsDetails(fullLengthLiningTDS);
                        fullLengthLiningWetOutCatalystsDetails.LoadAll(workId, companyId);
                    }
                    else
                    {
                        hdfActiveTab.Value = (string)Session["activeTabFll"];

                        // Restore datasets
                        fullLengthLiningTDS = (FullLengthLiningTDS)Session["fullLengthLiningTDS"];
                    }

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

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

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

                    // Restore dataset
                    fullLengthLiningTDS = (FullLengthLiningTDS)Session["fullLengthLiningTDS"];

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

                    tcFlDetails.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";

                // ... for wet out section list
                AssetSewerSectionList assetSewerSectionList = new AssetSewerSectionList();
                assetSewerSectionList.LoadAndAddItem(Int32.Parse(hdfCurrentProjectId.Value), hdfWorkType.Value, "-1", "(All)", Int32.Parse(hdfCompanyId.Value));
                cbxlWetOutDataSectionId.DataSource = assetSewerSectionList.Table;
                cbxlWetOutDataSectionId.DataValueField = "SectionID";
                cbxlWetOutDataSectionId.DataTextField = "FlowOrderID";
                cbxlWetOutDataSectionId.DataBind();

                cbxlInversionDataSectionId.DataSource = assetSewerSectionList.Table;
                cbxlInversionDataSectionId.DataValueField = "SectionID";
                cbxlInversionDataSectionId.DataTextField = "FlowOrderID";
                cbxlInversionDataSectionId.DataBind();

                // ... Data for current full length lining work
                LoadFullLengthLiningData(currentProjectId, assetId, companyId);

                // Databind
                Page.DataBind();

                // Especial load for Run details
                string runDetails = hdfRunDetails.Value;
                WorkFullLengthLiningWetOutGateway workFullLengthLiningWetOutGateway = new WorkFullLengthLiningWetOutGateway();
                workFullLengthLiningWetOutGateway.LoadByWorkId(workId, companyId);

                // ... Verify if work has cipp information to load run details
                if (workFullLengthLiningWetOutGateway.Table.Rows.Count > 0)
                {
                    string[] runDetailsList = runDetails.Split('>');
                    for (int i = 0; i < runDetailsList.Length; i++)
                    {
                        cbxlWetOutDataSectionId.Items.FindByValue(runDetailsList[i]).Selected = true;
                        cbxlInversionDataSectionId.Items.FindByValue(runDetailsList[i]).Selected = true;
                    }
                }
                else
                {
                    if (cbxlWetOutDataSectionId.Items.Count > 1)
                    {
                        cbxlWetOutDataSectionId.Items.FindByValue(hdfSectionId.Value).Selected = true;
                    }
                }
            }
            else
            {
                // Restore datasets
                fullLengthLiningTDS = (FullLengthLiningTDS)Session["fullLengthLiningTDS"];

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

                // Load summary for inversionfield cure record
                int companyId =Int32.Parse(hdfCompanyId.Value);
                int workId = Int32.Parse(hdfWorkId.Value);

                FlInversionFieldCureRecord FlInversionFieldCureRecordForSummary = new FlInversionFieldCureRecord();
                FlInversionFieldCureRecordForSummary.Load(workId, companyId);
                if (FlInversionFieldCureRecordForSummary.Table.Rows.Count > 0)
                {
                    lblInversionDataFieldCureRecordSummary.Text = FlInversionFieldCureRecordForSummary.GetSummary();
                }

            }
        }
        /// <summary>
        /// Save
        /// </summary>
        /// <param name="projectId">projectId</param>
        /// <param name="countryId">countryId</param>
        /// <param name="provinceId">provinceId</param>
        /// <param name="countyId">countyId</param>
        /// <param name="cityId">cityId</param>
        /// <param name="companyId">companyId</param>
        /// <param name="loginId">loginId</param>
        public void Save(int projectId, Int64 countryId, Int64? provinceId, Int64? countyId, Int64? cityId, int companyId, int loginId)
        {
            FullLengthLiningTDS fullLengthLiningTDS = new FullLengthLiningTDS();

            foreach (WincapBulkUploadTDS.WincapBulkUploadRow row in (WincapBulkUploadTDS.WincapBulkUploadDataTable)Table)
            {
                string state = ""; if (!row.IsStateNull()) state = row.State;
                string direction = ""; if (!row.IsDirectionNull()) direction = row.Direction;
                string distance = ""; if (!row.IsDistanceNull()) distance = row.Distance;
                string videoDistance = ""; if (!row.IsVideoDistanceNull()) videoDistance = row.VideoDistance;
                string clockPosition = ""; if (!row.IsClockPositionNull()) clockPosition = row.ClockPosition;
                string distanceToCentre = ""; if (!row.IsDistanceToCentreNull()) distanceToCentre = row.DistanceToCentre;
                string reverseSetup = ""; if (!row.IsReverseSetupNull()) reverseSetup = row.ReverseSetup;
                string comments = ""; if (!row.IsCommentsNull()) comments = row.Comments;
                string measuredFromMh = "USMH";
                if (row.Direction.Contains("D"))
                {
                    measuredFromMh = "DSMH";
                }

                int section_assetId = SaveSection(row.SectionID, projectId, countryId, provinceId, countyId, cityId, companyId);

                WorkFullLengthLining workFullLengthLining = new WorkFullLengthLining(null);
                int workId = workFullLengthLining.InsertDirectEmptyWorks(projectId, section_assetId, null, "", null, null, null, null, null, null, null, false, false, false, false, false, false, false, companyId, false, "", "");

                FullLengthLiningLateralDetails flLateralDetails = new FullLengthLiningLateralDetails();
                flLateralDetails.LoadForEdit(workId, section_assetId, companyId, projectId);

                // Generate increment
                string lateralIdIncrement = "";

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

                string videoLength = "";

                string lateralId = "FL-" + lateralIdIncrement;

                FullLengthLiningLateralDetails model = new FullLengthLiningLateralDetails(fullLengthLiningTDS);
                model.Insert(videoDistance, clockPosition, distanceToCentre, "", reverseSetup, null, comments, lateralId, "", "", false, companyId, true, state, "", "", "", "", null, false, null, false, false, false, "", false, false, null);

                model.Save(workId, projectId, section_assetId, countryId, provinceId, countyId, cityId, videoLength, companyId, false, false, null);
            }
        }
        // ////////////////////////////////////////////////////////////////////////
        // EVENTS
        //
        protected void Page_Load(object sender, EventArgs e)
        {
            // Register client scripts
            this.RegisterClientScripts();

            if (!IsPostBack)
            {
                // Security check
                if (!(Convert.ToBoolean(Session["sgLFS_CWP_FULLLENGTHLINING_VIEW"]) && Convert.ToBoolean(Session["sgLFS_CWP_FULLLENGTHLINING_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) || ((string)Request.QueryString["asset_id"] == null))
                {
                    Response.Redirect("./../../error_page.aspx?error=" + "Invalid query string in fl_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 Section";

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

                    fullLengthLiningTDS = new FullLengthLiningTDS();

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

                    FullLengthLiningSectionDetails fullLengthLiningSectionDetails = new FullLengthLiningSectionDetails(fullLengthLiningTDS);
                    fullLengthLiningSectionDetails.LoadByWorkId(workId, companyId);

                    FullLengthLiningWorkDetails fullLengthLiningWorkDetails = new FullLengthLiningWorkDetails(fullLengthLiningTDS);
                    fullLengthLiningWorkDetails.LoadByWorkIdAssetId(workId, assetId, companyId);

                    FullLengthLiningLateralDetails fullLengthLiningLateralDetails = new FullLengthLiningLateralDetails(fullLengthLiningTDS);
                    fullLengthLiningLateralDetails.LoadAllByWorkId(workId, companyId);

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

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

                    // Restore dataset
                    fullLengthLiningTDS = (FullLengthLiningTDS)Session["fullLengthLiningTDS"];
                }
            }
            else
            {
                // Restore datasets
                fullLengthLiningTDS = (FullLengthLiningTDS)Session["fullLengthLiningTDS"];
            }
        }
        private void GrdFLAddLateralsNewAdd()
        {
            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 = ((CheckBox)grdLaterals.FooterRow.FindControl("cbxInProject")).Checked;
                    int workId = Int32.Parse(hdfWorkId.Value);
                    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;
                    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 = ((CheckBox)grdLaterals.FooterRow.FindControl("cbxNewJl")).Checked;
                    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;

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

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

                    tbxLaterals.Text = model.GetTotalLaterals().ToString();
                    tbxLiveLaterals.Text = model.GetLiveLaterals().ToString();
                }
            }
        }
        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);
            FullLengthLiningLateralDetails model = new FullLengthLiningLateralDetails(fullLengthLiningTDS);

            // Delete lateral
            model.Delete(lateral);

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

            // Store dataset
            Session["fullLengthLiningTDS"] = fullLengthLiningTDS;
        }
        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 sectionAssetId = Int32.Parse(hdfAssetId.Value);
            bool isNewMeasuredFromDsmh = false;

            FullLengthLiningLateralDetails flLateralDetails = new FullLengthLiningLateralDetails();
            flLateralDetails.LoadForEdit(workId, sectionAssetId, companyId, projectId);

            if (flLateralDetails.Table.Rows.Count == 0)
            {
                if (ddlM1DataMeasuredFromMh.SelectedValue == "DSMH")
                {
                    isNewMeasuredFromDsmh = true;
                    FullLengthLiningLateralDetails fllLateralDetails = new FullLengthLiningLateralDetails(fullLengthLiningTDS);
                    fllLateralDetails.ModifyLateralId();
                }
            }

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

                FullLengthLiningLateralDetails fullLengthLiningLateralDetails = new FullLengthLiningLateralDetails(fullLengthLiningTDS);
                fullLengthLiningLateralDetails.Save(workId, projectId, sectionAssetId, countryId, provinceId, countyId, cityId, tbxVideoLength.Text.Trim(), companyId, isNewMeasuredFromDsmh, roboticPrepCompleted, roboticPrepCompletedCompleted);

                // Save catalyst details
                string newRunDetails = "";
                foreach (ListItem lst in cbxlSectionId.Items)
                {
                    if (lst.Selected)
                    {
                        newRunDetails = newRunDetails + lst.Value + ">";
                    }
                }
                newRunDetails = newRunDetails.Substring(0, newRunDetails.Length - 1);
                FullLengthLiningWetOutCatalystsDetails fullLengthLiningWetOutCatalystsDetails = new FullLengthLiningWetOutCatalystsDetails(fullLengthLiningTDS);
                fullLengthLiningWetOutCatalystsDetails.Save(companyId, newRunDetails, projectId);

                // Save section details
                FullLengthLiningSectionDetails fullLengthLiningSectionDetails = new FullLengthLiningSectionDetails(fullLengthLiningTDS);
                fullLengthLiningSectionDetails.Save(countryId, provinceId, countyId, cityId, projectId, companyId);

                // Save work details
                FullLengthLiningWorkDetails fullLengthLiningWorkDetails = new FullLengthLiningWorkDetails(fullLengthLiningTDS);
                fullLengthLiningWorkDetails.Save(countryId, provinceId, countyId, cityId, projectId, sectionAssetId, companyId, ckbxWetOutDataIncludeWetOutInformation.Checked, ckbxInversionDataIncludeInversionInformation.Checked);

                // 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
                fullLengthLiningTDS.AcceptChanges();
                Session["fullLengthLiningTDS"] = fullLengthLiningTDS;

                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 void UpdateDatabase()
        {
            try
            {
                TeamProjectTime2Gateway teamProjectTime2Gateway = new TeamProjectTime2Gateway(teamProjectTime2TDSToSave);
                teamProjectTime2Gateway.Update(projectTime2TDS);

                teamProjectTime2TDSToSave.AcceptChanges();
                teamProjectTime2TDS.AcceptChanges();
                projectTime2TDS.AcceptChanges();
                Session["teamProjectTime2TDS"] = teamProjectTime2TDS;
            }
            catch (Exception ex)
            {
                string url = string.Format("./../../error_page.aspx?error={0}", ex.Message.Replace('\n', ' '));
                Response.Redirect(url);
            }

            DB.Open();
            DB.BeginTransaction();
            try
            {
                if (ddlTypeOfWork.SelectedValue == "MH Rehab")
                {
                    int companyId = Int32.Parse(hdfCompanyId.Value);

                    // Get ids & location
                    int projectId = Int32.Parse(ddlProject.SelectedValue);
                    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);

                    manholeRehabilitationTDS = new ManholeRehabilitationTDS();
                    ManholeRehabilitationWorkDetails manholeRehabilitationWorkDetails = new ManholeRehabilitationWorkDetails(manholeRehabilitationTDS);
                    ManholeRehabilitationWorkDetailsGateway manholeRehabilitationWorkDetailsGateway = new ManholeRehabilitationWorkDetailsGateway(manholeRehabilitationTDS);

                    switch (ddlFunction.SelectedValue)
                    {
                        case "Prep":
                            foreach (GridViewRow row in grdManholesRehabPrep.Rows)
                            {
                                bool selected = ((CheckBox)row.FindControl("cbxSelected")).Checked;
                                DateTime? prepDate = Convert.ToDateTime(((Label)row.FindControl("lblPrepDate")).Text);

                                if (selected)
                                {
                                    int assetId = Convert.ToInt32(grdManholesRehabPrep.DataKeys[row.RowIndex].Values["AssetID"].ToString());
                                    int workId = 0;

                                    workId = GetWorkId(Int32.Parse(ddlProject.SelectedValue), assetId, "Manhole Rehabilitation", companyId);

                                    manholeRehabilitationWorkDetails.LoadByWorkIdAssetId(workId, assetId, Int32.Parse(hdfCompanyId.Value));

                                    if (manholeRehabilitationWorkDetailsGateway.Table.Rows.Count > 0)
                                    {
                                        int? batchId = manholeRehabilitationWorkDetailsGateway.GetBatchID(workId);
                                        manholeRehabilitationWorkDetails.Update(workId, prepDate, manholeRehabilitationWorkDetailsGateway.GetSprayedDate(workId), batchId, manholeRehabilitationWorkDetailsGateway.GetDate(workId).Value, companyId);
                                    }
                                    else
                                    {
                                        manholeRehabilitationWorkDetails.Update(workId, prepDate, null, null, DateTime.Now, companyId);
                                    }

                                    manholeRehabilitationWorkDetails.Save2(countryId, provinceId, countyId, cityId, projectId, assetId, companyId, true);
                                }
                            }
                            break;

                        case "Spray":
                            foreach (GridViewRow row in grdManholesRehabSpray.Rows)
                            {
                                bool selected = ((CheckBox)row.FindControl("cbxSelected")).Checked;
                                DateTime? sprayDate = Convert.ToDateTime(((Label)row.FindControl("lblSprayDate")).Text);

                                if (selected)
                                {
                                    int assetId = Convert.ToInt32(grdManholesRehabSpray.DataKeys[row.RowIndex].Values["AssetID"].ToString());
                                    int workId = 0;

                                    workId = GetWorkId(Int32.Parse(ddlProject.SelectedValue), assetId, "Manhole Rehabilitation", companyId);

                                    manholeRehabilitationWorkDetails.LoadByWorkIdAssetId(workId, assetId, Int32.Parse(hdfCompanyId.Value));

                                    if (manholeRehabilitationWorkDetailsGateway.Table.Rows.Count > 0)
                                    {
                                        int? batchId = manholeRehabilitationWorkDetailsGateway.GetBatchID(workId);
                                        manholeRehabilitationWorkDetails.Update(workId, manholeRehabilitationWorkDetailsGateway.GetPreppedDate(workId), sprayDate, batchId, manholeRehabilitationWorkDetailsGateway.GetDate(workId).Value, companyId);
                                    }
                                    else
                                    {
                                        manholeRehabilitationWorkDetails.Update(workId, null, sprayDate, null, DateTime.Now, companyId);
                                    }

                                    manholeRehabilitationWorkDetails.Save2(countryId, provinceId, countyId, cityId, projectId, assetId, companyId, true);
                                }
                            }
                            break;
                    }

                    DB.CommitTransaction();

                    // Store datasets
                    manholeRehabilitationTDS.AcceptChanges();
                }
                else
                {
                    if (ddlTypeOfWork.SelectedValue == "Full Length")
                    {
                        fullLengthLiningTDS = new FullLengthLiningTDS();
                        AssetSewerSectionGateway aass = new AssetSewerSectionGateway();
                        FullLengthLiningWorkDetails fullLengthLiningWorkDetails = new FullLengthLiningWorkDetails(fullLengthLiningTDS);
                        FullLengthLiningWorkDetailsGateway fullLengthLiningWorkDetailsGateway = new FullLengthLiningWorkDetailsGateway(fullLengthLiningTDS);

                        int assetId = 0;
                        int workId = 0;

                        // Get ids & location
                        int projectId = Int32.Parse(ddlProject.SelectedValue);
                        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);

                        int companyId = Int32.Parse(hdfCompanyId.Value);

                        switch (ddlFunction.SelectedValue)
                        {
                            case "Install":
                                foreach (GridViewRow row in grdSectionsInstall.Rows)
                                {
                                    bool selected = ((CheckBox)row.FindControl("cbxSelected")).Checked;
                                    DateTime? installDate = Convert.ToDateTime(((Label)row.FindControl("lblInstallDate")).Text);

                                    if (selected)
                                    {
                                        if (installDate != tkrdpDate_.SelectedDate.Value)
                                        {
                                            installDate = tkrdpDate_.SelectedDate.Value;
                                        }

                                        string sectionId = grdSectionsInstall.DataKeys[row.RowIndex].Values["SectionID"].ToString();
                                        aass.LoadBySectionId(sectionId, companyId);
                                        assetId = aass.GetAssetID(sectionId);
                                        workId = GetWorkId(Int32.Parse(ddlProject.SelectedValue), assetId, "Full Length Lining", companyId);

                                        fullLengthLiningWorkDetails.LoadByWorkIdAssetId(workId, assetId, Int32.Parse(hdfCompanyId.Value));
                                        fullLengthLiningWorkDetails.Update(workId, fullLengthLiningWorkDetailsGateway.GetP1Date(workId), fullLengthLiningWorkDetailsGateway.GetP1Completed(workId), installDate, fullLengthLiningWorkDetailsGateway.GetFinalVideoDate(workId));
                                        fullLengthLiningWorkDetails.Save(countryId, provinceId, countyId, cityId, projectId, assetId, companyId, false, false);
                                    }
                                }
                                break;

                            case "Prep & Measure":
                                foreach (GridViewRow row in grdSections.Rows)
                                {
                                    bool selected = ((CheckBox)row.FindControl("cbxSelected")).Checked;
                                    bool completed = ((CheckBox)row.FindControl("cbxCompleted")).Checked;
                                    DateTime? prepDate = Convert.ToDateTime(((Label)row.FindControl("lblPrepDate")).Text);

                                    if (selected)
                                    {
                                        if (completed)
                                        {
                                            if (prepDate != tkrdpDate_.SelectedDate.Value)
                                            {
                                                prepDate = tkrdpDate_.SelectedDate.Value;
                                            }
                                        }
                                        else
                                        {
                                            prepDate = null;
                                        }

                                        string sectionId = grdSections.DataKeys[row.RowIndex].Values["SectionID"].ToString();
                                        aass.LoadBySectionId(sectionId, companyId);
                                        assetId = aass.GetAssetID(sectionId);
                                        workId = GetWorkId(Int32.Parse(ddlProject.SelectedValue), assetId, "Full Length Lining", companyId);

                                        fullLengthLiningWorkDetails.LoadByWorkIdAssetId(workId, assetId, Int32.Parse(hdfCompanyId.Value));
                                        fullLengthLiningWorkDetails.Update(workId, prepDate, completed, fullLengthLiningWorkDetailsGateway.GetInstallDate(workId), fullLengthLiningWorkDetailsGateway.GetFinalVideoDate(workId));
                                        fullLengthLiningWorkDetails.Save(countryId, provinceId, countyId, cityId, projectId, assetId, companyId, false, false);
                                    }
                                }
                                break;

                            case "Reinstate & Post Video":
                                FullLengthLiningLateralDetails fullLengthLiningLateralDetails = new FullLengthLiningLateralDetails(fullLengthLiningTDS);
                                FullLengthLiningLateralDetailsGateway fullLengthLiningLateralDetailsGateway = new FullLengthLiningLateralDetailsGateway(fullLengthLiningTDS);

                                foreach (GridViewRow row in grdSectionsReinstatePostVideo.Rows)
                                {
                                    bool selected = ((CheckBox)row.FindControl("cbxSelected")).Checked;
                                    bool completed = ((CheckBox)row.FindControl("cbxCompleted")).Checked;
                                    DateTime? postVideo = Convert.ToDateTime(((Label)row.FindControl("lblPostVideo")).Text);
                                    string sectionId = grdSectionsReinstatePostVideo.DataKeys[row.RowIndex].Values["SectionID"].ToString();

                                    aass.LoadBySectionId(sectionId, companyId);
                                    assetId = aass.GetAssetID(sectionId);
                                    workId = GetWorkId(Int32.Parse(ddlProject.SelectedValue), assetId, "Full Length Lining", companyId);

                                    if (selected)
                                    {
                                        if (completed)
                                        {
                                            if (postVideo != tkrdpDate_.SelectedDate.Value)
                                            {
                                                postVideo = tkrdpDate_.SelectedDate.Value;
                                            }
                                        }
                                        else
                                        {
                                            postVideo = null;
                                        }

                                        fullLengthLiningWorkDetails.LoadByWorkIdAssetId(workId, assetId, Int32.Parse(hdfCompanyId.Value));
                                        fullLengthLiningWorkDetails.Update(workId, fullLengthLiningWorkDetailsGateway.GetP1Date(workId), fullLengthLiningWorkDetailsGateway.GetP1Completed(workId), fullLengthLiningWorkDetailsGateway.GetInstallDate(workId), postVideo);
                                        fullLengthLiningWorkDetails.Save(countryId, provinceId, countyId, cityId, projectId, assetId, companyId, false, false);
                                    }
                                }

                                foreach (GridViewRow row in grdLaterals.Rows)
                                {
                                    string sectionId = grdLaterals.DataKeys[row.RowIndex].Values["SectionID"].ToString();
                                    int assetIdLateral = Convert.ToInt32(((Label)row.FindControl("lblAssetIDLateral")).Text);
                                    bool selected = ((CheckBox)row.FindControl("cbxSelected")).Checked;
                                    DateTime? opened = null; if (((CheckBox)row.FindControl("cbxOpened")).Checked) opened = tkrdpDate_.SelectedDate;
                                    DateTime? brushed = null; if (((CheckBox)row.FindControl("cbxBrushed")).Checked) brushed = tkrdpDate_.SelectedDate;

                                    if (selected)
                                    {
                                        aass.LoadBySectionId(sectionId, companyId);
                                        assetId = aass.GetAssetID(sectionId);
                                        workId = GetWorkId(Int32.Parse(ddlProject.SelectedValue), assetId, "Full Length Lining", companyId);

                                        fullLengthLiningLateralDetails.SaveFll(workId, assetIdLateral, companyId, opened, brushed);
                                    }
                                }
                                break;
                        }

                        DB.CommitTransaction();

                        // Store datasets
                        fullLengthLiningTDS.AcceptChanges();
                    }
                }
            }
            catch (Exception ex)
            {
                DB.RollbackTransaction();

                string url = string.Format("./../../error_page.aspx?error={0}", ex.Message.Replace('\n', ' '));
                Response.Redirect(url);
            }
        }