using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Globalization;
using System.Threading;
using System.Reflection;
using System.Resources;
using System.IO;
/****************************************************************************************************************************
* Project Name    : TimeCheck                                                             Started Date  : 16-Feb-2008
* Module          : Payroll Re-Process                                                    Last Modified : 16-Feb-2008
* Programmer      : Kumuthini.L
* Current Storage : \\Angler56\Projects\Inprogress\SCREEN1206\code\Time_AttendanceApp
* BackUp          : \\windev\Projects\Inprogress\SCREEN1206\code\Time_AttendanceApp
****************************************************************************************************************************/
public partial class Transactions_PayrollReprocessPopup : Base.BasePage
{
    ResourceManager rm;
    // Create object for the Class MonthClosureEventData to use the methods that are used to interact with the Payroll Process 
    // related Tables in the Timecheck Database
    MonthClosureEventData objMonthClosure = new MonthClosureEventData();
    // Create object for the Class EmployeeEventData to use the methods that are used to interact with the Employee Details 
    // related Tables in the Timecheck Database
    EmployeeEventData objEmployeeEventData = new EmployeeEventData();
    ShiftAllocationEvendata objShiftAllocationEvendata = new ShiftAllocationEvendata();
    ShiftExchangeEventData objShiftExchangeEventData = new ShiftExchangeEventData();
    ShiftEvenData objShiftEvenData = new ShiftEvenData();
    HolidayEventData objHolidayEventData = new HolidayEventData();
    LeaveApplicationEventData objLeaveApplicationEventData = new LeaveApplicationEventData();
    LeaveEventData objLeaveEventData = new LeaveEventData();
    StringWriter strWriteXML = new StringWriter();
    DateTime gdtmStartDate, gdtmEndDate;
    int gintUserId, gintMonthCloseID;
    CultureInfo ci;
    DataSet dsEmployeeDetails = new DataSet();
    //Create a Dataset
    DataSet dsProcess = new DataSet();
    string strLevels = string.Empty;
    DataSet dsEmployee = new DataSet();
    string gstrEmployeeId = string.Empty, gstrDate = string.Empty;
    string ChkBoxIDs = string.Empty;
    protected override void Page_Load(object sender, EventArgs e)
    {
        // session checking and reset date format
        base.Page_Load(sender, e);
        //Session.LCID = 1033;
        loadcss();
        if (Session["Session_ActiveLanguage"] == null)
        {
            string str = "<script language=\"javascript\">";
            str = str + "opener.focus();";
            //str = str + "alert(opener.location+'?fl=1&sid=';";
            str = str + "opener.location.href = opener.location + '?fl=1&sid=" + Session.SessionID + "';";
            str = str + "self.close();";
            str = str + "</script>";
            Response.Write(str);
        }
        else
        {
            string source_Language;
            source_Language = Convert.ToString(Session["Session_ActiveLanguage"]);
            rm = new ResourceManager(source_Language, System.Reflection.Assembly.Load("App_GlobalResources"));
            ci = Thread.CurrentThread.CurrentCulture;
            aspnetForm.Attributes.CssStyle.Add("Direction", rm.GetString("Direction", ci));
            // Call the function LoadStrings to load the Label Names from the Resource Files
            LoadStrings(ci);
            string strSetAlert = "";
            strSetAlert = strSetAlert + "<script language='javascript'>";
            strSetAlert = strSetAlert + "SetAlertMessages_DeleteRestore('" + rm.GetString("Alert_ConfirmDelete") + "','" + rm.GetString("Alert_SelectItemsToDelete") + "','" + rm.GetString("Alert_ConfirmDeletePermanent") + "','" + rm.GetString("Alert_Areyousuretorestore") + "','" + rm.GetString("Alert_SelectItemsToRestore") + "','" + rm.GetString("Alert_SelectItemToForwarded") + "','" + rm.GetString("Alert_SelectItemToApproved") + "');";
            strSetAlert = strSetAlert + "</script>";
            Page.RegisterStartupScript("SetAlertMessages", strSetAlert);
        }
        // Get the Employee Id who have logged in from the Session Variable and store in Variable (i.e., gintUserId) for Audit Trail
        gintUserId = Int32.Parse(Session["EmpAutoID"].ToString());
        gintMonthCloseID = Int16.Parse(Request.QueryString["MonthCloseID"]);
        gdtmStartDate = DateTime.Parse(Request.QueryString["FromDate"]);
        gdtmEndDate = DateTime.Parse(Request.QueryString["ToDate"]);
        strLevels = Request.QueryString["LevelId"].ToString();
        if (!Page.IsPostBack)
        {
            Session["EmployeeIds"] = "";
            Session["SelectAllStatus"] = "False";
            // Function to fill Employee in Grid based on the Level and its Child
            BindEmployeeGrid();
        }
        btn_Back.Attributes.Add("onclick", "window.close();return false;");
        btn_Reprocess.Focus();
    }
    // Fill Employee in Grid based on the Level and its Child
    protected void BindEmployeeGrid()
    {
        //if (!IsPostBack)
        //{
        // Create a DataTable. 
        DataTable dtProcess = new DataTable("ReprocessEmployees");
        // Create a DataColumn and set various properties. 
        DataColumn dcProcess = new DataColumn();
        dcProcess.DataType = System.Type.GetType("System.String");
        dcProcess.ColumnName = "EmployeeId";
        // Add the column to the table. 
        dtProcess.Columns.Add(dcProcess);
        dsProcess.Tables.Add(dtProcess);
        dsProcess.Tables[0].WriteXml(strWriteXML);
        dsEmployee = objEmployeeEventData.Select_EmployeeDetailsForMonthClosure(gdtmEndDate.ToShortDateString(), strLevels, Convert.ToString(Session["UserGroupName"]), Convert.ToInt16(strLevels), gintMonthCloseID, gintUserId, 1, "BindGrid", strWriteXML.ToString(), "", "");
        Session["dsEmployee"] = dsEmployee;
        if (dsEmployee.Tables.Count > 0)
        {
            if (dsEmployee.Tables[0].Rows.Count > 0)
            {
                grv_Employee.DataSource = dsEmployee.Tables[0];
                grv_Employee.DataBind();
                grv_Employee.Visible = true;
                Session["TotalEmployees"] = dsEmployee.Tables[0].Rows.Count;
                CheckBox chkSelect = new CheckBox();
                chkSelect = (CheckBox)grv_Employee.HeaderRow.Cells[0].FindControl("checkall");
                chkSelect.Checked = Convert.ToBoolean(Session["SelectAllStatus"].ToString());
                foreach (GridViewRow gr in grv_Employee.Rows)
                {
                    CheckBox chkdeletethis = new CheckBox();
                    chkdeletethis = (CheckBox)gr.Cells[0].FindControl("deletethis");
                    if (chkSelect.Checked == true)
                    {
                        chkdeletethis.Checked = true;
                    }
                    else
                    {
                        chkdeletethis.Checked = false;
                    }
                }
            }
            else
            {
                lblStatus.Text = rm.GetString("Alert_NoRecords", ci);
                btn_Reprocess.Visible = false;
                return;
            }
        }
        //}
    }
    // Reprocess Button - Click Event
    protected void btn_Reprocess_Click(object sender, EventArgs e)
    {
        string strEmployees = string.Empty;
        string strEmployeeCodeIds = string.Empty;
        //CheckBox deleteChkBxItem = new CheckBox();
        //// Get the Employees from the Grid whose CheckBox is Checked
        //strEmployeeCodeIds = "'";
        //foreach(GridViewRow i in grv_Employee.Rows)
        //{
        //    //HtmlInputCheckBox deleteChkBxItem = (HtmlInputCheckBox)i.FindControl("deletethis");
        //    deleteChkBxItem = (CheckBox)i.Cells[0].FindControl("deletethis");
        //    if (deleteChkBxItem.Checked)
        //    {
        //        string strEmployeeCodeId = Convert.ToString(((Label)i.FindControl("lbl_EmpId")).Text);
        //        if (strEmployees == string.Empty)
        //        {
        //            strEmployees = strEmployeeCodeId;
        //            strEmployeeCodeIds += strEmployeeCodeId;
        //        }
        //        else
        //        {
        //            strEmployees = strEmployees + "," + strEmployeeCodeId;
        //            strEmployeeCodeIds = strEmployeeCodeIds + "','" + strEmployeeCodeId ;
        //        }
        //    }
        //}
        //strEmployeeCodeIds = strEmployeeCodeIds + "'";
        lblStatus.Text = "";
        lblStatus.Text = rm.GetString("PayrollProcess_Status", ci);
        strEmployees = Session["EmployeeIds"].ToString();
        strEmployeeCodeIds = Session["EmployeeIds"].ToString();
        string[] strEmployeeArray = strEmployees.Split(',');
        DataSet dsProcess = new DataSet();
        dsProcess = ToDataSet(strEmployeeArray);
        StringWriter strWriteXML = new StringWriter();
        dsProcess.Tables[0].WriteXml(strWriteXML);
        if (strEmployees != string.Empty)
        {
            //Check Non-Processed data exists
            string gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
            cls_Common objcls_Common = new cls_Common();
            //string strStartDate = objcls_Common.DateConvertion(gstrDateFormat, Request.QueryString["FromDate"]);
            //string strEndDate = objcls_Common.DateConvertion(gstrDateFormat, Request.QueryString["ToDate"]);
            string strStartDate = Request.QueryString["FromDate"];
            string strEndDate = Request.QueryString["ToDate"];
            DateTime dtmStartDate = DateTime.Parse(strStartDate);
            DateTime dtmEndDate = DateTime.Parse(strEndDate);
            string strLevels = Request.QueryString["LevelId"].ToString();
            string strResult = string.Empty;
            if (Convert.ToString(Session["Session_ActiveLanguage"]) == "Resources.Resource_EN")
            {
                strResult = objMonthClosure.ProcessDataCountEmployees(strLevels, dtmStartDate, dtmEndDate, strWriteXML.ToString(), Convert.ToString(Session["UserGroupName"]), Convert.ToInt16(strLevels));
            }
            else if (Convert.ToString(Session["Session_ActiveLanguage"]) == "Resources.Resource_AR")
            {
                strResult = objMonthClosure.ProcessDataCountEmployees_Arabic(strLevels, dtmStartDate, dtmEndDate, strWriteXML.ToString(), Convert.ToString(Session["UserGroupName"]), Convert.ToInt16(strLevels));
            }
            //strResult = string.Empty;
            if (strResult == string.Empty)
            {
                // Call the ReProcess Method to process the Employees Data
                //ReProcess(strEmployees);
                // Call the Payroll Method to calculate Payroll Details for the selected Employees
                PayrollProcess(strWriteXML.ToString());
            }
            else
            {
                if (strResult == "Non Processed Manual Entry Data Exists")
                {
                    lblStatus.Text = rm.GetString("PayRollNonProcess", ci);
                    return;
                }
                else
                {
                    lblStatus.Text = strResult;
                    return;
                }
            }
        }
        else
        {
            lblStatus.Text = rm.GetString("ShiftAllocation_SelectedEmployees", ci);
            return;
        }
        //string strScript = "<script language='javascript' type='text/javascript'>";
        //strScript += "alert('Data have been reprocessed Successfully for the selected employees');window.close();";
        //strScript += " </script>";
    }
    /// <summary>
    /// GetShiftId Function is used to get the Shift Id for the particular Employee
    /// </summary>
    /// <param name="strEmployee">Employee Id</param>
    /// <param name="dtmDate">Date</param>
    /// <returns></returns>
    /// 
    private int GetShiftId(string strEmployee, DateTime dtmDate)
    {
        int intShiftId = 0;
        DataTable dtTempShift = new DataTable();
        dtTempShift = objShiftExchangeEventData.SelectTemporaryShiftId(strEmployee, dtmDate.Year.ToString(), dtmDate.Month.ToString(), dtmDate.Day.ToString());
        DataTable dtActualShift = new DataTable();
        dtActualShift = objShiftExchangeEventData.SelectPermanentShiftId(strEmployee, dtmDate.Year.ToString(), dtmDate.Month.ToString(), dtmDate.Day.ToString());
        if (dtTempShift.Rows.Count > 0)
        {
            if (dtTempShift.Rows[0][0] != DBNull.Value && dtTempShift.Rows[0][0].ToString() != string.Empty)
            {
                intShiftId = int.Parse(dtTempShift.Rows[0][0].ToString());
            }
        }
        if (intShiftId == 0)
        {
            if (dtActualShift.Rows.Count > 0)
            {
                if (dtActualShift.Rows[0][0] != DBNull.Value && dtActualShift.Rows[0][0].ToString() != string.Empty)
                {
                    intShiftId = int.Parse(dtActualShift.Rows[0][0].ToString());
                }
            }
        }
        return (intShiftId);
    }

