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.Data.SqlClient;
using System.Globalization;
using System.Threading;
using System.Reflection;
using System.Resources;
using System.IO;


public partial class Transactions_PopUpOnDutyEntryApproval : Base.BasePage
{

    #region Variable Declaration

    ResourceManager rm;
    CultureInfo ci;

    Cls_CheckUser objCheckUser = new Cls_CheckUser();
    ManualEntryEventData objManualEntryEventData = new ManualEntryEventData();
    LeaveApplicationEventData objLeaveApplicationEventData = new LeaveApplicationEventData();
    YearSettingsEventData objYearSettingsEventData = new YearSettingsEventData();
    cls_Common objcls_Common = new cls_Common();
    Rpt_Common rptcommon = new Rpt_Common();

    DataTable dtManualEntrySanctionView = new DataTable();
    DataSet dsYearSetting = new DataSet();
    DataSet ds_Checkuser = new DataSet();

    int vmonthValue;
    string startDate;
    bool CheckGrid = false;
    bool statusProcess = false;
    bool checkRecordExists;
    int intCount, EmployeeCategory, EmployeeType;
    string endDate, gstrDateFormat, LevelId, Status, From_Date, To_Date, StartMonth, EndMonth, StartYear, EndYear;
    string EmployeeID, EmployeeName;
    string strSwipeCard = "";

    #endregion

