protected void btnDelete_Click(object sender, EventArgs e)
        {
            PostPageChanges();

            int ruleId = GetRuleId();

            if (ruleId > 0)
            {
                ServiceInformationBasicInformation serviceInformationBasicInformation = new ServiceInformationBasicInformation();
                serviceInformationBasicInformation.LoadInProgressByRuleId(ruleId, int.Parse(hdfCompanyId.Value));

                if (serviceInformationBasicInformation.Table.Rows.Count > 0)
                {
                    cvSelection.ErrorMessage = "The checklist rule have pending service requests, please complete them before delete checklist.";
                    cvSelection.IsValid = false;
                }
                else
                {
                    // Redirect
                    string url = "./checklist_rules_delete.aspx?source_page=checklist_rules_navigator.aspx&rule_id=" + ruleId;
                    Response.Redirect(url);
                }
            }
            else
            {
                cvSelection.ErrorMessage = "Please select one checklist rule.";
                cvSelection.IsValid = false;
            }
        }
        private void Save2()
        {
            // Costs Gridview, if the gridview is edition mode
            if (grdCosts.EditIndex >= 0)
            {
                grdCosts.UpdateRow(grdCosts.EditIndex, true);
            }

            // Notes Gridview, if the gridview is edition mode
            if (grdNotes.EditIndex >= 0)
            {
                grdNotes.UpdateRow(grdNotes.EditIndex, true);
            }

            // Save cost and notes data
            GrdCostsAdd();
            GrdNotesAdd();

            // Save data
            int companyId = Int32.Parse(hdfCompanyId.Value);
            int serviceId = Int32.Parse(hdfServiceId.Value);

            // Unmodified data
            ServiceInformationBasicInformationGateway serviceInformationBasicInformationGatewayForEdit = new ServiceInformationBasicInformationGateway(serviceInformationTDS);
            string serviceState = serviceInformationBasicInformationGatewayForEdit.GetServiceState(serviceId);
            string associatedChecklistRuleState = serviceInformationBasicInformationGatewayForEdit.GetAssociatedChecklistRuleState(serviceId);

            // ... Get basic service data
            bool newMtoDto = ckbxMtoDto.Checked;
            string newServiceDescription = tbxServiceDescription.Text.Trim();

            // ... Get general service data
            string newMileage = tbxGeneralMileage.Text.Trim();

            // ... Get assigned data
            DateTime? newAssignmentDateTime = null;
            DateTime? newAssignmentDeadlineDate = null;
            bool newToTeamMember = false;
            int? newAssignTeamMemberID = null;
            string newThirdPartyVendor = "";
            DateTime? assignmentAcceptedDateTime = null;
            string newAssignmentRejectedReason = "";
            DateTime? assignmentRejectedDateTime = null;

            if (pnlAssignmentData.Visible)
            {
                if (pnlAssignedToReadOnly.Visible)
                {
                    if (serviceInformationBasicInformationGatewayForEdit.GetAssignmentDateTimeOriginal(serviceId).HasValue) newAssignmentDateTime = (DateTime)serviceInformationBasicInformationGatewayForEdit.GetAssignmentDateTimeOriginal(serviceId);
                    if (serviceInformationBasicInformationGatewayForEdit.GetAssignedDeadlineDate(serviceId).HasValue) newAssignmentDeadlineDate = (DateTime)serviceInformationBasicInformationGatewayForEdit.GetAssignedDeadlineDate(serviceId);
                    newToTeamMember = serviceInformationBasicInformationGatewayForEdit.GetToTeamMember(serviceId);
                    if (newToTeamMember) newAssignTeamMemberID = (int)serviceInformationBasicInformationGatewayForEdit.GetAssignTeamMemberId(serviceId);
                    newThirdPartyVendor = serviceInformationBasicInformationGatewayForEdit.GetAssignedThirdPartyVendor(serviceId);
                }

                if (pnlAssignedTo.Visible)
                {
                    if (serviceInformationBasicInformationGatewayForEdit.GetAssignmentDateTimeOriginal(serviceId).HasValue) newAssignmentDateTime = (DateTime)serviceInformationBasicInformationGatewayForEdit.GetAssignmentDateTimeOriginal(serviceId);
                    if (tkrdpAssignmentDataAssignedDeadlineDate.SelectedDate.HasValue) newAssignmentDeadlineDate = tkrdpAssignmentDataAssignedDeadlineDate.SelectedDate.Value;
                    newToTeamMember = rbtnAssignmentDataToTeamMember.Checked;
                    if (newToTeamMember) newAssignTeamMemberID = Int32.Parse(ddlAssignmentDataAssignToTeamMember.SelectedValue);
                    newThirdPartyVendor = tbxAssignmentDataAssignToThirdPartyVendor.Text.Trim();
                }

                if (serviceInformationBasicInformationGatewayForEdit.GetAcceptedDateTime(serviceId).HasValue) assignmentAcceptedDateTime = (DateTime)serviceInformationBasicInformationGatewayForEdit.GetAcceptedDateTime(serviceId);
                if (serviceInformationBasicInformationGatewayForEdit.GetRejectedDateTime(serviceId).HasValue) assignmentRejectedDateTime = (DateTime)serviceInformationBasicInformationGatewayForEdit.GetRejectedDateTime(serviceId);
                newAssignmentRejectedReason = tbxAssignmentDataRejectedReason.Text.Trim();
            }
            else
            {
                if (pnlAssignmentDataReadOnly.Visible)
                {
                    if (serviceInformationBasicInformationGatewayForEdit.GetAssignmentDateTimeOriginal(serviceId).HasValue) newAssignmentDateTime = (DateTime)serviceInformationBasicInformationGatewayForEdit.GetAssignmentDateTimeOriginal(serviceId);
                    if (serviceInformationBasicInformationGatewayForEdit.GetAssignedDeadlineDate(serviceId).HasValue) newAssignmentDeadlineDate = (DateTime)serviceInformationBasicInformationGatewayForEdit.GetAssignedDeadlineDate(serviceId);
                    newToTeamMember = serviceInformationBasicInformationGatewayForEdit.GetToTeamMember(serviceId);
                    if (newToTeamMember) newAssignTeamMemberID = (int)serviceInformationBasicInformationGatewayForEdit.GetAssignTeamMemberId(serviceId);
                    newThirdPartyVendor = serviceInformationBasicInformationGatewayForEdit.GetAssignedThirdPartyVendor(serviceId);
                    if (serviceInformationBasicInformationGatewayForEdit.GetAcceptedDateTime(serviceId).HasValue) assignmentAcceptedDateTime = (DateTime)serviceInformationBasicInformationGatewayForEdit.GetAcceptedDateTime(serviceId);
                    if (serviceInformationBasicInformationGatewayForEdit.GetRejectedDateTime(serviceId).HasValue) assignmentRejectedDateTime = (DateTime)serviceInformationBasicInformationGatewayForEdit.GetRejectedDateTime(serviceId);
                    newAssignmentRejectedReason = tbxAssignmentDataRejectedReasonReadOnly.Text.Trim();
                }
            }

            // ... Get start work data
            DateTime? startWorkDateTime = null; if (serviceInformationBasicInformationGatewayForEdit.GetStartWorkDateTime(serviceId).HasValue) startWorkDateTime = (DateTime)serviceInformationBasicInformationGatewayForEdit.GetStartWorkDateTime(serviceId);
            DateTime? newUnitOutOfServiceDate = null;
            string newUnitOutOfServiceTime = "";
            string newStartWorkMileage = "";

            if (pnlStartWorkData.Visible)
            {
                if (tkrdpStartWorkDataUnitOutOfServiceDate.SelectedDate.HasValue) newUnitOutOfServiceDate = tkrdpStartWorkDataUnitOutOfServiceDate.SelectedDate.Value;
                newUnitOutOfServiceTime = "8:00 AM";
                newStartWorkMileage = tbxStartWorkDataStartMileage.Text.Trim();
            }
            else
            {
                if (pnlStartWorkDataReadOnly.Visible)
                {
                    newUnitOutOfServiceDate = serviceInformationBasicInformationGatewayForEdit.GetUnitOutOfServiceDate(serviceId);
                    newUnitOutOfServiceTime = serviceInformationBasicInformationGatewayForEdit.GetUnitOutOfServiceTime(serviceId);
                    newStartWorkMileage = serviceInformationBasicInformationGatewayForEdit.GetMileage(serviceId);
                }
            }

            // ... Get complete work data
            DateTime? completeWorkDateTime = null; if (serviceInformationBasicInformationGatewayForEdit.GetCompleteWorkDateTime(serviceId).HasValue) completeWorkDateTime = (DateTime)serviceInformationBasicInformationGatewayForEdit.GetCompleteWorkDateTime(serviceId);
            DateTime? newUnitBackInServiceDate = null; if (tkrdpCompleteWorkDataUnitBackInServiceDate.SelectedDate.HasValue) newUnitBackInServiceDate = tkrdpCompleteWorkDataUnitBackInServiceDate.SelectedDate.Value;
            string newUnitBackInServiceTime = "8:00 AM";
            string newCompleteWorkMileage = tbxCompleteWorkDataCompleteMileage.Text.Trim();
            string newCompleteWorkDetailDescription = "";
            bool newCompleteWorkDetailPreventable = false;

            // ... ... From team member
            if (pnlTeamMemberAssigned.Visible)
            {
                if (tbxCompleteWorkDataDescription.Text.Trim() != "") newCompleteWorkDetailDescription = tbxCompleteWorkDataDescription.Text.Trim();
                newCompleteWorkDetailPreventable = ckbxCompleteWorkDataPreventable.Checked;
            }
            decimal? newCompleteWorkDetailTMLabourHours = null; if (tbxCompleteWorkDataLabourHours.Text.Trim() != "") newCompleteWorkDetailTMLabourHours = decimal.Parse(tbxCompleteWorkDataLabourHours.Text.Trim());

            // ... ... From Third party vendor
            if (pnlThirdPartyVendorAssigned.Visible)
            {
                if (tbxCompleteWorkDataDescriptionThirdPartyVendor.Text.Trim() != "") newCompleteWorkDetailDescription = tbxCompleteWorkDataDescriptionThirdPartyVendor.Text.Trim();
                newCompleteWorkDetailPreventable = ckbxCompleteWorkDataPreventableThirdPartyVendor.Checked;
            }
            string newCompleteWorkDetailTPVInvoiceNumber = tbxCompleteWorkDataInvoiceNumberThirdPartyVendor.Text.Trim();
            decimal? newCompleteWorkDetailTPVInvoiceAmout = null; if (tbxCompleteWorkDataInvoiceAmountThirdPartyVendor.Text.Trim() != "") newCompleteWorkDetailTPVInvoiceAmout = decimal.Parse(tbxCompleteWorkDataInvoiceAmountThirdPartyVendor.Text.Trim());

            // Update service data
            ServiceInformationBasicInformation serviceInformationBasicInformation = new ServiceInformationBasicInformation(serviceInformationTDS);
            int? libraryCategoriesId = null; if (serviceInformationBasicInformationGatewayForEdit.GetLibraryCategoriesId(int.Parse(hdfServiceId.Value)).HasValue) libraryCategoriesId = (int)serviceInformationBasicInformationGatewayForEdit.GetLibraryCategoriesId(int.Parse(hdfServiceId.Value));
            serviceInformationBasicInformation.Update(serviceId, serviceState, newMtoDto, newServiceDescription, newMileage, newAssignmentDateTime, newAssignmentDeadlineDate, newToTeamMember, newAssignTeamMemberID, newThirdPartyVendor, assignmentAcceptedDateTime, assignmentRejectedDateTime, newAssignmentRejectedReason, startWorkDateTime, newUnitOutOfServiceDate, newUnitOutOfServiceTime, newStartWorkMileage, completeWorkDateTime, newUnitBackInServiceDate, newUnitBackInServiceTime, newCompleteWorkMileage, newCompleteWorkDetailDescription, newCompleteWorkDetailPreventable, newCompleteWorkDetailTMLabourHours, newCompleteWorkDetailTPVInvoiceNumber, newCompleteWorkDetailTPVInvoiceAmout, associatedChecklistRuleState, libraryCategoriesId);

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

            ViewState["update"] = "no";
        }
        private void Save()
        {
            // Validate data
            bool validData = true;

            validData = ValidatePage();

            // For valid data
            if (validData)
            {
                // Costs Gridview, if the gridview is edition mode
                if (grdCosts.EditIndex >= 0)
                {
                    grdCosts.UpdateRow(grdCosts.EditIndex, true);
                }

                // Notes Gridview, if the gridview is edition mode
                if (grdNotes.EditIndex >= 0)
                {
                    grdNotes.UpdateRow(grdNotes.EditIndex, true);
                }

                // Save cost and notes data
                GrdCostsAdd();
                GrdNotesAdd();

                // Save data
                int companyId = Int32.Parse(hdfCompanyId.Value);
                int serviceId = Int32.Parse(hdfServiceId.Value);

                // Unmodified data
                ServiceInformationBasicInformationGateway serviceInformationBasicInformationGatewayForEdit = new ServiceInformationBasicInformationGateway(serviceInformationTDS);
                string serviceState = serviceInformationBasicInformationGatewayForEdit.GetServiceState(serviceId);
                string associatedChecklistRuleState = serviceInformationBasicInformationGatewayForEdit.GetAssociatedChecklistRuleState(serviceId);

                // ... Get basic service data
                bool newMtoDto = ckbxMtoDto.Checked;
                string newServiceDescription = tbxServiceDescription.Text.Trim();

                // ... Get general service data
                string newMileage = tbxGeneralMileage.Text.Trim();

                // ... Get assigned data
                DateTime? newAssignmentDateTime = null;
                DateTime? newAssignmentDeadlineDate = null;
                bool newToTeamMember = false;
                int? newAssignTeamMemberID = null;
                string newThirdPartyVendor = "";
                DateTime? assignmentAcceptedDateTime = null;
                string newAssignmentRejectedReason = "";
                DateTime? assignmentRejectedDateTime = null;

                if (pnlAssignmentData.Visible)
                {
                    if (pnlAssignedToReadOnly.Visible)
                    {
                        if (serviceInformationBasicInformationGatewayForEdit.GetAssignmentDateTimeOriginal(serviceId).HasValue) newAssignmentDateTime = (DateTime)serviceInformationBasicInformationGatewayForEdit.GetAssignmentDateTimeOriginal(serviceId);
                        if (serviceInformationBasicInformationGatewayForEdit.GetAssignedDeadlineDate(serviceId).HasValue) newAssignmentDeadlineDate = (DateTime)serviceInformationBasicInformationGatewayForEdit.GetAssignedDeadlineDate(serviceId);
                        newToTeamMember = serviceInformationBasicInformationGatewayForEdit.GetToTeamMember(serviceId);
                        if (newToTeamMember) newAssignTeamMemberID = (int)serviceInformationBasicInformationGatewayForEdit.GetAssignTeamMemberId(serviceId);
                        newThirdPartyVendor = serviceInformationBasicInformationGatewayForEdit.GetAssignedThirdPartyVendor(serviceId);
                    }

                    if (pnlAssignedTo.Visible)
                    {
                        if (serviceInformationBasicInformationGatewayForEdit.GetAssignmentDateTimeOriginal(serviceId).HasValue) newAssignmentDateTime = (DateTime)serviceInformationBasicInformationGatewayForEdit.GetAssignmentDateTimeOriginal(serviceId);
                        if (tkrdpAssignmentDataAssignedDeadlineDate.SelectedDate.HasValue) newAssignmentDeadlineDate = tkrdpAssignmentDataAssignedDeadlineDate.SelectedDate.Value;
                        newToTeamMember = rbtnAssignmentDataToTeamMember.Checked;
                        if (newToTeamMember) newAssignTeamMemberID = Int32.Parse(ddlAssignmentDataAssignToTeamMember.SelectedValue);
                        newThirdPartyVendor = tbxAssignmentDataAssignToThirdPartyVendor.Text.Trim();
                    }

                    if (serviceInformationBasicInformationGatewayForEdit.GetAcceptedDateTime(serviceId).HasValue) assignmentAcceptedDateTime = (DateTime)serviceInformationBasicInformationGatewayForEdit.GetAcceptedDateTime(serviceId);
                    if (serviceInformationBasicInformationGatewayForEdit.GetRejectedDateTime(serviceId).HasValue) assignmentRejectedDateTime = (DateTime)serviceInformationBasicInformationGatewayForEdit.GetRejectedDateTime(serviceId);
                    newAssignmentRejectedReason = tbxAssignmentDataRejectedReason.Text.Trim();
                }
                else
                {
                    if (pnlAssignmentDataReadOnly.Visible)
                    {
                        if (serviceInformationBasicInformationGatewayForEdit.GetAssignmentDateTimeOriginal(serviceId).HasValue) newAssignmentDateTime = (DateTime)serviceInformationBasicInformationGatewayForEdit.GetAssignmentDateTimeOriginal(serviceId);
                        if (serviceInformationBasicInformationGatewayForEdit.GetAssignedDeadlineDate(serviceId).HasValue) newAssignmentDeadlineDate = (DateTime)serviceInformationBasicInformationGatewayForEdit.GetAssignedDeadlineDate(serviceId);
                        newToTeamMember = serviceInformationBasicInformationGatewayForEdit.GetToTeamMember(serviceId);
                        if (newToTeamMember) newAssignTeamMemberID = (int)serviceInformationBasicInformationGatewayForEdit.GetAssignTeamMemberId(serviceId);
                        newThirdPartyVendor = serviceInformationBasicInformationGatewayForEdit.GetAssignedThirdPartyVendor(serviceId);
                        if (serviceInformationBasicInformationGatewayForEdit.GetAcceptedDateTime(serviceId).HasValue) assignmentAcceptedDateTime = (DateTime)serviceInformationBasicInformationGatewayForEdit.GetAcceptedDateTime(serviceId);
                        if (serviceInformationBasicInformationGatewayForEdit.GetRejectedDateTime(serviceId).HasValue) assignmentRejectedDateTime = (DateTime)serviceInformationBasicInformationGatewayForEdit.GetRejectedDateTime(serviceId);
                        newAssignmentRejectedReason = tbxAssignmentDataRejectedReasonReadOnly.Text.Trim();
                    }
                }

                // ... Get start work data
                DateTime? startWorkDateTime = null; if (serviceInformationBasicInformationGatewayForEdit.GetStartWorkDateTime(serviceId).HasValue) startWorkDateTime = (DateTime)serviceInformationBasicInformationGatewayForEdit.GetStartWorkDateTime(serviceId);
                DateTime? newUnitOutOfServiceDate = null;
                string newUnitOutOfServiceTime = "";
                string newStartWorkMileage = "";

                if (pnlStartWorkData.Visible)
                {
                    if (tkrdpStartWorkDataUnitOutOfServiceDate.SelectedDate.HasValue) newUnitOutOfServiceDate = tkrdpStartWorkDataUnitOutOfServiceDate.SelectedDate.Value;
                    newUnitOutOfServiceTime = "8:00 AM";
                    newStartWorkMileage = tbxStartWorkDataStartMileage.Text.Trim();
                }
                else
                {
                    if (pnlStartWorkDataReadOnly.Visible)
                    {
                        if (tbxStartWorkDataUnitOutOfServiceDateReadOnly.Text.Trim() != "") newUnitOutOfServiceDate = DateTime.Parse(tbxStartWorkDataUnitOutOfServiceDateReadOnly.Text.Trim());
                        newUnitOutOfServiceTime = "8:00 AM";
                        newStartWorkMileage = tbxStartWorkDataStartMileageReadOnly.Text.Trim();
                    }
                }

                // ... Get complete work data
                DateTime? completeWorkDateTime = null; if (serviceInformationBasicInformationGatewayForEdit.GetCompleteWorkDateTime(serviceId).HasValue) completeWorkDateTime = (DateTime)serviceInformationBasicInformationGatewayForEdit.GetCompleteWorkDateTime(serviceId);
                DateTime? newUnitBackInServiceDate = null;
                string newUnitBackInServiceTime = "";
                string newCompleteWorkMileage = "";
                string newCompleteWorkDetailDescription = "";
                bool newCompleteWorkDetailPreventable = false;
                decimal? newCompleteWorkDetailTMLabourHours = 0.0M;
                string newCompleteWorkDetailTPVInvoiceNumber = "";
                decimal? newCompleteWorkDetailTPVInvoiceAmout = 0.0M;

                if (pnlCompleteWorkData.Visible)
                {
                    if (tkrdpCompleteWorkDataUnitBackInServiceDate.SelectedDate.HasValue) newUnitBackInServiceDate = tkrdpCompleteWorkDataUnitBackInServiceDate.SelectedDate.Value;
                    newUnitBackInServiceTime = "8:00 AM";
                    newCompleteWorkMileage = tbxCompleteWorkDataCompleteMileage.Text.Trim();

                    // ... ... From team member
                    if (pnlTeamMemberAssigned.Visible)
                    {
                        if (tbxCompleteWorkDataDescription.Text.Trim() != "") newCompleteWorkDetailDescription = tbxCompleteWorkDataDescription.Text.Trim();
                        newCompleteWorkDetailPreventable = ckbxCompleteWorkDataPreventable.Checked;
                    }
                    newCompleteWorkDetailTMLabourHours = null; if (tbxCompleteWorkDataLabourHours.Text.Trim() != "") newCompleteWorkDetailTMLabourHours = decimal.Parse(tbxCompleteWorkDataLabourHours.Text.Trim());

                    // ... ... From Third party vendor
                    if (pnlThirdPartyVendorAssigned.Visible)
                    {
                        if (tbxCompleteWorkDataDescriptionThirdPartyVendor.Text.Trim() != "") newCompleteWorkDetailDescription = tbxCompleteWorkDataDescriptionThirdPartyVendor.Text.Trim();
                        newCompleteWorkDetailPreventable = ckbxCompleteWorkDataPreventableThirdPartyVendor.Checked;
                    }
                    newCompleteWorkDetailTPVInvoiceNumber = tbxCompleteWorkDataInvoiceNumberThirdPartyVendor.Text.Trim();
                    newCompleteWorkDetailTPVInvoiceAmout = null; if (tbxCompleteWorkDataInvoiceAmountThirdPartyVendor.Text.Trim() != "") newCompleteWorkDetailTPVInvoiceAmout = decimal.Parse(tbxCompleteWorkDataInvoiceAmountThirdPartyVendor.Text.Trim());
                }
                else
                {
                    if (pnlCompleteWorkDataReadOnly.Visible)
                    {
                        if (tbxCompleteWorkDataUnitBackInServiceDateReadOnly.Text.Trim() != "") newUnitBackInServiceDate = DateTime.Parse(tbxCompleteWorkDataUnitBackInServiceDateReadOnly.Text.Trim());
                        newUnitBackInServiceTime = "8:00 AM";
                        newCompleteWorkMileage = tbxCompleteWorkDataCompleteMileageReadOnly.Text.Trim();

                        // ... ... From team member
                        if (pnlTeamMemberAssignedReadOnly.Visible)
                        {
                            if (tbxCompleteWorkDataDescriptionReadOnly.Text.Trim() != "") newCompleteWorkDetailDescription = tbxCompleteWorkDataDescriptionReadOnly.Text.Trim();
                            newCompleteWorkDetailPreventable = ckbxCompleteWorkDataPreventableReadOnly.Checked;
                        }
                        newCompleteWorkDetailTMLabourHours = null; if (tbxCompleteWorkDataLabourHoursReadOnly.Text.Trim() != "") newCompleteWorkDetailTMLabourHours = decimal.Parse(tbxCompleteWorkDataLabourHoursReadOnly.Text.Trim());

                        // ... ... From Third party vendor
                        if (pnlThirdPartyVendorAssignedReadOnly.Visible)
                        {
                            if (tbxCompleteWorkDataDescriptionThirdPartyVendorReadOnly.Text.Trim() != "") newCompleteWorkDetailDescription = tbxCompleteWorkDataDescriptionThirdPartyVendorReadOnly.Text.Trim();
                            newCompleteWorkDetailPreventable = ckbxCompleteWorkDataPreventableThirdPartyVendorReadOnly.Checked;
                        }
                        newCompleteWorkDetailTPVInvoiceNumber = tbxCompleteWorkDataInvoiceNumberThirdPartyVendorReadOnly.Text.Trim();
                        newCompleteWorkDetailTPVInvoiceAmout = null; if (tbxCompleteWorkDataInvoiceAmountThirdPartyVendorReadOnly.Text.Trim() != "") newCompleteWorkDetailTPVInvoiceAmout = decimal.Parse(tbxCompleteWorkDataInvoiceAmountThirdPartyVendorReadOnly.Text.Trim());
                    }
                }

                // Update service data
                ServiceInformationBasicInformation serviceInformationBasicInformation = new ServiceInformationBasicInformation(serviceInformationTDS);
                int? libraryCategoriesId = null; if (serviceInformationBasicInformationGatewayForEdit.GetLibraryCategoriesId(int.Parse(hdfServiceId.Value)).HasValue) libraryCategoriesId = (int)serviceInformationBasicInformationGatewayForEdit.GetLibraryCategoriesId(int.Parse(hdfServiceId.Value));
                serviceInformationBasicInformation.Update(serviceId, serviceState, newMtoDto, newServiceDescription, newMileage, newAssignmentDateTime, newAssignmentDeadlineDate, newToTeamMember, newAssignTeamMemberID, newThirdPartyVendor, assignmentAcceptedDateTime, assignmentRejectedDateTime, newAssignmentRejectedReason, startWorkDateTime, newUnitOutOfServiceDate, newUnitOutOfServiceTime, newStartWorkMileage, completeWorkDateTime, newUnitBackInServiceDate, newUnitBackInServiceTime, newCompleteWorkMileage, newCompleteWorkDetailDescription, newCompleteWorkDetailPreventable, newCompleteWorkDetailTMLabourHours, newCompleteWorkDetailTPVInvoiceNumber, newCompleteWorkDetailTPVInvoiceAmout, associatedChecklistRuleState, libraryCategoriesId);

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

                Session.Remove("libraryTDSForServices");

                // Update database
                UpdateDatabase();

                ViewState["update"] = "yes";

                // Redirect
                string url = "";
                if (Request.QueryString["source_page"] == "services_navigator2.aspx" || Request.QueryString["source_page"] == "services_add_request.aspx")
                {
                    url = "./services_navigator2.aspx?source_page=services_edit.aspx&service_id=" + hdfServiceId.Value + GetNavigatorState() + "&update=yes";
                }

                if (Request.QueryString["source_page"] == "services_summary.aspx")
                {
                    string activeTab = hdfActiveTab.Value;
                    url = "./services_summary.aspx?source_page=services_edit.aspx&dashboard=" + hdfDashboard.Value + "&service_id=" + hdfServiceId.Value + "&active_tab=" + activeTab + GetNavigatorState() + "&update=yes";
                }

                Response.Redirect(url);
            }
        }
        protected void btnUnassociate_Click(object sender, EventArgs e)
        {
            Session["activeTabServices"] = "4";
            Session["dialogOpenedServices"] = "1";

            ServiceInformationBasicInformation serviceInformationBasicInformation = new ServiceInformationBasicInformation(serviceInformationTDS);
            serviceInformationBasicInformation.UpdateLibraryCategoriesId(int.Parse(hdfServiceId.Value), null);

            ViewState["update"] = "no";

            btnUnassociate.Visible = false;
            btnAssociate.Visible = true;
            tbxCategoryAssocited.Text = "";
        }
        protected void Page_PreRender(object sender, EventArgs e)
        {
            // Set active toolbar
            mForm6 master = (mForm6)this.Master;
            master.ActiveToolbar = "FleetManagement";

            int ruleId = Int32.Parse(hdfRuleId.Value);

            foreach (int categoryId in arrayCategoriesSelected)
            {
                // Mark selected units
                RuleCategoryUnitsGateway ruleCategoryUnitsGateway = new RuleCategoryUnitsGateway();

                if (cbxlUnitsSelected.Items.Count > 0)
                {
                    foreach (ListItem lst in cbxlUnitsSelected.Items)
                    {
                        if (ruleCategoryUnitsGateway.IsUsedInRuleCategoryUnits(ruleId, categoryId, Int32.Parse(lst.Value)))
                        {
                            lst.Selected = true;
                        }
                    }
                }
            }

            ServiceInformationBasicInformation serviceInformationBasicInformation = new ServiceInformationBasicInformation();
            serviceInformationBasicInformation.LoadInProgressByRuleId(ruleId, int.Parse(hdfCompanyId.Value));

            if (serviceInformationBasicInformation.Table.Rows.Count > 0)
            {
                tkrmTop.Items[1].Visible = false;
            }
        }
        protected void cvUnits_ServerValidate(object source, ServerValidateEventArgs args)
        {
            args.IsValid = false;
            StringBuilder errorMessage = new StringBuilder();

            // Validate for save and apply only
            if (hdfCheckUnitsFlag.Value == "Yes")
            {
                if (cbxlUnitsSelected.Items.Count > 0)
                {
                    foreach (ListItem lst in cbxlUnitsSelected.Items)
                    {
                        if (lst.Selected)
                        {
                            args.IsValid = true;
                        }
                    }
                }
                else
                {
                    args.IsValid = true;
                }
            }
            else
            {
                args.IsValid = true;
            }

            if (args.IsValid)
            {
                foreach (ListItem lst in cbxlUnitsSelected.Items)
                {
                    if (!lst.Selected)
                    {
                        ServiceInformationBasicInformation model = new ServiceInformationBasicInformation();
                        model.LoadInProgressByUnitIdRuleId(Int32.Parse(lst.Value), Int32.Parse(hdfRuleId.Value), int.Parse(hdfCompanyId.Value));

                        if (model.Table.Rows.Count > 0)
                        {
                            errorMessage.Append(string.Format("The unit {0} have pending service requests, please complete them before unchecking from checklist</br>", lst.Text));
                        }
                    }
                }
            }

            if (errorMessage.Length > 0)
            {
                args.IsValid = false;
                cvUnits.ErrorMessage = errorMessage.ToString();
            }
        }
        /// <summary>
        /// Update
        /// </summary>
        /// <param name="serviceId">serviceId</param>
        /// <param name="serviceState">serviceState</param>
        /// <param name="mtoDto">mtoDto</param>
        /// <param name="serviceDescription">serviceDescription</param>
        /// <param name="mileage">mileage</param>
        /// <param name="assignmentDateTime">assignmentDateTime</param>
        /// <param name="assignmentDeadlineDate"></param>
        /// <param name="toTeamMember">toTeamMember</param>
        /// <param name="assignTeamMemberID">assignTeamMemberID</param>
        /// <param name="thirdPartyVendor">thirdPartyVendor</param>
        /// <param name="assignmentAcceptedDateTime">assignmentAcceptedDateTime</param>
        /// <param name="assignmentRejectedDateTime">assignmentRejectedDateTime</param>
        /// <param name="assignmentRejectedReason">assignmentRejectedReason</param>
        /// <param name="startWorkDateTime">startWorkDateTime</param>
        /// <param name="unitOutOfServiceDate">unitOutOfServiceDate</param>
        /// <param name="unitOutOfServiceTime">unitOutOfServiceTime</param>
        /// <param name="startWorkMileage">startWorkMileage</param>
        /// <param name="completeWorkDateTime">completeWorkDateTime</param>
        /// <param name="unitBackInServiceDate">unitBackInServiceDate</param>
        /// <param name="unitBackInServiceTime">unitBackInServiceTime</param>
        /// <param name="completeWorkMileage">completeWorkMileage</param>
        /// <param name="completeWorkDetailDescription">completeWorkDetailDescription</param>
        /// <param name="completeWorkDetailPreventable">completeWorkDetailPreventable</param>
        /// <param name="completeWorkDetailTMLabourHours">completeWorkDetailTMLabourHours</param>
        /// <param name="completeWorkDetailTPVInvoiceNumber">completeWorkDetailTPVInvoiceNumber</param>
        /// <param name="completeWorkDetailTPVInvoiceAmout">completeWorkDetailTPVInvoiceAmout</param>
        /// <param name="newAssociatedChecklistRuleState">newAssociatedChecklistRuleState</param>
        /// <param name="libraryCategoriesId">libraryCategoriesId</param>
        public void Update(int serviceId, string serviceState, bool mtoDto, string serviceDescription, string mileage, DateTime? assignmentDateTime, DateTime? assignmentDeadlineDate, bool toTeamMember, int? assignTeamMemberID, string thirdPartyVendor, DateTime? assignmentAcceptedDateTime, DateTime? assignmentRejectedDateTime, string assignmentRejectedReason, DateTime? startWorkDateTime, DateTime? unitOutOfServiceDate, string unitOutOfServiceTime, string startWorkMileage, DateTime? completeWorkDateTime, DateTime? unitBackInServiceDate, string unitBackInServiceTime, string completeWorkMileage, string completeWorkDetailDescription, bool completeWorkDetailPreventable, decimal? completeWorkDetailTMLabourHours, string completeWorkDetailTPVInvoiceNumber, decimal? completeWorkDetailTPVInvoiceAmout, string newAssociatedChecklistRuleState, int? libraryCategoriesId)
        {
            ServiceInformationTDS.BasicInformationRow row = GetRow(serviceId);

            // General Data
            string originalServiceState = row.ServiceState;
            DateTime? originalUnitBackInServiceDate = null; if (!row.IsUnitBackInServiceDateNull()) originalUnitBackInServiceDate = row.UnitBackInServiceDate;
            row.ServiceState = serviceState;
            row.MtoDto = mtoDto;
            if (serviceDescription.Trim() != "") row.ServiceDescription = serviceDescription; else row.SetServiceDescriptionNull();
            if (mileage.Trim() != "") row.Mileage = mileage; else row.SetMileageNull();
            if (assignmentDateTime.HasValue) row.AssignmentDateTime = (DateTime)assignmentDateTime; else row.SetAssignmentDateTimeNull();
            if (assignmentDeadlineDate.HasValue) row.AssignedDeadlineDate = (DateTime)assignmentDeadlineDate;
            row.ToTeamMember = toTeamMember;
            if (assignTeamMemberID.HasValue) row.AssignTeamMemberID = (int)assignTeamMemberID; else row.SetAssignTeamMemberIDNull();
            if (thirdPartyVendor != "") row.AssignedThirdPartyVendor = thirdPartyVendor; else row.SetAssignedThirdPartyVendorNull();
            if (assignmentAcceptedDateTime.HasValue) row.AcceptedDateTime = (DateTime)assignmentAcceptedDateTime; else row.SetAcceptedDateTimeNull();
            if (assignmentRejectedDateTime.HasValue) row.RejectedDateTime = (DateTime)assignmentRejectedDateTime; else row.SetRejectedDateTimeNull();
            if (assignmentRejectedReason != "") row.RejectedReason = assignmentRejectedReason; else row.SetRejectedReasonNull();
            if (startWorkDateTime.HasValue) row.StartWorkDateTime = (DateTime)startWorkDateTime; else row.SetStartWorkDateTimeNull();
            if (unitOutOfServiceDate.HasValue) row.UnitOutOfServiceDate = (DateTime)unitOutOfServiceDate; else row.SetUnitOutOfServiceDateNull();
            if (unitOutOfServiceTime != "") row.UnitOutOfServiceTime = unitOutOfServiceTime; else row.SetUnitOutOfServiceTimeNull();
            if (startWorkMileage != "") row.StartWorkMileage = startWorkMileage; else row.SetStartWorkMileageNull();
            if (completeWorkDateTime.HasValue) row.CompleteWorkDateTime = (DateTime)completeWorkDateTime; else row.SetCompleteWorkDateTimeNull();
            if (unitBackInServiceDate.HasValue) row.UnitBackInServiceDate = (DateTime)unitBackInServiceDate; else row.SetUnitBackInServiceDateNull();
            if (unitBackInServiceTime != "") row.UnitBackInServiceTime = unitBackInServiceTime; else row.SetUnitBackInServiceTimeNull();
            if (completeWorkMileage != "") row.CompleteWorkMileage = completeWorkMileage; else row.SetCompleteWorkMileageNull();
            if (completeWorkDetailDescription != "") row.CompleteWorkDetailDescription = completeWorkDetailDescription; else row.SetCompleteWorkDetailDescriptionNull();
            row.CompleteWorkDetailPreventable = completeWorkDetailPreventable;
            if (completeWorkDetailTMLabourHours.HasValue) row.CompleteWorkDetailTMLabourHours = (Decimal)completeWorkDetailTMLabourHours; else row.SetCompleteWorkDetailTMLabourHoursNull();
            if (completeWorkDetailTPVInvoiceNumber != "") row.CompleteWorkDetailTPVInvoiceNumber = completeWorkDetailTPVInvoiceNumber; else row.SetCompleteWorkDetailTPVInvoiceNumberNull();
            if (completeWorkDetailTPVInvoiceAmout.HasValue) row.CompleteWorkDetailTPVInvoiceAmout = (Decimal)completeWorkDetailTPVInvoiceAmout; else row.SetCompleteWorkDetailTPVInvoiceAmoutNull();
            if (libraryCategoriesId.HasValue) row.LIBRARY_CATEGORIES_ID = libraryCategoriesId.Value; else row.SetLIBRARY_CATEGORIES_IDNull();

            if (row.Type == "Checklist")
            {
                if ((originalServiceState != "Completed") && (serviceState == "Completed"))
                {
                    RuleGateway ruleGateway = new RuleGateway();
                    ruleGateway.LoadAllByRuleId(row.RuleID, row.COMPANY_ID);

                    DateTime? lastService = (DateTime)unitBackInServiceDate;
                    DateTime? nextDue = null;

                    string frecuency = ruleGateway.GetFrequency(row.RuleID);

                    if (!ruleGateway.GetMto(row.RuleID))
                    {
                        if (ruleGateway.GetFrequency(row.RuleID) != "Only once")
                        {
                            // Get next due
                            DateTime timeToAdded = new DateTime(((DateTime)lastService).Year, ((DateTime)lastService).Month, ((DateTime)lastService).Day);

                            if (frecuency == "Monthly") nextDue = timeToAdded.AddMonths(1);
                            if (frecuency == "Every 2 months") nextDue = timeToAdded.AddMonths(2);
                            if (frecuency == "Every 3 months") nextDue = timeToAdded.AddMonths(3);
                            if (frecuency == "Every 4 months") nextDue = timeToAdded.AddMonths(4);
                            if (frecuency == "Every 6 months") nextDue = timeToAdded.AddMonths(6);
                            if (frecuency == "Yearly") nextDue = timeToAdded.AddYears(1);

                            row.AssociatedChecklistLastService = (DateTime)lastService;
                            row.AssociatedChecklistNextDue = (DateTime)nextDue;
                            row.AssociatedChecklistDone = false;
                            if (newAssociatedChecklistRuleState != "") row.AssociatedChecklistRuleState = newAssociatedChecklistRuleState; else row.SetAssociatedChecklistRuleStateNull();
                        }
                        else
                        {
                            row.AssociatedChecklistLastService = (DateTime)lastService;
                            row.SetAssociatedChecklistNextDueNull();
                            row.AssociatedChecklistDone = true;
                            if (newAssociatedChecklistRuleState != "") row.AssociatedChecklistRuleState = newAssociatedChecklistRuleState; else row.SetAssociatedChecklistRuleStateNull();
                        }
                    }
                    else
                    {
                        ServiceInformationBasicInformation serviceInformationBasicInformation = new ServiceInformationBasicInformation();
                        serviceInformationBasicInformation.LoadInProgressByServiceIdUnitIdRuleId(row.ServiceID, row.UnitID, row.RuleID, row.COMPANY_ID);

                        if (serviceInformationBasicInformation.Table.Rows.Count > 1)
                        {
                            row.AssociatedChecklistRuleState = "In Progress";
                        }
                        else
                        {
                            row.AssociatedChecklistRuleState = newAssociatedChecklistRuleState;
                        }

                        if (frecuency != "Only once")
                        {
                            row.AssociatedChecklistDone = false;
                        }
                        else
                        {
                            row.AssociatedChecklistDone = true;
                        }
                    }
                }
                else
                {
                    if ((originalServiceState == "Completed") && (originalUnitBackInServiceDate != unitBackInServiceDate))
                    {
                        RuleGateway ruleGateway = new RuleGateway();
                        ruleGateway.LoadAllByRuleId(row.RuleID, row.COMPANY_ID);

                        DateTime? lastService = (DateTime)unitBackInServiceDate;
                        DateTime? nextDue = null;

                        string frecuency = ruleGateway.GetFrequency(row.RuleID);

                        if (!ruleGateway.GetMto(row.RuleID))
                        {
                            if (ruleGateway.GetFrequency(row.RuleID) != "Only once")
                            {
                                // Get next due
                                DateTime timeToAdded = new DateTime(((DateTime)lastService).Year, ((DateTime)lastService).Month, ((DateTime)lastService).Day);

                                if (frecuency == "Monthly") nextDue = timeToAdded.AddMonths(1);
                                if (frecuency == "Every 2 months") nextDue = timeToAdded.AddMonths(2);
                                if (frecuency == "Every 3 months") nextDue = timeToAdded.AddMonths(3);
                                if (frecuency == "Every 4 months") nextDue = timeToAdded.AddMonths(4);
                                if (frecuency == "Every 6 months") nextDue = timeToAdded.AddMonths(6);
                                if (frecuency == "Yearly") nextDue = timeToAdded.AddYears(1);

                                row.AssociatedChecklistLastService = (DateTime)lastService;
                                row.AssociatedChecklistNextDue = (DateTime)nextDue;
                                row.AssociatedChecklistDone = false;
                                if (newAssociatedChecklistRuleState != "") row.AssociatedChecklistRuleState = newAssociatedChecklistRuleState; else row.SetAssociatedChecklistRuleStateNull();
                            }
                            else
                            {
                                row.AssociatedChecklistLastService = (DateTime)lastService;
                                row.SetAssociatedChecklistNextDueNull();
                                row.AssociatedChecklistDone = true;
                                if (newAssociatedChecklistRuleState != "") row.AssociatedChecklistRuleState = newAssociatedChecklistRuleState; else row.SetAssociatedChecklistRuleStateNull();
                            }
                        }
                        else
                        {
                            ServiceInformationBasicInformation serviceInformationBasicInformation = new ServiceInformationBasicInformation();
                            serviceInformationBasicInformation.LoadInProgressByServiceIdUnitIdRuleId(row.ServiceID, row.UnitID, row.RuleID, row.COMPANY_ID);

                            if (serviceInformationBasicInformation.Table.Rows.Count > 1)
                            {
                                row.AssociatedChecklistRuleState = "In Progress";
                            }
                            else
                            {
                                row.AssociatedChecklistRuleState = newAssociatedChecklistRuleState;
                            }

                            if (frecuency != "Only once")
                            {
                                row.AssociatedChecklistDone = false;
                            }
                            else
                            {
                                row.AssociatedChecklistDone = true;
                            }
                        }
                    }
                }
            }
        }
        private void Delete()
        {
            Page.Validate();

            if (Page.IsValid)
            {
                // Delete all data for service
                int serviceId = Int32.Parse(hdfServiceId.Value);

                ServiceInformationBasicInformation serviceInformationBasicInformation = new ServiceInformationBasicInformation(serviceInformationTDS);
                serviceInformationBasicInformation.Delete(serviceId);

                ServiceInformationServiceCost serviceInformationServiceCostForEdit = new ServiceInformationServiceCost(serviceInformationTDS);
                serviceInformationServiceCostForEdit.DeleteAll(serviceId);

                ServiceInformationServiceNote serviceInformationServiceNoteForEdit = new ServiceInformationServiceNote(serviceInformationTDS);
                serviceInformationServiceNoteForEdit.DeleteAll(serviceId);

                // Update databse
                UpdateDatabase();

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

                // Redirect
                string url = "";

                if (Request.QueryString["dashboard"] == "True")
                {
                    url = "./../../FleetManagement/Dashboard/dashboard_login.aspx?source_page=out";
                }
                else
                {
                    url = "./services_navigator2.aspx?source_page=services_delete.aspx&service_id=" + hdfServiceId.Value + GetNavigatorState() + "&update=yes";
                }
                Response.Redirect(url);
            }
        }
        private void UpdateDatabase()
        {
            int companyId = Int32.Parse(hdfCompanyId.Value);

            DB.Open();
            DB.BeginTransaction();
            try
            {
                ServiceInformationBasicInformation serviceInformationBasicInformation = new ServiceInformationBasicInformation(serviceInformationTDS);
                serviceInformationBasicInformation.Save(companyId);
                string subject = "";
                string title = "";

                // Send Mails
                switch ((string)Request.QueryString["state"])
                {
                    case "Assigned":
                        // ... If there is an assignation send mail to Assigned Personal
                        if (rbtnPnlAssignToTeamMember.Checked)
                        {
                            SendMailTeamMember();
                        }

                        // ... Send  mail to fleet manager
                        subject = "New service request has been registered.";
                        title = "The following service request has been assigned.";
                        SendMailFleetManager (subject, title);
                        break;

                    case "Accepted":
                        subject = "A service request has been accepted.";
                        title = "The following service request has been accepted.";
                        SendMailFleetManagerAcceptRejectCompleted(subject, title);
                        break;

                    case "Rejected":
                        subject = "A service request has been rejected.";
                        title = "The following service request has been rejected.";
                        SendMailFleetManagerAcceptRejectCompleted(subject, title);
                        break;

                    case "CompleteWork":
                        subject = "A service request has been completed.";
                        title = "The following service request has been completed.";
                        SendMailFleetManagerAcceptRejectCompleted(subject, title);
                        break;
                }

                DB.CommitTransaction();

                // Store datasets
                serviceInformationTDS.AcceptChanges();
                Session["serviceInformationTDS"] = serviceInformationTDS;
            }
            catch (Exception ex)
            {
                DB.RollbackTransaction();

                string url = string.Format("./../../error_page.aspx?error={0}", ex.Message.Replace('\n', ' '));
                Response.Redirect(url);
            }
        }
        private void UpdateState()
        {
            int serviceId = Int32.Parse(hdfServiceId.Value);
            ServiceInformationBasicInformationGateway serviceInformationBasicInformationGateway = new ServiceInformationBasicInformationGateway(serviceInformationTDS);

            // General Data
            bool mtoDto = serviceInformationBasicInformationGateway.GetMtoDto(serviceId);
            string serviceDescription = serviceInformationBasicInformationGateway.GetServiceDescription(serviceId);
            string mileage = serviceInformationBasicInformationGateway.GetMileage(serviceId);
            int? libraryCategoriesId = null; if (serviceInformationBasicInformationGateway.GetLibraryCategoriesId(serviceId).HasValue) libraryCategoriesId = serviceInformationBasicInformationGateway.GetLibraryCategoriesId(serviceId).Value;

            // Initialize Data
            // ... Initialize Assigned Data with existent data
            DateTime? newAssignmentDateTime = null; if (serviceInformationBasicInformationGateway.GetAssignmentDateTime(serviceId).HasValue) newAssignmentDateTime = (DateTime)serviceInformationBasicInformationGateway.GetAssignmentDateTime(serviceId);
            DateTime? newDeadlineDate = null; if (serviceInformationBasicInformationGateway.GetAssignedDeadlineDate(serviceId).HasValue) newDeadlineDate = (DateTime)serviceInformationBasicInformationGateway.GetAssignedDeadlineDate(serviceId);
            bool newToTeamMember = serviceInformationBasicInformationGateway.GetToTeamMember(serviceId);
            int? newAssignTeamMemberID = null; if(serviceInformationBasicInformationGateway.GetAssignTeamMemberId(serviceId).HasValue) newAssignTeamMemberID = (int)serviceInformationBasicInformationGateway.GetAssignTeamMemberId(serviceId);
            string newThirdPartyVendor = serviceInformationBasicInformationGateway.GetAssignedThirdPartyVendor(serviceId);

            // ... Initialize Assigned Accepted Data with existent data
            DateTime? newAssignmentAcceptedDateTime = null; if (serviceInformationBasicInformationGateway.GetAcceptedDateTime(serviceId).HasValue) newAssignmentAcceptedDateTime = (DateTime)serviceInformationBasicInformationGateway.GetAcceptedDateTime(serviceId);

            // ... Initialize Assigned Rejected Data with existent data
            DateTime? newAssignmentRejectedDateTime = null; if (serviceInformationBasicInformationGateway.GetRejectedDateTime(serviceId).HasValue) newAssignmentRejectedDateTime = (DateTime)serviceInformationBasicInformationGateway.GetRejectedDateTime(serviceId);
            string newAssignmnetRejectedReason = serviceInformationBasicInformationGateway.GetRejectedReason(serviceId);

            // ... Initialize Start Work Data with existent data
            DateTime? newStartWorkDateTime = null; if (serviceInformationBasicInformationGateway.GetStartWorkDateTime(serviceId).HasValue) newStartWorkDateTime = (DateTime)serviceInformationBasicInformationGateway.GetStartWorkDateTime(serviceId);
            DateTime? newUnitOutOfServiceDate = null; if (serviceInformationBasicInformationGateway.GetUnitOutOfServiceDate(serviceId).HasValue) newUnitOutOfServiceDate = (DateTime)serviceInformationBasicInformationGateway.GetUnitOutOfServiceDate(serviceId);
            string newUnitOutOfServiceTime = serviceInformationBasicInformationGateway.GetUnitOutOfServiceTime(serviceId);
            string newStartWorkMileage = serviceInformationBasicInformationGateway.GetStartWorkMileage(serviceId);

            // ... Initialize Complete Work Data with existent data
            DateTime? newCompleteWorkDateTime = null; if (serviceInformationBasicInformationGateway.GetCompleteWorkDateTime(serviceId).HasValue) newCompleteWorkDateTime = (DateTime)serviceInformationBasicInformationGateway.GetCompleteWorkDateTime(serviceId);
            DateTime? newUnitBackInServiceDate = null; if (serviceInformationBasicInformationGateway.GetUnitBackInServiceDate(serviceId).HasValue) newUnitBackInServiceDate = (DateTime)serviceInformationBasicInformationGateway.GetUnitBackInServiceDate(serviceId);
            string newUnitBackInServiceTime = serviceInformationBasicInformationGateway.GetUnitBackInServiceTime(serviceId);
            string newCompleteWorkMileage = serviceInformationBasicInformationGateway.GetCompleteWorkMileage(serviceId);
            string newAssociatedChecklistRuleState = serviceInformationBasicInformationGateway.GetAssociatedChecklistRuleState(serviceId);

            // ... Get new values
            string serviceState = null;
            switch ((string)Request.QueryString["state"])
            {
                case "Assigned":
                    serviceState = "Assigned";
                    newAssignmentDateTime = DateTime.Now;
                    if (tkrdpPnlAssignDeadlineDate.SelectedDate.HasValue) newDeadlineDate = tkrdpPnlAssignDeadlineDate.SelectedDate.Value;
                    newToTeamMember = rbtnPnlAssignToTeamMember.Checked;
                    newAssignTeamMemberID = null; if (newToTeamMember) newAssignTeamMemberID = Int32.Parse(ddlPnlAssignAssignToTeamMember.SelectedValue);
                    newThirdPartyVendor = tbxPnlAssignAssignToThirdPartyVendor.Text.Trim();
                    break;

                case "Accepted":
                    serviceState = "Accepted";
                    newAssignmentAcceptedDateTime = DateTime.Now;
                    break;

                case "Rejected":
                    serviceState = "Rejected";
                    newAssignmentRejectedDateTime = DateTime.Now;
                    newAssignmnetRejectedReason = tbxPnlAssignmentRejectDataRejectedReason.Text.Trim();
                    break;

                case "StartWork":
                    serviceState = "In Progress";
                    newStartWorkDateTime = DateTime.Now;
                    newUnitOutOfServiceDate = null; if (tkrdpPnlStartWorkUnitOutOfServiceDate.SelectedDate.HasValue) newUnitOutOfServiceDate = tkrdpPnlStartWorkUnitOutOfServiceDate.SelectedDate.Value;
                    newUnitOutOfServiceTime = DateTime.Now.ToShortTimeString();
                    newStartWorkMileage = tbxPnlStartWorkStartMileage.Text.Trim();
                    break;

                case "CompleteWork":
                    serviceState = "Completed";
                    newCompleteWorkDateTime = DateTime.Now;
                    newUnitBackInServiceDate = null; if (tkrdpPnlCompleteWorkUnitBackInServiceDate.SelectedDate.HasValue) newUnitBackInServiceDate = tkrdpPnlCompleteWorkUnitBackInServiceDate.SelectedDate.Value;
                    newUnitBackInServiceTime = DateTime.Now.ToShortTimeString();
                    newCompleteWorkMileage = tbxPnlCompleteWorkCompleteMileage.Text.Trim();
                    newAssociatedChecklistRuleState = "Healthy";
                    break;
            }

            // Update service data
            ServiceInformationBasicInformation serviceInformationBasicInformation = new ServiceInformationBasicInformation(serviceInformationTDS);
            serviceInformationBasicInformation.Update(serviceId, serviceState, mtoDto, serviceDescription, mileage, newAssignmentDateTime, newDeadlineDate, newToTeamMember, newAssignTeamMemberID, newThirdPartyVendor, newAssignmentAcceptedDateTime, newAssignmentRejectedDateTime, newAssignmnetRejectedReason, newStartWorkDateTime, newUnitOutOfServiceDate, newUnitOutOfServiceTime, newStartWorkMileage, newCompleteWorkDateTime, newUnitBackInServiceDate, newUnitBackInServiceTime, newCompleteWorkMileage, "", false, null, "", null, newAssociatedChecklistRuleState, libraryCategoriesId);
        }
        /// <summary>
        /// Update a Service
        /// </summary>
        /// <param name="serviceId">serviceId</param>
        /// <param name="serviceState">serviceState</param>
        /// <param name="assignDateTime">assignDateTime</param>
        /// <param name="assignedDeadlineDate">assignedDeadlineDate</param>
        /// <param name="assignTeamMember">assignTeamMember</param>
        /// <param name="assignTeamMemberId">assignTeamMemberId</param>
        /// <param name="assignThirdPartyVendor">assignThirdPartyVendor</param>
        /// <param name="acceptDateTime">acceptDateTime</param>
        /// <param name="startWorkDateTime">startWorkDateTime</param>
        /// <param name="unitOutOfServiceDate">unitOutOfServiceDate</param>
        /// <param name="unitOutOfServiceTime">unitOutOfServiceTime</param>
        /// <param name="completeWorkDateTime">completeWorkDateTime</param>
        /// <param name="unitBackInServiceDate">unitBackInServiceDate</param>
        /// <param name="unitBackInServiceTime">unitBackInServiceTime</param>
        /// <param name="completeWorkDetailDescription">completeWorkDetailDescription</param>
        /// <param name="completeWorkDetailPreventable">completeWorkDetailPreventable</param>
        /// <param name="completeWorkDetailTMLabourHours">completeWorkDetailTMLabourHours</param>
        /// <param name="completeWorkDetailTMCost">completeWorkDetailTMCost</param>
        /// <param name="completeWorkInvoiceNumber">completeWorkInvoiceNumber</param>
        /// <param name="completeWorkInvoiceAmount">completeWorkInvoiceAmount</param>
        /// <param name="startWorkMileage">startWorkMileage</param>
        /// <param name="completeWorkMileage">completeWorkMileage</param>
        /// <param name="newAssociatedChecklistRuleState">newAssociatedChecklistRuleState</param>
        /// <param name="deleted">deleted</param>
        /// <param name="companyId">companyId</param>
        /// <param name="libraryCategoriesId">libraryCategoriesId</param>
        public void Update(int serviceId, string serviceState, DateTime? assignDateTime, DateTime? assignedDeadlineDate, bool assignTeamMember, int? assignTeamMemberId, string assignThirdPartyVendor, DateTime? acceptDateTime, DateTime? startWorkDateTime, DateTime? unitOutOfServiceDate, string unitOutOfServiceTime, DateTime? completeWorkDateTime, DateTime? unitBackInServiceDate, string unitBackInServiceTime, string completeWorkDetailDescription, bool completeWorkDetailPreventable, Decimal? completeWorkDetailTMLabourHours, Decimal? completeWorkDetailTMCost, string completeWorkInvoiceNumber, decimal? completeWorkInvoiceAmount, string startWorkMileage, string completeWorkMileage, string newAssociatedChecklistRuleState, bool deleted, int companyId, int? libraryCategoriesId)
        {
            ServiceRequestsManagerToolTDS.BasicInformationRow row = GetRow(serviceId);

            row.ServiceState = serviceState;

            // Assignment information
            if (assignDateTime.HasValue) row.AssignmentDateTime = (DateTime)assignDateTime;
            if (assignedDeadlineDate.HasValue) row.AssignedDeadlineDate = (DateTime)assignedDeadlineDate;
            row.AssignTeamMember = assignTeamMember;
            if (assignTeamMemberId.HasValue) row.AssignTeamMemberID = (int)assignTeamMemberId; else row.SetAssignTeamMemberIDNull();
            if (assignThirdPartyVendor != "") row.AssignThirdPartyVendor = assignThirdPartyVendor; else row.SetAssignThirdPartyVendorNull();

            // Accept information
            if (acceptDateTime.HasValue) row.AcceptDateTime = (DateTime)acceptDateTime; else row.SetAcceptDateTimeNull();

            // Start work information
            if (startWorkDateTime.HasValue) row.StartWorkDateTime = (DateTime)startWorkDateTime; else row.SetStartWorkDateTimeNull();
            if (unitOutOfServiceDate.HasValue) row.UnitOutOfServiceDate = (DateTime)unitOutOfServiceDate; else row.SetUnitOutOfServiceDateNull();
            if (unitOutOfServiceTime != "") row.UnitOutOfServiceTime = unitOutOfServiceTime; else row.SetUnitOutOfServiceTimeNull();

            // Complete work information
            if (completeWorkDateTime.HasValue) row.CompleteWorkDateTime = (DateTime)completeWorkDateTime; else row.SetCompleteWorkDateTimeNull();
            if (unitBackInServiceDate.HasValue) row.UnitBackInServiceDate = (DateTime)unitBackInServiceDate; else row.SetUnitBackInServiceDateNull();
            if (unitBackInServiceTime != "") row.UnitBackInServiceTime = unitBackInServiceTime; else row.SetUnitBackInServiceTimeNull();
            if (completeWorkDetailDescription != "") row.CompleteWorkDetailDescription = completeWorkDetailDescription; else row.SetCompleteWorkDetailDescriptionNull();
            row.CompleteWorkDetailPreventable = completeWorkDetailPreventable;
            if (completeWorkDetailTMLabourHours.HasValue) row.CompleteWorkDetailTMLabourHours = (Decimal)completeWorkDetailTMLabourHours; else row.SetCompleteWorkDetailTMLabourHoursNull();
            if (completeWorkDetailTMCost.HasValue) row.CompleteWorkDetailTMCost = (Decimal)completeWorkDetailTMCost; else row.SetCompleteWorkDetailTMCostNull();
            if (completeWorkInvoiceNumber != "") row.CompleteWorkInvoiceNumber = completeWorkInvoiceNumber; else row.IsCompleteWorkInvoiceNumberNull();
            if (completeWorkInvoiceAmount.HasValue) row.CompleteWorkInvoiceAmount = (decimal)completeWorkInvoiceAmount; else row.IsCompleteWorkInvoiceAmountNull();
            if (startWorkMileage != "") row.StartWorkMileage = startWorkMileage; else row.SetStartWorkMileageNull();
            if (completeWorkMileage != "") row.CompleteWorkMileage = completeWorkMileage; else row.SetCompleteWorkMileageNull();
            row.Deleted = deleted;
            row.COMPANY_ID = companyId;

            if (libraryCategoriesId.HasValue) row.LIBRARY_CATEGORIES_ID = libraryCategoriesId.Value; else row.SetLIBRARY_CATEGORIES_IDNull();

            if (row.Type == "Checklist")
            {
                if (serviceState == "Completed")
                {
                    RuleGateway ruleGateway = new RuleGateway();
                    ruleGateway.LoadAllByRuleId(row.RuleID, row.COMPANY_ID);

                    DateTime? lastService = (DateTime)unitBackInServiceDate;
                    DateTime? nextDue = null;

                    string frecuency = ruleGateway.GetFrequency(row.RuleID);

                    if (!ruleGateway.GetMto(row.RuleID))
                    {
                        if (frecuency != "Only once")
                        {
                            // Get next due
                            DateTime timeToAdded = new DateTime(((DateTime)lastService).Year, ((DateTime)lastService).Month, ((DateTime)lastService).Day);

                            if (frecuency == "Monthly") nextDue = timeToAdded.AddMonths(1);
                            if (frecuency == "Every 2 months") nextDue = timeToAdded.AddMonths(2);
                            if (frecuency == "Every 3 months") nextDue = timeToAdded.AddMonths(3);
                            if (frecuency == "Every 4 months") nextDue = timeToAdded.AddMonths(4);
                            if (frecuency == "Every 6 months") nextDue = timeToAdded.AddMonths(6);
                            if (frecuency == "Yearly") nextDue = timeToAdded.AddYears(1);

                            row.AssociatedChecklistLastService = (DateTime)lastService;
                            row.AssociatedChecklistNextDue = (DateTime)nextDue;
                            row.AssociatedChecklistDone = false;
                            if (newAssociatedChecklistRuleState != "") row.AssociatedChecklistRuleState = newAssociatedChecklistRuleState; else row.SetAssociatedChecklistRuleStateNull();
                        }
                        else
                        {
                            row.AssociatedChecklistLastService = (DateTime)lastService;
                            row.SetAssociatedChecklistNextDueNull();
                            row.AssociatedChecklistDone = true;
                            if (newAssociatedChecklistRuleState != "") row.AssociatedChecklistRuleState = newAssociatedChecklistRuleState; else row.SetAssociatedChecklistRuleStateNull();
                        }
                    }
                    else
                    {
                        ServiceInformationBasicInformation serviceInformationBasicInformation = new ServiceInformationBasicInformation();
                        serviceInformationBasicInformation.LoadInProgressByServiceIdUnitIdRuleId(row.ServiceID, row.UnitID, row.RuleID, row.COMPANY_ID);

                        if (serviceInformationBasicInformation.Table.Rows.Count > 1)
                        {
                            row.AssociatedChecklistRuleState = "In Progress";
                        }
                        else
                        {
                            row.AssociatedChecklistRuleState = newAssociatedChecklistRuleState;
                        }

                        if (frecuency != "Only once")
                        {
                            row.AssociatedChecklistDone = false;
                        }
                        else
                        {
                            row.AssociatedChecklistDone = true;
                        }
                    }
                }
            }
        }
        // ////////////////////////////////////////////////////////////////////////
        // EVENTS
        //
        protected void Page_Load(object sender, EventArgs e)
        {
            // Register client scripts
            this.RegisterClientScripts();

            if (!IsPostBack)
            {
                // Security check
                if (!(Convert.ToBoolean(Session["sgLFS_FLEETMANAGEMENT_SERVICES_VIEW"]) && Convert.ToBoolean(Session["sgLFS_FLEETMANAGEMENT_SERVICES_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["service_id"] == null) || ((string)Request.QueryString["dashboard"] == null))
                {
                    Response.Redirect("./../../error_page.aspx?error=" + "Invalid query string in services_delete.aspx");
                }

                // Tag Page
                hdfCompanyId.Value = Session["companyID"].ToString();
                hdfServiceId.Value = Request.QueryString["service_id"].ToString();
                hdfDashboard.Value = Request.QueryString["dashboard"].ToString();
                hdfFmType.Value = "Services";

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

                    serviceInformationTDS = new ServiceInformationTDS();
                    servicesTDS = new ServicesTDS();

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

                    ServiceInformationBasicInformation serviceInformationBasicInformation = new ServiceInformationBasicInformation(serviceInformationTDS);
                    serviceInformationBasicInformation.LoadByServiceId(serviceId, companyId);

                    ServiceInformationServiceCost serviceInformationServiceCostForEdit = new ServiceInformationServiceCost(serviceInformationTDS);
                    serviceInformationServiceCostForEdit.LoadByServiceId(serviceId, companyId);

                    ServiceInformationServiceNote serviceInformationServiceNoteForEdit = new ServiceInformationServiceNote(serviceInformationTDS);
                    serviceInformationServiceNoteForEdit.LoadByServiceId(serviceId, companyId);

                    // Store dataset
                    Session["serviceInformationTDS"] = serviceInformationTDS;
                    Session["servicesTDS"] = servicesTDS;
                }

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

                    // Restore dataset
                    servicesTDS = (ServicesTDS)Session["servicesTDS"];
                    serviceInformationTDS = (ServiceInformationTDS)Session["serviceInformationTDS"];
                }
            }
            else
            {
                // Restore datasets
                servicesTDS = (ServicesTDS)Session["servicesTDS"];
                serviceInformationTDS = (ServiceInformationTDS)Session["serviceInformationTDS"];
            }
        }
        private void UpdateDatabase()
        {
            // Get ids
            int serviceId = Int32.Parse(hdfServiceId.Value);
            string serviceType = hdfFmType.Value;
            int companyId = Int32.Parse(hdfCompanyId.Value);

            ServiceInformationBasicInformationGateway serviceInformationBasicInformationGatewayForId = new ServiceInformationBasicInformationGateway(serviceInformationTDS);
            int? unitId = serviceInformationBasicInformationGatewayForId.GetUnitID(serviceId);

            UnitsGateway unitsGateway = new UnitsGateway();
            unitsGateway.LoadByUnitId((int)unitId, companyId);
            string unitType = unitsGateway.GetType((int)unitId);

            // Delete
            DB.Open();
            DB.BeginTransaction();
            try
            {
                ServiceInformationBasicInformation serviceInformationBasicInformation = new ServiceInformationBasicInformation(serviceInformationTDS);
                serviceInformationBasicInformation.DeleteDirect(serviceId, unitType, (int)unitId, companyId);

                DB.CommitTransaction();
            }
            catch (Exception ex)
            {
                DB.RollbackTransaction();

                string url = string.Format("./../../error_page.aspx?error={0}", ex.Message.Replace('\n', ' '));
                Response.Redirect(url);
            }
        }
        private void UpdateDatabase()
        {
            int companyId = Int32.Parse(hdfCompanyId.Value);

            LibraryFilesGateway libraryFilesGateway = new LibraryFilesGateway(libraryTDSForServices);
            libraryFilesGateway.Update();

            DB.Open();
            DB.BeginTransaction();
            try
            {
                ServiceInformationServiceNoteGateway serviceInformationServiceNoteGateway = new ServiceInformationServiceNoteGateway(serviceInformationTDS);
                ServiceInformationServiceNote serviceInformationServiceNote = new ServiceInformationServiceNote(serviceInformationTDS);

                foreach (ServiceInformationTDS.NoteInformationRow rowNotes in (ServiceInformationTDS.NoteInformationDataTable)serviceInformationServiceNoteGateway.Table)
                {
                    if (!rowNotes.IsLIBRARY_FILES_IDNull())
                    {
                        if (rowNotes.LIBRARY_FILES_ID == 0 && rowNotes.FILENAME != "")
                        {
                            libraryFilesGateway.LoadByFileName(rowNotes.FILENAME, companyId);
                            int newLibraryFilesId = libraryFilesGateway.GetlibraryFilesId(rowNotes.FILENAME);

                            rowNotes.LIBRARY_FILES_ID = newLibraryFilesId;
                        }
                    }
                }

                // Save costs information
                ServiceInformationServiceCost serviceInformationServiceCost = new ServiceInformationServiceCost(serviceInformationTDS);
                serviceInformationServiceCost.Save(companyId);

                // Save notes information
                serviceInformationServiceNote.Save(companyId);

                // Save service information
                ServiceInformationBasicInformation serviceInformationBasicInformation = new ServiceInformationBasicInformation(serviceInformationTDS);
                serviceInformationBasicInformation.Save(companyId);

                DB.CommitTransaction();

                // Store datasets
                libraryTDSForServices.AcceptChanges();
                serviceInformationTDS.AcceptChanges();
                Session["serviceInformationTDS"] = serviceInformationTDS;
                Session["libraryTDSForServices"] = libraryTDSForServices;
            }
            catch (Exception ex)
            {
                DB.RollbackTransaction();

                string url = string.Format("./../../error_page.aspx?error={0}", ex.Message.Replace('\n', ' '));
                Response.Redirect(url);
            }
        }
        /// <summary>
        /// UpdateUnitState
        /// </summary>
        /// <param name="unitId">unitId</param>
        /// <param name="state">state</param>
        /// <param name="companyId">companyId</param>
        private void UpdateUnitState(int unitId, string state, int companyId)
        {
            ServiceInformationBasicInformation serviceInformationBasicInformation = new ServiceInformationBasicInformation();
            serviceInformationBasicInformation.LoadInProgressByUnitId(unitId, companyId);

            if (serviceInformationBasicInformation.Table.Rows.Count == 0)
            {
                LiquiForce.LFSLive.BL.FleetManagement.Units.Units units = new LiquiForce.LFSLive.BL.FleetManagement.Units.Units(null);
                units.UpdateStateDirect(unitId, companyId, state);
            }
        }
        // ////////////////////////////////////////////////////////////////////////
        // EVENTS
        //
        protected void Page_Load(object sender, EventArgs e)
        {
            // Register client scripts
            this.RegisterClientScripts();

            if (!IsPostBack)
            {
                // Security check
                if (!(Convert.ToBoolean(Session["sgLFS_FLEETMANAGEMENT_SERVICES_VIEW"]) && Convert.ToBoolean(Session["sgLFS_FLEETMANAGEMENT_SERVICES_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["service_id"] == null) || ((string)Request.QueryString["active_tab"] == null) || ((string)Request.QueryString["dashboard"] == null))
                {
                    Response.Redirect("./../../error_page.aspx?error=" + "Invalid query string in services_edit.aspx");
                }

                // Tag Page
                hdfCompanyId.Value = Session["companyID"].ToString();
                hdfFmType.Value = "Services";
                hdfServiceId.Value = Request.QueryString["service_id"].ToString();
                hdfActiveTab.Value = Request.QueryString["active_tab"].ToString();
                hdfLoginId.Value = Convert.ToInt32(Session["loginID"]).ToString();
                hdfDashboard.Value = Request.QueryString["dashboard"].ToString();

                // Prepare initial data
                Session.Remove("serviceCostsDummy");
                Session.Remove("serviceNotesDummy");

                // If coming from
                int companyId = Int32.Parse(hdfCompanyId.Value.Trim());
                int serviceId = Int32.Parse(hdfServiceId.Value.Trim());
                string fmType = hdfFmType.Value;

                // ... services_navigator2.aspx, services_add_request.aspx, services_manager_tool.aspx
                if ((Request.QueryString["source_page"] == "services_navigator2.aspx") || (Request.QueryString["source_page"] == "services_add_request.aspx") || (Request.QueryString["source_page"] == "services_manager_tool.aspx"))
                {
                    StoreNavigatorState();
                    ViewState["update"] = "no";

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

                        serviceInformationTDS = new ServiceInformationTDS();

                        ServiceInformationBasicInformation serviceInformationBasicInformation = new ServiceInformationBasicInformation(serviceInformationTDS);
                        serviceInformationBasicInformation.LoadByServiceId(serviceId, companyId);

                        ServiceInformationServiceCost serviceInformationServiceCostForEdit = new ServiceInformationServiceCost(serviceInformationTDS);
                        serviceInformationServiceCostForEdit.LoadByServiceId(serviceId, companyId);

                        ServiceInformationServiceNote serviceInformationServiceNoteForEdit = new ServiceInformationServiceNote(serviceInformationTDS);
                        serviceInformationServiceNoteForEdit.LoadByServiceId(serviceId, companyId);
                    }
                    else
                    {
                        hdfActiveTab.Value = (string)Session["activeTabServices"];

                        // Restore datasets
                        serviceInformationTDS = (ServiceInformationTDS)Session["serviceInformationTDS"];
                    }

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

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

                    // ... Restore dataset
                    serviceInformationTDS = (ServiceInformationTDS)Session["serviceInformationTDS"];

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

                        if (ViewState["update"].ToString().Trim() == "yes")
                        {
                            ServiceInformationBasicInformation serviceInformationBasicInformation = new ServiceInformationBasicInformation(serviceInformationTDS);
                            serviceInformationBasicInformation.LoadByServiceId(serviceId, companyId);

                            ServiceInformationServiceCost serviceInformationServiceCostForEdit = new ServiceInformationServiceCost(serviceInformationTDS);
                            serviceInformationServiceCostForEdit.LoadByServiceId(serviceId, companyId);

                            ServiceInformationServiceNote serviceInformationServiceNoteForEdit = new ServiceInformationServiceNote(serviceInformationTDS);
                            serviceInformationServiceNoteForEdit.LoadByServiceId(serviceId, companyId);

                            // ... Store dataset
                            Session["serviceInformationTDS"] = serviceInformationTDS;
                        }
                    }
                    else
                    {
                        hdfActiveTab.Value = (string)Session["activeTabServices"];
                    }
                }

                // Prepare initial data
                lblMissingData.Visible = false;

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

                // ... For total cost
                ServiceInformationServiceCost serviceInformationServiceCostForTotalCost = new ServiceInformationServiceCost(serviceInformationTDS);
                tbxTotalCost.Text = Decimal.Round(serviceInformationServiceCostForTotalCost.GetTotalCost(serviceId, companyId), 2).ToString();

                // ... Data for current servicew
                LoadServiceData(companyId);

                // Databind
                Page.DataBind();

                ServiceInformationBasicInformationGateway serviceInformationBasicInformationGateway = new ServiceInformationBasicInformationGateway(serviceInformationTDS);
                if (serviceInformationBasicInformationGateway.GetAssignTeamMemberId(serviceId).HasValue)
                {
                    try
                    {
                        ddlAssignmentDataAssignToTeamMember.SelectedValue = ((int)serviceInformationBasicInformationGateway.GetAssignTeamMemberId(serviceId)).ToString();
                    }
                    catch
                    {
                        ddlAssignmentDataAssignToTeamMember.SelectedIndex = 0;
                    }

                    int teamMemberId = (int)serviceInformationBasicInformationGateway.GetAssignTeamMemberId(serviceId);
                    EmployeeGateway employeeGateway = new EmployeeGateway();
                    employeeGateway.LoadByEmployeeId(teamMemberId);
                    tbxAssignmentDataAssignToTeamMemberReadOnly.Text = employeeGateway.GetLastName(teamMemberId) + " " + employeeGateway.GetFirstName(teamMemberId);
                }

                // For thirds party vendor autocomplete
                aceThirdPartyVendor.ContextKey = serviceId.ToString() + "," + hdfCompanyId.Value;

                // ... For Library
                if (Session["libraryTDSForServices"] != null)
                {
                    libraryTDSForServices = (LibraryTDS)Session["libraryTDSForServices"];
                }
                else
                {
                    libraryTDSForServices = new LibraryTDS();
                }
            }
            else
            {
                // Restore datasets
                serviceInformationTDS = (ServiceInformationTDS)Session["serviceInformationTDS"];

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

                if (Session["libraryTDSForServices"] != null)
                {
                    libraryTDSForServices = (LibraryTDS)Session["libraryTDSForServices"];
                }
                else
                {
                    libraryTDSForServices = new LibraryTDS();
                }

                LoadNotes();
            }
        }
        // ////////////////////////////////////////////////////////////////////////
        // EVENTS
        //
        protected void Page_Load(object sender, EventArgs e)
        {
            // Register client scripts
            this.RegisterClientScripts();

            if (!IsPostBack)
            {
                // Security check
                if (!(Convert.ToBoolean(Session["sgLFS_FLEETMANAGEMENT_SERVICES_VIEW"]) && Convert.ToBoolean(Session["sgLFS_FLEETMANAGEMENT_SERVICES_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["service_id"] == null) || ((string)Request.QueryString["active_tab"] == null) || ((string)Request.QueryString["dashboard"] == null))
                {
                    Response.Redirect("./../../error_page.aspx?error=" + "Invalid query string in services_summary.aspx");
                }

                // Tag Page
                hdfCompanyId.Value = Session["companyID"].ToString();
                hdfFmType.Value = "Services";
                hdfServiceId.Value = Request.QueryString["service_id"].ToString();
                hdfActiveTab.Value = Request.QueryString["active_tab"].ToString();
                hdfLoginId.Value = Convert.ToInt32(Session["loginID"]).ToString();
                hdfDashboard.Value = Request.QueryString["dashboard"].ToString();

                // Prepare initial data
                Session.Remove("serviceCostsDummy");
                Session.Remove("serviceNotesDummy");

                // If comming from
                int companyId = Int32.Parse(hdfCompanyId.Value.Trim());
                int serviceId = Int32.Parse(hdfServiceId.Value.Trim());
                string fmType = hdfFmType.Value;

                // ... services_navigator2.aspx, add_service_request.aspx, wucSRUnassigned.ascx, wucSRMyServiceRequest.ascx, wucItemsAboutToExpire.ascx, wucExpiredItems.ascx, wucAlarms.ascx, wucSRInProgress.ascx, services_manager_tool.aspx
                if ((Request.QueryString["source_page"] == "services_navigator2.aspx") || (Request.QueryString["source_page"] == "services_add_request.aspx") || (Request.QueryString["source_page"] == "wucSRUnassigned.ascx") || (Request.QueryString["source_page"] == "wucSRMyServiceRequest.ascx") || (Request.QueryString["source_page"] == "wucItemsAboutToExpire.ascx") || (Request.QueryString["source_page"] == "wucExpiredItems.ascx") || (Request.QueryString["source_page"] == "wucAlarms.ascx") || (Request.QueryString["source_page"] == "wucSRInProgress.ascx") || (Request.QueryString["source_page"] == "services_manager_tool.aspx"))
                {
                    StoreNavigatorState();
                    ViewState["update"] = "yes";

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

                        serviceInformationTDS = new ServiceInformationTDS();

                        ServiceInformationBasicInformation serviceInformationBasicInformation = new ServiceInformationBasicInformation(serviceInformationTDS);
                        serviceInformationBasicInformation.LoadByServiceId(serviceId, companyId);

                        ServiceInformationServiceCost serviceInformationServiceCostForEdit = new ServiceInformationServiceCost(serviceInformationTDS);
                        serviceInformationServiceCostForEdit.LoadByServiceId(serviceId, companyId);
                        tbxTotalCost.Text = Decimal.Round(serviceInformationServiceCostForEdit.GetTotalCost(serviceId, companyId), 2).ToString();

                        ServiceInformationServiceNote serviceInformationServiceNoteForEdit = new ServiceInformationServiceNote(serviceInformationTDS);
                        serviceInformationServiceNoteForEdit.LoadByServiceId(serviceId, companyId);
                    }
                    else
                    {
                        hdfActiveTab.Value = (string)Session["activeTabServices"];

                        // Restore datasets
                        serviceInformationTDS = (ServiceInformationTDS)Session["serviceInformationTDS"];
                    }

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

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

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

                    // Restore dataset
                    serviceInformationTDS = (ServiceInformationTDS)Session["serviceInformationTDS"];

                    ServiceInformationBasicInformation serviceInformationBasicInformation = new ServiceInformationBasicInformation(serviceInformationTDS);
                    serviceInformationBasicInformation.LoadByServiceId(serviceId, companyId);

                    ServiceInformationServiceCost serviceInformationServiceCostForEdit = new ServiceInformationServiceCost(serviceInformationTDS);
                    serviceInformationServiceCostForEdit.LoadByServiceId(serviceId, companyId);
                    tbxTotalCost.Text = Decimal.Round(serviceInformationServiceCostForEdit.GetTotalCost(serviceId, companyId), 2).ToString();

                    ServiceInformationServiceNote serviceInformationServiceNoteForEdit = new ServiceInformationServiceNote(serviceInformationTDS);
                    serviceInformationServiceNoteForEdit.LoadByServiceId(serviceId, companyId);

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

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

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

                // Prepare initial data
                // ... Data for current service
                LoadServiceData(companyId);

                // ... For total cost
                ServiceInformationServiceCost serviceInformationServiceCostForTotalCost = new ServiceInformationServiceCost(serviceInformationTDS);
                tbxTotalCost.Text = Decimal.Round(serviceInformationServiceCostForTotalCost.GetTotalCost(serviceId, companyId), 2).ToString();

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

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