using DevExpress.Web;
using System;
using System.Data;
using System.Globalization;
using System.IO;
using System.Resources;
using System.Text.RegularExpressions;
using System.Threading;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Text;
/****************************************************************************************************************************
* Project Name    : TimeCheck                                   Started Date  : 12-Aug-2007
* Module          : Leave                                       Last Modified : 14-Aug-2007
* Programmer      : 
* Current Storage : \\Angler56\Projects\Inprogress\SCREEN1206\code\Time_AttendanceApp
* BackUp          :
****************************************************************************************************************************/
public partial class Master_TA_UI_EmailSchedule : Base.BasePage
{
    EmailConfiguration objEmailConfiguration = new EmailConfiguration();
    cls_Common objcommon = new cls_Common();
    ShiftAllocationEvendata obj = new ShiftAllocationEvendata();
    ResourceManager rm;
    CultureInfo ci;
    string source_Language;
    DataSet ds = new DataSet();
    EmployeeEventData objEmployee = new EmployeeEventData();
    enum EmailSendtype { LINK, ATTACHMENT };
    enum LoginRequired { NO, YES };
    int totRecords = 0;
    bool checkRecordExists;
    bool checkLevel;
    string strFromdate, gstrDateFormat;
    protected override void Page_Load(object sender, EventArgs e)
    {
        // session checking
        base.Page_Load(sender, e);
        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;
        string str = Convert.ToString(Session["GridCSS"]);
        grv_EmailEmpDetails.Styles.CssFilePath = Convert.ToString(Session["GridCSS"]);

        DataSet dsEmailLDAPValidation = new DataSet();
        dsEmailLDAPValidation = objEmailConfiguration.LDAPLinkValidation();
        if(dsEmailLDAPValidation.Tables[0].Rows.Count>0)
        {
            lblEmailSendType.Visible = false;
            rbAttachment.Visible = false;
            rbLink.Visible = false;
            lblLoginRequired.Visible = false;
            tdLoginRequired.Visible = false;
        }

        if (Session["Session_ActiveLanguage"] == null)
        {
            string strScript1 = "<script language='javascript' type='text/javascript'>";
            strScript1 += "alert('" + rm.GetString("Alert_SessionExpired", ci) + "');self.close();";
            strScript1 += " </script>";
            this.RegisterStartupScript("closeScript1", strScript1);
            return;
        }
        string strSetAlert1 = "";
        strSetAlert1 = strSetAlert1 + "<script language='javascript'>";
        strSetAlert1 = strSetAlert1 + "SetAlertMessages('" + rm.GetString("Alert_Selectreportname", ci) + "','" + rm.GetString("Alert_EnterScheduleName", ci) + "','" + rm.GetString("Alert_SelectChooseFilters", ci) + "','" + rm.GetString("Alert_EnterTimeToSend", ci) + "','" + rm.GetString("Alert_EnterToMailIds", ci) + "','" + rm.GetString("Alert_EnterSubject", ci) + "','" + rm.GetString("Alert_SelectDayTo", ci) + "','" + rm.GetString("Alert_Are_you_sure_to_Save", ci) + "');";
        strSetAlert1 = strSetAlert1 + "</script>";
        Page.RegisterStartupScript("SetAlertMessages", strSetAlert1);
        site.SiteMapProvider = Convert.ToString(Session["SiteMapProvider"]);
        LoadStrings(ci);
        hiddenTime.Value = Convert.ToString(Session["ITimeFormat"]);
        if (!Page.IsPostBack)
        {
            LoadReportName();
            ViewState["Report"] = string.Empty;
            objcommon.menu("Masters_EmailConfiguration", "177");
        }
        string strSetAlert = string.Empty;
        strSetAlert = strSetAlert + "<script language='javascript'>";
        strSetAlert = strSetAlert + "MaxLengthh('" + rm.GetString("Alert_MaximumLengthis", ci) + "');SetAuthentication();EnableDisableToAndCC();EnableChooseFilters();";
        strSetAlert = strSetAlert + "</script>";
        Page.RegisterStartupScript("MaxLength", strSetAlert);
        string strScript;
        if (!Page.IsPostBack)
        {
            if (Request.QueryString["ScheduleId"] != null)
            {
                btnChooseFilters.Enabled = true;
                //ddlReportName.Enabled = false;
                DataSet dsEmailSchedule = new DataSet();
                dsEmailSchedule = objEmailConfiguration.SelectEmailScheduleBasedOnId(Convert.ToInt32(Request.QueryString["ScheduleId"]));
                if (dsEmailSchedule.Tables[0].Rows.Count > 0)
                {
                    Session["ScheduleId"] = Convert.ToString(Request.QueryString["ScheduleId"]);
                    if (Convert.ToString(dsEmailSchedule.Tables[0].Rows[0]["ScheduleName"]) != "")
                        txtScheduleName.Text = Convert.ToString(dsEmailSchedule.Tables[0].Rows[0]["ScheduleName"]);
                    int Authentication = 0;
                    if (Convert.ToString(dsEmailSchedule.Tables[0].Rows[0]["Authentication"]) != "")
                        Authentication = Convert.ToInt32(dsEmailSchedule.Tables[0].Rows[0]["Authentication"]);
                    if (Convert.ToString(dsEmailSchedule.Tables[0].Rows[0]["ReportId"]) != "")
                        ddlReportName.SelectedValue = Convert.ToString(dsEmailSchedule.Tables[0].Rows[0]["ReportId"]);
                    if (Convert.ToString(dsEmailSchedule.Tables[0].Rows[0]["FileType"]) != "")
                        ddlFileType.SelectedValue = Convert.ToString(dsEmailSchedule.Tables[0].Rows[0]["FileType"]);
                    string Frequency = "";
                    if (Convert.ToString(dsEmailSchedule.Tables[0].Rows[0]["Frequency"]) != "")
                        Frequency = Convert.ToString(dsEmailSchedule.Tables[0].Rows[0]["Frequency"]);
                    if (Convert.ToString(dsEmailSchedule.Tables[0].Rows[0]["DateTo"]) != "")
                        ddlDateTo.SelectedValue = Convert.ToString(dsEmailSchedule.Tables[0].Rows[0]["DateTo"]);
                    int EmailSendType = 0;
                    if (Convert.ToString(dsEmailSchedule.Tables[0].Rows[0]["EmailSendType"]) != "")
                        EmailSendType = Convert.ToInt32(dsEmailSchedule.Tables[0].Rows[0]["EmailSendType"]);
                    if (Convert.ToString(dsEmailSchedule.Tables[0].Rows[0]["Subject"]) != "")
                        txtSubject.Text = Convert.ToString(dsEmailSchedule.Tables[0].Rows[0]["Subject"]);
                    if (Convert.ToString(dsEmailSchedule.Tables[0].Rows[0]["EmailContent"]) != "")
                    {
                        editor.InnerText = Convert.ToString(dsEmailSchedule.Tables[0].Rows[0]["EmailContent"]);
                        string check = ConvertHtmlToPlainText(editor.InnerText);
                        HtmlConverter converter = new HtmlConverter();
                        string plainTextContent = converter.ConvertHtmlToPlainText(editor.InnerText);
                        editor.InnerText = plainTextContent;
                    }
                    //editor.Text = Convert.ToString(dsEmailSchedule.Tables[0].Rows[0]["EmailContent"]);
                    if (Convert.ToString(dsEmailSchedule.Tables[0].Rows[0]["ToEmailList"]) != "")
                        txtToemailID.Text = Convert.ToString(dsEmailSchedule.Tables[0].Rows[0]["ToEmailList"]);
                    if (Convert.ToString(dsEmailSchedule.Tables[0].Rows[0]["CCEmailList"]) != "")
                        txtCCemailID.Text = Convert.ToString(dsEmailSchedule.Tables[0].Rows[0]["CCEmailList"]);
                    if (Convert.ToString(dsEmailSchedule.Tables[0].Rows[0]["Filters"]) != "")
                        hdnFilters.Value = Convert.ToString(dsEmailSchedule.Tables[0].Rows[0]["Filters"]);
                    if (Convert.ToString(dsEmailSchedule.Tables[0].Rows[0]["ReportType"]) != "")
                        hdnReportType.Value = Convert.ToString(dsEmailSchedule.Tables[0].Rows[0]["ReportType"]);
                    if (Convert.ToString(dsEmailSchedule.Tables[0].Rows[0]["CompanyId"]) != "")
                        hdnCompanyId.Value = Convert.ToString(dsEmailSchedule.Tables[0].Rows[0]["CompanyId"]);
                    Session["parentLevelId_modify"] = hdnCompanyId.Value;
                    //if (Convert.ToString(dsEmailSchedule.Tables[0].Rows[0]["ReportId"]) == "34")
                    //{
                    divTowhom.Style.Add("display", "");
                    divTimeOption.Style.Add("display", "");
                    if (Convert.ToString(dsEmailSchedule.Tables[0].Rows[0]["ToWhom"]) == "1")
                    {
                        if (Convert.ToString(dsEmailSchedule.Tables[0].Rows[0]["Reminder_afterDays"]) != "" && Convert.ToString(dsEmailSchedule.Tables[0].Rows[0]["Reminder_afterDays"]) != "0")
                        {
                            divAfterDays.Style.Add("display", "");
                            chkboxReporting.Checked = true;
                            txtAfter.Enabled = true;
                            txtAfter.Text = Convert.ToString(dsEmailSchedule.Tables[0].Rows[0]["Reminder_afterDays"]);
                        }
                        else
                        {
                            divAfterDays.Style.Add("display", "none");
                            chkboxReporting.Checked = false;
                            txtAfter.Enabled = false;
                        }
                    }
                    else
                    {
                        divAfterDays.Style.Add("display", "none");
                        chkboxReporting.Checked = false;
                        txtAfter.Enabled = false;
                    }
                    if (Convert.ToString(dsEmailSchedule.Tables[0].Rows[0]["ToWhom"]) == "1")
                    {
                        if (Convert.ToString(dsEmailSchedule.Tables[0].Rows[0]["TimeToSend"]) != "")
                            txtTimeToSendEmp.Text = Convert.ToString(dsEmailSchedule.Tables[0].Rows[0]["TimeToSend"]);
                        rbtnEmployee.Checked = true;
                    }
                    else if (Convert.ToString(dsEmailSchedule.Tables[0].Rows[0]["ToWhom"]) == "0")
                    {
                        if (Convert.ToString(dsEmailSchedule.Tables[0].Rows[0]["TimeToSend"]) != "")
                            txtTimeToSend.Text = Convert.ToString(dsEmailSchedule.Tables[0].Rows[0]["TimeToSend"]);
                        rbtnOthers.Checked = true;
                    }
                    else
                    {
                        if (Convert.ToString(dsEmailSchedule.Tables[0].Rows[0]["TimeToSend"]) != "")
                            txtTimeToSendEmp.Text = Convert.ToString(dsEmailSchedule.Tables[0].Rows[0]["TimeToSend"]);
                        rbtnReportingTo.Checked = true;
                    }
                    rbtnEmployee_CheckedChanged(sender, e);
                    if (Convert.ToString(dsEmailSchedule.Tables[0].Rows[0]["TimeSendOption"]) != null)
                    {
                        ddlTimeOption.SelectedValue = Convert.ToString(dsEmailSchedule.Tables[0].Rows[0]["TimeSendOption"]);
                    }
                    else
                    {
                        ddlTimeOption.SelectedValue = "1";
                    }
                    //}
                    if (Frequency == "Daily")
                    {
                        rbDaily.Checked = true;
                        rbWeekly.Checked = false;
                        rbMonthly.Checked = false;
                    }
                    else if (Frequency == "Monthly")
                    {
                        rbMonthly.Checked = true;
                        rbWeekly.Checked = false;
                        rbDaily.Checked = false;
                        if (Convert.ToString(dsEmailSchedule.Tables[0].Rows[0]["DateToSend"]) != "")
                            ddlDateToSend.SelectedValue = Convert.ToString(dsEmailSchedule.Tables[0].Rows[0]["DateToSend"]);
                        if (Convert.ToString(dsEmailSchedule.Tables[0].Rows[0]["DateFrom"]) != "")
                            ddlDateFrom.SelectedValue = Convert.ToString(dsEmailSchedule.Tables[0].Rows[0]["DateFrom"]);
                        if (Convert.ToString(dsEmailSchedule.Tables[0].Rows[0]["DateTo"]) != "")
                            ddlDateTo.SelectedValue = Convert.ToString(dsEmailSchedule.Tables[0].Rows[0]["DateTo"]);
                    }
                    else
                    {
                        rbWeekly.Checked = true;
                        rbDaily.Checked = false;
                        rbMonthly.Checked = false;
                        if (Convert.ToString(dsEmailSchedule.Tables[0].Rows[0]["DayToSend"]) != "")
                            ddlDayToSend.SelectedValue = SelectDropDownItem(Convert.ToString(dsEmailSchedule.Tables[0].Rows[0]["DayToSend"]));
                        if (Convert.ToString(dsEmailSchedule.Tables[0].Rows[0]["DayFrom"]) != "")
                            ddlDayFrom.SelectedValue = SelectDropDownItem(Convert.ToString(dsEmailSchedule.Tables[0].Rows[0]["DayFrom"]));
                        if (Convert.ToString(dsEmailSchedule.Tables[0].Rows[0]["DayTo"]) != "")
                            ddlDayTo.SelectedValue = SelectDropDownItem(Convert.ToString(dsEmailSchedule.Tables[0].Rows[0]["DayTo"]));
                    }
                    if (Convert.ToInt32(EmailSendtype.ATTACHMENT) == EmailSendType)
                    {
                        rbAttachment.Checked = true;
                        rbLink.Checked = false;
                    }
                    else
                    {
                        rbLink.Checked = true;
                        rbAttachment.Checked = false;
                    }
                    if (Convert.ToInt32(LoginRequired.YES) == Authentication)
                    {
                        rbYes.Checked = true;
                        rbNo.Checked = false;
                    }
                    else
                    {
                        rbNo.Checked = true;
                        rbYes.Checked = false;
                    }
                    strScript = string.Empty;
                    strScript = "<script language='javascript'>";
                    strScript = strScript + "SetFrequency();SetAuthentication();";
                    strScript = strScript + "</script>";
                    Page.RegisterStartupScript("Script", strScript);
                    GetSampleDataForDaily();
                    return;
                }
            }
            else
            {
                //BinddropdownItem(1);
                Session["ScheduleId"] = 0;
            }
        }
        
        GetSampleDataForDaily();
    }
    private void GetSampleDataForDaily()
    {
        try
        {
            lbldailysamplevalue.Text = (Convert.ToDateTime(System.DateTime.Now.AddDays(-1).ToShortDateString())).ToString("dd/MM/yyyy");
        }
        catch
        {
            lbldailysamplevalue.Text = DateTime.Now.AddDays(-1).ToString();
        }
    }
    //Getting Information from resource file and display it in label
    private void LoadStrings(CultureInfo ci)
    {
        lblApprovalTO.Text = rm.GetString("Caption_ToMailIds", ci);
        lblApprovalCC.Text = rm.GetString("Caption_CcMailIds", ci);
        btnSave.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Save", ci);
        btnBack.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Back", ci);
        btn_Delete.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Delete", ci);
        btnApprovalTO.Text = rm.GetString("Caption_To", ci);
        btnApprovalCC.Text = rm.GetString("Caption_CC", ci);
        lbl_IndicatesMandatoryFields.Text = rm.GetString("IndicatesMandatoryFields", ci);
        lblSelectEmployee.Text = rm.GetString("lblSelectEmployee", ci);
        lbl_EmailSchedule.Text = rm.GetString("Masters_EmailConfiguration", ci);
        lblScheduleName.Text = rm.GetString("lblEmailScheduleName", ci);
        lblReportName.Text = rm.GetString("lblEmailReportName", ci);
        lblFrequency.Text = rm.GetString("lblEmailFrequency", ci);
        btnChooseFilters.Text = "&nbsp;&nbsp;" + rm.GetString("lnkbtnChooseFilter", ci);
        rbDaily.Text = rm.GetString("lblEmailDaily", ci);
        rbWeekly.Text = rm.GetString("lblEmailWeekly", ci);
        rbMonthly.Text = rm.GetString("lblEmailMonthly", ci);
        lblTimeToSend.Text = rm.GetString("lblEmailTimeToSend", ci);
        lblDayToSend.Text = rm.GetString("lblEmailDayToSend", ci);
        lblDayFrom.Text = rm.GetString("lblEmailPreviousWeek", ci);
        lblDayTo.Text = rm.GetString("email_ToDate", ci);
        lblSample.Text = rm.GetString("lblEmailSample", ci);
        lblDateToSend.Text = rm.GetString("lblEmailDateToSend", ci);
        lblDateFrom.Text = rm.GetString("lblEmailPreviousMonth", ci);
        lblDateTo.Text = rm.GetString("email_ToDate", ci);
        Label3.Text = rm.GetString("lblEmailSample", ci);
        lblEmailSendType.Text = rm.GetString("lblEmailEmailSendtype", ci);
        rbAttachment.Text = rm.GetString("lblEmailAttachment", ci);
        rbLink.Text = rm.GetString("lblEmailLink", ci);
        lblLoginRequired.Text = rm.GetString("lblEmailLoginRequired", ci);
        rbYes.Text = rm.GetString("ShiftSetting_Yes", ci);
        rbNo.Text = rm.GetString("ShiftSetting_No", ci);
        lblEmailTemplate.Text = rm.GetString("lblEmailEmailTemplate", ci);
        lblSubject.Text = rm.GetString("lblEmailSubject", ci);
    }
    public void LoadReportName()
    {
        DataSet dsReportName = new DataSet();
        dsReportName = objEmailConfiguration.SelectReportsForEmailSchedule(Convert.ToString(Session["UserGroupName"]));
        if (dsReportName.Tables[0].Rows.Count > 0)
        {
            ViewState["ReportNames"] = dsReportName.Tables[0];
            ddlReportName.DataSource = dsReportName;
            ddlReportName.DataValueField = "pageId";
            ddlReportName.DataTextField = "displayName";
            ddlReportName.DataBind();
        }
        foreach (ListItem list in ddlReportName.Items)
        {
            if (list.Text == "Report_CountFactor_WorkingDays")
                list.Text = "Count factor Working days";
            else if (list.Text == "Leave Approval")
                list.Text = "Leave Approval";
            else if (list.Text == "Onduty Approval")
                list.Text = "Onduty Approval";
            else
                list.Text = Convert.ToString(rm.GetString(list.Text));
        }
    }

