/// <summary>
        /// Reject
        /// </summary>
        /// <param name="employeeId">employeeId</param>
        /// <param name="payPeriodId">payPeriodId</param>
        public void Reject(int employeeId, int payPeriodId)
        {
            // Update timesheet's data
            TimesheetGateway timesheetGateway = new TimesheetGateway(Data);
            TimesheetTDS.LFS_TIMESHEETRow timesheetRow = (TimesheetTDS.LFS_TIMESHEETRow)timesheetGateway.GetRowByEmployeeIdPayPeriodId(employeeId, payPeriodId);
            timesheetRow.State = "Rejected";

            // Update timesheet's project time
            ProjectTimeGateway projectTimeGateway = new ProjectTimeGateway(Data);
            projectTimeGateway.LoadByEmployeeIdPayPeriodId(employeeId, payPeriodId);
            foreach (TimesheetTDS.LFS_PROJECT_TIMERow projectTimeRow in (TimesheetTDS.LFS_PROJECT_TIMEDataTable)projectTimeGateway.Table)
            {
                projectTimeRow.ProjectTimeState = "Rejected";
            }
        }
        // ////////////////////////////////////////////////////////////////////////
        // EVENTS
        //
        protected void Page_Load(object sender, EventArgs e)
        {
            // Register client scripts
            this.RegisterClientScripts();

            if (!IsPostBack)
            {
                // Validate query string
                if (((string)Request.QueryString["source_page"] == null) && ((string)Request.QueryString["others"] == null) && ((string)Request.QueryString["employee_id"] == null) && ((string)Request.QueryString["period_id"] == null) && ((string)Request.QueryString["projecttime_id"] == null))
                {
                    Response.Redirect("./../../error_page.aspx?error=" + "Invalid query string in timesheet_delete.aspx");
                }

                // Security check
                if (!Convert.ToBoolean(Session["sgLFS_LABOUR_HOURS_FULL_EDITING"]))
                {
                    if (Request.QueryString["others"] == "no")
                    {
                        if (!(Convert.ToBoolean(Session["sgLFS_LABOUR_HOURS_MY_TIMESHEETS_VIEW"]) && Convert.ToBoolean(Session["sgLFS_LABOUR_HOURS_MY_TIMESHEETS_DELETE"])))
                        {
                            if (!Convert.ToBoolean(Session["sgLFS_LABOUR_HOURS_MY_TIMESHEETS_MANAGEMENT"]))
                            {
                                if (!Convert.ToBoolean(Session["sgLFS_LABOUR_HOURS_MY_TIMESHEETS_MANAGEMENT_WED"]))
                                {
                                    Response.Redirect("./../../error_page.aspx?error=" + "You are not authorized to view this page. Contact your system administrator.");
                                }
                            }
                        }
                    }
                    else
                    {
                        if (!(Convert.ToBoolean(Session["sgLFS_LABOUR_HOURS_MY_TIMESHEETS_VIEW"]) && Convert.ToBoolean(Session["sgLFS_LABOUR_HOURS_MY_TIMESHEETS_DELETE"])))
                        {
                            if (!Convert.ToBoolean(Session["sgLFS_LABOUR_HOURS_MY_TIMESHEETS_MANAGEMENT"]))
                            {
                                if (!Convert.ToBoolean(Session["sgLFS_LABOUR_HOURS_MY_TIMESHEETS_MANAGEMENT_WED"]))
                                {
                                    if (!(Convert.ToBoolean(Session["sgLFS_LABOUR_HOURS_OTHERS_TIMESHEETS_VIEW"]) && Convert.ToBoolean(Session["sgLFS_LABOUR_HOURS_OTHERS_TIMESHEETS_DELETE"])))
                                    {
                                        if (!Convert.ToBoolean(Session["sgLFS_LABOUR_HOURS_OTHERS_TIMESHEETS_MANAGEMENT"]))
                                        {
                                            if (!Convert.ToBoolean(Session["sgLFS_LABOUR_HOURS_OTHERS_TIMESHEETS_MANAGEMENT_WED"]))
                                            {
                                                Response.Redirect("./../../error_page.aspx?error=" + "You are not authorized to view this page. Contact your system administrator.");
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                // Initialize viewstate variables
                ViewState["others"] = Request.QueryString["others"];
                ViewState["employee_id"] = int.Parse(Request.QueryString["employee_id"]);
                ViewState["period_id"] = int.Parse(Request.QueryString["period_id"]);
                ViewState["projecttime_id"] = int.Parse(Request.QueryString["projecttime_id"]);
                System.Configuration.AppSettingsReader appSettingReader = new System.Configuration.AppSettingsReader();
                ViewState["LHMode"] = appSettingReader.GetValue("LABOUR_HOURS_OPERATION_MODE", typeof(System.String)).ToString();

                // Get ProjectTime record
                projectTimeTDS = new ProjectTimeTDS();

                ProjectTimeGateway projectTimeGateway = new ProjectTimeGateway(projectTimeTDS);
                projectTimeGateway.LoadByProjectTimeId((int)ViewState["projecttime_id"]);

                // Project time state check
                if ((!Convert.ToBoolean(Session["sgLFS_LABOUR_HOURS_FULL_EDITING"])))
                {
                    if (projectTimeGateway.GetProjectTimeState((int)ViewState["projecttime_id"]) == "Approved")
                    {
                        Response.Redirect("./../../error_page.aspx?error=" + "You cannot delete an approved project time.");
                    }
                }

                if (!Convert.ToBoolean(Session["sgLFS_LABOUR_HOURS_FULL_EDITING"]))
                {
                    if (Convert.ToBoolean(Session["sgLFS_LABOUR_HOURS_MY_TIMESHEETS_MANAGEMENT"]) || Convert.ToBoolean(Session["sgLFS_LABOUR_HOURS_OTHERS_TIMESHEETS_MANAGEMENT"]))
                    {
                        bool isValidLimitPayPeriodToManagementEdit = LiquiForce.LFSLive.BL.LabourHours.ProjectTime.ProjectTime.ValidateLimitedPayPeriodToManagementEdit(projectTimeGateway.GetDate_((int)ViewState["projecttime_id"]), projectTimeGateway.GetProjectId((int)ViewState["projecttime_id"]));

                        if (!isValidLimitPayPeriodToManagementEdit)
                        {
                            Response.Redirect("./../../error_page.aspx?error=" + "You are not authorized to view this page. Contact your system administrator.");
                        }
                    }

                    if (Convert.ToBoolean(Session["sgLFS_LABOUR_HOURS_MY_TIMESHEETS_MANAGEMENT_WED"]) || Convert.ToBoolean(Session["sgLFS_LABOUR_HOURS_OTHERS_TIMESHEETS_MANAGEMENT_WED"]))
                    {
                        bool isValidLimitPayPeriodToManagementEdit = LiquiForce.LFSLive.BL.LabourHours.ProjectTime.ProjectTime.ValidateLimitedPayPeriodToWednesdayManagementEdit(projectTimeGateway.GetDate_((int)ViewState["projecttime_id"]), projectTimeGateway.GetProjectId((int)ViewState["projecttime_id"]));

                        if (!isValidLimitPayPeriodToManagementEdit)
                        {
                            Response.Redirect("./../../error_page.aspx?error=" + "You are not authorized to view this page. Contact your system administrator.");
                        }
                    }
                }

                // Prepare initial data for client
                StoreNavigatorState();

                // Store datasets
                Session["projectTimeTDS"] = projectTimeTDS;
            }
            else
            {
                // Restore datasets
                projectTimeTDS = (ProjectTimeTDS)Session["projectTimeTDS"];
            }
        }
        private void UpdateDatabase()
        {
            try
            {
                ProjectTimeGateway projectTimeGateway = new ProjectTimeGateway(projectTimeTDS);
                projectTimeGateway.Update();

                projectTimeTDS.AcceptChanges();

                Session["projectTimeTDS"] = projectTimeTDS;
            }
            catch (Exception ex)
            {
                string url = string.Format("./../../error_page.aspx?error={0}", ex.Message.Replace('\n', ' '));
                Response.Redirect(url);
            }
        }
        protected void cvAlreadyRegisteredMealsAllowanceEdit_ServerValidate(object source, ServerValidateEventArgs args)
        {
            args.IsValid = true;

            if (grdProjectTime.Rows.Count > 0)
            {
                foreach (GridViewRow row in grdProjectTime.Rows)
                {
                    if ((row.RowType == DataControlRowType.DataRow) && ((row.RowState == DataControlRowState.Edit) || (row.RowState == (DataControlRowState.Edit | DataControlRowState.Alternate))))
                    {
                        int companyId = Int32.Parse(hdfCompanyId.Value);
                        int employeeId = Int32.Parse(((DropDownList)row.FindControl("ddlEmployeesEdit")).SelectedValue);
                        DateTime date_ = tkrdpDate_.SelectedDate.Value;
                        bool isMealsAllowance = false;// ((CheckBox)row.FindControl("ckbxMealsAllowanceEdit")).Checked;
                        int projectTimeId2 = Int32.Parse(((Label)row.FindControl("lblDetailIdEdit")).Text);

                        string mealsCountry = hdfMealsCountry.Value;
                        int projectTimeId = -1;
                        args.IsValid = true;

                        TeamProjectTime2DetailTemp teamProjectTime2DetailTemp = new TeamProjectTime2DetailTemp(teamProjectTime2TDS);
                        bool validMealsAllowance1 = teamProjectTime2DetailTemp.ValidateMealsAllowanceEdit(employeeId, isMealsAllowance, projectTimeId2);
                        if (validMealsAllowance1)
                        {
                            if ((mealsCountry != "-1") && (isMealsAllowance))
                            {
                                ProjectTimeGateway projectTimeGateway = new ProjectTimeGateway();
                                if (projectTimeId == -1)
                                {
                                    if (projectTimeGateway.ExistsMealsAllowanceByEmployeIdDate(employeeId, date_, companyId))
                                    {
                                        args.IsValid = false;
                                    }
                                }
                                else
                                {
                                    if (projectTimeGateway.ExistsMealsAllowanceByProjectTimeIdEmployeIdDate(projectTimeId, employeeId, date_, companyId))
                                    {
                                        args.IsValid = false;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        // ////////////////////////////////////////////////////////////////////////
        // EVENTS
        //
        protected void Page_Load(object sender, EventArgs e)
        {
            // Register client scripts
            this.RegisterClientScripts();

            if (!IsPostBack)
            {
                // Validate query string
                if (((string)Request.QueryString["source_page"] == null) && ((string)Request.QueryString["others"] == null) && ((string)Request.QueryString["employee_id"] == null) && ((string)Request.QueryString["period_id"] == null) && ((string)Request.QueryString["projecttime_id"] == null))
                {
                    Response.Redirect("./../../error_page.aspx?error=" + "Invalid query string in timesheet_summary.aspx");
                }

                // Security check
                if (!Convert.ToBoolean(Session["sgLFS_LABOUR_HOURS_FULL_EDITING"]))
                {
                    if (Request.QueryString["others"] == "no")
                    {
                        if (!Convert.ToBoolean(Session["sgLFS_LABOUR_HOURS_MY_TIMESHEETS_VIEW"]))
                        {
                            if (!Convert.ToBoolean(Session["sgLFS_LABOUR_HOURS_MY_TIMESHEETS_MANAGEMENT"]))
                            {
                                if (!Convert.ToBoolean(Session["sgLFS_LABOUR_HOURS_MY_TIMESHEETS_MANAGEMENT_WED"]))
                                {
                                    Response.Redirect("./../../error_page.aspx?error=" + "You are not authorized to view this page. Contact your system administrator.");
                                }
                            }
                        }
                    }
                    else
                    {
                        if (!Convert.ToBoolean(Session["sgLFS_LABOUR_HOURS_MY_TIMESHEETS_VIEW"]))
                        {
                            if (!Convert.ToBoolean(Session["sgLFS_LABOUR_HOURS_MY_TIMESHEETS_MANAGEMENT"]))
                            {
                                if (!Convert.ToBoolean(Session["sgLFS_LABOUR_HOURS_MY_TIMESHEETS_MANAGEMENT_WED"]))
                                {
                                    if (!Convert.ToBoolean(Session["sgLFS_LABOUR_HOURS_OTHERS_TIMESHEETS_VIEW"]))
                                    {
                                        if (!Convert.ToBoolean(Session["sgLFS_LABOUR_HOURS_OTHERS_TIMESHEETS_MANAGEMENT"]))
                                        {
                                            if (!Convert.ToBoolean(Session["sgLFS_LABOUR_HOURS_OTHERS_TIMESHEETS_MANAGEMENT_WED"]))
                                            {
                                                Response.Redirect("./../../error_page.aspx?error=" + "You are not authorized to view this page. Contact your system administrator.");
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                // Initialize viewstate's variables
                ViewState["others"] = Request.QueryString["others"];
                ViewState["employee_id"] = int.Parse(Request.QueryString["employee_id"]);
                ViewState["period_id"] = int.Parse(Request.QueryString["period_id"]);
                ViewState["projecttime_id"] = int.Parse(Request.QueryString["projecttime_id"]);
                System.Configuration.AppSettingsReader appSettingReader = new System.Configuration.AppSettingsReader();
                ViewState["LHMode"] = appSettingReader.GetValue("LABOUR_HOURS_OPERATION_MODE", typeof(System.String)).ToString();

                // Get ProjectTime record
                projectTimeTDS =  new ProjectTimeTDS();

                ProjectTimeGateway projectTimeGateway = new ProjectTimeGateway(projectTimeTDS);
                projectTimeGateway.LoadByProjectTimeId((int)ViewState["projecttime_id"]);

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

                // Databind
                tbxDate.DataBind();
                tbxWorkingDetails.DataBind();
                tbxStartTime.DataBind();
                tbxEndTime.DataBind();
                tbxLunch.DataBind();
                tbxComments.DataBind();
                tbxState.DataBind();

                // Prepare initial data for client
                StoreNavigatorState();

                EmployeeGateway employeeGateway = new EmployeeGateway(new DataSet());
                employeeGateway.LoadByEmployeeId((int)ViewState["employee_id"]);
                tbxEmployee.Text = employeeGateway.GetFullName((int)ViewState["employee_id"]);

                int companyId = Int32.Parse(Session["companyID"].ToString());

                CompaniesGateway companiesGateway = new CompaniesGateway(new DataSet());
                companiesGateway.LoadAllByCompaniesId(projectTimeGateway.GetCompaniesId((int)ViewState["projecttime_id"]), companyId);
                tbxClient.Text = companiesGateway.GetName(projectTimeGateway.GetCompaniesId((int)ViewState["projecttime_id"]));

                ProjectGateway projectGateway = new ProjectGateway(new DataSet());
                projectGateway.LoadByProjectId(projectTimeGateway.GetProjectId((int)ViewState["projecttime_id"]));
                tbxProject.Text = projectGateway.GetName(projectTimeGateway.GetProjectId((int)ViewState["projecttime_id"])) + "(" + projectGateway.GetProjectNumber(projectTimeGateway.GetProjectId((int)ViewState["projecttime_id"])) + ")";

                if (projectGateway.GetFairWageApplies(projectTimeGateway.GetProjectId((int)ViewState["projecttime_id"])))
                {
                    tbxJobClassType.Visible = true;
                    lblJobClassType.Visible = true;
                    tbxJobClassType.Text = projectTimeGateway.GetJobClassType((int)ViewState["projecttime_id"]);
                }
                else
                {
                    tbxJobClassType.Visible = false;
                    lblJobClassType.Visible = false;
                }

                if (projectTimeGateway.GetMealsCountry((int)ViewState["projecttime_id"]).HasValue)
                {
                    CountryGateway countryGateway = new CountryGateway(new DataSet());
                    countryGateway.LoadByCountryId((Int64)projectTimeGateway.GetMealsCountry((int)ViewState["projecttime_id"]));
                    tbxMealsCountry.Text = countryGateway.GetName((Int64)projectTimeGateway.GetMealsCountry((int)ViewState["projecttime_id"]));
                }

                //if (projectTimeGateway.GetMealsAllowance((int)ViewState["projecttime_id"]) > 0)
                //{
                //    cbxMealsAllowance.Checked = true;
                //}

                //if (projectTimeGateway.GetFairWage((int)ViewState["projecttime_id"]))
                //{
                //    cbxFairWage.Checked = true;
                //}

                if (projectTimeGateway.GetUnitId((int)ViewState["projecttime_id"]).HasValue)
                {
                    UnitsGateway unitGateway = new UnitsGateway(new DataSet());
                    unitGateway.LoadByUnitId((int)projectTimeGateway.GetUnitId((int)ViewState["projecttime_id"]), Convert.ToInt32(Session["companyID"]));
                    tbxUnit.Text = unitGateway.GetUnitCode((int)projectTimeGateway.GetUnitId((int)ViewState["projecttime_id"]));
                }

                if (projectTimeGateway.GetTowedUnitId((int)ViewState["projecttime_id"]).HasValue)
                {
                    UnitsGateway unitGateway = new UnitsGateway(new DataSet());
                    unitGateway.LoadByUnitId((int)projectTimeGateway.GetTowedUnitId((int)ViewState["projecttime_id"]), Convert.ToInt32(Session["companyID"]));
                    tbxTowed.Text = unitGateway.GetUnitCode((int)projectTimeGateway.GetTowedUnitId((int)ViewState["projecttime_id"]));
                }

                tbxTypeOfWork.Text = "";
                if (projectTimeGateway.GetWork((int)ViewState["projecttime_id"]) != "")
                {
                    tbxTypeOfWork.Text = projectTimeGateway.GetWork((int)ViewState["projecttime_id"]);
                }

                tbxFunction.Text = "";
                if (projectTimeGateway.GetFunction((int)ViewState["projecttime_id"]) != "")
                {
                    tbxFunction.Text = projectTimeGateway.GetFunction((int)ViewState["projecttime_id"]);
                }
            }
            else
            {
                // Restore datasets
                projectTimeTDS = (ProjectTimeTDS)Session["projectTimeTDS"];
            }
        }
        protected void cvAlreadyRegisteredMealsAllowanceFooter_ServerValidate(object source, ServerValidateEventArgs args)
        {
            int companyId = Int32.Parse(hdfCompanyId.Value);
            int employeeId = Int32.Parse(hdfEmployeeID.Value);
            DateTime startDate = tkrdpStartDate.SelectedDate.Value;
            DateTime lastDate = tkrdpEndDate.SelectedDate.Value;
            bool isMealsAllowance = false;// ((CheckBox)grdProjectTime.FooterRow.FindControl("ckbxMealsAllowanceFooter")).Checked;
            string mealsCountry = ddlMealsCountry.SelectedValue;
            int projectTimeId = -1;
            args.IsValid = true;

            int projectId = int.Parse(ddlProject.SelectedValue);

            if (projectId == 35 || projectId == 39 || projectId == 716)
            {
                if (isMealsAllowance)
                {
                    args.IsValid = false;
                }
            }
            else
            {
                ProjectTimeTemp projectTimeTemp = new ProjectTimeTemp(projectTimeTDS);
                bool validMealsAllowance1 = projectTimeTemp.ValidateMealsAllowance(employeeId, isMealsAllowance);
                if (validMealsAllowance1)
                {
                    if ((mealsCountry != "-1") && (isMealsAllowance))
                    {
                        ProjectTimeGateway projectTimeGateway = new ProjectTimeGateway();
                        if (projectTimeId == -1)
                        {
                            if (projectTimeGateway.ExistsMealsAllowanceByEmployeIdDate(employeeId, startDate, companyId))
                            {
                                args.IsValid = false;
                            }
                        }
                        else
                        {
                            if (projectTimeGateway.ExistsMealsAllowanceByProjectTimeIdEmployeIdDate(projectTimeId, employeeId, startDate, companyId))
                            {
                                args.IsValid = false;
                            }
                        }
                    }
                }
            }
        }
        protected void cvAlreadyRegisteredMealsAllowanceEdit_ServerValidate(object source, ServerValidateEventArgs args)
        {
            args.IsValid = true;

            if (grdProjectTime.Rows.Count > 0)
            {
                foreach (GridViewRow row in grdProjectTime.Rows)
                {
                    if ((row.RowType == DataControlRowType.DataRow) && ((row.RowState == DataControlRowState.Edit) || (row.RowState == (DataControlRowState.Edit | DataControlRowState.Alternate))))
                    {
                        int companyId = Int32.Parse(hdfCompanyId.Value);
                        int employeeId = Int32.Parse(hdfEmployeeID.Value);
                        DateTime startDate = tkrdpStartDate.SelectedDate.Value;
                        DateTime lastDate = tkrdpEndDate.SelectedDate.Value;
                        bool isMealsAllowance = false;// ((CheckBox)row.FindControl("ckbxMealsAllowanceEdit")).Checked;
                        int projectTimeId2 = Int32.Parse(((Label)row.FindControl("lblProjectTimeIdEdit")).Text);
                        int projectId = int.Parse(ddlProject.SelectedValue);

                        if (projectId == 35 || projectId == 39 || projectId == 716)
                        {
                            if (isMealsAllowance)
                            {
                                args.IsValid = false;
                            }
                        }
                        else
                        {
                            string mealsCountry = ddlMealsCountry.SelectedValue;
                            int projectTimeId = -1;
                            args.IsValid = true;

                            ProjectTimeTemp projectTimeTemp = new ProjectTimeTemp(projectTimeTDS);
                            bool validMealsAllowance1 = projectTimeTemp.ValidateMealsAllowanceEdit(employeeId, isMealsAllowance, projectTimeId2);
                            if (validMealsAllowance1)
                            {
                                if ((mealsCountry != "-1") && (isMealsAllowance))
                                {
                                    ProjectTimeGateway projectTimeGateway = new ProjectTimeGateway();
                                    if (projectTimeId == -1)
                                    {
                                        if (projectTimeGateway.ExistsMealsAllowanceByEmployeIdDate(employeeId, startDate, companyId))
                                        {
                                            args.IsValid = false;
                                        }
                                    }
                                    else
                                    {
                                        if (projectTimeGateway.ExistsMealsAllowanceByProjectTimeIdEmployeIdDate(projectTimeId, employeeId, startDate, companyId))
                                        {
                                            args.IsValid = false;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        /// <summary>
        /// Update TeamProjectTime, TeamProjectTimeDetail and ProjectTimes
        /// </summary>
        /// <param name="projectTime2TDS">ProjectTime2TDS</param>
        public void Update(ProjectTimeTDS projectTime2TDS)
        {
            TeamProjectTime2DetailGateway teamProjectTime2DetailGateway = new TeamProjectTime2DetailGateway(Data);
            ProjectTimeGateway projectTime2Gateway = new ProjectTimeGateway(projectTime2TDS);
            ProjectTimeSectionGateway projectTime2SectionGateway = new ProjectTimeSectionGateway(projectTime2TDS);

            DataTable teamProjectTime2Changes = Table.GetChanges();
            DataTable teamProjectTime2DetailChanges = teamProjectTime2DetailGateway.Table.GetChanges();
            DataTable projectTime2Changes = projectTime2Gateway.Table.GetChanges();
            DataTable projectTime2SectionChanges = projectTime2SectionGateway.Table.GetChanges();

            if ((teamProjectTime2Changes == null) && (teamProjectTime2DetailChanges == null) && (projectTime2Changes == null)) return;

            try
            {
                DB.Open();
                DB.BeginTransaction();

                Adapter.InsertCommand.Transaction = DB.Transaction;
                Adapter.UpdateCommand.Transaction = DB.Transaction;
                Adapter.DeleteCommand.Transaction = DB.Transaction;

                teamProjectTime2DetailGateway.Adapter.InsertCommand.Transaction = DB.Transaction;
                teamProjectTime2DetailGateway.Adapter.UpdateCommand.Transaction = DB.Transaction;
                teamProjectTime2DetailGateway.Adapter.DeleteCommand.Transaction = DB.Transaction;

                projectTime2Gateway.Adapter.InsertCommand.Transaction = DB.Transaction;
                projectTime2Gateway.Adapter.UpdateCommand.Transaction = DB.Transaction;
                projectTime2Gateway.Adapter.DeleteCommand.Transaction = DB.Transaction;

                projectTime2SectionGateway.Adapter.InsertCommand.Transaction = DB.Transaction;
                projectTime2SectionGateway.Adapter.UpdateCommand.Transaction = DB.Transaction;
                projectTime2SectionGateway.Adapter.DeleteCommand.Transaction = DB.Transaction;

                if ((teamProjectTime2Changes != null) && (teamProjectTime2Changes.Rows.Count > 0))
                {
                    int lastTeamProjectTimeId = DB.GetIdentCurrent("LFS_TEAM_PROJECT_TIME", DB.Transaction);
                    Adapter.Update(teamProjectTime2Changes);
                    int newTeamProjectTimeId = DB.GetIdentCurrent("LFS_TEAM_PROJECT_TIME", DB.Transaction);
                    if (lastTeamProjectTimeId != newTeamProjectTimeId)
                    {
                        TeamProjectTime2TDS.LFS_TEAM_PROJECT_TIMERow row = ((TeamProjectTime2TDS.LFS_TEAM_PROJECT_TIMEDataTable)Table).FindByTeamProjectTimeID(0);
                        row.TeamProjectTimeID = newTeamProjectTimeId;
                        teamProjectTime2DetailChanges = teamProjectTime2DetailGateway.Table.GetChanges();
                    }
                }

                if ((teamProjectTime2DetailChanges != null) && (teamProjectTime2DetailChanges.Rows.Count > 0))
                {
                    teamProjectTime2DetailGateway.Adapter.Update(teamProjectTime2DetailChanges);
                }

                if ((projectTime2Changes != null) && (projectTime2Changes.Rows.Count > 0))
                {
                    projectTime2Gateway.Adapter.Update(projectTime2Changes);
                }

                if ((projectTime2SectionChanges != null) && (projectTime2SectionChanges.Rows.Count > 0))
                {
                    projectTime2SectionGateway.Adapter.Update(projectTime2SectionChanges);
                }

                DB.CommitTransaction();
            }
            catch (DBConcurrencyException dBConcurrencyException)
            {
                DB.RollbackTransaction();
                throw new Exception("Concurrency error: Another user already updated the data you are working on.  Your operation has been cancelled.", dBConcurrencyException);
            }
            catch (SqlException sqlException)
            {
                DB.RollbackTransaction();
                byte severityLevel = sqlException.Class;
                if (severityLevel <= 16)
                {
                    throw new Exception("Low severity error. Your operation has been cancelled.  SQL Error " + severityLevel + ".");
                }
                if ((severityLevel >= 17) && (severityLevel <= 19))
                {
                    throw new Exception("Mid severity error. Your operation has been cancelled.  SQL Error " + severityLevel + ".");
                }
                if (severityLevel >= 20)
                {
                    throw new Exception("High severity error. Your operation has been cancelled.  SQL Error " + severityLevel + ".");
                }
            }
            catch (Exception e)
            {
                DB.RollbackTransaction();
                throw new Exception("Unknow error. Your operation has been cancelled.", e);
            }
            finally
            {
                DB.Close();
            }
        }
        // ////////////////////////////////////////////////////////////////////////
        // EVENTS
        //
        protected void Page_Load(object sender, EventArgs e)
        {
            // Register client scripts
            this.RegisterClientScripts();

            if (!IsPostBack)
            {
                // Validate query string
                if (((string)Request.QueryString["source_page"] == null) && ((string)Request.QueryString["others"] == null))
                {
                    Response.Redirect("./../../error_page.aspx?error=" + "Invalid query string in timesheet_state.aspx");
                }

                // Security check
                EmployeeGateway employeeGateway1 = new EmployeeGateway(new DataSet());
                int employeeId = employeeGateway1.GetEmployeIdByLoginId(Convert.ToInt32(Session["loginID"]));
                employeeGateway1.LoadByEmployeeId(employeeId);

                if (!employeeGateway1.GetApproveTimesheets(employeeId))
                {
                    Response.Redirect("./../../error_page.aspx?error=" + "You are not authorized to view this page. Contact your system administrator.");
                }
                else
                {
                    if (!ValidateWedManagement())
                    {
                        Response.Redirect("./../../error_page.aspx?error=" + "You are not authorized to view this page. Contact your system administrator.");
                    }
                }

                // Initialize viewstate variables
                System.Configuration.AppSettingsReader appSettingReader = new System.Configuration.AppSettingsReader();
                ViewState["LHMode"] = appSettingReader.GetValue("LABOUR_HOURS_OPERATION_MODE", typeof(System.String)).ToString();
                ViewState["others"] = Request.QueryString["others"];
                ViewState["employee_id"] = int.Parse(Request.QueryString["employee_id"]);
                ViewState["period_id"] = int.Parse(Request.QueryString["period_id"]);
                ViewState["source_page"] = Request.QueryString["source_page"];
                if ((string)ViewState["source_page"] == "timesheet_summary.aspx")
                {
                    ViewState["projecttime_id"] = int.Parse(Request.QueryString["projecttime_id"]);
                }

                // Labour Hours Mode check
                if ((string)ViewState["LHMode"] == "Partial")
                {
                    Response.Redirect("./../../error_page.aspx?error=" + "The system is on partial mode. Contact your system administrator.");
                }

                // Timesheet state check
                projectTimeTDSForState = new ProjectTimeTDS();
                ProjectTimeGateway projectTimeGateway = new ProjectTimeGateway(projectTimeTDSForState);
                projectTimeGateway.ClearBeforeFill = false;

                if ((string)ViewState["source_page"] == "timesheet_approve.aspx")
                {
                    List<int> projectTimesIdSelected = ((List<int>)Session["projectTimesIdSelected"]);
                    foreach (int projectTimeId in projectTimesIdSelected)
                    {
                        projectTimeGateway.LoadByProjectTimeId(projectTimeId);
                    }
                }
                else
                {
                    if ((string)ViewState["source_page"] == "timesheet_summary.aspx")
                    {
                        int projecttime_id = Int32.Parse(ViewState["projecttime_id"].ToString());
                        projectTimeGateway.LoadByProjectTimeId(projecttime_id);
                    }
                }

                projectTimeGateway.ClearBeforeFill = true;

                // Store datasets
                Session["projectTimeTDSForState"] = projectTimeTDSForState;
            }
            else
            {
                // Restore datasets
                projectTimeTDSForState = (ProjectTimeTDS)Session["projectTimeTDSForState"];
            }
        }
        /// <summary>
        /// GetNewProjectTimeId
        /// </summary>
        /// <returns>int</returns>
        public int GetNewProjectTimeId()
        {
            int newProjectTimeId = 0;

            if (Data.Tables["LFS_PROJECT_TIME"].Rows.Count == 0)
            {
                ProjectTimeGateway projectTimeGateway = new ProjectTimeGateway();
                newProjectTimeId = projectTimeGateway.GetLastProjectTimeId();
            }

            foreach (ProjectTimeTDS.LFS_PROJECT_TIMERow row in ((ProjectTimeTDS)Data).LFS_PROJECT_TIME)
            {
                if (newProjectTimeId < row.ProjectTimeID)
                {
                    newProjectTimeId = row.ProjectTimeID;
                }
            }

            newProjectTimeId++;

            return newProjectTimeId;
        }
        /// <summary>
        /// FillData2
        /// </summary>
        private void FillData2()
        {
            PrintHoursForPayrollPeriodOriginalGateway originalGateway = new PrintHoursForPayrollPeriodOriginalGateway(Data);

            foreach (PrintHoursForPayrollPeriodTDS.OriginalRow originalRow in (PrintHoursForPayrollPeriodTDS.OriginalDataTable)originalGateway.Table)
            {
                PrintHoursForPayrollPeriodTDS.PrintHoursForPayrollPeriodRow newRow = ((PrintHoursForPayrollPeriodTDS.PrintHoursForPayrollPeriodDataTable)Table).NewPrintHoursForPayrollPeriodRow();

                newRow.EmployeeID = originalRow.EmployeeID;
                newRow.EmployeeName = originalRow.EmployeeName;
                newRow.CountryID = originalRow.CountryID;
                newRow.CountryName = originalRow.CountryName;
                newRow.Date_ = originalRow.Date_;
                newRow.ProjectName = originalRow.ProjectName;
                if (!originalRow.IsWork_Null()) newRow.Work_ = originalRow.Work_; else newRow.SetWork_Null();
                if (!originalRow.IsFunction_Null()) newRow.Function_ = originalRow.Function_; else newRow.SetFunction_Null();
                if (!originalRow.IsStartTimeNull()) newRow.StartTime = originalRow.StartTime; else newRow.SetStartTimeNull();
                if (!originalRow.IsEndTimeNull()) newRow.EndTime = originalRow.EndTime; else newRow.SetEndTimeNull();
                if (!originalRow.IsOffsetNull()) newRow.Offset = originalRow.Offset; else newRow.SetOffsetNull();
                newRow.FairWage = false;
                originalRow.FairWage = false;

                if (!originalRow.IsJobClassTypeNull()) newRow.JobClassType = originalRow.JobClassType; else newRow.JobClassType = " ";

                if (originalRow.CountryID == 1)
                {
                    newRow.TimeCA = originalRow.ProjectTime;
                    newRow.TimeUS = originalRow.ProjectTime;
                }
                else
                {
                    newRow.TimeCA = originalRow.ProjectTime;
                    newRow.TimeUS = originalRow.ProjectTime;
                }

                newRow.TimeFairWage = 0;
                newRow.TimeFairWageOt = 0;
                newRow.TimeMob = 0;
                newRow.TimeMobOt = 0;
                newRow.TimeStandard = 0;
                newRow.TimeStandardOt = 0;

                if (!originalRow.IsStartTimeNull() && !originalRow.IsEndTimeNull())
                {
                    if (originalRow.IsWork_Null()) originalRow.Work_ = "";
                    if (originalRow.IsFunction_Null()) originalRow.Function_ = "";
                    ProjectGateway projectGateway = new ProjectGateway(null);
                    ProjectTimeGateway projectTimeGateway = new ProjectTimeGateway();
                    projectTimeGateway.LoadByProjectTimeId(originalRow.ProjectTimeID);
                    if (projectGateway.IsFairWageProjectWorkFunction(projectTimeGateway.GetProjectId(originalRow.ProjectTimeID), originalRow.Work_, originalRow.Function_))
                    {
                        newRow.FairWage = true;
                        originalRow.FairWage = true;
                    }

                    int overtime = 40; //Default for USA

                    // Canada
                    if (originalRow.CountryID == 1)
                    {
                        switch (originalRow.Category)
                        {
                            case "Special Forces":
                                overtime = 50;
                                break;

                            case "Field":
                                overtime = 50;
                                break;

                            case "Field 44":
                                overtime = 44;
                                break;

                            case "Office/Admin":
                                overtime = 44;
                                break;

                            case "Mechanic/Manufactoring":
                                overtime = 44;
                                break;
                        }

                        if ((originalRow.Work_ == "Mobilization") && (originalRow.Function_ == "Prevail/Min Wage"))
                        {
                            double acumPeriod = GetTotalHoursByEmployeeIdPeriodId(originalRow.EmployeeID, originalRow.Date_, originalRow.ProjectTimeID);

                            if (acumPeriod > overtime)
                            {
                                newRow.TimeMob = 0;
                                newRow.TimeMobOt = originalRow.ProjectTime;
                            }
                            else
                            {
                                double newAcumPeriod = acumPeriod + originalRow.ProjectTime;

                                if (newAcumPeriod > overtime)
                                {
                                    newRow.TimeMobOt = newAcumPeriod - overtime;
                                    newRow.TimeMob = originalRow.ProjectTime - newRow.TimeMobOt;
                                }
                                else
                                {
                                    newRow.TimeMob = originalRow.ProjectTime;
                                    newRow.TimeMobOt = 0;
                                }
                            }
                        }
                        else
                        {
                            if ((originalRow.FairWage) && (originalRow.Work_ != "Mobilization"))
                            {
                                double acumPeriod = GetTotalHoursByEmployeeIdPeriodId(originalRow.EmployeeID, originalRow.Date_, originalRow.ProjectTimeID);

                                if (acumPeriod > overtime)
                                {
                                    newRow.TimeFairWage = 0;
                                    newRow.TimeFairWageOt = originalRow.ProjectTime;
                                }
                                else
                                {
                                    double newAcumPeriod = acumPeriod + originalRow.ProjectTime;

                                    if (newAcumPeriod > overtime)
                                    {
                                        newRow.TimeFairWageOt = newAcumPeriod - overtime;
                                        newRow.TimeFairWage = originalRow.ProjectTime - newRow.TimeFairWageOt;
                                    }
                                    else
                                    {
                                        newRow.TimeFairWage = originalRow.ProjectTime;
                                        newRow.TimeFairWageOt = 0;
                                    }
                                }
                            }
                            else
                            {
                                double acumPeriod = GetTotalHoursByEmployeeIdPeriodId(originalRow.EmployeeID, originalRow.Date_, originalRow.ProjectTimeID);

                                if (acumPeriod > overtime)
                                {
                                    newRow.TimeStandard = 0;
                                    newRow.TimeStandardOt = originalRow.ProjectTime;
                                }
                                else
                                {
                                    double newAcumPeriod = acumPeriod + originalRow.ProjectTime;

                                    if (newAcumPeriod > overtime)
                                    {
                                        newRow.TimeStandardOt = newAcumPeriod - overtime;
                                        newRow.TimeStandard = originalRow.ProjectTime - newRow.TimeStandardOt;
                                    }
                                    else
                                    {
                                        newRow.TimeStandard = originalRow.ProjectTime;
                                        newRow.TimeStandardOt = 0;
                                    }
                                }
                            }
                        }
                    }
                    else //USA
                    {
                        if ((originalRow.FairWage) && (originalRow.Work_ != "Mobilization"))
                        {
                            double acumPeriod = GetTotalHoursByEmployeeIdPeriodId(originalRow.EmployeeID, originalRow.Date_, originalRow.ProjectTimeID);

                            if (acumPeriod > overtime)
                            {
                                newRow.TimeFairWage = 0;
                                newRow.TimeFairWageOt = originalRow.ProjectTime;
                            }
                            else
                            {
                                double newAcumPeriod = acumPeriod + originalRow.ProjectTime;

                                if (newAcumPeriod > overtime)
                                {
                                    newRow.TimeFairWageOt = newAcumPeriod - overtime;
                                    newRow.TimeFairWage = originalRow.ProjectTime - newRow.TimeFairWageOt;
                                }
                                else
                                {
                                    newRow.TimeFairWage = originalRow.ProjectTime;
                                    newRow.TimeFairWageOt = 0;
                                }
                            }
                        }
                        else
                        {
                            double acumPeriod = GetTotalHoursByEmployeeIdPeriodId(originalRow.EmployeeID, originalRow.Date_, originalRow.ProjectTimeID);

                            if (acumPeriod > overtime)
                            {
                                newRow.TimeStandard = 0;
                                newRow.TimeStandardOt = originalRow.ProjectTime;
                            }
                            else
                            {
                                double newAcumPeriod = acumPeriod + originalRow.ProjectTime;

                                if (newAcumPeriod > overtime)
                                {
                                    newRow.TimeStandardOt = newAcumPeriod - overtime;
                                    newRow.TimeStandard = originalRow.ProjectTime - newRow.TimeStandardOt;
                                }
                                else
                                {
                                    newRow.TimeStandard = originalRow.ProjectTime;
                                    newRow.TimeStandardOt = 0;
                                }
                            }
                        }
                    }
                }

                if ((originalRow.WorkingDetails == "Sick Day") || (originalRow.WorkingDetails == "Holiday") || (originalRow.WorkingDetails == "Vacation / Other") || (originalRow.WorkingDetails == "Day Off - No Pay"))
                {
                    newRow.WorkingDetails = originalRow.WorkingDetails;
                }
                else
                {
                    newRow.WorkingDetails = "";
                }

                newRow.ClientName = originalRow.ClientName;
                newRow.Location = originalRow.Location;

                if (!originalRow.IsMealsCountryNull())
                {
                    if (originalRow.MealsCountry == 1)
                    {
                        newRow.MealsCA = true;
                        newRow.MealsUS = false;
                    }
                    else
                    {
                        newRow.MealsCA = false;
                        newRow.MealsUS = true;
                    }
                }
                else
                {
                    newRow.MealsCA = false;
                    newRow.MealsUS = false;
                }

                if (!originalRow.IsMealsCountryNull())
                {
                    if (originalRow.MealsCountry == 1)
                    {
                        newRow.TotalCA = originalRow.MealsAllowance;
                        newRow.TotalUS = 0;
                    }
                    else
                    {
                        newRow.TotalCA = 0;
                        newRow.TotalUS = originalRow.MealsAllowance;
                    }
                }
                else
                {
                    newRow.TotalCA = 0;
                    newRow.TotalUS = 0;
                }

                if (!originalRow.IsProjectTimeStateNull())
                {
                    if (originalRow.ProjectTimeState == "Approved")
                    {
                        newRow.IsApproved = true;
                    }
                    else
                    {
                        newRow.IsApproved = false;
                    }
                }
                else
                {
                    newRow.IsApproved = false;
                }

                if (!originalRow.IsApprovedByNull())
                {
                    newRow.ApprovedBy = originalRow.ApprovedBy;
                }
                else
                {
                    newRow.ApprovedBy = "";
                }

                if (!originalRow.IsProjectTimeStateNull())
                {
                    string projectTimeState = originalRow.ProjectTimeState;

                    if (projectTimeState == "Approved")
                    {
                        newRow.ProjectTimeState = originalRow.ApprovedBy;
                    }
                    else
                    {
                        newRow.ProjectTimeState = "--";
                    }
                }
                else
                {
                    newRow.ProjectTimeState = "--";
                }

                if (!originalRow.IsJobClassProjectTimeNull())
                {
                    string jobClassProjectTime = originalRow.JobClassProjectTime;

                    switch (jobClassProjectTime)
                    {
                        case "Laborer Group 2":
                            originalRow.JobClassProjectTime = "Lab 2";
                            break;

                        case "Laborer Group 6":
                            originalRow.JobClassProjectTime = "Lab 6";
                            break;

                        case "Operator Group 1":
                            originalRow.JobClassProjectTime = "Op 1";
                            break;

                        case "Operator Group 2":
                            originalRow.JobClassProjectTime = "Op 2";
                            break;

                        case "Regular Rate":
                            originalRow.JobClassProjectTime = "Reg Rate";
                            break;
                    }
                }

                // Show or not Job Class Project Time
                if (!originalRow.IsWork_Null())
                {
                    if (originalRow.Work_ != "Mobilization")
                    {
                        if (!originalRow.IsJobClassProjectTimeNull())
                        {
                            newRow.JobClassProjectTime = originalRow.JobClassProjectTime;
                        }
                        else
                        {
                            newRow.JobClassProjectTime = "";
                        }
                    }
                    else
                    {
                        newRow.JobClassProjectTime = "";
                    }
                }
                else
                {
                    if (!originalRow.IsJobClassProjectTimeNull())
                    {
                        newRow.JobClassProjectTime = originalRow.JobClassProjectTime;
                    }
                    else
                    {
                        newRow.JobClassProjectTime = "";
                    }
                }

                if (!originalRow.IsCommentsNull()) newRow.Comments = originalRow.Comments; else newRow.SetCommentsNull();

                ((PrintHoursForPayrollPeriodTDS.PrintHoursForPayrollPeriodDataTable)Table).AddPrintHoursForPayrollPeriodRow(newRow);
            }
        }
 /// <summary>
 /// ValidateMealsAllowance
 /// </summary>
 /// <param name="projectTimeId">projectTimeId</param>
 /// <param name="employeeId">employeeId</param>
 /// <param name="date_">date_</param>
 /// <param name="mealsCountry">mealsCountry</param>
 /// <param name="mealsAllowance">mealsAllowance</param>
 /// <param name="companyId">companyId</param>
 /// <returns></returns>
 public static bool ValidateMealsAllowance(int projectTimeId, int employeeId, DateTime date_, string mealsCountry, bool mealsAllowance, int companyId)
 {
     if ((mealsCountry != "-1") && (mealsAllowance))
     {
         ProjectTimeGateway projectTimeGateway = new ProjectTimeGateway();
         if (projectTimeId == -1)
         {
             if (projectTimeGateway.ExistsMealsAllowanceByEmployeIdDate(employeeId, date_, companyId))
             {
                 return false;
             }
             else
             {
                 return true;
             }
         }
         else
         {
             if (projectTimeGateway.ExistsMealsAllowanceByProjectTimeIdEmployeIdDate(projectTimeId,employeeId, date_, companyId))
             {
                 return false;
             }
             else
             {
                 return true;
             }
         }
     }
     return true;
 }
        private bool StepEndFinish()
        {
            lblError.Visible = false;
            lblError2.Visible = false;
            int companyId = Int32.Parse(hdfCompanyId.Value);

            if (ValidateStepEnd())
            {
                if (cbxEndConfirm.Checked)
                {
                    // Review all times
                    if (rbtnBeginTemplate.Checked)
                    {
                        if (grdProjectTime.Rows.Count > 0)
                        {
                            foreach (GridViewRow row in grdProjectTime.Rows)
                            {
                                if ((row.RowType == DataControlRowType.DataRow) && ((row.RowState == DataControlRowState.Normal) || (row.RowState == (DataControlRowState.Normal | DataControlRowState.Alternate))))
                                {
                                    ProjectTimeGateway projectTimeGatewayForVerify = new ProjectTimeGateway();
                                    int employeeId = 0; if (((HiddenField)row.FindControl("hdfEmployeeId")).Value.Trim() != "") employeeId = Int32.Parse(((HiddenField)row.FindControl("hdfEmployeeId")).Value.Trim());

                                    DateTime date_ = DateTime.Parse(tbxDate.Text);
                                    string startTime = ""; if (((TextBox)row.FindControl("tbxStartTime")).Text.Trim() != "") startTime = ((TextBox)row.FindControl("tbxStartTime")).Text.Trim();

                                    string endTime = ""; if (((TextBox)row.FindControl("tbxEndTime")).Text.Trim() != "") endTime = ((TextBox)row.FindControl("tbxEndTime")).Text.Trim();

                                    // Verify if the time not exists at DB
                                    if (projectTimeGatewayForVerify.NotExistsByEmployeIdDate_StartTimeEndTime(employeeId, date_, startTime, endTime, companyId))
                                    {
                                        // Verify Job Class
                                        EmployeeGateway employee = new EmployeeGateway();
                                        employee.LoadByEmployeeId(employeeId);
                                        string jobClass = employee.GetJobClassType(employeeId);

                                        if (jobClass == "")
                                        {
                                            lblError2.Visible = true;
                                            lblError2.Text = lblError2.Text + ((TextBox)row.FindControl("tbxTeamMember")).Text.Trim() + ", ";
                                        }
                                    }
                                    else
                                    {
                                        lblError.Visible = true;
                                        lblError.Text = lblError.Text + ((TextBox)row.FindControl("tbxTeamMember")).Text.Trim() + ", ";
                                    }
                                }
                            }
                        }
                    }
                }

                if ((lblError.Visible)||(lblError2.Visible))
                {
                    return false;
                }
                else
                {
                    if (PostStepEndChanges(companyId))
                    {
                        UpdateDatabase();
                        return true;
                    }
                    else
                    {
                       return false;
                    }
                }
            }
            else
            {
                return false;
            }
        }
        protected void cvAlreadyRegisteredMealsAllowanceFooter_ServerValidate(object source, ServerValidateEventArgs args)
        {
            int companyId = Int32.Parse(hdfCompanyId.Value);
            int employeeId = Int32.Parse(((DropDownList)grdProjectTime.FooterRow.FindControl("ddlEmployeesFooter")).SelectedValue);
            DateTime date_ = tkrdpDate_.SelectedDate.Value;
            bool isMealsAllowance = false;// ((CheckBox)grdProjectTime.FooterRow.FindControl("ckbxMealsAllowanceFooter")).Checked;
            string mealsCountry = hdfMealsCountry.Value;
            int projectTimeId = -1;
            args.IsValid = true;

            TeamProjectTime2DetailTemp teamProjectTime2DetailTemp = new TeamProjectTime2DetailTemp(teamProjectTime2TDS);
            bool validMealsAllowance1 = teamProjectTime2DetailTemp.ValidateMealsAllowance(employeeId, isMealsAllowance);
            if (validMealsAllowance1)
            {
                if ((mealsCountry != "-1") && (isMealsAllowance))
                {
                    ProjectTimeGateway projectTimeGateway = new ProjectTimeGateway();
                    if (projectTimeId == -1)
                    {
                        if (projectTimeGateway.ExistsMealsAllowanceByEmployeIdDate(employeeId, date_, companyId))
                        {
                            args.IsValid = false;
                        }
                    }
                    else
                    {
                        if (projectTimeGateway.ExistsMealsAllowanceByProjectTimeIdEmployeIdDate(projectTimeId, employeeId, date_, companyId))
                        {
                            args.IsValid = false;
                        }
                    }
                }
            }
        }
        protected void cvValidTimesEdit_ServerValidate(object source, ServerValidateEventArgs args)
        {
            args.IsValid = false;

            if (grdProjectTime.Rows.Count > 0)
            {
                foreach (GridViewRow row in grdProjectTime.Rows)
                {
                    if ((row.RowType == DataControlRowType.DataRow) && ((row.RowState == DataControlRowState.Edit) || (row.RowState == (DataControlRowState.Edit | DataControlRowState.Alternate))))
                    {
                        ProjectTimeGateway projectTimeGatewayForVerify = new ProjectTimeGateway();
                        int employeeId = Int32.Parse(hdfEmployeeID.Value);
                        int companyId = Int32.Parse(hdfCompanyId.Value);
                        DateTime date_ = tkrdpStartDate.SelectedDate.Value;
                        string startTime = "";
                        string startHoursEdit = ""; if (((DropDownList)row.FindControl("ddlStartTimeHourEdit")).SelectedValue.Trim() != "") startHoursEdit = ((DropDownList)row.FindControl("ddlStartTimeHourEdit")).SelectedValue.Trim();
                        string startMinutesEdit = ""; if (((DropDownList)row.FindControl("ddlStartTimeMinuteEdit")).SelectedValue.Trim() != "") startMinutesEdit = ((DropDownList)row.FindControl("ddlStartTimeMinuteEdit")).SelectedValue.Trim();

                        if ((startHoursEdit != "") && (startMinutesEdit != ""))
                        {
                            startTime = startHoursEdit + ":" + startMinutesEdit;
                        }

                        string endTime = "";
                        string endHoursEdit = ""; if (((DropDownList)row.FindControl("ddlEndTimeHourEdit")).SelectedValue.Trim() != "") endHoursEdit = ((DropDownList)row.FindControl("ddlEndTimeHourEdit")).SelectedValue.Trim();
                        string endMinutesEdit = ""; if (((DropDownList)row.FindControl("ddlEndTimeMinuteEdit")).SelectedValue.Trim() != "") endMinutesEdit = ((DropDownList)row.FindControl("ddlEndTimeMinuteEdit")).SelectedValue.Trim();

                        if ((endHoursEdit != "") && (endMinutesEdit != ""))
                        {
                            endTime = endHoursEdit + ":" + endMinutesEdit;
                        }

                        // Verify if the time already exists at DB
                        if (projectTimeGatewayForVerify.NotExistsByEmployeIdDate_StartTimeEndTime(employeeId, date_, startTime, endTime, companyId))
                        {
                            args.IsValid = true;
                        }

                        int cant = 0;
                        if (args.IsValid)
                        {
                            // Verify if it exist at last entered rows
                            if (grdProjectTime.Rows.Count > 0)
                            {
                                foreach (GridViewRow rowTemp in grdProjectTime.Rows)
                                {
                                    if ((rowTemp.RowType == DataControlRowType.DataRow) && ((rowTemp.RowState == DataControlRowState.Normal) || (rowTemp.RowState == (DataControlRowState.Normal | DataControlRowState.Alternate))))
                                    {
                                        TimeSpan spanGridStartTime = TimeSpan.Parse(((TextBox)rowTemp.FindControl("tbxStartTime")).Text.Trim());
                                        TimeSpan spanGridEndTime = TimeSpan.Parse(((TextBox)rowTemp.FindControl("tbxEndTime")).Text.Trim());
                                        TimeSpan spanStartTime = TimeSpan.Parse(startTime);
                                        TimeSpan spanEndTime = TimeSpan.Parse(endTime);
                                        string twentyForHours = "23:59";
                                        TimeSpan midNight = TimeSpan.Parse(twentyForHours);

                                        if ((Int32.Parse(hdfEmployeeID.Value) == employeeId) && (tkrdpStartDate.SelectedDate.Value == date_))
                                        {
                                            // When End Time < StartTime   (when they finish work the next day)
                                            if ((spanGridEndTime < spanGridStartTime) && (spanEndTime > spanStartTime))
                                            {
                                                if (((spanStartTime >= spanGridStartTime) && (spanStartTime <= midNight)) || ((spanEndTime >= spanGridStartTime) && (spanEndTime <= midNight)))
                                                {
                                                    cant++;
                                                }
                                            }
                                            else
                                            {
                                                if ((spanEndTime < spanStartTime) && (spanGridEndTime > spanGridStartTime))
                                                {
                                                    if (((spanGridStartTime >= spanStartTime) && (midNight <= spanStartTime)) || ((spanGridStartTime >= spanEndTime) && (midNight <= spanEndTime)))
                                                    {
                                                        cant++;
                                                    }
                                                }
                                                else
                                                {
                                                    if (((spanGridEndTime < spanGridStartTime) && (spanEndTime < spanStartTime)))
                                                    {
                                                        cant++;
                                                    }
                                                    else
                                                    {
                                                        // When End Time > Start Time.  (times in the same day)
                                                        // ... If it's a valid entry
                                                        if (((spanStartTime < spanGridStartTime) && (spanEndTime <= spanGridStartTime)) || (spanStartTime >= spanGridEndTime) && (spanEndTime > spanGridEndTime))
                                                        {

                                                        }
                                                        else
                                                        {
                                                            // If the range exists
                                                            cant++;
                                                        }

                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }

                            if (cant == 0)
                            {
                                args.IsValid = true;
                            }
                            else
                            {
                                args.IsValid = false;
                            }
                        }
                    }
                }
            }
        }
        private void UpdateDatabase()
        {
            try
            {
                DataRow[] drEmployees = projectTimeTDSForState.LFS_PROJECT_TIME.Select("ProjectTimeState = 'For Approval'", "EmployeeID ASC", DataViewRowState.OriginalRows);

                ProjectTimeGateway projectTimeGateway = new ProjectTimeGateway(projectTimeTDSForState);
                projectTimeGateway.Update();

                SendMailEmployees(drEmployees);

                projectTimeTDSForState.AcceptChanges();

                Session["projectTimeTDSForState"] = projectTimeTDSForState;
            }
            catch (Exception ex)
            {
                string url = string.Format("./../../error_page.aspx?error={0}", ex.Message.Replace('\n', ' '));
                Response.Redirect(url);
            }
        }
        protected void cvValidTimesFooter_ServerValidate(object source, ServerValidateEventArgs args)
        {
            args.IsValid = false;

            ProjectTimeGateway projectTimeGatewayForVerify = new ProjectTimeGateway();
            int employeeId = Int32.Parse(hdfEmployeeID.Value);
            int companyId = Int32.Parse(hdfCompanyId.Value);
            DateTime date_ = tkrdpStartDate.SelectedDate.Value;
            string startTimeFooter = "";
            string startHoursFooter = ""; if (((DropDownList)grdProjectTime.FooterRow.FindControl("ddlStartTimeHourFooter")).SelectedValue != "") startHoursFooter = ((DropDownList)grdProjectTime.FooterRow.FindControl("ddlStartTimeHourFooter")).SelectedValue.Trim();
            string startMinutesFooter = ""; if (((DropDownList)grdProjectTime.FooterRow.FindControl("ddlStartTimeMinuteFooter")).SelectedValue != "") startMinutesFooter = ((DropDownList)grdProjectTime.FooterRow.FindControl("ddlStartTimeMinuteFooter")).SelectedValue.Trim();

            string endTimeFooter = "";
            string endHoursFooter = ""; if (((DropDownList)grdProjectTime.FooterRow.FindControl("ddlEndTimeHourFooter")).SelectedValue != "") endHoursFooter = ((DropDownList)grdProjectTime.FooterRow.FindControl("ddlEndTimeHourFooter")).SelectedValue.Trim();
            string endMinutesFooter = ""; if (((DropDownList)grdProjectTime.FooterRow.FindControl("ddlEndTimeMinuteFooter")).SelectedValue != "") endMinutesFooter = ((DropDownList)grdProjectTime.FooterRow.FindControl("ddlEndTimeMinuteFooter")).SelectedValue.Trim();

            if ((startHoursFooter != "") && (startMinutesFooter != "") && (endHoursFooter != "") && (endMinutesFooter != ""))
            {
                startTimeFooter = startHoursFooter + ":" + startMinutesFooter;
                endTimeFooter = endHoursFooter + ":" + endMinutesFooter;

                // Verify if the time already exists at DB
                if (projectTimeGatewayForVerify.NotExistsByEmployeIdDate_StartTimeEndTime(employeeId, date_, startTimeFooter, endTimeFooter, companyId))
                {
                    args.IsValid = true;
                }

                if (args.IsValid)
                {
                    // Verify if it exist at last entered rows
                    ProjectTimeTemp modelForReview = new ProjectTimeTemp(projectTimeTDS);
                    if (modelForReview.NotExistsByEmployeIdDate_StartTimeEndTime(employeeId, date_, startTimeFooter, endTimeFooter))
                    {
                        args.IsValid = true;
                    }
                    else
                    {
                        args.IsValid = false;
                    }
                }
            }
        }
        private bool ValidateWedManagement()
        {
            if (!Convert.ToBoolean(Session["sgLFS_LABOUR_HOURS_FULL_EDITING"]))
            {
                if (Convert.ToBoolean(Session["sgLFS_LABOUR_HOURS_MY_TIMESHEETS_MANAGEMENT_WED"]) || Convert.ToBoolean(Session["sgLFS_LABOUR_HOURS_OTHERS_TIMESHEETS_MANAGEMENT_WED"]))
                {
                    List<int> projectTimesIdSelected = ((List<int>)Session["projectTimesIdSelected"]);

                    ProjectTimeGateway projectTimeGateway = new ProjectTimeGateway();

                    foreach (int projectTimeId in projectTimesIdSelected)
                    {
                        projectTimeGateway.LoadByProjectTimeId(projectTimeId);

                        bool isValidLimitPayPeriodToManagementEdit = LiquiForce.LFSLive.BL.LabourHours.ProjectTime.ProjectTime.ValidateLimitedPayPeriodToWednesdayManagementEdit(projectTimeGateway.GetDate_(projectTimeId), projectTimeGateway.GetProjectId(projectTimeId));

                        if (!isValidLimitPayPeriodToManagementEdit)
                        {
                            return false;
                        }
                    }
                }
            }

            return true;
        }
        private void UpdateDatabase()
        {
            try
            {
                ProjectTimeGateway projectTimeGateway = new ProjectTimeGateway(projectTimeTDS);
                projectTimeGateway.Update2();

                //TimesheetTDS timesheetTDS = new TimesheetTDS();
                //TimesheetGateway timesheetGateway = new TimesheetGateway(timesheetTDS);
                //timesheetGateway.LoadByEmployeeIdPayPeriodId((int)ViewState["employee_id"], (int)ViewState["period_id"]);
                //if (timesheetGateway.Table.Rows.Count == 0)
                //{
                //    LiquiForce.LFSLive.BL.LabourHours.Timesheet.Timesheet timesheet = new LiquiForce.LFSLive.BL.LabourHours.Timesheet.Timesheet(timesheetTDS);
                //    timesheet.SetForApproval((int)ViewState["employee_id"], (int)ViewState["period_id"]);

                //    timesheetGateway.Update();
                //    timesheetTDS.AcceptChanges();
                //}

                projectTimeTDS.AcceptChanges();

                Session["projectTimeTDS"] = projectTimeTDS;

                //if (ViewState["timesheetState"].ToString() != "For Approval")
                //{
                //    UpdateTimesheet();
                //}
            }
            catch (Exception ex)
            {
                string url = string.Format("./../../error_page.aspx?error={0}", ex.Message.Replace('\n', ' '));
                Response.Redirect(url);
            }
        }
        private void UpdateDatabase()
        {
            DropDownList ddlOthersFor = (DropDownList)tkrpbLeftMenuOthersTimesheets.FindItemByValue("nbOthersTimesheetsDDL").FindControl("ddlOthersFor");
            Session["ddlOthersForSelectedValue"] = ddlOthersFor.SelectedValue;

            try
            {
                ProjectTimeGateway projectTimeGateway = new ProjectTimeGateway(projectTimeTDS);
                projectTimeGateway.Update();

                projectTimeTDS.AcceptChanges();

                Session["projectTimeTDS"] = projectTimeTDS;
            }
            catch (Exception ex)
            {
                string url = string.Format("./../../error_page.aspx?error={0}", ex.Message.Replace('\n', ' '));
                Response.Redirect(url);
            }
        }
        /// <summary>
        /// Submit
        /// </summary>
        /// <param name="employeeId">employeeId</param>
        /// <param name="payPeriodId">payPeriodId</param>
        public void Submit(int employeeId, int payPeriodId)
        {
            // Insert or update a timesheet
            // ... Search timesheet
            TimesheetTDS.LFS_TIMESHEETRow timesheetRow = null;
            if (Table.Rows.Count > 0)
            {
                TimesheetGateway timesheetGateway = new TimesheetGateway(Data);
                timesheetRow = (TimesheetTDS.LFS_TIMESHEETRow)timesheetGateway.GetRowByEmployeeIdPayPeriodId(employeeId, payPeriodId);
            }

            // ... If timesheet not exists
            bool newRow = false;
            if (timesheetRow == null)
            {
                newRow = true;
                timesheetRow = ((TimesheetTDS.LFS_TIMESHEETDataTable)Table).NewLFS_TIMESHEETRow();
            }

            // ... Update timesheet's data
            timesheetRow.EmployeeID = employeeId;
            timesheetRow.PayPeriodID = payPeriodId;
            timesheetRow.State = "Submitted";
            timesheetRow.Deleted = false;
            if (newRow)
            {
                ((TimesheetTDS.LFS_TIMESHEETDataTable)Table).AddLFS_TIMESHEETRow(timesheetRow);
            }

            // Update timesheet's project time
            ProjectTimeGateway projectTimeGateway = new ProjectTimeGateway(Data);
            projectTimeGateway.LoadByEmployeeIdPayPeriodId(employeeId, payPeriodId);
            foreach (TimesheetTDS.LFS_PROJECT_TIMERow projectTimeRow in (TimesheetTDS.LFS_PROJECT_TIMEDataTable) projectTimeGateway.Table)
            {
                projectTimeRow.ProjectTimeState = "Submitted";
            }
        }
        protected void cvValidTimes_ServerValidate(object source, ServerValidateEventArgs args)
        {
            args.IsValid = false;

            int projectId = int.Parse(ddlProject.SelectedValue);
            if (projectId != 35 && projectId != 39 && projectId != 716)
            {
                ProjectTimeGateway projectTimeGatewayForVerify = new ProjectTimeGateway();
                int employeeId = Int32.Parse(ViewState["employee_id"].ToString());
                int companyId = Int32.Parse(hdfCompanyId.Value);
                DateTime date_ = tkrdpDate_.SelectedDate.Value;
                string startTimeFooter = "";
                string startHoursFooter = ""; if (ddlStartTimeHour.SelectedValue != "") startHoursFooter = ddlStartTimeHour.SelectedValue.Trim();
                string startMinutesFooter = ""; if (ddlStartTimeMinute.SelectedValue != "") startMinutesFooter = ddlStartTimeMinute.SelectedValue.Trim();

                string endTimeFooter = "";
                string endHoursFooter = ""; if (ddlEndTimeHour.SelectedValue != "") endHoursFooter = ddlEndTimeHour.SelectedValue.Trim();
                string endMinutesFooter = ""; if (ddlEndTimeMinute.SelectedValue != "") endMinutesFooter = ddlEndTimeMinute.SelectedValue.Trim();

                int projectTimeId = (int)ViewState["projecttime_id"];

                if ((startHoursFooter != "") && (startMinutesFooter != "") && (endHoursFooter != "") && (endMinutesFooter != ""))
                {
                    startTimeFooter = startHoursFooter + ":" + startMinutesFooter;
                    endTimeFooter = endHoursFooter + ":" + endMinutesFooter;

                    // Verify if the time already exists at DB
                    if (projectTimeGatewayForVerify.NotExistsByEmployeIdDate_StartTimeEndTimeEdit(projectTimeId, employeeId, date_, startTimeFooter, endTimeFooter, companyId))
                    {
                        args.IsValid = true;
                    }
                }
                else
                {
                    args.IsValid = true;
                }
            }
            else
            {
                args.IsValid = true;
            }
        }
        protected void Page_PreRender(object sender, EventArgs e)
        {
            // Set active toolbar
            mForm6 master = (mForm6)this.Master;
            master.ActiveToolbar = "LabourHours";

            // ... Labour Hours Mode
            if ((string)ViewState["LHMode"] == "Partial")
            {
                // Access control
                // ... Employees
                EmployeeListGateway employeeListGateway = new EmployeeListGateway(new DataSet());
                employeeListGateway.LoadByRequestProjectTime(1);

                DropDownList ddlOthersFor = (DropDownList)tkrpbLeftMenuOthersTimesheets.FindItemByValue("nbOthersTimesheetsDDL").FindControl("ddlOthersFor");
                ddlOthersFor.DataSource = employeeListGateway.Table;
                ddlOthersFor.DataValueField = "EmployeeID";
                ddlOthersFor.DataTextField = "FullName";
                ddlOthersFor.DataBind();

                tkrpbLeftMenuMyTimesheets.Visible = false;
                tkrpbLeftMenuOthersTimesheets.Items[0].Text = "Timesheets";
                tkrpbLeftMenuTools.Items[0].Items[1].Visible = false;
            }
            else
            {
                EmployeeGateway employeeGateway1 = new EmployeeGateway(new DataSet());
                int employeeId = employeeGateway1.GetEmployeIdByLoginId(Convert.ToInt32(Session["loginID"]));
                employeeGateway1.LoadByEmployeeId(employeeId);

                if (Request.QueryString["source_page"] == "timesheet_approve.aspx")
                {
                    tkrmTop.Items[3].Visible = false; //Timesheet
                    tkrmTop.Items[4].Visible = true; //Approve Project Times
                }
                else
                {
                    tkrmTop.Items[3].Visible = true; //Timesheet

                    // Timesheet state check
                    ProjectTimeGateway projectTimeGatewayForState = new ProjectTimeGateway(projectTimeTDS);
                    int projecttime_id = Int32.Parse(ViewState["projecttime_id"].ToString());

                    if (projectTimeGatewayForState.GetProjectTimeState(projecttime_id) == "For Approval")
                    {
                        tkrmTop.Items[4].Visible = true; //Approve Project Times
                    }
                    else
                    {
                        tkrmTop.Items[4].Visible = false; //Approve Project Times
                    }
                }

                if (!employeeGateway1.GetApproveTimesheets(employeeId))
                {
                    tkrpbLeftMenuTools.Items[0].Items[1].Visible = false; //Approve Project Times
                }

                if (Convert.ToBoolean(Session["sgLFS_LABOUR_HOURS_OTHERS_TIMESHEETS_VIEW"]) || Convert.ToBoolean(Session["sgLFS_LABOUR_HOURS_OTHERS_TIMESHEETS_MANAGEMENT"]) || Convert.ToBoolean(Session["sgLFS_LABOUR_HOURS_OTHERS_TIMESHEETS_MANAGEMENT_WED"]) || Convert.ToBoolean(Session["sgLFS_LABOUR_HOURS_FULL_EDITING"]))
                {
                    tkrpbLeftMenuOthersTimesheets.Visible = true;
                    tkrpbLeftMenuTools.Items[0].Items[0].Visible = true; // Add Team Project Time
                    tkrpbLeftMenuTools.Items[0].Items[2].Visible = true; // Missing Project Time

                    // Access control
                    // ... Employees
                    EmployeeListGateway employeeListGateway = new EmployeeListGateway(new DataSet());

                    if (!Convert.ToBoolean(Session["sgLFS_LABOUR_HOURS_FULL_EDITING"]))
                    {
                        employeeListGateway.LoadByRequestProjectTimeWithoutEmployeeId(1, employeeId);
                    }
                    else
                    {
                        employeeListGateway.LoadByRequestProjectTime(1);
                    }

                    DropDownList ddlOthersFor = (DropDownList)tkrpbLeftMenuOthersTimesheets.FindItemByValue("nbOthersTimesheetsDDL").FindControl("ddlOthersFor");
                    ddlOthersFor.DataSource = employeeListGateway.Table;
                    ddlOthersFor.DataValueField = "EmployeeID";
                    ddlOthersFor.DataTextField = "FullName";
                    ddlOthersFor.DataBind();
                    try
                    {
                        ddlOthersFor.SelectedValue = Session["ddlOthersForSelectedValue"].ToString();
                    }
                    catch
                    {
                    }
                }
                else
                {
                    tkrpbLeftMenuOthersTimesheets.Visible = false;

                    if (!employeeGateway1.GetApproveTimesheets(employeeId))
                    {
                        tkrpbLeftMenuTools.Visible = false;
                    }

                    tkrpbLeftMenuTools.Items[0].Items[0].Visible = false; // Add Team Project Time
                    tkrpbLeftMenuTools.Items[0].Items[2].Visible = false; // Missing Project Time
                }

                if (!((Convert.ToBoolean(Session["sgLFS_LABOUR_HOURS_MY_TIMESHEETS_VIEW"]) || Convert.ToBoolean(Session["sgLFS_LABOUR_HOURS_MY_TIMESHEETS_MANAGEMENT"]) || Convert.ToBoolean(Session["sgLFS_LABOUR_HOURS_MY_TIMESHEETS_MANAGEMENT_WED"]) || Convert.ToBoolean(Session["sgLFS_LABOUR_HOURS_FULL_EDITING"])) && (employeeGateway1.GetRequestProjectTime(employeeId))))
                {
                    tkrpbLeftMenuMyTimesheets.Visible = false;
                    tkrpbLeftMenuOthersTimesheets.Items[0].Text = "Timesheets";
                }

                if (!Convert.ToBoolean(Session["sgLFS_LABOUR_HOURS_FULL_EDITING"]))
                {
                    if (!Convert.ToBoolean(Session["sgLFS_LABOUR_HOURS_REPORTS"]))
                    {
                        tkrpbLeftMenuReports.Visible = false;
                    }
                }

                // Get ProjectTime record, can't edit or delete approved timesheets
                ProjectTimeGateway projectTimeGateway = new ProjectTimeGateway(projectTimeTDS);
                projectTimeGateway.LoadByProjectTimeId((int)ViewState["projecttime_id"]);

                if (!Convert.ToBoolean(Session["sgLFS_LABOUR_HOURS_FULL_EDITING"]))
                {
                    if (projectTimeGateway.GetProjectTimeState((int)ViewState["projecttime_id"]) == "Approved")
                    {
                        tkrmTop.Items[1].Visible = false;
                        tkrmTop.Items[2].Visible = false;
                    }
                }

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

            if (!IsPostBack)
            {
                // Validate query string
                if (((string)Request.QueryString["source_page"] == null) && ((string)Request.QueryString["others"] == null) && ((string)Request.QueryString["employee_id"] == null) && ((string)Request.QueryString["period_id"] == null) && ((string)Request.QueryString["projecttime_id"] == null))
                {
                    Response.Redirect("./../../error_page.aspx?error=" + "Invalid query string in timesheet_edit.aspx");
                }

                // Security check
                if (!Convert.ToBoolean(Session["sgLFS_LABOUR_HOURS_FULL_EDITING"]))
                {
                    if (Request.QueryString["others"] == "no")
                    {
                        if (!(Convert.ToBoolean(Session["sgLFS_LABOUR_HOURS_MY_TIMESHEETS_VIEW"]) && Convert.ToBoolean(Session["sgLFS_LABOUR_HOURS_MY_TIMESHEETS_EDIT"])))
                        {
                            if (!Convert.ToBoolean(Session["sgLFS_LABOUR_HOURS_MY_TIMESHEETS_MANAGEMENT"]))
                            {
                                if (!Convert.ToBoolean(Session["sgLFS_LABOUR_HOURS_MY_TIMESHEETS_MANAGEMENT_WED"]))
                                {
                                    Response.Redirect("./../../error_page.aspx?error=" + "You are not authorized to view this page. Contact your system administrator.");
                                }
                            }
                        }
                    }
                    else
                    {
                        if (!(Convert.ToBoolean(Session["sgLFS_LABOUR_HOURS_MY_TIMESHEETS_VIEW"]) && Convert.ToBoolean(Session["sgLFS_LABOUR_HOURS_MY_TIMESHEETS_EDIT"])))
                        {
                            if (!Convert.ToBoolean(Session["sgLFS_LABOUR_HOURS_MY_TIMESHEETS_MANAGEMENT"]))
                            {
                                if (!Convert.ToBoolean(Session["sgLFS_LABOUR_HOURS_MY_TIMESHEETS_MANAGEMENT_WED"]))
                                {
                                    if (!(Convert.ToBoolean(Session["sgLFS_LABOUR_HOURS_OTHERS_TIMESHEETS_VIEW"]) && Convert.ToBoolean(Session["sgLFS_LABOUR_HOURS_OTHERS_TIMESHEETS_EDIT"])))
                                    {
                                        if (!Convert.ToBoolean(Session["sgLFS_LABOUR_HOURS_OTHERS_TIMESHEETS_MANAGEMENT"]))
                                        {
                                            if (!Convert.ToBoolean(Session["sgLFS_LABOUR_HOURS_OTHERS_TIMESHEETS_MANAGEMENT_WED"]))
                                            {
                                                Response.Redirect("./../../error_page.aspx?error=" + "You are not authorized to view this page. Contact your system administrator.");
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                // Initialize viewstate variables
                ViewState["others"] = Request.QueryString["others"];
                ViewState["employee_id"] = int.Parse(Request.QueryString["employee_id"]);
                ViewState["period_id"] = int.Parse(Request.QueryString["period_id"]);
                ViewState["projecttime_id"] = int.Parse(Request.QueryString["projecttime_id"]);
                System.Configuration.AppSettingsReader appSettingReader = new System.Configuration.AppSettingsReader();
                ViewState["LHMode"] = appSettingReader.GetValue("LABOUR_HOURS_OPERATION_MODE", typeof(System.String)).ToString();
                hdfCompanyId.Value = Session["companyID"].ToString();

                // Get ProjectTime record
                ProjectTimeGateway projectTimeGateway = new ProjectTimeGateway(projectTimeTDS);
                projectTimeGateway.LoadByProjectTimeId((int)ViewState["projecttime_id"]);

                // Project time state check
                if (!Convert.ToBoolean(Session["sgLFS_LABOUR_HOURS_FULL_EDITING"]))
                {
                    if (projectTimeGateway.GetProjectTimeState((int)ViewState["projecttime_id"]) == "Approved")
                    {
                        Response.Redirect("./../../error_page.aspx?error=" + "You cannot edit an approved project time.");
                    }
                }

                if (!Convert.ToBoolean(Session["sgLFS_LABOUR_HOURS_FULL_EDITING"]))
                {
                    if (Convert.ToBoolean(Session["sgLFS_LABOUR_HOURS_MY_TIMESHEETS_MANAGEMENT"]) || Convert.ToBoolean(Session["sgLFS_LABOUR_HOURS_OTHERS_TIMESHEETS_MANAGEMENT"]))
                    {
                        bool isValidLimitPayPeriodToManagementEdit = LiquiForce.LFSLive.BL.LabourHours.ProjectTime.ProjectTime.ValidateLimitedPayPeriodToManagementEdit(projectTimeGateway.GetDate_((int)ViewState["projecttime_id"]), projectTimeGateway.GetProjectId((int)ViewState["projecttime_id"]));

                        if (!isValidLimitPayPeriodToManagementEdit)
                        {
                            Response.Redirect("./../../error_page.aspx?error=" + "You are not authorized to view this page. Contact your system administrator.");
                        }
                    }
                    else
                    {
                        if (Convert.ToBoolean(Session["sgLFS_LABOUR_HOURS_MY_TIMESHEETS_MANAGEMENT_WED"]) || Convert.ToBoolean(Session["sgLFS_LABOUR_HOURS_OTHERS_TIMESHEETS_MANAGEMENT_WED"]))
                        {
                            bool isValidLimitPayPeriodToManagementEdit = LiquiForce.LFSLive.BL.LabourHours.ProjectTime.ProjectTime.ValidateLimitedPayPeriodToWednesdayManagementEdit(projectTimeGateway.GetDate_((int)ViewState["projecttime_id"]), projectTimeGateway.GetProjectId((int)ViewState["projecttime_id"]));

                            if (!isValidLimitPayPeriodToManagementEdit)
                            {
                                Response.Redirect("./../../error_page.aspx?error=" + "You are not authorized to view this page. Contact your system administrator.");
                            }
                        }
                    }
                }

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

                // Databind
                tkrdpDate_.DataBind();
                ddlLunch.DataBind();
                tbxComments.DataBind();
                tbxState.DataBind();

                // Prepare initial data for client
                StoreNavigatorState();

                EmployeeGateway employeeGateway = new EmployeeGateway(new DataSet());
                employeeGateway.LoadByEmployeeId((int)ViewState["employee_id"]);
                tbxEmployee.Text = employeeGateway.GetFullName(int.Parse(Request.QueryString["employee_id"]));

                int companyId = Int32.Parse(hdfCompanyId.Value);
                CompaniesList companiesList = new CompaniesList();
                companiesList.LoadAndAddItem(-1, "(Select a client)", companyId);
                ddlClient.DataSource = companiesList.Table;
                ddlClient.DataValueField = "COMPANIES_ID";
                ddlClient.DataTextField = "Name";
                ddlClient.DataBind();

                CompaniesGateway companiesGateway = new CompaniesGateway();
                companiesGateway.LoadAllByCompaniesId(Int32.Parse(DataBinder.Eval(projectTimeTDS, "Tables[LFS_PROJECT_TIME].DefaultView.[0].CompaniesID").ToString()), companyId);

                // ... If Company is active
                bool deleted = companiesGateway.GetDeleted(Int32.Parse(DataBinder.Eval(projectTimeTDS, "Tables[LFS_PROJECT_TIME].DefaultView.[0].CompaniesID").ToString()));

                if (deleted)
                {
                    ddlClient.SelectedIndex = -1;
                }
                else
                {
                    ddlClient.SelectedValue = DataBinder.Eval(projectTimeTDS, "Tables[LFS_PROJECT_TIME].DefaultView.[0].CompaniesID").ToString();
                }

                ProjectList projectList = new ProjectList();
                projectList.LoadProjectsInternalProjectsBallparkProjectsAndAddItem(-1, "(Select a project)", int.Parse(ddlClient.SelectedValue));
                ddlProject.DataSource = projectList.Table;
                ddlProject.DataValueField = "ProjectID";
                ddlProject.DataTextField = "Name";
                ddlProject.DataBind();

                if (!deleted)
                {
                    try
                    {
                        ddlProject.SelectedValue = DataBinder.Eval(projectTimeTDS, "Tables[LFS_PROJECT_TIME].DefaultView.[0].ProjectID").ToString();
                    }
                    catch
                    {
                        ddlProject.SelectedIndex = -1;
                    }
                }
                else
                {
                    ddlProject.SelectedIndex = -1;
                }

                if (ddlProject.SelectedIndex != 0)
                {
                    ProjectGateway projectGateway = new ProjectGateway();
                    projectGateway.LoadByProjectId(Int32.Parse(ddlProject.SelectedValue));

                    if (projectGateway.GetCountryID(Int32.Parse(ddlProject.SelectedValue)) == 1) //Canada
                    {
                        if (projectGateway.GetFairWageApplies(int.Parse(ddlProject.SelectedValue)))
                        {
                            ddlJobClassType.Visible = true;
                            lblJobClassType.Visible = true;

                            ProjectTimeJobClassTypeList projectTimeJobClassTypeList = new ProjectTimeJobClassTypeList();
                            projectTimeJobClassTypeList.LoadAndAddItem(1, companyId, "(Select a Job Class Type)");
                            ddlJobClassType.DataSource = projectTimeJobClassTypeList.Table;
                            ddlJobClassType.DataValueField = "JobClassType";
                            ddlJobClassType.DataTextField = "JobClassType";
                            ddlJobClassType.DataBind();

                            if (projectTimeGateway.GetJobClassType((int)ViewState["projecttime_id"]).ToString() == "")
                            {
                                ddlJobClassType.SelectedIndex = 0;
                            }
                            else
                            {
                                ddlJobClassType.SelectedValue = (string)DataBinder.Eval(projectTimeTDS, "Tables[LFS_PROJECT_TIME].DefaultView.[0].JobClassType");
                            }
                        }
                        else
                        {
                            ddlJobClassType.Visible = false;
                            lblJobClassType.Visible = false;
                        }
                    }
                    else
                    {
                        if (projectGateway.GetFairWageApplies(int.Parse(ddlProject.SelectedValue)))
                        {
                            ddlJobClassType.Visible = true;
                            lblJobClassType.Visible = true;

                            ProjectTimeJobClassTypeList projectTimeJobClassTypeList = new ProjectTimeJobClassTypeList();
                            projectTimeJobClassTypeList.LoadAndAddItem(2, companyId, "(Select a Job Class Type)");
                            ddlJobClassType.DataSource = projectTimeJobClassTypeList.Table;
                            ddlJobClassType.DataValueField = "JobClassType";
                            ddlJobClassType.DataTextField = "JobClassType";
                            ddlJobClassType.DataBind();

                            if (projectTimeGateway.GetJobClassType((int)ViewState["projecttime_id"]).ToString() == "")
                            {
                                ddlJobClassType.SelectedIndex = 0;
                            }
                            else
                            {
                                ddlJobClassType.SelectedValue = (string)DataBinder.Eval(projectTimeTDS, "Tables[LFS_PROJECT_TIME].DefaultView.[0].JobClassType");
                            }
                        }
                        else
                        {
                            ddlJobClassType.Visible = false;
                            lblJobClassType.Visible = false;
                        }
                    }
                }
                else
                {
                    ddlJobClassType.Visible = false;
                    lblJobClassType.Visible = false;
                }

                WorkingDetailsGateway workingDetailsGateway = new WorkingDetailsGateway(new DataSet());
                workingDetailsGateway.Load();
                ddlWorkingDetails.DataSource = workingDetailsGateway.Table;
                ddlWorkingDetails.DataValueField = "WorkingDetails";
                ddlWorkingDetails.DataTextField = "WorkingDetails";
                ddlWorkingDetails.DataBind();

                if (!deleted)
                {
                    ddlWorkingDetails.SelectedValue = projectTimeGateway.GetWorkingDetails((int)ViewState["projecttime_id"]);
                }
                else
                {
                    ddlWorkingDetails.SelectedIndex = -1;
                }

                ProjectTimeWorkList projectTimeWorkList = new ProjectTimeWorkList(new DataSet());

                int projectId = 0;
                try
                {
                    projectId = Int32.Parse(ddlProject.SelectedValue);
                }
                catch
                {
                }

                if (projectId == 35 || projectId == 39 || projectId == 716)
                {
                    projectTimeWorkList.LoadAndAddItem("");
                }
                else
                {
                    projectTimeWorkList.LoadAndAddItem("(Select a Type)");
                }

                // Setting start time, end time
                string startTime = DataBinder.Eval(projectTimeTDS, "Tables[LFS_PROJECT_TIME].DefaultView.[0].StartTime", "{0:H:mm}").ToString();
                if (!String.IsNullOrEmpty(startTime))
                {
                    string[] hoursMin1 = startTime.Split(':');
                    ddlStartTimeHour.SelectedValue = hoursMin1[0].Trim();
                    ddlStartTimeMinute.SelectedValue = hoursMin1[1].Trim();
                }
                else
                {
                    ddlStartTimeHour.SelectedIndex = 0;
                    ddlStartTimeMinute.SelectedIndex = 0;
                }

                string endTime = DataBinder.Eval(projectTimeTDS, "Tables[LFS_PROJECT_TIME].DefaultView.[0].EndTime", "{0:H:mm}").ToString();
                if (!String.IsNullOrEmpty(endTime))
                {
                    string[] endHoursMin1 = endTime.Split(':');
                    ddlEndTimeHour.SelectedValue = endHoursMin1[0].Trim();
                    ddlEndTimeMinute.SelectedValue = endHoursMin1[1].Trim();
                }
                else
                {
                    ddlEndTimeHour.SelectedIndex = 0;
                    ddlEndTimeMinute.SelectedIndex = 0;
                }

                // Setting type of Work
                ddlTypeOfWork.DataSource = projectTimeWorkList.Table;
                ddlTypeOfWork.DataValueField = "Work_";
                ddlTypeOfWork.DataTextField = "Work_";
                ddlTypeOfWork.DataBind();
                if (projectTimeGateway.GetWork((int)ViewState["projecttime_id"]) == "") ddlTypeOfWork.SelectedIndex = -1; else ddlTypeOfWork.SelectedValue = projectTimeGateway.GetWork((int)ViewState["projecttime_id"]);

                ProjectTimeWorkFunctionList projectTimeWorkFunctionList = new ProjectTimeWorkFunctionList(new DataSet());
                if (projectTimeGateway.GetWork((int)ViewState["projecttime_id"]) == "")
                {
                    // ... If there is no type of Work, no function should be loaded
                    projectTimeWorkFunctionList.LoadAndAddItem("", "-1");
                }
                else
                {
                    projectTimeWorkFunctionList.LoadAndAddItem("(Select a Function)", projectTimeGateway.GetWork((int)ViewState["projecttime_id"]).ToString());
                }
                ddlFunction.DataSource = projectTimeWorkFunctionList.Table;
                ddlFunction.DataValueField = "Function_";
                ddlFunction.DataTextField = "Function_";
                ddlFunction.DataBind();
                if (projectTimeGateway.GetWork((int)ViewState["projecttime_id"]).ToString() == "")
                {
                    ddlFunction.SelectedValue = "";
                }
                else
                {
                    ddlFunction.SelectedValue = (string)DataBinder.Eval(projectTimeTDS, "Tables[LFS_PROJECT_TIME].DefaultView.[0].Function_");
                }

                CountryList countryList = new CountryList(new DataSet());
                countryList.LoadAndAddItem(-1, " ");
                ddlMealsCountry.DataSource = countryList.Table;
                ddlMealsCountry.DataValueField = "CountryID";
                ddlMealsCountry.DataTextField = "Name";
                ddlMealsCountry.DataBind();

                if (!deleted)
                {
                    if (projectTimeGateway.GetMealsCountry((int)ViewState["projecttime_id"]).HasValue)
                    {
                        ddlMealsCountry.SelectedValue = projectTimeGateway.GetMealsCountry((int)ViewState["projecttime_id"]).ToString();
                    }
                    else
                    {
                        ddlMealsCountry.SelectedValue = "-1";
                    }
                }
                else
                {
                    ddlMealsCountry.SelectedIndex = -1;
                }

                //if (projectTimeGateway.GetMealsAllowance((int)ViewState["projecttime_id"]) > 0)
                //{
                //    cbxMealsAllowance.Checked = true;
                //}

                string unitType = "Vehicle";
                UnitsList unitsList = new UnitsList(new DataSet());
                unitsList.LoadAndAddItem("-1", " ", Int32.Parse(Session["companyID"].ToString()), true, 0, unitType);
                ddlUnit.DataSource = unitsList.Table;
                ddlUnit.DataValueField = "UnitID";
                ddlUnit.DataTextField = "UnitCode";
                ddlUnit.DataBind();
                if (projectTimeGateway.GetUnitId((int)ViewState["projecttime_id"]).HasValue)
                {
                    ddlUnit.SelectedValue = ((int)projectTimeGateway.GetUnitId((int)ViewState["projecttime_id"])).ToString();
                }

                UnitsList towed = new UnitsList(new DataSet());
                towed.LoadAndAddItem("-1", " ", Int32.Parse(Session["companyID"].ToString()), true, 1, unitType);
                ddlTowed.DataSource = towed.Table;
                ddlTowed.DataValueField = "UnitID";
                ddlTowed.DataTextField = "UnitCode";
                ddlTowed.DataBind();
                if (projectTimeGateway.GetTowedUnitId((int)ViewState["projecttime_id"]).HasValue)
                {
                    ddlTowed.SelectedValue = ((int)projectTimeGateway.GetTowedUnitId((int)ViewState["projecttime_id"])).ToString();
                }
            }
            else
            {
                // Restore datasets
                projectTimeTDS = (ProjectTimeTDS)Session["projectTimeTDS"];
            }
        }
        /// <summary>
        /// Update2
        /// </summary>
        public void Update2()
        {
            ProjectTimeGateway projectTimeGateway = new ProjectTimeGateway(Data);

            DataTable timesheetChanges = Table.GetChanges();
            DataTable projectTimeChanges = projectTimeGateway.Table.GetChanges();

            if ((timesheetChanges == null) && (projectTimeChanges == null)) return;

            try
            {
                DB.Open();
                DB.BeginTransaction();

                Adapter.InsertCommand.Transaction = DB.Transaction;
                Adapter.UpdateCommand.Transaction = DB.Transaction;
                Adapter.DeleteCommand.Transaction = DB.Transaction;

                projectTimeGateway.Adapter.InsertCommand.Transaction = DB.Transaction;
                projectTimeGateway.Adapter.UpdateCommand.Transaction = DB.Transaction;
                projectTimeGateway.Adapter.DeleteCommand.Transaction = DB.Transaction;

                if ((timesheetChanges != null) && (timesheetChanges.Rows.Count > 0))
                {
                    Adapter.Update(timesheetChanges);
                }

                if ((projectTimeChanges != null) && (projectTimeChanges.Rows.Count > 0))
                {
                    projectTimeGateway.Adapter.Update(projectTimeChanges);
                }

                DB.CommitTransaction();
            }
            catch (DBConcurrencyException dBConcurrencyException)
            {
                DB.RollbackTransaction();
                throw new Exception("Concurrency error: Another user already updated the data you are working on.  Your operation has been cancelled.", dBConcurrencyException);
            }
            catch (SqlException sqlException)
            {
                DB.RollbackTransaction();
                byte severityLevel = sqlException.Class;
                if (severityLevel <= 16)
                {
                    throw new Exception("Low severity error. Your operation has been cancelled.  SQL Error " + severityLevel + ".");
                }
                if ((severityLevel >= 17) && (severityLevel <= 19))
                {
                    throw new Exception("Mid severity error. Your operation has been cancelled.  SQL Error " + severityLevel + ".");
                }
                if (severityLevel >= 20)
                {
                    throw new Exception("High severity error. Your operation has been cancelled.  SQL Error " + severityLevel + ".");
                }
            }
            catch (Exception e)
            {
                DB.RollbackTransaction();
                throw new Exception("Unknow error. Your operation has been cancelled.", e);
            }
            finally
            {
                DB.Close();
            }
        }
        protected void cvValidTimesFooter_ServerValidate(object source, ServerValidateEventArgs args)
        {
            if (hdfBtnNext.Value == "True")
            {
                args.IsValid = true;
            }
            else
            {
                args.IsValid = false;

                ProjectTimeGateway projectTimeGatewayForVerify = new ProjectTimeGateway();
                int employeeId = 0; if (((DropDownList)grdProjectTime.FooterRow.FindControl("ddlEmployeesFooter")).SelectedValue.Trim() != "") employeeId = Int32.Parse(((DropDownList)grdProjectTime.FooterRow.FindControl("ddlEmployeesFooter")).SelectedValue.Trim());
                int companyId = Int32.Parse(hdfCompanyId.Value);
                DateTime date_ = DateTime.Parse(tbxDate.Text);
                string startTimeFooter = "";
                string startHoursFooter = ""; if (((DropDownList)grdProjectTime.FooterRow.FindControl("ddlStartTimeHourFooter")).SelectedValue != "") startHoursFooter = ((DropDownList)grdProjectTime.FooterRow.FindControl("ddlStartTimeHourFooter")).SelectedValue.Trim();
                string startMinutesFooter = ""; if (((DropDownList)grdProjectTime.FooterRow.FindControl("ddlStartTimeMinuteFooter")).SelectedValue != "") startMinutesFooter = ((DropDownList)grdProjectTime.FooterRow.FindControl("ddlStartTimeMinuteFooter")).SelectedValue.Trim();

                string endTimeFooter = "";
                string endHoursFooter = ""; if (((DropDownList)grdProjectTime.FooterRow.FindControl("ddlEndTimeHourFooter")).SelectedValue != "") endHoursFooter = ((DropDownList)grdProjectTime.FooterRow.FindControl("ddlEndTimeHourFooter")).SelectedValue.Trim();
                string endMinutesFooter = ""; if (((DropDownList)grdProjectTime.FooterRow.FindControl("ddlEndTimeMinuteFooter")).SelectedValue != "") endMinutesFooter = ((DropDownList)grdProjectTime.FooterRow.FindControl("ddlEndTimeMinuteFooter")).SelectedValue.Trim();

                if ((startHoursFooter != "") && (startMinutesFooter != "") && (endHoursFooter != "") && (endMinutesFooter != ""))
                {
                    startTimeFooter = startHoursFooter + ":" + startMinutesFooter;
                    endTimeFooter = endHoursFooter + ":" + endMinutesFooter;

                    // Verify if the time not exists at DB
                    if (projectTimeGatewayForVerify.NotExistsByEmployeIdDate_StartTimeEndTime(employeeId, date_, startTimeFooter, endTimeFooter, companyId))
                    {
                        args.IsValid = true;
                    }

                    if (args.IsValid)
                    {
                        // Verify if it exist at last entered rows
                        TeamProjectTime2DetailTemp teamProjectTime2DetailTemp = new TeamProjectTime2DetailTemp(teamProjectTime2TDS);
                        if (teamProjectTime2DetailTemp.NotExistsByEmployeIdDate_StartTime(employeeId, date_, startTimeFooter, endTimeFooter))
                        {
                            args.IsValid = true;
                        }
                        else
                        {
                            args.IsValid = false;
                        }
                    }
                }
            }
        }