// ////////////////////////////////////////////////////////////////////////
        // 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();
            }
        }
        protected void grdNotes_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            // Notes Gridview, if the gridview is edition mode
            if (grdNotes.EditIndex >= 0)
            {
                grdNotes.UpdateRow(grdNotes.EditIndex, true);
            }

            // Delete notes
            int serviceId = (int)e.Keys["ServiceID"];
            int refId = (int)e.Keys["RefID"];

            ServiceInformationServiceNote model = new ServiceInformationServiceNote(serviceInformationTDS);

            model.Delete(serviceId, refId);

            int? libraryFilesId = null;
            if (((Label)grdNotes.Rows[e.RowIndex].Cells[3].FindControl("lblLibraryFileId")).Text.Trim() != "")
            {
                libraryFilesId = Int32.Parse(((Label)grdNotes.Rows[e.RowIndex].Cells[3].FindControl("lblLibraryFileId")).Text.Trim());
                LibraryFilesGateway libraryFilesGateway = new LibraryFilesGateway();
                libraryFilesGateway.DeleteByLibraryFilesId((int)libraryFilesId);
            }

            // Store dataset
            Session["serviceInformationTDS"] = serviceInformationTDS;
        }
        protected void grdNotes_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            Page.Validate("notesDataEdit");

            if (Page.IsValid)
            {
                int serviceId = (int)e.Keys["ServiceID"];
                int refId = (int)e.Keys["RefID"];

                string subject = ((TextBox)grdNotes.Rows[e.RowIndex].Cells[2].FindControl("tbxNoteSubjectEdit")).Text.Trim();
                string note = ((TextBox)grdNotes.Rows[e.RowIndex].Cells[3].FindControl("tbxNoteNoteEdit")).Text.Trim();

                int? libraryFilesId = null;
                if (((Label)grdNotes.Rows[e.RowIndex].Cells[3].FindControl("lblLibraryFileIdEdit")).Text.Trim() != "")
                {
                    libraryFilesId = Int32.Parse(((Label)grdNotes.Rows[e.RowIndex].Cells[3].FindControl("lblLibraryFileIdEdit")).Text.Trim());
                }

                // Update data
                ServiceInformationServiceNote model = new ServiceInformationServiceNote(serviceInformationTDS);
                model.Update(serviceId, refId, subject, note, libraryFilesId);

                // Store dataset
                Session["serviceInformationTDS"] = serviceInformationTDS;
            }
            else
            {
                e.Cancel = true;
            }
        }
        private void GrdNotesDeleteAttachment(int libraryFileId, int refId)
        {
            // Button delete functionality
            if (libraryFileId != 0)
            {
                ServiceInformationServiceNote model = new ServiceInformationServiceNote(serviceInformationTDS);
                model.UpdateLibraryFilesId(int.Parse(hdfServiceId.Value), refId, null, "", "");

                LibraryFilesGateway libraryFilesGateway = new LibraryFilesGateway(libraryTDSForServices);
                libraryFilesGateway.DeleteByLibraryFilesId(libraryFileId);

                ViewState["update"] = "no";

                Session["serviceInformationTDS"] = serviceInformationTDS;
                Session["libraryTDSForServices"] = libraryTDSForServices;
                grdNotes.DataBind();
                grdCosts.DataBind();
            }
        }
        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);
            }
        }
        private void GrdNotesAddAttachment(int? refId, string subject)
        {
            Save2();

            // Escape single quote
            subject = subject.Replace("'", "%27");

            if (refId.HasValue)
            {
                if (ViewState["libraryCategoriesId"] != null)
                {

                    string script = "<script language='javascript'>";
                    string url = "./services_add_attachment.aspx?source_page=services_edit.aspx&subject=" + Server.UrlEncode(subject) + "&refId=" + refId.ToString() + "&service_id=" + hdfServiceId.Value + "&library_categories_id=" + Int32.Parse(ViewState["libraryCategoriesId"].ToString());
                    script = script + string.Format("window.open('{0}', '_blank', 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width=510, height=270')", url);
                    script = script + "</script>";
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "Notes", script, false);
                }
            }
            else
            {
                ServiceInformationServiceNote model = new ServiceInformationServiceNote(serviceInformationTDS);
                refId = model.GetLastRefId();

                if (ViewState["libraryCategoriesId"] != null)
                {
                    string script = "<script language='javascript'>";
                    string url = "./services_add_attachment.aspx?source_page=services_edit.aspx&subject=" + Server.UrlEncode(subject) + "&refId=" + refId.ToString() + "&service_id=" + hdfServiceId.Value + "&library_categories_id=" + Int32.Parse(ViewState["libraryCategoriesId"].ToString());
                    script = script + string.Format("window.open('{0}', '_blank', 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width=510, height=270')", url);
                    script = script + "</script>";
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "Notes", script, false);
                }
            }
        }
        private void GrdNotesAddFromCost(string subject, string note)
        {
            int serviceId = Int32.Parse(hdfServiceId.Value);
            int companyId = Int32.Parse(hdfCompanyId.Value);
            string newSubject = subject;
            int loginId = Convert.ToInt32(Session["loginID"]);
            DateTime dateTime_ = DateTime.Now;
            string newNote = note;
            bool inServiceNoteDatabase = false;
            int? libraryFilesId = null;

            ServiceInformationServiceNote model = new ServiceInformationServiceNote(serviceInformationTDS);
            model.Insert(serviceId, newSubject, loginId, dateTime_, newNote, libraryFilesId, false, companyId, inServiceNoteDatabase);

            Session.Remove("serviceNotesDummy");
            Session["serviceInformationTDS"] = serviceInformationTDS;

            grdNotes.DataBind();
            grdNotes.PageIndex = grdNotes.PageCount - 1;
        }
        protected void btnAddAtachment_Click(object sender, EventArgs e)
        {
            Session["activeTabServices"] = "4";
            Session["dialogOpenedServices"] = "1";

            GrdNotesAddFromCost(tbxNoteNoteNew.Text, tbxNoteNoteNew.Text);//TODO

            ServiceInformationServiceNote model = new ServiceInformationServiceNote(serviceInformationTDS);
            int refId = model.GetLastRefId();

            if (ViewState["libraryCategoriesId"] != null)
            {
                string subject = "";

                // Escape single quote
                subject = tbxNoteNoteNew.Text.Replace("'", "%27");

                string script = "<script language='javascript'>";
                string url = "./services_add_attachment.aspx?source_page=services_edit.aspx&subject=" + Server.UrlEncode(subject) + "&refId=" + refId.ToString() + "&service_id=" + hdfServiceId.Value + "&library_categories_id=" + Int32.Parse(ViewState["libraryCategoriesId"].ToString());
                script = script + string.Format("window.open('{0}', '_blank', 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width=510, height=270')", url);
                script = script + "</script>";
                ScriptManager.RegisterStartupScript(this, this.GetType(), "Notes", script, false);
            }
        }
        private void GrdNotesAdd()
        {
            if (ValidateNotesFooter())
            {
                Page.Validate("notesDataAdd");
                if (Page.IsValid)
                {
                    int serviceId = Int32.Parse(hdfServiceId.Value);
                    int companyId = Int32.Parse(hdfCompanyId.Value);
                    string newSubject = ((TextBox)grdNotes.FooterRow.FindControl("tbxNoteSubjectNew")).Text.Trim();
                    int loginId = Convert.ToInt32(Session["loginID"]);
                    DateTime dateTime_ = DateTime.Now;
                    string newNote = ((TextBox)grdNotes.FooterRow.FindControl("tbxNoteNoteNew")).Text.Trim();
                    bool inServiceNoteDatabase = false;
                    int? libraryFilesId = null;
                    string fileName = ((Label)grdNotes.FooterRow.FindControl("lblFileNameNoteAttachmentNew")).Text.Trim();
                    if (fileName != "")
                    {
                        LibraryFilesGateway libraryFilesGateway = new LibraryFilesGateway();
                        libraryFilesId = libraryFilesGateway.GetlibraryFilesId(fileName);
                    }

                    ServiceInformationServiceNote model = new ServiceInformationServiceNote(serviceInformationTDS);
                    model.Insert(serviceId, newSubject, loginId, dateTime_, newNote, libraryFilesId, false, companyId, inServiceNoteDatabase);

                    Session.Remove("serviceNotesDummy");
                    Session["serviceInformationTDS"] = serviceInformationTDS;

                    grdNotes.DataBind();
                    grdNotes.PageIndex = grdNotes.PageCount - 1;
                }
            }
        }
        // ////////////////////////////////////////////////////////////////////////
        // STEP2 - STEPS INFORMATION - METHODS
        //
        private void StepStepsInformationIn()
        {
            // Set instruction
            Label instruction = (Label)this.Master.FindControl("lblInstruction");
            instruction.Text = "";

            // Load data for selected service request
            int serviceId = Int32.Parse(hdfSelectedSRId.Value);
            int companyId = Int32.Parse(hdfCompanyId.Value);

            ServiceRequestsManagerToolBasicInformation serviceRequestsManagerToolBasicInformation = new ServiceRequestsManagerToolBasicInformation(serviceRequestsManagerToolTDS);
            ServiceRequestsManagerToolCostInformation serviceRequestsManagerToolCostInformation = new ServiceRequestsManagerToolCostInformation(serviceRequestsManagerToolTDS);
            ServiceInformationServiceNote serviceInformationServiceNoteForEdit = new ServiceInformationServiceNote(serviceInformationTDS);

            if (Session["dialogOpenedServicesManagerTool"] == null)
            {
                // ... Load basic data
                serviceRequestsManagerToolBasicInformation.LoadByServiceId(serviceId, companyId);

                // ... Load costs
                serviceRequestsManagerToolCostInformation.LoadByServiceId(serviceId, companyId);

                //... Load notes
                serviceInformationServiceNoteForEdit.LoadByServiceId(serviceId, companyId);
            }
            else
            {
                ServiceRequestsManagerToolBasicInformationGateway serviceRequestsManagerToolBasicInformationGateway2 = new ServiceRequestsManagerToolBasicInformationGateway(serviceRequestsManagerToolBasicInformation.Data);

                Session.Remove("dialogOpenedServicesManagerTool");

                if (serviceRequestsManagerToolBasicInformationGateway2.GetAcceptedDateTime(serviceId).HasValue) ckbxAcceptSR.Checked = true;
                if (serviceRequestsManagerToolBasicInformationGateway2.GetStartWorkDateTime(serviceId).HasValue) ckbxStartSR.Checked = true;
                if (serviceRequestsManagerToolBasicInformationGateway2.GetUnitOutOfServiceDate(serviceId).HasValue) tkrdpStartWorkUnitOutOfServiceDate.SelectedDate = serviceRequestsManagerToolBasicInformationGateway2.GetUnitOutOfServiceDate(serviceId);
                tbxStartWorkStartMileage.Text = serviceRequestsManagerToolBasicInformationGateway2.GetStartWorkMileage(serviceId);
                if (serviceRequestsManagerToolBasicInformationGateway2.GetCompleteWorkDateTime(serviceId).HasValue) ckbxCompleteSR.Checked = true;
                if (serviceRequestsManagerToolBasicInformationGateway2.GetUnitBackInServiceDate(serviceId).HasValue) tkrdpCompleteWorkUnitBackInServiceDate.SelectedDate = serviceRequestsManagerToolBasicInformationGateway2.GetUnitBackInServiceDate(serviceId);
                tbxCompleteWorkCompleteMileage.Text = serviceRequestsManagerToolBasicInformationGateway2.GetCompleteWorkMileage(serviceId);
                tbxCompleteWorkDataDescription.Text = serviceRequestsManagerToolBasicInformationGateway2.GetCompleteWorkDetailDescription(serviceId);
                ckbxPreventableTPV.Checked = serviceRequestsManagerToolBasicInformationGateway2.GetCompleteWorkDetailPreventable(serviceId);
                tbxCompleteWorkDataLabourHours.Text = serviceRequestsManagerToolBasicInformationGateway2.GetCompleteWorkDetailTMLabourHours(serviceId).ToString();
            }

            ServiceRequestsManagerToolBasicInformationGateway serviceRequestsManagerToolBasicInformationGateway = new ServiceRequestsManagerToolBasicInformationGateway(serviceRequestsManagerToolBasicInformation.Data);

            // Validate panels and information
            string state = serviceRequestsManagerToolBasicInformationGateway.GetServiceStateOriginal(serviceId);
            hdfState.Value = state;
            hdfServiceNumber.Value = serviceRequestsManagerToolBasicInformationGateway.GetServiceNumberOriginal(serviceId);
            hdfServiceDescription.Value = serviceRequestsManagerToolBasicInformationGateway.GetServiceDescriptionOriginal(serviceId);

            string originalThirdsPartyVendor = serviceRequestsManagerToolBasicInformationGateway.GetAssignedThirdPartyVendor(serviceId);
            int? unitId = null;
            if (serviceRequestsManagerToolBasicInformationGateway.GetUnitId(serviceId).HasValue)
            {
                unitId = (int)serviceRequestsManagerToolBasicInformationGateway.GetUnitId(serviceId);
                hdfUnitId.Value = unitId.ToString();
            }

            // ... Validate vehicle information
            if (unitId.HasValue)
            {
                UnitsGateway unitsGateway = new UnitsGateway();
                unitsGateway.LoadByUnitId((int)unitId, companyId);
                string unitType = unitsGateway.GetType((int)unitId);
                hdfUnitType.Value = unitType;
                int companyLevel = unitsGateway.GetCompanyLevelId((int)unitId);
                hdfCompanyLevel.Value = unitsGateway.GetCompanyLevelId((int)unitId).ToString();

                CompanyLevelGateway companyLevelGateway = new CompanyLevelGateway();
                companyLevelGateway.LoadByCompanyLevelId(companyLevel, companyId);
                hdfMileageUnitOfMeasurement.Value = companyLevelGateway.GetUnitsUnitOfMeasurement(companyLevel);
                lblStartWorkStartMileageUnitOfMeasurement.Text = hdfMileageUnitOfMeasurement.Value;
                lblCompleteWorkCompleteMileageUnitOfMeasurement.Text = hdfMileageUnitOfMeasurement.Value;

                if (unitType == "Vehicle")
                {
                    lblStartWorkStartMileage.Visible = true;
                    tbxStartWorkStartMileage.Visible = true;
                    lblCompleteWorkCompleteMileage.Visible = true;
                    tbxCompleteWorkCompleteMileage.Visible = true;
                    lblStartWorkStartMileageUnitOfMeasurement.Visible = true;
                    lblCompleteWorkCompleteMileageUnitOfMeasurement.Visible = true;
                }
                else
                {
                    lblStartWorkStartMileage.Visible = false;
                    tbxStartWorkStartMileage.Visible = false;
                    lblStartWorkStartMileageUnitOfMeasurement.Visible = false;
                    lblCompleteWorkCompleteMileage.Visible = false;
                    tbxCompleteWorkCompleteMileage.Visible = false;
                    lblCompleteWorkCompleteMileageUnitOfMeasurement.Visible = false;
                }
            }

            // ... Validate visible internal panels (complete work info)
            if (state == "Unassigned")
            {
                if (!rbtnAssignToThirdPartyVendor.Checked)
                {
                    pnlAssignTeamMember.Visible = true;
                    pnlAssignThirdPartyVendor.Visible = false;
                }
                else
                {
                    pnlAssignThirdPartyVendor.Visible = true;
                    pnlAssignTeamMember.Visible = false;
                }
            }
            else
            {
                bool teamMemberAssigned = serviceRequestsManagerToolBasicInformationGateway.GetAssignTeamMember(serviceId);
                if (teamMemberAssigned)
                {
                    pnlAssignTeamMember.Visible = true;
                    pnlAssignThirdPartyVendor.Visible = false;
                }
                else
                {
                    pnlAssignThirdPartyVendor.Visible = true;
                    pnlAssignTeamMember.Visible = false;
                }
            }

            // ... Validate panels
            switch (state)
            {
                case "Unassigned":
                    pnlAssignmentInformation.Visible = true;
                    acceptInformationSeparator.Visible = true;
                    pnlAcceptInformation.Visible = true;
                    startWorkSeparator.Visible = true;
                    pnlStartWorkInformation.Visible = true;
                    completeWorkSeparator.Visible = true;
                    pnlCompleteWorkInformation.Visible = true;
                    break;

                case "Assigned":
                    pnlAssignmentInformation.Visible = false;
                    acceptInformationSeparator.Visible = false;
                    pnlAcceptInformation.Visible = true;
                    startWorkSeparator.Visible = true;
                    pnlStartWorkInformation.Visible = true;
                    completeWorkSeparator.Visible = true;
                    pnlCompleteWorkInformation.Visible = true;
                    break;

                case "Rejected":
                    pnlAssignmentInformation.Visible = true;
                    acceptInformationSeparator.Visible = true;
                    pnlAcceptInformation.Visible = true;
                    startWorkSeparator.Visible = true;
                    pnlStartWorkInformation.Visible = true;
                    completeWorkSeparator.Visible = true;
                    pnlCompleteWorkInformation.Visible = true;
                    break;

                case "Accepted":
                    pnlAssignmentInformation.Visible = false;
                    acceptInformationSeparator.Visible = false;
                    pnlAcceptInformation.Visible = false;
                    startWorkSeparator.Visible = false;
                    pnlStartWorkInformation.Visible = true;
                    completeWorkSeparator.Visible = true;
                    pnlCompleteWorkInformation.Visible = true;
                    break;

                case "In Progress":
                    pnlAssignmentInformation.Visible = false;
                    acceptInformationSeparator.Visible = false;
                    pnlAcceptInformation.Visible = false;
                    startWorkSeparator.Visible = false;
                    pnlStartWorkInformation.Visible = false;
                    completeWorkSeparator.Visible = false;
                    pnlCompleteWorkInformation.Visible = true;
                    break;

                default:
                    throw new Exception("The option for " + wzServices.ActiveStep.Name + " step in services_manager_tool.Wizard_ActiveStepChanged function does not exist");
            }

            hdfPnlAcceptInformation.Value = pnlAcceptInformation.Visible.ToString();
            hdfPnlAssignmentInformation.Value = pnlAssignmentInformation.Visible.ToString();
            hdfPnlStartWorkInformation.Value = pnlStartWorkInformation.Visible.ToString();
            hdfPnlCompleteWorkInformation.Value = pnlCompleteWorkInformation.Visible.ToString();

            // ... Load resource library
            int? libraryCategoriesId = null; if (serviceRequestsManagerToolBasicInformationGateway.GetLibraryCategoriesId(serviceId).HasValue) libraryCategoriesId = (int)serviceRequestsManagerToolBasicInformationGateway.GetLibraryCategoriesId(serviceId);

            if (libraryCategoriesId.HasValue)
            {
                ViewState["libraryCategoriesId"] = (int)libraryCategoriesId;
                tbxCategoryAssocited.Text = GetFullCategoryName((int)libraryCategoriesId, companyId);
                btnAssociate.Visible = false;
                btnUnassociate.Visible = true;
            }
            else
            {
                tbxCategoryAssocited.Text = "";
                btnAssociate.Visible = true;
                btnUnassociate.Visible = false;
            }

            // Store session
            Session["serviceRequestsManagerToolTDS"] = serviceRequestsManagerToolTDS;
        }
        // ////////////////////////////////////////////////////////////////////////
        // 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 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);
            }
        }
        // ////////////////////////////////////////////////////////////////////////
        // 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;
            }
        }
        // ////////////////////////////////////////////////////////////////////////
        // METHODS
        //
        private void ProcessUpload2(int serviceId, int refId, int companyId)
        {
            LibraryFilesGateway libraryFilesGateway = new LibraryFilesGateway();

            try
            {
                //... Set the default path to store uploaded files.
                AppSettingsReader appSettingReader = new AppSettingsReader();
                string websitePath = appSettingReader.GetValue("WebsitePath", typeof(System.String)).ToString();

                string filename = "";

                //... Get the extension of file
                string[] shortFilename = nuifAttachment.FileName.Split(new char[] { '.' });
                string ext = "." + shortFilename[shortFilename.Length - 1];

                bool exit = false;

                while (!exit)
                {
                    StringBuilder builder = new StringBuilder();
                    Random rand = new Random();
                    char ch;

                    for (int i = 0; i < 8; i++)
                    {
                        ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * rand.NextDouble() + 65)));
                        builder.Append(ch);
                    }

                    filename = builder.ToString();
                    filename = filename + ext;

                    libraryFilesGateway.LoadByFileName(filename, companyId);

                    if (libraryFilesGateway.Table.Rows.Count > 0)
                    {
                        exit = false;
                    }
                    else
                    {
                        exit = true;
                    }
                }

                string pathFull = websitePath + "\\Files\\LF_DGHOUGDH\\Library\\";

                //... Save the file
                nuifAttachment.MoveTo(Path.Combine(pathFull, filename), MoveToOptions.Overwrite);

                LibraryFiles libraryFiles = new LibraryFiles(libraryTDSForServices);
                libraryFiles.Insert(filename, tbxDescription.Text, nuifAttachment.FileName, null, Convert.ToInt32(ViewState["libraryCategoriesId"]), Convert.ToInt32(hdfLoginId.Value), int.Parse(Session["companyID"].ToString()), nuifAttachment.FileContent.Length.ToString()); //Note: COMPANY_ID

                ServiceInformationServiceNote model = new ServiceInformationServiceNote(serviceInformationTDS);
                model.UpdateLibraryFilesId(serviceId, refId, 0, nuifAttachment.FileName, filename);

                int refIdCost = Convert.ToInt32(ViewState["refIdCost"].ToString());
                if (refIdCost > 0)
                {
                    ServiceInformationServiceCost modelCost = new ServiceInformationServiceCost(serviceInformationTDS);
                    modelCost.UpdateLibraryFilesId(serviceId, refIdCost, nuifAttachment.FileName, filename);
                }

                Session["libraryTDSForServices"] = libraryTDSForServices;

                if (Request.QueryString["source_page"] == "services_edit.aspx")
                {
                    Session["serviceInformationTDS"] = serviceInformationTDS;
                }
                else
                {
                    Session["serviceInformationTDSForManagerTool"] = serviceInformationTDS;
                }
            }
            catch (Exception ex)
            {
            }
        }