    public string ConvertHtmlToPlainText(string htmlContent)
    {
        if (string.IsNullOrWhiteSpace(htmlContent))
        {
            return string.Empty;
        }

        // Remove script and style tags and their content
        htmlContent = Regex.Replace(htmlContent, @"<script[^>]*>[\s\S]*?</script>|<style[^>]*>[\s\S]*?</style>", string.Empty, RegexOptions.IgnoreCase);

        // Replace specific tags with line breaks
        htmlContent = Regex.Replace(htmlContent, @"<(br|div|p)[^>]*>", "\n", RegexOptions.IgnoreCase);
        htmlContent = Regex.Replace(htmlContent, @"<\/(div|p|h[1-6])>", "\n", RegexOptions.IgnoreCase);

        // Remove all other HTML tags
        htmlContent = Regex.Replace(htmlContent, @"<[^>]+>|&nbsp;", string.Empty).Trim();

        // Replace HTML entities
        htmlContent = Regex.Replace(htmlContent, @"&lt;", "<", RegexOptions.IgnoreCase);
        htmlContent = Regex.Replace(htmlContent, @"&gt;", ">", RegexOptions.IgnoreCase);
        htmlContent = Regex.Replace(htmlContent, @"&quot;", "\"", RegexOptions.IgnoreCase);
        htmlContent = Regex.Replace(htmlContent, @"&apos;", "'", RegexOptions.IgnoreCase);
        htmlContent = Regex.Replace(htmlContent, @"&amp;", "&", RegexOptions.IgnoreCase);

        // Normalize multiple consecutive newlines and spaces
        htmlContent = Regex.Replace(htmlContent, @"\n\s*\n", "\n\n"); // double newline for paragraphs
        htmlContent = Regex.Replace(htmlContent, @"[ \t\r\f\v]+", " "); // replace multiple spaces with a single space

        // Trim leading and trailing whitespace
        htmlContent = htmlContent.Trim();
        return htmlContent;
    }

