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;
using System.IO;
public partial class Transactions_TA_UI_Transactions_ShiftReAllocation : Base.BasePage
{
    #region Variable Declaration
    Cls_CheckUser objCheckUser = new Cls_CheckUser();
    DataSet ds_Checkuser = new DataSet();
    ResourceManager rm;
    cls_Common objCommon = new cls_Common();
    EmployeeEventData objEmployee = new EmployeeEventData();
    ShiftEvenData objShift = new ShiftEvenData();
    ShiftAllocationEvendata objShiftAllocation = new ShiftAllocationEvendata();
    string strAlert = string.Empty;
    CultureInfo ci;
    #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);
        //get the culture info to set the language       
        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;
        site.SiteMapProvider = Convert.ToString(Session["SiteMapProvider"]);
        LoadStrings(ci);
        string strSetAlert = "";
        strSetAlert = strSetAlert + "<script language='javascript'>";
        strSetAlert = strSetAlert + "MaxLengthh('" + rm.GetString("Alert_MaximumLengthis", ci) + "');";
        strSetAlert = strSetAlert + "SetAlertMessages('" + rm.GetString("Alert_SelectShiftToBeChanged", ci) + "','" + rm.GetString("Alert_SelectCurrentShift", ci) + "','" + rm.GetString("Alert_EnterDate", ci) + "','" + rm.GetString("Alert_EnterToDate", ci) + "','" + rm.GetString("Alert_Shifttobechangedshouldnotbesameastheselectedshift", ci) + "','" + rm.GetString("Alert_Are_you_sure_to_Save", ci) + "');";
        strSetAlert = strSetAlert + "SetAlertCheckDate('" + rm.GetString("Alert_Validmonthdatefourdigit", ci) + "','" + rm.GetString("Alert_Validdatemonthfourdigit", ci) + "','" + rm.GetString("Alert_Invalidyearentry", ci) + "','" + rm.GetString("Alert_Invalidmonthentry", ci) + "','" + rm.GetString("Alert_Invaliddateentry", ci) + "','" + rm.GetString("Alert_IncorrectdateformatDDMONYYYY", ci) + "','" + rm.GetString("Alert_Entertime", ci) + "','" + rm.GetString("Alert_Invalidvalueforhours", ci) + "','" + rm.GetString("Alert_Invalidvalueforminites", ci) + "','" + rm.GetString("Alert_Invalidtimeformat1", ci) + "','" + rm.GetString("Alert_PleaseentervalidDateandTime", ci) + "','" + rm.GetString("Alert_ValiddatemonthMMDDYYHHMM", ci) + "','" + rm.GetString("Alert_ValiddatemonthMMDDYYHHMMTT", ci) + "','" + rm.GetString("Alert_PleaseentervalidDateandTime", ci) + "','" + rm.GetString("Alert_Invalidvalueforhours", ci) + "','" + rm.GetString("Alert_Invalidvalueforminites", ci) + "');";
        strSetAlert = strSetAlert + "</script>";
        Page.RegisterStartupScript("SetAlertMessages", strSetAlert);
        string TimeFormat = string.Empty;
        TimeFormat = Convert.ToString(Session["ITimeFormat"]);
        if (TimeFormat == "%H:%M")
        {
            hiddenTime.Value = "%H:%M:%S";
        }
        else
        {
            hiddenTime.Value = "%I:%M:%S %p";
        }
        //Set UserRights
        UserRights();
        Hidden1.Value = Convert.ToString(Session["IDateFormat"]);
        Hidden2.Value = Convert.ToString(Session["ITimeFormat"]);
        ddlCurrentShift.PreRender += LB_PreRender;
        ddlShiftToBeChanged.PreRender += LB_PreRender;
        if (!Page.IsPostBack)
        {
            FillCurrentShift();
            txtFromDate.Text = (Convert.ToDateTime(System.DateTime.Now.ToShortDateString())).ToString(Session["MDateFormat"].ToString());
            txtToDate.Text = (Convert.ToDateTime(System.DateTime.Now.ToShortDateString())).ToString(Session["MDateFormat"].ToString());
            btn_Cancel.OnClientClick = "return confirm('" + rm.GetString("Alert_SureToCancel", ci) + "')";
            objCommon.menu("ShiftTransaction", "116");
        }
    }
    #endregion
    #region User Defined Functions
    /// <summary>
    /// To fill the shift in the current shift drop down
    /// </summary>
    public void FillCurrentShift()
    {
        DataSet ds = new DataSet();
        string strusergroup = string.Empty;
        ds = objShift.SelectShift(Convert.ToString(Session["UserGroupName"]), Convert.ToString(Session["LevelRights"]), 0);
        foreach (DataRow drRow in ds.Tables[0].Rows)
        {
            switch (drRow["Shift_Name"].ToString())
            {
                case "No Shift":
                    drRow["Shift_Name"] = rm.GetString("Caption_NoShift", ci);
                    break;
            }
        }
        if (ds.Tables[0].Rows.Count > 0)
        {
            ddlCurrentShift.DataSource = ds;
            ddlCurrentShift.DataTextField = "Shift_Name";
            ddlCurrentShift.DataValueField = "Shift_Id";
            ddlCurrentShift.DataBind();
        }
        ListItem lstItem_Select = new ListItem();
        lstItem_Select.Value = "0";
        lstItem_Select.Text = rm.GetString("Select", ci);
        ListItem lstItem_WeeklyOff = new ListItem();
        lstItem_WeeklyOff.Value = "-1";
        lstItem_WeeklyOff.Text = rm.GetString("MyCalendar_WeekOff", ci);
        ddlCurrentShift.Items.Insert(0, lstItem_Select);
        ddlCurrentShift.Items.Insert(1, lstItem_WeeklyOff);
        foreach (ListItem item in ddlCurrentShift.Items)
        {
            item.Attributes.Add("title", item.Text);
        }
    }
    /// <summary>
    /// To fill shift in the shift to be changed drop down based on the selected company
    /// </summary>
    public void FillShiftToBeChanged()
    {
        DataSet ds = new DataSet();
        string strusergroup = string.Empty;
        ds = objShift.SelectShift(Convert.ToString(Session["UserGroupName"]), Convert.ToString(Session["LevelRights"]), Convert.ToInt32(Session["parentLevelId"]));
        foreach (DataRow drRow in ds.Tables[0].Rows)
        {
            switch (drRow["Shift_Name"].ToString())
            {
                case "No Shift":
                    drRow["Shift_Name"] = rm.GetString("Caption_NoShift", ci);
                    break;
            }
        }
        ListItem lstItem_Select = new ListItem();
        lstItem_Select.Value = "0";
        lstItem_Select.Text = rm.GetString("Select", ci);
        ListItem lstItem_WeeklyOff = new ListItem();
        lstItem_WeeklyOff.Value = "-1";
        lstItem_WeeklyOff.Text = rm.GetString("MyCalendar_WeekOff", ci);
        if (ds.Tables[0].Rows.Count > 0)
        {
            ddlShiftToBeChanged.DataSource = ds;
            ddlShiftToBeChanged.DataTextField = "Shift_Name";
            ddlShiftToBeChanged.DataValueField = "Shift_Id";
            ddlShiftToBeChanged.DataBind();
        }
        ddlShiftToBeChanged.Items.Insert(0, lstItem_Select);
        ddlShiftToBeChanged.Items.Insert(1, lstItem_WeeklyOff);
        foreach (ListItem item in ddlShiftToBeChanged.Items)
        {
            item.Attributes.Add("title", item.Text);
        }
    }
    /// <summary>
    /// Compare ToDate with FromDate
    /// </summary>
    /// <param name="s"></param>
    /// <param name="e"></param>
    public void CompareDate(object s, ServerValidateEventArgs e)
    {
        try
        {
            string strTodate = objCommon.DateConvertion(Session["MDateFormat"].ToString(), txtToDate.Text);
            string strFromdate = objCommon.DateConvertion(Session["MDateFormat"].ToString(), txtFromDate.Text);
            DateTime dtToDate = DateTime.Parse(strTodate);
            DateTime dtFromDate = DateTime.Parse(strFromdate);
            TimeSpan diff = dtToDate.Subtract(dtFromDate);
            int day = diff.Days;
            if (day >= 0)
            {
                e.IsValid = true;
                grdEmployeeDetails.Visible = true;
            }
            else
            {
                grdEmployeeDetails.Visible = false;
                btnSave.Visible = false;
                base.Message(rm.GetString("Msg_GrearterThanFrmDate", ci));
                e.IsValid = false;
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    /// <summary>
    /// Getting Information from resource file and display it in label
    /// </summary>
    /// <param name="ci"></param>
    private void LoadStrings(CultureInfo ci)
    {
        btn_View.Text = "&nbsp;&nbsp;" + rm.GetString("btn_View", ci);
        btn_Cancel.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Cancel", ci);
        btnSave.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Save", ci);
        lblShiftReAllocationReport.Text = rm.GetString("Caption_ShiftReAllocation", ci);
        lblEmployeeName.Text = rm.GetString("email_EmployeeName", ci);
        lblEmployeeId.Text = rm.GetString("email_EmployeeId", ci);
        //lblEmpCategory.Text = rm.GetString("Master_Category", ci);
        //lblEmpType.Text = rm.GetString("Master_Type", ci);
        lblTimePeriod.Text = rm.GetString("Reports_TimePeriod", ci);
        lblFrom.Text = rm.GetString("email_FromDate", ci);
        lblTo.Text = rm.GetString("email_ToDate", ci);
        lblCurrentShift.Text = rm.GetString("ShiftReallocation_CurrentShift", ci);
        cus_ComToDate.ErrorMessage = rm.GetString("Custom_TodateShouldbegreaterthanFromdate", ci);
        grdEmployeeDetails.Columns[2].HeaderText = rm.GetString("email_EmployeeId", ci);
        grdEmployeeDetails.Columns[3].HeaderText = rm.GetString("email_EmployeeName", ci);
        lbl_IndicatesMandatoryFields.Text = rm.GetString("IndicatesMandatoryFields", ci);
        lblPreviousShift.Text = rm.GetString("ShiftReallocation_SelectedShift", ci);
        lblSelectedDateRange.Text = rm.GetString("ShiftReallocation_SelectedDateRange", ci);
        lblShiftToTransfer.Text = rm.GetString("ShiftReallocation_ShiftTransfer", ci);
        lblLoading.Text = rm.GetString("ProgressBarText", ci);
        lblFilter.Text = rm.GetString("lblFilter", ci);
        lbl_Mandatory.Text = rm.GetString("IndicatesMandatoryFields", ci);
    }
    /// <summary>
    /// To check rights for the logged in user.
    /// </summary>
    private void UserRights()
    {
        ds_Checkuser = objCheckUser.checkRights(116, Convert.ToInt32(Session["userGroup_Id"]), "addPrv");
        if (ds_Checkuser.Tables[0].Rows.Count == 0)
        {
            Response.Redirect("TransactionLandingPage.aspx");
        }
    }
    /// <summary>
    /// To bind the employee details in the grid
    /// </summary>
    private void BindGridBasedOnSorting()
    {
        DataTable dtEmployee = new DataTable();
        dtEmployee = (DataTable)Session["EmployeeDetails"];
        DataView dvEmployee = new DataView(dtEmployee);
        if (ViewState["Sort_Field"] != null)
        {
            dvEmployee.Sort = ViewState["Sort_Field"].ToString() + " " + ViewState["Sort_Order"].ToString();
        }
        grdEmployeeDetails.DataSource = dvEmployee;
        grdEmployeeDetails.DataBind();
        divGrid.Style.Add("display", "block");
        Session["EmployeeDetails"] = dvEmployee.ToTable();
    }
    /// <summary>
    /// To get the column names which is used in update statement
    /// </summary>
    /// <param name="Startdata">day to start loop</param>
    /// <param name="EndDate">day to end loop</param>
    /// <returns></returns>
    private string ToGetColumnNames(int StartDateForLoop, int EndDateForLopp)
    {
        int i = 0;
        string ColumnNames = string.Empty;
        for (i = StartDateForLoop; i <= EndDateForLopp; i++)
        {
            if (ColumnNames == string.Empty)
            {
                ColumnNames = "Day" + i + "Shift = case Day" + i + "Shift when " + hdnPreviousShiftId.Value + " then " + ddlShiftToBeChanged.SelectedValue + " else Day" + i + "Shift end";
            }
            else
            {
                ColumnNames = ColumnNames + ",Day" + i + "Shift = case Day" + i + "Shift when " + hdnPreviousShiftId.Value + " then " + ddlShiftToBeChanged.SelectedValue + " else Day" + i + "Shift end";
            }
        }
        return ColumnNames;
    }
    /// <summary>
    /// To apply tooltip for the shift in the drop down
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void LB_PreRender(object sender, System.EventArgs e)
    {
        foreach (ListItem item in ddlCurrentShift.Items)
        {
            item.Attributes.Add("title", item.Text);
        }
        foreach (ListItem item in ddlShiftToBeChanged.Items)
        {
            item.Attributes.Add("title", item.Text);
        }
    }
    #endregion
    #region Button Events
    /// <summary>
    /// To view the employees with the selected shift Id in the grid
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btn_View_Click(object sender, EventArgs e)
    {
        ddlShiftToBeChanged.Items.Clear();
        FillShiftToBeChanged();
        ddlShiftToBeChanged.SelectedIndex = 0;
        if (Convert.ToInt32(Session["parentLevelId"]) == 0)
        {
            string strMsg;
            strMsg = "<script language='javascript'>";
            strMsg = strMsg + "alert('" + rm.GetString("Alert_SelectCompany", ci) + "');";
            strMsg = strMsg + "</script>";
            Page.RegisterStartupScript("SelectCompany", strMsg);
            return;
        }
        string FromDate = objCommon.DateConvertion(Session["MDateFormat"].ToString(), txtFromDate.Text);
        string ToDate = objCommon.DateConvertion(Session["MDateFormat"].ToString(), txtToDate.Text);
        DataSet dsEmployeeForShiftReAllocation = new DataSet();
        dsEmployeeForShiftReAllocation = objShift.SelectEmployeeForShiftReAllocation(FromDate, ToDate, txtEmployeeId.Text, Convert.ToInt32(ddlCurrentShift.SelectedValue), txtEmployeeName.Text, Convert.ToString(Session["UserGroupName"]), Convert.ToInt16(Session["parentLevelId"]), Int32.Parse(Session["EmpAutoID"].ToString()));
        if (dsEmployeeForShiftReAllocation.Tables[0].Rows.Count > 0)
        {
            Session["EmployeeDetails"] = dsEmployeeForShiftReAllocation.Tables[0];
            grdEmployeeDetails.DataSource = dsEmployeeForShiftReAllocation;
            grdEmployeeDetails.DataBind();
            divGrid.Style.Add("display", "block");
            lblPreviousShiftName.Text = ddlCurrentShift.SelectedItem.Text;
            hdnPreviousShiftId.Value = ddlCurrentShift.SelectedValue;
            lblSelecteddate.Text = txtFromDate.Text + " - " + txtToDate.Text;
            hdnSelectedFromDate.Value = txtFromDate.Text;
            hdnSelectedToDate.Value = txtToDate.Text;
        }
        else
        {
            Session["EmployeeDetails"] = null;
            divGrid.Style.Add("display", "none");
            string strMsg;
            strMsg = "<script language='javascript'>";
            strMsg = strMsg + "alert('" + rm.GetString("Alert_Norecordsfound", ci) + "');";
            strMsg = strMsg + "</script>";
            Page.RegisterStartupScript("SelectCompany", strMsg);
            return;
        }
    }
    /// <summary>
    /// To update the shift id for shift re-allocation
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnSave_Click(object sender, EventArgs e)
    {
        DataTable dtEmployee = new DataTable();
        dtEmployee = (DataTable)Session["EmployeeDetails"];
        dtEmployee.DefaultView.RowFilter = "SelectedRecords=1";
        dtEmployee = dtEmployee.DefaultView.ToTable();
        if (dtEmployee.Rows.Count == 0)
        {
            string strMsg;
            strMsg = "<script language='javascript'>";
            strMsg = strMsg + "alert('" + rm.GetString("Alert_SelectAnyRecord", ci) + "');";
            strMsg = strMsg + "</script>";
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", strMsg, false);
            //Page.RegisterStartupScript("SelectAnyRecord", strMsg);
            return;
        }
        dtEmployee.Columns.Remove("Employee_Code_Id");
        dtEmployee.Columns.Remove("EmpName");
        dtEmployee.Columns.Remove("SelectedRecords");
        StringWriter strXMLWriter = new StringWriter();
        dtEmployee.DefaultView.ToTable().WriteXml(strXMLWriter);
        DataSet dsOverlappedEmployee = objShiftAllocation.SelectOverLappedEmployee(Convert.ToInt32(ddlShiftToBeChanged.SelectedValue), Int32.Parse(Session["EmpAutoID"].ToString()), strXMLWriter.ToString());
        if (dsOverlappedEmployee.Tables[0].Rows.Count > 0)
        {
            string strMsg;
            strMsg = "<script language='javascript'>";
            strMsg = strMsg + "alert('Shift overlap exists for " + dsOverlappedEmployee.Tables[1].Rows[0][0].ToString() + "');";
            strMsg = strMsg + "</script>";
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", strMsg, false);
            //Page.RegisterStartupScript("OverlappedExists", strMsg);
            return;
        }
        string strFromDate = objCommon.DateConvertion(Session["MDateFormat"].ToString(), hdnSelectedFromDate.Value);
        string strToDate = objCommon.DateConvertion(Session["MDateFormat"].ToString(), hdnSelectedToDate.Value);
        DateTime dtFromdate = Convert.ToDateTime(strFromDate);
        DateTime dtTodate = Convert.ToDateTime(strToDate);
        string ColumnNames = string.Empty;
        DataSet ds_Shift = objShiftAllocation.CheckLeaveAndPermissionWhileDeleteEmpShift(strXMLWriter.ToString(), strFromDate, strToDate, "SRA");
        if (ds_Shift.Tables.Count > 0)
        {
            if (ds_Shift.Tables[0].Rows.Count > 0)
            {
                string strMessage = Convert.ToString(ds_Shift.Tables[0].Rows[0][0]);
                if (strMessage != string.Empty)
                {
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString(strMessage, ci) + "');", true);
                    txtToDate.Focus();
                    return;
                }
            }
        }
        //If start year and end year are same.
        if (dtFromdate.Year == dtTodate.Year)
        {
            int FromMonth = dtFromdate.Month;
            int ToMonth = dtTodate.Month;
            int increment = FromMonth;
            //loop upto the end month.
            while (increment <= ToMonth)
            {
                //if from month and to month are the same.
                if (FromMonth == ToMonth)
                {
                    ColumnNames = string.Empty;
                    ColumnNames = ToGetColumnNames(dtFromdate.Day, dtTodate.Day);
                }
                //if increment month is the from month 
                else if (increment == FromMonth)
                {
                    ColumnNames = string.Empty;
                    ColumnNames = ToGetColumnNames(dtFromdate.Day, 31);
                }
                //if increment month is the end month 
                else if (increment == ToMonth)
                {
                    ColumnNames = string.Empty;
                    ColumnNames = ToGetColumnNames(1, dtTodate.Day);
                }
                //if increment month is in between
                else
                {
                    ColumnNames = string.Empty;
                    ColumnNames = ToGetColumnNames(1, 31);
                }
                objShiftAllocation.ShiftReAllocation(ColumnNames, dtTodate.Year, increment, Session["EmpAutoID"].ToString(), strXMLWriter.ToString());
                increment = increment + 1;
            }
        }
        //If start year and end year differs.
        else
        {
            int FromYear = dtFromdate.Year;
            int ToYear = dtTodate.Year;
            int increment_Year = FromYear;
            while (increment_Year <= ToYear)
            {
                //If the increment year is the start year.
                if (increment_Year == FromYear)
                {
                    int increment_Month = dtFromdate.Month;
                    while (increment_Month <= 12)
                    {
                        //if increment month is the from month 
                        if (increment_Month == dtFromdate.Month)
                        {
                            ColumnNames = string.Empty;
                            ColumnNames = ToGetColumnNames(dtFromdate.Day, 31);
                        }
                        //if increment month is in between
                        else
                        {
                            ColumnNames = string.Empty;
                            ColumnNames = ToGetColumnNames(1, 31);
                        }
                        objShiftAllocation.ShiftReAllocation(ColumnNames, increment_Year, increment_Month, Session["EmpAutoID"].ToString(), strXMLWriter.ToString());
                        increment_Month = increment_Month + 1;
                    }
                }
                //If the increment year is the end year.
                else if (increment_Year == ToYear)
                {
                    int increment_Month = 1;
                    while (increment_Month <= dtTodate.Month)
                    {
                        //if increment month is the end month 
                        if (increment_Month == dtTodate.Month)
                        {
                            ColumnNames = string.Empty;
                            ColumnNames = ToGetColumnNames(1, dtTodate.Day);
                        }
                        else
                        {
                            ColumnNames = string.Empty;
                            ColumnNames = ToGetColumnNames(1, 31);
                        }
                        objShiftAllocation.ShiftReAllocation(ColumnNames, increment_Year, increment_Month, Session["EmpAutoID"].ToString(), strXMLWriter.ToString());
                        increment_Month = increment_Month + 1;
                    }
                }
                //If the increment year is in between.
                else
                {
                    int increment_Month = 1;
                    while (increment_Month <= 12)
                    {
                        ColumnNames = string.Empty;
                        ColumnNames = ToGetColumnNames(1, 31);
                        objShiftAllocation.ShiftReAllocation(ColumnNames, increment_Year, increment_Month, Session["EmpAutoID"].ToString(), strXMLWriter.ToString());
                        increment_Month = increment_Month + 1;
                    }
                }
                increment_Year = increment_Year + 1;
            }
        }
        //Reprocess 
        try
        {
            objShiftAllocation.ShiftReAllocation_Reprocess_ProcessedData(dtFromdate, dtTodate, strXMLWriter.ToString(), Convert.ToInt32(hdnPreviousShiftId.Value));
            objShiftAllocation.ShiftReAllocation_Reprocess_ClockDetails(dtFromdate, dtTodate, strXMLWriter.ToString());
            objShiftAllocation.ShiftReAllocation_Reprocess_ManualEntry(dtFromdate, dtTodate, strXMLWriter.ToString());
            objShiftAllocation.ShiftReAllocation_Reprocess_RawData(dtFromdate, dtTodate, strXMLWriter.ToString());
        }
        catch (Exception ex)
        {
            throw ex;
        }
        string strAlert = string.Empty;
        //strAlert = "alert('" + rm.GetString("Alert_ShiftReAllocatedSucessfully", ci) + "');";
        // Page.ClientScript.RegisterStartupScript(this.GetType(), "alertBox2", strAlert, true);
        //ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", strAlert, true);
        string strScript = "";
        strScript = strScript + "<script language='javascript'>";
        strScript = strScript + "alert('" + rm.GetString("Alert_ShiftReAllocatedSucessfully", ci) + "');";
        strScript = strScript + "location.replace('TA_UI_Transactions_ShiftReAllocation.aspx');";
        strScript = strScript + "</script>";
        ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", strScript, false);
        Session["EmployeeDetails"] = null;
        Session["SelectAllStatus"] = null;
        //divGrid.Style.Add("display", "none");
    }
    /// <summary>
    /// To hide the grid and save,cancel button
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btn_Cancel_Click(object sender, EventArgs e)
    {
        Session["EmployeeDetails"] = null;
        divGrid.Style.Add("display", "none");
    }
    #endregion
    #region Grid Events
    /// <summary>
    /// Binding grid accoring to sorting
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void grdEmployeeDetails_Sorting(object sender, GridViewSortEventArgs e)
    {
        ViewState["Sort_Field"] = e.SortExpression;
        if (ViewState["Sort_Order"] == null)
            ViewState["Sort_Order"] = "Asc";
        else if (ViewState["Sort_Order"].ToString() == "Asc")
            ViewState["Sort_Order"] = "Desc";
        else
            ViewState["Sort_Order"] = "Asc";
        if (grdEmployeeDetails.PageCount > 0)
            grdEmployeeDetails.PageIndex = 0;
        BindGridBasedOnSorting();
    }
    /// <summary>
    /// On changing the page in the grid
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void grdEmployeeDetails_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        BindGridBasedOnSorting();
        grdEmployeeDetails.PageIndex = e.NewPageIndex;
        grdEmployeeDetails.DataBind();
        CheckBox chkSelect = new CheckBox();
        chkSelect = (CheckBox)grdEmployeeDetails.HeaderRow.Cells[0].FindControl("checkall");
        chkSelect.Checked = Convert.ToBoolean(Session["SelectAllStatus"]);
    }
    /// <summary>
    /// To select or deselect specific rows
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void grv_Check_CheckedChanged(object sender, EventArgs e)
    {
        Label lblEmployeeAutoID = new Label();
        lblEmployeeAutoID.Text = ((Label)((CheckBox)(sender)).FindControl("lblEmployeeAutoID")).Text.ToString();
        DataTable dtEmployeeDetails = new DataTable();
        dtEmployeeDetails = (DataTable)Session["EmployeeDetails"];
        DataRow[] OTCheckedRow = dtEmployeeDetails.Select("EmployeeAutoID = " + lblEmployeeAutoID.Text);
        if (OTCheckedRow.Length > 0)
        {
            if (((CheckBox)(sender)).Checked == true)
            {
                OTCheckedRow[0]["SelectedRecords"] = "1";
            }
            else
            {
                OTCheckedRow[0]["SelectedRecords"] = "0";
            }
        }
        dtEmployeeDetails.DefaultView.RowFilter = "SelectedRecords=0";
        int intSelectAllCount = dtEmployeeDetails.DefaultView.ToTable().Rows.Count;
        dtEmployeeDetails.DefaultView.RowFilter = string.Empty;
        CheckBox chkSelectAll = new CheckBox();
        chkSelectAll = (CheckBox)grdEmployeeDetails.HeaderRow.Cells[0].FindControl("checkall");
        if (intSelectAllCount == 0)
        {
            chkSelectAll.Checked = true;
        }
        else
        {
            chkSelectAll.Checked = false;
        }
        Session["SelectAllStatus"] = chkSelectAll.Checked;
        Session["EmployeeDetails"] = dtEmployeeDetails;
    }
    /// <summary>
    /// check all functionality
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void grv_CheckAll_CheckedChanged(object sender, EventArgs e)
    {
        try
        {
            DataTable dtEmployeeDetailsCheckAll = new DataTable();
            dtEmployeeDetailsCheckAll = (DataTable)Session["EmployeeDetails"];
            foreach (DataRow drRow in dtEmployeeDetailsCheckAll.Rows)
            {
                if (((CheckBox)(sender)).Checked == true)
                {
                    drRow["SelectedRecords"] = "1";
                }
                else
                {
                    drRow["SelectedRecords"] = "0";
                }
            }
            grdEmployeeDetails.DataSource = dtEmployeeDetailsCheckAll;
            grdEmployeeDetails.DataBind();
            Session["EmployeeDetails"] = dtEmployeeDetailsCheckAll;
            CheckBox chkSelect = new CheckBox();
            chkSelect = (CheckBox)grdEmployeeDetails.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;
        }
    }
    #endregion
    #region Not Used
    /// <summary>
    /// Bindings the employee category and type.
    /// </summary>
    private void BindingEmployeeCategoryandType()
    {
        // employee category binding
        DataSet dsCategory = new DataSet();
        dsCategory = objEmployee.SelectCategoryDetailsEmployee("");
        if (dsCategory != null)
        {
            if (dsCategory.Tables[0].Rows.Count > 0)
            {
                ddlEmpCatagory.DataSource = dsCategory;
                ddlEmpCatagory.DataTextField = "CategoryName";
                ddlEmpCatagory.DataValueField = "CategoryId";
                ddlEmpCatagory.DataBind();
            }
            dsCategory.Dispose();
            foreach (ListItem item in ddlEmpCatagory.Items)
            {
                item.Attributes.Add("title", item.Text);
            }
        }
        // employee type binding
        DataSet dsType = new DataSet();
        dsType = objEmployee.SelectTypeDetailsEmployee("");
        if (dsType != null)
        {
            if (dsType.Tables[0].Rows.Count > 0)
            {
                ddlEmpType.DataSource = dsType;
                ddlEmpType.DataTextField = "TypeName";
                ddlEmpType.DataValueField = "TypeId";
                ddlEmpType.DataBind();
            }
            dsType.Dispose();
            foreach (ListItem item in ddlEmpType.Items)
            {
                item.Attributes.Add("title", item.Text);
            }
        }
    }
    /// <summary>
    /// Validate the FromDate
    /// </summary>
    /// <param name="s"></param>
    /// <param name="e"></param>
    public void ValidateFromDate(object s, ServerValidateEventArgs e)
    {
        try
        {
            string strFromdate = objCommon.DateConvertion(Session["MDateFormat"].ToString(), txtFromDate.Text);
            DateTime dtCurrentDate = Convert.ToDateTime(DateTime.Today.Date);
            DateTime dtFromDate = DateTime.Parse(strFromdate);
            TimeSpan diff = dtFromDate.Subtract(dtCurrentDate);
            int day = diff.Days;
            if (day <= 0)
            {
                e.IsValid = true;
                grdEmployeeDetails.Visible = true;
            }
            else
            {
                grdEmployeeDetails.Visible = false;
                btnSave.Visible = false;
                strAlert = string.Empty;
                strAlert = "alert('" + rm.GetString("Alert_SelectvalidFromDate", ci) + "')";
                ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", strAlert, true);
                //base.Message(rm.GetString("Alert_SelectvalidFromDate", ci));
                txtFromDate.Focus();
                e.IsValid = false;
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    /// <summary>
    /// Validate the ToDate
    /// </summary>
    /// <param name="s"></param>
    /// <param name="e"></param>
    public void ValidateToDate(object s, ServerValidateEventArgs e)
    {
        try
        {
            string strTodate = objCommon.DateConvertion(Session["MDateFormat"].ToString(), txtToDate.Text);
            //DateTime dtCurrentDate = Convert.ToDateTime(DateTime.Today.Date.ToString("MM/dd/yyyy"));
            DateTime dtCurrentDate = Convert.ToDateTime(DateTime.Today.Date);
            DateTime dtFromDate = DateTime.Parse(strTodate);
            TimeSpan diff = dtFromDate.Subtract(dtCurrentDate);
            int day = diff.Days;
            if (day <= 0)
            {
                e.IsValid = true;
                grdEmployeeDetails.Visible = true;
            }
            else
            {
                grdEmployeeDetails.Visible = false;
                btnSave.Visible = false;
                strAlert = string.Empty;
                strAlert = "alert('" + rm.GetString("Alert_SelectvalidToDate", ci) + "')";
                ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", strAlert, true);
                //base.Message(rm.GetString("Alert_SelectvalidToDate", ci));
                txtToDate.Focus();
                e.IsValid = false;
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    #endregion
}
