protected void GetMyAccessRights()
 {
     int userid = Convert.ToInt32(Session["UserId"]);
     User user = new User();
     user = user.GetUser(userid);
     Module module = new Module();
     module = module.GetModule("SetupUserRate.aspx");
     myAccessRights = myAccessRights.GetRolesModuleAccess(Convert.ToInt32(user.RoleId), module.Id);
 }
 protected void InitializeRepeater()
 {
     int userid = Convert.ToInt32(Session["UserId"]);
     User user = new User();
     user = user.GetUser(userid);
     Module module = new Module();
     var list = module.GetModuleList(Convert.ToInt32(user.RoleId), "Report");
     repeaterReport.DataSource = list;
     repeaterReport.DataBind();
 }
 protected bool HasAccess()
 {
     int userid = Convert.ToInt32(Session["UserId"]);
     bool result = false;
     User user = new User();
     user = user.GetUser(userid);
     Module module = new Module();
     var list = module.GetModuleList(Convert.ToInt32(user.RoleId), "Report");
     if (list.Count > 0)
         result = true;
     return result;
 }
 protected bool hasAccess(string modulename)
 {
     bool result = false;
     User user = new User();
     user = user.GetUser(Convert.ToInt32(HttpContext.Current.Session["UserId"]));
     Module module = new Module();
     var list = module.GetModuleList(Convert.ToInt32(user.RoleId),modulename);
     RolesModuleAccess moduleAccess = new RolesModuleAccess();
     if (list.Count > 0)
         result = true;
     return result;
 }
        public TimeClock GetStartEndTime(int userid, DateTime selectedDate)
        {
            TimeTrackerEntities db = new TimeTrackerEntities();
            TimeClock result = new TimeClock();
            User user = new User();

            user = user.GetUser(userid);

            //DateTime stime = Convert.ToDateTime(selectedDate.ToString("yyyy-MM-dd") + " 00:00");
            //DateTime etime = Convert.ToDateTime(selectedDate.ToString("yyyy-MM-dd") + " 23:59");
            DateTime stime = new DateTime();
            DateTime etime = new DateTime();
            TimeSpan startTime = new TimeSpan();
            TimeSpan endTime = new TimeSpan();
            TimeSpan.TryParse(user.startTime == "" ? "08:00":user.startTime, out startTime);
            TimeSpan.TryParse(user.endTime == "" ? "17:00":user.endTime, out endTime);
            if (startTime > endTime)
            {

            }
            var data = (from t in db.T_TimeClock
                        where t.EmployeeNumber == user.EmployeeNumber
                        && t.ScanTime >= stime
                        && t.ScanTime <= etime
                        orderby t.ScanTime ascending
                        select new TimeClock()
                        {
                            Id = t.Id,
                            EmployeeNumber = t.EmployeeNumber,
                            ScanTime = t.ScanTime,
                            CreateDate = t.CreateDate,
                            Filename = t.Filename
                        }).ToList();

            db.Dispose();
            result.starttime = DateTime.Now.AddYears(1);
            for (int i = 0; i < data.Count; i++)
            {
                if (i % 2 == 0)
                {
                    if (result.starttime == null || result.starttime > data[i].ScanTime)
                        result.starttime = data[i].ScanTime;
                }
                else
                {
                    if (result.endtime == null || result.endtime < data[i].ScanTime)
                        result.endtime = data[i].ScanTime;
                }
            }

            return data.Count < 2 ? null : result;
        }
 protected bool isValidUser()
 {
     bool isvalid = false;
     if (Session["UserId"] != null)
     {
         int userid = Convert.ToInt32(Session["UserId"]);
         User user = new User();
         user = user.GetUser(userid);
         if (user != null)
         {
             isvalid = true;
         }
     }
     return isvalid;
 }
        protected void BtnBreak_Click(object sender, EventArgs e)
        {
            int userid = Convert.ToInt32(Session["UserId"]);
            JobType jobtype = new JobType();
            jobtype = jobtype.GetDefaultBreak();
            DateTime selectedDate = DateTime.Parse(txtBoxDate.Text);
            JobTracker jobtracker = new JobTracker();
            bool noError = true;
            User user = new User();
            user = user.GetUser(userid, selectedDate);

            if (jobtracker.HasPreviousUnclosedJobs(userid,DateTime.Today)) //check if user has unclosed jobs
            {
                noError = false;
                panelAlertHeader2.CssClass = "modalAlertHeader";
                alertModalBtnOK2.CssClass = "buttonalert";
                labelAlertHeader2.Text = "Error";
                labelAlertMessage2.Text = "Please close all jobs before adding a new one.";
                programmaticAlertModalPopup2.Show();
            }
            else
            {
                string errMsg = "";
                errMsg = jobtracker.GetError(userid, selectedDate, 30); //check if there is an error
                if (errMsg.Trim() != "")
                {
                    noError = false;
                    panelAlertHeader2.CssClass = "modalAlertHeader";
                    alertModalBtnOK2.CssClass = "buttonalert";
                    labelAlertHeader2.Text = "Error";
                    labelAlertMessage2.Text = errMsg.Trim() + " Please settle error first.";
                    programmaticAlertModalPopup2.Show();
                }
            }
            if (noError)
            {
                if (TimeSpan.Parse(user.startTime) > TimeSpan.Parse(user.endTime)) //check if user has shifting hours
                {
                    RunBreakButtonActionForShifting();
                }
                else
                {
                    RunBreakButtonAction();
                }

            }
        }
        protected void gridViewUser_Command(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "Select")
            {
                GetMyAccessRights();
                modalLabelError.Text = "";
                modalLabelError.Visible = false;
                int index = Convert.ToInt32(e.CommandArgument);
                int userid = Convert.ToInt32(((Label)gridViewUser.Rows[index].FindControl("labelUserId")).Text);
                User user = new User();
                user = user.GetUser(userid);
                InitializeModalDropDownDepartment(user.DepartmentId.ToString());
                InitializeModalDropDownRole(user.RoleId.ToString());
                InitializeModalDropDownStatus(user.Status);
                modalBtnSubmit.Visible = Convert.ToBoolean(myAccessRights.CanUpdate);
                modalLabelUserId.Text = userid.ToString();
                modalBtnSubmit.CommandArgument = "Update";
                modalTxtBoxEmployeeNo.Text = user.EmployeeNumber.ToString();
                modalTxtBoxFirstname.Text = user.Firstname.Trim();
                modalTxtBoxLastname.Text = user.Lastname;
                modalTxtBoxUsername.Text = user.Username;
                modalTxtBoxPassword.Attributes.Add("value", user.Password);
                modalTxtBoxPhone.Text = user.Phone;
                modalTxtBoxMobile.Text = user.Mobile;
                modalTxtBoxEmail.Text = user.Email;
                modalTxtBoxFax.Text = user.Fax;
                //InitializeModalRadBtnShift(user.Shift);

                modalTxtBoxStartTime.Text = user.startTime;
                modalTxtBoxEndTime.Text = user.endTime;
                modalTxtBoxSalary.Text = user.currentSalary.ToString();
                modalTxtBoxBreakTimeMin.Text = user.currentMinBreak.ToString();

                InitializeModalDropDownOffDay(user.currentOffDay.ToString());
                InitializeModalDropDownSpecialOffDay(user.currentSpecialOffDay.ToString());
                modalChckBoxNoOTPay.Checked = user.noOTpay;
                modalChckBoxOfficeWorker.Checked =  user.isOfficeWorker;

                TimeSpan cutOfTime = user.GetMyCutOfTime();

                modalChkBoxUpdateRate.Checked = false;
                cpeSalaryRate.ClientState = "true";
                ToggleReqField(false);

                this.programmaticModalPopup.Show();
            }
        }
 protected void BtnLogin_Click(object sender, EventArgs e)
 {
     User user = new User();
     user = user.GetActiveUser(txtBoxUsername.Text.Trim(), txtBoxPassword.Text.Trim());
     if (user != null)
     {
         Session["UserId"] = user.Id;
         Session["RoleId"] = user.RoleId;
         Session["DepartmentId"] = user.DepartmentId;
         labelError.Visible = false;
         //Server.Transfer("Default.aspx", false);
         Response.Redirect("Dashboard.aspx", true);
     }
     else
     {
         labelError.Text = "Login Failed. Please check your username or/and password.";
         labelError.Visible = true;
     }
 }
        protected void linkBtnUserlink_Click(object sender, EventArgs e)
        {
            modalUserlinkChkBoxUpdate.Checked = false;
            cpeUserlink.ClientState = "true"; //Collapse the panel
            ToggleReqField(false);

            modalUserlinkLabelError.Text = "";
            modalUserlinkLabelError.Visible = false;
            int userid = Convert.ToInt32(Session["UserId"]);
            User user = new User();
            user = user.GetUser(userid);
            modalUserlinkTxtBoxFirstname.Text = user.Firstname.Trim();
            modalUserlinkTxtBoxLastname.Text = user.Lastname.Trim();
            modalUserlinkTxtBoxUsername.Text = user.Username.Trim();
            modalUserlinkTxtBoxEmail.Text = user.Email.Trim();
            modalUserlinkTxtBoxPhone.Text = user.Phone.Trim();
            modalUserlinkTxtBoxMobile.Text = user.Mobile.Trim();
            modalUserlinkTxtBoxFax.Text = user.Fax.Trim();
            this.programmaticUserlinkModalPopup.Show();
        }
        protected void gridViewUser_Command(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "Select")
            {
                GetMyAccessRights();
                modalLabelError.Text = "";
                modalLabelError.Visible = false;
                int index = Convert.ToInt32(e.CommandArgument);
                int userid = Convert.ToInt32(((Label)gridViewUser.Rows[index].FindControl("labelUserId")).Text);
                User user = new User();
                user = user.GetUser(userid);
                modalBtnSubmit.Visible = Convert.ToBoolean(myAccessRights.CanUpdate);
                modalLabelUserId.Text = userid.ToString();
                modalLabelEmployeeNo.Text = user.EmployeeNumber.ToString();
                modalLabelFirstName.Text = user.Firstname.Trim();
                modalLableLastName.Text = user.Lastname;
                modalTxtBoxStartTime.Text = user.startTime;
                modalTxtBoxEndTime.Text = user.endTime;
                modalTxtBoxSalary.Text = user.currentSalary.ToString();
                modalTxtBoxBreakTimeMin.Text = user.currentMinBreak.ToString();

                InitializeOffDayDropDown(modalDropDownOffDay,user.currentOffDay.ToString());
                InitializeOffDayDropDown(modalDropDownSpecialOffDay, user.currentSpecialOffDay.ToString());
                InitializeOffDayDropDown(modalDropDownOptionalOffDay1,user.currentOptOffDay1.ToString());
                InitializeOffDayDropDown(modalDropDownOptionalOffDay2,user.currentOptOffDay2.ToString());
                InitializeOffDayDropDown(modalDropDownOptionalOffDay3,user.currentOptOffDay3.ToString());
                InitializeOffDayDropDown(modalDropDownOptionalOffDay4,user.currentOptOffDay4.ToString());
                modalChckBoxNoOTPay.Checked = user.noOTpay;
                modalChckBoxOfficeWorker.Checked = user.isOfficeWorker;
                if (user.currentRateCreateDate == DateTime.Today)
                {
                    modalTxtBoxStartDate.Text = user.currentRateStartDate.ToString("dd MMM yyyy");
                    calendarExtenderStartDate.SelectedDate = user.currentRateStartDate;
                }
                else
                {
                    modalTxtBoxStartDate.Text = DateTime.Today.ToString("dd MMM yyyy");
                    calendarExtenderStartDate.SelectedDate = DateTime.Today;
                }
                UserRateSchedule prevUserRateSchedule= new UserRateSchedule();
                prevUserRateSchedule = prevUserRateSchedule.GetPreviousUserScheduleRateByUserIdLastUpdateDate(user.Id, DateTime.Today);
                if (prevUserRateSchedule != null)
                {
                    calendarExtenderStartDate.StartDate = prevUserRateSchedule.StartDate.AddDays(1);
                }
                else
                {
                    calendarExtenderStartDate.StartDate = null;
                }

                modalChckBoxUsePattern.Checked = user.usePattern;
                ToggleReqField(user.usePattern);
                modalTxtBoxPattern.Text = user.offPattern.Trim();
                modalTxtBoxPatternStartDate.Text = user.patternStartDate.ToString("dd MMM yyyy");
                calendarExtenderPatternStartDate.SelectedDate = user.patternStartDate;
                if (modalChckBoxUsePattern.Checked == true)
                {
                    cpeNormalUse.ClientState = "true";
                    cpePatternUse.ClientState = "false";
                }
                else
                {
                    cpePatternUse.ClientState = "true";
                    cpeNormalUse.ClientState = "false";
                }

                this.programmaticModalPopup.Show();
            }
        }
        protected void InitializeModalDropDownSupervisor()
        {
            int userid = Convert.ToInt32(modalDropDownUsers.SelectedItem.Value);
            int deptid = Convert.ToInt32(modalDropDownDepartment.SelectedItem.Value);
            User user = new User();
            var data = user.GetAvailableSupervisors(userid, deptid);

            modalDropDownSupervisor.DataSource = data;
            for (int i = 0; i < gridViewModal.Rows.Count; i++)
            {
                Label labelSupId = (Label)gridViewModal.Rows[i].FindControl("modalLabelSupId");
                int lid = Convert.ToInt32(labelSupId.Text);
                for (int j = 0; j < data.Count; j++)
                {
                    if (data[j].Id == lid)
                    {
                        data.RemoveAt(j);
                        break;
                    }
                }
            }
            modalDropDownSupervisor.DataTextField = "fullname";
            modalDropDownSupervisor.DataValueField = "Id";
            modalDropDownSupervisor.DataBind();
            if (modalDropDownSupervisor.Items.Count < 1)
                modalBtnAdd.Visible = false;
            else
                modalBtnAdd.Visible = true;
        }
        protected void modalBtnSubmit_Command(object sender, CommandEventArgs e)
        {
            if (modalLabelError.Visible == true)
                this.programmaticModalPopup.Show();
            else
            {
                int userid = Convert.ToInt32(Session["UserId"]);
                User user = new User();
                if (modalLabelUserId.Text.Trim() != "") //Update
                {
                    user = user.GetUser(Convert.ToInt32(modalLabelUserId.Text));
                }

                UserRateSchedule userRateSchedule = new UserRateSchedule();
                UserRateSchedule prevUserRateSchedule = userRateSchedule.GetPreviousUserScheduleRateByUserIdLastUpdateDate(user.Id, DateTime.Today);
                userRateSchedule = userRateSchedule.GetUserScheduleRateByUserIdCreateDate(user.Id, DateTime.Today); //Checks if there is already a schedule date with the same start date

                if (userRateSchedule != null)
                {
                    userRateSchedule.StartTime = modalTxtBoxStartTime.Text.Trim();
                    userRateSchedule.EndTime = modalTxtBoxEndTime.Text.Trim();
                    userRateSchedule.MonthlySalary = userRateSchedule.EncryptSalary(modalTxtBoxSalary.Text.Trim());
                    userRateSchedule.OffDay = Convert.ToInt32(modalDropDownOffDay.SelectedItem.Value);
                    userRateSchedule.SpecialOffDay = Convert.ToInt32(modalDropDownSpecialOffDay.SelectedItem.Value);
                    userRateSchedule.OptionalOffDay1 = Convert.ToInt32(modalDropDownOptionalOffDay1.SelectedItem.Value);
                    userRateSchedule.OptionalOffDay2 = Convert.ToInt32(modalDropDownOptionalOffDay2.SelectedItem.Value);
                    userRateSchedule.OptionalOffDay3 = Convert.ToInt32(modalDropDownOptionalOffDay3.SelectedItem.Value);
                    userRateSchedule.OptionalOffDay4 = Convert.ToInt32(modalDropDownOptionalOffDay4.SelectedItem.Value);
                    userRateSchedule.NoOTPay = modalChckBoxNoOTPay.Checked;
                    userRateSchedule.IsOfficeWorker = modalChckBoxOfficeWorker.Checked;
                    userRateSchedule.MinsBreak = Convert.ToInt32(modalTxtBoxBreakTimeMin.Text);
                    userRateSchedule.StartDate = Convert.ToDateTime(modalTxtBoxStartDate.Text.Trim());
                    userRateSchedule.LastUpdatedDate = DateTime.Today;
                    userRateSchedule.IsCurrentRate = true;
                    userRateSchedule.UsePattern = modalChckBoxUsePattern.Checked;
                    userRateSchedule.OffPattern = modalTxtBoxPattern.Text.Trim();
                    userRateSchedule.PatternStartDate = Convert.ToDateTime(modalTxtBoxPatternStartDate.Text.Trim());
                    userRateSchedule.Update(userRateSchedule);
                }
                else
                {
                    userRateSchedule = new UserRateSchedule();
                    userRateSchedule.StartTime = modalTxtBoxStartTime.Text.Trim();
                    userRateSchedule.EndTime = modalTxtBoxEndTime.Text.Trim();
                    userRateSchedule.UserId = user.Id;
                    userRateSchedule.MonthlySalary = userRateSchedule.EncryptSalary(modalTxtBoxSalary.Text.Trim());
                    userRateSchedule.OffDay = Convert.ToInt32(modalDropDownOffDay.SelectedItem.Value);
                    userRateSchedule.SpecialOffDay = Convert.ToInt32(modalDropDownSpecialOffDay.SelectedItem.Value);
                    userRateSchedule.OptionalOffDay1 = Convert.ToInt32(modalDropDownOptionalOffDay1.SelectedItem.Value);
                    userRateSchedule.OptionalOffDay2 = Convert.ToInt32(modalDropDownOptionalOffDay2.SelectedItem.Value);
                    userRateSchedule.OptionalOffDay3 = Convert.ToInt32(modalDropDownOptionalOffDay3.SelectedItem.Value);
                    userRateSchedule.OptionalOffDay4 = Convert.ToInt32(modalDropDownOptionalOffDay4.SelectedItem.Value);
                    userRateSchedule.NoOTPay = modalChckBoxNoOTPay.Checked;
                    userRateSchedule.IsOfficeWorker = modalChckBoxOfficeWorker.Checked;
                    userRateSchedule.MinsBreak = Convert.ToInt32(modalTxtBoxBreakTimeMin.Text);
                    userRateSchedule.StartDate = Convert.ToDateTime(modalTxtBoxStartDate.Text.Trim());
                    userRateSchedule.IsCurrentRate = true;
                    userRateSchedule.CreatedDate = DateTime.Today;
                    userRateSchedule.LastUpdatedDate = DateTime.Today;
                    userRateSchedule.UsePattern = modalChckBoxUsePattern.Checked;
                    userRateSchedule.OffPattern = modalTxtBoxPattern.Text.Trim();
                    userRateSchedule.PatternStartDate = Convert.ToDateTime(modalTxtBoxPatternStartDate.Text.Trim());
                    userRateSchedule.Insert(userRateSchedule);
                }
                if (prevUserRateSchedule != null)
                {
                    prevUserRateSchedule.EndDate = Convert.ToDateTime(modalTxtBoxStartDate.Text.Trim()+" 23:59:59");
                    prevUserRateSchedule.IsCurrentRate = false;
                    prevUserRateSchedule.LastUpdatedDate = DateTime.Today;

                    prevUserRateSchedule.Update(prevUserRateSchedule);
                }
            }
        }
        private void InitializeMainGrid()
        {
            GetMyAccessRights();

            User user = new User();
            if (myAccessRights.CanAdd == true)
            {
                if (dropDownListDepartment.SelectedItem.Text == "All" && user.GetActiveUsersWithoutSupervisor().Count > 0)
                {
                    linkBtnAdd.Visible = true;
                }
                else if (user.GetActiveUsersWithoutSupervisor(Convert.ToInt32(dropDownListDepartment.SelectedItem.Value)).Count > 0)
                {
                    linkBtnAdd.Visible = true;
                }
                else
                    linkBtnAdd.Visible = false;
            }
            else
                linkBtnAdd.Visible = false;

            List<User> userlist = new List<User>();
            if (dropDownListDepartment.SelectedItem.Text == "All")
            {
                userlist = user.GetActiveUsersWithSupervisor();
            }
            else
            {
                userlist = user.GetActiveUsersWithSupervisor(Convert.ToInt32(dropDownListDepartment.SelectedItem.Value));
            }

            gridViewUser.DataSource = userlist;
            gridViewUser.DataBind();
        }
 protected void InitializeBottomDropDownDepartment()
 {
     ddlBottomDepartment.Enabled = true;
     int roleid = Convert.ToInt32(Session["RoleId"]);
     RoleDepartmentAccess departmentAccess = new RoleDepartmentAccess();
     var departmentlist = departmentAccess.GetRoleDepartmentList(roleid);
     if (departmentlist.Count > 1)
     {
         departmentAccess.DepartmentId = 0;
         departmentAccess.department = "All";
         departmentlist.Insert(0, departmentAccess);
     }
     else if (departmentlist.Count < 1)
     {
         int userid = Convert.ToInt32(Session["UserId"]);
         Department department = new Department();
         User user = new User();
         user = user.GetUser(userid);
         department = department.GetDepartment(Convert.ToInt32(user.DepartmentId));
         departmentAccess.DepartmentId = department.Id;
         departmentAccess.department = department.Description;
         departmentlist.Insert(0, departmentAccess);
         ddlBottomDepartment.Enabled = false;
     }
     ddlBottomDepartment.DataSource = departmentlist;
     ddlBottomDepartment.DataTextField = "department";
     ddlBottomDepartment.DataValueField = "DepartmentId";
     ddlBottomDepartment.DataBind();
 }
        //Use to get newly created jobtracker
        public JobTracker GetJobTracker(int createdby, int lastupdatedby, DateTime starttime, int jobtypeid, string actionrequest, string status, bool computetime)
        {
            TimeTrackerEntities db = new TimeTrackerEntities();

            var data = (from j in db.T_JobTracker
                        where j.CreatedBy == createdby
                        && j.LastUpdatedBy == lastupdatedby
                        && j.StartTime == starttime
                        && j.JobTypeId == jobtypeid
                        && j.ActionRequest == actionrequest
                        && j.Status == status
                        select new JobTracker()
                        {
                            Id = j.Id,
                            UserId = j.UserId,
                            StartTime = j.StartTime,
                            EndTime = j.EndTime,
                            Description = j.Description,
                            JobTypeId = j.JobTypeId,
                            JobIdNumber = j.JobIdNumber,
                            jobtype = j.M_JobType.Description,
                            Remarks = j.Remarks,
                            ApprovedBy = j.ApprovedBy,
                            CreateDate = j.CreateDate,
                            LastUpdateDate = j.LastUpdateDate,
                            CreatedBy = j.CreatedBy,
                            LastUpdatedBy = j.LastUpdatedBy,
                            Status = j.Status,
                            SupervisorRemarks = j.SupervisorRemarks,
                            ActionRequest = j.ActionRequest,
                            ScheduleDate = j.ScheduleDate,
                            SWNo = j.SWNo,
                            HWNo = j.HWNo,
                            JobStatus = j.JobStatus,
                            fullname = j.M_User.Firstname + " " + j.M_User.Lastname,
                            Customer = j.Customer,
                            EvalNo = j.EvalNo
                        }).FirstOrDefault();

            db.Dispose();

            //if (data.JobIdNumber != null && data.JobIdNumber != "")
            //{
            //    GetCustomer(data);
            //}
            if (computetime == true)
            {
                User user = new User();
                user = user.GetUser(Convert.ToInt32(data.UserId), Convert.ToDateTime(data.StartTime));
                if (data.EndTime != null)
                {
                    TimeSpan stime = Convert.ToDateTime(data.StartTime).TimeOfDay;
                    TimeSpan etime = Convert.ToDateTime(data.EndTime).TimeOfDay;
                    double nmins = 0;
                    double omins = 0;
                    otcost = 0;
                    normalcost = 0;

                    double time = Convert.ToDateTime(data.EndTime).Subtract(Convert.ToDateTime(data.StartTime)).TotalMinutes;
                    if (user.shifting == false)
                    {
                        if (TimeSpan.Parse(user.endTime) <= stime) //entry is OT
                        {
                            omins = time;
                        }
                        else if ((etime == new TimeSpan(0, 0, 0) ? new TimeSpan(1, 0, 0, 0) : etime) > TimeSpan.Parse(user.endTime)) //entry is from normal time to OT
                        {
                            nmins = TimeSpan.Parse(user.endTime).Subtract(stime).TotalMinutes;
                            omins = (etime == new TimeSpan(0, 0, 0) ? new TimeSpan(1, 0, 0, 0) : etime).Subtract(TimeSpan.Parse(user.endTime)).TotalMinutes;
                        }
                        else //entry is within normal time
                        {
                            nmins = time;
                        }
                    }
                    else
                    {
                        TimeSpan cutoff = user.GetMyCutOfTime();
                        if (stime >= cutoff)
                        {
                            nmins = time;
                        }
                        else
                        {
                            if (TimeSpan.Parse(user.endTime) <= stime) //entry is OT
                            {
                                omins = time;
                            }
                            else if ((etime == new TimeSpan(0, 0, 0) ? new TimeSpan(1, 0, 0, 0) : etime) > TimeSpan.Parse(user.endTime))
                            {
                                nmins = TimeSpan.Parse(user.endTime).Subtract(stime).TotalMinutes;
                                omins = (etime == new TimeSpan(0, 0, 0) ? new TimeSpan(1, 0, 0, 0) : etime).Subtract(TimeSpan.Parse(user.endTime)).TotalMinutes;
                            }
                        }
                    }
                    double hr = Math.Truncate(time / 60);
                    double min = time % 60;
                    data.totalhours = hr == 0 && min == 0 ? "0 min" : (hr > 0 ? hr > 1 ? hr + " hrs" : hr + " hr" : "") + (hr > 0 && min > 0 ? ", " : "") + (min > 0 ? min > 1 ? min + " mins" : min + " min" : "");

                    hr = Math.Truncate(nmins / 60);
                    min = nmins % 60;
                    data.normalhours = hr == 0 && min == 0 ? "0 min" : (hr > 0 ? hr > 1 ? hr + " hrs" : hr + " hr" : "") + (hr > 0 && min > 0 ? ", " : "") + (min > 0 ? min > 1 ? min + " mins" : min + " min" : "");

                    hr = Math.Truncate(omins / 60);
                    min = omins % 60;
                    data.othours = hr == 0 && min == 0 ? "0 min" : (hr > 0 ? hr > 1 ? hr + " hrs" : hr + " hr" : "") + (hr > 0 && min > 0 ? ", " : "") + (min > 0 ? min > 1 ? min + " mins" : min + " min" : "");
                }
            }

            return data;
        }
        private bool HasTimeClockGap(int userid, DateTime selecteddate)
        {
            //Checks if the user has a gap between his facetime time and the time key in, in jobtrack
            bool result = false;
            User user = new User();
            user = user.GetUser(userid,selecteddate);
            if (user.EmployeeNumber != 0)
            {
                if (TimeSpan.Parse(user.startTime) > TimeSpan.Parse(user.endTime)) //user with shifting hour
                {
                    TimeClock timeclock1 = new TimeClock();
                    TimeClock timeclock2 = new TimeClock();
                    TimeSpan cutOffTime = user.GetMyCutOfTime();

                    timeclock2 = timeclock2.GetStartEndTimeForShifting(Convert.ToInt32(user.EmployeeNumber), Convert.ToDateTime(selecteddate.AddDays(-1).ToString("yyyy-MM-dd") + " " + cutOffTime.ToString("hh\\:mm\\:ss")), Convert.ToDateTime(selecteddate.ToString("yyyy-MM-dd") + " " + cutOffTime.ToString("hh\\:mm\\:ss")), false);
                    if (timeclock2 != null)
                    {
                        var data = GetJobTrackerListWithEndTimeAndNotRejected(userid, Convert.ToDateTime(selecteddate.ToString("yyyy-MM-dd") + " 00:00:00"), Convert.ToDateTime(selecteddate.ToString("yyyy-MM-dd") + " " + cutOffTime.ToString("hh\\:mm\\:ss")));
                        if (data.Count > 0)
                        {
                            if (timeclock2.starttime < Convert.ToDateTime(data[0].StartTime))
                                result = true;
                            if ((timeclock2.endtime.TimeOfDay < new TimeSpan(0,30,0) ? timeclock1.endtime : timeclock2.endtime.AddMinutes(-30)) > Convert.ToDateTime(data[data.Count - 1].EndTime))
                                result = true;
                        }
                        else
                        {
                            result = true;
                        }
                    }
                    if (result == false)
                    {
                        timeclock1 = timeclock1.GetStartEndTimeForShifting(Convert.ToInt32(user.EmployeeNumber), Convert.ToDateTime(selecteddate.ToString("yyyy-MM-dd") + " " + cutOffTime.ToString("hh\\:mm\\:ss")), Convert.ToDateTime(selecteddate.AddDays(1).ToString("yyyy-MM-dd") + " " + cutOffTime.ToString("hh\\:mm\\:ss")), true);
                        if (timeclock1 != null)
                        {
                            var data = GetJobTrackerListWithEndTimeAndNotRejected(userid, Convert.ToDateTime(selecteddate.ToString("yyyy-MM-dd") + " " + cutOffTime.ToString("hh\\:mm\\:ss")), Convert.ToDateTime(selecteddate.AddDays(1).ToString("yyyy-MM-dd") + " 00:00:00"));
                            if (data.Count > 0)
                            {
                                if (timeclock1.starttime.AddMinutes(30) < Convert.ToDateTime(data[0].StartTime))
                                    result = true;
                                if ((timeclock1.endtime.TimeOfDay < new TimeSpan(0, 30, 0) ? timeclock1.endtime : timeclock1.endtime.AddMinutes(-30)) > Convert.ToDateTime(data[data.Count - 1].EndTime))
                                    result = true;
                            }
                            else
                            {
                                result = true;
                            }
                        }
                    }

                }
                else
                {
                    TimeClock timeclock = new TimeClock();
                    timeclock = timeclock.GetStartEndTime(Convert.ToInt32(user.EmployeeNumber), Convert.ToDateTime(selecteddate.ToString("dd MMM yyyy") + " 00:00:00"), Convert.ToDateTime(selecteddate.ToString("dd MMM yyyy") + " 23:59:59"));

                    if (timeclock != null)
                    {
                        var data = GetJobTrackerListWithEndTimeAndNotRejected(userid,selecteddate);
                        if (data.Count > 0)
                        {
                            //TimeSetting timesetting = new TimeSetting();
                            //timesetting = timesetting.GetTimeSetting();
                            //if (timeclock.starttime.AddMinutes(timesetting.Interval) < Convert.ToDateTime(data[0].StartTime))
                            if (timeclock.starttime.AddMinutes(30) < Convert.ToDateTime(data[0].StartTime))
                                result = true;
                            //if (timeclock.endtime.AddMinutes(-1 * timesetting.Interval) > Convert.ToDateTime(data[data.Count - 1].EndTime))
                            if (timeclock.endtime.AddMinutes(-30) > Convert.ToDateTime(data[data.Count - 1].EndTime))
                                result = true;
                        }
                        else
                        {
                            result = true;
                        }
                    }
                }
            }
            return result;
        }
        protected void InitializeGridUser()
        {
            //int userid = Convert.ToInt32(Session["UserId"]);
            GetMyAccessRights();
            User user = new User();
            if (myAccessRights.CanAdd == true)
                linkBtnAddUser.Visible = true;
            else
                linkBtnAddUser.Visible = false;

            List<User> userlist = new List<User>();
            if (dropDownListDepartment.SelectedItem.Text == "All")
            {
                if (radioBtnListStatus.SelectedItem.Text == "All")
                    userlist = user.GetUserList();
                else
                    userlist = user.GetUserListByStatus(radioBtnListStatus.SelectedItem.Value.Trim());
            }
            else
            {
                if (radioBtnListStatus.SelectedItem.Text == "All")
                    userlist = user.GetUserList(Convert.ToInt32(dropDownListDepartment.SelectedItem.Value));
                else
                    userlist = user.GetUserListByDepartmentAndStatus(Convert.ToInt32(dropDownListDepartment.SelectedItem.Value), radioBtnListStatus.SelectedItem.Value.Trim());
            }
            gridViewUser.DataSource = userlist;
            gridViewUser.DataBind();
        }
 protected void InitializeModalDropDownUsers(int userid = 0)
 {
     User user = new User();
     List<User> userlist = new List<User>();
     if (userid == 0)
     {
         if (dropDownListDepartment.SelectedItem.Text == "All")
         {
             userlist = user.GetActiveUsersWithoutSupervisor();
         }
         else
         {
             userlist = user.GetActiveUsersWithoutSupervisor(Convert.ToInt32(dropDownListDepartment.SelectedItem.Value));
         }
     }
     else
     {
         user = user.GetUser(userid);
         userlist.Add(user);
     }
     modalDropDownUsers.DataSource = userlist;
     modalDropDownUsers.DataTextField = "fullname";
     modalDropDownUsers.DataValueField = "Id";
     modalDropDownUsers.DataBind();
 }
        protected void modalUserlinkBtnSubmit_Command(object sender, CommandEventArgs e)
        {
            bool haserror = false;
            int userid = Convert.ToInt32(Session["UserId"]);
            User user = new User();
            user = user.GetUser(userid);

            if (modalUserlinkChkBoxUpdate.Checked == true)
            {
                if (modalUserlinkTxtBoxOldPassword.Text.Trim() != user.Password.Trim())
                {
                    modalUserlinkLabelError.Text = "Invalid Old Password.";
                    modalUserlinkLabelError.Visible = true;
                    haserror = true;
                }
                else if (modalUserlinkTxtBoxPassword.Text.Trim() != modalUserlinkTxtBoxRetypePassword.Text.Trim())
                {
                    modalUserlinkLabelError.Text = "New password and retype-password does not match.";
                    modalUserlinkLabelError.Visible = true;
                    haserror = true;
                }
                if (haserror == false)
                {
                    user.Username = modalUserlinkTxtBoxUsername.Text.Trim();
                    user.Password = modalUserlinkTxtBoxPassword.Text.Trim();
                }
            }
            if (haserror == false)
            {
                user.Firstname = modalUserlinkTxtBoxFirstname.Text.Trim();
                user.Lastname = modalUserlinkTxtBoxLastname.Text.Trim();
                user.Email = modalUserlinkTxtBoxEmail.Text.Trim();
                user.Phone = modalUserlinkTxtBoxPhone.Text.Trim();
                user.Fax = modalUserlinkTxtBoxFax.Text.Trim();
                user.Mobile = modalUserlinkTxtBoxMobile.Text.Trim();
                user.LastUpdatedBy = userid;
                user.LastUpdateDate = DateTime.Now;
                user.Update(user);
            }
            else
            {
                this.programmaticUserlinkModalPopup.Show();
            }
        }
        private bool IsValidUserName(string username)
        {
            int userid = Convert.ToInt32(Session["UserId"]);
            bool result = true;
            User user = new User();

            user = user.GetUser(username);
            if (user != null)
            {
                var curUser = user.GetUser(userid);
                if (curUser.Username != user.Username)
                    result = false;
            }
            return result;
        }
        private void ComputeCost()
        {
            if (EndTime != null)
            {
                User user = new User();
                user = user.GetUser(Convert.ToInt32(UserId), Convert.ToDateTime(StartTime));
                Holiday holiday = new Holiday();
                OTRateSetting otRateSetting = new OTRateSetting();
                DateTime startdatetime = Convert.ToDateTime(StartTime);
                //int workingdays = holiday.GetWorkingDaysInMonth(user.Id, startdatetime);
                double normalRatePerMin = 0;
                //double normalRatePerMin = Convert.ToDouble((user.currentSalary/workingdays) / user.minsWorkPerDay);
                if (user.minsWorkPerDay < 490)
                    normalRatePerMin = Convert.ToDouble((user.currentSalary * 12) / (2080 * 60));
                else
                    normalRatePerMin = Convert.ToDouble((user.currentSalary * 12) / (2184 * 60));
                normalcost = normalmins * normalRatePerMin;
                otRateSetting = otRateSetting.GetOTRateSettingByDate(startdatetime);

                #region OT COMPUTATION
                otcost = 0;
                if (!user.noOTpay && otRateSetting != null)
                {
                    if (user.currentSalary >= otRateSetting.OTExemptedSalary) //User is Exempted from Salary
                    {
                        otcost = otmins * Convert.ToDouble((otRateSetting.ExemptedSalaryIncentive / 60));
                    }
                    else
                    {
                        if (user.shifting == false)
                        {
                            if (user.usePattern == true)
                            {
                                if (holiday.IsHoliday(startdatetime.Date))
                                {
                                    otcost = otmins * (normalRatePerMin * otRateSetting.OTSpecialRate);
                                }
                                else
                                {
                                    otcost = otmins * (normalRatePerMin * otRateSetting.OTNormalRate);
                                }
                            }
                            else
                            {
                                if (holiday.IsHoliday(startdatetime.Date) || user.isOfficeWorker && user.currentSpecialOffDay == (int)startdatetime.DayOfWeek)
                                {
                                    otcost = otmins * (normalRatePerMin * otRateSetting.OTSpecialRate);
                                }
                                else
                                {
                                    otcost = otmins * (normalRatePerMin * otRateSetting.OTNormalRate);
                                }
                            }
                        }
                        else //For Shifting Hours
                        {
                            TimeSpan stime = startdatetime.TimeOfDay;
                            TimeSpan etime = Convert.ToDateTime(EndTime).TimeOfDay;
                            TimeSpan cutoff = user.GetMyCutOfTime();

                            if (user.usePattern == true)
                            {
                                if (user.offPattern.Trim() != "")
                                {

                                    if (stime >= cutoff)
                                    {
                                        if (holiday.IsHoliday(startdatetime.Date))
                                        {
                                            otcost = otmins * (normalRatePerMin * otRateSetting.OTSpecialRate);
                                        }
                                        else
                                        {
                                            otcost = otmins * (normalRatePerMin * otRateSetting.OTNormalRate);
                                        }
                                    }
                                    else
                                    {
                                        if (holiday.IsHoliday(startdatetime.AddDays(-1).Date))
                                        {
                                            otcost = otmins * (normalRatePerMin * otRateSetting.OTSpecialRate);
                                        }
                                        else
                                        {
                                            otcost = otmins * (normalRatePerMin * otRateSetting.OTNormalRate);
                                        }
                                    }
                                }
                            }
                            else
                            {
                                if (stime >= cutoff)
                                {
                                    if (holiday.IsHoliday(startdatetime.Date) || (user.isOfficeWorker && user.currentSpecialOffDay == (int)startdatetime.DayOfWeek))
                                    {
                                        otcost = otmins * (normalRatePerMin * otRateSetting.OTSpecialRate);
                                    }
                                    else
                                    {
                                        otcost = otmins * (normalRatePerMin * otRateSetting.OTNormalRate);
                                    }
                                }
                                else
                                {
                                    if (holiday.IsHoliday(startdatetime.AddDays(-1).Date) || user.isOfficeWorker && user.currentSpecialOffDay == (int)startdatetime.AddDays(-1).DayOfWeek)
                                    {
                                        otcost = otmins * (normalRatePerMin * otRateSetting.OTSpecialRate);
                                    }
                                    else
                                    {
                                        otcost = otmins * (normalRatePerMin * otRateSetting.OTNormalRate);
                                    }
                                }
                            }
                        }
                    }
                    normalcost = Math.Round(normalcost, 2, MidpointRounding.AwayFromZero);
                    otcost = Math.Round(otcost, 2, MidpointRounding.AwayFromZero);
                }
                #endregion
            }
        }
        private void ComputeHours()
        {
            User user = new User();
            user = user.GetUser(Convert.ToInt32(UserId), Convert.ToDateTime(StartTime));
            if (EndTime != null)
            {
                DateTime startdatetime = Convert.ToDateTime(StartTime);
                TimeSpan stime = startdatetime.TimeOfDay;
                TimeSpan etime = Convert.ToDateTime(EndTime).TimeOfDay;
                int curday = (int)startdatetime.DayOfWeek;
                Holiday holiday = new Holiday();

                otcost = 0;
                normalcost = 0;

                double time = Convert.ToDateTime(EndTime).Subtract(Convert.ToDateTime(StartTime)).TotalMinutes;
                if (user.shifting == false)
                {
                    if (user.usePattern == true)
                    {
                        string[] pattern = user.offPattern.Split(',');
                        int patterndays = 0;
                        List<bool> isOffdays = new List<bool>();
                        for (int i = 0; i < pattern.Length; i++)
                        {
                            patterndays += Convert.ToInt32(pattern[i]);
                            for (int j = 0; j < Convert.ToInt32(pattern[i]); j++)
                            {
                                if (i % 2 == 0)
                                    isOffdays.Add(true);
                                else
                                    isOffdays.Add(false);
                            }
                        }
                        int offdayindex = 0;
                        offdayindex = Convert.ToInt32(Math.Floor((startdatetime.Date - user.patternStartDate.Date).TotalDays)) % patterndays;
                        if (TimeSpan.Parse(user.endTime) <= stime || holiday.IsHoliday(startdatetime.Date) || isOffdays[offdayindex] == true) //entry is OT
                        {
                            otmins = time;
                        }
                        else if ((etime == new TimeSpan(0, 0, 0) ? new TimeSpan(1, 0, 0, 0) : etime) > TimeSpan.Parse(user.endTime)) //entry is from normal time to OT
                        {
                            normalmins = TimeSpan.Parse(user.endTime).Subtract(stime).TotalMinutes;
                            otmins = (etime == new TimeSpan(0, 0, 0) ? new TimeSpan(1, 0, 0, 0) : etime).Subtract(TimeSpan.Parse(user.endTime)).TotalMinutes;
                        }
                        else //entry is within normal time
                        {
                            normalmins = time;
                        }
                    }
                    else
                    {
                        if (TimeSpan.Parse(user.endTime) <= stime || holiday.IsHoliday(startdatetime.Date) || curday == user.currentOffDay || curday == user.currentSpecialOffDay || curday == user.currentOptOffDay1 || curday == user.currentOptOffDay2 || curday == user.currentOptOffDay3 || curday == user.currentOptOffDay4) //entry is OT
                        {
                            otmins = time;
                        }
                        else if ((etime == new TimeSpan(0, 0, 0) ? new TimeSpan(1, 0, 0, 0) : etime) > TimeSpan.Parse(user.endTime)) //entry is from normal time to OT
                        {
                            normalmins = TimeSpan.Parse(user.endTime).Subtract(stime).TotalMinutes;
                            otmins = (etime == new TimeSpan(0, 0, 0) ? new TimeSpan(1, 0, 0, 0) : etime).Subtract(TimeSpan.Parse(user.endTime)).TotalMinutes;
                        }
                        else //entry is within normal time
                        {
                            normalmins = time;
                        }
                    }
                }
                else
                {
                    TimeSpan cutoff = user.GetMyCutOfTime();
                    if (user.usePattern == true)
                    {
                        string[] pattern = user.offPattern.Split(',');
                        int patterndays = 0;
                        List<bool> isOffdays = new List<bool>();
                        for (int i = 0; i < pattern.Length; i++)
                        {
                            patterndays += Convert.ToInt32(pattern[i]);
                            for (int j = 0; j < Convert.ToInt32(pattern[i]); j++)
                            {
                                if (i % 2 == 0)
                                    isOffdays.Add(true);
                                else
                                    isOffdays.Add(false);
                            }
                        }
                        int offdayindex = 0;

                        if (stime >= cutoff)
                        {
                            offdayindex = Convert.ToInt32(Math.Floor((startdatetime.Date - user.patternStartDate.Date).TotalDays)) % patterndays;
                            if (holiday.IsHoliday(startdatetime.Date) || isOffdays[offdayindex] == true)
                                otmins = time;
                            else
                                normalmins = time;
                        }
                        else
                        {
                            offdayindex = Convert.ToInt32(Math.Floor((startdatetime.AddDays(-1).Date - user.patternStartDate.Date).TotalDays)) % patterndays;
                            if (TimeSpan.Parse(user.endTime) <= stime || holiday.IsHoliday(startdatetime.AddDays(-1).Date) || isOffdays[offdayindex] == true)
                            {
                                otmins = time;
                            }
                            else if ((etime == new TimeSpan(0, 0, 0) ? new TimeSpan(1, 0, 0, 0) : etime) > TimeSpan.Parse(user.endTime))
                            {
                                normalmins = TimeSpan.Parse(user.endTime).Subtract(stime).TotalMinutes;
                                otmins = (etime == new TimeSpan(0, 0, 0) ? new TimeSpan(1, 0, 0, 0) : etime).Subtract(TimeSpan.Parse(user.endTime)).TotalMinutes;
                            }
                        }
                    }
                    else
                    {
                        if (stime >= cutoff)
                        {
                            if (holiday.IsHoliday(startdatetime.Date) || curday == user.currentOffDay || curday == user.currentSpecialOffDay || curday == user.currentOptOffDay1 || curday == user.currentOptOffDay2 || curday == user.currentOptOffDay3 || curday == user.currentOptOffDay4)
                                otmins = time;
                            else
                                normalmins = time;
                        }
                        else
                        {
                            curday = (int)startdatetime.AddDays(-1).DayOfWeek;
                            if (TimeSpan.Parse(user.endTime) <= stime || holiday.IsHoliday(startdatetime.AddDays(-1).Date) || curday == user.currentOffDay || curday == user.currentSpecialOffDay || curday == user.currentOptOffDay1 || curday == user.currentOptOffDay2 || curday == user.currentOptOffDay3 || curday == user.currentOptOffDay4) //entry is OT
                            {
                                otmins = time;
                            }
                            else if ((etime == new TimeSpan(0, 0, 0) ? new TimeSpan(1, 0, 0, 0) : etime) > TimeSpan.Parse(user.endTime))
                            {
                                normalmins = TimeSpan.Parse(user.endTime).Subtract(stime).TotalMinutes;
                                otmins = (etime == new TimeSpan(0, 0, 0) ? new TimeSpan(1, 0, 0, 0) : etime).Subtract(TimeSpan.Parse(user.endTime)).TotalMinutes;
                            }
                        }
                    }
                }
                double hr = Math.Truncate(time / 60);
                double min = time % 60;
                totalhours = hr == 0 && min == 0 ? "0 min" : (hr > 0 ? hr > 1 ? hr + " hrs" : hr + " hr" : "") + (hr > 0 && min > 0 ? ", " : "") + (min > 0 ? min > 1 ? min + " mins" : min + " min" : "");

                hr = Math.Truncate(normalmins / 60);
                min = normalmins % 60;
                normalhours = hr == 0 && min == 0 ? "0 min" : (hr > 0 ? hr > 1 ? hr + " hrs" : hr + " hr" : "") + (hr > 0 && min > 0 ? ", " : "") + (min > 0 ? min > 1 ? min + " mins" : min + " min" : "");

                hr = Math.Truncate(otmins / 60);
                min = otmins % 60;
                othours = hr == 0 && min == 0 ? "0 min" : (hr > 0 ? hr > 1 ? hr + " hrs" : hr + " hr" : "") + (hr > 0 && min > 0 ? ", " : "") + (min > 0 ? min > 1 ? min + " mins" : min + " min" : "");

            }
        }
 protected void GetMyAccessRights()
 {
     int userid = Convert.ToInt32(Session["UserId"]);
     User user = new User();
     user = user.GetUser(userid);
     TimeTracker.Model.Module module = new TimeTracker.Model.Module();
     module = module.GetModule("ReportLaborCost.aspx");
     myAccessRights = myAccessRights.GetRolesModuleAccess(Convert.ToInt32(user.RoleId), module.Id);
 }
        private bool HasTimeGap(int userid, DateTime selecteddate)
        {
            bool result = false;

            var data = GetJobTrackerListWithEndTimeAndNotRejected(userid, selecteddate);

            User user = new User();
            user = user.GetUser(userid,selecteddate);
            if (TimeSpan.Parse(user.startTime) > TimeSpan.Parse(user.endTime)) //for shifting hours check two time (12 midnight - cutofftime and cutooftime to 12 midnight)
            {
                int loop = 0;
                TimeSpan cutOfTime = user.GetMyCutOfTime();
                DateTime stime1 = new DateTime();
                stime1 = DateTime.Parse(selecteddate.Year + "-" + selecteddate.Month + "-" + selecteddate.Day + " 00:00:00");
                DateTime stime2 = new DateTime();
                for (int i = 0; i < data.Count; i++)
                {
                    if (Convert.ToDateTime(data[i].StartTime).TimeOfDay < cutOfTime)
                    {
                        if (stime1 != data[i].StartTime)
                        {
                            result = true;
                            break;
                        }
                        else
                        {
                            stime1 = Convert.ToDateTime(data[i].EndTime);
                        }
                    }
                    else
                    {
                        if (loop == 0)
                        {
                            stime2 = Convert.ToDateTime(data[i].EndTime);
                        }
                        else if (stime2 != data[i].StartTime)
                        {
                            result = true;
                            break;
                        }
                        else
                        {
                            stime2 = Convert.ToDateTime(data[i].EndTime);
                        }
                    }
                }
            }
            else
            {
                DateTime sTime = new DateTime();
                for (int i = 0; i < data.Count; i++)
                {
                    if (i == 0)
                    {
                        sTime = Convert.ToDateTime(data[i].EndTime);
                    }
                    else if (sTime != data[i].StartTime)
                    {
                        result = true;
                        break;
                    }
                    else
                    {
                        sTime = Convert.ToDateTime(data[i].EndTime);
                    }
                }
            }

            return result;
        }
        private bool IsValidUserName(string username)
        {
            int userid = 0;
            if (modalLabelUserId.Text.Trim() != "")
                userid = Convert.ToInt32(modalLabelUserId.Text);
            bool result = true;
            User user = new User();

            user = user.GetUser(username);
            if (user != null)
            {
                if (userid == 0)
                {
                    result = false;
                }
                else
                {
                    var curUser = user.GetUser(userid);
                    if (curUser.Username != user.Username)
                        result = false;
                }
            }
            return result;
        }
        protected void InitializeBottomDropDownPersonel()
        {
            int userid = Convert.ToInt32(Session["UserId"]);
            int roleid = Convert.ToInt32(Session["RoleId"]);
            RoleDepartmentAccess departmentAccess = new RoleDepartmentAccess();
            var departmentlist = departmentAccess.GetRoleDepartmentList(roleid);
            User user = new User();
            List<User> userlist = new List<User>();
            user = user.GetUser(userid);
            if (departmentlist.Count < 1)
            {
                userlist.Add(user);
                ddlBottomPersonel.Enabled = false;
            }
            else
            {
                int departmentid = Convert.ToInt32(ddlBottomDepartment.SelectedItem.Value);
                if (departmentid == 0)
                {
                    foreach (RoleDepartmentAccess r in departmentlist)
                    {
                        var ulist = user.GetUserList(r.DepartmentId);
                        userlist.AddRange(ulist);
                    }
                    userlist = userlist.Distinct().ToList();
                }
                else
                {
                    userlist = user.GetUserList(departmentid);
                }
                if (userlist.Count > 1)
                {
                    User alluser = new User();
                    alluser.fullname = "All";
                    alluser.Id = 0;
                    userlist.Insert(0, alluser);
                }
                ddlBottomPersonel.Enabled = true;
            }

            ddlBottomPersonel.DataSource = userlist;
            ddlBottomPersonel.DataTextField = "fullname";
            ddlBottomPersonel.DataValueField = "Id";
            ddlBottomPersonel.DataBind();
        }
        protected void InitializeGridUser()
        {
            //int userid = Convert.ToInt32(Session["UserId"]);
            GetMyAccessRights();
            User user = new User();

            List<User> userlist = new List<User>();
            if (dropDownListDepartment.SelectedItem.Text == "All")
            {
                userlist = user.GetUserListByStatus("Active");
            }
            else
            {
                userlist = user.GetUserListByDepartmentAndStatus(Convert.ToInt32(dropDownListDepartment.SelectedItem.Value),"Active");
            }
            gridViewUser.DataSource = userlist;
            gridViewUser.DataBind();
        }
        protected void modalBtnSubmit_Command(object sender, CommandEventArgs e)
        {
            //if (modalChkBoxUpdateRate.Checked == true) //Checks if starttime and endtime is in correct format
            //{
            //    TimeSpan starttime = new TimeSpan();
            //    TimeSpan endtime = new TimeSpan();
            //    if (TimeSpan.TryParse(modalTxtBoxStartTime.Text, out starttime))
            //    {

            //    }
            //    else
            //    {
            //        modalLabelError.Text = "Start Time not in valid format.";
            //        modalLabelError.Visible = true;
            //    }
            //    if (TimeSpan.TryParse(modalTxtBoxEndTime.Text, out endtime))
            //    {

            //    }
            //    else
            //    {
            //        modalLabelError.Text = "End Time not in valid format.";
            //        modalLabelError.Visible = true;
            //    }
            //}
            if (modalLabelError.Visible == true)
                this.programmaticModalPopup.Show();
            else
            {
                int userid = Convert.ToInt32(Session["UserId"]);
                User user = new User();
                if (modalLabelUserId.Text.Trim() != "") //Update
                {
                    user = user.GetUser(Convert.ToInt32(modalLabelUserId.Text));
                }
                user.Firstname = modalTxtBoxFirstname.Text.Trim();
                user.Lastname = modalTxtBoxLastname.Text.Trim();
                user.RoleId = Convert.ToInt32(modalDropDownRole.SelectedItem.Value);
                user.DepartmentId = Convert.ToInt32(modalDropDownDepartment.SelectedItem.Value);
                user.Username = modalTxtBoxUsername.Text.Trim();
                user.Password = modalTxtBoxPassword.Text.Trim();
                user.Email = modalTxtBoxEmail.Text.Trim();
                user.Phone = modalTxtBoxPhone.Text.Trim();
                user.Fax = modalTxtBoxFax.Text.Trim();
                user.Mobile = modalTxtBoxMobile.Text.Trim();
                user.LastUpdatedBy = userid;
                user.LastUpdateDate = DateTime.Now;
                user.EmployeeNumber = Convert.ToInt32(modalTxtBoxEmployeeNo.Text);
                user.Status = modalDropDownStatus.SelectedItem.Value;
                //user.Shift = modalRadBtnListShift.SelectedItem.Value.Trim();
                if (e.CommandArgument.ToString().Trim() == "Add")
                {
                    user.CreateDate = DateTime.Now;
                    user.CreatedBy = userid;
                    user.Insert(user);
                    user = user.GetLastInsertedUser(); //assign newly created user to variable user
                }
                else if (e.CommandArgument.ToString().Trim() == "Update")
                {
                    user.Update(user);
                }
                if (modalChkBoxUpdateRate.Checked == true) //User intends to update salary rate
                {
                    UserRateSchedule userRateSchedule = new UserRateSchedule();
                    userRateSchedule = userRateSchedule.GetUserScheduleRateByUserIdStartDate(user.Id, DateTime.Today); //Checks if there is already a schedule date with the same start date
                    if (userRateSchedule != null)
                    {
                        userRateSchedule.StartTime = modalTxtBoxStartTime.Text.Trim();
                        userRateSchedule.EndTime = modalTxtBoxEndTime.Text.Trim();
                        userRateSchedule.OffDay = Convert.ToInt32(modalDropDownOffDay.SelectedItem.Value);
                        userRateSchedule.SpecialOffDay = Convert.ToInt32(modalDropDownSpecialOffDay.SelectedItem.Value);
                        userRateSchedule.NoOTPay = modalChckBoxNoOTPay.Checked;
                        userRateSchedule.Update(userRateSchedule);
                        userRateSchedule.IsOfficeWorker = modalChckBoxOfficeWorker.Checked;
                        userRateSchedule.MinsBreak = Convert.ToInt32(modalTxtBoxBreakTimeMin.Text);
                    }
                    else
                    {
                        userRateSchedule = new UserRateSchedule();
                        UserRateSchedule prevUserRateSchedule = userRateSchedule.GetPreviousUserScheduleRateByUserIdLastUpdateDate(user.Id, DateTime.Today);
                        userRateSchedule.StartTime = modalTxtBoxStartTime.Text.Trim();
                        userRateSchedule.EndTime = modalTxtBoxEndTime.Text.Trim();
                        userRateSchedule.UserId = user.Id;
                        userRateSchedule.OffDay = Convert.ToInt32(modalDropDownOffDay.SelectedItem.Value);
                        userRateSchedule.SpecialOffDay = Convert.ToInt32(modalDropDownSpecialOffDay.SelectedItem.Value);
                        userRateSchedule.NoOTPay = modalChckBoxNoOTPay.Checked;
                        userRateSchedule.IsOfficeWorker = modalChckBoxOfficeWorker.Checked;
                        userRateSchedule.MinsBreak = Convert.ToInt32(modalTxtBoxBreakTimeMin.Text);
                        userRateSchedule.StartDate = DateTime.Today;
                        userRateSchedule.IsCurrentRate = true;

                        if (prevUserRateSchedule != null)
                        {
                            prevUserRateSchedule.EndDate = Convert.ToDateTime(DateTime.Today.AddDays(-1).ToString("dd MMM yyyy") + " 23:59:59");

                            prevUserRateSchedule.IsCurrentRate = false;
                            prevUserRateSchedule.Update(prevUserRateSchedule);
                        }

                        userRateSchedule.Insert(userRateSchedule);
                    }
                }
                InitializeGridUser();
                this.programmaticModalPopup.Hide();
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            string selectedTab = "";
            if (HttpContext.Current.Session["UserId"] == null || HttpContext.Current.Session["UserId"].ToString() == "0")
            {
                linkBtnUserName.Visible = false;
            }
            else
            {
                User user = new User();
                user = user.GetUser(Convert.ToInt32(HttpContext.Current.Session["UserId"]));
                linkBtnUserName.Text = "Welcome " + user.Firstname + " " + user.Lastname;
                linkBtnUserName.Text += " | ";
                linkBtnUserName.Visible = true;
                InitializeRepError();
            }
            Setup.Visible = hasAccess("Setup");
            Settings.Visible = hasAccess("Settings");
            Report.Visible = hasAccess("Report");

            //if (modalUserlinkChkBoxUpdate.Checked == false)
            //{
            //    ToggleReqField(false);
            //    cpeUserlink.ClientState = "true"; //Collapse
            //}
            //else
            //{
            //    ToggleReqField(true);
            //    cpeUserlink.ClientState = "false"; //Expand
            //}

            if (HttpContext.Current.Session["selectedTab"] != null)
            {
                selectedTab = HttpContext.Current.Session["selectedTab"].ToString();
            }

            if (HttpContext.Current.Session["siteSubHeader"] != null)
            {
                subHeader.Text = HttpContext.Current.Session["siteSubHeader"].ToString();
            }

            SetSelectedNavLink(selectedTab);
        }