    private string ConvertPlainTextToHtml(string plainText)
    {
        StringBuilder htmlBuilder = new StringBuilder();

        // Convert newlines to <br/> and paragraphs to <div>
        string[] lines = plainText.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None);
        foreach (string line in lines)
        {
            if (line.StartsWith("·"))
            {
                htmlBuilder.Append("<li>" + line.Substring(1).Trim() + "</li>");
            }
            else if (line.Contains("Chapter"))
            {
                htmlBuilder.Append("<u style='color:blue; font:Calibri;size:11;'>" + line + "</u><br/>");
            }
            else if (line.StartsWith("http"))
            {
                htmlBuilder.Append("<a style='color:blue; font:Calibri;size:11;' href='" + line + "'>" + line + "</a><br/>");
            }
            else if (line.Contains("@"))
            {
                htmlBuilder.Append("<u><a style='color:blue; font:Calibri;size:11;' href='mailto:" + line + "'>" + line + "</a></u><br/>");
            }
            else
            {
                htmlBuilder.Append("<div>" + line + "</div><br/>");
            }
        }

        // Wrap list items in <ul>
        string htmlContent = htmlBuilder.ToString();
        htmlContent = htmlContent.Replace("<li>", "<ul><li>").Replace("</li><br/><div>", "</li></ul><div>");

