using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Resources;
using System.Globalization;
using System.Threading;
using System.Net.Mail;
using System.Net;
using DevExpress.Web;
using System.Text;
/*
 * Modified By      :   Manjula.P
 * Modified On      :   28-Sep-2013
 * Descriptinos     :   Commented and added for passing ParentId insetead of levelid Mantis : 0019145
 * */
public partial class Transactions_TA_UI_Transactions_PermissionBulkSanction_Angler : Base.BasePage
{
    #region Variable Declaration
    ResourceManager rm;
    CultureInfo ci;
    Cls_CheckUser objCheckUser = new Cls_CheckUser();
    DataSet ds_Checkuser = new DataSet();
    LeaveEventData objLeave = new LeaveEventData();
    PermissionEventData_Angler objPermissionEventData = new PermissionEventData_Angler();
    LeaveApplicationEventData_Angler objLeaveApplicationEventData = new LeaveApplicationEventData_Angler();
    YearSettingsEventData objYearSettingsEventData = new YearSettingsEventData();
    cls_Common objcls_Common = new cls_Common();
    Rpt_Common rptcommon = new Rpt_Common();
    DataTable dtPermissionSanctionView = new DataTable();
    DataSet dsYearSetting = new DataSet();
    DataTable dtSanctionView = new DataTable();
    int vmonthValue;
    string startDate;
    string endDate, gstrDateFormat, LevelId = "", NewStatus, Status, StartMonth, EndMonth, StartYear, EndYear, From_Date, To_Date;
    string strSwipeCardNo = string.Empty;
    string strEmployeeName = string.Empty;
    string strEmployeeCodeId = string.Empty;
    string SelectedShift = string.Empty;
    bool checkEmail = true;
    string LastName = ""; string lblPermissionDate; string lblPermissionFromTime; string lblPermissionToTime;
    cls_Common objClassCommon = new cls_Common();
    DataSet ds_EmailIdOfSanctionAuthority = new DataSet();
    DataSet dsEmailIdOfReportingTo = new DataSet();
    DataSet dsRecordsCount = new DataSet();
    int Permission_Id, Employee_Id;
    string Remarks, EmployeeEamilId, strEmailIdSanctionAuthority, EmployeeName, Employee_Code_Id, strlevelName, gstrTimeFormat;
    string NotSendedEmployeeCodeId = "";
    string source_Language;
    string[] chkBoxIDs;
    DataSet ds_ReportingToSanctionAuthorityList = new DataSet();
    //Added by Manjula.P on 25-Apr-2014
    int gintCompanyId;
    string reportingToEmployee, sanctioningEmployee, strEmailIdReportingTo;
    string strHtml = string.Empty;
    CCGroupEventData_Angler objCCGroup = new CCGroupEventData_Angler();
    #endregion
    #region PageLoad
    protected override void Page_Load(object sender, EventArgs e)
    {
        // session checking
        base.Page_Load(sender, e);
        source_Language = Convert.ToString(Session["Session_ActiveLanguage"]);
        rm = new ResourceManager(source_Language, System.Reflection.Assembly.Load("App_GlobalResources"));
        ci = Thread.CurrentThread.CurrentCulture;
        LoadStrings(ci);
        string Level = "";
        //Set UserRights
        UserRights();
        if (Convert.ToString(Session["LevelId"]) == string.Empty)
        {
            LevelId = Request.QueryString["LevelId"].ToString();
            Level = rptcommon.getNodes(Convert.ToInt16(LevelId), Convert.ToString(Session["LevelRights"]));
            LevelId = rptcommon.getNodes(Convert.ToInt16(LevelId), Convert.ToString(Session["LevelRights"]));
            Session["Level"] = Level;
            Session["LevelId"] = LevelId;
        }
        else
        {
            Level = Convert.ToString(Session["Level"]);
            LevelId = Convert.ToString(Session["LevelId"]);
        }
        if (Convert.ToString(Session["PermissionSanctionStatus"]) == string.Empty)
        {
            Status = Convert.ToString(Request.QueryString["Status"]);
            Session["PermissionSanctionStatus"] = Status;
        }
        else
        {
            Status = Convert.ToString(Session["PermissionSanctionStatus"]);
        }
        if (Convert.ToString(Session["strSwipeCardNo"]) == string.Empty)
        {
            if (Request.QueryString["strSwipeCardNo"] != null)
            {
                strSwipeCardNo = Convert.ToString(Request.QueryString["strSwipeCardNo"]);
            }
            else
            {
                strSwipeCardNo = "";
            }
            Session["strSwipeCardNo"] = strSwipeCardNo;
        }
        else
        {
            strSwipeCardNo = Convert.ToString(Session["strSwipeCardNo"]);
        }
        if (Convert.ToString(Session["strEmployeeName"]) == string.Empty)
        {
            if (Request.QueryString["strEmployeeName"] != null)
            {
                strEmployeeName = Convert.ToString(Request.QueryString["strEmployeeName"]);
            }
            else
            {
                strEmployeeName = "";
            }
            Session["strEmployeeName"] = strEmployeeName;
        }
        else
        {
            strEmployeeName = Convert.ToString(Session["strEmployeeName"]);
        }
        if (Convert.ToString(Session["strEmployeeCodeId"]) == string.Empty)
        {
            if (Request.QueryString["strEmployeeName"] != null)
            {
                strEmployeeCodeId = Convert.ToString(Request.QueryString["strEmployeeCodeId"]);
            }
            else
            {
                strEmployeeCodeId = "";
            }
            Session["strEmployeeCodeId"] = strEmployeeCodeId;
        }
        else
        {
            strEmployeeCodeId = Convert.ToString(Session["strEmployeeCodeId"]);
        }
        gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
        if (Request.QueryString["From_Date"] != null)
        {
            From_Date = Convert.ToString(Request.QueryString["From_Date"]);
            Session["PermissionFrom_Date"] = From_Date;
        }
        else
        {
            From_Date = "";
        }
        if (Convert.ToString(Session["PermissionFrom_Date"]) == null)
        {
        }
        else
        {
            From_Date = Convert.ToString(Session["PermissionFrom_Date"]);
        }
        if (Request.QueryString["To_Date"] != null)
        {
            To_Date = Convert.ToString(Request.QueryString["To_Date"]);
            Session["PermissionTo_Date"] = To_Date;
        }
        else
        {
            To_Date = "";
        }
        if (Convert.ToString(Session["PermissionTo_Date"]) == null)
        {
        }
        else
        {
            To_Date = Convert.ToString(Session["PermissionTo_Date"]);
        }
        if (Request.QueryString["isDashBoard"] != null && Convert.ToString(Request.QueryString["isDashBoard"]) == "Yes")
        {
            From_Date = Request.QueryString["From_Date"].ToString();
            To_Date = Request.QueryString["To_Date"].ToString();
        }
        if (Request.QueryString["Shift"] != null)
        {
            SelectedShift = Convert.ToString(Request.QueryString["Shift"]);
        }
        if (From_Date != "")
        {
            From_Date = objcls_Common.DateConvertion(gstrDateFormat, From_Date);
        }
        if (To_Date != "")
        {
            To_Date = objcls_Common.DateConvertion(gstrDateFormat, To_Date);
        }
        dsYearSetting = objYearSettingsEventData.GetActiveYearSettings();
        if (dsYearSetting.Tables[0].Rows.Count <= 0)
        {
            return;
        }
        else
        {
            StartMonth = Convert.ToString(dsYearSetting.Tables[0].Rows[0]["StartMonth"]);
            StartYear = Convert.ToString(dsYearSetting.Tables[0].Rows[0]["StartYear"]);
            vmonthValue = MonthValue(StartMonth);
            startDate = vmonthValue.ToString() + "/1/" + StartYear;
            EndMonth = Convert.ToString(dsYearSetting.Tables[0].Rows[0]["EndMonth"]);
            EndYear = Convert.ToString(dsYearSetting.Tables[0].Rows[0]["EndYear"]);
            vmonthValue = MonthValue(EndMonth);
            endDate = vmonthValue.ToString() + "/31/" + EndYear;
        }
        if (Convert.ToString(Session["isDashBoard"]) != "Yes")
        {
            if (LevelId == "0")
            {
                LevelId = null;
            }
        }
        if (Status == "-Select Status-")
        {
            Status = null;
        }
        else if (Status == "All")
        {
            Status = null;
        }
        if (From_Date == "")
        {
            From_Date = startDate;
        }
        if (To_Date == "")
        {
            To_Date = endDate;
        }
        if (!IsPostBack)
        {
            objClassCommon.menu("PermissionTransaction", "261");
            Session["PermissionChecked"] = null;
        }
        ///Added by Manjula.P on 25-Apr-2014 when the status is in forwarded.
        if (Status == "Forwarded")
        {
            btnForward.Enabled = false;
        }
        bindpermissionsanctiondetails();
        //Added by Manjula.P on 25-Apr-2014 for user rights for Forward and Approve buttons visibling
        if (!IsPostBack)
        {
            dvRemarks.Visible = false;
            divMandatory.Visible = false;
            btnForward.Visible = false;
            btnApprove.Visible = false;
            int EmpID = Convert.ToInt32(Session["EmpAutoID"].ToString());
            DataSet ds = new DataSet();
            DataSet ds1 = new DataSet();
            //if the user login is sanctiona authority then approve button visibleing
            ds = objPermissionEventData.CheckSanctioningPerson(EmpID);
            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                if (ds.Tables[0].Rows[0][0] != DBNull.Value && Convert.ToInt16(ds.Tables[0].Rows[0][0]) > 0)
                {
                    btnApprove.Visible = true;
                    dvRemarks.Visible = true;
                    divMandatory.Visible = true;
                }
                else
                {
                    btnApprove.Visible = false;
                    //if the user login is forward authority then forward button visible.
                    ds1 = objPermissionEventData.CheckReportingPerson(EmpID);
                    if (ds1.Tables[0].Rows[0][0] != DBNull.Value && Convert.ToInt16(ds1.Tables[0].Rows[0][0]) > 0 && Request.QueryString["Status"].ToString() != "Forwarded")
                    {
                        btnForward.Visible = true;
                        dvRemarks.Visible = true;
                        divMandatory.Visible = true;
                    }
                    else
                    {
                        btnForward.Visible = false;
                        gdPermissionSanctionView.Columns[0].Visible = false;
                    }
                }
            }
            if (gdPermissionSanctionView.VisibleRowCount == 0)
            {
                dvRemarks.Visible = false;
                divMandatory.Visible = false;
                btnForward.Visible = false;
                btnApprove.Visible = false;
                gdPermissionSanctionView.Columns[0].Visible = false;
            }
            if (Request.QueryString["Status"].ToString() == "All" || Request.QueryString["Status"].ToString() == "Approved" || Request.QueryString["Status"].ToString() == "Rejected" || Request.QueryString["Status"].ToString() == "Resend" || Request.QueryString["Status"].ToString() == "Reply")
            {
                dvRemarks.Visible = false;
                divMandatory.Visible = false;
                btnForward.Visible = false;
                btnApprove.Visible = false;
                gdPermissionSanctionView.Columns[0].Visible = false;
            }
            if (Request.QueryString["Status"].ToString() != "Pending" && Request.QueryString["Status"].ToString() != "Forwarded")
            {
                dvRemarks.Visible = false;
                divMandatory.Visible = false;
                btnForward.Visible = false;
                btnApprove.Visible = false;
                gdPermissionSanctionView.Columns[0].Visible = false;
            }
        }
    }
    #endregion
    #region  Gridview
    protected void gdPermissionSanctionView_PageIndexChanged(object sender, EventArgs e)
    {
        try
        {
            if ((ViewState["SortExpression"]) != null)
            {
                string SortColumn = Convert.ToString(ViewState["SortExpression"]);
                string SortOrder = Convert.ToString(Session["SortOrder"]);
                SortGrid(SortColumn, SortOrder);
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    protected void gdPermissionSanctionView_Sorting(object sender, GridViewSortEventArgs e)
    {
        ViewState["SortExpression"] = e.SortExpression;
        if (Convert.ToString(Session["SortOrder"]) == string.Empty)
        {
            Session["SortOrder"] = "Asc";
        }
        else if (Convert.ToString(Session["SortOrder"]) == "Asc")
        {
            Session["SortOrder"] = "Desc";
        }
        else
        {
            Session["SortOrder"] = "Asc";
        }
        SortGrid(e.SortExpression, Convert.ToString(Session["SortOrder"]));
    }
    protected void gdPermissionSanctionView_HtmlRowCreated(object sender, DevExpress.Web.ASPxGridViewTableRowEventArgs e)
    {
        if (e.RowType == GridViewRowType.Data)
        {
            source_Language = Convert.ToString(Session["Session_ActiveLanguage"]);
            rm = new ResourceManager(source_Language, System.Reflection.Assembly.Load("App_GlobalResources"));
            ci = Thread.CurrentThread.CurrentCulture;
            string Label1 = (string)e.GetValue("Permission_AppliedDate");
            string Lbl_FromTime = e.GetValue("Permission_FromTime").ToString();
            string Lbl_EndTime = e.GetValue("Permission_ToTime").ToString();
            string TEndTime;
            TEndTime = DateTime.Parse(Lbl_EndTime).ToString(Session["MTimeFormat"].ToString());
            string TFromTime;
            TFromTime = DateTime.Parse(Lbl_FromTime).ToString(Session["MDateFormat"].ToString()) + "&nbsp;" + DateTime.Parse(Lbl_FromTime).ToString(Session["MTimeFormat"].ToString());
            //e.Row.Cells[3].Text = TFromTime + " To " + TEndTime;
            Label lblStatus = (Label)gdPermissionSanctionView.FindRowCellTemplateControl(e.VisibleIndex, null, "lblPermissionStatus");
            if (lblStatus.Text == "Approved")
            {
                lblStatus.Text = rm.GetString("btn_Approved", ci);
            }
            else if (lblStatus.Text == "Forwarded")
            {
                lblStatus.Text = rm.GetString("btn_Forwarded", ci);
            }
            else if (lblStatus.Text == "Pending")
            {
                lblStatus.Text = rm.GetString("btn_Pending", ci);
            }
            else if (lblStatus.Text == "Rejected")
            {
                lblStatus.Text = rm.GetString("btn_Reject", ci);
            }
            //Added by Manjula.P on 25-Apr-2014
            HtmlInputCheckBox cbDeleteThis = (HtmlInputCheckBox)gdPermissionSanctionView.FindRowCellTemplateControl(e.VisibleIndex, null, "chkSelect");
            if (cbDeleteThis != null)
            {
                e.Row.Cells[4].Text = TFromTime + " To " + TEndTime;
            }
            else
            {
                e.Row.Cells[3].Text = TFromTime + " To " + TEndTime;
            }
        }
    }
    #endregion
    #region UserDefinedFunction
    /// <summary>
    /// Clear all session Values
    /// </summary>
    public void clearAllSession()
    {
        Session["LevelId"] = string.Empty;
        //Session["LeaveSanctionStatus"] = string.Empty;
        Session["PermissionSanctionStatus"] = string.Empty;
        Session["strSwipeCardNo"] = string.Empty;
        Session["strEmployeeName"] = string.Empty;
        Session["strEmployeeCodeId"] = string.Empty;
        Session["PermissionFrom_Date"] = string.Empty;
        Session["PermissionTo_Date"] = string.Empty;
    }
    // Getting Information from resource file and display it in label
    private void LoadStrings(CultureInfo ci)
    {
        lbl_HeaderPermissionSanction.Text = rm.GetString("Transaction_PermissionSanction_PermissionSanction", ci);
        btnBack.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Back", ci);
        gdPermissionSanctionView.Columns[1].Caption = rm.GetString("email_EmployeeName", ci);
        gdPermissionSanctionView.Columns[2].Caption = rm.GetString("LevelDetails_LevelName", ci);
        gdPermissionSanctionView.Columns[3].Caption = rm.GetString("LeaveApplication_LeaveApplicationDate", ci);
        gdPermissionSanctionView.Columns[4].Caption = rm.GetString("Report_Duration", ci);
        gdPermissionSanctionView.Columns[5].Caption = rm.GetString("email_Status", ci);
        gdPermissionSanctionView.Columns[6].Caption = rm.GetString("email_Reason", ci);
        //btnSave.Text = rm.GetString("btn_Save", ci);
        btnForward.Text = "&nbsp;&nbsp;" + rm.GetString("Sanction_Forward", ci);
        btnApprove.Text = "&nbsp;&nbsp;" + rm.GetString("Sanction_Approve", ci);
    }
    public void SortGrid(string SortColumn, string SortOrder)
    {
        DataTable dtSrch = new DataTable();
        DataView dvSearch = new DataView();
        dtSrch = (DataTable)ViewState["DataPermissionSanction"];
        dvSearch.Table = dtSrch;
        dvSearch.Sort = SortColumn + " " + SortOrder;
        gdPermissionSanctionView.DataSource = dvSearch;
        gdPermissionSanctionView.DataBind();
    }
    public int MonthValue(string monthName)
    {
        if (monthName == "January")
            return 1;
        else if (monthName == "February")
            return 2;
        else if (monthName == "March")
            return 3;
        else if (monthName == "April")
            return 4;
        else if (monthName == "May")
            return 5;
        else if (monthName == "June")
            return 6;
        else if (monthName == "July")
            return 7;
        else if (monthName == "August")
            return 8;
        else if (monthName == "September")
            return 9;
        else if (monthName == "October")
            return 10;
        else if (monthName == "November")
            return 11;
        else if (monthName == "December")
            return 12;
        else
            return 0;
    }
    private void UserRights()
    {
        ds_Checkuser = objCheckUser.checkRights(261, Convert.ToInt32(Session["userGroup_Id"]), "viewPrv");
        if (ds_Checkuser.Tables[0].Rows.Count == 0)
        {
            Response.Redirect("TransactionLandingPage.aspx");
        }
        else
        {
            //   
        }
    }
    public void bindpermissionsanctiondetails()
    {
        if (Convert.ToString(Session["UserGroupName"]) == "SuperAdmin" || Convert.ToString(Session["HasSpecialRights"]) == "True")
        {
            dtPermissionSanctionView = objPermissionEventData.GetPermissionSanctionDetailsForSuperAdmin(LevelId, Status, Convert.ToDateTime(From_Date), Convert.ToDateTime(To_Date), strSwipeCardNo, strEmployeeName, strEmployeeCodeId, Convert.ToString(Session["UserGroupName"]), Convert.ToInt16(Session["parentLevelId"]));
            gdPermissionSanctionView.DataSource = dtPermissionSanctionView;
            ViewState["DataPermissionSanction"] = dtPermissionSanctionView;
            Session["TotalPermissionID"] = dtPermissionSanctionView.Rows.Count;
            gdPermissionSanctionView.DataBind();
        }
        else
        {
            dtPermissionSanctionView = objPermissionEventData.GetPermissionSanctionDetails(Convert.ToInt32(Session["EmpAutoId"]), LevelId, Status, Convert.ToDateTime(From_Date), Convert.ToDateTime(To_Date), strSwipeCardNo, strEmployeeName, strEmployeeCodeId, Convert.ToString(Session["UserGroupName"]), Convert.ToInt32(Session["parentLevelId"]));
            gdPermissionSanctionView.DataSource = dtPermissionSanctionView;
            ViewState["DataPermissionSanction"] = dtPermissionSanctionView;
            Session["TotalPermissionID"] = dtPermissionSanctionView.Rows.Count;
            gdPermissionSanctionView.DataBind();
        }
        //txtRemarks.Text = "OK";
    }
    public string CalculateNumberOfHoursApplied(string startTime, string EndTime)
    {
        TimeSpan tsDiff = new TimeSpan();
        //Converting datetime for string recognize error by Manjula.P on 13-May-2014
        startTime = objClassCommon.DateConvertion(gstrDateFormat, startTime);
        EndTime = objClassCommon.DateConvertion(gstrDateFormat, EndTime);
        //************************************
        DateTime dtmIn = DateTime.Parse(startTime);
        DateTime dtmOut = DateTime.Parse(EndTime);
        tsDiff = dtmOut.Subtract(dtmIn);
        string s = tsDiff.ToString();
        int sReturn = s.LastIndexOf(':');
        string RemainHours = s.Remove(sReturn);
        return (RemainHours);
    }
    #region control creation
    private void ControlCreation(int iPermissionID, string lbl_EmployeeName)
    {
        //New Data table definition
        DataTable dtReplyResend = new DataTable();
        dtReplyResend.TableName = "dtReplyResend";
        DataColumn dcDate = new DataColumn("Date");
        DataColumn dcCommentsBy = new DataColumn("Comments By");
        DataColumn dcComments = new DataColumn("Comments");
        dtReplyResend.Columns.Add(dcDate);
        dtReplyResend.Columns.Add(dcCommentsBy);
        dtReplyResend.Columns.Add(dcComments);
        DataRow dRowReplyResend;
        DataSet ds_PermissionConversation = new DataSet();
        ds_PermissionConversation = objPermissionEventData.GetPermissionConversation(iPermissionID);
        //if (!IsPostBack)
        //{
        //    // getting leave conversation 
        //    ViewState["PermissionConversation"] = ds_PermissionConversation;
        //}
        if (ds_PermissionConversation != null && ds_PermissionConversation.Tables[0].Rows.Count > 0)
        {
            //if (ViewState["PermissionConversation"] != null)
            //{
            //    ds_PermissionConversation =(DataSet) ViewState["PermissionConversation"];
            //}
            Table leaveConversation = new Table();
            leaveConversation.BorderWidth = 1;
            leaveConversation.CellPadding = 5;
            leaveConversation.CellSpacing = 0;
            leaveConversation.Width = Unit.Pixel(600);
            leaveConversation.CssClass = "td";
            leaveConversation.Attributes.Add("border", "1");
            TableHeaderRow leaveConversationHr = new TableHeaderRow();
            TableHeaderCell leaveConversationHeading3 = new TableHeaderCell();
            leaveConversationHeading3.Text = rm.GetString("TerminalDataType_Date_And_Time", ci);
            leaveConversationHeading3.HorizontalAlign = HorizontalAlign.Left;
            leaveConversationHr.Cells.Add(leaveConversationHeading3);
            TableHeaderCell leaveConversationHeading1 = new TableHeaderCell();
            //leaveConversationHeading1.Width = 75;
            leaveConversationHeading1.Text = rm.GetString("leaveConversationHeading1", ci);
            leaveConversationHeading1.HorizontalAlign = HorizontalAlign.Left;
            leaveConversationHr.Cells.Add(leaveConversationHeading1);
            TableHeaderCell leaveConversationHeading2 = new TableHeaderCell();
            leaveConversationHeading2.Text = rm.GetString("leaveConversationHeading2", ci);
            //leaveConversationHeading2.Width = 200;
            leaveConversationHeading2.HorizontalAlign = HorizontalAlign.Left;
            leaveConversationHr.Cells.Add(leaveConversationHeading2);
            leaveConversation.Rows.Add(leaveConversationHr);
            if (ds_PermissionConversation.Tables[0].Rows.Count > 0)
            {
                int rowIndex = 0;
                foreach (DataRow drLeaveConversation in ds_PermissionConversation.Tables[0].Rows)
                {
                    dRowReplyResend = dtReplyResend.NewRow();
                    TableRow trLeaveConversation = new TableRow();
                    TableCell tcLeaveConversationRepliedOn = new TableCell();
                    Label lblLeaveConversationRepliedOn = new Label();
                    tcLeaveConversationRepliedOn.BorderWidth = 1;
                    tcLeaveConversationRepliedOn.Width = 120;
                    lblLeaveConversationRepliedOn.ID = "lblLeaveConversationRepliedOn" + rowIndex;
                    lblLeaveConversationRepliedOn.Text = Convert.ToDateTime(drLeaveConversation["TimeStamp"]).ToString(Session["MDateFormat"].ToString()) + " " + Convert.ToDateTime(drLeaveConversation["TimeStamp"]).ToString(Session["MTimeFormat"].ToString());
                    dRowReplyResend["Date"] = Convert.ToDateTime(drLeaveConversation["TimeStamp"]).ToString(Session["MDateFormat"].ToString()) + " " + Convert.ToDateTime(drLeaveConversation["TimeStamp"]).ToString(Session["MTimeFormat"].ToString());
                    tcLeaveConversationRepliedOn.Controls.Add(lblLeaveConversationRepliedOn);
                    trLeaveConversation.Cells.Add(tcLeaveConversationRepliedOn);
                    TableCell tcLeaveConversationCommentsBy = new TableCell();
                    Label lblLeaveConversationCommentsBy = new Label();
                    tcLeaveConversationCommentsBy.Width = 120;
                    lblLeaveConversationCommentsBy.ID = "lblLeaveConversationCommentsBy" + rowIndex;
                    if (drLeaveConversation["CommentsBy"].ToString() == "0")
                    {
                        lblLeaveConversationCommentsBy.Text = lbl_EmployeeName;
                        dRowReplyResend["Comments By"] = lbl_EmployeeName;
                    }
                    else if (drLeaveConversation["CommentsBy"].ToString() == "1")
                    {
                        lblLeaveConversationCommentsBy.Text = (string)ViewState["reportingToEmployee"];
                        dRowReplyResend["Comments By"] = ViewState["reportingToEmployee"].ToString();
                    }
                    else if (drLeaveConversation["CommentsBy"].ToString() == "2")
                    {
                        lblLeaveConversationCommentsBy.Text = (string)ViewState["sanctioningEmployee"];
                        dRowReplyResend["Comments By"] = ViewState["sanctioningEmployee"].ToString();
                    }
                    else if (drLeaveConversation["CommentsBy"].ToString() == "3")
                    {
                        lblLeaveConversationCommentsBy.Text = objLeaveApplicationEventData.GetEmployeeName(Convert.ToInt32(drLeaveConversation["Emp_Id"].ToString()));
                        dRowReplyResend["Comments By"] = objLeaveApplicationEventData.GetEmployeeName(Convert.ToInt32(drLeaveConversation["Emp_Id"].ToString()));
                    }
                    tcLeaveConversationCommentsBy.Controls.Add(lblLeaveConversationCommentsBy);
                    trLeaveConversation.Cells.Add(tcLeaveConversationCommentsBy);
                    TableCell tcLeaveConversationComments = new TableCell();
                    Label lblLeaveConversationComments = new Label();
                    lblLeaveConversationComments.ID = "lblLeaveConversationComments" + rowIndex;
                    lblLeaveConversationComments.Text = drLeaveConversation["Comments"].ToString();
                    dRowReplyResend["Comments"] = drLeaveConversation["Comments"].ToString();
                    tcLeaveConversationComments.Controls.Add(lblLeaveConversationComments);
                    trLeaveConversation.Cells.Add(tcLeaveConversationComments);
                    leaveConversation.Rows.Add(trLeaveConversation);
                    rowIndex += 1;
                    dtReplyResend.Rows.Add(dRowReplyResend);
                }
            }
            //divLeaveConversation.Controls.Add(leaveConversation);
        }
        if (ds_PermissionConversation.Tables[0].Rows.Count > 0)
        {
            strHtml = buildPage("Test", dtReplyResend);
        }
    }
    #endregion
    #region build page
    public string buildPage(string strPageTitle, DataTable myDT)
    {
        StringBuilder sb = new StringBuilder();
        //HTML header
        sb.Append("<html>");
        sb.Append("<head>");
        sb.Append("<title>");
        sb.Append(strPageTitle);
        sb.Append("</title>");
        sb.Append("<style type='text/css'>");
        sb.Append(".Header {color: #FFFFFF; font-family: Arial;font-size: x-small;font-weight: bold;}");
        sb.Append(".rows {font-family: Arial; font-size: x-small;background-color:#FFE3B9}");
        sb.Append(".rowsNew {font-family: Arial; font-size: x-small;background-color:#FFEED5}");
        sb.Append("</style>");
        sb.Append("</head>");
        sb.Append("<body>");
        sb.Append("<table border='1' cellpadding='2' style='border-collapse: collapse' bordercolor='#666666' width='700'>");
        sb.Append("  <tr bgcolor='#003466'>");
        //Table header       
        foreach (DataColumn Col in myDT.Columns)
        {
            sb.Append("<td><span class='Header'>" + Col.ColumnName.ToString() + "</span></td>");
        }
        sb.Append("  </tr>");
        //add rows to the table for the length of the dataset
        int intWidth = 0;
        int intIncrement = 0;
        foreach (DataRow Row in myDT.Rows)
        {
            intWidth = 0;
            if (intIncrement % 2 == 0)
            {
                sb.Append("  <tr>");
            }
            else
            {
                sb.Append("  <tr>");
            }
            foreach (DataColumn Col in myDT.Columns)
            {
                if (intWidth == 2)
                {
                    sb.Append("<td width='60%'><font face='Arial' size='2'>" + Row[Col.ColumnName].ToString() + "</font></td>");
                    //intWidth = 1;
                }
                else
                {
                    sb.Append("<td><font face='Arial' size='2'>" + Row[Col.ColumnName].ToString() + "</font></td>");
                    //intWidth = 0;
                }
                intWidth = intWidth + 1;
            }
            sb.Append("  </tr>");
            intIncrement = intIncrement + 1;
        }
        //Close the html string
        sb.Append("</table>");
        sb.Append("</body>");
        sb.Append("</html>");
        return sb.ToString();
    }
    private string[] SplitCCTo(string CCTo)
    {
        string[] strArrEmailAddressForCC;
        strArrEmailAddressForCC = CCTo.Split(';');
        return (strArrEmailAddressForCC);
    }
    #endregion
    #region send mail
    private void SendMail(int FirstLevelAuthorityId, int SecondLevelAuthorityId, string strEmailIdReportingTo, string strEmailIdSanctionAuthority, string ApplicantEmailId, string Status, string EmployeeCodeId, string EmployeeName, string Remarks, string TotalHours, string levelName, string ApprovalCC, string lbl_EmployeeName, string lblPermissionDate, string lblPermissionFromTime, string lblPermissionToTime, string lblReason)
    {
        try
        {
            MailMessage mailMessage = new MailMessage();
            SmtpClient loSMTPServer = new SmtpClient();
            System.Net.Mime.ContentType loTextType = new System.Net.Mime.ContentType("text/plain");
            System.Net.Mime.ContentType loHTMLType = new System.Net.Mime.ContentType("text/html");
            AlternateView loTextView = null;
            AlternateView loHTMLView = null;
            string scriptText;
            DataTable dtTableScript = new DataTable();
            string ScriptType = "Forwarded Permission Application Sanction";
            //cl.fillDT("Select * from TA_TBL_EmailScripts where ScriptType='Forwarded Permission Application Sanction'", dtTableScript);
            dtTableScript = objLeaveApplicationEventData.GetEmailScripts(ScriptType);
            scriptText = dtTableScript.Rows[0]["ScriptText"].ToString();
            //mail.From = System.Configuration.ConfigurationManager.AppSettings["FromId"];
            //mail.To = EmailIdSanctionAuthority;
            //mail.Subject = Status + " Permission Application | " + lblPermissionDate.Text + " | " + EmployeeCodeId + " | " + EmployeeName + " - " + levelName;
            //mail.BodyFormat = MailFormat.Html;
            //mail.Priority = MailPriority.Normal;
            //if (ViewState["vsEmployeeEamilId"].ToString() != string.Empty)
            //{
            //    mailMessage.From = new MailAddress(ConfigurationManager.AppSettings.Get("FromId"));
            //}
            //else
            //{
            //    mailMessage.From = new MailAddress(ConfigurationManager.AppSettings.Get("FromId"));
            //}
            // Select the Recipient for To and CC based on the Approval Authority and Status
            int intLoginEmpId = 0;
            string strCCTo = string.Empty;
            // Get the Employee Auto Id who have Logged In from Session
            intLoginEmpId = Convert.ToInt32(Session["EmpAutoId"]);
            if (intLoginEmpId == SecondLevelAuthorityId)
            {
                if (Status == "Pending")
                {
                    mailMessage.From = new MailAddress(strEmailIdSanctionAuthority);
                    mailMessage.To.Add(new MailAddress(ApplicantEmailId));
                    //strCCTo = strEmailIdSanctionAuthority;
                    strCCTo = strEmailIdReportingTo;
                }
                else if (Status == "Rejected")
                {
                    mailMessage.From = new MailAddress(strEmailIdSanctionAuthority);
                    mailMessage.To.Add(new MailAddress(ApplicantEmailId));
                    //strCCTo = strEmailIdSanctionAuthority + ";" + strEmailIdReportingTo;
                    strCCTo = strEmailIdReportingTo;
                }
                else if (Status == "Approved")
                {
                    mailMessage.From = new MailAddress(strEmailIdSanctionAuthority);
                    mailMessage.To.Add(new MailAddress(ApplicantEmailId));
                    //strCCTo = strEmailIdSanctionAuthority + ";" + strEmailIdReportingTo;
                    strCCTo = strEmailIdReportingTo;
                }
                else if (Status == "Resend")
                {
                    mailMessage.From = new MailAddress(strEmailIdSanctionAuthority);
                    mailMessage.To.Add(new MailAddress(ApplicantEmailId));
                    //strCCTo = strEmailIdSanctionAuthority + ";" + strEmailIdReportingTo;
                    strCCTo = strEmailIdReportingTo;
                }
                else
                {
                    // Nothing
                }
            }
            else if (intLoginEmpId == FirstLevelAuthorityId)
            {
                if (Status == "Forwarded")
                {
                    mailMessage.From = new MailAddress(strEmailIdReportingTo);
                    mailMessage.To.Add(new MailAddress(strEmailIdSanctionAuthority));
                    strCCTo = ApplicantEmailId;
                }
                else if (Status == "Resend")
                {
                    mailMessage.From = new MailAddress(strEmailIdReportingTo);
                    mailMessage.To.Add(new MailAddress(ApplicantEmailId));
                    //strCCTo = strEmailIdSanctionAuthority + ";" + strEmailIdReportingTo;
                }
                else if (Status == "Rejected")
                {
                    mailMessage.From = new MailAddress(strEmailIdReportingTo);
                    mailMessage.To.Add(new MailAddress(ApplicantEmailId));
                    //strCCTo = strEmailIdSanctionAuthority + ";" + strEmailIdReportingTo;
                }
                else if (Status == "Approved")
                {
                    mailMessage.From = new MailAddress(strEmailIdReportingTo);
                    mailMessage.To.Add(new MailAddress(ApplicantEmailId));
                }
            }
            else
            {
                if (Status == "Pending" || Status == "Rejected")
                {
                    mailMessage.To.Add(new MailAddress(ApplicantEmailId));
                    strCCTo = strEmailIdReportingTo;
                }
                else if (Status == "Forwarded")
                {
                    mailMessage.To.Add(new MailAddress(strEmailIdSanctionAuthority));
                    strCCTo = strEmailIdReportingTo + ";" + ApplicantEmailId;
                }
                else if (Status == "Approved")
                {
                    mailMessage.To.Add(new MailAddress(ApplicantEmailId));
                    strCCTo = strEmailIdSanctionAuthority + ";" + strEmailIdReportingTo;
                }
                else if (Status == "Resend")
                {
                    mailMessage.To.Add(new MailAddress(ApplicantEmailId));
                    strCCTo = strEmailIdSanctionAuthority + ";" + strEmailIdReportingTo;
                }
                else
                {
                    // Nothing
                }
                if (Session["loginEmailId"].ToString() != string.Empty || Session["loginEmailId"] != null)
                {
                    mailMessage.From = new MailAddress(Session["loginEmailId"].ToString());
                }
                else
                {
                    mailMessage.From = new MailAddress(ConfigurationManager.AppSettings.Get("FromId"));
                }
            }
            if (Status == "Approved")
            {
                DataSet dsCCEmailIds = new DataSet();
                DataTable dtSanctionView = (DataTable)ViewState["dtSanctionView"];
                dsCCEmailIds = objCCGroup.GetCCEmailIds(Convert.ToInt16(dtSanctionView.Rows[0]["LevelId"].ToString()), Convert.ToInt16(dtSanctionView.Rows[0]["DesignationId"].ToString()), "O");
                if (dsCCEmailIds != null)
                {
                    if (dsCCEmailIds.Tables[0].Rows.Count > 0)
                    {
                        foreach (DataRow drCcEmailId in dsCCEmailIds.Tables[0].Rows)
                        {
                            MailAddressCollection MailAddrCollectionCC = mailMessage.CC;
                            // added by Gopinath.k for Mantis Bug no.24059 & 24098
                            if (drCcEmailId["EmailId"].ToString() != string.Empty)
                            {
                                MailAddress newCC = new MailAddress(drCcEmailId["EmailId"].ToString());
                                MailAddrCollectionCC.Add(newCC);
                            }
                        }
                    }
                }
            }
            if (strCCTo != string.Empty)
            {
                string[] strArrEmailAddressForCC;
                strArrEmailAddressForCC = SplitCCTo(strCCTo);
                MailAddressCollection MailAddrCollectionCC = mailMessage.CC;
                for (int iLoop = 0; iLoop < strArrEmailAddressForCC.Length; iLoop++)
                {
                    MailAddress newCC = new MailAddress(strArrEmailAddressForCC[iLoop]);
                    MailAddrCollectionCC.Add(newCC);
                }
            }
            //Send mails by selection Emails
            //string strToMails = txtApprovalTO.Text;
            string strCcMails = txtApprovalCC.Text;
            //CC Mails from text box
            if (strCcMails != string.Empty)
            {
                string[] strArrEmailAddressForCC;
                strArrEmailAddressForCC = SplitCCTo(strCcMails);
                MailAddressCollection MailAddrCollectionCC = mailMessage.CC;
                for (int iLoop = 0; iLoop < strArrEmailAddressForCC.Length; iLoop++)
                {
                    MailAddress newCC = new MailAddress(strArrEmailAddressForCC[iLoop]);
                    MailAddrCollectionCC.Add(newCC);
                }
            }
            //check for duplicate mail Ids
            //included by sashma on 20-Oct-2010
            Hashtable htToMails = new Hashtable();
            Hashtable htCCMails = new Hashtable();
            int intToMailCount = 0;
            int intCCMailCount = 0;
            //inserts the TO mailIds in the hashtable
            foreach (MailAddress ToMail in mailMessage.To)
            {
                if (htToMails.ContainsValue(ToMail) == false)
                {
                    htToMails.Add(intToMailCount++, ToMail);
                }
            }
            //inserts the CC mailIds in the hashtable
            foreach (MailAddress CCMail in mailMessage.CC)
            {
                //check whether the mail alredy exists in CC mails.
                if (htCCMails.ContainsValue(CCMail) == false)
                {
                    //check whether the mail alredy exists in TO mails.
                    if (htToMails.ContainsValue(CCMail) == false)
                    {
                        htCCMails.Add(intCCMailCount++, CCMail);
                    }
                }
            }
            mailMessage.To.Clear();
            mailMessage.CC.Clear();
            //Adds the TO mails from the hastable.
            foreach (DictionaryEntry ToMails in htToMails)
            {
                mailMessage.To.Add(ToMails.Value.ToString());
            }
            //Adds the CC mails from the hastable.
            foreach (DictionaryEntry CCMails in htCCMails)
            {
                mailMessage.CC.Add(CCMails.Value.ToString());
            }
            mailMessage.Subject = "TimeCheck : " + levelName + " | " + lbl_EmployeeName + " - " + EmployeeCodeId + " | Permission  | " + Status;
            //mailMessage.Subject = levelName + " | " + lbl_EmployeeName.Text + " - " + EmployeeCodeId + " | " + lblPermissionDate.Text + " | " + "Permission " + " | " + Status;
            mailMessage.Body = scriptText.Replace("<<lblPermissionSanction>>", rm.GetString("email_PermissionForm", ci));
            mailMessage.Body = mailMessage.Body.Replace("<<lblEmployeeId>>", rm.GetString("email_EmployeeId", ci));
            mailMessage.Body = mailMessage.Body.Replace("<<EmployeeId>>", EmployeeCodeId);
            mailMessage.Body = mailMessage.Body.Replace("<<lblEmployeeName>>", rm.GetString("email_EmployeeName", ci));
            mailMessage.Body = mailMessage.Body.Replace("<<EmployeeName>>", lbl_EmployeeName);
            mailMessage.Body = mailMessage.Body.Replace("<<lblDepartment>>", "Department");
            mailMessage.Body = mailMessage.Body.Replace("<<Department>>", levelName);
            mailMessage.Body = mailMessage.Body.Replace("<<lblPermissionDate>>", rm.GetString("Permission_PermissionDate", ci));
            mailMessage.Body = mailMessage.Body.Replace("<<PermissionDate>>", lblPermissionDate);
            mailMessage.Body = mailMessage.Body.Replace("<<lblNumberOfHoursApplied>>", rm.GetString("email_NumberOfHoursApplied", ci));
            mailMessage.Body = mailMessage.Body.Replace("<<NumberOfHoursApplied>>", TotalHours);
            mailMessage.Body = mailMessage.Body.Replace("<<lblPermission>>", rm.GetString("Dash_Permission", ci));
            mailMessage.Body = mailMessage.Body.Replace("<<lblFromTime>>", rm.GetString("email_FromDate", ci));
            mailMessage.Body = mailMessage.Body.Replace("<<FromTime>>", lblPermissionFromTime);
            mailMessage.Body = mailMessage.Body.Replace("<<lblToTime>>", rm.GetString("email_ToDate", ci));
            mailMessage.Body = mailMessage.Body.Replace("<<ToTime>>", lblPermissionToTime);
            mailMessage.Body = mailMessage.Body.Replace("<<lblStatus>>", rm.GetString("email_Status", ci));
            mailMessage.Body = mailMessage.Body.Replace("<<Status>>", Status);
            mailMessage.Body = mailMessage.Body.Replace("<<lblReason>>", rm.GetString("email_Reason", ci));
            mailMessage.Body = mailMessage.Body.Replace("<<Reason>>", lblReason);
            mailMessage.Body = mailMessage.Body.Replace("<<divMailThread>>", strHtml);
            string strServerIP = string.Empty;
            strServerIP = System.Configuration.ConfigurationManager.AppSettings["ServerIP"].ToString();
            if (Status == "Forwarded")
            {
                string LevelId = "1";
                //mailMessage.Body = mailMessage.Body.Replace("<<LinkData>>", strServerIP + "Index.aspx?Permission_Id=" + Convert.ToInt32(Request.QueryString["Permission_Id"]) + "&LevelId=" + LevelId + "&ApprovalType=Permission");
                mailMessage.Body = mailMessage.Body.Replace("<<LinkData>>", strServerIP + "Transactions/TA_UI_Transactions_PermissionSanctionModify_Angler.aspx?Permission_Id=" + Convert.ToInt32(ViewState["Permission_Id"]) + "&LevelId=" + LevelId + "&ApprovalType=Permission&Status=All&From_Date=&To_Date=&strSwipeCardNo=&strEmployeeName=&strEmployeeCodeId=&Angler=1");
            }
            else
            {
                string strReplaceText = "<font face=\"Arial\" size=\"2\"><a href=\"<<LinkData>>\">Click here for approval</a></font>";
                mailMessage.Body = mailMessage.Body.Replace(strReplaceText, string.Empty);
            }
            objClassCommon.SendMail(mailMessage);
        }
        catch
        {
            checkEmail = false;
        }
    }
    #endregion
    private void SendMailToApplicant(string EmployeeEamilId, string strEmailIdReportingTo, string strEmailIdSanctionAuthority, string Status, string Remarks, string EmployeeCodeId, string TotalHours, string levelName, string employeename)
    {
        MailMessage mailMessage = new MailMessage();
        SmtpClient loSMTPServer = new SmtpClient();
        System.Net.Mime.ContentType loTextType = new System.Net.Mime.ContentType("text/plain");
        System.Net.Mime.ContentType loHTMLType = new System.Net.Mime.ContentType("text/html");
        AlternateView loTextView = null;
        AlternateView loHTMLView = null;
        string scriptText;
        DataTable dtTableScript = new DataTable();
        string strFromEmailId = string.Empty;
        try
        {
            string ScriptType = "Permission Application Sanction By Reporting to Person";
            dtTableScript = objLeaveApplicationEventData.GetEmailScripts(ScriptType);
            scriptText = dtTableScript.Rows[0]["ScriptText"].ToString();
            if (Session["loginEmailId"] != null && Convert.ToString(Session["loginEmailId"]) != string.Empty)
            {
                mailMessage.From = new MailAddress(Session["loginEmailId"].ToString());
                strFromEmailId = Convert.ToString(Session["loginEmailId"]);
            }
            else
            {
                mailMessage.From = new MailAddress(ConfigurationManager.AppSettings.Get("FromId"));
                strFromEmailId = Convert.ToString(ConfigurationManager.AppSettings.Get("FromId"));
            }
            if (Status == "Forwarded")
            {
                if (strEmailIdSanctionAuthority != string.Empty)
                {
                    mailMessage.To.Add(new MailAddress(strEmailIdSanctionAuthority));
                }
                if (EmployeeEamilId != string.Empty)
                {
                    mailMessage.CC.Add(new MailAddress(EmployeeEamilId));
                }
            }
            if (Session["loginEmailId"] != null && Session["loginEmailId"].ToString() != string.Empty)
            {
                if (strEmailIdSanctionAuthority != strEmailIdReportingTo)
                {
                    if (Status != "Forwarded")
                    {
                        if (Session["loginEmailId"].ToString() == strEmailIdSanctionAuthority)
                        {
                            if (EmployeeEamilId != string.Empty)
                            {
                                mailMessage.To.Add(new MailAddress(EmployeeEamilId));
                            }
                            if (strEmailIdReportingTo != string.Empty)
                            {
                                mailMessage.CC.Add(new MailAddress(strEmailIdReportingTo));
                            }
                        }
                        if (Session["loginEmailId"].ToString() == strEmailIdReportingTo)
                        {
                            if (EmployeeEamilId != string.Empty)
                            {
                                mailMessage.To.Add(new MailAddress(EmployeeEamilId));
                            }
                        }
                    }
                }
                else
                {
                    if (Status != "Forwarded")
                    {
                        //EmployeeEamilId = "manikandan.rr@angleritech.com";
                        if (EmployeeEamilId != string.Empty)
                        {
                            mailMessage.To.Add(new MailAddress(EmployeeEamilId));
                        }
                    }
                }
            }
            else
            {
                if (Status != "Forwarded")
                {
                    //EmployeeEamilId = "manikandan.rr@angleritech.com";
                    if (EmployeeEamilId != string.Empty)
                    {
                        mailMessage.To.Add(new MailAddress(EmployeeEamilId));
                    }
                }
            }
            if (Status == "Approved")
            {
                Status = rm.GetString("btn_Approved", ci);
            }
            else if (Status == "Forwarded")
            {
                Status = rm.GetString("btn_Forwarded", ci);
            }
            else if (Status == "Pending")
            {
                Status = rm.GetString("btn_Pending", ci);
            }
            else if (Status == "Rejected")
            {
                Status = rm.GetString("btn_Reject", ci);
            }
            //mailMessage.To.Add(new MailAddress(EmployeeEamilId));
            //mailMessage.Subject = levelName + " | " + lbl_EmployeeName.Text + " - " + EmployeeCodeId + " | " + lblPermissionDate.Text + " | " + "Permission " + Status;
            mailMessage.Subject = rm.GetString("email_YourPermissionApplicationFor", ci) + " - " + lblPermissionDate + " | " + Status;
            mailMessage.Body = scriptText.Replace("<<lblPermissionSanction>>", rm.GetString("email_PermissionForm", ci));
            mailMessage.Body = mailMessage.Body.Replace("<<lblEmployeeId>>", rm.GetString("email_EmployeeId", ci));
            mailMessage.Body = mailMessage.Body.Replace("<<EmployeeId>>", EmployeeCodeId);
            mailMessage.Body = mailMessage.Body.Replace("<<lblEmployeeName>>", rm.GetString("email_EmployeeName", ci));
            mailMessage.Body = mailMessage.Body.Replace("<<EmployeeName>>", employeename);
            mailMessage.Body = mailMessage.Body.Replace("<<lblPermissionDate>>", rm.GetString("Permission_PermissionDate", ci));
            mailMessage.Body = mailMessage.Body.Replace("<<PermissionDate>>", lblPermissionDate);
            mailMessage.Body = mailMessage.Body.Replace("<<lblNumberOfHoursApplied>>", rm.GetString("email_NumberOfHoursApplied", ci));
            mailMessage.Body = mailMessage.Body.Replace("<<NumberOfHoursApplied>>", TotalHours);
            mailMessage.Body = mailMessage.Body.Replace("<<lblPermission>>", rm.GetString("Dash_Permission", ci));
            mailMessage.Body = mailMessage.Body.Replace("<<lblFromTime>>", rm.GetString("email_FromDate", ci));
            mailMessage.Body = mailMessage.Body.Replace("<<FromTime>>", lblPermissionFromTime);
            mailMessage.Body = mailMessage.Body.Replace("<<lblToTime>>", rm.GetString("email_ToDate", ci));
            mailMessage.Body = mailMessage.Body.Replace("<<ToTime>>", lblPermissionToTime);
            mailMessage.Body = mailMessage.Body.Replace("<<lblStatus>>", rm.GetString("email_Status", ci));
            mailMessage.Body = mailMessage.Body.Replace("<<Status>>", Status);
            mailMessage.Body = mailMessage.Body.Replace("<<lblReason>>", rm.GetString("email_Reason", ci));
            mailMessage.Body = mailMessage.Body.Replace("<<Reason>>", Remarks);
            mailMessage.Body = mailMessage.Body.Replace("<<lblRemarks>>", rm.GetString("email_Remarks", ci));
            mailMessage.Body = mailMessage.Body.Replace("<<Remarks>>", Remarks);
            objClassCommon.SendMail(mailMessage);
        }
        catch
        {
            //string strScript = string.Empty;
            //strScript = strScript + "<script language='javascript'>";
            //strScript = strScript + "alert('Permission Application saved,Email not sent');";
            //strScript = strScript + "location.replace('TA_UI_Transactions_PermissionSanction.aspx');";
            //strScript = strScript + "</script>";
            ////Dispaly alert messsage.
            //Page.RegisterStartupScript("AlertPAdd34", strScript);
            objLeaveApplicationEventData.InsertLeaveApplicationDetailsInEmailTrigger(Permission_Id, strFromEmailId, EmployeeEamilId, strEmailIdReportingTo, rm.GetString("email_YourPermissionApplicationFor", ci) + " - " + lblPermissionDate + " | " + Status, mailMessage.Body.ToString(), "", "PermissionSanction");
            checkEmail = false;
        }
    }
    private void SendMailToSanctionAuthority(string EmailIdSanctionAuthority, string Status, string EmployeeCodeId, string EmployeeName, string Remarks, string TotalHours, string levelName)
    {
        try
        {
            MailMessage mailMessage = new MailMessage();
            SmtpClient loSMTPServer = new SmtpClient();
            System.Net.Mime.ContentType loTextType = new System.Net.Mime.ContentType("text/plain");
            System.Net.Mime.ContentType loHTMLType = new System.Net.Mime.ContentType("text/html");
            AlternateView loTextView = null;
            AlternateView loHTMLView = null;
            string scriptText;
            DataTable dtTableScript = new DataTable();
            string ScriptType = "Forwarded Permission Application Sanction";
            //cl.fillDT("Select * from TA_TBL_EmailScripts where ScriptType='Forwarded Permission Application Sanction'", dtTableScript);
            dtTableScript = objLeaveApplicationEventData.GetEmailScripts(ScriptType);
            scriptText = dtTableScript.Rows[0]["ScriptText"].ToString();
            //mail.From = System.Configuration.ConfigurationManager.AppSettings["FromId"];
            //mail.To = EmailIdSanctionAuthority;
            //mail.Subject = Status + " Permission Application | " + lblPermissionDate.Text + " | " + EmployeeCodeId + " | " + EmployeeName + " - " + levelName;
            //mail.BodyFormat = MailFormat.Html;
            //mail.Priority = MailPriority.Normal;
            if (Session["loginEmailId"] != null && Session["loginEmailId"].ToString() != string.Empty)
            {
                mailMessage.From = new MailAddress(Session["loginEmailId"].ToString());
            }
            else
            {
                mailMessage.From = new MailAddress(ConfigurationManager.AppSettings.Get("FromId"));
            }
            mailMessage.To.Add(new MailAddress(EmailIdSanctionAuthority));
            mailMessage.Subject = levelName + " | " + " - " + EmployeeCodeId + " | " + lblPermissionDate + " | " + "Permission " + Status;
            mailMessage.Body = scriptText.Replace("<<lblPermissionSanction>>", rm.GetString("email_PermissionForm", ci));
            mailMessage.Body = mailMessage.Body.Replace("<<lblEmployeeId>>", rm.GetString("email_EmployeeId", ci));
            mailMessage.Body = mailMessage.Body.Replace("<<EmployeeId>>", EmployeeCodeId);
            mailMessage.Body = mailMessage.Body.Replace("<<lblEmployeeName>>", rm.GetString("email_EmployeeName", ci));
            //mailMessage.Body = mailMessage.Body.Replace("<<EmployeeName>>", lbl_EmployeeName.Text);
            mailMessage.Body = mailMessage.Body.Replace("<<lblPermissionDate>>", rm.GetString("Permission_PermissionDate", ci));
            mailMessage.Body = mailMessage.Body.Replace("<<PermissionDate>>", lblPermissionDate);
            mailMessage.Body = mailMessage.Body.Replace("<<lblNumberOfHoursApplied>>", rm.GetString("email_NumberOfHoursApplied", ci));
            mailMessage.Body = mailMessage.Body.Replace("<<NumberOfHoursApplied>>", TotalHours);
            mailMessage.Body = mailMessage.Body.Replace("<<lblPermission>>", rm.GetString("Dash_Permission", ci));
            mailMessage.Body = mailMessage.Body.Replace("<<lblFromTime>>", rm.GetString("email_FromDate", ci));
            mailMessage.Body = mailMessage.Body.Replace("<<FromTime>>", lblPermissionFromTime);
            mailMessage.Body = mailMessage.Body.Replace("<<lblToTime>>", rm.GetString("email_ToDate", ci));
            mailMessage.Body = mailMessage.Body.Replace("<<ToTime>>", lblPermissionToTime);
            mailMessage.Body = mailMessage.Body.Replace("<<lblStatus>>", rm.GetString("email_Status", ci));
            mailMessage.Body = mailMessage.Body.Replace("<<Status>>", Status);
            mailMessage.Body = mailMessage.Body.Replace("<<lblRemarks>>", rm.GetString("email_Remarks", ci));
            mailMessage.Body = mailMessage.Body.Replace("<<Remarks>>", Remarks);
            objClassCommon.SendMail(mailMessage);
        }
        catch
        {
            //string strScript = string.Empty;
            //strScript = strScript + "<script language='javascript'>";
            //strScript = strScript + "alert('Permission Application saved,Email not sent');";
            //strScript = strScript + "location.replace('TA_UI_Transactions_PermissionSanction.aspx');";
            //strScript = strScript + "</script>";
            ////Dispaly alert messsage.
            //Page.RegisterStartupScript("AlertPAdd678", strScript);
            checkEmail = false;
        }
    }
    private void SanctionViewDetails(int PermissionID)
    {
        Permission_Id = Convert.ToInt32(PermissionID);
        dtSanctionView = objPermissionEventData.GetPermissionByPermissionId(Permission_Id);
        if (dtSanctionView.Rows[0]["Employee_LastName"] != DBNull.Value)
        {
            LastName = dtSanctionView.Rows[0]["Employee_LastName"].ToString();
        }
        EmployeeEamilId = dtSanctionView.Rows[0]["EmailId"].ToString();
        lblPermissionDate = (Convert.ToDateTime(dtSanctionView.Rows[0]["Permission_Date"])).ToString(Session["MDateFormat"].ToString());
        string[] PerTime = dtSanctionView.Rows[0]["Permission_FromTime"].ToString().Split(" ".ToCharArray());
        string timePart1 = PerTime[1].ToString() + " " + PerTime[2].ToString();
        lblPermissionFromTime = (Convert.ToDateTime(PerTime[0])).ToString(Session["MDateFormat"].ToString()) + " " + DateTime.Parse(timePart1).ToString(Session["MTimeFormat"].ToString());
        string[] PerTime1 = dtSanctionView.Rows[0]["Permission_ToTime"].ToString().Split(" ".ToCharArray());
        string timePart2 = PerTime1[1].ToString() + " " + PerTime1[2].ToString();
        lblPermissionToTime = (Convert.ToDateTime(PerTime1[0])).ToString(Session["MDateFormat"].ToString()) + " " + DateTime.Parse(timePart2).ToString(Session["MTimeFormat"].ToString());
    }
    #endregion
    #region ButtonEvents
    protected void btnSave_Click(object sender, EventArgs e)
    {
        #region Comments
        //if (hdnSelectRow.Value != string.Empty)
        //{
        //    DataTable dsCheckedItem;
        //    dsCheckedItem = (DataTable)Session["PermissionChecked"];
        //    chkBoxIDs = objLeave.commaStringToArray(hdnSelectRow.Value);
        //    for (int i = 0; i < chkBoxIDs.Length; i++)
        //    {
        //        Permission_Id = Convert.ToInt32(chkBoxIDs[i]);
        //        dtSanctionView = objPermissionEventData.GetPermissionByPermissionId(Permission_Id);
        //        if (dtSanctionView.Rows.Count > 0)
        //        {
        //            if (dtSanctionView.Rows[0]["EmailId"] != DBNull.Value)
        //            {
        //                EmployeeEamilId = dtSanctionView.Rows[0]["EmailId"].ToString();
        //            }
        //            if (dtSanctionView.Rows[0]["Employee_Id"] != DBNull.Value)
        //            {
        //                Employee_Id = Convert.ToInt32(dtSanctionView.Rows[0]["Employee_Id"]);
        //            }
        //            if (dtSanctionView.Rows[0]["Employee_Code_Id"] != DBNull.Value)
        //            {
        //                Employee_Code_Id = dtSanctionView.Rows[0]["Employee_Code_Id"].ToString();
        //            }
        //            if (dtSanctionView.Rows[0]["Employee_FirstName"] != DBNull.Value)
        //            {
        //                EmployeeName = dtSanctionView.Rows[0]["Employee_FirstName"].ToString();
        //            }
        //            if (dtSanctionView.Rows[0]["name"] != DBNull.Value)
        //            {
        //                strlevelName = dtSanctionView.Rows[0]["name"].ToString();
        //            }
        //            gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
        //            gstrTimeFormat = Session["MTimeFormat"].ToString();
        //            string strFromDateTime = string.Empty;
        //            string strToDateTime = string.Empty;
        //            string[] PerTime = dtSanctionView.Rows[0]["Permission_FromTime"].ToString().Split(" ".ToCharArray());
        //            //Commented by MAnjula.P on 28-Sep-2013 to avoiding index bound array error
        //            //string timePart1 = PerTime[1].ToString() + " " + PerTime[2].ToString();
        //            string timePart1 = PerTime[0].ToString() + " " + PerTime[1].ToString();
        //            //***************Code End *****************************************
        //            lblPermissionFromTime = (Convert.ToDateTime(PerTime[0])).ToString(Session["MDateFormat"].ToString()) + " " + DateTime.Parse(timePart1).ToString(Session["MTimeFormat"].ToString());
        //            string[] PerTime1 = dtSanctionView.Rows[0]["Permission_ToTime"].ToString().Split(" ".ToCharArray());
        //            //Commented by MAnjula.P on 28-Sep-2013 to avoiding index bound array error
        //            // string timePart2 = PerTime1[1].ToString() + " " + PerTime1[2].ToString();
        //            string timePart2 = PerTime1[0].ToString() + " " + PerTime1[1].ToString();
        //            lblPermissionToTime = (Convert.ToDateTime(PerTime1[0])).ToString(Session["MDateFormat"].ToString()) + " " + DateTime.Parse(timePart2).ToString(Session["MTimeFormat"].ToString());
        //            lblPermissionDate = (Convert.ToDateTime(dtSanctionView.Rows[0]["Permission_Date"])).ToString(Session["MDateFormat"].ToString());
        //            NewStatus = dtSanctionView.Rows[0]["Permission_Status"].ToString();
        //            strFromDateTime = objClassCommon.DateTimeConvertion((gstrDateFormat + " " + gstrTimeFormat), lblPermissionFromTime, "B");
        //            strToDateTime = objClassCommon.DateTimeConvertion((gstrDateFormat + " " + gstrTimeFormat), lblPermissionToTime, "B");
        //            string dNumberOfHoursApplied = string.Empty;
        //            dNumberOfHoursApplied = CalculateNumberOfHoursApplied(strFromDateTime, strToDateTime);
        //            ds_ReportingToSanctionAuthorityList = objLeaveApplicationEventData.SelectReportingToSanctionAuthorityForPermission(Permission_Id);
        //            if (Session["UserGroupName"].ToString() != "SuperAdmin")
        //            {
        //                if (ds_ReportingToSanctionAuthorityList.Tables.Count > 0)
        //                {
        //                    if (ds_ReportingToSanctionAuthorityList.Tables[0].Rows.Count > 0)
        //                    {
        //                        if (Convert.ToString(Session["EmpAutoId"]) == Convert.ToString(ds_ReportingToSanctionAuthorityList.Tables[0].Rows[0]["Reporting_To"]) && Convert.ToString(Session["EmpAutoId"]) == Convert.ToString(ds_ReportingToSanctionAuthorityList.Tables[0].Rows[0]["Leave_Sanc_Authority"]))
        //                        {
        //                            NewStatus = "Approved";
        //                        }
        //                        else if (Convert.ToString(Session["EmpAutoId"]) == Convert.ToString(ds_ReportingToSanctionAuthorityList.Tables[0].Rows[0]["Reporting_To"]))
        //                        {
        //                            NewStatus = "Forwarded";
        //                        }
        //                        else if (Convert.ToString(Session["EmpAutoId"]) == Convert.ToString(ds_ReportingToSanctionAuthorityList.Tables[0].Rows[0]["Leave_Sanc_Authority"]))
        //                        {
        //                            NewStatus = "Approved";
        //                        }
        //                    }
        //                }
        //            }
        //            else
        //            {
        //                if (NewStatus == "Forwarded")
        //                {
        //                    NewStatus = "Approved";
        //                }
        //                if (NewStatus == "Pending")
        //                {
        //                    NewStatus = "Forwarded";
        //                }
        //            }
        //            Remarks = "";
        //            try
        //            {
        //                objPermissionEventData.UpdatePermissionSanction(Permission_Id, NewStatus, Remarks, Convert.ToInt32(Session["EmpAutoId"]));
        //                cls_Common objclscommon = new cls_Common();
        //                string strPermissionDate = objclscommon.DateConvertion(gstrDateFormat, lblPermissionDate);
        //                // Update Processed Data Flag
        //                objLeaveApplicationEventData.UpdateProcessedDataFlag(Employee_Id, strPermissionDate, strPermissionDate, 0);
        //                //if (ViewState["StatusOnLoad"].ToString() != Status)
        //                //{
        //                if (EmployeeEamilId != string.Empty)
        //                {
        //                    //SendMailToApplicant(EmployeeEamilId, Status, txtRemarks.Text, Employee_Code_Id, dNumberOfHoursApplied, strlevelName);
        //                }
        //                //To find Leave Sanction Authorities Email_ID
        //                ds_EmailIdOfSanctionAuthority = objPermissionEventData.SelectMailIdOfSanctionAuthority(Employee_Id);
        //                if (ds_EmailIdOfSanctionAuthority.Tables[0].Rows.Count > 0)
        //                {
        //                    if (ds_EmailIdOfSanctionAuthority.Tables[0].Rows[0]["EmailId"] != DBNull.Value)
        //                    {
        //                        if (ds_EmailIdOfSanctionAuthority.Tables[0].Rows[0]["EmailId"].ToString() != "")
        //                        {
        //                            strEmailIdSanctionAuthority = ds_EmailIdOfSanctionAuthority.Tables[0].Rows[0]["EmailId"].ToString();
        //                            //mail to sanctioning person
        //                            //SendMailToSanctionAuthority(strEmailIdSanctionAuthority, Status, Employee_Code_Id, EmployeeName, txtRemarks.Text, dNumberOfHoursApplied, strlevelName);
        //                        }
        //                        else
        //                        {
        //                            //checkEmail = false;
        //                        }
        //                    }
        //                    else
        //                    {
        //                        //checkEmail = false;
        //                    }
        //                }
        //                else
        //                {
        //                    //checkEmail = false;
        //                }
        //                //strEmailIdSanctionAuthority = "manikandan.rr@angleritech.com";
        //                //mail to Reporting to person
        //                dsEmailIdOfReportingTo = objPermissionEventData.SelectMailIdOfReportingTo(Employee_Id);
        //                string strEmailIdReportingTo = string.Empty;
        //                if (dsEmailIdOfReportingTo.Tables[0].Rows.Count > 0)
        //                {
        //                    if (dsEmailIdOfReportingTo.Tables[0].Rows[0]["EmailId"] != DBNull.Value)
        //                    {
        //                        if (dsEmailIdOfReportingTo.Tables[0].Rows[0]["EmailId"].ToString() != string.Empty)
        //                        {
        //                            strEmailIdReportingTo = dsEmailIdOfReportingTo.Tables[0].Rows[0]["EmailId"].ToString();
        //                        }
        //                    }
        //                }
        //                //strEmailIdReportingTo = "manikandan.rr@angleritech.com";
        //                SendMailToApplicant(EmployeeEamilId, strEmailIdReportingTo, strEmailIdSanctionAuthority, NewStatus, Remarks, Employee_Code_Id, dNumberOfHoursApplied, strlevelName, EmployeeName);
        //                if (checkEmail == true)
        //                {
        //                    hdnSelectRow.Value = "";
        //                    string strScript = string.Empty;
        //                    strScript = strScript + "<script language='javascript'>";
        //                    strScript = strScript + "alert('" + rm.GetString("Alert_PermissionApplicationsaved", ci) + "');";
        //                    strScript = strScript + "location.replace('TA_UI_Transactions_PermissionSanction.aspx');";
        //                    strScript = strScript + "</script>";
        //                    //Dispaly alert messsage.
        //                    Page.RegisterStartupScript("AlertPsaved36774", strScript);
        //                }
        //                else
        //                {
        //                    if (NotSendedEmployeeCodeId == "")
        //                    {
        //                        NotSendedEmployeeCodeId = Employee_Code_Id;
        //                    }
        //                    else
        //                    {
        //                        //Changing Employee Id into Employee Code Id for viewing to the user by Manjula.P on 28-Sep-2013 Employee_Id <>Employee_Code_Id  
        //                        string[] ExistEmployeeCode = NotSendedEmployeeCodeId.Split(',');
        //                        if (ExistEmployeeCode.Length > 0)
        //                        {
        //                            //To avoiding duplicate employee codes in message
        //                            int pos = Array.IndexOf(ExistEmployeeCode, Employee_Code_Id);
        //                            if (pos <= -1)
        //                            {
        //                                NotSendedEmployeeCodeId = NotSendedEmployeeCodeId + ',' + Employee_Code_Id;
        //                            }
        //                        }
        //                    }
        //                }
        //            }
        //            catch (Exception ex)
        //            {
        //                throw ex;
        //            }
        //        }
        //    }
        //    if (NotSendedEmployeeCodeId != null)
        //    {
        //        hdnSelectRow.Value = "";
        //        string strScript = string.Empty;
        //        strScript = strScript + "<script language='javascript'>";
        //        strScript = strScript + "alert('" + rm.GetString("Alert_PermissionApplicationsavedEmailnotsent_Bulk", ci) + NotSendedEmployeeCodeId + "');";
        //        strScript = strScript + "</script>";
        //        //Dispaly alert messsage.
        //        Page.RegisterStartupScript("AlertPAdd3674", strScript);
        //    }
        //    bindpermissionsanctiondetails();
        //}
        //else
        //{
        //    string strScript = string.Empty;
        //    strScript = strScript + "<script language='javascript'>";
        //    strScript = strScript + "alert('" + rm.GetString("Alert_SelectAnyOneApplication", ci) + "');";
        //    strScript = strScript + "</script>";
        //    Page.RegisterStartupScript("AlertPAdd3674", strScript);
        //}
        #endregion
    }
    public void GetEmptyText(object sender, EventArgs e)
    {
        Label lblNoRecords = (Label)sender;
        lblNoRecords.Text = rm.GetString("Alert_Norecordsfound", ci);
    }
    protected void btnBack_Click(object sender, EventArgs e)
    {
        clearAllSession();
        if (Convert.ToString(Session["isDashBoard"]) != "Yes")
        {
            Response.Redirect("TA_UI_Transactions_PermissionSanction_Angler.aspx");
        }
        else
        {
            if (Convert.ToString(Session["packageID"]) != "")
            {
                if (Convert.ToInt32(Session["packageID"]) == 168)  //Samsung
                    Response.Redirect("../Dashboard_Samsung.aspx?LevelId=" + LevelId + "&From_Date=" + From_Date + "&Shift=" + SelectedShift, true);
            }
            Response.Redirect("../DashBoard.aspx?LevelId=" + LevelId + "&From_Date=" + From_Date + "&Shift=" + SelectedShift, true);
        }
    }
    protected void btnForward_Click(object sender, EventArgs e)
    {
        string strReason = "";
        cls_Common objClassCommon = new cls_Common();
        DataSet dsEmailIdOfReportingTo = new DataSet();
        DataSet ds_EmailIdOfSanctionAuthority = new DataSet();
        LeaveSettingsEventData_Angler objLeaveSettingsEventData = new LeaveSettingsEventData_Angler();
        DataTable dtSanctionView = new DataTable();
        if (txtRemarks.Text == string.Empty)
        {
            base.Message("Remarks is required");
            return;
        }
        else
        {
            string strLengthCheck = txtRemarks.Text.Trim().Replace("'", "''");
            if (strLengthCheck.Length > 1000)
            {
                Message("Maximum character for Reason is 1000");
                return;
            }
            chkBoxIDs = objLeave.commaStringToArray(hdnSelectRow.Value);
            for (int i = 0; i < chkBoxIDs.Length; i++)
            {
                Permission_Id = Convert.ToInt32(chkBoxIDs[i]);
                dtSanctionView = objPermissionEventData.GetPermissionByPermissionId(Permission_Id);
                ViewState["Permission_Id"] = Permission_Id;
                dtSanctionView = objPermissionEventData.GetPermissionByPermissionId(Permission_Id);
                ViewState["dtSanctionView"] = dtSanctionView;
                if (dtSanctionView.Rows.Count > 0)
                {
                    if (dtSanctionView.Rows[0]["EmailId"] != DBNull.Value)
                    {
                        EmployeeEamilId = dtSanctionView.Rows[0]["EmailId"].ToString();
                    }
                    if (dtSanctionView.Rows[0]["Employee_Id"] != DBNull.Value)
                    {
                        Employee_Id = Convert.ToInt32(dtSanctionView.Rows[0]["Employee_Id"]);
                    }
                    if (dtSanctionView.Rows[0]["Employee_Code_Id"] != DBNull.Value)
                    {
                        Employee_Code_Id = dtSanctionView.Rows[0]["Employee_Code_Id"].ToString();
                    }
                    if (dtSanctionView.Rows[0]["Employee_FirstName"] != DBNull.Value)
                    {
                        EmployeeName = dtSanctionView.Rows[0]["Employee_FirstName"].ToString();
                    }
                    if (dtSanctionView.Rows[0]["Employee_lastname"] != DBNull.Value)
                    {
                        EmployeeName = EmployeeName + " " + dtSanctionView.Rows[0]["Employee_lastname"].ToString();
                    }
                    if (dtSanctionView.Rows[0]["name"] != DBNull.Value)
                    {
                        strlevelName = dtSanctionView.Rows[0]["name"].ToString();
                    }
                    string strFromDateTime = string.Empty;
                    string strToDateTime = string.Empty;
                    if (dtSanctionView.Rows[0]["Permission_Reason"] != DBNull.Value)
                    {
                        strReason = dtSanctionView.Rows[0]["Permission_Reason"].ToString();
                    }
                    if (dtSanctionView.Rows[0]["Permission_Hours"] != DBNull.Value)
                    {
                        ViewState["AppliedHours"] = dtSanctionView.Rows[0]["Permission_Hours"].ToString();
                    }
                    gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
                    gstrTimeFormat = Session["MTimeFormat"].ToString();
                    string[] PerTime = dtSanctionView.Rows[0]["Permission_FromTime"].ToString().Split(" ".ToCharArray());
                    string timePart1 = PerTime[1].ToString() + " " + PerTime[2].ToString();
                    strFromDateTime = (Convert.ToDateTime(PerTime[0])).ToString(Session["MDateFormat"].ToString()) + " " + DateTime.Parse(timePart1).ToString(Session["MTimeFormat"].ToString());
                    string[] PerTime1 = dtSanctionView.Rows[0]["Permission_ToTime"].ToString().Split(" ".ToCharArray());
                    string timePart2 = PerTime1[1].ToString() + " " + PerTime1[2].ToString();
                    strToDateTime = (Convert.ToDateTime(PerTime1[0])).ToString(Session["MDateFormat"].ToString()) + " " + DateTime.Parse(timePart2).ToString(Session["MTimeFormat"].ToString());
                    string strPermissionDate = (Convert.ToDateTime(dtSanctionView.Rows[0]["Permission_Date"])).ToString(Session["MDateFormat"].ToString());
                    DataSet ds_PermissionSettings = new DataSet();
                    DataTable dt_PermissionSettings = new DataTable();
                    string strApprovalCC = string.Empty;
                    DataSet ds_getOrg = new DataSet();
                    org_levelsEventData getOrg = new org_levelsEventData();
                    getOrg.GetOrgParentLevels_FromID(Convert.ToInt32(dtSanctionView.Rows[0]["LevelId"]));
                    ds_getOrg = getOrg.GetOrgParentLevels();
                    gintCompanyId = Convert.ToInt32(ds_getOrg.Tables[0].Rows[0]["LevelID"].ToString());
                    DataSet dsDepartmentMailIds = new DataSet();
                    dsDepartmentMailIds = objLeaveSettingsEventData.GetDepartmentMailIds(Convert.ToInt32(dtSanctionView.Rows[0]["LevelId"]));
                    ViewState["vsStrApprovalToDept"] = dsDepartmentMailIds.Tables[0].Rows[0]["ToMailIds"].ToString();
                    ViewState["vsStrApprovalCCDept"] = dsDepartmentMailIds.Tables[0].Rows[0]["CCMailIds"].ToString();
                    ds_PermissionSettings = objLeaveSettingsEventData.GetLeaveSettingsByComId(gintCompanyId);
                    if (ds_PermissionSettings.Tables.Count > 0)
                    {
                        dt_PermissionSettings = ds_PermissionSettings.Tables[0];
                    }
                    if (dt_PermissionSettings.Rows.Count > 0)
                    {
                        if (dt_PermissionSettings.Rows[0]["ApprovalCC"] != DBNull.Value && dt_PermissionSettings.Rows[0]["ApprovalCC"].ToString() != string.Empty)
                        {
                            strApprovalCC = dt_PermissionSettings.Rows[0]["ApprovalCC"].ToString();
                        }
                    }
                    gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
                    gstrTimeFormat = Session["MTimeFormat"].ToString();
                    string dNumberOfHoursApplied = string.Empty;
                    dNumberOfHoursApplied = CalculateNumberOfHoursApplied(strFromDateTime, strToDateTime);
                    Status = "Forwarded";
                    Remarks = txtRemarks.Text.Trim().Replace("'", "''");
                    int intLoginEmpId = Convert.ToInt32(Session["EmpAutoId"]);
                    int intApproval = 0, intAuthorityLevel = 0, intFirstLevelAuthorityId = 0, intSecondLevelAuthorityId = 0;
                    DataTable dt_ApprovalAuthority = new DataTable();
                    dt_ApprovalAuthority = objLeaveApplicationEventData.GetApprovalAuthorityIds(Employee_Id);
                    if (dt_ApprovalAuthority.Rows.Count > 0)
                    {
                        if (dt_ApprovalAuthority.Rows[0]["Reporting_To"] != DBNull.Value && dt_ApprovalAuthority.Rows[0]["Reporting_To"].ToString() != string.Empty)
                        {
                            intFirstLevelAuthorityId = int.Parse(dt_ApprovalAuthority.Rows[0]["Reporting_To"].ToString());
                            reportingToEmployee = dt_ApprovalAuthority.Rows[0]["ReportingToEmployee"].ToString();
                            ViewState["reportingToEmployee"] = reportingToEmployee;
                        }
                        if (dt_ApprovalAuthority.Rows[0]["Leave_Sanc_Authority"] != DBNull.Value && dt_ApprovalAuthority.Rows[0]["Leave_Sanc_Authority"].ToString() != string.Empty)
                        {
                            intSecondLevelAuthorityId = int.Parse(dt_ApprovalAuthority.Rows[0]["Leave_Sanc_Authority"].ToString());
                            sanctioningEmployee = dt_ApprovalAuthority.Rows[0]["SanctioningEmployee"].ToString();
                            ViewState["sanctioningEmployee"] = sanctioningEmployee;
                        }
                    }
                    if (intFirstLevelAuthorityId != intSecondLevelAuthorityId)
                    {
                        if (intLoginEmpId == intFirstLevelAuthorityId)
                        {
                            intAuthorityLevel = 1;
                        }
                        else if (intLoginEmpId == intSecondLevelAuthorityId)
                        {
                            intAuthorityLevel = 2;
                        }
                        else
                        {
                        }
                    }
                    else if (intFirstLevelAuthorityId == intSecondLevelAuthorityId)
                    {
                        if (intLoginEmpId == intSecondLevelAuthorityId)
                        {
                            intAuthorityLevel = 2;
                        }
                        else
                        {
                            intAuthorityLevel = 3;
                        }
                    }
                    else
                    {
                        intAuthorityLevel = 3;
                    }
                    ViewState["vsCommentsBy"] = intAuthorityLevel;
                    try
                    {
                        if (Status != "")
                        {
                            objPermissionEventData.UpdatePermissionApplicationConversation(Permission_Id, Status, 1, Remarks, Convert.ToInt32(Session["EmpAutoId"]));
                            objPermissionEventData.UpdatePermissionSanction(Permission_Id, Status, Remarks, Convert.ToInt32(Session["EmpAutoId"]));
                            cls_Common objclscommon = new cls_Common();
                            // Update Processed Data Flag
                            objLeaveApplicationEventData.UpdateProcessedDataFlag(Employee_Id, strPermissionDate, strPermissionDate, 0);
                            // To find Reporting To & Leave Sanction Authority Email_ID
                            // Gets the Reporting To Authority Id and Email Id
                            //int intFirstLevelAuthorityId = 0, intSecondLevelAuthorityId = 0;
                            //To find Leave Sanction Authorities Email_ID
                            ds_EmailIdOfSanctionAuthority = objPermissionEventData.SelectMailIdOfSanctionAuthority(Employee_Id);
                            if (ds_EmailIdOfSanctionAuthority.Tables[0].Rows.Count > 0)
                            {
                                if (ds_EmailIdOfSanctionAuthority.Tables[0].Rows[0]["EmailId"] != DBNull.Value)
                                {
                                    if (ds_EmailIdOfSanctionAuthority.Tables[0].Rows[0]["EmailId"].ToString() != "")
                                    {
                                        intSecondLevelAuthorityId = int.Parse(ds_EmailIdOfSanctionAuthority.Tables[0].Rows[0]["Employee_Id"].ToString());
                                        strEmailIdSanctionAuthority = ds_EmailIdOfSanctionAuthority.Tables[0].Rows[0]["EmailId"].ToString();
                                    }
                                    else
                                    {
                                        checkEmail = false;
                                    }
                                }
                                else
                                {
                                    checkEmail = false;
                                }
                            }
                            else
                            {
                                checkEmail = false;
                            }
                            //mail to Reporting to person
                            dsEmailIdOfReportingTo = objPermissionEventData.SelectMailIdOfReportingTo(Employee_Id);
                            if (dsEmailIdOfReportingTo.Tables[0].Rows.Count > 0)
                            {
                                if (dsEmailIdOfReportingTo.Tables[0].Rows[0]["EmailId"] != DBNull.Value)
                                {
                                    if (dsEmailIdOfReportingTo.Tables[0].Rows[0]["EmailId"].ToString() != string.Empty)
                                    {
                                        intFirstLevelAuthorityId = int.Parse(dsEmailIdOfReportingTo.Tables[0].Rows[0]["Employee_Id"].ToString());
                                        strEmailIdReportingTo = dsEmailIdOfReportingTo.Tables[0].Rows[0]["EmailId"].ToString();
                                    }
                                }
                            }
                            if (strEmailIdSanctionAuthority == string.Empty && strEmailIdReportingTo == string.Empty)
                            {
                                checkEmail = false;
                            }
                            if (strEmailIdSanctionAuthority == null && strEmailIdReportingTo == null)
                            {
                                checkEmail = false;
                            }
                            if (checkEmail == true)
                            {
                                ControlCreation(Permission_Id, EmployeeName);
                                if (Convert.ToInt32(ConfigurationManager.AppSettings.Get("isRequiredEmail")) == 1)
                                {
                                    SendMail(intFirstLevelAuthorityId, intSecondLevelAuthorityId, strEmailIdReportingTo, strEmailIdSanctionAuthority, EmployeeEamilId, Status, Employee_Code_Id, EmployeeName, txtRemarks.Text.Trim().Replace("'", "''"), ViewState["AppliedHours"].ToString(), strlevelName, strApprovalCC, EmployeeName, strPermissionDate, strFromDateTime, strToDateTime, strReason);
                                }
                            }
                            if (checkEmail == true)
                            {
                                string strScript = string.Empty;
                                strScript = strScript + "<script language='javascript'>";
                                strScript = strScript + "alert('Permission Application saved');";
                                strScript = strScript + "RedirectionFunction();";
                                //strScript = strScript + "location.replace('TA_UI_Transactions_PermissionSanctionView.aspx?Permission_Id=" + Request.QueryString["Permission_Id"].ToString() + "&LevelId=" + Request.QueryString["LevelId"].ToString() + "&Status=" + Request.QueryString["Status"].ToString() + "&From_Date=" + Request.QueryString["From_Date"].ToString() + "&To_Date=" + Request.QueryString["To_Date"].ToString() + "&strSwipeCardNo=" + Request.QueryString["strSwipeCardNo"].ToString() + "&strEmployeeName=" + Request.QueryString["strEmployeeName"].ToString() + "&strEmployeeCodeId=" + Request.QueryString["strEmployeeCodeId"].ToString() + "')";
                                //strScript = strScript + "location.replace('TA_UI_Transactions_PermissionSanction.aspx');";
                                strScript = strScript + "</script>";
                                //Dispaly alert messsage.
                                Page.RegisterStartupScript("AlertPsaved36774", strScript);
                            }
                            else
                            {
                                string strScript = string.Empty;
                                strScript = strScript + "<script language='javascript'>";
                                strScript = strScript + "alert('Permission Application saved,Email not sent');";
                                strScript = strScript + "RedirectionFunction();";
                                //strScript = strScript + "location.replace('TA_UI_Transactions_PermissionSanctionView.aspx?Permission_Id=" + Request.QueryString["Permission_Id"].ToString() + "&LevelId=" + Request.QueryString["LevelId"].ToString() + "&Status=" + Request.QueryString["Status"].ToString() + "&From_Date=" + Request.QueryString["From_Date"].ToString() + "&To_Date=" + Request.QueryString["To_Date"].ToString() + "&strSwipeCardNo=" + Request.QueryString["strSwipeCardNo"].ToString() + "&strEmployeeName=" + Request.QueryString["strEmployeeName"].ToString() + "&strEmployeeCodeId=" + Request.QueryString["strEmployeeCodeId"].ToString() + "')";
                                //strScript = strScript + "location.replace('TA_UI_Transactions_PermissionSanction.aspx');";
                                strScript = strScript + "</script>";
                                //Dispaly alert messsage.
                                Page.RegisterStartupScript("AlertPAdd3674", strScript);
                            }
                        }
                        else
                        {
                            //lbl_Error.Text = "Please change the status";
                            Message("Please change the status");
                            return;
                        }
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }
                // }
            }
            //end of if
        }
        Status = Request.QueryString["Status"];
        bindpermissionsanctiondetails();
    }
    protected void btnApprove_Click(object sender, EventArgs e)
    {
        string strReason = "";
        cls_Common objClassCommon = new cls_Common();
        DataSet dsEmailIdOfReportingTo = new DataSet();
        DataSet ds_EmailIdOfSanctionAuthority = new DataSet();
        LeaveSettingsEventData_Angler objLeaveSettingsEventData = new LeaveSettingsEventData_Angler();
        //int Permission_Id, Employee_Id, gintCompanyId;
        //string Status, Remarks, EmployeeEamilId, strEmailIdReportingTo, strEmailIdSanctionAuthority, EmployeeName, Employee_Code_Id, gstrDateFormat, strlevelName, gstrTimeFormat, reportingToEmployee, sanctioningEmployee;
        DataTable dtSanctionView = new DataTable();
        if (txtRemarks.Text == string.Empty)
        {
            base.Message("Remarks is required");
            return;
        }
        else
        {
            string strLengthCheck = txtRemarks.Text.Trim().Replace("'", "''");
            if (strLengthCheck.Length > 1000)
            {
                Message("Maximum character for Reason is 1000");
                return;
            }
            //foreach (GridViewRow i in gdPermissionSanctionView.Rows)
            //{
            chkBoxIDs = objLeave.commaStringToArray(hdnSelectRow.Value);
            for (int i = 0; i < chkBoxIDs.Length; i++)
            {
                Permission_Id = Convert.ToInt32(chkBoxIDs[i]);
                dtSanctionView = objPermissionEventData.GetPermissionByPermissionId(Permission_Id);
                //CheckBox ChkBxItem = (CheckBox)i.FindControl("deletethis");
                //if (ChkBxItem.Checked)
                //{
                //Permission_Id = Convert.ToInt16(((Label)i.FindControl("lblPerID")).Text);
                ViewState["Permission_Id"] = Permission_Id;
                //Permission_Id = Convert.ToInt32(Request.QueryString["Permission_Id"]);
                dtSanctionView = objPermissionEventData.GetPermissionByPermissionId(Permission_Id);
                ViewState["dtSanctionView"] = dtSanctionView;
                if (dtSanctionView.Rows.Count > 0)
                {
                    if (dtSanctionView.Rows[0]["EmailId"] != DBNull.Value)
                    {
                        EmployeeEamilId = dtSanctionView.Rows[0]["EmailId"].ToString();
                    }
                    if (dtSanctionView.Rows[0]["Employee_Id"] != DBNull.Value)
                    {
                        Employee_Id = Convert.ToInt32(dtSanctionView.Rows[0]["Employee_Id"]);
                    }
                    if (dtSanctionView.Rows[0]["Employee_Code_Id"] != DBNull.Value)
                    {
                        Employee_Code_Id = dtSanctionView.Rows[0]["Employee_Code_Id"].ToString();
                    }
                    if (dtSanctionView.Rows[0]["Employee_FirstName"] != DBNull.Value)
                    {
                        EmployeeName = dtSanctionView.Rows[0]["Employee_FirstName"].ToString();
                    }
                    if (dtSanctionView.Rows[0]["Employee_lastname"] != DBNull.Value)
                    {
                        EmployeeName = EmployeeName + " " + dtSanctionView.Rows[0]["Employee_lastname"].ToString();
                    }
                    if (dtSanctionView.Rows[0]["name"] != DBNull.Value)
                    {
                        strlevelName = dtSanctionView.Rows[0]["name"].ToString();
                    }
                    string strFromDateTime = string.Empty;
                    string strToDateTime = string.Empty;
                    if (dtSanctionView.Rows[0]["Permission_Reason"] != DBNull.Value)
                    {
                        strReason = dtSanctionView.Rows[0]["Permission_Reason"].ToString();
                    }
                    if (dtSanctionView.Rows[0]["Permission_Hours"] != DBNull.Value)
                    {
                        ViewState["AppliedHours"] = dtSanctionView.Rows[0]["Permission_Hours"].ToString();
                    }
                    //strFromDateTime = objClassCommon.DateTimeConvertion((gstrDateFormat + " " + gstrTimeFormat), lblPermissionFromTime.Text, "B");
                    //strToDateTime = objClassCommon.DateTimeConvertion((gstrDateFormat + " " + gstrTimeFormat), lblPermissionToTime.Text, "B");
                    gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
                    gstrTimeFormat = Session["MTimeFormat"].ToString();
                    string[] PerTime = dtSanctionView.Rows[0]["Permission_FromTime"].ToString().Split(" ".ToCharArray());
                    string timePart1 = PerTime[1].ToString() + " " + PerTime[2].ToString();
                    //txt_StartTime.Text = (Convert.ToDateTime(PerTime[0])).ToString(Session["MDateFormat"].ToString()) + " " + DateTime.Parse(PerTime[1]).ToString("hh:mm") + " " + PerTime[2];
                    strFromDateTime = (Convert.ToDateTime(PerTime[0])).ToString(Session["MDateFormat"].ToString()) + " " + DateTime.Parse(timePart1).ToString(Session["MTimeFormat"].ToString());
                    string[] PerTime1 = dtSanctionView.Rows[0]["Permission_ToTime"].ToString().Split(" ".ToCharArray());
                    string timePart2 = PerTime1[1].ToString() + " " + PerTime1[2].ToString();
                    //txt_EndTime.Text = (Convert.ToDateTime(PerTime1[0])).ToString(Session["MDateFormat"].ToString()) + " " + DateTime.Parse(PerTime1[1]).ToString("hh:mm") + " " + PerTime1[2];
                    strToDateTime = (Convert.ToDateTime(PerTime1[0])).ToString(Session["MDateFormat"].ToString()) + " " + DateTime.Parse(timePart2).ToString(Session["MTimeFormat"].ToString());
                    //strFromDateTime = objClassCommon.DateTimeConvertion(("MM/dd/yyyy" + " " + gstrTimeFormat), Convert.ToString(dtSanctionView.Rows[0]["Permission_FromTime"]), "B");
                    //strToDateTime = objClassCommon.DateTimeConvertion((gstrDateFormat + " " + gstrTimeFormat), Convert.ToString(dtSanctionView.Rows[0]["Permission_ToTime"]), "B");
                    string strPermissionDate = (Convert.ToDateTime(dtSanctionView.Rows[0]["Permission_Date"])).ToString(Session["MDateFormat"].ToString());
                    DataSet ds_PermissionSettings = new DataSet();
                    DataTable dt_PermissionSettings = new DataTable();
                    string strApprovalCC = string.Empty;
                    DataSet ds_getOrg = new DataSet();
                    org_levelsEventData getOrg = new org_levelsEventData();
                    getOrg.GetOrgParentLevels_FromID(Convert.ToInt32(dtSanctionView.Rows[0]["LevelId"]));
                    ds_getOrg = getOrg.GetOrgParentLevels();
                    gintCompanyId = Convert.ToInt32(ds_getOrg.Tables[0].Rows[0]["LevelID"].ToString());
                    //ViewState["CompanyId"] = gintCompanyId;
                    DataSet dsDepartmentMailIds = new DataSet();
                    dsDepartmentMailIds = objLeaveSettingsEventData.GetDepartmentMailIds(Convert.ToInt32(dtSanctionView.Rows[0]["LevelId"]));
                    ViewState["vsStrApprovalToDept"] = dsDepartmentMailIds.Tables[0].Rows[0]["ToMailIds"].ToString();
                    ViewState["vsStrApprovalCCDept"] = dsDepartmentMailIds.Tables[0].Rows[0]["CCMailIds"].ToString();
                    //gintCompanyId = int.Parse(ViewState["CompanyId"].ToString());
                    ds_PermissionSettings = objLeaveSettingsEventData.GetLeaveSettingsByComId(gintCompanyId);
                    if (ds_PermissionSettings.Tables.Count > 0)
                    {
                        dt_PermissionSettings = ds_PermissionSettings.Tables[0];
                    }
                    if (dt_PermissionSettings.Rows.Count > 0)
                    {
                        if (dt_PermissionSettings.Rows[0]["ApprovalCC"] != DBNull.Value && dt_PermissionSettings.Rows[0]["ApprovalCC"].ToString() != string.Empty)
                        {
                            strApprovalCC = dt_PermissionSettings.Rows[0]["ApprovalCC"].ToString();
                        }
                    }
                    //Convert Date Format to MM/dd/yyyy Format
                    //Convert Date Format to MM/dd/yyyy Format
                    //strFromTime = objClassCommon.DateTimeConvertion((gstrDateFormat + " hh:mm tt"), lblPermissionFromTime.Text, "B");
                    //strToTime = objClassCommon.DateTimeConvertion((gstrDateFormat + " hh:mm tt"), lblPermissionToTime.Text, "B");
                    gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
                    gstrTimeFormat = Session["MTimeFormat"].ToString();
                    string dNumberOfHoursApplied = string.Empty;
                    dNumberOfHoursApplied = CalculateNumberOfHoursApplied(strFromDateTime, strToDateTime);
                    //TimeSpan tsHours = DateTime.Parse(lblPermissionToTime.Text).Subtract(DateTime.Parse(lblPermissionFromTime.Text));
                    Status = "Approved";
                    Remarks = txtRemarks.Text.Trim().Replace("'", "''");
                    int intLoginEmpId = Convert.ToInt32(Session["EmpAutoId"]);
                    int intApproval = 0, intAuthorityLevel = 0, intFirstLevelAuthorityId = 0, intSecondLevelAuthorityId = 0;
                    DataTable dt_ApprovalAuthority = new DataTable();
                    // Get First and Second Level Authority Ids
                    dt_ApprovalAuthority = objLeaveApplicationEventData.GetApprovalAuthorityIds(Employee_Id);
                    if (dt_ApprovalAuthority.Rows.Count > 0)
                    {
                        if (dt_ApprovalAuthority.Rows[0]["Reporting_To"] != DBNull.Value && dt_ApprovalAuthority.Rows[0]["Reporting_To"].ToString() != string.Empty)
                        {
                            intFirstLevelAuthorityId = int.Parse(dt_ApprovalAuthority.Rows[0]["Reporting_To"].ToString());
                            reportingToEmployee = dt_ApprovalAuthority.Rows[0]["ReportingToEmployee"].ToString();
                            ViewState["reportingToEmployee"] = reportingToEmployee;
                        }
                        if (dt_ApprovalAuthority.Rows[0]["Leave_Sanc_Authority"] != DBNull.Value && dt_ApprovalAuthority.Rows[0]["Leave_Sanc_Authority"].ToString() != string.Empty)
                        {
                            intSecondLevelAuthorityId = int.Parse(dt_ApprovalAuthority.Rows[0]["Leave_Sanc_Authority"].ToString());
                            sanctioningEmployee = dt_ApprovalAuthority.Rows[0]["SanctioningEmployee"].ToString();
                            ViewState["sanctioningEmployee"] = sanctioningEmployee;
                        }
                    }
                    // Check whether the Login Employee Id is whether First or Second Level Sanctioning Authority
                    if (intFirstLevelAuthorityId != intSecondLevelAuthorityId)
                    {
                        if (intLoginEmpId == intFirstLevelAuthorityId)
                        {
                            intAuthorityLevel = 1;
                        }
                        else if (intLoginEmpId == intSecondLevelAuthorityId)
                        {
                            intAuthorityLevel = 2;
                        }
                        else
                        {
                            // Nothing
                        }
                    }
                    else if (intFirstLevelAuthorityId == intSecondLevelAuthorityId)
                    {
                        if (intLoginEmpId == intSecondLevelAuthorityId)
                        {
                            intAuthorityLevel = 2;
                        }
                        else
                        {
                            intAuthorityLevel = 3;
                        }
                    }
                    else
                    {
                        intAuthorityLevel = 3;
                    }
                    ViewState["vsCommentsBy"] = intAuthorityLevel;
                    try
                    {
                        if (Status != "")
                        {
                            //Updates the status based on the permission status.
                            string strPermissionStatus = Convert.ToString(dtSanctionView.Rows[0]["Permission_Status"]);
                            //((Label)i.FindControl("lblPermissionStatus")).Text;
                            int intCommentsBy = 0;
                            if (strPermissionStatus == "Pending")
                            {
                                Status = "Forwarded";
                                intCommentsBy = 1;
                            }
                            else if (strPermissionStatus == "Forwarded")
                            {
                                Status = "Approved";
                                intCommentsBy = 2;
                            }
                            // update the status,remareks(only) of permission application
                            //insert into TA_Tbl_PermissionConversation
                            objPermissionEventData.UpdatePermissionApplicationConversation(Permission_Id, Status, intCommentsBy, Remarks, Convert.ToInt32(Session["EmpAutoId"]));
                            objPermissionEventData.UpdatePermissionSanction(Permission_Id, Status, Remarks, Convert.ToInt32(Session["EmpAutoId"]));
                            cls_Common objclscommon = new cls_Common();
                            // Update Processed Data Flag
                            //Added by Manjula.P on 13-May-2014 for getting datetime format as like in genral in product
                            strPermissionDate = objClassCommon.DateConvertion(gstrDateFormat, strPermissionDate);
                            objLeaveApplicationEventData.UpdateProcessedDataFlag(Employee_Id, strPermissionDate, strPermissionDate, 0);
                            // To find Reporting To & Leave Sanction Authority Email_ID
                            // Gets the Reporting To Authority Id and Email Id
                            //int intFirstLevelAuthorityId = 0, intSecondLevelAuthorityId = 0;
                            //To find Leave Sanction Authorities Email_ID
                            ds_EmailIdOfSanctionAuthority = objPermissionEventData.SelectMailIdOfSanctionAuthority(Employee_Id);
                            if (ds_EmailIdOfSanctionAuthority.Tables[0].Rows.Count > 0)
                            {
                                if (ds_EmailIdOfSanctionAuthority.Tables[0].Rows[0]["EmailId"] != DBNull.Value)
                                {
                                    if (ds_EmailIdOfSanctionAuthority.Tables[0].Rows[0]["EmailId"].ToString() != "")
                                    {
                                        intSecondLevelAuthorityId = int.Parse(ds_EmailIdOfSanctionAuthority.Tables[0].Rows[0]["Employee_Id"].ToString());
                                        strEmailIdSanctionAuthority = ds_EmailIdOfSanctionAuthority.Tables[0].Rows[0]["EmailId"].ToString();
                                    }
                                    else
                                    {
                                        checkEmail = false;
                                    }
                                }
                                else
                                {
                                    checkEmail = false;
                                }
                            }
                            else
                            {
                                checkEmail = false;
                            }
                            //mail to Reporting to person
                            dsEmailIdOfReportingTo = objPermissionEventData.SelectMailIdOfReportingTo(Employee_Id);
                            if (dsEmailIdOfReportingTo.Tables[0].Rows.Count > 0)
                            {
                                if (dsEmailIdOfReportingTo.Tables[0].Rows[0]["EmailId"] != DBNull.Value)
                                {
                                    if (dsEmailIdOfReportingTo.Tables[0].Rows[0]["EmailId"].ToString() != string.Empty)
                                    {
                                        intFirstLevelAuthorityId = int.Parse(dsEmailIdOfReportingTo.Tables[0].Rows[0]["Employee_Id"].ToString());
                                        strEmailIdReportingTo = dsEmailIdOfReportingTo.Tables[0].Rows[0]["EmailId"].ToString();
                                    }
                                }
                            }
                            if (strEmailIdSanctionAuthority == string.Empty && strEmailIdReportingTo == string.Empty)
                            {
                                checkEmail = false;
                            }
                            if (strEmailIdSanctionAuthority == null && strEmailIdReportingTo == null)
                            {
                                checkEmail = false;
                            }
                            if (checkEmail == true)
                            {
                                ControlCreation(Permission_Id, EmployeeName);
                                if (Convert.ToInt32(ConfigurationManager.AppSettings.Get("isRequiredEmail")) == 1)
                                {
                                    SendMail(intFirstLevelAuthorityId, intSecondLevelAuthorityId, strEmailIdReportingTo, strEmailIdSanctionAuthority, EmployeeEamilId, Status, Employee_Code_Id, EmployeeName, txtRemarks.Text.Trim().Replace("'", "''"), ViewState["AppliedHours"].ToString(), strlevelName, strApprovalCC, EmployeeName, strPermissionDate, strFromDateTime, strToDateTime, strReason);
                                }
                            }
                            if (checkEmail == true)
                            {
                                string strScript = string.Empty;
                                strScript = strScript + "<script language='javascript'>";
                                strScript = strScript + "alert('Permission Application saved');";
                                strScript = strScript + "RedirectionFunction();";
                                //strScript = strScript + "location.replace('TA_UI_Transactions_PermissionSanctionView.aspx?Permission_Id=" + Request.QueryString["Permission_Id"].ToString() + "&LevelId=" + Request.QueryString["LevelId"].ToString() + "&Status=" + Request.QueryString["Status"].ToString() + "&From_Date=" + Request.QueryString["From_Date"].ToString() + "&To_Date=" + Request.QueryString["To_Date"].ToString() + "&strSwipeCardNo=" + Request.QueryString["strSwipeCardNo"].ToString() + "&strEmployeeName=" + Request.QueryString["strEmployeeName"].ToString() + "&strEmployeeCodeId=" + Request.QueryString["strEmployeeCodeId"].ToString() + "')";
                                //strScript = strScript + "location.replace('TA_UI_Transactions_PermissionSanction.aspx');";
                                strScript = strScript + "</script>";
                                //Dispaly alert messsage.
                                Page.RegisterStartupScript("AlertPsaved36774", strScript);
                            }
                            else
                            {
                                string strScript = string.Empty;
                                strScript = strScript + "<script language='javascript'>";
                                strScript = strScript + "alert('Permission Application saved,Email not sent');";
                                strScript = strScript + "RedirectionFunction();";
                                //strScript = strScript + "location.replace('TA_UI_Transactions_PermissionSanctionView.aspx?Permission_Id=" + Request.QueryString["Permission_Id"].ToString() + "&LevelId=" + Request.QueryString["LevelId"].ToString() + "&Status=" + Request.QueryString["Status"].ToString() + "&From_Date=" + Request.QueryString["From_Date"].ToString() + "&To_Date=" + Request.QueryString["To_Date"].ToString() + "&strSwipeCardNo=" + Request.QueryString["strSwipeCardNo"].ToString() + "&strEmployeeName=" + Request.QueryString["strEmployeeName"].ToString() + "&strEmployeeCodeId=" + Request.QueryString["strEmployeeCodeId"].ToString() + "')";
                                //strScript = strScript + "location.replace('TA_UI_Transactions_PermissionSanction.aspx');";
                                strScript = strScript + "</script>";
                                //Dispaly alert messsage.
                                Page.RegisterStartupScript("AlertPAdd3674", strScript);
                            }
                        }
                        else
                        {
                            //lbl_Error.Text = "Please change the status";
                            Message("Please change the status");
                            return;
                        }
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }
                //}
            }
            //end of if
        }
        Status = Request.QueryString["Status"];
        bindpermissionsanctiondetails();
    }
    #endregion
}