    private void loadcss()
    {
        CultureInfo ci;
        string source_Language;
        source_Language = Convert.ToString(Session["Session_ActiveLanguage"]);
        rm = new ResourceManager(source_Language, System.Reflection.Assembly.Load("App_GlobalResources"));
        ci = Thread.CurrentThread.CurrentCulture;
        //if Standard Demo
        htmlprocessPop.Attributes.Add("dir", rm.GetString("Direction", ci));
        if (source_Language == "Resources.Resource_AR")
        {
            stylebootstrap.Href = "../bootstrap/css/bootstrap-rtl.min.css";
            stylefontawesome.Href = "../bootstrap/font-awesome/css/font-awesome-rtl.css";
            styleAdminLTE.Href = "../dist/css/AdminLTE.min-rtl.css";
            stylecustom.Href = "../dist/css/custom-rtl.css";
            stylefonts.Href = "../dist/css/fonts.css";
            styleselect2.Href = "../plugins/select2/select2.min-rtl.css";
            styleGrid.Href = "../bootstrap/css/GridView-rtl.css";
            styleAutocomp.Href = "../bootstrap/css/autoCompleteNew-rtl.css";
        }
        else
        {
            //htmlGetEmail.Attributes.Add("dir", "rtl");
            //stylebootstrap.Href = "../bootstrap/css/bootstrap-rtl.min.css";
            //stylefontawesome.Href = "../bootstrap/font-awesome/css/font-awesome-rtl.css";
            //styleAdminLTE.Href = "../dist/css/AdminLTE.min-rtl.css";
            //stylecustom.Href = "../dist/css/custom-rtl.css";
            //styleselect2.Href = "../plugins/select2/select2.min-rtl.css";
            //styleGrid.Href = "../bootstrap/css/GridView-rtl.css";
            //stylefonts.Href = "../dist/css/fonts.css";
            stylebootstrap.Href = "../bootstrap/css/bootstrap.min.css";
            stylefontawesome.Href = "../bootstrap/font-awesome/css/font-awesome.css";
            styleAdminLTE.Href = "../dist/css/AdminLTE.min.css";
            stylecustom.Href = "../dist/css/custom.css";
            styleGrid.Href = "../bootstrap/css/GridView.css";
            stylefonts.Href = "../dist/css/fonts.css";
            styleselect2.Href = "../plugins/select2/select2.min-rtl.css";
            styleAutocomp.Href = "../bootstrap/css/autoCompleteNew.css";
        }
    }
    private void ReProcess(string strEmployees)
    {
        int iLoop = 0;
        string[] strEmployeeArray = strEmployees.Split(',');
        int intEmployeeArrayLengh = strEmployeeArray.Length;
        DataSet dsShift = new DataSet();
        DataTable dtShift = new DataTable();
        string gstrAttendance = string.Empty;
        DateTime dtmWorkHrs = new DateTime();
        try
        {
            for (iLoop = 0; iLoop < intEmployeeArrayLengh; iLoop++)
            {
                // Get the UnProcessed Data for the duration Start Date and End Date
                DataTable dtUnProcessedData = new DataTable();
                dtUnProcessedData = objMonthClosure.SelectUnProcessedData("P", strEmployeeArray[iLoop], gdtmStartDate.ToShortDateString(), gdtmEndDate.ToShortDateString());
                foreach (DataRow drUnProcessedData in dtUnProcessedData.Rows)
                {
                    DateTime dtmDate = new DateTime();
                    dtmDate = DateTime.Parse(drUnProcessedData["Date"].ToString());
                    // Get Shift ID for appropriate Employee and Date
                    int intShiftId = 0;
                    intShiftId = GetShiftId(drUnProcessedData["Employee_Code_Id"].ToString(), dtmDate);
                    dsShift = objShiftEvenData.SelectShiftById(intShiftId);
                    dtShift = dsShift.Tables[0];
                    if (dtShift.Rows.Count > 0)
                    {
                        if (dtShift.Rows[0]["Shift_TotalWorkingHours"] != DBNull.Value && dtShift.Rows[0]["Shift_TotalWorkingHours"].ToString() != string.Empty)
                        {
                            dtmWorkHrs = Convert.ToDateTime(dtShift.Rows[0]["Shift_TotalWorkingHours"]);
                        }
                    }
                    DataTable dtHoliday = new DataTable();
                    dtHoliday = objHolidayEventData.CheckDateForHoliday(dtmDate.ToShortDateString(), drUnProcessedData["Employee_Code_Id"].ToString());
                    // If Employee Attendance is Present
                    if (drUnProcessedData["Attendance"].ToString() == "Present")
                    {
                        string strFirstIn = string.Empty, strLastOut = string.Empty, strDate = string.Empty;
                        string strLateInTime = "00:00", strEarlyExit = "00:00";
                        double dLateInMins = 0, dEarlyOutMins = 0, dLateExitMins = 0;
                        strDate = dtmDate.ToShortDateString();
                        if (drUnProcessedData["InTime"] != DBNull.Value && drUnProcessedData["InTime"].ToString() != string.Empty && drUnProcessedData["OutTime"] != DBNull.Value && drUnProcessedData["OutTime"].ToString() != string.Empty && drUnProcessedData["InTime"].ToString() != "0" && drUnProcessedData["OutTime"].ToString() != "0" && drUnProcessedData["InTime"].ToString() != "00:00" && drUnProcessedData["OutTime"].ToString() != "00:00")
                        {
                            strFirstIn = drUnProcessedData["InTime"].ToString();
                            strLastOut = drUnProcessedData["OutTime"].ToString();
                            TimeSpan tsFirstInTime = DateTime.Parse(strFirstIn.ToString()).TimeOfDay;
                            TimeSpan tsLastOutTime = DateTime.Parse(strLastOut.ToString()).TimeOfDay;
                            // Get actual Working hours,shift in time and shift out time from shift table
                            //int WorkHrs, ShftGraceInTime = 0, ShftGraceOutTime = 0;
                            string strShftGraceOutTime = "00:00", strShftGraceInTime = "00:00", strShftMinOTTime = "00:00", strShftMaxOTTime = "00:00";
                            string ActualShfInTime = string.Empty, ActualShfOutTime = string.Empty;
                            string strActualLunchStartTime = "00:00", strActualLunchEndTime = "00:00";
                            int ShftWorkOverTime = 0, ShftWeekOffOverTime = 0, ShftHolyOverTime = 0;
                            int TotalHrs = 0, Totalmin = 0;
                            if (dtShift.Rows.Count > 0)
                            {
                                if (dtShift.Rows[0]["Shift_TotalWorkingHours"] != DBNull.Value && dtShift.Rows[0]["Shift_TotalWorkingHours"].ToString() != string.Empty)
                                {
                                    dtmWorkHrs = Convert.ToDateTime(dtShift.Rows[0]["Shift_TotalWorkingHours"]);
                                    TotalHrs = dtmWorkHrs.Hour;
                                    Totalmin = dtmWorkHrs.Minute;
                                }
                                if (dtShift.Rows[0]["Shift_StartTime"] != DBNull.Value && dtShift.Rows[0]["Shift_StartTime"].ToString() != string.Empty)
                                {
                                    ActualShfInTime = dtShift.Rows[0]["Shift_StartTime"].ToString();
                                }
                                if (dtShift.Rows[0]["Shift_EndTime"] != DBNull.Value && dtShift.Rows[0]["Shift_EndTime"].ToString() != string.Empty)
                                {
                                    ActualShfOutTime = dtShift.Rows[0]["Shift_EndTime"].ToString();
                                }
                                if (dtShift.Rows[0]["Shift_BreakStartTime2"] != DBNull.Value && dtShift.Rows[0]["Shift_BreakStartTime1"].ToString() != string.Empty)
                                {
                                    strActualLunchStartTime = dtShift.Rows[0]["Shift_BreakStartTime1"].ToString();
                                }
                                if (dtShift.Rows[0]["Shift_BreakEndTime2"] != DBNull.Value && dtShift.Rows[0]["Shift_BreakEndTime1"].ToString() != string.Empty)
                                {
                                    strActualLunchEndTime = dtShift.Rows[0]["Shift_BreakEndTime1"].ToString();
                                }
                                if (dtShift.Rows[0]["Shift_GraceInTime"] != DBNull.Value && dtShift.Rows[0]["Shift_GraceInTime"].ToString() != string.Empty)
                                {
                                    strShftGraceInTime = dtShift.Rows[0]["Shift_GraceInTime"].ToString();
                                }
                                if (dtShift.Rows[0]["Shift_GraceOutTime"] != DBNull.Value && dtShift.Rows[0]["Shift_GraceOutTime"].ToString() != string.Empty)
                                {
                                    strShftGraceOutTime = dtShift.Rows[0]["Shift_GraceOutTime"].ToString();
                                }
                                if (dtShift.Rows[0]["Shift_WorkingDay_OverTime"] != DBNull.Value && dtShift.Rows[0]["Shift_WorkingDay_OverTime"].ToString() != string.Empty)
                                {
                                    ShftWorkOverTime = Convert.ToInt32(dtShift.Rows[0]["Shift_WorkingDay_OverTime"]);
                                }
                                if (dtShift.Rows[0]["Shift_WeekOff_OverTime"] != DBNull.Value && dtShift.Rows[0]["Shift_WeekOff_OverTime"].ToString() != string.Empty)
                                {
                                    ShftWeekOffOverTime = Convert.ToInt32(dtShift.Rows[0]["Shift_WeekOff_OverTime"]);
                                }
                                if (dtShift.Rows[0]["Shift_HoliDay_OverTime"] != DBNull.Value && dtShift.Rows[0]["Shift_HoliDay_OverTime"].ToString() != string.Empty)
                                {
                                    ShftHolyOverTime = Convert.ToInt32(dtShift.Rows[0]["Shift_HoliDay_OverTime"]);
                                }
                                if (dtShift.Rows[0]["Shift_MinTimeOT"] != DBNull.Value && dtShift.Rows[0]["Shift_MinTimeOT"].ToString() != string.Empty)
                                {
                                    strShftMinOTTime = dtShift.Rows[0]["Shift_MinTimeOT"].ToString();
                                }
                                if (dtShift.Rows[0]["Shift_MaxTimeOT"] != DBNull.Value && dtShift.Rows[0]["Shift_MaxTimeOT"].ToString() != string.Empty)
                                {
                                    strShftMaxOTTime = dtShift.Rows[0]["Shift_MaxTimeOT"].ToString();
                                }
                            }
                            // Calculate the Total working hours for the Employee
                            string strTotalWorkHours = string.Empty;
                            DataTable dtClockDetails = new DataTable();
                            dtClockDetails = objMonthClosure.GetClockDetails(drUnProcessedData["SwipeCardNo"].ToString(), strDate);
                            double dTotalMinsWorked = 0;
                            if (dtClockDetails.Rows.Count > 0)
                            {
                                for (int k = 0; k < dtClockDetails.Rows.Count; k++)
                                {
                                    if ((dtClockDetails.Rows[k]["Clk_InDate"] != DBNull.Value) && (dtClockDetails.Rows[k]["Clk_InTime"] != DBNull.Value) && (dtClockDetails.Rows[k]["Clk_OutDate"] != DBNull.Value) && (dtClockDetails.Rows[k]["Clk_OutTime"] != DBNull.Value))
                                    {
                                        if ((dtClockDetails.Rows[k]["Clk_InDate"].ToString() != string.Empty) && (dtClockDetails.Rows[k]["Clk_InTime"].ToString() != string.Empty) && (dtClockDetails.Rows[k]["Clk_OutDate"].ToString() != string.Empty) && (dtClockDetails.Rows[k]["Clk_OutTime"].ToString() != string.Empty))
                                        {
                                            string strInDateTime = DateTime.Parse(dtClockDetails.Rows[k]["Clk_InDate"].ToString()).ToShortDateString() + " " + DateTime.Parse(dtClockDetails.Rows[k]["Clk_InTime"].ToString()).ToShortTimeString();
                                            string strOutDateTime = DateTime.Parse(dtClockDetails.Rows[k]["Clk_OutDate"].ToString()).ToShortDateString() + " " + DateTime.Parse(dtClockDetails.Rows[k]["Clk_OutTime"].ToString()).ToShortTimeString();
                                            DateTime dtmInDateTime = DateTime.Parse(strInDateTime);
                                            DateTime dtmOutDateTime = DateTime.Parse(strOutDateTime);
                                            dTotalMinsWorked += double.Parse(dtmOutDateTime.Subtract(dtmInDateTime).TotalMinutes.ToString());
                                        }
                                    }
                                }
                            }
                            double dTotHrs = Math.Floor(dTotalMinsWorked / 60);
                            double dTotMins = dTotalMinsWorked % 60;
                            int iTotHrs = Convert.ToInt32(dTotHrs);
                            int iTotMins = Convert.ToInt32(dTotMins);
                            if (Convert.ToInt32(dTotMins) >= 60)
                            {
                                iTotMins = Convert.ToInt32(dTotMins) % 60;
                                iTotHrs += Convert.ToInt32(dTotMins) / 60;
                            }
                            strTotalWorkHours = iTotHrs.ToString("00") + ":" + iTotMins.ToString("00");
                            // Calculate Less Hours Work,Extra Hours Work and Over Time
                            string strHrsOT = "0", strNorOT = "0", strWeekOffOT = "0", strHoliOT = "0";
                            string strLessHours = "0", strExtraHours = "0";
                            double dShftHolyOverTime = 0, dShftWeekOffOverTime = 0, dShftWorkingDayOverTime = 0, dOT = 0;
                            if (dtHoliday.Rows.Count > 0)
                            {
                                if (ShftHolyOverTime != 0)
                                {
                                    dShftHolyOverTime = dTotalMinsWorked * ShftHolyOverTime;
                                    double dHolyTotHrs = Math.Floor(dShftHolyOverTime / 60);
                                    double dHolyTotMins = dShftHolyOverTime % 60;
                                    int iHolyTotHrs = Convert.ToInt32(dHolyTotHrs);
                                    int iHolyTotMins = Convert.ToInt32(dHolyTotMins);
                                    if (Convert.ToInt32(dHolyTotMins) >= 60)
                                    {
                                        iHolyTotMins = Convert.ToInt32(dHolyTotMins) % 60;
                                        iHolyTotHrs += Convert.ToInt32(dHolyTotMins) / 60;
                                    }
                                    strHoliOT = iHolyTotHrs.ToString("00") + ":" + iHolyTotMins.ToString("00");
                                }
                            }
                            else
                            {
                                int count = 0;
                                count = CheckAdditionalWeekOff(dtmDate, drUnProcessedData["SwipeCardNo"].ToString());
                                // Calculate Weekly Off OT
                                if (intShiftId == -1 || count == 1)
                                {
                                    if (ShftWeekOffOverTime != 0)
                                    {
                                        dShftWeekOffOverTime = dTotalMinsWorked * ShftWeekOffOverTime;
                                        double dWeekTotHrs = Math.Floor(dShftWeekOffOverTime / 60);
                                        double dWeekTotMins = dShftWeekOffOverTime % 60;
                                        int iWeekTotHrs = Convert.ToInt32(dWeekTotHrs);
                                        int iWeekTotMins = Convert.ToInt32(dWeekTotMins);
                                        if (Convert.ToInt32(dWeekTotMins) >= 60)
                                        {
                                            iWeekTotMins = Convert.ToInt32(dWeekTotMins) % 60;
                                            iWeekTotHrs += Convert.ToInt32(dWeekTotMins) / 60;
                                        }
                                        strWeekOffOT = iWeekTotHrs.ToString("00") + ":" + iWeekTotMins.ToString("00");
                                    }
                                    intShiftId = -1;
                                }
                                else if (intShiftId > 0)
                                {
                                    // Check for Permission
                                    DataTable dtPermission = new DataTable();
                                    dtPermission = objMonthClosure.CheckPermission(drUnProcessedData["SwipeCardNo"].ToString(), strDate);
                                    DateTime dtmPermissionFromDateTime = new DateTime();
                                    DateTime dtmPermissionToDateTime = new DateTime();
                                    if (dtPermission.Rows.Count > 0)
                                    {
                                        dtmPermissionFromDateTime = DateTime.Parse(dtPermission.Rows[0]["Permission_FromTime"].ToString());
                                        dtmPermissionToDateTime = DateTime.Parse(dtPermission.Rows[0]["Permission_ToTime"].ToString());
                                    }
                                    // Check for Half a Day Leave
                                    DataTable dtLeave = new DataTable();
                                    dtLeave = objMonthClosure.CheckLeave(drUnProcessedData["SwipeCardNo"].ToString(), strDate);
                                    // CALCULATE LATE INTIME
                                    string strShiftStartTime = string.Empty;
                                    // If there is permission during the Shift Start Time, then Set Start Time as
                                    // Permission To Time and Calculate Late. Else check if there is First half Leave
                                    // Late should not be calculated during Permission Hours or First half Leave.
                                    // If Half a Day Leave Present
                                    if (dtLeave.Rows.Count > 0)
                                    {
                                        // Check for First half Leave. If so then set the Shift Start time as Lunch End Time
                                        if (dtLeave.Rows[0]["Leave_SessionFrom"].ToString() == "First half")
                                        {
                                            strShiftStartTime = dtShift.Rows[0]["Shift_SecondHalf_StartTime"].ToString();
                                        }
                                    }
                                    if (strShiftStartTime == string.Empty)
                                    {
                                        // Check whether there is Permission during the Shift Start Time
                                        if (dtPermission.Rows.Count > 0)
                                        {
                                            DateTime dtmShiftStartDateTime = new DateTime();
                                            string strShiftStartDateTime = dtmDate.ToShortDateString() + " " + ActualShfInTime;
                                            dtmShiftStartDateTime = DateTime.Parse(strShiftStartDateTime);
                                            if (DateTime.Parse(dtPermission.Rows[0]["Permission_ToTime"].ToString()).ToShortTimeString() == DateTime.Parse(dtShift.Rows[0]["Shift_FirstHalf_EndTime"].ToString()).ToShortTimeString())
                                            {
                                                strShiftStartTime = dtShift.Rows[0]["Shift_SecondHalf_StartTime"].ToString();
                                            }
                                            else if (DateTime.Parse(dtPermission.Rows[0]["Permission_ToTime"].ToString()).ToShortTimeString() == DateTime.Parse(strActualLunchStartTime).ToShortTimeString())
                                            {
                                                strShiftStartTime = strActualLunchEndTime;
                                            }
                                            else
                                            {
                                                if (dtmShiftStartDateTime >= dtmPermissionFromDateTime && dtmShiftStartDateTime <= dtmPermissionToDateTime)
                                                {
                                                    strShiftStartTime = dtPermission.Rows[0]["Permission_ToTime"].ToString();
                                                }
                                                else
                                                {
                                                    // Nothing
                                                }
                                            }
                                        }
                                    }
                                    if (strShiftStartTime == string.Empty)
                                    {
                                        strShiftStartTime = ActualShfInTime;
                                    }
                                    TimeSpan tsActualShiftStartTime = DateTime.Parse(strShiftStartTime).TimeOfDay;
                                    TimeSpan tsShftStartTimePlusGrace = new TimeSpan();
                                    TimeSpan tsLateIn = new TimeSpan();
                                    // Add Grace In with Shift Start Time
                                    tsShftStartTimePlusGrace = tsActualShiftStartTime.Add(DateTime.Parse(strShftGraceInTime).TimeOfDay);
                                    tsFirstInTime = DateTime.Parse(tsFirstInTime.ToString().Substring(0, 5)).TimeOfDay;
                                    //Calculate Late In, if Actual InTime is greater that Shift Start Time
                                    if (tsFirstInTime > tsShftStartTimePlusGrace)
                                    {
                                        tsLateIn = tsFirstInTime.Subtract(tsActualShiftStartTime);
                                        strLateInTime = tsLateIn.ToString().Substring(0, 5);
                                        tsLateIn = DateTime.Parse(strLateInTime).TimeOfDay;
                                        dLateInMins = double.Parse(tsLateIn.TotalMinutes.ToString());
                                    }
                                    // CALCULATE EARLY EXIT
                                    string strShiftEndTime = string.Empty;
                                    // If there is permission during the Shift End Time, then Set End Time as
                                    // Permission From Time and Calculate Early Out. Else check for Second half Leave.
                                    // Early Out should not be calculated during Permission Hours or Second half Leave.
                                    // If Half a Day Leave Present
                                    if (dtLeave.Rows.Count > 0)
                                    {
                                        // Check for Second half Leave. If so then set the Shift End time as Lunch Start Time
                                        if (dtLeave.Rows[0]["Leave_SessionFrom"].ToString() == "Second half")
                                        {
                                            strShiftEndTime = dtShift.Rows[0]["Shift_FirstHalf_EndTime"].ToString();
                                        }
                                    }
                                    if (strShiftEndTime == string.Empty)
                                    {
                                        if (dtPermission.Rows.Count > 0)
                                        {
                                            DateTime dtmShiftEndDateTime = new DateTime();
                                            string strShiftEndDateTime = dtmDate.ToShortDateString() + " " + ActualShfOutTime;
                                            dtmShiftEndDateTime = DateTime.Parse(strShiftEndDateTime);
                                            if (dtmShiftEndDateTime >= dtmPermissionFromDateTime && dtmShiftEndDateTime <= dtmPermissionToDateTime)
                                            {
                                                strShiftEndTime = dtPermission.Rows[0]["Permission_FromTime"].ToString();
                                            }
                                            else
                                            {
                                                strShiftEndTime = ActualShfOutTime;
                                            }
                                        }
                                        else
                                        {
                                            strShiftEndTime = ActualShfOutTime;
                                        }
                                    }
                                    TimeSpan tsActualShiftEndTime = DateTime.Parse(strShiftEndTime).TimeOfDay;
                                    TimeSpan tsShftEndTimeMinusGrace = new TimeSpan();
                                    TimeSpan tsEarlyOut = new TimeSpan();
                                    // Subtract Shift End Time by Grace Out
                                    tsShftEndTimeMinusGrace = tsActualShiftEndTime.Subtract(DateTime.Parse(strShftGraceOutTime).TimeOfDay);
                                    tsLastOutTime = DateTime.Parse(tsLastOutTime.ToString().Substring(0, 5)).TimeOfDay;
                                    //Calculate Early Out, if Actual OutTime is lesser that Shift End Time
                                    if (tsLastOutTime < tsShftEndTimeMinusGrace)
                                    {
                                        tsEarlyOut = tsActualShiftEndTime.Subtract(tsLastOutTime);
                                        strEarlyExit = tsEarlyOut.ToString().Substring(0, 5);
                                        tsEarlyOut = DateTime.Parse(strEarlyExit).TimeOfDay;
                                        dEarlyOutMins = double.Parse(tsEarlyOut.TotalMinutes.ToString());
                                    }
                                    // Calculate Less Hours Work and Extra Hours Work
                                    double dTotalWorkMins, dActWorkMins = 0, dMinLess;
                                    if (strTotalWorkHours != ":")
                                    {
                                        if (dTotHrs == 24 && iTotMins != 0)
                                        {
                                            // Nothing
                                        }
                                        else
                                        {
                                            if (dTotHrs >= 0 && dTotHrs <= 24)
                                            {
                                                TimeSpan ActWorkHrs = DateTime.Parse(strTotalWorkHours.ToString()).TimeOfDay;
                                                dActWorkMins = double.Parse(ActWorkHrs.TotalMinutes.ToString());
                                            }
                                        }
                                    }
                                    dTotalWorkMins = (TotalHrs * 60) + Totalmin;
                                    // Calculate Less hours work
                                    if (dActWorkMins < dTotalWorkMins)
                                    {
                                        dMinLess = dTotalWorkMins - dActWorkMins;
                                        double dLessHrs = Math.Floor(dMinLess / 60);
                                        double dLessMins = dMinLess % 60;
                                        int iLessHrs = Convert.ToInt32(dLessHrs);
                                        int iLessMins = Convert.ToInt32(dLessMins);
                                        strLessHours = iLessHrs.ToString() + ":" + iLessMins.ToString();
                                    }
                                    // Calculate Extra hours working for the Employee and Over Time
                                    if (tsLastOutTime > tsActualShiftEndTime)
                                    {
                                        TimeSpan tsLateExit = new TimeSpan();
                                        TimeSpan tsShftMaxOTTime = new TimeSpan();
                                        TimeSpan tsShftMinOTTime = new TimeSpan();
                                        tsLateExit = tsLastOutTime.Subtract(tsActualShiftEndTime);
                                        strExtraHours = tsLateExit.ToString().Substring(0, 5);
                                        tsLateExit = DateTime.Parse(strExtraHours).TimeOfDay;
                                        dLateExitMins = double.Parse(tsLateExit.TotalMinutes.ToString());
                                        if (strShftMinOTTime != "00:00")
                                        {
                                            tsShftMinOTTime = DateTime.Parse(strShftMinOTTime).TimeOfDay;
                                        }
                                        if (strShftMaxOTTime != "00:00")
                                        {
                                            tsShftMaxOTTime = DateTime.Parse(strShftMaxOTTime).TimeOfDay;
                                        }
                                        // Normal OT
                                        string strNormOTFlag = "N";
                                        if (tsShftMinOTTime <= tsLateExit && tsLateExit <= tsShftMaxOTTime)
                                        {
                                            dLateExitMins = Double.Parse(tsLateExit.TotalMinutes.ToString());
                                            strNormOTFlag = "Y";
                                        }
                                        else if (tsLateExit >= tsShftMaxOTTime)
                                        {
                                            dLateExitMins = Double.Parse(tsShftMaxOTTime.TotalMinutes.ToString());
                                            strNormOTFlag = "Y";
                                        }
                                        if (strNormOTFlag == "Y")
                                        {
                                            strNorOT = ConvertMinutesToHoursMins(dLateExitMins);
                                            dOT = dOT + dLateExitMins;
                                        }
                                        // Hrs OT
                                        //else if (iExtraHrs >= strShftMinOTTime)
                                        //{
                                        //    strHrsOT = iExtraHrs.ToString("00") + ":" + iExtraMins.ToString("00");
                                        //    dOT = dOT + dMinExtra;
                                        //}
                                    }
                                }
                            }
                            double dOTmins = 0;
                            dOTmins = dShftHolyOverTime + dShftWeekOffOverTime + dOT;
                            if (drUnProcessedData["OT_Eligible"] != DBNull.Value)
                            {
                                if (drUnProcessedData["OT_Eligible"].ToString() == "0")
                                {
                                    strHrsOT = "0"; strNorOT = "0"; strWeekOffOT = "0"; strHoliOT = "0";
                                    dOTmins = 0;
                                }
                            }
                            // Update the All the calculated data to the Processed Data table
                            objMonthClosure.UpdateProcessedData(strFirstIn, strLastOut, intShiftId, strTotalWorkHours, strHrsOT, strNorOT, strWeekOffOT, strHoliOT, strEarlyExit, strLateInTime, dtmWorkHrs.ToShortTimeString(), strLessHours, strExtraHours, Convert.ToSingle(dLateInMins.ToString()), Convert.ToSingle(dEarlyOutMins.ToString()), dOTmins, Int64.Parse(drUnProcessedData["Process_Rec_ID"].ToString()));
                        }
                    }
                    // If Employee Attendance is not Present
                    else
                    {
                        // Check in the TimeCheck Holiday Table
                        if (dtHoliday.Rows.Count > 0)
                        {
                            gstrAttendance = "Holiday";
                        }
                        else
                        {
                            if (intShiftId == -1)
                            {
                                gstrAttendance = "Weekly Off";
                            }
                            else
                            {
                                int count = 0;
                                count = CheckAdditionalWeekOff(dtmDate, drUnProcessedData["SwipeCardNo"].ToString());
                                if (count == 1)
                                {
                                    gstrAttendance = "Weekly Off";
                                    intShiftId = -1;
                                }
                                else
                                {
                                    // Check in the TimeCheck Leave Application Table
                                    DataTable dtLeave = new DataTable();
                                    dtLeave = objLeaveApplicationEventData.CheckLeaveForDate(drUnProcessedData["SwipeCardNo"].ToString(), dtmDate);
                                    if (dtLeave.Rows.Count > 0)
                                    {
                                        if (dtLeave.Rows[0]["Type"] != DBNull.Value)
                                        {
                                            if (dtLeave.Rows[0]["Type"].ToString() == "Leave")
                                            {
                                                if (dtLeave.Rows[0]["LeaveType_id"] != DBNull.Value)
                                                {
                                                    if (int.Parse(dtLeave.Rows[0]["LeaveType_id"].ToString()) > 0)
                                                    {
                                                        DataSet dsLeaveType = new DataSet();
                                                        DataTable dtLeaveType = new DataTable();
                                                        dsLeaveType = objLeaveEventData.SelectLeaveTypeDetailsById(int.Parse(dtLeave.Rows[0]["LeaveType_id"].ToString()), string.Empty);
                                                        dtLeaveType = dsLeaveType.Tables[0];
                                                        if (dtLeaveType.Rows.Count > 0)
                                                        {
                                                            if (dtLeaveType.Rows[0]["LeaveType"] != DBNull.Value)
                                                            {
                                                                gstrAttendance = dtLeaveType.Rows[0]["LeaveType"].ToString();
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                            else if (dtLeave.Rows[0]["Type"].ToString() == "Restricted Holiday")
                                            {
                                                gstrAttendance = "RH";
                                            }
                                            else if (dtLeave.Rows[0]["Type"].ToString() == "Comp Off")
                                            {
                                                gstrAttendance = "Comp Off";
                                                intShiftId = 0;
                                            }
                                            else if (dtLeave.Rows[0]["Type"].ToString() == "ESI")
                                            {
                                                gstrAttendance = "ESI";
                                            }
                                            else if (dtLeave.Rows[0]["Type"].ToString() == "LOP")
                                            {
                                                gstrAttendance = "LOP";
                                            }
                                        }
                                    }
                                    else
                                    {
                                        gstrAttendance = "Absent";
                                    }
                                }
                            }
                        }
                        // Update the Processed Data with Appropriate Attendance
                        objMonthClosure.UpdateAttendanceInProcessedData(intShiftId, dtmWorkHrs.ToString("hh:mm"), gstrAttendance, Int64.Parse(drUnProcessedData["Process_Rec_ID"].ToString()));
                    }
                }
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    // Function to Convert Total Minutes to hh:mm format
    public string ConvertMinutesToHoursMins(double inTotalMinutes)
    {
        string strHoursMins = "00:00";
        double dTotHrs = Math.Floor(inTotalMinutes / 60);
        double dTotMins = inTotalMinutes % 60;
        int iTotHrs = Convert.ToInt32(dTotHrs);
        int iTotMins = Convert.ToInt32(dTotMins);
        if (Convert.ToInt32(dTotMins) >= 60)
        {
            iTotMins = Convert.ToInt32(dTotMins) % 60;
            iTotHrs += Convert.ToInt32(dTotMins) / 60;
        }
        strHoursMins = iTotHrs.ToString("00") + ":" + iTotMins.ToString("00");
        return (strHoursMins);
    }
    // Function to check Additional Weekly Off
    public int CheckAdditionalWeekOff(DateTime dtmDate, string EmployeeId)
    {
        DateTime startOfMonth;
        string strStartOfMonth;
        int DaysToAdd, NthWeek = 0, TargetDayOfWeek = 0;
        string flag = "NE";
        try
        {
            DataTable dtAdditionalWeekOff = new DataTable();
            dtAdditionalWeekOff = objMonthClosure.GetAdditionalWeekOff(EmployeeId, dtmDate.ToShortDateString());
            if (dtAdditionalWeekOff.Rows.Count > 0)
            {
                foreach (DataRow drRow in dtAdditionalWeekOff.Rows)
                {
                    if (drRow["Addl_WeekOff_Day"] != DBNull.Value && drRow["Addl_WeekOff_Day"].ToString() != string.Empty)
                    {
                        TargetDayOfWeek = GetWeekDay(drRow["Addl_WeekOff_Day"].ToString());
                    }
                    if (drRow["Addl_WeekOff_Week"] != DBNull.Value && drRow["Addl_WeekOff_Week"].ToString() != string.Empty)
                    {
                        string strTargetDayOfWeek = drRow["Addl_WeekOff_Week"].ToString();
                        if (strTargetDayOfWeek == "First Week")
                        {
                            NthWeek = 1;
                        }
                        else if (strTargetDayOfWeek == "Second Week")
                        {
                            NthWeek = 2;
                        }
                        else if (strTargetDayOfWeek == "Third Week")
                        {
                            NthWeek = 3;
                        }
                        else if (strTargetDayOfWeek == "Fourth Week")
                        {
                            NthWeek = 4;
                        }
                        else if (strTargetDayOfWeek == "Fifth Week")
                        {
                            NthWeek = 5;
                        }
                    }
                    if (NthWeek != 0 && TargetDayOfWeek != 0)
                    {
                        strStartOfMonth = dtmDate.Month + "/01/" + dtmDate.Year;
                        startOfMonth = DateTime.Parse(strStartOfMonth);
                        string WeekDayName = startOfMonth.DayOfWeek.ToString();
                        int WeekDay = GetWeekDay(WeekDayName);
                        DaysToAdd = (7 - (WeekDay + (7 - TargetDayOfWeek)) % 7) % 7;
                        DateTime dtmResult = startOfMonth.AddDays(DaysToAdd + ((NthWeek - 1) * 7));
                        if (dtmResult == dtmDate)
                        {
                            flag = "E";
                        }
                    }
                }
            }
            if (flag == "E")
            {
                return (1);
            }
            else
            {
                return (0);
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    public int GetWeekDay(string WeekDayName)
    {
        int intWeekDay = 0;
        switch (WeekDayName)
        {
            case "Sunday":
                intWeekDay = 1;
                break;
            case "Monday":
                intWeekDay = 2;
                break;
            case "Tuesday":
                intWeekDay = 3;
                break;
            case "Wednesday":
                intWeekDay = 4;
                break;
            case "Thursday":
                intWeekDay = 5;
                break;
            case "Friday":
                intWeekDay = 6;
                break;
            case "Saturday":
                intWeekDay = 7;
                break;
        }
        return (intWeekDay);
    }
    private static DataSet ToDataSet(string[] input)
    {
        //Create a Dataset
        DataSet dsProcess = new DataSet();
        // Create a DataTable. 
        DataTable dtProcess = new DataTable("ReprocessEmployees");
        // Create a DataColumn and set various properties. 
        DataColumn dcProcess = new DataColumn();
        dcProcess.DataType = System.Type.GetType("System.String");
        dcProcess.ColumnName = "EmployeeId";
        // Add the column to the table. 
        dtProcess.Columns.Add(dcProcess);
        DataRow row;
        for (int i = 0; i < input.Length; i++)
        {
            row = dtProcess.NewRow();
            row["EmployeeId"] = input[i].ToString();
            dtProcess.Rows.Add(row);
        }
        dsProcess.Tables.Add(dtProcess);
        return dsProcess;
    }
    private void PayrollProcess(string strEmployees)
    {
        ////int iLoop = 0;
        ////string[] strEmployeeArray = strEmployees.Split(',');
        ////DataSet dsProcess = new DataSet();
        ////dsProcess = ToDataSet(strEmployeeArray);
        ////return;
        ////int intEmployeeArrayLengh = strEmployeeArray.Length;
        try
        {
            DataSet dsEmpDetails = new DataSet();
            dsEmpDetails = objEmployeeEventData.Select_EmployeeDetailsForMonthClosure(gdtmEndDate.ToShortDateString(), "", Convert.ToString(Session["UserGroupName"]), Convert.ToInt32(Request.QueryString["LevelId"].ToString()), gintMonthCloseID, gintUserId, 1, "Process", strEmployees, "", "");
            //////DataSet dsEmpDetails = new DataSet();
            ////DataTable dtPayroll = new DataTable();
            ////// Get every Active Employees
            ////string UserGroupName = string.Empty;
            //////dsEmpDetails = objEmployeeEventData.Select_EmployeeDetails(UserGroupName, Convert.ToString(Session["LevelRights"]), Convert.ToString(Session["GradeLevel"]), Convert.ToInt16(Session["parentLevelId"]));
            ////// For each Employee, process the details in the ProcessedData Table
            ////for (iLoop = 0; iLoop < intEmployeeArrayLengh; iLoop++)
            ////{
            ////    string strHrsWork = string.Empty, strHrsOT = string.Empty, strNormOT = string.Empty;
            ////    string strOffOT = string.Empty, strHolOT = string.Empty, strEarlyOut = string.Empty;
            ////    string strLateIn = string.Empty, strWorkHrs = string.Empty, strHrsLess = string.Empty;
            ////    string strHrsExtra = string.Empty;
            ////    DataTable dtProcessedData = new DataTable();
            ////    if (strEmployeeArray[iLoop] != string.Empty)
            ////    {
            ////        // Get the Details of the Particular Employee from the ProcessedData Table for a specified Date Range Start Date and End Date
            ////        dtProcessedData = objMonthClosure.SelectProcessedDataForPayRollCalculation(strEmployeeArray[iLoop], gdtmStartDate, gdtmEndDate);
            ////    }
            ////    double dHrsWork = 0, dHrsOT = 0, dNormOT = 0, dOffOT = 0, dHolOT = 0, dEarlyOut = 0, dLateIn = 0, dWorkHrs = 0, dHrsLess = 0, dHrsExtra = 0;
            ////    double dblLeaveDays = 0, dblAbsentDays = 0, dblPresentDays = 0, dblHolidays = 0, dblLOPDays = 0;
            ////    gstrEmployeeId = strEmployeeArray[iLoop];
            ////    // If Records exists in the ProcessedData Table
            ////    if (dtProcessedData.Rows.Count > 0)
            ////    {
            ////        // Loop through each row 
            ////        for (int k = 0; k < dtProcessedData.Rows.Count; k++)
            ////        {
            ////            if (dtProcessedData.Rows[k]["Date"] != DBNull.Value && dtProcessedData.Rows[k]["Date"].ToString() != string.Empty)
            ////            {
            ////                gstrDate = dtProcessedData.Rows[k]["Date"].ToString();
            ////            }
            ////            if (dtProcessedData.Rows[k]["HrsWork"] != DBNull.Value && dtProcessedData.Rows[k]["HrsWork"].ToString() != string.Empty && dtProcessedData.Rows[k]["HrsWork"].ToString() != "0")
            ////            {
            ////                dHrsWork += ConvertHoursMinsToMinutes(dtProcessedData.Rows[k]["HrsWork"].ToString());
            ////            }
            ////            if (dtProcessedData.Rows[k]["HrsOT"] != DBNull.Value && dtProcessedData.Rows[k]["HrsOT"].ToString() != string.Empty && dtProcessedData.Rows[k]["HrsOT"].ToString() != "0")
            ////            {
            ////                if (dtProcessedData.Rows[k]["overtimestatus"] != DBNull.Value && dtProcessedData.Rows[k]["overtimestatus"].ToString() != string.Empty && dtProcessedData.Rows[k]["overtimestatus"].ToString() == "Approved")
            ////                {
            ////                    dHrsOT += ConvertHoursMinsToMinutes(dtProcessedData.Rows[k]["HrsOT"].ToString());
            ////                }
            ////            }
            ////            if (dtProcessedData.Rows[k]["NormOT"] != DBNull.Value && dtProcessedData.Rows[k]["NormOT"].ToString() != string.Empty && dtProcessedData.Rows[k]["NormOT"].ToString() != "0")
            ////            {
            ////                if (dtProcessedData.Rows[k]["overtimestatus"] != DBNull.Value && dtProcessedData.Rows[k]["overtimestatus"].ToString() != string.Empty && dtProcessedData.Rows[k]["overtimestatus"].ToString() == "Approved")
            ////                {
            ////                    dNormOT += ConvertHoursMinsToMinutes(dtProcessedData.Rows[k]["NormOT"].ToString());
            ////                }
            ////            }
            ////            if (dtProcessedData.Rows[k]["OffOT"] != DBNull.Value && dtProcessedData.Rows[k]["OffOT"].ToString() != string.Empty && dtProcessedData.Rows[k]["OffOT"].ToString() != "0")
            ////            {
            ////                if (dtProcessedData.Rows[k]["overtimestatus"] != DBNull.Value && dtProcessedData.Rows[k]["overtimestatus"].ToString() != string.Empty && dtProcessedData.Rows[k]["overtimestatus"].ToString() == "Approved")
            ////                {
            ////                    dOffOT += ConvertHoursMinsToMinutes(dtProcessedData.Rows[k]["OffOT"].ToString());
            ////                }
            ////            }
            ////            if (dtProcessedData.Rows[k]["HolOT"] != DBNull.Value && dtProcessedData.Rows[k]["HolOT"].ToString() != string.Empty && dtProcessedData.Rows[k]["HolOT"].ToString() != "0")
            ////            {
            ////                if (dtProcessedData.Rows[k]["overtimestatus"] != DBNull.Value && dtProcessedData.Rows[k]["overtimestatus"].ToString() != string.Empty && dtProcessedData.Rows[k]["overtimestatus"].ToString() == "Approved")
            ////                {
            ////                    dHolOT += ConvertHoursMinsToMinutes(dtProcessedData.Rows[k]["HolOT"].ToString());
            ////                }
            ////            }
            ////            if (dtProcessedData.Rows[k]["EarlyOut"] != DBNull.Value && dtProcessedData.Rows[k]["EarlyOut"].ToString() != string.Empty && dtProcessedData.Rows[k]["EarlyOut"].ToString() != "0")
            ////            {
            ////                dEarlyOut += ConvertHoursMinsToMinutes(dtProcessedData.Rows[k]["EarlyOut"].ToString());
            ////            }
            ////            if (dtProcessedData.Rows[k]["LateIn"] != DBNull.Value && dtProcessedData.Rows[k]["LateIn"].ToString() != string.Empty && dtProcessedData.Rows[k]["LateIn"].ToString() != "0")
            ////            {
            ////                dLateIn += ConvertHoursMinsToMinutes(dtProcessedData.Rows[k]["LateIn"].ToString());
            ////            }
            ////            if (dtProcessedData.Rows[k]["WorkHrs"] != DBNull.Value && dtProcessedData.Rows[k]["WorkHrs"].ToString() != string.Empty && dtProcessedData.Rows[k]["WorkHrs"].ToString() != "0")
            ////            {
            ////                dWorkHrs += ConvertHoursMinsToMinutes(dtProcessedData.Rows[k]["WorkHrs"].ToString());
            ////            }
            ////            if (dtProcessedData.Rows[k]["HrsLess"] != DBNull.Value && dtProcessedData.Rows[k]["HrsLess"].ToString() != string.Empty && dtProcessedData.Rows[k]["HrsLess"].ToString() != "0")
            ////            {
            ////                dHrsLess += ConvertHoursMinsToMinutes(dtProcessedData.Rows[k]["HrsLess"].ToString());
            ////            }
            ////            if (dtProcessedData.Rows[k]["HrsExtra"] != DBNull.Value && dtProcessedData.Rows[k]["HrsExtra"].ToString() != string.Empty && dtProcessedData.Rows[k]["HrsExtra"].ToString() != "0")
            ////            {
            ////                dHrsExtra += ConvertHoursMinsToMinutes(dtProcessedData.Rows[k]["HrsExtra"].ToString());
            ////            }
            ////            // First Half
            ////            if (dtProcessedData.Rows[k]["FNAttendanceCode"] != DBNull.Value && dtProcessedData.Rows[k]["FNAttendanceCode"].ToString() != string.Empty)
            ////            {
            ////                string strLeaveCode = string.Empty;
            ////                double dblTotalDays = 0;
            ////                string strAttendance = dtProcessedData.Rows[k]["FNAttendanceCode"].ToString();
            ////                if (dtProcessedData.Rows[k]["TotalDays"] != DBNull.Value && dtProcessedData.Rows[k]["TotalDays"].ToString() != string.Empty)
            ////                {
            ////                    dblTotalDays = double.Parse(dtProcessedData.Rows[k]["TotalDays"].ToString());
            ////                }
            ////                if (strAttendance == "Present")
            ////                {
            ////                    dblPresentDays += 0.5;
            ////                }
            ////                if (strAttendance == "Absent")
            ////                {
            ////                    dblAbsentDays += 0.5;
            ////                }
            ////                if (strAttendance == "Comp Off")
            ////                {
            ////                    dblAbsentDays += 0.5;
            ////                }
            ////                if (strAttendance == "Holiday" || strAttendance == "Weekly Off")
            ////                {
            ////                    dblHolidays += 0.5;
            ////                }
            ////                if (strAttendance == "LOP")
            ////                {
            ////                    dblLOPDays += 0.5;
            ////                }
            ////                if ((strAttendance != "Present" && strAttendance != "Absent" && strAttendance != "BL" && strAttendance != "Holiday" && strAttendance != "Weekly Off" && strAttendance != "Comp Off" && strAttendance != "LOP") || strAttendance == "RH")
            ////                {
            ////                    strLeaveCode = strAttendance;
            ////                }
            ////                if (strLeaveCode != string.Empty && strLeaveCode != "LOP")
            ////                {
            ////                    dblLeaveDays += 0.5;
            ////                }
            ////            }
            ////            // Second half
            ////            if (dtProcessedData.Rows[k]["ANAttendanceCode"] != DBNull.Value && dtProcessedData.Rows[k]["ANAttendanceCode"].ToString() != string.Empty)
            ////            {
            ////                string strLeaveCode = string.Empty;
            ////                double dblTotalDays = 0;
            ////                string strAttendance = dtProcessedData.Rows[k]["ANAttendanceCode"].ToString();
            ////                if (dtProcessedData.Rows[k]["TotalDays"] != DBNull.Value && dtProcessedData.Rows[k]["TotalDays"].ToString() != string.Empty)
            ////                {
            ////                    dblTotalDays = double.Parse(dtProcessedData.Rows[k]["TotalDays"].ToString());
            ////                }
            ////                if (strAttendance == "Present")
            ////                {
            ////                    dblPresentDays += 0.5;
            ////                }
            ////                if (strAttendance == "Comp Off")
            ////                {
            ////                    dblPresentDays += 0.5;
            ////                }
            ////                if (strAttendance == "Absent")
            ////                {
            ////                    dblAbsentDays += 0.5;
            ////                }
            ////                if (strAttendance == "Holiday" || strAttendance == "Weekly Off")
            ////                {
            ////                    dblHolidays += 0.5;
            ////                }
            ////                if (strAttendance == "LOP")
            ////                {
            ////                    dblLOPDays += 0.5;
            ////                }
            ////                if ((strAttendance != "Present" && strAttendance != "Absent" && strAttendance != "BL" && strAttendance != "Holiday" && strAttendance != "Weekly Off" && strAttendance != "Comp Off" && strAttendance != "LOP") || strAttendance == "RH")
            ////                {
            ////                    strLeaveCode = strAttendance;
            ////                }
            ////                if (strLeaveCode != string.Empty && strLeaveCode != "LOP")
            ////                {
            ////                    dblLeaveDays += 0.5;
            ////                }
            ////            }
            ////        }
            ////        strHrsWork = TimeFormat(dHrsWork);
            ////        strHrsOT = TimeFormat(dHrsOT);
            ////        strNormOT = TimeFormat(dNormOT);
            ////        strOffOT = TimeFormat(dOffOT);
            ////        strHolOT = TimeFormat(dHolOT);
            ////        strEarlyOut = TimeFormat(dEarlyOut);
            ////        strLateIn = TimeFormat(dLateIn);
            ////        strWorkHrs = TimeFormat(dWorkHrs);
            ////        strHrsLess = TimeFormat(dHrsLess);
            ////        strHrsExtra = TimeFormat(dHrsExtra);
            ////        int count = 0;
            ////        // Check whether Payroll Details are already Processed or not by passing MonthClocsureId
            ////        count = objMonthClosure.CheckMonthClosureProcessFlag(gintMonthCloseID);
            ////        if (count == 0)
            ////        {
            ////            objMonthClosure.InsertPayrollProcessDetails(gintMonthCloseID, strEmployeeArray[iLoop], strHrsWork, strHrsOT, strNormOT, strOffOT, strHolOT, strEarlyOut, strLateIn, strWorkHrs, strHrsLess, strHrsExtra, dblLeaveDays, dblAbsentDays, dblPresentDays, dblHolidays, dblLOPDays, gintUserId, DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss tt"));
            ////        }
            ////        else
            ////        {
            ////            objMonthClosure.UpdatePayrollProcessDetails(strHrsWork, strHrsOT, strNormOT, strOffOT, strHolOT, strEarlyOut, strLateIn, strWorkHrs, strHrsLess, strHrsExtra, dblLeaveDays, dblAbsentDays, dblPresentDays, dblHolidays, dblLOPDays, gintUserId, DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss tt"), gintMonthCloseID, strEmployeeArray[iLoop]);
            ////        }
            ////    }
            ////}
        }
        catch (Exception ex)
        {
            lblStatus.Text = string.Empty;
            string strErrorMessage = "<script language='javascript' type='text/javascript'>";
            strErrorMessage += "alert('Error : " + ex.Message + " has occured for Employee " + gstrEmployeeId + " and Date " + gstrDate + "');";
            strErrorMessage += "</script>";
            this.RegisterStartupScript("setScript", strErrorMessage);
        }
    }
    // Function to Convert hh:mm format to Total Minutes
    public double ConvertHoursMinsToMinutes(string inHoursMins)
    {
        int intTotalMinutes = 0, intHours = 0, intMinutes = 0;
        string[] HoursMins = inHoursMins.Split(':');
        intHours = Int16.Parse(HoursMins[0]);
        intMinutes = Int16.Parse(HoursMins[1]);
        intTotalMinutes = (intHours * 60) + intMinutes;
        return (double.Parse(intTotalMinutes.ToString()));
    }
    // Function to Convert Total Minutes to hh:mm format
    public string TimeFormat(double TotMins)
    {
        string strHrsMins = string.Empty;
        double dHrs = Math.Floor(TotMins / 60);
        double dMins = TotMins % 60;
        int iHrs = Convert.ToInt32(dHrs);
        int iMins = Convert.ToInt32(dMins);
        if (Convert.ToInt32(dMins) >= 60)
        {
            iMins = Convert.ToInt32(dMins) % 60;
            iHrs += Convert.ToInt32(dMins) / 60;
        }
        strHrsMins = iHrs.ToString("00") + ":" + iMins.ToString("00");
        return (strHrsMins);
    }
    /// <summary>
    /// LoadStrings Method is used to load the Label Names from the Resource File
    /// </summary>
    /// <param name="ci"></param>
    private void LoadStrings(CultureInfo ci)
    {
        btn_Reprocess.Text = "&nbsp&nbsp" + rm.GetString("btn_Reprocess", ci);
        btn_Back.Text = "&nbsp&nbsp" + rm.GetString("btn_Back", ci);
        grv_Employee.Columns[1].HeaderText = rm.GetString("email_EmployeeId", ci);
        grv_Employee.Columns[2].HeaderText = rm.GetString("email_EmployeeName", ci);
        lblId.Text = rm.GetString("email_EmployeeId", ci);
        lblName.Text = "&nbsp&nbsp" + rm.GetString("email_EmployeeName", ci);
        btnSearch.Text = "&nbsp&nbsp" + rm.GetString("btn_Search", ci);
        btnClear.Text = "&nbsp&nbsp" + rm.GetString("btn_Clear", ci);        
    }
    protected void grv_Employee_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        grv_Employee.EnableViewState = true;
        string ChkBoxIDs = string.Empty;
        CheckBox deleteChkBxItem = new CheckBox();
        // Add EmployeeId in Session Variable.
        foreach (GridViewRow i in grv_Employee.Rows)
        {
            //HtmlInputCheckBox deleteChkBxItem = (HtmlInputCheckBox)i.FindControl("deletethis");
            deleteChkBxItem = (CheckBox)i.Cells[0].FindControl("deletethis");
            if (deleteChkBxItem.Checked)
            {
                if (ChkBoxIDs == string.Empty)
                {
                    ChkBoxIDs = ((Label)i.FindControl("lbl_EmpId")).Text.ToString();
                }
                else
                {
                    // Concatenate DataGrid item with comma for SQL Delete
                    ChkBoxIDs = ChkBoxIDs + "," + ((Label)i.FindControl("lbl_EmpId")).Text.ToString();
                }
            }
        }
        if (Session["EmployeeIds"] == null || Session["EmployeeIds"].ToString() == string.Empty)
        {
            Session["EmployeeIds"] = ChkBoxIDs;
        }
        else
        {
            if (ChkBoxIDs != string.Empty)
            {
                Session["EmployeeIds"] = Session["EmployeeIds"] + "," + ChkBoxIDs;
            }
        }
        grv_Employee.PageIndex = e.NewPageIndex;
        //BindEmployeeGrid();
        grv_Employee.DataSource = ((DataSet)Session["dsEmployee"]).Tables[0];
        grv_Employee.DataBind();
        grv_Employee.Visible = true;
        Session["TotalEmployees"] = ((DataSet)Session["dsEmployee"]).Tables[0].Rows.Count;
        CheckEmployeeId_CheckBox();
        CheckBox chkSelect = new CheckBox();
        chkSelect = (CheckBox)grv_Employee.HeaderRow.Cells[0].FindControl("checkall");
        chkSelect.Checked = Convert.ToBoolean(Session["SelectAllStatus"].ToString());
    }
    public void CheckEmployeeId_CheckBox()
    {
        string strEmpId = string.Empty;
        strEmpId = (string)Session["EmployeeIds"];
        int intEmployeeIdsLength = strEmpId.Length;
        char[] Delimit ={ ',' };
        string[] Empid = strEmpId.Split(Delimit);
        CheckBox deleteChkBxItem = new CheckBox();
        foreach (GridViewRow gr in grv_Employee.Rows)
        {
            string empId = ((Label)gr.FindControl("lbl_EmpId")).Text.ToString();
            foreach (string str in Empid)
            {
                if (str == empId)
                {
                    deleteChkBxItem = (CheckBox)gr.Cells[0].FindControl("deletethis");
                    deleteChkBxItem.Checked = true;
                    int intLength = empId.Length;
                    if (intEmployeeIdsLength > intLength)
                    {
                        //More than One Id Present in the list
                        int intIndex = strEmpId.IndexOf("," + str + ",");
                        if (intIndex != -1)
                        {
                            //Exist in between
                            strEmpId = strEmpId.Remove(intIndex, (intLength + 1));
                        }
                        else
                        {
                            //Exist as the first or last
                            if (strEmpId.IndexOf(str + ",") != -1 && strEmpId.IndexOf(str + ",") == 0)
                            {
                                //Exist as a first Id
                                strEmpId = strEmpId.Remove(0, (intLength + 1));
                            }
                            else if (strEmpId.IndexOf("," + str) != -1 && (strEmpId.IndexOf("," + str) + intLength + 1) == intEmployeeIdsLength)
                            {
                                //Exist as a Last Id
                                strEmpId = strEmpId.Substring(0, (intEmployeeIdsLength - (intLength + 1)));
                            }
                        }
                    }
                    else
                    {
                        //Only one Id in the list
                        strEmpId = strEmpId.Replace(empId, "");
                    }
                    intEmployeeIdsLength = strEmpId.Length;
                    Session["EmployeeIds"] = strEmpId;
                    goto D;
                }
            }
        D: ;
        }
    }
    protected void btn_Back_Click(object sender, EventArgs e)
    {
    }
    protected void grv_CheckAll_CheckedChanged(object sender, EventArgs e)
    {
        CheckBox chkSelect = new CheckBox();
        chkSelect = (CheckBox)grv_Employee.HeaderRow.Cells[0].FindControl("checkall");
        string ChkBoxIDs = string.Empty;
        if (chkSelect.Checked)
        {
            ChkBoxIDs = GetEmployeeIdsInOtherPagesOfGrid();
            foreach (GridViewRow gr in grv_Employee.Rows)
            {
                // string ChkBoxIDs = string.Empty;
                ChkBoxIDs = ((Label)gr.FindControl("lbl_EmpId")).Text.ToString();
                if (Session["EmployeeIds"].ToString() == "")
                {
                    Session["EmployeeIds"] = ChkBoxIDs;
                }
                else
                {
                    if (ChkBoxIDs != "")
                    {
                        Session["EmployeeIds"] = Session["EmployeeIds"] + "," + ChkBoxIDs;
                    }
                }
            }
            //if (Session["EmployeeIds"].ToString() == "")
            //{
            //    Session["EmployeeIds"] = ChkBoxIDs;
            //}
            //else
            //{
            //    if (ChkBoxIDs != "")
            //    {
            //        Session["EmployeeIds"] = Session["EmployeeIds"] + "," + ChkBoxIDs;
            //    }
            //}
        }
        else
        {
            Session["EmployeeIds"] = string.Empty;
        }
        foreach (GridViewRow gr in grv_Employee.Rows)
        {
            chkSelect = (CheckBox)gr.Cells[0].FindControl("deletethis");
            chkSelect.Checked = ((CheckBox)sender).Checked;
        }
        Session["SelectAllStatus"] = ((CheckBox)sender).Checked;
    }
    protected void grv_Check_CheckedChanged(object sender, EventArgs e)
    {
        string ChkBoxIDs = string.Empty;
        int intCount = 0;
        bool boolAllChecked = false;
        CheckBox chkSelect = new CheckBox();
        CheckBox chkSelectAll = new CheckBox();
        chkSelectAll = (CheckBox)grv_Employee.HeaderRow.Cells[0].FindControl("checkall");
        if (((CheckBox)sender).Checked == false)
        {
            chkSelectAll.Checked = false;
        }
        else
        {
            foreach (GridViewRow gr in grv_Employee.Rows)
            {
                //intCount Keeps track of the number of checkbox checked in the current page.
                chkSelect = (CheckBox)gr.Cells[0].FindControl("deletethis");
                if (chkSelect.Checked)
                    intCount = intCount + 1;
            }
            if (Convert.ToInt32(Session["TotalEmployees"].ToString()) == intCount)
            {
                //no paging and all chekbox is in checked state
                chkSelectAll.Checked = true;
                DataSet ds = new DataSet();
                ds = (DataSet)Session["dsEmployee"];
                foreach (GridViewRow gr in grv_Employee.Rows)
                {
                    // string ChkBoxIDs = string.Empty;
                    ChkBoxIDs = ((Label)gr.FindControl("lbl_EmpId")).Text.ToString();
                    if (Session["EmployeeIds"].ToString() == "")
                    {
                        Session["EmployeeIds"] = ChkBoxIDs;
                    }
                    else
                    {
                        if (ChkBoxIDs != "")
                        {
                            Session["EmployeeIds"] = Session["EmployeeIds"] + "," + ChkBoxIDs;
                        }
                    }
                }
            }
            else if (intCount > 0 && Convert.ToInt32(Session["TotalEmployees"].ToString()) > intCount)
            {
                //Paging might present.
                int intGridPageSize = grv_Employee.PageSize;
                int intGridTotalPages = grv_Employee.PageCount;
                if (Convert.ToInt32(Session["TotalEmployees"].ToString()) > intGridPageSize)
                {   //Paging is present
                    if (intCount == intGridPageSize)
                    {   //All checkbox are checked in the current page
                        if (Session["EmployeeIds"] != null || Session["EmployeeIds"].ToString() != string.Empty)
                        {   //some checkbox in other pages is also checked
                            ChkBoxIDs = GetEmployeeIdsInOtherPagesOfGrid();
                            char[] Delimit ={ ',' };
                            string[] SessionEmployeeIds = Session["EmployeeIds"].ToString().Split(Delimit);
                            string[] ChedkedEmployeeIds = ChkBoxIDs.Split(Delimit);
                            Array.Sort(SessionEmployeeIds);
                            Array.Sort(ChedkedEmployeeIds);
                            if (SessionEmployeeIds.Length == ChedkedEmployeeIds.Length)
                            {
                                for (int iLoop = 0; iLoop < ChedkedEmployeeIds.Length; iLoop++)
                                {
                                    if (SessionEmployeeIds[iLoop] != ChedkedEmployeeIds[iLoop])
                                    {
                                        boolAllChecked = false;
                                        break;
                                    }
                                }
                                boolAllChecked = true;
                            }
                            if (boolAllChecked == true)
                            {   //All checkBox Checked
                                chkSelectAll.Checked = true;
                            }
                        }
                    }
                    else if (grv_Employee.PageIndex == intGridTotalPages - 1)
                    {   //Last Page
                        int intLastPageCount = Convert.ToInt32(Session["TotalEmployees"].ToString()) - (intGridPageSize * (intGridTotalPages - 1));
                        if (intCount == intLastPageCount)
                        {
                            if (Session["EmployeeIds"] != null || Session["EmployeeIds"].ToString() != string.Empty)
                            {   //some checkbox in other pages is also checked
                                ChkBoxIDs = GetEmployeeIdsInOtherPagesOfGrid();
                                char[] Delimit ={ ',' };
                                string[] SessionEmployeeIds = Session["EmployeeIds"].ToString().Split(Delimit);
                                string[] ChedkedEmployeeIds = ChkBoxIDs.Split(Delimit);
                                Array.Sort(SessionEmployeeIds);
                                Array.Sort(ChedkedEmployeeIds);
                                if (SessionEmployeeIds.Length == ChedkedEmployeeIds.Length)
                                {
                                    for (int iLoop = 0; iLoop < ChedkedEmployeeIds.Length; iLoop++)
                                    {
                                        if (SessionEmployeeIds[iLoop] != ChedkedEmployeeIds[iLoop])
                                        {
                                            boolAllChecked = false;
                                            break;
                                        }
                                    }
                                    boolAllChecked = true;
                                }
                                if (boolAllChecked == true)
                                {   //All checkBox Checked
                                    chkSelectAll.Checked = true;
                                }
                            }
                        }
                    }
                    else
                    {
                        string ChkBoxID = string.Empty;
                        string strEmpId = string.Empty;
                        CheckBox chkSelectRow = new CheckBox();
                        //No paging and not all check box checked.
                        foreach (GridViewRow gr in grv_Employee.Rows)
                        {
                            chkSelectRow = (CheckBox)gr.Cells[0].FindControl("deletethis");
                            if (chkSelectRow.Checked)
                            {
                                strEmpId = ((Label)gr.FindControl("lbl_EmpId")).Text.ToString();
                                if (ChkBoxIDs == "")
                                {
                                    ChkBoxIDs = strEmpId;
                                }
                                else
                                {
                                    ChkBoxIDs = ChkBoxIDs + "," + strEmpId;
                                }
                                Session["EmployeeIds"] = ChkBoxIDs;
                                //ChkBoxID = GetEmployeeIdsInOtherPagesOfGrid();
                                //if (Session["EmployeeIds"].ToString() == "")
                                //{
                                //    Session["EmployeeIds"] = ChkBoxIDs;
                                //}
                                //else
                                //{
                                //    if (ChkBoxID != "")
                                //    {
                                //        Session["EmployeeIds"] = Session["EmployeeIds"] + "," + ChkBoxIDs;
                                //    }
                                //}
                            }
                        }
                    }
                }
                else
                {
                    string ChkBoxID = string.Empty;
                    string strEmpId = string.Empty;
                    CheckBox chkSelectRow = new CheckBox();
                    //No paging and not all check box checked.
                    foreach (GridViewRow gr in grv_Employee.Rows)
                    {
                        chkSelectRow = (CheckBox)gr.Cells[0].FindControl("deletethis");
                        if (chkSelectRow.Checked)
                        {
                            strEmpId = ((Label)gr.FindControl("lbl_EmpId")).Text.ToString();
                            if (ChkBoxIDs == "")
                            {
                                ChkBoxIDs = strEmpId;
                            }
                            else
                            {
                                ChkBoxIDs = ChkBoxIDs + "," + strEmpId;
                            }
                            //ChkBoxID = GetEmployeeIdsInOtherPagesOfGrid();
                            if (Session["EmployeeIds"].ToString() == "")
                            {
                                Session["EmployeeIds"] = ChkBoxIDs;
                            }
                            else
                            {
                                if (ChkBoxID != "")
                                {
                                    Session["EmployeeIds"] = Session["EmployeeIds"] + "," + ChkBoxIDs;
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    protected string GetEmployeeIdsInOtherPagesOfGrid()
    {
        //string strLevels = Request.QueryString["LevelId"].ToString();
        //gdtmEndDate = DateTime.Parse(Request.QueryString["ToDate"]);
        //dsEmployeeDetails = objEmployeeEventData.Select_EmployeeDetailsForMonthClosure(gdtmEndDate.ToShortDateString(), strLevels);
        dsEmployeeDetails = (DataSet)Session["dsEmployee"];
        string strEmpId = string.Empty;
        foreach (DataRow dr in dsEmployeeDetails.Tables[0].Rows)
        {
            foreach (GridViewRow gr in grv_Employee.Rows)
            {
                strEmpId = ((Label)gr.FindControl("lbl_EmpId")).Text.ToString();
                if (strEmpId == dr["Employee_Code_Id"].ToString())
                {
                    goto A;
                }
            }
            if (ChkBoxIDs == "")
            {
                ChkBoxIDs = dr["Employee_Code_Id"].ToString();
            }
            else
            {
                ChkBoxIDs = ChkBoxIDs + "," + dr["Employee_Code_Id"].ToString();
            }
        A: ;
        }
        return ChkBoxIDs;
    }
    protected void grv_Employee_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Header)
        {
            Label lblCheckAll = (Label)e.Row.Cells[0].FindControl("lblCheckAll");
           // lblCheckAll.Text = rm.GetString("ExportData_All", ci);
        }
    }
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        // Create a DataTable. 
        DataTable dtProcess = new DataTable("ReprocessEmployees");
        // Create a DataColumn and set various properties. 
        DataColumn dcProcess = new DataColumn();
        dcProcess.DataType = System.Type.GetType("System.String");
        dcProcess.ColumnName = "EmployeeId";
        // Add the column to the table. 
        dtProcess.Columns.Add(dcProcess);
        dsProcess.Tables.Add(dtProcess);
        dsProcess.Tables[0].WriteXml(strWriteXML);
        dsEmployee = objEmployeeEventData.Select_EmployeeDetailsForMonthClosure(gdtmEndDate.ToShortDateString(), strLevels, Convert.ToString(Session["UserGroupName"]), Convert.ToInt16(strLevels), gintMonthCloseID, gintUserId, 1, "BindGrid", strWriteXML.ToString(), txtEmployeeId.Text, txtEmployeeName.Text);
        Session["dsEmployee"] = dsEmployee;
        grv_Employee.DataSource = ((DataSet)Session["dsEmployee"]).Tables[0];
        grv_Employee.DataBind();
        grv_Employee.Visible = true;
        Session["TotalEmployees"] = ((DataSet)Session["dsEmployee"]).Tables[0].Rows.Count;
        if (dsEmployee.Tables.Count > 0)
        {
            if (dsEmployee.Tables[0].Rows.Count > 0)
            {
            }
            else
            {
                btn_Reprocess.Visible = false;
                btn_Back.Visible = false;
            }
        }
        else
        {
            btn_Reprocess.Visible = false;
            btn_Back.Visible = false;
        }
    }
    /// <summary>
    /// To Sorting the data based on the Branch Name
    /// </summary>
    #region sorting
    public SortDirection gridviewsortdirection
    {
        get
        {
            if (ViewState["sortdirection"] == null)
            {
                ViewState["sortdirection"] = SortDirection.Ascending;
            }
            return (SortDirection)ViewState["sortdirection"];
        }
        set
        {
            ViewState["sortdirection"] = value;
        }
    }

    public void sortgridview(string sortexpression, string direction)
    {
        DataSet ds = new DataSet();
        ds = (DataSet)Session["dsEmployee"];
        DataTable dt = new DataTable();
        dt = ds.Tables[0];

        DataView dv = new DataView(dt);
        dv.Sort = sortexpression + " " + direction;

        dt = dv.ToTable();
        grv_Employee.DataSource = dv;
        grv_Employee.DataBind();
    }
    #endregion
    protected void grv_Employee_Sorting(object sender, GridViewSortEventArgs e)
    {
        try
        {
            string sort = e.SortExpression;
            if (gridviewsortdirection == SortDirection.Ascending)
            {
                gridviewsortdirection = SortDirection.Descending;
                sortgridview(sort, "DESC");
            }
            else
            {
                gridviewsortdirection = SortDirection.Ascending;
                sortgridview(sort, "ASC");
            }
        }
        catch (Exception ex)
        {
            // ScriptManager.RegisterStartupScript(this, this.GetType(), "AlertIndex", "alert(\" " + ex.Message + "\" );", true);
        }
    }
    protected void btnClear_Click(object sender, EventArgs e)
    {
        txtEmployeeId.Text = "";
        txtEmployeeName.Text = "";
        btn_Reprocess.Visible = true;
        lblStatus.Text = string.Empty;
        btn_Back.Visible = true;
        Session["SelectAllStatus"] = "False";
        BindEmployeeGrid();
    }
}