        return htmlContent;
    }


    protected void btnSave_Click(object sender, EventArgs e)
    {

        string plainTextContents = editor.InnerText.ToString();

        //string plainTextContent = Request.Form["editor"];

        // Convert the plain text to HTML
        string htmlContent = ConvertPlainTextToHtml(plainTextContents);


        string strInvalidEmailIdInTo = string.Empty;
        string strInvalidEmailIdInCC = string.Empty;
        string Frequency = "Daily";
        char[] Delimit = { ';' };
        StringBuilder strFilters = new StringBuilder();
        if (Convert.ToInt32(ddlReportName.SelectedValue) == 248)
        {
            hdnReportType.Value = "0";
            strFilters.Append("@fromDat=" + " Duration_From " + ",");
            strFilters.Append("@ToDat=" + " Duration_To " + ",");
            strFilters.Append("@empId=,");
            strFilters.Append("@shift= 0,");
            strFilters.Append("@EmployeeName=,");
            strFilters.Append("@LevelID=" + "0,");
            strFilters.Append("@EmployeeCategory=0,");
            strFilters.Append("@EmployeeType=0,");
            strFilters.Append("@UserGroupName=" + Convert.ToString(Session["UserGroupName"]) + ",");
            strFilters.Append("@GradeLevel=" + Convert.ToString(Session["GradeLevel"]) + ",");
            strFilters.Append("@EmpSwipeCard=,");
            strFilters.Append("@ParentId=" + Convert.ToInt32(Session["parentLevelId"]).ToString() + ",");
            strFilters.Append("@DesignationID=0,");
            strFilters.Append("@Gender=Both,");
            strFilters.Append("@LeaveType=All,");
            strFilters.Append("@LeaveStatus=All,");
            strFilters.Append("@EmpAutoId=0");
            hdnFilters.Value = Convert.ToString(strFilters);
            hdnCompanyId.Value = "0";
        }
        else if (Convert.ToInt32(ddlReportName.SelectedValue) == 249)
        {
            hdnReportType.Value = "0";
            strFilters.Append("@fromDate=" + " Duration_From " + ",");
            strFilters.Append("@ToDate=" + " Duration_To " + ",");
            strFilters.Append("@EmployeeId=,");
            strFilters.Append("@EmployeeName=,");
            strFilters.Append("@LevelID=0,");
            strFilters.Append("@EmployeeCategory=0,");
            strFilters.Append("@EmployeeType=0,");
            strFilters.Append("@UserGroupName=" + Convert.ToString(Session["UserGroupName"]) + ",");
            strFilters.Append("@GradeLevel=" + Convert.ToString(Session["GradeLevel"]) + ",");
            strFilters.Append("@EmpSwipeCard=,");
            strFilters.Append("@ParentId=" + Convert.ToInt32(Session["parentLevelId"]).ToString() + ",");
            strFilters.Append("@Status=All,");
            strFilters.Append("@DesignationID=0,");
            strFilters.Append("@EmpAutoId=0,");
            strFilters.Append("@Gender=Both");
            hdnFilters.Value = Convert.ToString(strFilters);
            hdnCompanyId.Value = "0";
        }
        if (txtScheduleName.Text.Trim() == "")
        {
            Message(rm.GetString("Alert_EnterScheduleName", ci));
            return;
        }
        else if (ddlReportName.SelectedIndex == -1)
        {
            Message(rm.GetString("Alert_Selectreportname", ci));
            return;
        }
        else if (hdnFilters.Value == "")
        {
            Message(rm.GetString("Alert_SelectChooseFilters", ci));
            return;
        }
        else if (txtTimeToSend.Text.Trim() == "" && txtTimeToSendEmp.Text.Trim() == "")
        {
            Message(rm.GetString("Alert_EnterTimeToSend", ci));
            return;
        }
        else if (txtToemailID.Text != string.Empty)
        {
            string strMailIdsTo = txtToemailID.Text;
            string[] MailIdsTo = strMailIdsTo.Split(Delimit);
            foreach (string MailId in MailIdsTo)
            {
                if (!ValidateEmailID(MailId))
                {
                    base.Message(rm.GetString("Alert_EnterValidEmailIdinToMailIds", ci));
                    return;
                }
            }
        }
        else if (txtCCemailID.Text != string.Empty)
        {
            string strMailIdsCC = txtCCemailID.Text;
            string[] MailIdsCC = strMailIdsCC.Split(Delimit);
            foreach (string MailId in MailIdsCC)
            {
                if (!ValidateEmailID(MailId))
                {
                    base.Message(rm.GetString("Alert_EnterValidEmailIdinCcMailIds", ci));
                    return;
                }
            }
        }
        int towhom = 0;
        int TimeSendOption = 0;
        //if (ddlReportName.SelectedItem.Text == "Absent")
        //{
        if (rbtnEmployee.Checked || rbtnReportingTo.Checked)
        {
            String str = hdnSelectRow.Value;
            towhom = (rbtnEmployee.Checked) ? 1 : 2;
            if (ViewState["Employees"] != null)
            {
                if (hdnSelectRow.Value != "")
                {
                    DataSet dsvalue = (DataSet)ViewState["Employees"];
                    string[] valuesArray = hdnSelectRow.Value.Split(',');

                    foreach (var n in valuesArray)
                    {
                        foreach (DataRow dr in dsvalue.Tables[0].Rows)
                        {
                            if (Convert.ToString(dr["Employee_Code_Id"]) == n)
                            {
                                dr["emailScheduler_flag"] = 1;
                            }
                        }
                    }
                    ViewState["Employees"] = dsvalue;
                }

                ds = (DataSet)ViewState["Employees"];
                DataRow[] drfilter = ds.Tables[0].Select("emailScheduler_flag=1");
                if (drfilter.Length == 0)
                {
                    divTowhom.Style.Add("display", "");
                    divTimeOption.Style.Add("display", "");
                    divgrid.Style.Add("display", "");
                    Message("Select any one employee in the listview");
                    return;
                }
                else
                {
                    for (int i = 0; i < drfilter.Length; i++)
                    {
                        if (Convert.ToString(drfilter[i]["EmailId"]) == "")
                        {
                            divTowhom.Style.Add("display", "");
                            divTimeOption.Style.Add("display", "");
                            divgrid.Style.Add("display", "");
                            Message("Email id is not availabe for this employee id : " + Convert.ToString(drfilter[i]["Employee_Code_Id"]));
                            return;
                        }
                    }
                }
            }
        }
        TimeSendOption = Convert.ToInt16(ddlTimeOption.SelectedItem.Value);
        //}
        Frequency = (rbMonthly.Checked == true) ? "Monthly" : (rbWeekly.Checked == true) ? "Weekly" : "Daily";

        int EmailSendType = Convert.ToInt32(EmailSendtype.LINK);
        if (rbAttachment.Checked == true)
        {
            EmailSendType = Convert.ToInt32(EmailSendtype.ATTACHMENT);
        }
        int Authentication = (rbYes.Checked == true) ? Convert.ToInt32(LoginRequired.YES) : Convert.ToInt32(LoginRequired.NO);
        int InsertedId = 0;
        string reportname = "";
        string strEmployeeIds = Convert.ToString(Session["EmployeeIds"]);
        int afterDays = 0;
        if (towhom == 1 && chkboxReporting.Checked)
        {
            //if (txtAfter.Enabled)
            if (txtAfter.Text != "")
                afterDays = Convert.ToInt32(txtAfter.Text);
        }
        if (Request.QueryString["ScheduleId"] == null)
        {
            if (Convert.ToString(hdnReportType.Value) == "0" && Convert.ToInt32(ddlReportName.SelectedValue) == 183)
                reportname = "RawDataDetailed";
            else
                reportname = Convert.ToString(ddlReportName.SelectedItem.Text);

            InsertedId = objEmailConfiguration.InsertUpdateEmailScheduleDetails(txtScheduleName.Text, Convert.ToInt32(ddlReportName.SelectedValue), Frequency, Convert.ToString(ddlDayToSend.SelectedItem.Text), Convert.ToString(ddlDayFrom.SelectedItem.Text), Convert.ToString(ddlDayTo.SelectedItem.Text), Convert.ToInt32(ddlDateToSend.SelectedValue), Convert.ToInt32(ddlDateFrom.SelectedValue), Convert.ToInt32(ddlDateTo.SelectedValue), (rbtnOthers.Checked) ? txtTimeToSend.Text : txtTimeToSendEmp.Text, Convert.ToInt32(Session["EmpAutoId"]), EmailSendType, Authentication, ddlFileType.SelectedValue, 1, 0, "I", reportname, towhom, TimeSendOption, afterDays);
            if (InsertedId == 0)
            {
                Message(rm.GetString("Alert_ScheduleNamealreadyexists", ci));
                return;
            }
            //objEmailConfiguration.InsertUpdateEmailTemplate(InsertedId, txtSubject.Text, editor.Text, "I"); 
            objEmailConfiguration.InsertUpdateEmailTemplate(InsertedId, txtSubject.Text, htmlContent, "I");
            objEmailConfiguration.InsertUpdateEmailScheduleFilters(InsertedId, hdnFilters.Value, hdnReportType.Value, "I", Convert.ToInt32(hdnCompanyId.Value));
        }
        else
        {
            if (Convert.ToString(hdnReportType.Value) == "0" && Convert.ToInt32(ddlReportName.SelectedValue) == 183)
            {
                reportname = "RawDataDetailed";
            }
            else
            {
                reportname = Convert.ToString(ddlReportName.SelectedItem.Text);
            }
            InsertedId = objEmailConfiguration.InsertUpdateEmailScheduleDetails(txtScheduleName.Text, Convert.ToInt32(ddlReportName.SelectedValue), Frequency, Convert.ToString(ddlDayToSend.SelectedItem.Text), Convert.ToString(ddlDayFrom.SelectedItem.Text), Convert.ToString(ddlDayTo.SelectedItem.Text), Convert.ToInt32(ddlDateToSend.SelectedValue), Convert.ToInt32(ddlDateFrom.SelectedValue), Convert.ToInt32(ddlDateTo.SelectedValue), (rbtnOthers.Checked) ? txtTimeToSend.Text : txtTimeToSendEmp.Text, Convert.ToInt32(Session["EmpAutoId"]), EmailSendType, Authentication, ddlFileType.SelectedValue, 1, Convert.ToInt32(Request.QueryString["ScheduleId"]), "U", reportname, towhom, TimeSendOption, afterDays);
            if (InsertedId == 0)
            {
                Message(rm.GetString("Alert_ScheduleNamealreadyexists", ci));
                return;
            }
            objEmailConfiguration.InsertUpdateEmailTemplate(InsertedId, txtSubject.Text, htmlContent, "I");
            objEmailConfiguration.InsertUpdateEmailTemplate(Convert.ToInt32(Request.QueryString["ScheduleId"]), txtSubject.Text, htmlContent, "U");
            //objEmailConfiguration.InsertUpdateEmailTemplate(Convert.ToInt32(Request.QueryString["ScheduleId"]), txtSubject.Text, editor.Text, "U");
            objEmailConfiguration.InsertUpdateEmailScheduleFilters(Convert.ToInt32(Request.QueryString["ScheduleId"]), hdnFilters.Value, hdnReportType.Value, "U", Convert.ToInt32(hdnCompanyId.Value));
            objEmailConfiguration.DeleteMailIDBeforeInserting(Convert.ToInt32(Request.QueryString["ScheduleId"]));
        }
        //if (ddlReportName.SelectedItem.Text == "Absent")
        //{
        if (rbtnEmployee.Checked || rbtnReportingTo.Checked)
        {
            if (ViewState["Employees"] != null)
            {
                ds = (DataSet)ViewState["Employees"];
                StringWriter swselectedEmp = new StringWriter();
                ds.WriteXml(swselectedEmp);
                string strselectedEmp = Convert.ToString(swselectedEmp);
                if (Request.QueryString["ScheduleId"] == null)
                    objEmailConfiguration.InsertAndUpdatEmployeeDetails(InsertedId, strselectedEmp);
                else
                    objEmailConfiguration.InsertAndUpdatEmployeeDetails(Convert.ToInt32(Request.QueryString["ScheduleId"]), strselectedEmp);
            }
        }
        else
        {
            if (Request.QueryString["ScheduleId"] != null)
                objEmailConfiguration.DeleteEmployeeDetails(Convert.ToInt32(Request.QueryString["ScheduleId"]));
        }
        //}
        if (txtToemailID.Text != string.Empty)
        {
            string strMailIds = txtToemailID.Text;
            string[] MailIds = strMailIds.Split(Delimit);
            foreach (string MailId in MailIds)
            {
                if (ValidateEmailID(MailId) == true)
                {
                    if (Request.QueryString["ScheduleId"] == null)
                    {
                        objEmailConfiguration.InsertMailIds(InsertedId, "To", MailId.Trim());
                    }
                    else
                    {
                        objEmailConfiguration.InsertMailIds(Convert.ToInt32(Request.QueryString["ScheduleId"]), "To", MailId.Trim());
                    }
                }
            }
        }
        if (txtCCemailID.Text != string.Empty)
        {
            string strMailIds = txtCCemailID.Text;
            string[] MailIds = strMailIds.Split(Delimit);
            foreach (string MailId in MailIds)
            {
                if (ValidateEmailID(MailId) == true)
                {
                    if (Request.QueryString["ScheduleId"] == null)
                    {
                        objEmailConfiguration.InsertMailIds(InsertedId, "CC", MailId.Trim());
                    }
                    else
                    {
                        objEmailConfiguration.InsertMailIds(Convert.ToInt32(Request.QueryString["ScheduleId"]), "CC", MailId.Trim());
                    }
                }
            }
        }
        string strMessage = (Request.QueryString["ScheduleId"] == null) ? rm.GetString("Alert_EmailSchedulerSavedSuccessfully", ci) : rm.GetString("Alert_EmailSchedulerUpdatedSuccessfully", ci);
        string strMsg;
        strMsg = "<script language='javascript'>";
        strMsg = strMsg + "alert('" + strMessage + "');location.replace('TA_UI_EmailScheduleList.aspx');";
        strMsg = strMsg + "</script>";
        Page.RegisterStartupScript("inserted successfully", strMsg);
        Session["EmployeeDetails"] = Session["hdnReportFilters"] = null;
        ViewState["Employees"] = null;
        return;
    }
    public bool ValidateEmailID(string EmailID)
    {
        string strRegex = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
            @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
            @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";
        strRegex = (hfemail.Value != null) ? Convert.ToString(hfemail.Value) : strRegex;
        Regex re = new Regex(strRegex);
        if (re.IsMatch(EmailID))
            return (true);
        else
            return (false);
    }
    protected void btnBack_Click(object sender, EventArgs e)
    {
        Response.Redirect("TA_UI_EmailScheduleList.aspx");
    }
    protected void btnChooseFilters_Click(object sender, EventArgs e)
    {
        if (ddlReportName.SelectedValue != "0")
        {
            if (Convert.ToString(ViewState["Report"]) != string.Empty)
            {
                if (Convert.ToString(ViewState["Report"]) == Convert.ToString(ddlReportName.SelectedValue))
                {
                    Session["hdnReportFilters"] = Session["hdnReportFilters"];
                    Session["EMailParentId"] = Session["EMailParentId"];
                    Session["ReportTypeID"] = Session["ReportTypeID"];
                    Session["LateReportName"] = Session["LateReportName"];
                }
                else
                {
                    ClearSessions();
                    Session["LateReportName"] = string.Empty;
                    ViewState["Report"] = ddlReportName.SelectedValue;
                }
            }
            else
            {
                ViewState["Report"] = ddlReportName.SelectedValue;
                ClearSessions();
            }
            showToAndCC();
            DataTable dtReportPage = new DataTable();
            dtReportPage = (DataTable)ViewState["ReportNames"];
            dtReportPage.DefaultView.RowFilter = "pageId='" + ddlReportName.SelectedValue + "'";
            if (Request.QueryString["ScheduleId"] != null)
            {
                string strMsg;
                strMsg = "<script language='javascript'>";
                strMsg = strMsg + "openURL('" + Convert.ToString(dtReportPage.DefaultView.ToTable().Rows[0]["path"]) + "?Source=Email&ScheduleId=" + Convert.ToInt32(Request.QueryString["ScheduleId"]) + "');";
                //strMsg = strMsg + "window.open('" + dtReportPage.DefaultView.ToTable().Rows[0]["path"].ToString() + "?Source=Email&ScheduleId=" + Convert.ToInt32(Request.QueryString["ScheduleId"]) + "','','height=550,top=300,left=125,width=1003');";
                strMsg = strMsg + "</script>";
                Page.RegisterStartupScript("open report window", strMsg);
                return;
            }
            else
            {
                //Response.Redirect("../Reports/" + dtReportPage.DefaultView.ToTable().Rows[0]["path"].ToString());
                string strMsg;
                strMsg = "<script language='javascript'>";
                strMsg = strMsg + "openURL('" + Convert.ToString(dtReportPage.DefaultView.ToTable().Rows[0]["path"]) + "?Source=Email');";
                //strMsg = strMsg + "window.open('" + dtReportPage.DefaultView.ToTable().Rows[0]["path"].ToString() + "?Source=Email','','height=550,top=300,left=125,width=1003');";
                strMsg = strMsg + "</script>";
                Page.RegisterStartupScript("open report window", strMsg);
                return;
            }
        }
        else
        {
            string strScript1 = "<script language='javascript' type='text/javascript'>";
            strScript1 += "alert('" + rm.GetString("Alert_Selectreportnamefirst", ci) + "');";
            strScript1 += " </script>";
            this.RegisterStartupScript("Select Report Name", strScript1);
            return;
        }
    }

    private void ClearSessions()
    {
        Session["hdnReportFilters"] = string.Empty;
        Session["EMailParentId"] = string.Empty;
        Session["ReportTypeID"] = string.Empty;
    }

    protected void ddlDayFrom_SelectedIndexChanged(object sender, EventArgs e)
    {
    }
    protected void ddlDayTo_SelectedIndexChanged(object sender, EventArgs e)
    {
    }
    public DataSet dropdownItem(int itemID)
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("Text", typeof(string));
        dt.Columns.Add("Value", typeof(string));
        dt.Rows.Add("Sunday", 1);
        dt.Rows.Add("Monday", 2);
        dt.Rows.Add("Tuesday", 3);
        dt.Rows.Add("Wednesday", 4);
        dt.Rows.Add("Thursday", 5);
        dt.Rows.Add("Friday", 6);
        dt.Rows.Add("Saturday", 7);
        for (int x = 0; x < dt.Rows.Count; x++)
        {
            DataRow[] matches = dt.Select("Value='" + itemID + "'");
            foreach (DataRow row in matches)
            {
                dt.Rows.Remove(row);
            }
        }
        DataSet ds = new DataSet();
        ds.Tables.Add(dt);
        return ds;
    }
    public void BinddropdownItem(int itemID)
    {
        DataSet dsReportName = new DataSet();
        dsReportName = dropdownItem(itemID);
        if (dsReportName.Tables[0].Rows.Count > 0)
        {
            ddlDayTo.DataSource = dsReportName;
            ddlDayTo.DataValueField = "Value";
            ddlDayTo.DataTextField = "Text";
            ddlDayTo.DataBind();
        }
        switch (itemID)
        {
            case 1:
                ddlDayTo.SelectedValue = "7";
                break;
            case 2:
                ddlDayTo.SelectedValue = "1";
                break;
            case 3:
                ddlDayTo.SelectedValue = "2";
                break;
            case 4:
                ddlDayTo.SelectedValue = "3";
                break;
            case 5:
                ddlDayTo.SelectedValue = "4";
                break;
            case 6:
                ddlDayTo.SelectedValue = "5";
                break;
            case 7:
                ddlDayTo.SelectedValue = "6";
                break;
        }
    }
    private void BindPreviousWeekDates(int Frequency, string DayFrom, string DayTo, int DateFrom, int DateTo)
    {
        //DataSet dsPrev_WeekDates = new DataSet();
        //dsPrev_WeekDates = objEmailConfiguration.GetSampleWeekDays(Frequency, Convert.ToString(DayFrom), Convert.ToString(DayTo), DateFrom, DateTo);
        //if (dsPrev_WeekDates.Tables.Count > 0)
        //{
        //    if (dsPrev_WeekDates.Tables[0].Rows.Count > 0)
        //    {
        //        Label2.Text = Convert.ToString(dsPrev_WeekDates.Tables[0].Rows[0]["Fromdate"]) + " To " + Convert.ToString(dsPrev_WeekDates.Tables[0].Rows[0]["Todate"]);
        //    }
        //}
    }
    private string SelectDropDownItem(string WeekName)
    {
        string value = "1";
        switch (WeekName)
        {
            case "Sunday":
                value = "1";
                break;
            case "Monday":
                value = "2";
                break;
            case "Tuesday":
                value = "3";
                break;
            case "Wednesday":
                value = "4";
                break;
            case "Thursday":
                value = "5";
                break;
            case "Friday":
                value = "6";
                break;
            case "Saturday":
                value = "7";
                break;
        }
        return value;
    }
    protected void rbtnEmployee_CheckedChanged(object sender, EventArgs e)
    {
        Session["SelectAllStatus"] = "False";
        Session["EmployeeIds"] = "";
        showToAndCC();
        //if (ddlReportName.SelectedItem.Text == "Absent")
        //{
        if (rbtnEmployee.Checked || rbtnReportingTo.Checked)
        {

            shiftDataBind();
            divTowhom.Style.Add("display", "");
            divTimeOption.Style.Add("display", "");
            divAfterDays.Style.Add("display", "");
        }
        else
        {
            divAfterDays.Style.Add("display", "none");
            divTowhom.Style.Add("display", "");
            divTimeOption.Style.Add("display", "none");
            ViewState["Employees"] = null;
            grv_EmailEmpDetails.DataSource = null;
            grv_EmailEmpDetails.DataBind();
            grv_EmailEmpDetails.EnableViewState = false;
            ddlTimeOption.SelectedIndex = -1;
        }
        //}
        //else
        //{
        //    ViewState["Employees"] = null;
        //    grv_EmailEmpDetails.DataSource = null;
        //    grv_EmailEmpDetails.DataBind();
        //    grv_EmailEmpDetails.EnableViewState = false;
        //}
    }

    //protected void rbtnEmployee_CheckedChanged(object sender, EventArgs e)
    //{
    //    Session["SelectAllStatus"] = "False";
    //    Session["EmployeeIds"] = "";
    //    showToAndCC();
    //    //if (ddlReportName.SelectedItem.Text == "Absent")
    //    //{
    //    if (rbtnEmployee.Checked || rbtnReportingTo.Checked)
    //    {
    //        shiftDataBind();
    //        divTowhom.Style.Add("display", "");
    //        divTimeOption.Style.Add("display", "");
    //        divAfterDays.Style.Add("display", "");
    //    }
    //    else
    //    {
    //        divAfterDays.Style.Add("display", "none");
    //        divTowhom.Style.Add("display", "");
    //        divTimeOption.Style.Add("display", "none");
    //        ViewState["Employees"] = null;
    //        grv_EmailEmpDetails.DataSource = null;
    //        grv_EmailEmpDetails.DataBind();
    //        grv_EmailEmpDetails.EnableViewState = false;
    //        ddlTimeOption.SelectedIndex = -1;
    //    }
    //    //}
    //    //else
    //    //{
    //    //    ViewState["Employees"] = null;
    //    //    grv_EmailEmpDetails.DataSource = null;
    //    //    grv_EmailEmpDetails.DataBind();
    //    //    grv_EmailEmpDetails.EnableViewState = false;
    //    //}
    //}

    private void showToAndCC()
    {
        string strScript = string.Empty;
        strScript = "<script language='javascript'>";
        strScript = strScript + "EnableDisableToAndCC();";
        strScript = strScript + "</script>";
        Page.RegisterStartupScript("Script", strScript);
    }
    //protected void grv_EmailEmpDetails_PageIndexChanging(object sender, GridViewPageEventArgs e)
    //{
    //    grv_EmailEmpDetails.EnableViewState = true;
    //    grv_EmailEmpDetails.PageIndex = e.NewPageIndex;
    //    shiftDataBind();
    //    showToAndCC();
    //    //CheckEmployeeId_CheckBox();
    //}
    //public void CheckEmployeeId_CheckBox()
    //{
    //    if (ViewState["Employees"] != null)
    //        ds = (DataSet)ViewState["Employees"];
    //    if (ds.Tables.Count > 0)
    //    {
    //        if (ds.Tables[0].Rows.Count > 0)
    //        {
    //            CheckBox deleteChkBxItem = new CheckBox();
    //            foreach (GridViewRow gr in grv_EmailEmpDetails.Rows)
    //            {
    //                string empId = ((Label)gr.FindControl("lbl_EmpId")).Text.ToString();
    //                DataRow[] dr = ds.Tables[0].Select("Employee_Code_Id='" + empId + "'");
    //                if (dr.Length > 0)
    //                {
    //                    deleteChkBxItem = (CheckBox)gr.Cells[0].FindControl("deletethis");
    //                    if (Convert.ToString(dr[0][6]) == "1")
    //                        deleteChkBxItem.Checked = true;
    //                    else
    //                        deleteChkBxItem.Checked = false;
    //                }
    //            }
    //        }
    //    }
    //}
    //protected void grv_CheckAll_CheckedChanged(object sender, EventArgs e)
    //{
    //    CheckBox chkSelect = new CheckBox();
    //    chkSelect = (CheckBox)grv_EmailEmpDetails.HeaderRow.Cells[0].FindControl("checkall");
    //    GetEmployeeIdsInOtherPagesOfGrid(chkSelect.Checked);
    //    showToAndCC();
    //}
    protected void grv_Check_CheckedChanged(object sender, EventArgs e)
    {
        GridViewRow gr = ((Control)sender).NamingContainer as GridViewRow;
        Label lblSelectedEmpid = new Label();
        lblSelectedEmpid = (Label)gr.FindControl("lbl_EmpId");
        if (lblSelectedEmpid != null)
        {
            if (lblSelectedEmpid.Text != "")
            {
                if (Convert.ToString(ViewState["Employees"]) != null)
                {
                    ds = (DataSet)ViewState["Employees"];
                    if (ds.Tables.Count > 0)
                    {
                        if (ds.Tables[0].Rows.Count > 0)
                        {
                            DataRow[] dr = ds.Tables[0].Select("Employee_Code_Id='" + lblSelectedEmpid.Text + "'");
                            if (dr.Length > 0)
                            {
                                CheckBox deleteChkBxItem = (CheckBox)gr.FindControl("deletethis");
                                if (deleteChkBxItem != null)
                                {
                                    dr[0][6] = deleteChkBxItem.Checked;
                                }
                            }
                            ds.AcceptChanges();
                        }
                    }
                }
            }
        }
        ViewState["Employees"] = ds;
        showToAndCC();
    }
    public void shiftDataBind()
    {
        if (ViewState["Employees"] == null)
        {
            ds = objEmployee.Search_EmployeeDetailsbyName
                ("", "",
                Convert.ToString(Session["UserGroupName"]),
                Convert.ToString(Session["LevelRights"]),
                Convert.ToString(Session["GradeLevel"]),
                "Select", " ", 0,
                Convert.ToInt32(Session["EmpAutoID"]),
                Convert.ToBoolean(Session["ApplnMode"]),
                0,
                0,
                0,
                "Both",
                Convert.ToInt32(Session["EmpAutoID"]), (Request.QueryString["ScheduleId"] != null) ? Convert.ToInt32(Request.QueryString["ScheduleId"]) : 0, 0, 0, 0, 0, 1, 0);
            ds.Tables[0].DefaultView.RowFilter = "Employee_Status='Active'";
            int count = ds.Tables[0].Rows.Count;
            DataTable dtnew = ds.Tables[0].DefaultView.ToTable();
            DataSet dsnew = new DataSet();
            dsnew.Tables.Add(dtnew);

            ViewState["Employees"] = dsnew;
            //grv_EmailEmpDetails.DataSourceID = "";
            grv_EmailEmpDetails.DataSourceID = ObjectDataSource1.ID;
            //grv_EmailEmpDetails.DataSource = dsnew;
            grv_EmailEmpDetails.DataBind();

        }
        else
        {
            if (hdnSelectRow.Value != "")
            {
                DataSet dsvalue = (DataSet)ViewState["Employees"];
                string[] valuesArray = hdnSelectRow.Value.Split(',');

                foreach (var n in valuesArray)
                {
                    foreach (DataRow dr in dsvalue.Tables[0].Rows)
                    {
                        if (Convert.ToString(dr["Employee_Code_Id"]) == n)
                        {
                            dr["emailScheduler_flag"] = 1;
                        }
                    }
                }
                ViewState["Employees"] = dsvalue;
            }
            ds = (DataSet)ViewState["Employees"];
            //grv_EmailEmpDetails.DataSourceID = "";
            //grv_EmailEmpDetails.DataSource = ds;
            //grv_EmailEmpDetails.DataBind();
        }

    }

    //protected void GetEmployeeIdsInOtherPagesOfGrid(bool chkboxstatus)
    //{
    //    if (ViewState["Employees"] != null)
    //        ds = (DataSet)ViewState["Employees"];
    //    else
    //        ds = objEmployee.Search_EmployeeDetailsbyName("", "", Convert.ToString(Session["UserGroupName"]), Convert.ToString(Session["LevelRights"]), Convert.ToString(Session["GradeLevel"]), "0", "0", 0, 0, Convert.ToBoolean(Session["ApplnMode"]), 0, 0, 0, "Both", Convert.ToInt32(Session["EmpAutoID"]), (Request.QueryString["ScheduleId"] != null) ? Convert.ToInt32(Request.QueryString["ScheduleId"]) : 0, 0, 0, 0, 0, 0,0);
    //    foreach (DataRow dr in ds.Tables[0].Rows)
    //    {
    //        if (Convert.ToString(dr["EmailId"]) != "")
    //            dr["emailScheduler_flag"] = Convert.ToInt16(chkboxstatus);
    //    }
    //    ds.Tables[0].AcceptChanges();
    //    ViewState["Employees"] = ds;
    //    CheckBox deleteChkBxItem = new CheckBox();
    //    foreach (GridViewRow gr in grv_EmailEmpDetails.Rows)
    //    {
    //        deleteChkBxItem = (CheckBox)gr.Cells[0].FindControl("deletethis");
    //        Label lblEmailId = (Label)gr.Cells[3].FindControl("lblEmailId");
    //        if (lblEmailId != null)
    //        {
    //            if (lblEmailId.Text != "")
    //            {
    //                if (deleteChkBxItem != null)
    //                {
    //                    deleteChkBxItem.Checked = chkboxstatus;
    //                }
    //            }
    //        }
    //    }
    //}
    protected void grv_EmailEmpDetails_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            Label lblflag = (Label)e.Row.Cells[4].FindControl("lblflag");
            CheckBox chkboxdeletethis = (CheckBox)e.Row.Cells[0].FindControl("deletethis");
            Label lblEmailId = (Label)e.Row.Cells[3].FindControl("lblEmailId");
            if (lblEmailId != null)
            {
                if (lblEmailId.Text == "")
                {
                    if (chkboxdeletethis != null)
                    {
                        chkboxdeletethis.Enabled = false;
                    }
                }
            }
            if (lblflag != null)
            {
                if (lblflag.Text == "1")
                {
                    if (chkboxdeletethis != null)
                    {
                        chkboxdeletethis.Checked = true;
                    }
                }
                else
                {
                    if (chkboxdeletethis != null)
                    {
                        chkboxdeletethis.Checked = false;
                    }
                }
            }
        }
    }

    protected void grv_EmailEmpDetails_HtmlRowPrepared(object sender, DevExpress.Web.ASPxGridViewTableRowEventArgs e)
    {
        if (e.RowType == DevExpress.Web.GridViewRowType.Data)
        {
            source_Language = Convert.ToString(Session["Session_ActiveLanguage"]);
            rm = new ResourceManager(source_Language, System.Reflection.Assembly.Load("App_GlobalResources"));
            ci = Thread.CurrentThread.CurrentCulture;
            Label ReportName = (Label)grv_EmailEmpDetails.FindRowCellTemplateControl(e.VisibleIndex, null, "lblReportName");
            Label lblemailflag = (Label)grv_EmailEmpDetails.FindRowCellTemplateControl(e.VisibleIndex, null, "lblemailflag");
            LinkButton Preview = (LinkButton)grv_EmailEmpDetails.FindRowCellTemplateControl(e.VisibleIndex, null, "lbPreview");

            Label lblStatus = (Label)grv_EmailEmpDetails.FindRowCellTemplateControl(e.VisibleIndex, null, "lblStatus");

            HtmlInputCheckBox checkBox = (HtmlInputCheckBox)grv_EmailEmpDetails.FindRowCellTemplateControl(e.VisibleIndex, null, "chkSelect");

            // Access the hidden field value (emailScheduler_flag)
            //string emailSchedulerFlag = DataBinder.Eval(e.DataItem, "emailScheduler_flag").ToString();

            //// Update the checkbox based on the hidden field value
            //if (emailSchedulerFlag == "1")
            //{
            //    checkBox.Checked = true;
            //}
            //else
            //{
            //    checkBox.Checked = false;
            //}

        }
    }
    //private void Page_init()
    //{
    //    if (hdnSelectRow.Value != "")
    //    {
    //        DataSet dsvalue = (DataSet)ViewState["Employees"];
    //        string[] valuesArray = hdnSelectRow.Value.Split(',');

    //        foreach (var n in valuesArray)
    //        {
    //            foreach (DataRow dr in dsvalue.Tables[0].Rows)
    //            {
    //                if (Convert.ToString(dr["Employee_Code_Id"]) == n)
    //                {
    //                    dr["emailScheduler_flag"] = 1;
    //                }
    //            }
    //        }
    //        ViewState["Employees"] = dsvalue;
    //    }
    //    shiftDataBind();
    //}

    protected void grv_EmailEmpDetails_PageIndexChanged(object sender, EventArgs e)
    {
        shiftDataBind();
    }

}
