/// <summary>
        /// UpdateForDashboard
        /// </summary>
        /// <param name="companyId">companyId</param>
        public void UpdateForDashboard(int companyId)
        {
            foreach (DashboardTDS.DashboardInProgressServiceRequestsRow row in (DashboardTDS.DashboardInProgressServiceRequestsDataTable)Table)
            {
                // Get ruleId for the each service
                ServiceInformationBasicInformationGateway serviceInformationBasicInformationGateway = new ServiceInformationBasicInformationGateway();
                serviceInformationBasicInformationGateway.LoadByServiceId(row.ServiceID, companyId);
                int? ruleId = serviceInformationBasicInformationGateway.GetRuleId(row.ServiceID);

                if (ruleId.HasValue)
                {
                    RuleGateway ruleGateway = new RuleGateway();
                    ruleGateway.LoadAllByRuleId((int)ruleId, companyId);

                    if (ruleGateway.Table.Rows.Count > 0)
                    {
                        // Get ruleName for each service if exists
                        string ruleName = ruleGateway.GetName((int)ruleId);
                        row.InProgressServicesCompleteName = row.InProgressServicesCompleteName + " - " + ruleName;
                    }
                }
            }
        }
        /// <summary>
        /// GetChecklistState
        /// </summary>
        /// <param name="ruleId">ruleId</param>
        /// <param name="frequency">frequency</param>
        /// <param name="lastService">lastService</param>
        /// <param name="nextDue">nextDue</param>
        /// <param name="companyId">companyId</param>
        /// <returns>State</returns>
        private string GetChecklistState(int ruleId, string frequency, DateTime? lastService, DateTime? nextDue, int companyId)
        {
            string state = "Healthy";

            if (nextDue.HasValue)
            {
                if ((DateTime)nextDue < DateTime.Now)
                {
                    state = "Expired";
                }
                else
                {
                    RuleGateway ruleGateway = new RuleGateway();
                    ruleGateway.LoadAllByRuleId(ruleId, companyId);

                    int? alarmDays = ruleGateway.GetAlarmDays(ruleId);

                    if (alarmDays.HasValue)
                    {
                        TimeSpan diference;
                        int daysBeforeNextDue = 0;

                        diference = (DateTime)nextDue - DateTime.Now;
                        daysBeforeNextDue = diference.Days;

                        if (daysBeforeNextDue <= (int)alarmDays)
                        {
                            state = "Warning";
                        }
                    }
                }
            }

            return state;
        }
        private void LoadBasicData(int serviceId)
        {
            ServiceInformationBasicInformationGateway serviceInformationBasicInformationGateway = new ServiceInformationBasicInformationGateway(serviceInformationTDS);
            if (serviceInformationBasicInformationGateway.Table.Rows.Count > 0)
            {
                // Load service basic data
                tbxServiceState.Text = serviceInformationBasicInformationGateway.GetServiceState(serviceId);
                tbxServiceNumber.Text = serviceInformationBasicInformationGateway.GetServiceNumber(serviceId);
                tbxDateTime.Text = serviceInformationBasicInformationGateway.GetDateTime_(serviceId).ToString();
                ckbxMtoDto.Checked = serviceInformationBasicInformationGateway.GetMtoDto(serviceId);
                tbxServiceDescription.Text = serviceInformationBasicInformationGateway.GetServiceDescription(serviceId);

                // Load unit basic data
                tbxUnitCode.Text = serviceInformationBasicInformationGateway.GetUnitCode(serviceId);
                tbxUnitDescription.Text = serviceInformationBasicInformationGateway.GetUnitDescription(serviceId);
                tbxVinSn.Text = serviceInformationBasicInformationGateway.GetVinSn(serviceId);
                tbxUnitState.Text = serviceInformationBasicInformationGateway.GetUnitState(serviceId);

                // Load checklist data
                tbxAssociatedChecklistRule.Text = serviceInformationBasicInformationGateway.GetAssociatedChecklistRule(serviceId);
                tbxChecklistState.Text = serviceInformationBasicInformationGateway.GetAssociatedChecklistRuleState(serviceId);

                if (serviceInformationBasicInformationGateway.GetRuleId(serviceId).HasValue)
                {
                    RuleGateway ruleGateway = new RuleGateway();
                    int? ruleId = serviceInformationBasicInformationGateway.GetRuleId(serviceId);
                    ruleGateway.LoadAllByRuleId(ruleId.Value, Int32.Parse(hdfCompanyId.Value));
                    int? serviceRequestDays = ruleGateway.GetServiceRequestDays(ruleId.Value);

                    if (ruleGateway.GetMto(ruleId.Value) && serviceInformationBasicInformationGateway.GetAssociatedChecklistLastService(serviceId).HasValue)
                    {
                        tbxChecklistNextDueDate.Text = serviceInformationBasicInformationGateway.GetAssociatedChecklistLastService(serviceId).Value.ToShortDateString();
                    }
                    else
                    {
                        if (serviceRequestDays.HasValue)
                        {
                            int negValue = -1;
                            serviceRequestDays = serviceRequestDays.Value * negValue;
                            DateTime serviceRequestCreationDate = serviceInformationBasicInformationGateway.GetDateTime_(serviceId);
                            tbxChecklistNextDueDate.Text = serviceInformationBasicInformationGateway.GetAssociatedChecklistNextDue(serviceId).Value.AddDays(Convert.ToDouble(serviceRequestDays.Value)).ToShortDateString();
                        }
                    }
                }
            }
        }
        /// <summary>
        /// Save services
        /// </summary>
        /// <param name="dateTime_">dateTime_</param>
        /// <param name="employeeId">employeeId</param>
        /// <param name="companyId">companyId</param>
        /// <param name="checklistState">checklistState</param>
        public int? Save(DateTime dateTime_, int employeeId, int companyId)
        {
            int? newServiceId = null;

            ServicesAddRequestTDS servicesAddRequestSelfAsignedChanges = (ServicesAddRequestTDS)Data.GetChanges();
            if (servicesAddRequestSelfAsignedChanges.BasicInformation.Rows.Count > 0)
            {
                ServicesGateway servicesGateway = new ServicesGateway(servicesAddRequestSelfAsignedChanges);

                foreach (ServicesAddRequestTDS.BasicInformationRow row in (ServicesAddRequestTDS.BasicInformationDataTable)servicesAddRequestSelfAsignedChanges.BasicInformation)
                {
                    DateTime? assignmentDeadlineDate = null; if (!row.IsAssignedDeadlineDateNull()) assignmentDeadlineDate = row.AssignedDeadlineDate;
                    DateTime? assignDateTime = null; if(row.IsAssignDateTimeNull()) row.AssignDateTime = DateTime.Now;
                    DateTime? acceptDatetime = null; if (!row.IsAcceptDatetimeNull()) acceptDatetime = row.AcceptDatetime;
                    DateTime? unitOutOfServiceDate = null; if (!row.IsUnitOutOfServiceDateNull()) unitOutOfServiceDate = row.UnitOutOfServiceDate;
                    string unitOutOfServiceTime = ""; if (!row.IsUnitOutOfServiceTimeNull()) unitOutOfServiceTime = row.UnitOutOfServiceTime;
                    DateTime? completeWorkDateTime = null; if (!row.IsCompleteWorkDateTimeNull()) completeWorkDateTime = row.CompleteWorkDateTime;
                    DateTime? unitBackInServiceDate = null; if (!row.IsUnitBackInServiceDateNull()) unitBackInServiceDate = row.UnitBackInServiceDate;
                    string unitBackInServiceTime = ""; if (!row.IsUnitBackInServiceTimeNull()) unitBackInServiceTime = row.UnitBackInServiceTime;
                    string completeWorkDetailDescription = ""; if (!row.IsCompleteWorkDetailDescriptionNull()) completeWorkDetailDescription = row.CompleteWorkDetailDescription;
                    bool completeWorkDetailPreventable = row.CompleteWorkDetailPreventable;
                    Decimal? completeWorkDetailTMLabourHours = null; if (!row.IsCompleteWorkDetailTMLabourHoursNull()) completeWorkDetailTMLabourHours = row.CompleteWorkDetailTMLabourHours;
                    Decimal? completeWorkDetailTMCost = null; if (!row.IsCompleteWorkDetailTMCostNull()) completeWorkDetailTMCost = row.CompleteWorkDetailTMCost;
                    string completeWorkDetaildTPVInvoiceNumber = ""; if (!row.IsCompleteWorkInvoiceNumberNull()) completeWorkDetaildTPVInvoiceNumber = row.CompleteWorkInvoiceNumber;
                    Decimal? completeWorkDetaildTPVInvoiceAmount = null; if (!row.IsCompleteWorkInvoiceAmountNull()) completeWorkDetaildTPVInvoiceAmount = row.CompleteWorkInvoiceAmount;
                    string mileage = ""; if (!row.IsMileageNull()) mileage = row.Mileage;
                    string startWorkMileage = ""; if (!row.IsStartWorkMileageNull()) startWorkMileage = row.StartWorkMileage;
                    string completeWorkMileage = ""; if (!row.IsCompleteWorkMileageNull()) completeWorkMileage = row.CompleteWorkMileage;
                    bool assignTeamMember = row.AssignTeamMember;
                    int? assignTeamMemberId = null; if (!row.IsAssignTeamMemberIdNull()) assignTeamMemberId = row.AssignTeamMemberId;
                    string assignThirdPartyVendor = ""; if (!row.IsAssignThirdPartyVendorNull()) assignThirdPartyVendor = row.AssignThirdPartyVendor;
                    DateTime? startWorkDateTime = null; if (!row.IsUnitOutOfServiceDateNull()) startWorkDateTime =  DateTime.Now;
                    int? ruleId = null; if (!row.IsRuleIDNull()) ruleId = row.RuleID;
                    string type = ""; if (ruleId.HasValue) type = "Checklist"; else type = "Normal";
                    int? libraryCategoriesId = 3736;//Fleet Maintence Invoices folder

                    Services services = new Services(null);
                    newServiceId = services.InsertDirect(dateTime_, row.MtoDot, row.ServiceDescription, row.UnitID, type, row.ServiceState, employeeId, assignDateTime, assignmentDeadlineDate, assignTeamMember, assignTeamMemberId, assignThirdPartyVendor, acceptDatetime, null, "", startWorkDateTime, unitOutOfServiceDate, unitOutOfServiceTime, completeWorkDateTime, unitBackInServiceDate, unitBackInServiceTime, completeWorkDetailDescription, completeWorkDetailPreventable, completeWorkDetailTMLabourHours, completeWorkDetailTMCost, completeWorkDetaildTPVInvoiceNumber, completeWorkDetaildTPVInvoiceAmount, "", ruleId, mileage, startWorkMileage, completeWorkMileage, row.Deleted, row.COMPANY_ID, libraryCategoriesId);

                    // modify checklist state
                    if (ruleId.HasValue)
                    {
                        string newChecklistState = "In Progress";

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

                            DateTime? newLastService = null; newLastService = DateTime.Now;
                            DateTime? newNextDue = null;
                            bool newDone = true;
                            newChecklistState = "Healthy";

                            if (newLastService.HasValue)
                            {
                                ChecklistGateway checklistGateway = new ChecklistGateway();
                                checklistGateway.LoadByUnitIdRuleId(row.UnitID, row.RuleID, companyId);

                                // ... Original values
                                DateTime? originalLastService = checklistGateway.GetLastService(row.UnitID, row.RuleID);
                                DateTime? originalNextDue = checklistGateway.GetNextDue(row.UnitID, row.RuleID);
                                bool originalDone = checklistGateway.GetDone(row.UnitID, row.RuleID);
                                string originalState = checklistGateway.GetState(row.UnitID, row.RuleID);

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

                                if (frecuency != "Only once")
                                {
                                    // Get next due
                                    DateTime timeToAdded = new DateTime(((DateTime)newLastService).Year, ((DateTime)newLastService).Month, ((DateTime)newLastService).Day);

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

                                    newDone = false;
                                }

                                Checklist checklist = new Checklist();
                                checklist.UpdateDirect(row.UnitID, row.RuleID, originalLastService, originalNextDue, originalDone, originalState, false, companyId, row.UnitID, row.RuleID, newLastService, newNextDue, newDone, newChecklistState, false, companyId);
                            }
                        }
                        else
                        {
                            Checklist checklist = new Checklist(null);
                            checklist.UpdateStateDirect(ruleId.Value, row.UnitID, companyId, newChecklistState);
                        }
                    }
                }
            }

            return newServiceId;
        }
        /// <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;
                            }
                        }
                    }
                }
            }
        }
        // ////////////////////////////////////////////////////////////////////////
        // 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["state"] == null) || ((string)Request.QueryString["source_page"] == null) || ((string)Request.QueryString["service_id"] == null) || ((string)Request.QueryString["active_tab"] == null))
                {
                    Response.Redirect("./../../error_page.aspx?error=" + "Invalid query string in services_state.aspx");
                }

                // Tag page
                TagPage();

                // If coming from services_summary.aspx
                if ((string)Request.QueryString["source_page"] == "services_summary.aspx")
                {
                    // Store Navigator State and Update control
                    StoreNavigatorState();
                    ViewState["update"] = Request.QueryString["update"];

                    // Get project record
                    int serviceId = Int32.Parse(hdfServiceId.Value);
                    int companyId = Int32.Parse(hdfCompanyId.Value);

                    serviceInformationTDS = (ServiceInformationTDS)Session["serviceInformationTDS"];
                    ServiceInformationBasicInformationGateway serviceInformationBasicInformationGateway = new ServiceInformationBasicInformationGateway(serviceInformationTDS);
                    serviceInformationBasicInformationGateway.LoadByServiceId(serviceId, companyId);

                    if (serviceInformationBasicInformationGateway.GetRuleId(serviceId).HasValue)
                    {
                        RuleGateway ruleGateway = new RuleGateway();
                        int? ruleId = serviceInformationBasicInformationGateway.GetRuleId(serviceId);
                        ruleGateway.LoadAllByRuleId(ruleId.Value, Int32.Parse(hdfCompanyId.Value));
                        int? serviceRequestDays = ruleGateway.GetServiceRequestDays(ruleId.Value);

                        if (serviceRequestDays.HasValue)
                        {
                            DateTime serviceRequestCreationDate = serviceInformationBasicInformationGateway.GetDateTime_(serviceId);
                            tkrdpPnlAssignDeadlineDate.SelectedDate = serviceRequestCreationDate.AddDays(Convert.ToDouble(serviceRequestDays.Value));
                        }
                    }

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

                // If coming from wucSRUnassigned.aspx
                if ((string)Request.QueryString["source_page"] == "wucSRUnassigned.ascx")
                {
                    // Store Navigator State and Update control
                    StoreNavigatorState();
                    ViewState["update"] = Request.QueryString["update"];

                    // Get project record
                    int serviceId = Int32.Parse(hdfServiceId.Value);
                    int companyId = Int32.Parse(hdfCompanyId.Value);

                    serviceInformationTDS = new ServiceInformationTDS();
                    ServiceInformationBasicInformationGateway serviceInformationBasicInformationGateway = new ServiceInformationBasicInformationGateway(serviceInformationTDS);
                    serviceInformationBasicInformationGateway.LoadByServiceId(serviceId, companyId);

                    if (serviceInformationBasicInformationGateway.GetRuleId(serviceId).HasValue)
                    {
                        RuleGateway ruleGateway = new RuleGateway();
                        int? ruleId = serviceInformationBasicInformationGateway.GetRuleId(serviceId);
                        ruleGateway.LoadAllByRuleId(ruleId.Value, Int32.Parse(hdfCompanyId.Value));
                        int? serviceRequestDays = ruleGateway.GetServiceRequestDays(ruleId.Value);

                        if (serviceRequestDays.HasValue)
                        {
                            DateTime serviceRequestCreationDate = serviceInformationBasicInformationGateway.GetDateTime_(serviceId);
                            tkrdpPnlAssignDeadlineDate.SelectedDate = serviceRequestCreationDate.AddDays(Convert.ToDouble(serviceRequestDays.Value));
                        }
                    }

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

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

                LoadMileage();
            }
            else
            {
                // Restore dataset
                serviceInformationTDS = (ServiceInformationTDS)Session["serviceInformationTDS"];
            }
        }
        /// <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;
                        }
                    }
                }
            }
        }