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;
/****************************************************************************************************************************
* 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;
        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();";
        strSetAlert = strSetAlert + "</script>";
        Page.RegisterStartupScript("MaxLengthh", 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.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"]) == "True")
                    {
                        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]["TimeToSend"]) != "")
                            txtTimeToSend.Text = Convert.ToString(dsEmailSchedule.Tables[0].Rows[0]["TimeToSend"]);
                        rbtnOthers.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();
        return;
    }
    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
                list.Text = Convert.ToString(rm.GetString(list.Text));
        }
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        string strInvalidEmailIdInTo = string.Empty;
        string strInvalidEmailIdInCC = string.Empty;
        string Frequency = "Daily";
        char[] Delimit = { ';' };
        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)
        {
            towhom = 1;
            if (ViewState["Employees"] != null)
            {
                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"]);
        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);
            if (InsertedId == 0)
            {
                Message(rm.GetString("Alert_ScheduleNamealreadyexists", ci));
                return;
            }
            objEmailConfiguration.InsertUpdateEmailTemplate(InsertedId, txtSubject.Text, editor.Text, "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);
            if (InsertedId == 0)
            {
                Message(rm.GetString("Alert_ScheduleNamealreadyexists", ci));
                return;
            }
            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)
        {
            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
                {
                    Session["hdnReportFilters"] = string.Empty;
                    Session["EMailParentId"] = string.Empty;
                    Session["ReportTypeID"] = string.Empty;
                    Session["LateReportName"] = string.Empty;
                    ViewState["Report"] = ddlReportName.SelectedValue;
                }
            }
            else
            {
                ViewState["Report"] = ddlReportName.SelectedValue;
                Session["hdnReportFilters"] = string.Empty;
                Session["EMailParentId"] = string.Empty;
                Session["ReportTypeID"] = string.Empty;
            }
            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;
        }
    }
    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)
        {
            shiftDataBind();
            divTowhom.Style.Add("display", "");
            divTimeOption.Style.Add("display", "");
        }
        else
        {
            divTowhom.Style.Add("display", "");
            divTimeOption.Style.Add("display", "none");
            ViewState["Employees"] = null;
            grv_EmpDetails.DataSource = null;
            grv_EmpDetails.DataBind();
            grv_EmpDetails.EnableViewState = false;
            ddlTimeOption.SelectedIndex = -1;
        }
        //}
        //else
        //{
        //    ViewState["Employees"] = null;
        //    grv_EmpDetails.DataSource = null;
        //    grv_EmpDetails.DataBind();
        //    grv_EmpDetails.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_EmpDetails_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        grv_EmpDetails.EnableViewState = true;
        grv_EmpDetails.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_EmpDetails.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_EmpDetails.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, 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;
        }
        else
        {
            ds = (DataSet)ViewState["Employees"];
        }
        grv_EmpDetails.DataSource = ds.Tables[0].DefaultView;
        grv_EmpDetails.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);
        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_EmpDetails.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_EmpDetails_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;
                    }
                }
            }
        }
    }
}
