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.Text.RegularExpressions;

public partial class Reports_GetEmailIds : System.Web.UI.Page
{
    Rpt_Common rptcommon = new Rpt_Common();
    EmployeeEventData objEmployeeEventData = new EmployeeEventData();
    ResourceManager rm;
    CultureInfo ci;

    bool gblnCheckRecordExists, gblnCheckLevel;
    int gintLevelID = 0;

    protected void Page_Load(object sender, EventArgs e)
    {
        Session.LCID = 1033;
        if (Session["Session_ActiveLanguage"] == null)
        {
            string strScript1 = "<script language='javascript' type='text/javascript'>";
            strScript1 += "alert('Session Expired...');parent.$('#myModal').modal('hide');";
            strScript1 += " </script>";
            this.RegisterStartupScript("closeScript1", strScript1);
            return;
        }
        if (Session["Session_ActiveLanguage"] == null)
        {
            string str = "<script language=\"javascript\">";

            //str = str + "opener.focus();";
            //str = str + "alert(opener.location+'?fl=1&sid=';";

            str = str + "top.location.href = top.location + '?fl=1&sid=" + Session.SessionID + "';";

            str = str + "parent.$('#myModal').modal('hide');";

            str = str + "</script>";

            Response.Write(str);
        }
        else
        {
            string source_Language;
            source_Language = Session["Session_ActiveLanguage"].ToString();
            rm = new ResourceManager(source_Language, System.Reflection.Assembly.Load("App_GlobalResources"));
            aspnetForm.Attributes.CssStyle.Add("Direction", rm.GetString("Direction", ci));
            ci = Thread.CurrentThread.CurrentCulture;
           
            // Call the function LoadStrings to load the Label Names from the Resource Files
            LoadStrings(ci);
        }
        loadcss();
        if (!IsPostBack)
        {
            string str = Request.QueryString["MailType"].ToString();
            string strScript = "<script language='javascript' type='text/javascript'>";
            strScript += "GetEmailList('" + str.ToString() + "');";
            strScript += " </script>";
            this.RegisterStartupScript("setScript", strScript);

            if (Request.QueryString["MailType"] == "CC")
            {
                btnAddCC.Text = "Add CC";
            }
            else
            {
                btnAddCC.Text = "Add TO";
            }
            //btn_Ok.Visible = false;
        }

        gblnCheckRecordExists = true;

        btn_Back.Attributes.Add("onclick", "window.close();return false;");
    }

    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
        Report_htmlGetEmail.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";
        }
    }

    //protected void btn_Ok_Click(object sender, EventArgs e)
    //{
    //    Rpt_Common rptcommon = new Rpt_Common();

    //    CheckBox chkSelect = new CheckBox();
    //    CheckBox chkSelectAll = new CheckBox();

    //    DataSet dsEmployee = new DataSet();

    //    int intEmployeeId = 0;
    //    int intLoopCounter = 0;
    //    string strEmployeeCode = string.Empty;
    //    string strEmployeeName = string.Empty;
    //    string strEmailId = string.Empty;
    //    string strLevel = string.Empty;
    //    string strEmailIds = string.Empty;

    //    string strEmployeeIds = Session["EmployeeIds"].ToString();
    //    char[] Delimit = { ',' };
    //    string[] EmployeeIds = strEmployeeIds.Split(Delimit);

    //    gintLevelID = Convert.ToInt32(Session["currentSession"]);

    //    if (gintLevelID != 0)
    //        strLevel = rptcommon.getNodes(gintLevelID, Convert.ToString(Session["LevelRights"]));

    //    dsEmployee = objEmployeeEventData.SelectEmployeeEmailId(strLevel, txtEmployeeName.Text, txtEmployeeCode.Text, "SuperAdmin", Convert.ToString(Session["GradeLevel"]));
    //    int intCount = dsEmployee.Tables[0].Rows.Count;

    //    chkSelectAll = (CheckBox)grv_Employee.HeaderRow.Cells[0].FindControl("checkall");

    //    if (chkSelectAll.Checked)
    //    {
    //        foreach (DataRow drEmployee in dsEmployee.Tables[0].Rows)
    //        {
    //            intEmployeeId = Convert.ToInt32(drEmployee["Employee_Id"].ToString());
    //            strEmployeeCode = drEmployee["Employee_Code_Id"].ToString();
    //            strEmployeeName = drEmployee["Employee Name"].ToString();
    //            strEmailId = drEmployee["EmailId"].ToString();

    //            if (strEmailId != string.Empty)
    //            {
    //                if (strEmailIds == string.Empty)
    //                {
    //                    strEmailIds = strEmailId;
    //                }
    //                else
    //                {
    //                    if (!strEmailIds.Contains(strEmailId))
    //                    {
    //                        strEmailIds = strEmailIds + ";" + strEmailId;
    //                    }
    //                }
    //            }
    //        }
    //    }
    //    else
    //    {
    //        strEmailIds = string.Empty;

    //        foreach (GridViewRow gr in grv_Employee.Rows)
    //        {
    //            chkSelect = (CheckBox)gr.Cells[0].FindControl("deletethis");

    //            if (chkSelect.Checked)
    //            {
    //                string strEmpCodeId = ((Label)gr.FindControl("lbl_EmpId")).Text.ToString();
    //                for (intLoopCounter = 0; intLoopCounter < intCount; intLoopCounter++)
    //                {
    //                    if (dsEmployee.Tables[0].Rows[intLoopCounter]["Employee_Code_Id"].ToString() == strEmpCodeId)
    //                    {
    //                        intEmployeeId = Convert.ToInt32(dsEmployee.Tables[0].Rows[intLoopCounter]["Employee_Id"].ToString());
    //                        strEmployeeCode = dsEmployee.Tables[0].Rows[intLoopCounter]["Employee_Code_Id"].ToString();
    //                        strEmployeeName = dsEmployee.Tables[0].Rows[intLoopCounter]["Employee Name"].ToString();
    //                        strEmailId = dsEmployee.Tables[0].Rows[intLoopCounter]["EmailId"].ToString();

    //                        if (strEmailId != string.Empty)
    //                        {
    //                            if (strEmailIds == string.Empty)
    //                            {
    //                                strEmailIds = strEmailId;
    //                            }
    //                            else
    //                            {
    //                                if (!strEmailIds.Contains(strEmailId))
    //                                {
    //                                    strEmailIds = strEmailIds + ";" + strEmailId;
    //                                }

    //                            }
    //                        }
    //                    }
    //                }
    //            }
    //        }

    //        foreach (string EmpCId in EmployeeIds)
    //        {
    //            for (intLoopCounter = 0; intLoopCounter < intCount; intLoopCounter++)
    //            {
    //                if (dsEmployee.Tables[0].Rows[intLoopCounter]["Employee_Code_Id"].ToString() == EmpCId)
    //                {
    //                    intEmployeeId = Convert.ToInt32(dsEmployee.Tables[0].Rows[intLoopCounter]["Employee_Id"].ToString());
    //                    strEmployeeCode = dsEmployee.Tables[0].Rows[intLoopCounter]["Employee_Code_Id"].ToString();
    //                    strEmployeeName = dsEmployee.Tables[0].Rows[intLoopCounter]["Employee Name"].ToString();
    //                    strEmailId = dsEmployee.Tables[0].Rows[intLoopCounter]["EmailId"].ToString();
    //                    //obj.InsertEmpDetails(intEmployeeId, strEmployeeCode, strEmployeeName.Replace("'", "''"), loginEmployeeId);

    //                    if (strEmailId != string.Empty)
    //                    {
    //                        if (strEmailIds == string.Empty)
    //                        {
    //                            strEmailIds = strEmailId;
    //                        }
    //                        else
    //                        {
    //                            if (!strEmailIds.Contains(strEmailId))
    //                            {
    //                                strEmailIds = strEmailIds + ";" + strEmailId;
    //                            }
    //                        }
    //                    }
    //                }
    //            }
    //        }
    //    }

    //    string strScript = "<script language=\"javascript\">";
    //    if (Request.QueryString["MailType"] == "CC")
    //    {
    //        strScript = strScript + "if (window.opener.parent.aspnetForm['ctl00_BodyContentPH_txtApprovalCC'].value=='') {";
    //        strScript = strScript + "window.opener.parent.aspnetForm['ctl00_BodyContentPH_txtApprovalCC'].value='" + strEmailIds + "';}";
    //        strScript = strScript + "else { window.opener.parent.aspnetForm['ctl00_BodyContentPH_txtApprovalCC'].value= window.opener.parent.aspnetForm['ctl00_BodyContentPH_txtApprovalCC'].value + ';" + strEmailIds + "';}";
    //    }
    //    else
    //    {
    //        strScript = strScript + "if (window.opener.parent.aspnetForm['ctl00_BodyContentPH_txtApprovalTO'].value=='') {";
    //        strScript = strScript + "window.opener.parent.aspnetForm['ctl00_BodyContentPH_txtApprovalTO'].value='" + strEmailIds + "';}";
    //        strScript = strScript + "else { window.opener.parent.aspnetForm['ctl00_BodyContentPH_txtApprovalTO'].value= window.opener.parent.aspnetForm['ctl00_BodyContentPH_txtApprovalTO'].value + ';" + strEmailIds + "';}";
    //    }
    //    strScript = strScript + "self.close();";
    //    strScript = strScript + "</script>";
    //    Response.Write(strScript);
    //}

    protected void btnAddCC_Click(object sender, EventArgs e)
    {
        if (grv_Employee.Visible == false)
        {
        }
        else
        {
            Rpt_Common rptcommon = new Rpt_Common();

            CheckBox chkSelect = new CheckBox();
            CheckBox chkSelectAll = new CheckBox();

            DataSet dsEmployee = new DataSet();

            int intEmployeeId = 0;
            int intLoopCounter = 0;
            string strEmployeeCode = string.Empty;
            string strEmployeeName = string.Empty;
            string strEmailId = string.Empty;
            string strLevel = string.Empty;
            string strEmailIds = string.Empty;
            strEmailIds = txtAddCC.Text;

            string strEmployeeIds = Session["EmployeeIds"].ToString();
            char[] Delimit = { ',' };
            string[] EmployeeIds = strEmployeeIds.Split(Delimit);

            gintLevelID = Convert.ToInt32(Session["currentSession"]);

            if (gintLevelID != 0)
                strLevel = rptcommon.getNodes(gintLevelID, Convert.ToString(Session["LevelRights"]));

            //dsEmployee = objEmployeeEventData.SelectEmployeeEmailId(strLevel, txtEmployeeName.Text, txtEmployeeCode.Text, "SuperAdmin", Convert.ToString(Session["GradeLevel"]));
            if (Session["dsEmployees"] != null)
            {
                dsEmployee = (DataSet)Session["dsEmployees"];
            }
            int intCount = dsEmployee.Tables[0].Rows.Count;

            chkSelectAll = (CheckBox)grv_Employee.HeaderRow.Cells[0].FindControl("checkall");

            if (chkSelectAll.Checked)
            {
                foreach (DataRow drEmployee in dsEmployee.Tables[0].Rows)
                {
                    intEmployeeId = Convert.ToInt32(drEmployee["Employee_Id"].ToString());
                    strEmployeeCode = drEmployee["Employee_Code_Id"].ToString();
                    strEmployeeName = drEmployee["Employee Name"].ToString();
                    strEmailId = drEmployee["EmailId"].ToString();

                    if (strEmailId != string.Empty)
                    {
                        if (strEmailIds == string.Empty)
                        {
                            strEmailIds = strEmailId;
                        }
                        else
                        {
                            if (!strEmailIds.Contains(strEmailId))
                            {
                                strEmailIds = strEmailIds + ";" + strEmailId;
                            }
                        }
                    }
                }
            }
            else
            {
                // strEmailIds = string.Empty;
                //strEmailIds = txtAddCC.Text;
                foreach (GridViewRow gr in grv_Employee.Rows)
                {
                    chkSelect = (CheckBox)gr.Cells[0].FindControl("deletethis");

                    if (chkSelect.Checked)
                    {
                        string strEmpCodeId = ((Label)gr.FindControl("lbl_EmpId")).Text.ToString();
                        for (intLoopCounter = 0; intLoopCounter < intCount; intLoopCounter++)
                        {
                            if (dsEmployee.Tables[0].Rows[intLoopCounter]["Employee_Code_Id"].ToString() == strEmpCodeId)
                            {
                                intEmployeeId = Convert.ToInt32(dsEmployee.Tables[0].Rows[intLoopCounter]["Employee_Id"].ToString());
                                strEmployeeCode = dsEmployee.Tables[0].Rows[intLoopCounter]["Employee_Code_Id"].ToString();
                                strEmployeeName = dsEmployee.Tables[0].Rows[intLoopCounter]["Employee Name"].ToString();
                                strEmailId = dsEmployee.Tables[0].Rows[intLoopCounter]["EmailId"].ToString();

                                if (strEmailId != string.Empty)
                                {
                                    if (strEmailIds == string.Empty)
                                    {
                                        strEmailIds = strEmailId;
                                    }
                                    else
                                    {
                                        if (!strEmailIds.Contains(strEmailId))
                                        {
                                            strEmailIds = strEmailIds + ";" + strEmailId;
                                        }

                                    }
                                }
                            }
                        }
                    }
                }
                //strEmailIds = txtAddCC.Text;
                foreach (string EmpCId in EmployeeIds)
                {
                    for (intLoopCounter = 0; intLoopCounter < intCount; intLoopCounter++)
                    {
                        if (dsEmployee.Tables[0].Rows[intLoopCounter]["Employee_Code_Id"].ToString() == EmpCId)
                        {
                            intEmployeeId = Convert.ToInt32(dsEmployee.Tables[0].Rows[intLoopCounter]["Employee_Id"].ToString());
                            strEmployeeCode = dsEmployee.Tables[0].Rows[intLoopCounter]["Employee_Code_Id"].ToString();
                            strEmployeeName = dsEmployee.Tables[0].Rows[intLoopCounter]["Employee Name"].ToString();
                            strEmailId = dsEmployee.Tables[0].Rows[intLoopCounter]["EmailId"].ToString();
                            //obj.InsertEmpDetails(intEmployeeId, strEmployeeCode, strEmployeeName.Replace("'", "''"), loginEmployeeId);

                            if (strEmailId != string.Empty)
                            {
                                if (strEmailIds == string.Empty)
                                {
                                    strEmailIds = strEmailId;
                                }
                                else
                                {
                                    if (!strEmailIds.Contains(strEmailId))
                                    {
                                        strEmailIds = strEmailIds + ";" + strEmailId;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            txtAddCC.Text = strEmailIds;

        }
    }

    protected void btn_Ok_Click(object sender, EventArgs e)
    {
        if (txtAddCC.Text != string.Empty)
        {
            string[] strEmailList;
            string strEmailIds = string.Empty;
            strEmailList = txtAddCC.Text.Split(';');
            foreach (string strEmailID in strEmailList)
            {
                if (!Regex.IsMatch(strEmailID, @"^(?("")("".+?""@)|(([0-9a-zA-Z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-zA-Z])@))(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,6}))$"))
                {
                    if (strEmailID != string.Empty)
                    {
                        string strScript1 = "<script language='javascript' type='text/javascript'>";
                        strScript1 += "alert('" + rm.GetString("Alert_InvalidEmail", ci) + " -  " + strEmailID + "');";
                        strScript1 += " </script>";
                        this.RegisterStartupScript("Incorrect", strScript1);
                        return;
                    }
                }
                else if (strEmailID != string.Empty)
                {
                    if (strEmailIds == string.Empty)
                    {
                        strEmailIds = strEmailID;
                    }
                    else
                    {
                        strEmailIds = strEmailIds + ";" + strEmailID;
                    }
                }
            }
            txtAddCC.Text = strEmailIds;
        }

        string strScript = "<script language=\"javascript\">";
        if (Request.QueryString["MailType"] == "CC")
        {
            //strScript = strScript + "{window.opener.parent.aspnetForm['ctl00_BodyContentPH_txtApprovalCC'].value='" + txtAddCC.Text + "';}";
            strScript = strScript + "{window.top.parent.document.getElementById('ctl00_BodyContentPH_txtApprovalCC').value='" + txtAddCC.Text + "';}";

        }
        else
        {
            //strScript = strScript + "{window.opener.parent.aspnetForm['ctl00_BodyContentPH_txtApprovalTO'].value='" + txtAddCC.Text + "';}";
            strScript = strScript + "{window.top.parent.document.getElementById('ctl00_BodyContentPH_txtApprovalTO').value='" + txtAddCC.Text + "';}";
        }
        strScript = strScript + "parent.$('#myModal').modal('hide');";
        strScript = strScript + "</script>";
        //string str = strScript;
        Response.Write(strScript);
    }

    protected void btn_Go_Click(object sender, EventArgs e)
    {
        Session["EmployeeIds"] = string.Empty;
        Session["currentSession"] = Session["parentLevelId"];
        Session["parentLevelId"] = null;
        
        EmployeeDataBind();
        
        if (gblnCheckLevel == true)
        {
            return;
        }

        if (gblnCheckRecordExists == true)
        {
            btn_Ok.Visible = true;
        }
        else
        {
            grv_Employee.Visible = false;
            btn_Ok.Visible = false;
            lblError.Text = "There is no records";

            string strMsg;
            strMsg = "<script language='javascript'>";
            strMsg = strMsg + "alert('" + rm.GetString("DeletionRecordAlert", ci) + "');";
            strMsg = strMsg + "</script>";
        }
    }

    protected void grv_Employee_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            CheckBox deleteChkBxItem = (CheckBox)e.Row.Cells[0].FindControl("deletethis");
            string strEmailId = Convert.ToString(((Label)e.Row.Cells[0].FindControl("lbl_EmailId")).Text);

            // Enable the Check Box for the employees who have Email Ids
            if (strEmailId == string.Empty)
            {
                deleteChkBxItem.Enabled = false;
                deleteChkBxItem.ToolTip = "No Email Id for this Employee";
            }
            else
            {
                deleteChkBxItem.Enabled = true;
                deleteChkBxItem.ToolTip = string.Empty;
            }
        }
    }

    /// <summary>
    /// Bind Employee Name along with Code Id in the List Box based on the Organization Level,
    /// Employee Name and Employee Id
    /// </summary>
    /// 
    public void EmployeeDataBind()
    {
        DataSet dsEmployee = new DataSet();
        string strLevel = string.Empty;

        gintLevelID = Convert.ToInt32(Session["currentSession"]);

        if (gintLevelID != 0)
        {
            strLevel = rptcommon.getNodes(gintLevelID, Convert.ToString(Session["LevelRights"]));
            lblError.Text = string.Empty;
        }
        else
        {
            grv_Employee.DataSourceID = string.Empty;
            grv_Employee.DataBind();
            grv_Employee.Visible = false;
            btn_Ok.Visible = false;
            lblError.Text = "Select Organization level";
            gblnCheckLevel = true;
            gblnCheckRecordExists = false;
            return;
        }

        //dsEmployee = objEmployeeEventData.SelectEmployeeEmailId(strLevel, txtEmployeeName.Text, txtEmployeeCode.Text, Session["UserGroupName"].ToString(), Convert.ToString(Session["GradeLevel"]));
        dsEmployee = objEmployeeEventData.SelectEmployeeEmailId(strLevel, txtEmployeeName.Text, txtEmployeeCode.Text, "SuperAdmin", Convert.ToString(Session["GradeLevel"]));

        if (dsEmployee.Tables.Count > 0)
        {
            if (dsEmployee.Tables[0].Rows.Count > 0)
            {
                // Load Employee in the Employee Grid
                grv_Employee.DataSource = dsEmployee;
                grv_Employee.DataBind();

                Session["TotalEmployees"] = dsEmployee.Tables[0].Rows.Count;
                Session["dsEmployees"] = dsEmployee;
                grv_Employee.Visible = true;
                btn_Ok.Visible = true;
            }
            else
            {
                Session["dsEmployees"] = null;
                btn_Ok.Visible = false;
                gblnCheckRecordExists = false;
            }
        }
        else
        {
            gblnCheckRecordExists = false;
        }
    }

    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();

            if (Session["EmployeeIds"].ToString() == string.Empty)
            {
                Session["EmployeeIds"] = ChkBoxIDs;
            }
            else
            {
                if (ChkBoxIDs != string.Empty)
                {
                    Session["EmployeeIds"] = Session["EmployeeIds"] + "," + ChkBoxIDs;
                }
            }
        }
        else
        {
            Session["EmployeeIds"] = string.Empty;
        }

        foreach (GridViewRow gr in grv_Employee.Rows)
        {
            string strEmailId = Convert.ToString(((Label)gr.Cells[0].FindControl("lbl_EmailId")).Text);

            if (strEmailId != string.Empty)
            {
                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 = grv_Employee.PageSize;
        int intGridTotalPages = grv_Employee.PageCount;
        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;
            }
            else if (intCount > 0 && Convert.ToInt32(Session["TotalEmployees"].ToString()) > intCount && 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;
                            }
                        }
                    }
                }
            }
        }
    }

    protected string GetEmployeeIdsInOtherPagesOfGrid()
    {
        Rpt_Common rptcommon = new Rpt_Common();
        DataSet dsEmployee = new DataSet();

        string strLevel = string.Empty;
        string strEmpId = string.Empty;
        string ChkBoxIDs = string.Empty;

        gintLevelID = Convert.ToInt32(Session["currentSession"]);

        if (gintLevelID != 0)
            strLevel = rptcommon.getNodes(gintLevelID, Convert.ToString(Session["LevelRights"]));

        dsEmployee = objEmployeeEventData.SelectEmployeeEmailId(strLevel, txtEmployeeName.Text, txtEmployeeCode.Text, Session["UserGroupName"].ToString(), Convert.ToString(Session["GradeLevel"]));

        foreach (DataRow dr in dsEmployee.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 == string.Empty)
            {
                ChkBoxIDs = dr["Employee_Code_Id"].ToString();
            }
            else
            {
                ChkBoxIDs = ChkBoxIDs + "," + dr["Employee_Code_Id"].ToString();
            }
            A: ;
        }

        return ChkBoxIDs;
    }

    protected void grv_Employee_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        CheckBox deleteChkBxItem = new CheckBox();
        string ChkBoxIDs = string.Empty;
        
        grv_Employee.EnableViewState = true;

        // 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"].ToString() == string.Empty)
        {
            Session["EmployeeIds"] = ChkBoxIDs;
        }
        else
        {
            if (ChkBoxIDs != string.Empty)
            {
                Session["EmployeeIds"] = Session["EmployeeIds"] + "," + ChkBoxIDs;
            }
        }

        CheckBox chkSelect = new CheckBox();
        chkSelect = (CheckBox)grv_Employee.HeaderRow.Cells[0].FindControl("checkall");
        Session["SelectAllStatus"] = chkSelect.Checked;

        grv_Employee.PageIndex = e.NewPageIndex;
        EmployeeDataBind();
        CheckEmployeeId_CheckBox();
    }

    public void CheckEmployeeId_CheckBox()
    {
        CheckBox deleteChkBxItem = new CheckBox();
        string strEmpId = string.Empty;

        strEmpId = (string)Session["EmployeeIds"];
        int intEmployeeIdsLength = strEmpId.Length;

        char[] Delimit ={ ',' };
        string[] Empid = strEmpId.Split(Delimit);

        foreach (GridViewRow gr in grv_Employee.Rows)
        {
            string empId = ((Label)gr.FindControl("lbl_EmpId")).Text.ToString();

            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["EmployeeIds"] = strEmpId;
                    goto D;
                }
            }
            D: ;
        }
    }

    /// <summary>
    /// LoadStrings Method is used to load the Label Names from the Resource File
    /// </summary>
    /// <param name="ci"></param>
    private void LoadStrings(CultureInfo ci)
    {
        lblEmployeeName.Text = rm.GetString("email_EmployeeName", ci);
        lblEmployeeCode.Text = rm.GetString("email_EmployeeId", ci);

        btn_Go.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Go", ci);
        btn_Ok.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Ok", ci);
        btn_Back.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Back", ci);
    }

}