    #region Page Load events
    /// <summary>
    /// on page loading
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected override void Page_Load(object sender, EventArgs e)
    {
        // session checking
        base.Page_Load(sender, e);

        //if Standar Edition set the visibility to false

        int manualEntryExists = 0;
        manualEntryExists = objcls_Common.CheckPageExistsInLicense(248);

        //if (Session["Edition"].ToString() == "1")
        if (manualEntryExists == 0)
        {
            string strScripts = "";
            strScripts = strScripts + "<script language='javascript'>";
            strScripts = strScripts + "window.close();</script>";
            Page.RegisterStartupScript("AlertManualApproval", strScripts);
            return;
        }

        string source_Language;
        source_Language = Session["Session_ActiveLanguage"].ToString();
        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);
        string strSetAlert = "";
        strSetAlert = strSetAlert + "<script language='javascript'>";
        strSetAlert = strSetAlert + "MaxLengthh('" + rm.GetString("Alert_MaximumLengthis", ci) + "');";

        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);
        //Set UserRights
        UserRights();

        //To check the user is in SuperAdmin Group

        // Check the dropdownlist are filled or not
        Status = Request.QueryString["Status"].ToString();
        From_Date = Request.QueryString["FromDate"].ToString();
        To_Date = Request.QueryString["ToDate"].ToString();
        EmployeeID = Request.QueryString["EmpId"].ToString();
        EmployeeName = Request.QueryString["EmpName"].ToString();
        EmployeeCategory = Convert.ToInt32(Request.QueryString["EmpCategory"].ToString());
        EmployeeType = Convert.ToInt32(Request.QueryString["EmpType"].ToString());
        strSwipeCard = Convert.ToString(Request.QueryString["SwipeCard"]);

        LevelId = rptcommon.getNodes(Convert.ToInt32(Session["parentLevelId"]), Convert.ToString(Session["LevelRights"]));

        //LevelId = Request.QueryString["LevelId"].ToString();
        //Checking and Convert to Date Format MM/dd/yyyy
        gstrDateFormat = Convert.ToString(Session["MDateFormat"]);

        if (From_Date != string.Empty)
        {
            From_Date = objcls_Common.DateConvertion(gstrDateFormat, From_Date);
        }
        if (To_Date != string.Empty)
        {
            To_Date = objcls_Common.DateConvertion(gstrDateFormat, To_Date);
        }
        if (!IsPostBack)
        {
            //LevelId = rptcommon.getNodes(Convert.ToInt32(Session["parentLevelId"]), Convert.ToString(Session["LevelRights"]));
            int intCompanyId;
            string strStatus = string.Empty;
            string strModule = string.Empty;

            string strScript = "";
            strScript = strScript + "<script language='javascript'>";
            bool blnParentExists = true;

            strModule = "Approval";
            if (Session["parentLevelId"] == null)
            {
                blnParentExists = false;
            }
            else if (Convert.ToInt32(Session["parentLevelId"]) == 0)
            {
                blnParentExists = false;
            }
            if (blnParentExists == false)
            {
                //strStatus = "Select a company";
                Div1.Visible = false;

                strScript = strScript + "alert('" + rm.GetString("Alert_SelectCompany", ci) + "');window.close();";
                strScript = strScript + "</script>";
                Page.RegisterStartupScript("AlertManualApproval", strScript);
                return;
            }

            intCompanyId = getParentCompany(Convert.ToInt32(Session["parentLevelId"]));
            strStatus = GetApprovalStatus(intCompanyId, strModule);

            if (strStatus == "ApprovalNotRequired")
            {
                //lblApprovalStatus.Text = "Approval Not Required for this company";
                strStatus = rm.GetString("Alert_ApprovalNotRequiredforthiscompany", ci);
                Div1.Visible = false;
                strScript = strScript + "alert('" + strStatus + "');window.close();";
                strScript = strScript + "</script>";
                Page.RegisterStartupScript("AlertManualApproval", strScript);
                return;
            }
            else if (strStatus == "ApprovalRequired")
            {
                //continue
            }
            else if (strStatus == "NotDefined")
            {
                //lblApprovalStatus.Text = "Approval Settings not defined for this company";
                strStatus = rm.GetString("Alert_ApprovalSettingsnotdefinedforthiscompany", ci);
                Div1.Visible = false;
                strScript = strScript + "alert('" + strStatus + "');window.close();";
                strScript = strScript + "</script>";
                Page.RegisterStartupScript("AlertManualApproval", strScript);
                return;
            }

            //Checking and Convert to Date Format MM/dd/yyyy
            gstrDateFormat = Convert.ToString(Session["MDateFormat"]);

            dsYearSetting = objYearSettingsEventData.GetActiveYearSettings();

            if (dsYearSetting.Tables[0].Rows.Count <= 0)
            {
                return;
            }
            else
            {
                StartMonth = dsYearSetting.Tables[0].Rows[0]["StartMonth"].ToString();
                StartYear = dsYearSetting.Tables[0].Rows[0]["StartYear"].ToString();
                vmonthValue = MonthValue(StartMonth);
                startDate = vmonthValue.ToString() + "/1/" + StartYear;

                EndMonth = dsYearSetting.Tables[0].Rows[0]["EndMonth"].ToString();
                EndYear = dsYearSetting.Tables[0].Rows[0]["EndYear"].ToString();
                vmonthValue = MonthValue(EndMonth);
                endDate = vmonthValue.ToString() + "/31/" + EndYear;
            }

            if (LevelId == "0")
            {
                LevelId = null;
            }
            if (Status == "-Select Status-")
            {
                Status = "All";
            }

            if (From_Date == string.Empty)
            {
                From_Date = startDate;
            }

            if (To_Date == string.Empty)
            {
                To_Date = endDate;
            }

            // Fill Manual Time Entry Sanction Details in Grid
            BindManualEntrySanctionDetails();
            if (Status == "Pending")
            {
                btnPending.Visible = false;
            }
            else if (Status == "Approved")
            {
                btnApproved.Visible = false;
                btnForwarded.Visible = false;
            }
            else if (Status == "Forwarded")
            {
                btnForwarded.Visible = false;
            }
            else if (Status == "Rejected")
            {
                btnReject.Visible = false;
            }
            //Session["EmployeeIds"] = "";
        }
        checkRecordExists = true;
    }

    #endregion

    #region User Defined Functions

    public int getParentCompany(int iEmployeeLevelID)
    {
        //Select Company
        org_levelsEventData getOrg = new org_levelsEventData();
        getOrg.GetOrgParentLevels_FromID(iEmployeeLevelID);
        DataSet ds_getOrg = new DataSet();
        ds_getOrg = getOrg.GetOrgParentLevels();
        int iCompanyID = 0;
        if (ds_getOrg != null)
        {
            if (ds_getOrg.Tables[0].Rows.Count > 0)
            {
                iCompanyID = Convert.ToInt32(ds_getOrg.Tables[0].Rows[0]["LevelID"].ToString());

            }
        }
        return iCompanyID;
    }

    public string GetApprovalStatus(int intCompanyId, string strModule)
    {
        int approvalSettingsPageExists = 0;
        //Checking grade module is available or not and changed the id value from 110 to 228
        approvalSettingsPageExists = objcls_Common.CheckPageExistsInLicense(228);
        string strStatus = string.Empty;
        if (approvalSettingsPageExists == 1)
        {
            //Get Approval Settings Based on Company Id
            DataSet dsApprovalSettings = new DataSet();
            ShiftEvenData objShift = new ShiftEvenData();

            dsApprovalSettings = objShift.SelectApprovalSettings(intCompanyId);

            if (dsApprovalSettings != null)
            {
                if (dsApprovalSettings.Tables.Count > 0)
                {
                    if (dsApprovalSettings.Tables[0].Rows.Count > 0)
                    {
                        if (Convert.ToBoolean(dsApprovalSettings.Tables[0].Rows[0][strModule]) == false)
                        {
                            strStatus = "ApprovalNotRequired";
                        }
                        else
                        {
                            strStatus = "ApprovalRequired";
                        }
                    }
                    else
                    {
                        strStatus = "NotDefined";
                    }
                }
            }
        }
        else
        {
            strStatus = "ApprovalRequired";
        }
        return strStatus;
    }

    public void BindManualEntrySanctionDetails()
    {
        // To check the user is in SuperAdmin Group

        //DataSet dsEmployeeGroup = new DataSet();
        //dsEmployeeGroup = objLeaveApplicationEventData.GetEmployeeGroupName(Convert.ToInt32(Session["EmpAutoId"]));

        if (Session["UserGroupName"].ToString() == "SuperAdmin" || Session["HasSpecialRights"].ToString() == "True")
        {
            dtManualEntrySanctionView = objManualEntryEventData.GetOnDutyEntrySanctionDetailsForSuperAdmin(LevelId, Status, EmployeeID, EmployeeName, EmployeeCategory, EmployeeType, From_Date, To_Date, strSwipeCard, Session["UserGroupName"].ToString(), Convert.ToInt16(Session["parentLevelId"]));
            Session["TotalEmployees"] = dtManualEntrySanctionView.Rows.Count;
            //ViewState["DataManualEntrySanction"] = dtManualEntrySanctionView;
            Session["DataManualEntrySanction"] = dtManualEntrySanctionView;

        }
        else
        {
            dtManualEntrySanctionView = objManualEntryEventData.GetOnDutySanctionDetails(Convert.ToInt32(Session["EmpAutoId"]), LevelId, Status, EmployeeID, EmployeeName, EmployeeCategory, EmployeeType, From_Date, To_Date, strSwipeCard, Session["UserGroupName"].ToString(), Convert.ToInt16(Session["parentLevelId"]));
            Session["TotalEmployees"] = dtManualEntrySanctionView.Rows.Count;
            //ViewState["DataManualEntrySanction"] = dtManualEntrySanctionView;
            Session["DataManualEntrySanction"] = dtManualEntrySanctionView;
        }
        if (dtManualEntrySanctionView.Rows.Count > 0)
        {
            gdManualEntrySanctionView.DataSource = dtManualEntrySanctionView;
            gdManualEntrySanctionView.DataBind();
        }
        else
        {
            gdManualEntrySanctionView.DataSource = dtManualEntrySanctionView;
            gdManualEntrySanctionView.DataBind();
            btnApproved.Visible = false;
            btnForwarded.Visible = false;
            btnPending.Visible = false;
            btnReject.Visible = false;
            lblRemarks.Visible = false;
            txtRemarks.Visible = false;
            checkRecordExists = false;
        }
        if (checkRecordExists == true)
        {
            CheckBox chkSelect = new CheckBox();
            chkSelect = (CheckBox)gdManualEntrySanctionView.HeaderRow.Cells[0].FindControl("checkall");
            chkSelect.Checked = Convert.ToBoolean(Session["SelectAllStatus"].ToString());
        }
    }

    public int MonthValue(string monthName)
    {
        if (monthName == "January")
            return 1;
        else if (monthName == "February")
            return 2;
        else if (monthName == "March")
            return 3;
        else if (monthName == "April")
            return 4;
        else if (monthName == "May")
            return 5;
        else if (monthName == "June")
            return 6;
        else if (monthName == "July")
            return 7;
        else if (monthName == "August")
            return 8;
        else if (monthName == "September")
            return 9;
        else if (monthName == "October")
            return 10;
        else if (monthName == "November")
            return 11;
        else if (monthName == "December")
            return 12;
        else
            return 0;
    }

    /// <summary>
    /// Getting Information from resource file and display it in label
    /// </summary>
    /// <param name="ci"></param>
    private void LoadStrings(CultureInfo ci)
    {
        lbl_Header.Text = rm.GetString("UserGroups_ManualODEntrySanction", ci);
        btnPending.Text = rm.GetString("btn_Pending", ci);
        btnApproved.Text = rm.GetString("btn_Approved", ci);
        btnForwarded.Text = rm.GetString("btn_Forwarded", ci);
        btnReject.Text = rm.GetString("btn_Reject", ci);
        lblRemarks.Text = rm.GetString("email_Remarks", ci);

        gdManualEntrySanctionView.Columns[2].HeaderText = rm.GetString("email_EmployeeId", ci);
        gdManualEntrySanctionView.Columns[3].HeaderText = rm.GetString("email_EmployeeName", ci);
        gdManualEntrySanctionView.Columns[4].HeaderText = rm.GetString("ODEntry_ODEntryDate", ci);
        gdManualEntrySanctionView.Columns[5].HeaderText = rm.GetString("ODEntrySanction_InEntry", ci);
        gdManualEntrySanctionView.Columns[6].HeaderText = rm.GetString("OnDutyEntrySanction_OutEntry", ci);
        gdManualEntrySanctionView.Columns[7].HeaderText = rm.GetString("email_Reason", ci);
        gdManualEntrySanctionView.Columns[8].HeaderText = rm.GetString("email_Status", ci);
    }

    private void UserRights()
    {
        ds_Checkuser = objCheckUser.checkRights(174, Convert.ToInt32(Session["userGroup_Id"]), "viewPrv");
        if (ds_Checkuser.Tables[0].Rows.Count == 0)
        {
            Response.Redirect("TransactionLandingPage.aspx");
        }
        else
        {
            //   
        }
    }

    /// <summary>
    /// To update the manual entry status if the manual entry is not processed
    /// </summary>
    /// <param name="Status"></param>
    protected void UpdatedManualTimeEntryStatus(string Status)
    {

        string strEmployeeName = string.Empty;
        string strRemarks = string.Empty;
        DataTable dtManual = new DataTable();
        dtManual = (DataTable)Session["DataManualEntrySanction"];
        strRemarks = txtRemarks.Text.Trim();
        intCount = dtManual.Rows.Count;

        if (dtManual.Rows.Count > 0)
        {
            DataTable dtDataToBeUpdated = new DataTable();
            dtManual.DefaultView.RowFilter = "SelectedRecords=1";
            dtDataToBeUpdated = dtManual.DefaultView.ToTable();
            if (dtDataToBeUpdated.Rows.Count > 0)
            {
                CheckGrid = true;
                dtDataToBeUpdated.Columns.Remove("name");
                dtDataToBeUpdated.Columns.Remove("Employee_Code_Id");
                dtDataToBeUpdated.Columns.Remove("Employee_FirstName");
                dtDataToBeUpdated.Columns.Remove("ManualTimeEntry_Date");
                dtDataToBeUpdated.Columns.Remove("InDateTime");
                dtDataToBeUpdated.Columns.Remove("OutDateTime");
                dtDataToBeUpdated.Columns.Remove("ManualTimeEntry_Status");
                dtDataToBeUpdated.Columns.Remove("ManualTimeEntry_Reason");
                dtDataToBeUpdated.Columns.Remove("SelectedRecords");

                StringWriter strXMLData = new StringWriter();
                dtDataToBeUpdated.WriteXml(strXMLData);
                DataSet dsProcessedData = new DataSet();
                dsProcessedData = objManualEntryEventData.UpdateManualTimeEntrySanction_Group(Status, strRemarks, Convert.ToInt32(Session["EmpAutoId"]), strXMLData.ToString());
                if (dsProcessedData.Tables[0].Rows.Count > 0)
                {
                    statusProcess = true;

                    if (Convert.ToInt16(dsProcessedData.Tables[0].Rows[0]["UpdateCount"]) > 0)
                    {
                        if (Convert.ToInt16(dsProcessedData.Tables[0].Rows[0]["ProcessedDataCount"]) > 0)
                        {
                            Message(rm.GetString("Msg_TheRecordhasbeenalreadyprocessedCannotModifytheStatus", ci));

                            Session["DataManualEntrySanction"] = null;
                            string str = "<script language=\"javascript\">";
                            str = str + "alert('" + rm.GetString("Alert_SavedSuccessfully", ci) + "');";
                            str = str + "opener.focus();";
                            str = str + "opener.location.href = opener.location + '?fl=1&sid=" + Session.SessionID + "';";
                            str = str + "self.close();";
                            str = str + "</script>";
                            Page.RegisterStartupScript("alert", str);
                        }
                        else
                        {
                            Session["DataManualEntrySanction"] = null;
                            string str = "<script language=\"javascript\">";
                            str = str + "alert('" + rm.GetString("Alert_SavedSuccessfully", ci) + "');";
                            str = str + "opener.focus();";
                            str = str + "opener.location.href = opener.location + '?fl=1&sid=" + Session.SessionID + "';";
                            str = str + "self.close();";
                            str = str + "</script>";
                            Page.RegisterStartupScript("alert", str);
                        }
                    }
                    else if (Convert.ToInt16(dsProcessedData.Tables[0].Rows[0]["ProcessedDataCount"]) > 0)
                    {
                        Message(rm.GetString("Msg_TheRecordhasbeenalreadyprocessedCannotModifytheStatus", ci));
                    }
                }
            }
        }
    }

    public void GetEmptyText(object sender, EventArgs e)
    {
        Label lblNoRecords = (Label)sender;
        lblNoRecords.Text = rm.GetString("Alert_Norecordsfound", ci);
    }

    #endregion

    #region Grid view events

    protected void gdManualEntrySanctionView_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            string NewTimeFormat = string.Empty;
            string TimeFormat = Convert.ToString(Session["ITimeFormat"]);

            if (TimeFormat == "%H:%M")
            {
                NewTimeFormat = "HH:mm:ss";

            }
            else
            {
                NewTimeFormat = "hh:mm:ss tt";
            }

            Label lblManualTimeEntryDate = (Label)e.Row.Cells[1].FindControl("lblManualTimeEntryDate");
            lblManualTimeEntryDate.Text = (Convert.ToDateTime(lblManualTimeEntryDate.Text.ToString())).ToString(Session["MDateFormat"].ToString());

            Label lblInEntry = (Label)e.Row.Cells[1].FindControl("lblInEntry");
            if (lblInEntry.Text != string.Empty && lblInEntry.Text != null)
            {
                string[] PerTime = lblInEntry.Text.Split(" ".ToCharArray());
                string timePart1 = PerTime[2].ToString() + " " + PerTime[3].ToString();
                lblInEntry.Text = (Convert.ToDateTime(PerTime[0])).ToString(Session["MDateFormat"].ToString()) + " " + (Convert.ToDateTime(timePart1)).ToString(NewTimeFormat);
            }

            Label lblOutEntry = (Label)e.Row.Cells[1].FindControl("lblOutEntry");
            if (lblOutEntry.Text != string.Empty && lblOutEntry.Text != null)
            {
                string[] PerTime = lblOutEntry.Text.Split(" ".ToCharArray());
                string timePart1 = PerTime[2].ToString() + " " + PerTime[3].ToString();
                lblOutEntry.Text = (Convert.ToDateTime(PerTime[0])).ToString(Session["MDateFormat"].ToString()) + " " + (Convert.ToDateTime(timePart1)).ToString(NewTimeFormat);
            }

            Label lblStatus = (Label)e.Row.Cells[1].FindControl("lblManualTimeEntryStatus");
            if (lblStatus.Text == "Approved")
            {
                lblStatus.Text = rm.GetString("btn_Approved", ci);
            }
            else if (lblStatus.Text == "Forwarded")
            {
                lblStatus.Text = rm.GetString("btn_Forwarded", ci);
            }
            else if (lblStatus.Text == "Pending")
            {
                lblStatus.Text = rm.GetString("btn_Pending", ci);
            }
            else if (lblStatus.Text == "Rejected")
            {
                lblStatus.Text = rm.GetString("btn_Reject", ci);
            }
            Label lblManualTimeEntryReason = (Label)e.Row.Cells[1].FindControl("lblManualTimeEntryReason");
            if (lblManualTimeEntryReason.Text.Trim() == "Discrepancy Entry")
            {
                lblManualTimeEntryReason.Text = rm.GetString("Discrepancy_Entry", ci);
            }
        }
    }

    protected void gdManualEntrySanctionView_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gdManualEntrySanctionView.PageIndex = e.NewPageIndex;

        DataTable dtManualEntryDatas = new DataTable();
        dtManualEntryDatas = (DataTable)Session["DataManualEntrySanction"];

        gdManualEntrySanctionView.DataSource = dtManualEntryDatas;
        gdManualEntrySanctionView.DataBind();

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



        //string ChkBoxIDs = "";
        ////bool BxsChkd = false;
        //string str = Status;

        //CheckBox deleteChkBxItem = new CheckBox();
        //// Add EmployeeId in Session Variable.

        //foreach (GridViewRow i in gdManualEntrySanctionView.Rows)
        //{

        //    //HtmlInputCheckBox deleteChkBxItem = (HtmlInputCheckBox)i.FindControl("deletethis");
        //    deleteChkBxItem = (CheckBox)i.Cells[0].FindControl("deletethis");


        //    if (deleteChkBxItem.Checked)
        //    {

        //        //BxsChkd = true;

        //        if (ChkBoxIDs == "")
        //        {
        //            ChkBoxIDs = ((Label)i.FindControl("lblManualTimeEntryId")).Text.ToString();
        //        }
        //        else
        //        {
        //            // Concatenate DataGrid item with comma for SQL Delete
        //            ChkBoxIDs = ChkBoxIDs + "," + ((Label)i.FindControl("lblManualTimeEntryId")).Text.ToString();
        //        }

        //    }

        //}


        //if (Session["EmployeeIds"].ToString() == "")
        //{
        //    Session["EmployeeIds"] = ChkBoxIDs;
        //}
        //else
        //{
        //    if (ChkBoxIDs != "")
        //    {
        //        Session["EmployeeIds"] = Session["EmployeeIds"] + "," + ChkBoxIDs;
        //    }
        //}
        //CheckBox chkSelect = new CheckBox();
        //chkSelect = (CheckBox)gdManualEntrySanctionView.HeaderRow.Cells[0].FindControl("checkall");
        //Session["SelectAllStatus"] = chkSelect.Checked;

        //gdManualEntrySanctionView.PageIndex = e.NewPageIndex;
        //BindManualEntrySanctionDetails();
        //CheckEmployeeId_CheckBox();
    }

    protected void grv_Check_CheckedChanged(object sender, EventArgs e)
    {
        Label lblManualTimeEntryId = new Label();
        lblManualTimeEntryId.Text = ((Label)((CheckBox)(sender)).FindControl("lblManualTimeEntryId")).Text.ToString();

        DataTable dtManualTimeEntry = new DataTable();
        dtManualTimeEntry = (DataTable)Session["DataManualEntrySanction"];

        DataRow[] OTCheckedRow = dtManualTimeEntry.Select("ManualTimeEntry_Id = " + lblManualTimeEntryId.Text);

        if (OTCheckedRow.Length > 0)
        {
            if (((CheckBox)(sender)).Checked == true)
            {

                OTCheckedRow[0]["SelectedRecords"] = "1";
            }
            else
            {
                OTCheckedRow[0]["SelectedRecords"] = "0";
            }
        }

        dtManualTimeEntry.DefaultView.RowFilter = "SelectedRecords=0";
        int intSelectAllCount = dtManualTimeEntry.DefaultView.ToTable().Rows.Count;
        dtManualTimeEntry.DefaultView.RowFilter = string.Empty;

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

        if (intSelectAllCount == 0)
        {
            chkSelectAll.Checked = true;
        }
        else
        {
            chkSelectAll.Checked = false;
        }
        Session["SelectAllStatus"] = chkSelectAll.Checked;
        Session["DataManualEntrySanction"] = dtManualTimeEntry;

        //string ChkBoxIDs = string.Empty;
        //int intCount = 0;
        //int intGridPageSize = gdManualEntrySanctionView.PageSize;
        //int intGridTotalPages = gdManualEntrySanctionView.PageCount;
        //bool boolAllChecked = false;

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

        //if (((CheckBox)sender).Checked == false)
        //{
        //    chkSelectAll.Checked = false;
        //}
        //else
        //{
        //    foreach (GridViewRow gr in gdManualEntrySanctionView.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 (gdManualEntrySanctionView.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 void grv_CheckAll_CheckedChanged(object sender, EventArgs e)
    {
        try
        {
            DataTable dtManualTimeEntryCheckAll = new DataTable();
            dtManualTimeEntryCheckAll = (DataTable)Session["DataManualEntrySanction"];

            foreach (DataRow drRow in dtManualTimeEntryCheckAll.Rows)
            {
                if (((CheckBox)(sender)).Checked == true)
                {
                    drRow["SelectedRecords"] = "1";
                }
                else
                {
                    drRow["SelectedRecords"] = "0";
                }
            }
            DataTable dt = new DataTable();
            dt = dtManualTimeEntryCheckAll.Copy();
            DataSet ds = new DataSet();
            ds.Tables.Add(dt);

            gdManualEntrySanctionView.DataSource = ds.Tables[0];
            gdManualEntrySanctionView.DataBind();

            //gdManualEntrySanctionView.DataSource = dtManualTimeEntryCheckAll;
            //gdManualEntrySanctionView.DataBind();

            Session["DataManualEntrySanction"] = dtManualTimeEntryCheckAll;

            CheckBox chkSelect = new CheckBox();
            chkSelect = (CheckBox)gdManualEntrySanctionView.HeaderRow.Cells[0].FindControl("checkall");

            if (((CheckBox)(sender)).Checked)
            {
                chkSelect.Checked = true;
            }
            else
            {
                chkSelect.Checked = false;
            }
            Session["SelectAllStatus"] = chkSelect.Checked;
        }
        catch (Exception ex)
        {
            throw ex;
        }
        //CheckBox chkSelect = new CheckBox();
        //chkSelect = (CheckBox)gdManualEntrySanctionView.HeaderRow.Cells[0].FindControl("checkall");

        //string ChkBoxIDs = string.Empty;

        //if (chkSelect.Checked)
        //{
        //    ChkBoxIDs = GetEmployeeIdsInOtherPagesOfGrid();

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

        //foreach (GridViewRow gr in gdManualEntrySanctionView.Rows)
        //{
        //    chkSelect = (CheckBox)gr.Cells[0].FindControl("deletethis");
        //    if (chkSelect.Enabled == true)
        //    {
        //        chkSelect.Checked = ((CheckBox)sender).Checked;
        //    }
        //}
    }

    #endregion

    #region Button events

    protected void btnBack_Click(object sender, EventArgs e)
    {
        Session["DataManualEntrySanction"] = null;
        Response.Redirect("TA_UI_Transactions_ManualTimeEntrySanction.aspx");
    }

    protected void btn_Pending_Click(object sender, EventArgs e)
    {
        UpdatedManualTimeEntryStatus("Pending");
        if (CheckGrid == false)
        {
            // Message("Select Any Record");
            Message(rm.GetString("Alert_SelectAnyRecord", ci));
        }
        else
        {
            //Session["DataManualEntrySanction"] = null;
            //string str = "<script language=\"javascript\">";
            //str = str + "alert('" + rm.GetString("Alert_SavedSuccessfully", ci) + "');";
            //str = str + "opener.focus();";
            //str = str + "opener.location.href = opener.location + '?fl=1&sid=" + Session.SessionID + "';";
            //str = str + "self.close();";
            //str = str + "</script>";
            //Page.RegisterStartupScript("alert", str);
        }
    }

    protected void btn_Approved_Click(object sender, EventArgs e)
    {
        UpdatedManualTimeEntryStatus("Approved");
        if (CheckGrid == false)
        {
            //Message("Select Any Record");
            Message(rm.GetString("Alert_SelectAnyRecord", ci));
        }
        else
        {
            if (statusProcess == false)
            {
                //Session["DataManualEntrySanction"] = null;
                //string str = "<script language=\"javascript\">";
                //str = str + "alert('" + rm.GetString("Alert_SavedSuccessfully", ci) + "');";
                //str = str + "opener.focus();";
                //str = str + "opener.location.href = opener.location + '?fl=1&sid=" + Session.SessionID + "';";
                //str = str + "self.close();";
                //str = str + "</script>";
                //Page.RegisterStartupScript("alert", str);
            }
        }
    }

    protected void btn_Forwarded_Click(object sender, EventArgs e)
    {
        UpdatedManualTimeEntryStatus("Forwarded");
        if (CheckGrid == false)
        {
            //Message("Select Any Record");
            Message(rm.GetString("Alert_SelectAnyRecord", ci));
        }
        else
        {
            //Session["DataManualEntrySanction"] = null;
            //string str = "<script language=\"javascript\">";
            //str = str + "alert('" + rm.GetString("Alert_SavedSuccessfully", ci) + "');";
            //str = str + "opener.focus();";
            //str = str + "opener.location.href = opener.location + '?fl=1&sid=" + Session.SessionID + "';";
            //str = str + "self.close();";
            //str = str + "</script>";
            //Page.RegisterStartupScript("alert", str);
        }
    }

    protected void btn_Reject_Click(object sender, EventArgs e)
    {
        UpdatedManualTimeEntryStatus("Rejected");
        if (CheckGrid == false)
        {
            //Message("Select Any Record");
            Message(rm.GetString("Alert_SelectAnyRecord", ci));
        }
        else
        {
            //Session["DataManualEntrySanction"] = null;
            //string str = "<script language=\"javascript\">";
            //str = str + "alert('" + rm.GetString("Alert_SavedSuccessfully", ci) + "');";
            //str = str + "opener.focus();";
            //str = str + "opener.location.href = opener.location + '?fl=1&sid=" + Session.SessionID + "';";
            //str = str + "self.close();";
            //str = str + "</script>";
            //Page.RegisterStartupScript("alert", str);
        }
    }

    #endregion

    #region MessageWithRedirect.

    /// <summary>
    /// Messages the with redirect.
    /// </summary>
    /// <param name="messageContent">Content of the message.</param>
    /// <param name="ToPage">To page.</param>
    private void Message(string messageContent)
    {
        string strScript = "<script language='javascript' type='text/javascript'>";
        strScript += "alert('" + messageContent + "');";
        strScript += " </script>";
        this.RegisterStartupScript("setScript", strScript);

    }
    #endregion

    #region NotUsed

    //protected void gdManualEntrySanctionView_Sorting(object sender, GridViewSortEventArgs e)
    //{
    //ViewState["SortExpression"] = e.SortExpression;

    //if (Convert.ToString(Session["SortOrderManualEntrySanction"]) == string.Empty)
    //{
    //    Session["SortOrderManualEntrySanction"] = "Asc";
    //}
    //else if (Convert.ToString(Session["SortOrderManualEntrySanction"]) == "Asc")
    //{
    //    Session["SortOrderManualEntrySanction"] = "Desc";
    //}
    //else
    //{
    //    Session["SortOrderManualEntrySanction"] = "Asc";
    //}

    //SortGrid(e.SortExpression, Convert.ToString(Session["SortOrderManualEntrySanction"]));
    //}

    //protected void gdManualEntrySanctionView_PageIndexChanged(object sender, EventArgs e)
    // {
    //try
    //{
    //    // To display the sorted records in the new page if the Vendor has Sorted the Gridview by clicking any header
    //    if ((ViewState["SortExpression"]) != null)
    //    {
    //        string SortColumn = Convert.ToString(ViewState["SortExpression"]);
    //        string SortOrder = Convert.ToString(Session["SortOrderManualEntrySanction"]);
    //        SortGrid(SortColumn, SortOrder);
    //    }
    //}
    //catch (Exception ex)
    //{
    //    throw ex;
    //}
    //}

    //public void SortGrid(string SortColumn, string SortOrder)
    //{
    //    DataTable dtSrch = new DataTable();
    //    DataView dvSearch = new DataView();

    //    dtSrch = (DataTable)ViewState["DataManualEntrySanction"];
    //    dvSearch.Table = dtSrch;
    //    dvSearch.Sort = SortColumn + " " + SortOrder;

    //    gdManualEntrySanctionView.DataSource = dvSearch;
    //    gdManualEntrySanctionView.DataBind();
    //}

    //public void CheckEmployeeId_CheckBox()
    //{
    //    string strEmpId = "";
    //    strEmpId = (string)Session["EmployeeIds"];
    //    int intEmployeeIdsLength = strEmpId.Length;

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

    //    CheckBox deleteChkBxItem = new CheckBox();

    //    foreach (GridViewRow gr in gdManualEntrySanctionView.Rows)
    //    {
    //        string empId = ((Label)gr.FindControl("lblManualTimeEntryId")).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: ;
    //    }
    //}

    //protected string GetEmployeeIdsInOtherPagesOfGrid()
    //{
    //    DataTable dtManual = new DataTable();
    //    //dtManual = (DataTable)ViewState["DataManualEntrySanction"];
    //    dtManual = (DataTable)Session["DataManualEntrySanction"];
    //    string strEmpId = string.Empty;
    //    string ChkBoxIDs = string.Empty;


    //    foreach (DataRow dr in dtManual.Rows)
    //    {
    //        foreach (GridViewRow gr in gdManualEntrySanctionView.Rows)
    //        {
    //            strEmpId = ((Label)gr.FindControl("lblManualTimeEntryId")).Text.ToString();
    //            //strEmpId = ((HiddenField)gr.FindControl("lblProcess_Rec_ID")).Value.ToString();
    //            CheckBox chkEnabled = (CheckBox)gr.FindControl("deletethis");
    //            if (chkEnabled.Enabled == false)
    //            {
    //                goto A;
    //            }
    //            if (strEmpId == dr["ManualTimeEntry_Id"].ToString())
    //            {
    //                goto A;
    //            }
    //        }
    //        if (ChkBoxIDs == "")
    //        {
    //            ChkBoxIDs = dr["ManualTimeEntry_Id"].ToString();
    //        }
    //        else
    //        {
    //            ChkBoxIDs = ChkBoxIDs + "," + dr["ManualTimeEntry_Id"].ToString();
    //        }
    //    A: ;
    //    }
    //    return ChkBoxIDs;
    //}

    #endregion

}
