using System;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Globalization;
using System.Threading;
using System.Resources;
using System.IO;
public partial class Transactions_TA_UI_Transactions_SwipesHandling : System.Web.UI.Page
{
    #region Variable Declaration
    ResourceManager rm;
    CultureInfo ci;
    int intCount;
    cls_Common objClassCommon = new cls_Common();
    bool CheckGrid = false;
    #endregion
    #region Page Load Events
    /// <summary>
    /// On page loading
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Page_Load(object sender, EventArgs e)
    {
        //string strTest = Request.QueryString["VoidUnVoid"];
        //Response.Write(Convert.ToString(Session["parentLevelId"]) + " ses");
        if (Session["Session_ActiveLanguage"] == null)
        {
            string strScript1 = "<script language='javascript' type='text/javascript'>";
            strScript1 += "alert('" + rm.GetString("Alert_SessionExpired", ci) + "');parent.$('#myModal').modal('hide');";
            strScript1 += " </script>";
            this.RegisterStartupScript("closeScript1", strScript1);
            return;
        }
        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));
        LoadStrings(ci);
        loadcss();
        if (!IsPostBack)
        {
            Session["TotalSwipes"] = 0;
            btnVoid.OnClientClick = "return confirm('" + rm.GetString("Alert_AreyousuretoIgnorethePunches", ci) + "');";
            btnUnVoid.OnClientClick = "return confirm('" + rm.GetString("Alert_AreyousuretoIncludethePunches", ci) + "');";
            bool blnParentExists = true;
            if (Session["parentLevelId"] == null)
            {
                blnParentExists = false;
            }
            else if (Convert.ToInt32(Session["parentLevelId"]) == 0)
            {
                blnParentExists = false;
            }
            if (blnParentExists == false)
            {
                string strScript = "";
                strScript = strScript + "<script language='javascript'>";
                strScript = strScript + "alert('" + rm.GetString("Alert_SelectCompany", ci) + "');parent.$('#myModal').modal('hide');";
                strScript = strScript + "</script>";
                Page.RegisterStartupScript("AlertManualApproval", strScript);
                return;
            }
            string EmpId = "";
            string EmpName = "";
            int EmpCategory = 0;
            int EmpType = 0;
            string FromDate = "";
            string ToDate = "";
            string SwipesType = "";
            string VoidUnVoid = "";
            string Level = "";
            Rpt_Common rptcommon = new Rpt_Common();
            Level = rptcommon.getNodes(Convert.ToInt16(Session["parentLevelId"]), Convert.ToString(Session["LevelRights"]));
            if (Request.QueryString["EmpId"] != null && Convert.ToString(Request.QueryString["EmpId"]) != "")
            {
                EmpId = Convert.ToString(Request.QueryString["EmpId"]);
            }
            if (Request.QueryString["EmpName"] != null && Convert.ToString(Request.QueryString["EmpName"]) != "")
            {
                EmpName = Convert.ToString(Request.QueryString["EmpName"]);
            }
            if (Request.QueryString["EmpCategory"] != null && Convert.ToString(Request.QueryString["EmpCategory"]) != "")
            {
                EmpCategory = Convert.ToInt16(Request.QueryString["EmpCategory"]);
            }
            if (Request.QueryString["EmpType"] != null && Convert.ToString(Request.QueryString["EmpType"]) != "")
            {
                EmpType = Convert.ToInt16(Request.QueryString["EmpType"]);
            }
            if (Request.QueryString["FromDate"] != null && Convert.ToString(Request.QueryString["FromDate"]) != "")
            {
                FromDate = Convert.ToString(Request.QueryString["FromDate"]);
            }
            if (Request.QueryString["ToDate"] != null && Convert.ToString(Request.QueryString["ToDate"]) != "")
            {
                ToDate = Convert.ToString(Request.QueryString["ToDate"]);
            }
            if (Request.QueryString["SwipesType"] != null && Convert.ToString(Request.QueryString["SwipesType"]) != "")
            {
                SwipesType = Convert.ToString(Request.QueryString["SwipesType"]);
            }
            if (Request.QueryString["VoidUnVoid"] != null && Convert.ToString(Request.QueryString["VoidUnVoid"]) != "")
            {
                VoidUnVoid = Convert.ToString(Request.QueryString["VoidUnVoid"]);
            }
            string strSwipeCard = "";
            if (Request.QueryString["SwipeCard"] != null && Convert.ToString(Request.QueryString["SwipeCard"]) != "")
            {
                strSwipeCard = Convert.ToString(Request.QueryString["SwipeCard"]);
            }
            DataSet ds = new DataSet();
            SwipesHandlingEventData objClass = new SwipesHandlingEventData();
            string strStartDate = "";
            string strEndDate = "";
            string gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
            cls_Common objClassCommon = new cls_Common();
            strStartDate = objClassCommon.DateConvertion(gstrDateFormat, FromDate);
            strEndDate = objClassCommon.DateConvertion(gstrDateFormat, ToDate);
            FromDate = strStartDate;
            ToDate = strEndDate;
            ds = objClass.SelectPunches(Convert.ToInt32(Session["EmpAutoID"]), EmpId, EmpName, EmpCategory, EmpType, FromDate, ToDate, SwipesType, VoidUnVoid, Level, strSwipeCard, Convert.ToString(Session["UserGroupName"]), Convert.ToInt16(Session["parentLevelId"]));
            if (ds != null && ds.Tables.Count > 0)
            {
                grd.DataSource = ds;
                grd.DataBind();
                ViewState["dtSwipes"] = ds.Tables[0];
                Session["TotalSwipes"] = Convert.ToInt32(ds.Tables[0].Rows.Count);
                if (ds.Tables[0].Rows.Count == 0)
                {
                    btnUnVoid.Visible = false;
                    btnVoid.Visible = false;
                    string strScript = "<script language='javascript' type='text/javascript'>";
                    strScript += "alert('" + rm.GetString("Alert_NoPunchesFound", ci) + "');parent.$('#myModal').modal('hide');";
                    strScript += " </script>";
                    this.RegisterStartupScript("closeScript", strScript);
                }
            }
            Session["SwipesID"] = "";
        }
    }
    #endregion
    #region User Defined
    private void LoadStrings(CultureInfo ci)
    {
        lbl_Header.Text = rm.GetString("Transaction_SwipesHandling", ci);
        btnUnVoid.Text = "&nbsp;&nbsp;" + rm.GetString("btnUnVoid", ci);
        btnVoid.Text = "&nbsp;&nbsp;" + rm.GetString("btnVoid", ci);
        grd.Columns[3].HeaderText = rm.GetString("email_EmployeeName", ci);
        grd.Columns[4].HeaderText = rm.GetString("ManualTimeEntry_InDate", ci);
        grd.Columns[5].HeaderText = rm.GetString("ManualTimeEntry_In_Time", ci);
        grd.Columns[6].HeaderText = rm.GetString("SwipesHandling_IgnorePunches", ci);
        
    }
    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
        htmlSwipesList.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";
        }
        else
        {
            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";
            stylefonts.Href = "../dist/css/fonts.css";
        }
    }
    private void Message(string messageContent)
    {
        string strScript = "<script language='javascript' type='text/javascript'>";
        strScript += "alert('" + messageContent + "');";
        strScript += " </script>";
        this.RegisterStartupScript("setScript", strScript);
    }
    public void BindGrid()
    {
        string EmpId = "";
        string EmpName = "";
        int EmpCategory = 0;
        int EmpType = 0;
        string FromDate = "";
        string ToDate = "";
        string SwipesType = "";
        string VoidUnVoid = "";
        string Level = "";
        Rpt_Common rptcommon = new Rpt_Common();
        Level = rptcommon.getNodes(Convert.ToInt16(Session["parentLevelId"]), Convert.ToString(Session["LevelRights"]));
        if (Request.QueryString["EmpId"] != null && Convert.ToString(Request.QueryString["EmpId"]) != "")
        {
            EmpId = Convert.ToString(Request.QueryString["EmpId"]);
        }
        if (Request.QueryString["EmpName"] != null && Convert.ToString(Request.QueryString["EmpName"]) != "")
        {
            EmpName = Convert.ToString(Request.QueryString["EmpName"]);
        }
        if (Request.QueryString["EmpCategory"] != null && Convert.ToString(Request.QueryString["EmpCategory"]) != "")
        {
            EmpCategory = Convert.ToInt16(Request.QueryString["EmpCategory"]);
        }
        if (Request.QueryString["EmpType"] != null && Convert.ToString(Request.QueryString["EmpType"]) != "")
        {
            EmpType = Convert.ToInt16(Request.QueryString["EmpType"]);
        }
        if (Request.QueryString["FromDate"] != null && Convert.ToString(Request.QueryString["FromDate"]) != "")
        {
            FromDate = Convert.ToString(Request.QueryString["FromDate"]);
        }
        if (Request.QueryString["ToDate"] != null && Convert.ToString(Request.QueryString["ToDate"]) != "")
        {
            ToDate = Convert.ToString(Request.QueryString["ToDate"]);
        }
        if (Request.QueryString["SwipesType"] != null && Convert.ToString(Request.QueryString["SwipesType"]) != "")
        {
            SwipesType = Convert.ToString(Request.QueryString["SwipesType"]);
        }
        if (Request.QueryString["VoidUnVoid"] != null && Convert.ToString(Request.QueryString["VoidUnVoid"]) != "")
        {
            VoidUnVoid = Convert.ToString(Request.QueryString["VoidUnVoid"]);
        }
        string strSwipeCard = "";
        if (Request.QueryString["SwipeCard"] != null && Convert.ToString(Request.QueryString["SwipeCard"]) != "")
        {
            strSwipeCard = Convert.ToString(Request.QueryString["SwipeCard"]);
        }
        cls_Common objCommon = new cls_Common();
        DataSet ds = new DataSet();
        SwipesHandlingEventData objClass = new SwipesHandlingEventData();
        string gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
        ds = objClass.SelectPunches(Convert.ToInt32(Session["EmpAutoID"]), EmpId, EmpName, EmpCategory, EmpType, objCommon.DateConvertion(gstrDateFormat, FromDate), objCommon.DateConvertion(gstrDateFormat, ToDate), SwipesType, VoidUnVoid, Level, strSwipeCard, Convert.ToString(Session["UserGroupName"]), Convert.ToInt16(Session["parentLevelId"]));
        if (ds != null && ds.Tables.Count > 0)
        {
            grd.DataSource = ds;
            grd.DataBind();
            //ViewState["dtSwipes"] = ds.Tables[0];
            //Session["TotalSwipes"] = Convert.ToInt32(ds.Tables[0].Rows.Count);
            CheckBox chkSelect = new CheckBox();
            chkSelect = (CheckBox)grd.HeaderRow.Cells[0].FindControl("checkall");
            chkSelect.Checked = Convert.ToBoolean(Session["SelectAllStatus"]);
        }
    }
    public void CheckSwipes_CheckBox()
    {
        string strEmpId = "";
        strEmpId = (string)Session["SwipesID"];
        int intEmployeeIdsLength = strEmpId.Length;
        char[] Delimit ={ ',' };
        string[] Empid = strEmpId.Split(Delimit);
        CheckBox deleteChkBxItem = new CheckBox();
        foreach (GridViewRow gr in grd.Rows)
        {
            string empId = Convert.ToString(((Label)gr.FindControl("lblClkID")).Text);
            foreach (string str in Empid)
            {
                if (str == empId)
                {
                    //HtmlInputCheckBox deleteChkBxItem = (HtmlInputCheckBox)gr.FindControl("deletethis");
                    deleteChkBxItem = (CheckBox)gr.Cells[0].FindControl("deletethis");
                    deleteChkBxItem.Checked = true;
                    int intLength = empId.Length;
                    //int intActualIndex = 0;
                    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["SwipesID"] = strEmpId;
                    goto D;
                }
            }
        D: ;
        }
    }
    protected string GetEmployeeIdsInOtherPagesOfGrid()
    {
        DataTable dtSwipes = new DataTable();
        dtSwipes = (DataTable)ViewState["dtSwipes"];
        string strEmpId = string.Empty;
        string ChkBoxIDs = string.Empty;
        foreach (DataRow dr in dtSwipes.Rows)
        {
            foreach (GridViewRow gr in grd.Rows)
            {
                strEmpId = Convert.ToString(((Label)gr.FindControl("lblClkID")).Text);
                //strEmpId = ((HiddenField)gr.FindControl("lblProcess_Rec_ID")).Value.ToString();
                CheckBox chkEnabled = (CheckBox)gr.FindControl("deletethis");
                if (chkEnabled.Enabled == false)
                {
                    goto A;
                }
                if (strEmpId == Convert.ToString(dr["Clk_ID"]))
                {
                    goto A;
                }
            }
            if (ChkBoxIDs == "")
            {
                ChkBoxIDs = Convert.ToString(dr["Clk_ID"]);
            }
            else
            {
                ChkBoxIDs = ChkBoxIDs + "," + Convert.ToString(dr["Clk_ID"]);
            }
        A: ;
        }
        return ChkBoxIDs;
    }
    #endregion
    #region Button Events
    /// <summary>
    /// To exclude the swipes
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnVoid_Click(object sender, EventArgs e)
    {
        SwipesHandlingEventData objClass = new SwipesHandlingEventData();
        int intAppoveCount = 0;
        int intLoopCounter = 0;
        int intClkID = 0;
        string strEmployeeName = string.Empty;
        string strRemarks = string.Empty;
        DataTable dtSwipes = new DataTable();
        dtSwipes = (DataTable)ViewState["dtSwipes"];
        string strSwipeIDs = Convert.ToString(Session["SwipesID"]);
        char[] Delimit ={ ',' };
        string[] SwipeIDs = strSwipeIDs.Split(Delimit);
        CheckBox chkSelect = new CheckBox();
        CheckBox chkSelectAll = new CheckBox();
        //strRemarks = txtRemarks.Text.Trim();
        intCount = dtSwipes.Rows.Count;
        chkSelectAll = (CheckBox)grd.HeaderRow.Cells[0].FindControl("checkall");
        if (chkSelectAll.Checked)
        {
            //foreach (DataRow dr in dtSwipes.Rows)
            //{
            //    intClkID = Convert.ToInt32(dr["Clk_ID"].ToString());                
            //    objClass.UpdateSwipes(intClkID,"Void");
            //    CheckGrid = true;
            //}
            if (dtSwipes.Rows.Count > 0)
            {
                StringWriter strXMLData = new StringWriter();
                dtSwipes.WriteXml(strXMLData);
                objClass.UpdateSwipes_Group("Void", Convert.ToString(strXMLData));
                CheckGrid = true;
            }
        }
        else
        {
            foreach (GridViewRow gr in grd.Rows)
            {
                chkSelect = (CheckBox)gr.Cells[0].FindControl("deletethis");
                if (chkSelect.Checked)
                {
                    string lblClkID = Convert.ToString(((Label)gr.FindControl("lblClkID")).Text);
                    for (intLoopCounter = 0; intLoopCounter < intCount; intLoopCounter++)
                    {
                        if (Convert.ToString(dtSwipes.Rows[intLoopCounter]["Clk_ID"]) == lblClkID)
                        {
                            intClkID = Convert.ToInt32(dtSwipes.Rows[intLoopCounter]["Clk_ID"]);
                            objClass.UpdateSwipes(intClkID, "Void");
                            CheckGrid = true;
                        }
                    }
                }
            }
            foreach (string EmpCId in SwipeIDs)
            {
                for (intLoopCounter = 0; intLoopCounter < intCount; intLoopCounter++)
                {
                    if (Convert.ToString(dtSwipes.Rows[intLoopCounter]["Clk_ID"]) == EmpCId)
                    {
                        intClkID = Convert.ToInt32(dtSwipes.Rows[intLoopCounter]["Clk_ID"]);
                        objClass.UpdateSwipes(intClkID, "Void");
                        CheckGrid = true;
                    }
                }
            }
        }
        if (CheckGrid == false)
        {
            //Message("Select Any Record");
            Message(rm.GetString("Alert_SelectAnyRecord", ci));
        }
        else
        {
            //BindGrid();
            ///Message(""); 
            string strScript = "<script language='javascript' type='text/javascript'>";
            strScript += "alert('" + rm.GetString("Alert_SwipesflagUpdatedSuccessfully", ci) + "');parent.$('#myModal').modal('hide');";
            //strScript += " parent.$('#myModal').modal('hide');</script>";
            strScript += " </script>";
            this.RegisterStartupScript("closeScript", strScript);
        }
    }
    /// <summary>
    /// To include the swipes
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnUnVoid_Click(object sender, EventArgs e)
    {
        SwipesHandlingEventData objClass = new SwipesHandlingEventData();
        bool CheckGrid = false;
        int intAppoveCount = 0;
        int intLoopCounter = 0;
        int intClkID = 0;
        string strEmployeeName = string.Empty;
        string strRemarks = string.Empty;
        DataTable dtSwipes = new DataTable();
        dtSwipes = (DataTable)ViewState["dtSwipes"];
        string strSwipeIDs = Convert.ToString(Session["SwipesID"]);
        char[] Delimit ={ ',' };
        string[] SwipeIDs = strSwipeIDs.Split(Delimit);
        CheckBox chkSelect = new CheckBox();
        CheckBox chkSelectAll = new CheckBox();
        //strRemarks = txtRemarks.Text.Trim();
        intCount = dtSwipes.Rows.Count;
        chkSelectAll = (CheckBox)grd.HeaderRow.Cells[0].FindControl("checkall");
        if (chkSelectAll.Checked)
        {
            //foreach (DataRow dr in dtSwipes.Rows)
            //{
            //    intClkID = Convert.ToInt32(dr["Clk_ID"].ToString());
            //    objClass.UpdateSwipes(intClkID, "UnVoid");
            //    CheckGrid = true;
            //}
            if (dtSwipes.Rows.Count > 0)
            {
                StringWriter strXMLData = new StringWriter();
                dtSwipes.WriteXml(strXMLData);
                objClass.UpdateSwipes_Group("UnVoid", Convert.ToString(strXMLData));
                CheckGrid = true;
            }
        }
        else
        {
            foreach (GridViewRow gr in grd.Rows)
            {
                chkSelect = (CheckBox)gr.Cells[0].FindControl("deletethis");
                if (chkSelect.Checked)
                {
                    string lblClkID = Convert.ToString(((Label)gr.FindControl("lblClkID")).Text);
                    for (intLoopCounter = 0; intLoopCounter < intCount; intLoopCounter++)
                    {
                        if (Convert.ToString(dtSwipes.Rows[intLoopCounter]["Clk_ID"]) == lblClkID)
                        {
                            intClkID = Convert.ToInt32(dtSwipes.Rows[intLoopCounter]["Clk_ID"]);
                            objClass.UpdateSwipes(intClkID, "UnVoid");
                            CheckGrid = true;
                        }
                    }
                }
            }
            foreach (string EmpCId in SwipeIDs)
            {
                for (intLoopCounter = 0; intLoopCounter < intCount; intLoopCounter++)
                {
                    if (Convert.ToString(dtSwipes.Rows[intLoopCounter]["Clk_ID"]) == EmpCId)
                    {
                        intClkID = Convert.ToInt32(dtSwipes.Rows[intLoopCounter]["Clk_ID"]);
                        objClass.UpdateSwipes(intClkID, "UnVoid");
                        CheckGrid = true;
                    }
                }
            }
        }
        if (CheckGrid == false)
        {
            Message(rm.GetString("Alert_SelectAnyRecord", ci));
        }
        else
        {
            //BindGrid();
            //Message("Swipes flag Updated Successfully");
            string strScript = "<script language='javascript' type='text/javascript'>";
            strScript += "alert('" + rm.GetString("Alert_SwipesflagUpdatedSuccessfully", ci) + "');parent.$('#myModal').modal('hide');";
            strScript += " </script>";
            this.RegisterStartupScript("closeScript", strScript);
        }
    }
    #endregion
    #region Grid events
    protected void grd_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);
        }
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            //check for null values
            Label lblInDate = (Label)e.Row.Cells[1].FindControl("lblInDate");
            Label lblInTime = (Label)e.Row.Cells[1].FindControl("lblInTime");
            Label lblIsVoid = (Label)e.Row.Cells[1].FindControl("lblIsVoid");
            if (lblIsVoid.Text == "True")
            {
                lblIsVoid.ForeColor = System.Drawing.Color.Red;
                lblIsVoid.Text = rm.GetString("ShiftSetting_Yes", ci);
            }
            if (lblIsVoid.Text == "False")
            {
                lblIsVoid.ForeColor = System.Drawing.Color.Black;
                //lblIsVoid.Text = "No";
                lblIsVoid.Text = rm.GetString("ShiftSetting_No", ci);
            }
        }
    }
    protected void grv_CheckAll_CheckedChanged(object sender, EventArgs e)
    {
        CheckBox chkSelect = new CheckBox();
        chkSelect = (CheckBox)grd.HeaderRow.Cells[0].FindControl("checkall");
        string ChkBoxIDs = string.Empty;
        if (chkSelect.Checked)
        {
            ChkBoxIDs = GetEmployeeIdsInOtherPagesOfGrid();
            if (Convert.ToString(Session["SwipesID"]) == "")
            {
                Session["SwipesID"] = ChkBoxIDs;
            }
            else
            {
                if (ChkBoxIDs != "")
                {
                    Session["SwipesID"] = Session["SwipesID"] + "," + ChkBoxIDs;
                }
            }
        }
        else
        {
            Session["SwipesID"] = string.Empty;
        }
        foreach (GridViewRow gr in grd.Rows)
        {
            chkSelect = (CheckBox)gr.Cells[0].FindControl("deletethis");
            chkSelect.Checked = ((CheckBox)sender).Checked;
        }
    }
    protected void grv_Check_CheckedChanged(object sender, EventArgs e)
    {
        string ChkBoxIDs = string.Empty;
        int intCount = 0;
        int intGridPageSize = grd.PageSize;
        int intGridTotalPages = grd.PageCount;
        bool boolAllChecked = false;
        CheckBox chkSelect = new CheckBox();
        CheckBox chkSelectAll = new CheckBox();
        chkSelectAll = (CheckBox)grd.HeaderRow.Cells[0].FindControl("checkall");
        if (((CheckBox)sender).Checked == false)
        {
            chkSelectAll.Checked = false;
        }
        else
        {
            foreach (GridViewRow gr in grd.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["TotalSwipes"]) == intCount)
            {
                //no paging and all chekbox is in checked state
                chkSelectAll.Checked = true;
            }
            else if (intCount > 0 && Convert.ToInt32(Session["TotalSwipes"]) > intCount && Convert.ToInt32(Session["TotalSwipes"]) > intGridPageSize)
            {
                //Paging is present.
                if (intCount == intGridPageSize)
                {   //All checkbox are checked in the current page
                    if (Session["SwipesID"] != null || Convert.ToString(Session["SwipesID"]) != string.Empty)
                    {   //some checkbox in other pages is also checked
                        ChkBoxIDs = GetEmployeeIdsInOtherPagesOfGrid();
                        char[] Delimit ={ ',' };
                        string[] SessionEmployeeIds = Convert.ToString(Session["SwipesID"]).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 (grd.PageIndex == intGridTotalPages - 1)
                {   //Last Page
                    int intLastPageCount = Convert.ToInt32(Session["TotalSwipes"]) - (intGridPageSize * (intGridTotalPages - 1));
                    if (intCount == intLastPageCount)
                    {
                        if (Session["SwipesID"] != null || Convert.ToString(Session["SwipesID"]) != string.Empty)
                        {   //some checkbox in other pages is also checked
                            ChkBoxIDs = GetEmployeeIdsInOtherPagesOfGrid();
                            char[] Delimit ={ ',' };
                            string[] SessionEmployeeIds = Convert.ToString(Session["SwipesID"]).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;
                            }
                        }
                    }
                }
            }
        }
    }
    protected void grd_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        //gdManualEntrySanctionView.PageIndex = e.NewPageIndex;
        //BindManualEntrySanctionDetails();
        //Session["EmployeeIds"] = "";
        grd.EnableViewState = true;
        string ChkBoxIDs = "";
        //bool BxsChkd = false;
        CheckBox deleteChkBxItem = new CheckBox();
        // Add EmployeeId in Session Variable.
        foreach (GridViewRow i in grd.Rows)
        {
            //HtmlInputCheckBox deleteChkBxItem = (HtmlInputCheckBox)i.FindControl("deletethis");
            deleteChkBxItem = (CheckBox)i.Cells[0].FindControl("deletethis");
            if (deleteChkBxItem.Checked)
            {
                //BxsChkd = true;
                if (ChkBoxIDs == "")
                {
                    ChkBoxIDs = Convert.ToString(((Label)i.FindControl("lblClkID")).Text);
                }
                else
                {
                    // Concatenate DataGrid item with comma for SQL Delete
                    ChkBoxIDs = ChkBoxIDs + "," + Convert.ToString(((Label)i.FindControl("lblClkID")).Text);
                }
            }
        }
        if (Convert.ToString(Session["SwipesID"]) == "")
        {
            Session["SwipesID"] = ChkBoxIDs;
        }
        else
        {
            if (ChkBoxIDs != "")
            {
                Session["SwipesID"] = Session["SwipesID"] + "," + ChkBoxIDs;
            }
        }
        CheckBox chkSelect = new CheckBox();
        chkSelect = (CheckBox)grd.HeaderRow.Cells[0].FindControl("checkall");
        Session["SelectAllStatus"] = chkSelect.Checked;
        grd.PageIndex = e.NewPageIndex;
        BindGrid();
        CheckSwipes_CheckBox();
    }
    #endregion
}
