using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
//using System.Web.Mail;
using System.Net.Mail;
using System.Globalization;
using System.Threading;
using System.Reflection;
using System.Resources;
using System.Net;
using System.Text;
/****************************************************************************************************************************
* Project Name    : TimeCheck                         Started Date  : 12-Aug-2007
* Module          : Leave Sanction                    Last Modified : 14-Aug-2007
* Programmer      : Prabakaran.P
* Current Storage : \\Angler56\Projects\Inprogress\SCREEN1206\code\Time_AttendanceApp
* BackUp          :
****************************************************************************************************************************/
public partial class Transactions_TA_UI_Transactions_LeaveSanctionModify_Angler : Base.BasePage
{
    #region "Variable Declaration"
    ResourceManager rm;
    CultureInfo ci;
    PermissionEventData_Angler objPermissionEventData = new PermissionEventData_Angler();
    LeaveApplicationEventData_Angler objLeaveApplicationEventData = new LeaveApplicationEventData_Angler();
    LeaveSettingsEventData_Angler objLeaveSettingsEventData = new LeaveSettingsEventData_Angler();
    CCGroupEventData_Angler objCCGroup = new CCGroupEventData_Angler();
    Cls_CheckUser objCheckUser = new Cls_CheckUser();
    DataSet ds_Checkuser = new DataSet();
    DataTable dtSanctionView = new DataTable();
    DataSet ds_EmailIdOfSanctionAuthority = new DataSet();
    DataSet dsEmailIdOfReportingTo = new DataSet();
    DataSet dsLeaveConversation = new DataSet();
    DataSet dsLeavePrivateNotes = new DataSet();
    // RadioButtonList rblStatus = new RadioButtonList();
    DataSet dsRecordsCount = new DataSet();
    /// <summary>
    /// Dataset for storing Active Year Setting Details 
    /// </summary>
    DataSet dsYear = new DataSet();
    DataTable dtLeaveavailedinMonth = new DataTable();
    int LeaveApplication_Id, Employee_Id, LeaveTypeId;
    string Status, Remarks, strEmailIdReportingTo, strEmailIdSanctionAuthority, EmployeeName, EmployeeEamilId, Employee_Code_Id, strLeaveApplicationDate, strNoOfDays, Leave_FromDate, Leave_ToDate, reportingToEmployee, sanctioningEmployee, levelName, strYearSettingsFromdate, strYearSettingsTodate;
    string strHtml = string.Empty;
    string strHtmlPrivateNotes = string.Empty;
    string strHtmlLeaveDetails = string.Empty;
    string LeaveApplicationIDs;
    double NumberOfDays;
    //double dblLeaveAvailedYear = 0.0;
    //double dblLeaveAvailedMonth = 0.0;
    bool checkEmail = true;
    bool blnPrivateNotes = false;
    bool blnCheckPrivateNotes = false;
    string strCrossdate = string.Empty;
    string strMonthValue = string.Empty;
    string strLeaveavailedinFirstMonth = string.Empty;
    string strLeaveavailedinSecondMonth = string.Empty;
    string strLeaveavailedinFirstMonthName = string.Empty;
    string strLeaveavailedinSecondMonthName = string.Empty;
    string ScriptType = string.Empty;
    int commentsBy = 0, gintCompanyId;
    //Added by Manjula.P on 13-May-2014 for getting datetime common format
    string gstrDateFormat = string.Empty;
    cls_Common objClassCommon = new cls_Common();
    #endregion
    #region Page Load events
    protected override void Page_Load(object sender, EventArgs e)
    {
        // session checking
        base.Page_Load(sender, e);
        //if Standar Edition set the visibility to false
        if (Session["Edition"].ToString() == "1")
        {
            Response.Redirect("TransactionLandingPage.aspx");
        }
        //if (Request.UrlReferrer != null)
        //{
        //    string GetURL = Request.UrlReferrer.ToString();
        //}
        //else
        //{
        //    Response.Redirect("TransactionLandingPage.aspx");
        //}
        //get the culture info to set the language        
        //Added by Manjula.P on 13-may-2014
        gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
        string source_Language;
        source_Language = Session["Session_ActiveLanguage"].ToString();
        rm = new ResourceManager(source_Language, System.Reflection.Assembly.Load("App_GlobalResources"));
        ci = Thread.CurrentThread.CurrentCulture;
        LoadStrings(ci);
        LeaveApplication_Id = Convert.ToInt32(Request.QueryString["LeaveApplication_Id"]);
        ViewState["vsLeaveApplication_Id"] = LeaveApplication_Id;
        //dynamic controls for Private Notes Conversation
        PrivateNotesControlCreation();
        cls_Common objClassCommon = new cls_Common();
        //Call to a function to get the Year setting details
        dsYear = objClassCommon.GetYearsetting();
        if (dsYear.Tables[0].Rows.Count <= 0)
        {
            string strScript = "";
            strScript = strScript + "<script language='javascript'>";
            strScript = strScript + "alert('Define Year Setting in Organization Settings');location.replace('../Organization Settings/Organization_YearSetting.aspx')";
            strScript = strScript + "</script>";
            Page.RegisterStartupScript("AlertLeavePolicyYear", strScript);
        }
        else
        {
            strYearSettingsFromdate = dsYear.Tables[0].Rows[0]["FromDate"].ToString();
            strYearSettingsTodate = dsYear.Tables[0].Rows[0]["ToDate"].ToString();
            dsYear.Dispose();
        }
        if (!IsPostBack)
        {
            if (Convert.ToString(Session["TopMenuPrevious"]) == "")
            {
                GenerateMenu();
                loadMenu();
                LoadYear();
            }
            objClassCommon.menu("LeaveTransaction", "260");
            //Automatically management Cc loaded in the CC list for the below mentioned sactioning authorites (Employee_Code_Id) 
            string strApprovalEmployeeCodeId = "2,7,18000000";
            string[] strArrEmployeeCodeId = strApprovalEmployeeCodeId.Split(',');
            bool blnManagementCc = false;
            for (int i = 0; i < strArrEmployeeCodeId.Length; i++)
            {
                if (strArrEmployeeCodeId[i].ToString() == Session["EmployeeCodeId"].ToString())
                {
                    blnManagementCc = true;
                }
            }
            if (blnManagementCc == true)
            {
                //lblManagementCcData.Text = "jayachandran@angleritech.com;giridhar@angleritech.com;balu@angleritech.com;prashanth@angleritech.com";
                //txtManagementCc.Text = "jayachandran@angleritech.com;giridhar@angleritech.com;balu@angleritech.com;prashanth@angleritech.com";
            }
            UserRights();
            SanctionViewDetails();
            //Private Notes checkbox disbaled
            Page.RegisterStartupScript("HidePrivateNotes", "<script>hidedivPrivateNotes();</script>");
        }
        if (IsPostBack)
        {
            //Private Notes checkbox disbaled
            Page.RegisterStartupScript("ShowHidePrivateNotes", "<script>showhidedivPrivateNotes();</script>");
        }
        // dynamic controls for leave conversation
        ControlCreation();
        if (Session["UserGroupName"].ToString() == "SuperAdmin" || Session["HasSpecialRights"].ToString() == "True")
        {
        }
        else if (ViewState["vsCommentsBy"] != null)
        {
            if (Convert.ToInt32(ViewState["vsCommentsBy"]) != 1 && Convert.ToInt32(ViewState["vsCommentsBy"]) != 2)
            {
                //rblStatus.Items.Clear();
                rbtnP.Enabled = false;
                rbtnUPWI.Enabled = false;
                rbtnUPWOI.Enabled = false;
            }
        }
        //if (rblStatus.Items.Count == 0)
        //{
        //    divStatus.Visible = false;
        //    chkBoxPrivateNotes.Checked = true;
        //    chkBoxPrivateNotes.Enabled = false;
        //    divToMail.Style.Add("display", "block");
        //}
    }
    #endregion
    #region User Defined Functions
    protected void GenerateMenu()
    {
        //Get Year Setting Details for Menu constructing and Year Setting Display
        cls_Common objClassCommon = new cls_Common();
        DataSet ds_Year = new DataSet();
        string strYearData = string.Empty;
        string StartYear = string.Empty, EndYear = string.Empty, StartMonth = string.Empty, EndMonth = string.Empty;
        ds_Year = objClassCommon.GetYearsetting();
        if (ds_Year.Tables[0].Rows.Count > 0)
        {
            Session["YearSettingsId"] = Convert.ToInt32(ds_Year.Tables[0].Rows[0]["YearSettings_Id"]);
            Session["YearSettingFromDate"] = Convert.ToString(ds_Year.Tables[0].Rows[0]["YearSettingFromDate"]);
            Session["YearSettingToDate"] = Convert.ToString(ds_Year.Tables[0].Rows[0]["YearSettingToDate"]);
            StartYear = ds_Year.Tables[0].Rows[0]["StartYear"].ToString();
            StartMonth = ds_Year.Tables[0].Rows[0]["StartMonth"].ToString();
            EndYear = ds_Year.Tables[0].Rows[0]["EndYear"].ToString();
            EndMonth = ds_Year.Tables[0].Rows[0]["EndMonth"].ToString();
            Session["SearchFromDate"] = Convert.ToDateTime(ds_Year.Tables[0].Rows[0]["FromDate"]);
            strYearData = StartMonth + " " + StartYear + " - " + EndMonth + " " + EndYear;
            string sYearValue = Convert.ToString(Cache["ActiveYearSetting"]);
            if (sYearValue == null || sYearValue == String.Empty)
            {
                TimeSpan SessTimeOut = new TimeSpan(0, 0, HttpContext.Current.Session.Timeout, 0, 0);
                HttpContext.Current.Cache.Insert("ActiveYearSetting", strYearData, null, DateTime.MaxValue, SessTimeOut, System.Web.Caching.CacheItemPriority.NotRemovable, null); // cache handling
            }
            else if (strYearData != sYearValue)
            {
                TimeSpan SessTimeOut = new TimeSpan(0, 0, HttpContext.Current.Session.Timeout, 0, 0);
                HttpContext.Current.Cache.Remove("ActiveYearSetting");
                HttpContext.Current.Cache.Insert("ActiveYearSetting", strYearData, null, DateTime.MaxValue, SessTimeOut, System.Web.Caching.CacheItemPriority.NotRemovable, null); // cache handling
            }
        }
        else
        {
            TimeSpan SessTimeOut = new TimeSpan(0, 0, HttpContext.Current.Session.Timeout, 0, 0);
            HttpContext.Current.Cache.Remove("ActiveYearSetting");
            HttpContext.Current.Cache.Insert("ActiveYearSetting", "", null, DateTime.MaxValue, SessTimeOut, System.Web.Caching.CacheItemPriority.NotRemovable, null); // cache handling
            Session["SearchFromDate"] = (Convert.ToDateTime(System.DateTime.Now.ToShortDateString())).ToString(Session["MDateFormat"].ToString());
        }
    }
    private void LoadYear()
    {
        Label lblYear = (Label)this.Master.FindControl("lblYear");
        Label lblYearData = (Label)this.Master.FindControl("lblYearData");
        //Year Setting Display in Main Menu
        string sYearValue = Convert.ToString(Cache["ActiveYearSetting"]);
        if (sYearValue != null && sYearValue != "")
        {
            lblYear.Text = rm.GetString("Year", ci);
            lblYearData.Text = sYearValue;
            if (lblYearData.Text.Contains("January"))
            {
                lblYearData.Text = lblYearData.Text.Replace("January", "Jan");
            }
            if (lblYearData.Text.Contains("February"))
            {
                lblYearData.Text = lblYearData.Text.Replace("February", "Feb");
            }
            if (lblYearData.Text.Contains("March"))
            {
                lblYearData.Text = lblYearData.Text.Replace("March", "Mar");
            }
            if (lblYearData.Text.Contains("April"))
            {
                lblYearData.Text = lblYearData.Text.Replace("April", "Apr");
            }
            if (lblYearData.Text.Contains("May"))
            {
                lblYearData.Text = lblYearData.Text.Replace("May", "May");
            }
            if (lblYearData.Text.Contains("June"))
            {
                lblYearData.Text = lblYearData.Text.Replace("June", "Jun");
            }
            if (lblYearData.Text.Contains("July"))
            {
                lblYearData.Text = lblYearData.Text.Replace("July", "Jul");
            }
            if (lblYearData.Text.Contains("August"))
            {
                lblYearData.Text = lblYearData.Text.Replace("August", "Aug");
            }
            if (lblYearData.Text.Contains("September"))
            {
                lblYearData.Text = lblYearData.Text.Replace("September", "Sep");
            }
            if (lblYearData.Text.Contains("October"))
            {
                lblYearData.Text = lblYearData.Text.Replace("October", "Oct");
            }
            if (lblYearData.Text.Contains("November"))
            {
                lblYearData.Text = lblYearData.Text.Replace("November", "Nov");
            }
            if (lblYearData.Text.Contains("December"))
            {
                lblYearData.Text = lblYearData.Text.Replace("December", "Dec");
            }
        }
        else
        {
            lblYearData.Text = string.Empty;
        }
    }
    private void loadMenu()
    {
        //Session["MenuCreate"] = "1";
        CultureInfo ci;
        string source_Language;
        source_Language = Convert.ToString(Session["Session_ActiveLanguage"]);
        rm = new ResourceManager(source_Language, System.Reflection.Assembly.Load("App_GlobalResources"));
        ci = Thread.CurrentThread.CurrentCulture;
        //if Standard Demo
        string strType = string.Empty;
        if (Session["Demo"] != null)
        {
            if (Session["Demo"].ToString() == "Standard")
            {
                strType = "Standard";
            }
            else if (Session["Demo"].ToString() == "Express")
            {
                strType = "Express";
            }
        }
        cls_Common getmenu = new cls_Common();
        DataSet ds = new DataSet();
        DataSet dsChildMenus = new DataSet();
        DataSet dsReportsMenu = new DataSet();
        DataSet dsReportsSubMenu = new DataSet();
        int intReportsMenu = 0;
        int intReportsSubMenu = 0;
        int MenuNo = 1;
        string strMenu = string.Empty;
        if (source_Language == "Resources.Resource_AR")
        {
            strMenu += "<ul class='sidebar-menu' id='MainMenu' runat='server'>";
            strMenu = "<ul class='treeview-menu'>";
            if (Convert.ToInt16(Session["userGroup_Id"]) != 0)
            {
                ds = getmenu.getUserMenu(0, Convert.ToInt16(Session["userGroup_Id"]), strType);
                for (int iloop = 0; iloop <= ds.Tables[0].Rows.Count - 1; iloop++)
                {
                    String txt = ds.Tables[0].Rows[iloop]["displayName"].ToString();
                    strMenu += "<li class='hasmore'><a href='" + ds.Tables[0].Rows[iloop]["path"] + "' title='" + rm.GetString(txt, ci) + " '><span>" + rm.GetString(txt, ci) + "</span> </a>";
                    dsChildMenus = getmenu.getUserMenu(Convert.ToInt32(ds.Tables[0].Rows[iloop]["pageid"]), Convert.ToInt16(Session["userGroup_Id"]), strType);
                    strMenu += "<ul class='treeview-menu'>";
                    for (int iloopChild = 0; iloopChild <= dsChildMenus.Tables[0].Rows.Count - 1; iloopChild++)
                    {
                        string txtChild = dsChildMenus.Tables[0].Rows[iloopChild]["displayName"].ToString();
                        string[] splittedPath = ds.Tables[0].Rows[iloop]["path"].ToString().Split("/".ToCharArray());
                        //strMenu += "<li><a href='" + dsChildMenus.Tables[0].Rows[iloopChild]["path"] + "' title='" + rm.GetString(txtChild, ci) + " '>" + rm.GetString(txtChild, ci) + " </a></li>";
                        if (dsChildMenus.Tables[0].Rows[iloopChild]["path"].ToString() != string.Empty)
                        {
                            strMenu += "<li class='hasmore'><a href='" + dsChildMenus.Tables[0].Rows[iloopChild]["path"] + "' title='" + rm.GetString(txtChild, ci) + " '>" + rm.GetString(txtChild, ci) + " </a>";
                        }
                        else
                        {
                            strMenu += "<li class='hasmore'><a title='" + rm.GetString(txtChild, ci) + " '><span class='nav-arrow'>" + rm.GetString(txtChild, ci) + " </span></a>";
                        }
                        dsReportsMenu = getmenu.getReportMenu("ReportsMenu", Convert.ToInt16(Session["userGroup_Id"]));
                        for (intReportsMenu = 0; intReportsMenu <= dsReportsMenu.Tables[0].Rows.Count - 1; intReportsMenu++)
                        {
                            if (dsChildMenus.Tables[0].Rows[iloopChild]["pageId"].ToString() == dsReportsMenu.Tables[0].Rows[intReportsMenu]["ParentIdForSubMenu"].ToString())
                            {
                                dsReportsSubMenu = getmenu.getReportMenu(dsReportsMenu.Tables[0].Rows[intReportsMenu]["ParentIdForSubMenu"].ToString(), Convert.ToInt16(Session["userGroup_Id"]));
                                strMenu += "<ul class='dropdown'>";
                                for (intReportsSubMenu = 0; intReportsSubMenu <= dsReportsSubMenu.Tables[0].Rows.Count - 1; intReportsSubMenu++)
                                {
                                    string txtChild1 = dsReportsSubMenu.Tables[0].Rows[intReportsSubMenu]["displayName"].ToString();
                                    strMenu += "<li class='hasmore'><a href='" + dsReportsSubMenu.Tables[0].Rows[intReportsSubMenu]["path"] + "' title='" + rm.GetString(txtChild1, ci) + " '>" + rm.GetString(txtChild1, ci) + "</a></li>";
                                }
                                strMenu += "</ul>";
                            }
                        }
                        strMenu += "</li>";
                    }
                    strMenu += "</ul>";
                    strMenu += "</li>";
                    //dsChildMenus.Clear();
                    dsChildMenus.Dispose();
                    MenuNo = MenuNo + 1;
                }
            }
            strMenu += "</ul>";
            strMenu += "</div>";
        }
        else
        {
            if (Convert.ToInt16(Session["userGroup_Id"]) != 0)
            {
                ds = getmenu.getUserMenu(0, Convert.ToInt16(Session["userGroup_Id"]), strType);
                for (int iloop = 0; iloop <= ds.Tables[0].Rows.Count - 1; iloop++)
                {
                    String txt = Convert.ToString(ds.Tables[0].Rows[iloop]["displayName"]);
                    string title = txt + "_Title";
                    string Icon = txt + "_Icon";
                    dsChildMenus = getmenu.getUserMenu(Convert.ToInt32(ds.Tables[0].Rows[iloop]["pageid"]), Convert.ToInt16(Session["userGroup_Id"]), strType);
                    if (dsChildMenus.Tables[0].Rows.Count > 0)
                    {
                        strMenu += "<li id='" + Convert.ToString(ds.Tables[0].Rows[iloop]["displayName"]) + "'><a class='menu-hed' href='" + ds.Tables[0].Rows[iloop]["path"] + "' id='" + Convert.ToString(ds.Tables[0].Rows[iloop]["pageid"]) + "' title='" + rm.GetString(title, ci) + " '><img class='icon' src='dist/img/" + rm.GetString(Icon, ci) + "'><span>" + rm.GetString(txt, ci) + "</span><i class='fa fa-angle-right pull-right'></i></a>";
                        strMenu += "<ul class='treeview-menu'>";
                    }
                    else
                    {
                        strMenu += "<li id='" + Convert.ToString(ds.Tables[0].Rows[iloop]["displayName"]) + "'><a class='menu-hed' href='" + ds.Tables[0].Rows[iloop]["path"] + "' id='" + Convert.ToString(ds.Tables[0].Rows[iloop]["pageid"]) + "' title='" + rm.GetString(title, ci) + " '><img class='icon' src='dist/img/" + rm.GetString(Icon, ci) + "'><span>" + rm.GetString(txt, ci) + "</span></a>";
                    }
                    for (int iloopChild = 0; iloopChild <= dsChildMenus.Tables[0].Rows.Count - 1; iloopChild++)
                    {
                        string txtChild = Convert.ToString(dsChildMenus.Tables[0].Rows[iloopChild]["displayName"]);
                        string titlechild = txtChild + "_Title";
                        string[] splittedPath = Convert.ToString(ds.Tables[0].Rows[iloop]["path"]).Split("/".ToCharArray());
                        if (dsChildMenus.Tables[0].Rows[iloopChild]["path"].ToString() != string.Empty)
                        {
                            strMenu += "<li id='" + Convert.ToString(dsChildMenus.Tables[0].Rows[iloopChild]["displayName"]) + "'><a href='" + dsChildMenus.Tables[0].Rows[iloopChild]["path"] + "' id='" + Convert.ToString(dsChildMenus.Tables[0].Rows[iloopChild]["pageid"]) + "' title='" + rm.GetString(titlechild, ci) + " '><i class='fa fa-circle-o'></i>" + rm.GetString(txtChild, ci) + " </a>";
                        }
                        else
                        {
                            strMenu += "<li id='" + Convert.ToString(dsChildMenus.Tables[0].Rows[iloopChild]["displayName"]) + "'><a id='" + Convert.ToString(dsChildMenus.Tables[0].Rows[iloopChild]["pageid"]) + "' title='" + rm.GetString(titlechild, ci) + " '><i class='fa fa-circle-o'></i>" + rm.GetString(txtChild, ci) + " <i class='fa fa-angle-right pull-right' style='padding-left:10px' ></i></a>";
                        }
                        dsReportsSubMenu = getmenu.getUserMenu(Convert.ToInt32(dsChildMenus.Tables[0].Rows[iloopChild]["pageId"]), Convert.ToInt16(Session["userGroup_Id"]), strType);
                        if (dsReportsSubMenu.Tables[0].Rows.Count > 0)
                        {
                            strMenu += "<ul class='treeview-menu' id='" + dsChildMenus.Tables[0].Rows[iloopChild]["displayname"].ToString() + "' style='padding:10px'>";
                            for (intReportsSubMenu = 0; intReportsSubMenu <= dsReportsSubMenu.Tables[0].Rows.Count - 1; intReportsSubMenu++)
                            {
                                string txtChild1 = Convert.ToString(dsReportsSubMenu.Tables[0].Rows[intReportsSubMenu]["displayName"]);
                                string titlechild1 = txtChild1 + "_Title";
                                strMenu += "<li class='active' id='" + Convert.ToString(dsReportsSubMenu.Tables[0].Rows[intReportsSubMenu]["displayName"]) + "' style='padding-left:8px'><a href='" + dsReportsSubMenu.Tables[0].Rows[intReportsSubMenu]["path"] + "' id='" + Convert.ToString(dsReportsSubMenu.Tables[0].Rows[intReportsSubMenu]["pageid"]) + "' title='" + rm.GetString(titlechild1, ci) + " '><i class='fa fa-circle-o'></i>" + rm.GetString(txtChild1, ci) + "</a></li>";
                            }
                            if (dsReportsSubMenu.Tables[0].Rows.Count == 2)
                            {
                                strMenu += "<li class='line-spec'></li>";
                            }
                            strMenu += "</ul>";
                        }
                        strMenu += "</li>";
                    }
                    if (dsChildMenus.Tables[0].Rows.Count > 0)
                    {
                        strMenu += "</ul>";
                    }
                    strMenu += "</li>";
                    dsChildMenus.Dispose();
                    MenuNo = MenuNo + 1;
                }
            }
        }
        ds.Clear();
        ds.Dispose();
        Session["TopMenu"] = strMenu;
        Session["TopMenuPrevious"] = strMenu;
    }
    private void ControlCreation()
    {
        //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;
        // getting leave conversation 
        dsLeaveConversation = objLeaveApplicationEventData.GetLeaveConversation(LeaveApplication_Id);
        if (dsLeaveConversation.Tables[0].Rows.Count > 0)
        {
            Table leaveConversation = new Table();
            leaveConversation.BorderWidth = 1;
            leaveConversation.BorderColor = System.Drawing.Color.White;
            leaveConversation.CellPadding = 5;
            leaveConversation.CellSpacing = 0;
            //leaveConversation.Width = Unit.Pixel(720);
            leaveConversation.CssClass = "table das-table1";
            leaveConversation.Attributes.Add("border", "1");
            TableHeaderRow leaveConversationHr = new TableHeaderRow();
            leaveConversationHr.CssClass = "empheader";
            TableHeaderCell leaveConversationHeading3 = new TableHeaderCell();
            leaveConversationHeading3.Text = rm.GetString("TerminalDataType_Date_And_Time", ci);
            //leaveConversationHeading3.Width = 120;
            leaveConversationHeading3.HorizontalAlign = HorizontalAlign.Left;
            leaveConversationHr.Cells.Add(leaveConversationHeading3);
            TableHeaderCell leaveConversationHeading1 = new TableHeaderCell();
            //leaveConversationHeading1.Width = 100;
            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 = 500;
            leaveConversationHeading2.HorizontalAlign = HorizontalAlign.Left;
            leaveConversationHr.Cells.Add(leaveConversationHeading2);
            leaveConversation.Rows.Add(leaveConversationHr);
            if (dsLeaveConversation != null && dsLeaveConversation.Tables.Count > 0)
            {
                if (dsLeaveConversation.Tables[0].Rows.Count > 0)
                {
                    int rowIndex = 0;
                    foreach (DataRow drLeaveConversation in dsLeaveConversation.Tables[0].Rows)
                    {
                        dRowReplyResend = dtReplyResend.NewRow();
                        TableRow trLeaveConversation = new TableRow();
                        TableCell tcLeaveConversationRepliedOn = new TableCell();
                        Label lblLeaveConversationRepliedOn = new Label();
                        tcLeaveConversationRepliedOn.BorderWidth = 1;
                        tcLeaveConversationRepliedOn.BorderColor = System.Drawing.Color.White;
                        tcLeaveConversationRepliedOn.Width = 200;
                        //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.BorderWidth = 1;
                        tcLeaveConversationCommentsBy.BorderColor = System.Drawing.Color.White;
                        tcLeaveConversationCommentsBy.Width = 200;
                        //lblLeaveConversationCommentsBy.ID = "lblLeaveConversationCommentsBy" + rowIndex;
                        if (drLeaveConversation["CommentsBy"].ToString() == "0")
                        {
                            //lblLeaveConversationCommentsBy.Text = lbl_EmployeeName.Text;
                            //dRowReplyResend["Comments By"] = lbl_EmployeeName.Text;
                            lblLeaveConversationCommentsBy.Text = objLeaveApplicationEventData.GetEmployeeName(Convert.ToInt32(drLeaveConversation["Emp_Id"].ToString()));
                            dRowReplyResend["Comments By"] = objLeaveApplicationEventData.GetEmployeeName(Convert.ToInt32(drLeaveConversation["Emp_Id"].ToString()));
                        }
                        else if (drLeaveConversation["CommentsBy"].ToString() == "1")
                        {
                            lblLeaveConversationCommentsBy.Text = objLeaveApplicationEventData.GetEmployeeName(Convert.ToInt32(drLeaveConversation["Emp_Id"].ToString()));
                            dRowReplyResend["Comments By"] = objLeaveApplicationEventData.GetEmployeeName(Convert.ToInt32(drLeaveConversation["Emp_Id"].ToString()));
                        }
                        else if (drLeaveConversation["CommentsBy"].ToString() == "2")
                        {
                            lblLeaveConversationCommentsBy.Text = objLeaveApplicationEventData.GetEmployeeName(Convert.ToInt32(drLeaveConversation["Emp_Id"].ToString()));
                            dRowReplyResend["Comments By"] = objLeaveApplicationEventData.GetEmployeeName(Convert.ToInt32(drLeaveConversation["Emp_Id"].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();
                        tcLeaveConversationComments.BorderWidth = 1;
                        tcLeaveConversationComments.BorderColor = System.Drawing.Color.White;
                        //tcLeaveConversationComments.ColumnSpan = 2;
                        // tcLeaveConversationComments.Width = 500;
                        //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);
        }
        else
        {
            divLeaveConversation.Visible = false;
        }
        if (dsLeaveConversation.Tables[0].Rows.Count > 0)
        {
            blnPrivateNotes = true;
            strHtml = buildPage("ReplyResend", dtReplyResend);
            blnPrivateNotes = false;
        }
    }
    private void PrivateNotesControlCreation()
    {
        //New Data table definition
        DataTable dtReplyResend = new DataTable();
        dtReplyResend.TableName = "dtPrivateNotes";
        DataColumn dcDate = new DataColumn("Date");
        DataColumn dcCommentsBy = new DataColumn("Notes By");
        DataColumn dcComments = new DataColumn("Notes");
        dtReplyResend.Columns.Add(dcDate);
        dtReplyResend.Columns.Add(dcCommentsBy);
        dtReplyResend.Columns.Add(dcComments);
        DataRow dRowReplyResend;
        // getting leave conversation 
        dsLeavePrivateNotes = objLeaveApplicationEventData.GetLeavePrivateNotes(LeaveApplication_Id);
        if (dsLeavePrivateNotes.Tables[0].Rows.Count > 0)
        {
            //if (dsLeavePrivateNotes.Tables[0].Rows[0]["FromMailId"].ToString() != null && dsLeavePrivateNotes.Tables[0].Rows[0]["FromMailId"].ToString() != string.Empty)
            //{
            //    txtApprovalTO.Text = dsLeavePrivateNotes.Tables[0].Rows[0]["FromMailId"].ToString();
            //}
            Table leaveConversation = new Table();
            leaveConversation.BorderWidth = 1;
            leaveConversation.BorderColor = System.Drawing.Color.White;
            leaveConversation.CellPadding = 5;
            leaveConversation.CellSpacing = 0;
            //leaveConversation.Width = Unit.Pixel(720);
            leaveConversation.CssClass = "table das-table1";
            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.Text = "Notes By";
            leaveConversationHeading1.HorizontalAlign = HorizontalAlign.Left;
            leaveConversationHr.Cells.Add(leaveConversationHeading1);
            TableHeaderCell leaveConversationHeading2 = new TableHeaderCell();
            leaveConversationHeading2.Text = "Notes";
            leaveConversationHeading2.HorizontalAlign = HorizontalAlign.Left;
            leaveConversationHr.Cells.Add(leaveConversationHeading2);
            leaveConversation.Rows.Add(leaveConversationHr);
            if (dsLeavePrivateNotes != null && dsLeavePrivateNotes.Tables.Count > 0)
            {
                if (dsLeavePrivateNotes.Tables[0].Rows.Count > 0)
                {
                    blnCheckPrivateNotes = false;
                    int rowIndex = 0;
                    foreach (DataRow drLeaveConversation in dsLeavePrivateNotes.Tables[0].Rows)
                    {
                        if (rowIndex == 1)
                        {
                            break;
                        }
                        dRowReplyResend = dtReplyResend.NewRow();
                        TableRow trLeaveConversation = new TableRow();
                        TableCell tcNotesConversationRepliedOn = new TableCell();
                        Label lblNotesConversationRepliedOn = new Label();
                        tcNotesConversationRepliedOn.BorderWidth = 1;
                        tcNotesConversationRepliedOn.BorderColor = System.Drawing.Color.White;
                        tcNotesConversationRepliedOn.Width = 200;
                        lblNotesConversationRepliedOn.ID = "lblNotesConversationRepliedOn" + rowIndex;
                        lblNotesConversationRepliedOn.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());
                        tcNotesConversationRepliedOn.Controls.Add(lblNotesConversationRepliedOn);
                        trLeaveConversation.Cells.Add(tcNotesConversationRepliedOn);
                        if (drLeaveConversation["NotesBy"].ToString() == Session["EmpAutoId"].ToString())
                        {
                            blnCheckPrivateNotes = true;
                        }
                        if (drLeaveConversation["ToMailIds"].ToString().Contains(Session["loginEmailId"].ToString()))
                        {
                            blnCheckPrivateNotes = true;
                        }
                        if (drLeaveConversation["CcMailIds"].ToString().Contains(Session["loginEmailId"].ToString()))
                        {
                            blnCheckPrivateNotes = true;
                        }
                        //TableRow trLeaveConversation = new TableRow();
                        TableCell tcLeaveConversationCommentsBy = new TableCell();
                        Label lblLeaveConversationCommentsBy = new Label();
                        tcLeaveConversationCommentsBy.BorderWidth = 1;
                        tcLeaveConversationCommentsBy.BorderColor = System.Drawing.Color.White;
                        tcLeaveConversationCommentsBy.Width = 200;
                        lblLeaveConversationCommentsBy.ID = "lblLeaveConversationNotesBy" + rowIndex;
                        lblLeaveConversationCommentsBy.Text = drLeaveConversation["NotesBy"].ToString();
                        dRowReplyResend["Notes By"] = drLeaveConversation["NotesBy"].ToString();
                        //if (drLeaveConversation["NotesBy"].ToString() == "0")
                        //{
                        //    lblLeaveConversationCommentsBy.Text = lbl_EmployeeName.Text;
                        //    dRowReplyResend["Notes By"] = lbl_EmployeeName.Text;
                        //}
                        //else if (drLeaveConversation["NotesBy"].ToString() == "1")
                        //{
                        //    lblLeaveConversationCommentsBy.Text = ViewState["reportingToEmployee"].ToString();
                        //    dRowReplyResend["Notes By"] = ViewState["reportingToEmployee"].ToString();
                        //}
                        //else if (drLeaveConversation["NotesBy"].ToString() == "2")
                        //{
                        //    lblLeaveConversationCommentsBy.Text = ViewState["sanctioningEmployee"].ToString();
                        //    dRowReplyResend["Notes By"] = ViewState["sanctioningEmployee"].ToString();
                        //}
                        //else if (drLeaveConversation["NotesBy"].ToString() == "3")
                        //{
                        //    lblLeaveConversationCommentsBy.Text = objLeaveApplicationEventData.GetEmployeeName(Convert.ToInt32(drLeaveConversation["Emp_Id"].ToString()));
                        //    dRowReplyResend["Notes 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();
                        tcLeaveConversationComments.BorderWidth = 1;
                        tcLeaveConversationComments.BorderColor = System.Drawing.Color.White;
                        tcLeaveConversationComments.ColumnSpan = 1;
                        lblLeaveConversationComments.ID = "lblLeaveConversationNotes" + rowIndex;
                        lblLeaveConversationComments.Text = drLeaveConversation["Notes"].ToString();
                        dRowReplyResend["Notes"] = drLeaveConversation["Notes"].ToString();
                        tcLeaveConversationComments.Controls.Add(lblLeaveConversationComments);
                        trLeaveConversation.Cells.Add(tcLeaveConversationComments);
                        leaveConversation.Rows.Add(trLeaveConversation);
                        rowIndex += 1;
                        dtReplyResend.Rows.Add(dRowReplyResend);
                    }
                }
            }
            divNotesConversation.Controls.Add(leaveConversation);
        }
        else
        {
            divNotesConversation.Visible = false;
        }
        if (dsLeavePrivateNotes.Tables[0].Rows.Count > 0)
        {
            blnPrivateNotes = true;
            strHtmlPrivateNotes = buildPage("PrivateNotes", dtReplyResend);
            blnPrivateNotes = false;
        }
    }
    /// <summary>
    /// Display Leave permission Details
    /// </summary>
    private void SanctionViewDetails()
    {
        //For SuperAdmin Login 
        DataSet dsEmployeeGroup = new DataSet();
        dsEmployeeGroup = objLeaveApplicationEventData.GetEmployeeGroupName(Convert.ToInt32(Session["EmpAutoId"]));
        DataSet ds_PermissionSettings = new DataSet();
        DataTable dt_PermissionSettings = new DataTable();
        DataTable dt_ApprovalAuthority = new DataTable();
        int intLoginEmpId = 0, intAuditEmpId = 0;
        string strApprovalCC = string.Empty;
        dtSanctionView = objLeaveApplicationEventData.GetLeaveApplicationByLeaveApplicationId(LeaveApplication_Id);
        if (dtSanctionView.Rows.Count > 0)
        {
            for (int i = 0; i < dtSanctionView.Rows.Count; i++)
            {
                if (LeaveApplicationIDs == string.Empty || LeaveApplicationIDs == null)
                {
                    LeaveApplicationIDs = dtSanctionView.Rows[i]["CheckedIDs"].ToString();
                }
                else
                {
                    LeaveApplicationIDs = LeaveApplicationIDs + ',' + dtSanctionView.Rows[i]["CheckedIDs"].ToString();
                }
            }
            Session["LeaveApplicationIDs"] = LeaveApplicationIDs;
        }
        if (dtSanctionView.Rows.Count == 0)
        {
            string strScript = string.Empty;
            strScript = strScript + "<script language='javascript'>";
            strScript = strScript + "alert('No records found');";
            strScript = strScript + "location.replace('TA_UI_Transactions_LeaveSanction.aspx')";
            strScript = strScript + "</script>";
            //Dispaly alert messsage.
            Page.RegisterStartupScript("AlertPA5dd3674", strScript);
            return;
        }
        ViewState["dtSanctionView"] = dtSanctionView;
        if (dtSanctionView.Rows[0]["LeaveAvailedMonth"].ToString() != string.Empty)
        {
            lblLeaveAvailedMonthData.Text = dtSanctionView.Rows[0]["LeaveAvailedMonth"].ToString();
        }
        else
        {
            lblLeaveAvailedMonthData.Text = "0.0";
        }
        if (dtSanctionView.Rows[0]["LeaveAvailedYear"].ToString() != string.Empty)
        {
            lblLeaveAvailedYearData.Text = dtSanctionView.Rows[0]["LeaveAvailedYear"].ToString();
        }
        else
        {
            lblLeaveAvailedYearData.Text = "0.0";
        }
        //if (dtSanctionView.Rows.Count == 0)
        //{
        //    string strScript = string.Empty;
        //    strScript = strScript + "<script language='javascript'>";
        //    strScript = strScript + "alert('Leave already cancelled');";            
        //    strScript = strScript + "location.replace('TA_UI_Transactions_LeaveSanction.aspx')";
        //    strScript = strScript + "</script>";
        //    //Dispaly alert messsage.
        //    Page.RegisterStartupScript("AlertPA5dd3674", strScript);
        //    return;
        //}
        grv_LeaveApplication.DataSource = dtSanctionView;
        grv_LeaveApplication.DataBind();
        //ViewState["vSLeaveDetails"] = (DataTable)grv_LeaveApplication.DataSource;
        Session["vSLeaveDetails"] = (DataTable)grv_LeaveApplication.DataSource;
        // Get the Employee Id
        int intEmployeeId = 0;
        if (dtSanctionView.Rows[0]["Employee_Id"] != DBNull.Value)
        {
            intEmployeeId = int.Parse(dtSanctionView.Rows[0]["Employee_Id"].ToString());
            ViewState["vSEmployeeId"] = intEmployeeId;
        }
        // Get the Employee Auto Id who have Logged In from Session
        intLoginEmpId = Convert.ToInt32(Session["EmpAutoId"]);
        if (intEmployeeId == intLoginEmpId)
        {
            Response.Redirect("TransactionLandingPage.aspx");
        }
        // Get the Employee Id who have last updated the Permission Application
        if (dtSanctionView.Rows[0]["Emp_Id"] != DBNull.Value)
        {
            intAuditEmpId = int.Parse(dtSanctionView.Rows[0]["Emp_Id"].ToString());
        }
        ViewState["vwReason"] = dtSanctionView.Rows[0]["Reason"].ToString();
        // Generate status radio button based on the first or second level authority
        int intApproval = 0, intAuthorityLevel = 0, intFirstLevelAuthorityId = 0, intSecondLevelAuthorityId = 0;
        // Get the Parent Company Id for the Employee by passing the Level Id
        org_levelsEventData getOrg = new org_levelsEventData();
        DataSet ds_getOrg = new DataSet();
        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();
        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;
        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]["Approval"] != DBNull.Value && dt_PermissionSettings.Rows[0]["Approval"].ToString() != string.Empty)
            {
                if (dt_PermissionSettings.Rows[0]["Approval"].ToString() == "False")
                {
                    // Both First and Second Level Authority Approval
                    intApproval = 0;
                }
                else if (dt_PermissionSettings.Rows[0]["Approval"].ToString() == "True")
                {
                    // First or Second Level Authority Approval - Either or one
                    intApproval = 1;
                }
                else
                {
                    // Nothing
                }
            }
            if (dt_PermissionSettings.Rows[0]["ApprovalCC"] != DBNull.Value && dt_PermissionSettings.Rows[0]["ApprovalCC"].ToString() != string.Empty)
            {
                strApprovalCC = dt_PermissionSettings.Rows[0]["ApprovalCC"].ToString();
                ViewState["vsStrApprovalCC"] = strApprovalCC;
            }
            else
            {
                ViewState["vsStrApprovalCC"] = string.Empty;
            }
        }
        // Get First and Second Level Authority Ids
        dt_ApprovalAuthority = objLeaveApplicationEventData.GetApprovalAuthorityIds(intEmployeeId);
        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"] = dt_ApprovalAuthority.Rows[0]["ReportingToEmployee"].ToString();
            }
            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"] = dt_ApprovalAuthority.Rows[0]["SanctioningEmployee"].ToString();
            }
        }
        // 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;
        // If the Login employee is First Level Authority for the selected Applicant
        if (intAuthorityLevel == 1)
        {
            //rblStatus.Items.Clear();
            if (intApproval == 1)
            {
                //rblStatus.Items.Insert(0, "Approved");
                //rblStatus.Items.Insert(1, "Forwarded");
                //rblStatus.Items.Insert(2, "Pending");
                //rblStatus.Items.Insert(3, "Rejected");
                //rblStatus.Items.Insert(4, "Resend");
                //rblStatus.Items.Insert(5, "Reply");
                //rblStatus.Enabled = true;
                rbApproved.Enabled = true;
                rbForwarded.Enabled = true;
                rbPending.Enabled = true;
                rbRejected.Enabled = true;
                rbReply.Enabled = true;
                rbResend.Enabled = true;
            }
            else
            {
                //rblStatus.Items.Insert(0, "Forwarded");
                //rblStatus.Items.Insert(1, "Pending");
                //rblStatus.Items.Insert(2, "Rejected");
                //rblStatus.Items.Insert(3, "Resend");
                //rblStatus.Items.Insert(4, "Reply");
                //rblStatus.Enabled = true;
                rbApproved.Enabled = false;
                rbForwarded.Enabled = true;
                rbPending.Enabled = true;
                rbRejected.Enabled = true;
                rbReply.Enabled = true;
                rbResend.Enabled = true;
            }
        }
        // If the Login employee is Second Level Authority for the selected Applicant
        else if (intAuthorityLevel == 2)
        {
            //rblStatus.Items.Clear();
            if (intApproval == 1)
            {
                //rblStatus.Items.Insert(0, "Approved");
                //rblStatus.Items.Insert(1, "Pending");
                //rblStatus.Items.Insert(2, "Rejected");
                //rblStatus.Items.Insert(3, "Resend");
                //rblStatus.Items.Insert(4, "Reply");
                //rblStatus.Enabled = true;
                rbApproved.Enabled = true;
                rbForwarded.Enabled = false;
                rbPending.Enabled = true;
                rbRejected.Enabled = true;
                rbReply.Enabled = true;
                rbResend.Enabled = true;
            }
            else
            {
                //rblStatus.Items.Insert(0, "Approved");
                //rblStatus.Items.Insert(1, "Rejected");
                //rblStatus.Items.Insert(2, "Resend");
                //rblStatus.Items.Insert(3, "Reply");
                //rblStatus.Enabled = true;
                rbApproved.Enabled = true;
                rbForwarded.Enabled = false;
                rbPending.Enabled = false;
                rbRejected.Enabled = true;
                rbReply.Enabled = true;
                rbResend.Enabled = true;
            }
        }
        else if (intAuthorityLevel == 3)
        {
            //rblStatus.Items.Clear();
            //rblStatus.Items.Insert(0, "Approved");
            //rblStatus.Items.Insert(1, "Pending");
            //rblStatus.Items.Insert(2, "Rejected");
            //rblStatus.Items.Insert(3, "Resend");
            //rblStatus.Items.Insert(4, "Reply");
            //rblStatus.Enabled = true;
            rbApproved.Enabled = true;
            rbForwarded.Enabled = false;
            rbPending.Enabled = true;
            rbRejected.Enabled = true;
            rbReply.Enabled = true;
            rbResend.Enabled = true;
        }
        if (dsEmployeeGroup.Tables[0].Rows.Count > 0)
        {
            if (dsEmployeeGroup.Tables[0].Rows[0]["GroupName"].ToString() == "SuperAdmin" || Session["HasSpecialRights"].ToString() == "True")
            {
                //rblStatus.Items.Clear();
                //rblStatus.Items.Insert(0, "Approved");
                //rblStatus.Items.Insert(1, "Forwarded");
                //rblStatus.Items.Insert(2, "Pending");
                //rblStatus.Items.Insert(3, "Rejected");
                //rblStatus.Items.Insert(4, "Resend");
                //rblStatus.Items.Insert(5, "Reply");
                //rblStatus.Enabled = true;
                rbApproved.Enabled = true;
                rbForwarded.Enabled = true;
                rbPending.Enabled = true;
                rbRejected.Enabled = true;
                rbReply.Enabled = true;
                rbResend.Enabled = true;
                txtRemarks.ReadOnly = false;
            }
        }
        //rblStatus.Items.Clear();
        //rblStatus.Items.Insert(0, "Approved");
        //rblStatus.Items.Insert(1, "Forwarded");
        //rblStatus.Items.Insert(2, "Pending");
        //rblStatus.Items.Insert(3, "Rejected");
        //rblStatus.Items.Insert(4, "Resend");
        //rblStatus.Items.Insert(5, "Reply");
        rbApproved.Enabled = true;
        rbForwarded.Enabled = true;
        rbPending.Enabled = true;
        rbRejected.Enabled = true;
        rbReply.Enabled = true;
        rbResend.Enabled = true;
        //----------- 
        ViewState["Employee_code_Id"] = dtSanctionView.Rows[0]["Employee_code_Id"].ToString();
        ViewState["vsIntimationType"] = dtSanctionView.Rows[0]["IntimationType"].ToString();
        lblEmployeeIdData.Text = ViewState["Employee_code_Id"].ToString();
        hdnEmployeeId.Value = ViewState["Employee_code_Id"].ToString();
        lbl_EmployeeName.Text = dtSanctionView.Rows[0]["Employee_FirstName"].ToString();
        lblLevel.Text = dtSanctionView.Rows[0]["levelname"].ToString();
        //lblFromDate.Text = (DateTime.Parse(dtSanctionView.Rows[0]["LeaveFrom"].ToString())).ToString(Session["MDateFormat"].ToString());
        //lblToDate.Text = (DateTime.Parse(dtSanctionView.Rows[0]["LeaveTo"].ToString())).ToString(Session["MDateFormat"].ToString());
        //lblNoOfDaysValue.Text = dtSanctionView.Rows[0]["NumberOfDays"].ToString();
        //lblLeaveType.Text = dtSanctionView.Rows[0]["LeaveType"].ToString();
        lblReason.Text = dtSanctionView.Rows[0]["Reason"].ToString();
        lblLeaveApplicationDateData.Text = (DateTime.Parse(dtSanctionView.Rows[0]["Leave_ApplicationDate"].ToString())).ToString(Session["MDateFormat"].ToString());
        //txtRemarks.Text = dtSanctionView.Rows[0]["Remarks"].ToString();
        //lblSessionFrom.Text = dtSanctionView.Rows[0]["Leave_SessionFrom"].ToString();
        //lblSessionTo.Text = dtSanctionView.Rows[0]["Leave_SessionTo"].ToString();
        ViewState["StatusOnLoad"] = dtSanctionView.Rows[0]["Status"].ToString();
        //if (ViewState["vsIntimationType"].ToString() == "P")
        //{
        //    lblIntimationTypeData.Text ="Planned";
        //}
        //else
        //{
        //    lblIntimationTypeData.Text =ViewState["vsIntimationType"].ToString();
        //}
        //Intimation Type
        string intimationType = dtSanctionView.Rows[0]["IntimationType"].ToString();
        // get inputs from UI
        if (intimationType == "P")
        {
            rbtnP.Checked = true;
        }
        else if (intimationType == "UP-WI")
        {
            rbtnUPWI.Checked = true;
        }
        else if (intimationType == "UP-WOI")
        {
            rbtnUPWOI.Checked = true;
        }
        ViewState["StatusBorrow"] = dtSanctionView.Rows[0]["IsBorrow"].ToString();
        bool blnApproved = false;
        bool blnForwarded = false;
        if (dtSanctionView.Rows[0]["Status"].ToString() == "Pending")
        {
            //rblStatus.SelectedValue = "Pending";
            rbPending.Checked = true;
        }
        else if (dtSanctionView.Rows[0]["Status"].ToString() == "Forwarded")
        {
            blnForwarded = true;
            //rblStatus.SelectedValue = "Forwarded";
            rbForwarded.Checked = true;
            // rblStatus.Enabled = true;
            txtRemarks.ReadOnly = false;
        }
        else if (dtSanctionView.Rows[0]["Status"].ToString() == "Rejected")
        {
            //rblStatus.SelectedValue = "Rejected";
            rbRejected.Checked = true;
            //rblStatus.Enabled = true;
            txtRemarks.ReadOnly = false;
        }
        else if (dtSanctionView.Rows[0]["Status"].ToString() == "Approved")
        {
            //rblStatus.SelectedValue = "Approved";
            rbApproved.Checked = true;
            // rblStatus.Enabled = true;
            txtRemarks.ReadOnly = false;
        }
        else if (dtSanctionView.Rows[0]["Status"].ToString() == "Resend")
        {
            //rblStatus.SelectedValue = "Resend";
            rbResend.Checked = true;
            //rblStatus.Enabled = true;
            txtRemarks.ReadOnly = false;
        }
        else if (dtSanctionView.Rows[0]["Status"].ToString() == "Reply")
        {
            //rblStatus.SelectedValue = "Reply";
            rbReply.Checked = true;
            //  rblStatus.Enabled = true;
            txtRemarks.ReadOnly = false;
        }
        if (rbApproved.Checked == true)
        {
            rbApproved.Enabled = false;
            blnApproved = true;
        }
        if (rbForwarded.Checked == true)
        {
            rbForwarded.Enabled = false;
        }
        if (rbPending.Checked == true)
        {
            rbPending.Enabled = false;
        }
        if (rbRejected.Checked == true)
        {
            rbRejected.Enabled = false;
        }
        if (rbReply.Checked == true)
        {
            rbReply.Enabled = false;
        }
        if (rbResend.Checked == true)
        {
            rbResend.Enabled = false;
            divStatus.Visible = false;
        }
        rbPending.Enabled = false;
        rbReply.Enabled = false;
        if (intAuthorityLevel == 2)
        {
            //if (rbForwarded.Checked == true)
            //{
            rbForwarded.Enabled = false;
            //}
        }
        if (blnApproved == true)
        {
            //if (rbRejected.Checked != true)
            //{
            rbRejected.Enabled = true;
            rbApproved.Enabled = false;
            rbForwarded.Enabled = false;
            rbPending.Enabled = false;
            rbRejected.Enabled = true;
            rbReply.Enabled = false;
            rbResend.Enabled = false;
            //}
        }
        if (intAuthorityLevel == 1)
        {
            rbApproved.Enabled = false;
            rbRejected.Enabled = false;
            if (blnForwarded == true)
            {
                rbForwarded.Enabled = false;
            }
        }
        //if (rbApproved.Checked == true)
        //    rbApproved.Enabled = false;
        //if (rbForwarded.Checked == true)
        //    rbForwarded.Enabled = false;
        //if (rbPending.Checked == true)
        //    rbPending.Enabled = false;
        //if (rbRejected.Checked == true)
        //    rbRejected.Enabled = true;
        //if (rbReply.Checked == true)
        //    rbReply.Enabled = false;
        //if (rbResend.Checked == true)
        //    rbResend.Enabled = false;
        //if (intAuthorityLevel == 2)
        //{
        //    rbForwarded.Enabled = false;
        //}
        //if (blnApproved == true)
        //{
        //    rbRejected.Enabled = true;
        //}
        //if (intAuthorityLevel == 1)
        //{
        //    rbApproved.Enabled = false;
        //    rbRejected.Enabled = true;
        //    if (blnForwarded == true)
        //    {
        //        rbForwarded.Enabled = false;
        //    }
        //}
        //for (int i = 0; i < rblStatus.Items.Count; i++)
        //{
        //    if (rblStatus.Items[i].Selected == true)
        //    {
        //        rblStatus.Items[i].Enabled = false;
        //    }
        //    if (rblStatus.Items[i].Value == "Pending")
        //    {
        //        rblStatus.Items[i].Enabled = false;
        //    }
        //    if (rblStatus.Items[i].Selected == true)
        //    {
        //        if (rblStatus.Items[i].Value == "Resend")
        //        {
        //            rblStatus.Enabled = false;
        //            divStatus.Visible = false;
        //        }
        //        else if (rblStatus.Items[i].Value == "Approved")
        //        {
        //            blnApproved = true;
        //        }
        //    }
        //    if (rblStatus.Items[i].Value == "Reply")
        //    {
        //        rblStatus.Items[i].Enabled = false;
        //    }
        //    if (intAuthorityLevel == 2)
        //    {
        //        if (rblStatus.Items[i].Value == "Forwarded")
        //        {
        //            rblStatus.Items[i].Enabled = false;
        //        }
        //    }
        //    if (blnApproved == true)
        //    {
        //        if (rblStatus.Items[i].Value != "Rejected")
        //        {
        //            rblStatus.Items[i].Enabled = false;
        //        }
        //    }
        //    if (intAuthorityLevel == 1)
        //    {
        //        if (rblStatus.Items[i].Value == "Approved" || rblStatus.Items[i].Value == "Rejected")
        //        {
        //            rblStatus.Items[i].Enabled = false;
        //        }
        //        if (blnForwarded == true)
        //        {
        //            rblStatus.Items[i].Enabled = false;
        //        }
        //    }
        //}
        //Leave availed in month and year
        //dblLeaveAvailedYear = objLeaveApplicationEventData.GetLeaveSummary(DateTime.Parse(strYearSettingsFromdate), DateTime.Parse(strYearSettingsTodate), Convert.ToInt32(ViewState["vSEmployeeId"]));
        //string CurrentDate = DateTime.Now.ToString();
        //DateTime startDayOfMonth = new DateTime(DateTime.Parse(CurrentDate).Year, DateTime.Parse(CurrentDate).Month, 1);
        // DateTime endDayOfMonth = startDayOfMonth.AddMonths(1).AddDays(-1);
        // dblLeaveAvailedMonth = objLeaveApplicationEventData.GetLeaveSummary(startDayOfMonth, endDayOfMonth, Convert.ToInt32(ViewState["vSEmployeeId"]));
        //lblLeaveAvailedMonthData.Text = dblLeaveAvailedMonth.ToString();
        //lblLeaveAvailedYearData.Text = dblLeaveAvailedYear.ToString();
        if (intAuthorityLevel == 2)
        {
            if (dtSanctionView.Rows[0]["Status"].ToString() == "Pending")
            {
                hdnStatusofApplication.Value = "Pending";
                hdnAutorityLevel.Value = "2";
            }
        }
        if (dsEmployeeGroup.Tables[0].Rows.Count > 0)
        {
            if (dsEmployeeGroup.Tables[0].Rows[0]["GroupName"].ToString() == "SuperAdmin" || Session["HasSpecialRights"].ToString() == "True")
            {
            }
            else if (Convert.ToInt32(ViewState["vsCommentsBy"]) != 1 && Convert.ToInt32(ViewState["vsCommentsBy"]) != 2)
            {
                divStatus.Visible = false;
            }
        }
        else if (Session["HasSpecialRights"].ToString() == "True")
        {
        }
        else if (Convert.ToInt32(ViewState["vsCommentsBy"]) != 1 && Convert.ToInt32(ViewState["vsCommentsBy"]) != 2)
        {
            divStatus.Visible = false;
        }
        if (Session["UserGroupName"].ToString() != "SuperAdmin" && Session["HasSpecialRights"].ToString() == "False")
        {
            if (intAuthorityLevel == 0 && blnCheckPrivateNotes == false)
            {
                string strScript = string.Empty;
                strScript = strScript + "<script language='javascript'>";
                strScript = strScript + "alert('You do not have rights to access this Leave Request!');";
                strScript = strScript + "location.replace('TransactionLandingPage.aspx')";
                strScript = strScript + "</script>";
                //Dispaly alert messsage.
                Page.RegisterStartupScript("AlertPerA5dd365434access", strScript);
                return;
            }
        }
    }
    protected void rbRejected_OnCheckedChanged(object sender, EventArgs e)
    {
        rbApproved.Checked = false;
        rbForwarded.Checked = false;
        rbPending.Checked = false;
        rbRejected.Checked = true;
        rbReply.Checked = false;
        rbResend.Checked = false;
    }
    protected void rbPending_OnCheckedChanged(object sender, EventArgs e)
    {
        rbApproved.Checked = false;
        rbForwarded.Checked = false;
        rbPending.Checked = true;
        rbRejected.Checked = false;
        rbReply.Checked = false;
        rbResend.Checked = false;
    }
    protected void rbForwarded_OnCheckedChanged(object sender, EventArgs e)
    {
        rbApproved.Checked = false;
        rbForwarded.Checked = true;
        rbPending.Checked = false;
        rbRejected.Checked = false;
        rbReply.Checked = false;
        rbResend.Checked = false;
    }
    protected void rbApproved_OnCheckedChanged(object sender, EventArgs e)
    {
        rbApproved.Checked = true;
        rbForwarded.Checked = false;
        rbPending.Checked = false;
        rbRejected.Checked = false;
        rbReply.Checked = false;
        rbResend.Checked = false;
    }
    protected void rbResend_OnCheckedChanged(object sender, EventArgs e)
    {
        rbApproved.Checked = false;
        rbForwarded.Checked = false;
        rbPending.Checked = false;
        rbRejected.Checked = false;
        rbReply.Checked = false;
        rbResend.Checked = true;
    }
    protected void rbReply_OnCheckedChanged(object sender, EventArgs e)
    {
        rbApproved.Checked = false;
        rbForwarded.Checked = false;
        rbPending.Checked = false;
        rbRejected.Checked = false;
        rbReply.Checked = true;
        rbResend.Checked = false;
    }
    /// <summary>
    /// Sending email to the Employee who applied for this permission
    /// </summary>
    /// <param name="EmployeeEamilId"></param>
    /// <param name="Status"></param>
    /// 
    private void SendMailToApplicant(string EmployeeEamilId, string EmployeeName, string Status, string Remarks, string LeaveApplicationDate, string NoOfDays, string strLeaveType)
    {
        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 = "Leave Application Sanction By Reporting to Person";
            // cl.fillDT("Select * from TA_TBL_EmailScripts where ScriptType='Leave Application Sanction By Reporting to Person'", dtTableScript);
            dtTableScript = objLeaveApplicationEventData.GetEmailScripts(ScriptType);
            scriptText = dtTableScript.Rows[0]["ScriptText"].ToString();
            string Employee_Code_Id = ViewState["Employee_code_Id"].ToString();
            //mail.From = System.Configuration.ConfigurationManager.AppSettings["FromId"];
            //mail.To = EmployeeEamilId;
            //mail.Subject = "Your Leave Application For - " + lblFromDate.Text + " - " + lblToDate.Text + " | " + Status;
            //mail.BodyFormat = MailFormat.Html;
            //mail.Priority = MailPriority.Normal;
            mailMessage.From = new MailAddress(ConfigurationManager.AppSettings.Get("FromId"));
            mailMessage.To.Add(new MailAddress(EmployeeEamilId));
            //mailMessage.Subject = rm.GetString("email_YourLeaveApplicationFor", ci) + " - " + lblFromDate.Text + " - " + lblToDate.Text + " | " + Status;
            mailMessage.Body = scriptText.Replace("<<lblLeaveApplicationForm>>", rm.GetString("email_LeaveApplicationForm", ci));
            mailMessage.Body = mailMessage.Body.Replace("<<lblEmployeeId>>", rm.GetString("email_EmployeeId", ci));
            mailMessage.Body = mailMessage.Body.Replace("<<EmployeeId>>", Employee_Code_Id);
            mailMessage.Body = mailMessage.Body.Replace("<<lblEmployeeName>>", rm.GetString("email_EmployeeName", ci));
            mailMessage.Body = mailMessage.Body.Replace("<<EmployeeName>>", EmployeeName);
            mailMessage.Body = mailMessage.Body.Replace("<<lblApplicationDate>>", rm.GetString("email_LeaveApplicationDate", ci));
            mailMessage.Body = mailMessage.Body.Replace("<<ApplicationDate>>", DateTime.Parse(LeaveApplicationDate).ToShortDateString());
            mailMessage.Body = mailMessage.Body.Replace("<<lblLeaveType>>", rm.GetString("lbl_leavetype", ci));
            mailMessage.Body = mailMessage.Body.Replace("<<LeaveType>>", strLeaveType);
            mailMessage.Body = mailMessage.Body.Replace("<<lblLeaveDate>>", rm.GetString("email_LeaveDate", ci));
            mailMessage.Body = mailMessage.Body.Replace("<<lblFromDate>>", rm.GetString("email_FromDate", ci));
            //mailMessage.Body = mailMessage.Body.Replace("<<FromDate>>", lblFromDate.Text);
            mailMessage.Body = mailMessage.Body.Replace("<<lblToDate>>", rm.GetString("email_ToDate", ci));
            //mailMessage.Body = mailMessage.Body.Replace("<<ToDate>>", lblToDate.Text);
            mailMessage.Body = mailMessage.Body.Replace("<<lblSession>>", rm.GetString("email_Session", ci));
            //mailMessage.Body = mailMessage.Body.Replace("<<FromSession>>", lblSessionFrom.Text);
            mailMessage.Body = mailMessage.Body.Replace("<<lblFromSession>>", rm.GetString("email_FromDate", ci));
            //mailMessage.Body = mailMessage.Body.Replace("<<ToSession>>", lblSessionTo.Text);
            mailMessage.Body = mailMessage.Body.Replace("<<lblToSession>>", rm.GetString("email_ToDate", ci));
            mailMessage.Body = mailMessage.Body.Replace("<<lblNumberDaysApplied>>", rm.GetString("email_NumberOfDaysApplied", ci));
            mailMessage.Body = mailMessage.Body.Replace("<<NumberDaysApplied>>", NoOfDays);
            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
        {
            checkEmail = false;
        }
    }
    /// <summary>
    /// Sending Mail to Sanctioning Authority of the Employee
    /// </summary>
    /// <param name="EmailIdSanctionAuthority"></param>
    /// <param name="Status"></param>
    /// <param name="EmployeeId"></param>
    /// <param name="EmployeeName"></param>
    private void SendMailToSanctionAuthority(string EmailIdSanctionAuthority, string Status, int EmployeeId, string EmployeeName, string Remarks, string LeaveApplicationDate, string NoOfDays, string strLeaveType)
    {
        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 Employee_Code_Id = ViewState["Employee_code_Id"].ToString();
            string ScriptType = "Forwarded Leave Application Sanction";
            //  cl.fillDT("Select * from TA_TBL_EmailScripts where ScriptType='Forwarded Leave Application Sanction'", dtTableScript);
            dtTableScript = objLeaveApplicationEventData.GetEmailScripts(ScriptType);
            scriptText = dtTableScript.Rows[0]["ScriptText"].ToString();
            //mailMessage.From = System.Configuration.ConfigurationManager.AppSettings["FromId"];
            //mailMessage.To = EmailIdSanctionAuthority;
            //mailMessage.Subject = Status + " Leave Application for - " + Employee_Code_Id + " | " + EmployeeName;
            mailMessage.From = new MailAddress(ConfigurationManager.AppSettings.Get("FromId"));
            mailMessage.To.Add(new MailAddress(EmailIdSanctionAuthority));
            mailMessage.Subject = "TimeCheck : " + ViewState["LevelName"].ToString() + " | " + EmployeeName + " - " + Employee_Code_Id + " | Leave  - " + Status;
            //mailMessage.BodyFormat = MailFormat.Html;
            //mailMessage.Priority = MailPriority.Normal;
            mailMessage.Body = scriptText.Replace("<<lblLeaveApplicationForm>>", rm.GetString("email_LeaveApplicationForm", ci));
            mailMessage.Body = mailMessage.Body.Replace("<<lblEmployeeId>>", rm.GetString("email_EmployeeId", ci));
            mailMessage.Body = mailMessage.Body.Replace("<<EmployeeId>>", Employee_Code_Id);
            mailMessage.Body = mailMessage.Body.Replace("<<lblEmployeeName>>", rm.GetString("email_EmployeeName", ci));
            mailMessage.Body = mailMessage.Body.Replace("<<EmployeeName>>", EmployeeName);
            mailMessage.Body = mailMessage.Body.Replace("<<lblApplicationDate>>", rm.GetString("email_LeaveApplicationDate", ci));
            mailMessage.Body = mailMessage.Body.Replace("<<ApplicationDate>>", DateTime.Parse(LeaveApplicationDate).ToShortDateString());
            mailMessage.Body = mailMessage.Body.Replace("<<lblLeaveType>>", rm.GetString("lbl_leavetype", ci));
            mailMessage.Body = mailMessage.Body.Replace("<<LeaveType>>", strLeaveType);
            mailMessage.Body = mailMessage.Body.Replace("<<lblLeaveDate>>", rm.GetString("email_LeaveDate", ci));
            mailMessage.Body = mailMessage.Body.Replace("<<lblFromDate>>", rm.GetString("email_FromDate", ci));
            //mailMessage.Body = mailMessage.Body.Replace("<<FromDate>>", lblFromDate.Text);
            mailMessage.Body = mailMessage.Body.Replace("<<lblToDate>>", rm.GetString("email_ToDate", ci));
            //mailMessage.Body = mailMessage.Body.Replace("<<ToDate>>", lblToDate.Text);
            mailMessage.Body = mailMessage.Body.Replace("<<lblSession>>", rm.GetString("email_Session", ci));
            //mailMessage.Body = mailMessage.Body.Replace("<<FromSession>>", lblSessionFrom.Text);
            mailMessage.Body = mailMessage.Body.Replace("<<lblFromSession>>", rm.GetString("email_FromDate", ci));
            //mailMessage.Body = mailMessage.Body.Replace("<<ToSession>>", lblSessionTo.Text);
            mailMessage.Body = mailMessage.Body.Replace("<<lblToSession>>", rm.GetString("email_ToDate", ci));
            mailMessage.Body = mailMessage.Body.Replace("<<lblNumberDaysApplied>>", rm.GetString("email_NumberOfDaysApplied", ci));
            mailMessage.Body = mailMessage.Body.Replace("<<NumberDaysApplied>>", NoOfDays);
            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
        {
            checkEmail = false;
        }
    }
    //Getting Information from resource file and display it in label
    private void LoadStrings(CultureInfo ci)
    {
        lbl_Header.Text = rm.GetString("Menu_Transactions_LeaveSanction", ci);
        //lbl_LeaveType.Text = rm.GetString("lbl_leavetype", ci);
        lbl_EmpName.Text = rm.GetString("email_EmployeeName", ci);
        //lbl_FromDate.Text = rm.GetString("email_FromDate", ci);
        //lbl_Todate.Text = rm.GetString("email_ToDate", ci);
        lbl_Reason.Text = rm.GetString("email_Reason", ci);
        lbl_Remarks.Text = rm.GetString("email_Remarks", ci);
        //lbl_NoOfDays.Text= rm.GetString("LeaveSanction_NumberOfDays",ci);
        lbl_IndicatesMandatoryFields.Text = rm.GetString("IndicatesMandatoryFields", ci);
        btn_Save.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Save", ci);
        btn_Cancel.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Back", ci);
    }
    private void SendMail(int FirstLevelAuthorityId, int SecondLevelAuthorityId, string FirstLevelAuthorityEmailId, string SecondLevelAuthorityEmailId, string ApplicantEmailId, string EmployeeCodeId, string EmployeeName, string Status, string Remarks, string LeaveApplicationDate, string NoOfDays, string strLeaveType, string levelName, string ApprovalCC, string IntimationType)
    {
        try
        {
            // Get the Application Root Path
            string strApplicationPath = Request.UrlReferrer.ToString();
            int intLastIndex = strApplicationPath.LastIndexOf('/');
            strApplicationPath = strApplicationPath.Substring(0, (intLastIndex - 1));
            intLastIndex = strApplicationPath.LastIndexOf('/');
            strApplicationPath = strApplicationPath.Substring(0, (intLastIndex + 1));
            string[] strSysName;
            strSysName = strApplicationPath.Split('/');
            string strServerIP = string.Empty;
            //= GetIPAddress();
            strServerIP = System.Configuration.ConfigurationManager.AppSettings["ServerIP"].ToString();
            strApplicationPath = strApplicationPath.Replace(strSysName[2].ToString(), strServerIP);
            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 Employee_Code_Id = ViewState["Employee_code_Id"].ToString();
            if (strCrossdate == "Yes")
            {
                ScriptType = "Forwarded CrossDate Leave Application Sanction";
            }
            else
            {
                ScriptType = "Forwarded Leave Application Sanction";
            }
            dtTableScript = objLeaveApplicationEventData.GetEmailScripts(ScriptType);
            scriptText = dtTableScript.Rows[0]["ScriptText"].ToString();
            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(SecondLevelAuthorityEmailId);
                    mailMessage.To.Add(new MailAddress(ApplicantEmailId));
                    //strCCTo = SecondLevelAuthorityEmailId;
                    strCCTo = FirstLevelAuthorityEmailId;
                }
                else if (Status == "Rejected")
                {
                    mailMessage.From = new MailAddress(SecondLevelAuthorityEmailId);
                    mailMessage.To.Add(new MailAddress(ApplicantEmailId));
                    //strCCTo = SecondLevelAuthorityEmailId + ";" + FirstLevelAuthorityEmailId;
                    strCCTo = FirstLevelAuthorityEmailId;
                }
                else if (Status == "Approved")
                {
                    mailMessage.From = new MailAddress(SecondLevelAuthorityEmailId);
                    mailMessage.To.Add(new MailAddress(ApplicantEmailId));
                    //strCCTo = SecondLevelAuthorityEmailId + ";" + FirstLevelAuthorityEmailId;
                    strCCTo = FirstLevelAuthorityEmailId;
                }
                else if (Status == "Resend")
                {
                    mailMessage.From = new MailAddress(SecondLevelAuthorityEmailId);
                    mailMessage.To.Add(new MailAddress(ApplicantEmailId));
                    strCCTo = SecondLevelAuthorityEmailId + ";" + FirstLevelAuthorityEmailId;
                    // strCCTo = FirstLevelAuthorityEmailId;
                }
                else
                {
                    // Nothing
                }
            }
            else if (intLoginEmpId == FirstLevelAuthorityId)
            {
                if (Status == "Forwarded")
                {
                    mailMessage.From = new MailAddress(FirstLevelAuthorityEmailId);
                    mailMessage.To.Add(new MailAddress(SecondLevelAuthorityEmailId));
                    strCCTo = ApplicantEmailId;
                }
                else if (Status == "Resend")
                {
                    mailMessage.From = new MailAddress(FirstLevelAuthorityEmailId);
                    mailMessage.To.Add(new MailAddress(ApplicantEmailId));
                    strCCTo = FirstLevelAuthorityEmailId;
                }
                else if (Status == "Rejected")
                {
                    mailMessage.From = new MailAddress(FirstLevelAuthorityEmailId);
                    mailMessage.To.Add(new MailAddress(ApplicantEmailId));
                    strCCTo = FirstLevelAuthorityEmailId;
                }
            }
            else
            {
                if (Status == "Pending" || Status == "Rejected")
                {
                    mailMessage.To.Add(new MailAddress(ApplicantEmailId));
                    strCCTo = FirstLevelAuthorityEmailId;
                }
                else if (Status == "Forwarded")
                {
                    mailMessage.To.Add(new MailAddress(SecondLevelAuthorityEmailId));
                    strCCTo = FirstLevelAuthorityEmailId + ";" + ApplicantEmailId;
                }
                else if (Status == "Approved")
                {
                    mailMessage.To.Add(new MailAddress(ApplicantEmailId));
                    strCCTo = SecondLevelAuthorityEmailId + ";" + FirstLevelAuthorityEmailId;
                }
                else if (Status == "Resend")
                {
                    mailMessage.To.Add(new MailAddress(ApplicantEmailId));
                    strCCTo = SecondLevelAuthorityEmailId + ";" + FirstLevelAuthorityEmailId;
                }
                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")
            {
                //if (ApprovalCC != string.Empty)
                //{
                //    strCCTo = strCCTo + ";" + ApprovalCC;
                //}
                DataSet dsCCEmailIds = new DataSet();
                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);
                }
            }
            #region Code By Gopinath.K For Pervious Leave Details
            string strLeaveDetails = string.Empty;
            if (Convert.ToString(Employee_Code_Id) != string.Empty)
            {
                DataSet dstLeave = objLeaveApplicationEventData.GetPreviousLeaveDetails(Convert.ToInt16(0), Employee_Code_Id, "M");
                strLeaveDetails = dstLeave.Tables.Count > 0 ? dstLeave.Tables[0].Rows.Count > 0 ? Convert.ToString(dstLeave.Tables[0].Rows[0][0]) : string.Empty : string.Empty;
            }
            #endregion
            //Send mails by selection Emails
            string strToMails = txtApprovalTO.Text;
            string strCcMails = txtApprovalCC.Text;
            //TO mail Ids
            if (strToMails != string.Empty)
            {
                string[] strArrEmailAddressForTO;
                strArrEmailAddressForTO = SplitCCTo(strToMails);
                MailAddressCollection MailAddrCollectionTO = mailMessage.To;
                for (int iLoop = 0; iLoop < strArrEmailAddressForTO.Length; iLoop++)
                {
                    MailAddress newCC = new MailAddress(strArrEmailAddressForTO[iLoop]);
                    MailAddrCollectionTO.Add(newCC);
                }
            }
            //CC Mails
            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());
            }
            if (IntimationType == "P")
            {
                IntimationType = "Planned";
            }
            mailMessage.Subject = "TimeCheck : " + levelName + " | " + EmployeeName + " - " + Employee_Code_Id + " | Leave  - " + Status + " | " + IntimationType;
            mailMessage.Body = scriptText.Replace("<<lblLeaveApplicationForm>>", rm.GetString("email_LeaveApplicationForm", ci));
            mailMessage.Body = mailMessage.Body.Replace("<<lblEmployeeId>>", rm.GetString("email_EmployeeId", ci));
            mailMessage.Body = mailMessage.Body.Replace("<<EmployeeId>>", Employee_Code_Id);
            mailMessage.Body = mailMessage.Body.Replace("<<lblEmployeeName>>", rm.GetString("email_EmployeeName", ci));
            mailMessage.Body = mailMessage.Body.Replace("<<EmployeeName>>", EmployeeName);
            mailMessage.Body = mailMessage.Body.Replace("<<lblDepartment>>", "Department");
            mailMessage.Body = mailMessage.Body.Replace("<<Department>>", levelName);
            if (strCrossdate != "Yes")
            {
                mailMessage.Body = mailMessage.Body.Replace("<<NoOfLeaveAvailedMonth>>", strLeaveavailedinFirstMonth);
                mailMessage.Body = mailMessage.Body.Replace("<<lblNoOfLeaveAvailedMonth>>", "Leave availed in " + strLeaveavailedinFirstMonthName);
            }
            else
            {
                mailMessage.Body = mailMessage.Body.Replace("<<NoOfLeaveAvailedInFirstMonth>>", strLeaveavailedinFirstMonth);
                mailMessage.Body = mailMessage.Body.Replace("<<lblNoOfLeaveAvailedinFirstMonth>>", "Leave availed in " + strLeaveavailedinFirstMonthName);
                mailMessage.Body = mailMessage.Body.Replace("<<NoOfLeaveAvailedinsecondMonth>>", strLeaveavailedinSecondMonth);
                mailMessage.Body = mailMessage.Body.Replace("<<lblNoOfLeaveAvailedinsecondMonth>>", "Leave availed in " + strLeaveavailedinSecondMonthName);
            }
            //mailMessage.Body = mailMessage.Body.Replace("<<NoOfLeaveAvailedYear>>", lblLeaveAvailedYearData.Text);
            //mailMessage.Body = mailMessage.Body.Replace("<<lblNoOfLeaveAvailedYear>>", "Leave availed in this Year");
            mailMessage.Body = mailMessage.Body.Replace("<<lblApplicationDate>>", rm.GetString("email_LeaveApplicationDate", ci));
            DateTime dtmTodaysDate = Convert.ToDateTime(LeaveApplicationDate);
            mailMessage.Body = mailMessage.Body.Replace("<<ApplicationDate>>", dtmTodaysDate.ToString(Session["MDateFormat"].ToString()));
            mailMessage.Body = mailMessage.Body.Replace("<<lblLeaveType>>", rm.GetString("lbl_leavetype", ci));
            mailMessage.Body = mailMessage.Body.Replace("<<LeaveType>>", strLeaveType);
            mailMessage.Body = mailMessage.Body.Replace("<<lblLeaveDate>>", rm.GetString("email_LeaveDate", ci));
            mailMessage.Body = mailMessage.Body.Replace("<<lblFromDate>>", rm.GetString("email_FromDate", ci));
            //mailMessage.Body = mailMessage.Body.Replace("<<FromDate>>", lblFromDate.Text);
            mailMessage.Body = mailMessage.Body.Replace("<<lblToDate>>", rm.GetString("email_ToDate", ci));
            //mailMessage.Body = mailMessage.Body.Replace("<<ToDate>>", lblToDate.Text);
            mailMessage.Body = mailMessage.Body.Replace("<<lblSession>>", rm.GetString("email_Session", ci));
            //mailMessage.Body = mailMessage.Body.Replace("<<FromSession>>", lblSessionFrom.Text);
            mailMessage.Body = mailMessage.Body.Replace("<<lblFromSession>>", rm.GetString("email_FromDate", ci));
            //mailMessage.Body = mailMessage.Body.Replace("<<ToSession>>", lblSessionTo.Text);
            mailMessage.Body = mailMessage.Body.Replace("<<lblToSession>>", rm.GetString("email_ToDate", ci));
            mailMessage.Body = mailMessage.Body.Replace("<<lblNumberDaysApplied>>", rm.GetString("email_NumberOfDaysApplied", ci));
            mailMessage.Body = mailMessage.Body.Replace("<<NumberDaysApplied>>", NoOfDays);
            mailMessage.Body = mailMessage.Body.Replace("<<lblStatus>>", rm.GetString("email_Status", ci));
            mailMessage.Body = mailMessage.Body.Replace("<<Status>>", Status);
            mailMessage.Body = mailMessage.Body.Replace("<<lblReason>>", "Reason");
            mailMessage.Body = mailMessage.Body.Replace("<<Reason>>", ViewState["vwReason"].ToString());
            //mailMessage.Body = mailMessage.Body.Replace("<<lblRemarks>>", rm.GetString("email_Remarks", ci));
            //mailMessage.Body = mailMessage.Body.Replace("<<Remarks>>", txtRemarks.Text);
            mailMessage.Body = mailMessage.Body.Replace("<<divMailLeaveThread>>", strHtmlLeaveDetails);
            //Added By Gopinath.k for show Leave details in table format
            mailMessage.Body = mailMessage.Body.Replace("<<divLeaveThread>>", strLeaveDetails);
            //mailMessage.Body = mailMessage.Body.Replace("<<divMailThread>>", strHtml.Replace("width='70%'", " ").Replace("width='30%'", " ").Replace("<td><span class='Header'>Comments</span></td>","<td style='width:40%'><span class='Header'>Comments</span></td>"));
            mailMessage.Body = mailMessage.Body.Replace("<<divMailThread>>", strHtml);
            if (Status == "Forwarded")
            {
                string LevelId = "1";
                //mailMessage.Body = mailMessage.Body.Replace("<<LinkData>>", strServerIP + "Index.aspx?LeaveApplication_Id=" + LeaveApplication_Id.ToString() + "&LevelId=" + LevelId + "&ApprovalType=Leave");
                mailMessage.Body = mailMessage.Body.Replace("<<LinkData>>", Convert.ToString(Session["HostServerURL"]) + "?LeaveApplication_Id=" + LeaveApplication_Id.ToString() + "&LevelId=" + LevelId + "&ApprovalType=Leave&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>";
                string strReplaceText = "<font face=\"Arial\" size=\"2\"><a href=\"<<LinkData>>\">Click here for approval</a></font>";
                mailMessage.Body = mailMessage.Body.Replace(strReplaceText, string.Empty);
            }
            // Create a mail object specifying the address of your SMTP mail server
            //string MailServerId = System.Configuration.ConfigurationManager.AppSettings["SMTPClientHost"].ToString();
            //SmtpMail.SmtpServer = MailServerId;
            //SmtpMail.Send(mail);
            loHTMLView = AlternateView.CreateAlternateViewFromString(mailMessage.Body, loHTMLType);
            mailMessage.AlternateViews.Add(loHTMLView);
            loSMTPServer.Host = ConfigurationManager.AppSettings.Get("SMTPClientHost");
            loSMTPServer.UseDefaultCredentials = true;
            loSMTPServer.DeliveryMethod = SmtpDeliveryMethod.Network;
            loSMTPServer.Send(mailMessage);
        }
        catch
        {
            checkEmail = false;
        }
    }
    private void SendPrivateNotes(int FirstLevelAuthorityId, int SecondLevelAuthorityId, string FirstLevelAuthorityEmailId, string SecondLevelAuthorityEmailId, string ApplicantEmailId, string EmployeeCodeId, string EmployeeName, string Status, string Remarks, string LeaveApplicationDate, string NoOfDays, string strLeaveType, string levelName, string ApprovalCC, string IntimationType)
    {
        try
        {
            string strToMails = txtApprovalTO.Text;
            string strCcMails = txtApprovalCC.Text;
            // Get the Application Root Path
            string strApplicationPath = Request.UrlReferrer.ToString();
            int intLastIndex = strApplicationPath.LastIndexOf('/');
            strApplicationPath = strApplicationPath.Substring(0, (intLastIndex - 1));
            intLastIndex = strApplicationPath.LastIndexOf('/');
            strApplicationPath = strApplicationPath.Substring(0, (intLastIndex + 1));
            string[] strSysName;
            strSysName = strApplicationPath.Split('/');
            string strServerIP = string.Empty;
            //= GetIPAddress();
            strServerIP = System.Configuration.ConfigurationManager.AppSettings["ServerIP"].ToString();
            strApplicationPath = strApplicationPath.Replace(strSysName[2].ToString(), strServerIP);
            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;
            // Select the Recipient for To and CC based on the Approval Authority and Status
            int intLoginEmpId = 0;
            string strCCTo = string.Empty;
            string scriptText;
            DataTable dtTableScript = new DataTable();
            string Employee_Code_Id = ViewState["Employee_code_Id"].ToString();
            string ScriptType = string.Empty;
            if (strCrossdate != "Yes")
            {
                ScriptType = "Leave Sanction Private Notes";
            }
            else
            {
                ScriptType = "Leave Sanction Cross Private Notes";
            }
            dtTableScript = objLeaveApplicationEventData.GetEmailScripts(ScriptType);
            scriptText = dtTableScript.Rows[0]["ScriptText"].ToString();
            //TO mail Ids
            if (strToMails != string.Empty)
            {
                string[] strArrEmailAddressForTO;
                strArrEmailAddressForTO = SplitCCTo(strToMails);
                MailAddressCollection MailAddrCollectionTO = mailMessage.To;
                for (int iLoop = 0; iLoop < strArrEmailAddressForTO.Length; iLoop++)
                {
                    MailAddress newCC = new MailAddress(strArrEmailAddressForTO[iLoop]);
                    MailAddrCollectionTO.Add(newCC);
                }
            }
            //CC Mails
            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);
                }
            }
            // Get the Employee Auto Id who have Logged In from Session
            intLoginEmpId = Convert.ToInt32(Session["EmpAutoId"]);
            string strLoginEmployeeEmailId = string.Empty;
            DataSet dsLoginEmployeeDetails = new DataSet();
            bool blnLoginMailexists = false;
            dsLoginEmployeeDetails = objLeaveApplicationEventData.GetEmployeeDetails(intLoginEmpId);
            if (dsLoginEmployeeDetails.Tables[0].Rows.Count > 0)
            {
                if (dsLoginEmployeeDetails.Tables[0].Rows[0]["EmailId"] != DBNull.Value && dsLoginEmployeeDetails.Tables[0].Rows[0]["EmailId"].ToString() != string.Empty)
                {
                    blnLoginMailexists = true;
                    mailMessage.From = new MailAddress(dsLoginEmployeeDetails.Tables[0].Rows[0]["EmailId"].ToString());
                }
            }
            if (blnLoginMailexists == false)
            {
                mailMessage.From = new MailAddress(ConfigurationManager.AppSettings.Get("FromId"));
            }
            mailMessage.Subject = "TimeCheck : " + "Reg - Private Notes | " + levelName + " | " + " Employee Name & Id  : " + lbl_EmployeeName.Text + " - " + ViewState["Employee_code_Id"].ToString();
            //mailMessage.Body = txtRemarks.Text;
            mailMessage.Body = scriptText.Replace("<<lblLeaveApplicationForm>>", rm.GetString("email_LeaveApplicationForm", ci));
            mailMessage.Body = mailMessage.Body.Replace("<<lblEmployeeId>>", rm.GetString("email_EmployeeId", ci));
            mailMessage.Body = mailMessage.Body.Replace("<<EmployeeId>>", Employee_Code_Id);
            mailMessage.Body = mailMessage.Body.Replace("<<lblEmployeeName>>", rm.GetString("email_EmployeeName", ci));
            mailMessage.Body = mailMessage.Body.Replace("<<EmployeeName>>", EmployeeName);
            mailMessage.Body = mailMessage.Body.Replace("<<lblDepartment>>", "Department");
            mailMessage.Body = mailMessage.Body.Replace("<<Department>>", levelName);
            mailMessage.Body = mailMessage.Body.Replace("<<lblApplicationDate>>", rm.GetString("email_LeaveApplicationDate", ci));
            DateTime dtmTodaysDate = Convert.ToDateTime(DateTime.Now.ToShortDateString());
            mailMessage.Body = mailMessage.Body.Replace("<<ApplicationDate>>", dtmTodaysDate.ToString(Session["MDateFormat"].ToString()));
            mailMessage.Body = mailMessage.Body.Replace("<<lblLeaveType>>", rm.GetString("lbl_leavetype", ci));
            mailMessage.Body = mailMessage.Body.Replace("<<LeaveType>>", strLeaveType);
            mailMessage.Body = mailMessage.Body.Replace("<<lblLeaveDate>>", rm.GetString("email_LeaveDate", ci));
            mailMessage.Body = mailMessage.Body.Replace("<<lblFromDate>>", rm.GetString("email_FromDate", ci));
            //mailMessage.Body = mailMessage.Body.Replace("<<FromDate>>", lblFromDate.Text);
            mailMessage.Body = mailMessage.Body.Replace("<<lblToDate>>", rm.GetString("email_ToDate", ci));
            //mailMessage.Body = mailMessage.Body.Replace("<<ToDate>>", lblToDate.Text);
            mailMessage.Body = mailMessage.Body.Replace("<<lblSession>>", rm.GetString("email_Session", ci));
            //mailMessage.Body = mailMessage.Body.Replace("<<FromSession>>", lblSessionFrom.Text);
            mailMessage.Body = mailMessage.Body.Replace("<<lblFromSession>>", rm.GetString("email_FromDate", ci));
            //mailMessage.Body = mailMessage.Body.Replace("<<ToSession>>", lblSessionTo.Text);
            mailMessage.Body = mailMessage.Body.Replace("<<lblToSession>>", rm.GetString("email_ToDate", ci));
            if (strCrossdate == "Yes")
            {
                mailMessage.Body = mailMessage.Body.Replace("<<NoOfLeaveAvailedinFirstMonth>>", strLeaveavailedinFirstMonth);
                mailMessage.Body = mailMessage.Body.Replace("<<lblNoOfLeaveAvailedinFirstMonth>>", "Leave availed in " + strLeaveavailedinFirstMonthName);
                mailMessage.Body = mailMessage.Body.Replace("<<NoOfLeaveAvailedinSecondMonth>>", strLeaveavailedinSecondMonth);
                mailMessage.Body = mailMessage.Body.Replace("<<lblNoOfLeaveAvailedinSecondMonth>>", "Leave availed in " + strLeaveavailedinSecondMonthName);
            }
            else
            {
                //mailMessage.Body = mailMessage.Body.Replace("<<NoOfLeaveAvailedMonth>>", strLeaveAvailedMonth);
                mailMessage.Body = mailMessage.Body.Replace("<<NoOfLeaveAvailedMonth>>", strLeaveavailedinFirstMonth);
                mailMessage.Body = mailMessage.Body.Replace("<<lblNoOfLeaveAvailedMonth>>", "Leave availed in " + strLeaveavailedinFirstMonthName);
                //mailMessage.Body = mailMessage.Body.Replace("<<NoOfLeaveAvailedinFirstMonth>>", strLeaveavailedinFirstMonth);
                //mailMessage.Body = mailMessage.Body.Replace("<<lblNoOfLeaveAvailedinFirstMonth>>", "Leave availed in " + strLeaveavailedinFirstMonthName);
            }
            //mailMessage.Body = mailMessage.Body.Replace("<<NoOfLeaveAvailedMonth>>", dblLeaveAvailedMonth.ToString());
            //mailMessage.Body = mailMessage.Body.Replace("<<NoOfLeaveAvailedMonth>>", lblLeaveAvailedMonthData.Text);
            //mailMessage.Body = mailMessage.Body.Replace("<<lblNoOfLeaveAvailedMonth>>", "Leave availed in this Month");
            //mailMessage.Body = mailMessage.Body.Replace("<<NoOfLeaveAvailedYear>>", dblLeaveAvailedYear.ToString());
            mailMessage.Body = mailMessage.Body.Replace("<<NoOfLeaveAvailedYear>>", lblLeaveAvailedYearData.Text);
            mailMessage.Body = mailMessage.Body.Replace("<<lblNoOfLeaveAvailedYear>>", "Leave availed in this Year");
            mailMessage.Body = mailMessage.Body.Replace("<<lblReason>>", "Reason");
            mailMessage.Body = mailMessage.Body.Replace("<<Reason>>", ViewState["vwReason"].ToString());
            //mailMessage.Body = mailMessage.Body.Replace("<<lblNotes>>", "Remarks");
            //mailMessage.Body = mailMessage.Body.Replace("<<Notes>>", txtRemarks.Text);
            string LevelId = "1";
            // mailMessage.Body = mailMessage.Body.Replace("<<LinkData>>", strServerIP + "Index.aspx?LeaveApplication_Id=" + LeaveApplication_Id.ToString() + "&LevelId=" + LevelId + "&ApprovalType=Leave");
            mailMessage.Body = mailMessage.Body.Replace("<<LinkData>>", strServerIP + "Transactions/TA_UI_Transactions_LeaveSanctionModify_Angler.aspx?LeaveApplication_Id=" + LeaveApplication_Id.ToString() + "&LevelId=" + LevelId + "&ApprovalType=Leave&Status=All&From_Date=&To_Date=&strSwipeCardNo=&strEmployeeName=&strEmployeeCodeId=&Angler=1");
            //string strReplaceText ="<font face='Verdana' size='2'><a href='<<LinkData>>'>Click here for approval</a></font>";
            //mailMessage.Body = mailMessage.Body.Replace(strReplaceText,string.Empty);
            mailMessage.Body = mailMessage.Body.Replace("<<divMailLeaveThread>>", strHtmlLeaveDetails);
            if (strHtmlPrivateNotes != string.Empty)
            {
                mailMessage.Body = mailMessage.Body.Replace("<<divMailPrivateNotesThread>>", strHtmlPrivateNotes);
            }
            else
            {
                mailMessage.Body = mailMessage.Body.Replace("<<divMailPrivateNotesThread>>", string.Empty);
            }
            if (strHtml != string.Empty)
            {
                mailMessage.Body = mailMessage.Body.Replace("<<divMailThread>>", strHtml);
            }
            else
            {
                mailMessage.Body = mailMessage.Body.Replace("<<divMailThread>>", string.Empty);
            }
            // Create a mail object specifying the address of your SMTP mail server
            loHTMLView = AlternateView.CreateAlternateViewFromString(mailMessage.Body, loHTMLType);
            mailMessage.AlternateViews.Add(loHTMLView);
            loSMTPServer.Host = ConfigurationManager.AppSettings.Get("SMTPClientHost");
            loSMTPServer.UseDefaultCredentials = true;
            loSMTPServer.DeliveryMethod = SmtpDeliveryMethod.Network;
            loSMTPServer.Send(mailMessage);
        }
        catch
        {
            checkEmail = false;
        }
    }
    private string[] SplitCCTo(string CCTo)
    {
        string[] strArrEmailAddressForCC;
        strArrEmailAddressForCC = CCTo.Split(';');
        return (strArrEmailAddressForCC);
    }
    private void UserRights()
    {
        ds_Checkuser = objCheckUser.checkRights(260, Convert.ToInt32(Session["userGroup_Id"]), "viewPrv");
        if (ds_Checkuser.Tables[0].Rows.Count == 0)
        {
            if (blnCheckPrivateNotes == false)
            {
                Response.Redirect("TransactionLandingPage.aspx");
            }
        }
        else
        {
            //   
        }
    }
    #region ServerIPAddress
    /// <summary>
    /// 
    /// </summary>
    /// <returns></returns>
    public string GetIPAddress()
    {
        string strHostName = System.Net.Dns.GetHostName();
        IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
        IPAddress ipAddress = ipHostInfo.AddressList[0];
        return ipAddress.ToString();
    }
    #endregion
    //protected void btnApprovalCC_Click(object sender, EventArgs e)
    //{
    //    btnApprovalCC.Attributes.Add("onclick", "window.open('GetEmailIdsPopup.aspx','Test','height=500,top=200,left=250,width=600');return false;");
    //}
    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)
                {
                    if (blnPrivateNotes == true)
                    {
                        sb.Append("<td width='60%'><font face='Arial' size='2'>" + Row[Col.ColumnName].ToString() + "</font></td>");
                    }
                    else
                    {
                        sb.Append("<td><font face='Arial' size='2'>" + Row[Col.ColumnName].ToString() + "</font></td>");
                    }
                    //intWidth = 1;
                }
                else if (intWidth != 2)
                {
                    if (blnPrivateNotes == true)
                    {
                        sb.Append("<td width='20%'><font face='Arial' size='2'>" + Row[Col.ColumnName].ToString() + "</font></td>");
                    }
                    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();
    }
    #endregion
    #region Button Click & Grid Events
    /// <summary>
    /// 
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void grv_LeaveApplication_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            Label lblLeaveFrom = (Label)e.Row.Cells[0].FindControl("lblLeaveFrom");
            lblLeaveFrom.Text = (Convert.ToDateTime(lblLeaveFrom.Text)).ToString(Session["MDateFormat"].ToString());
            Label lblLeaveTo = (Label)e.Row.Cells[0].FindControl("lblLeaveTo");
            lblLeaveTo.Text = (Convert.ToDateTime(lblLeaveTo.Text)).ToString(Session["MDateFormat"].ToString());
        }
    }
    /// <summary>
    /// Redirects to Leave sanction page
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btn_Cancel_Click(object sender, EventArgs e)
    {
        Response.Redirect("../Transactions/TA_UI_Transactions_LeaveSanction_Angler.aspx");
    }
    /// <summary>
    /// Save leave sanction Details
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btn_Save_Click(object sender, EventArgs e)
    {
        //System.Threading.Thread.Sleep(10);
        string strFromDate = string.Empty;
        //btn_Save.Enabled = false;
        //btn_Save.Text = "Processing";
        string strToDate = string.Empty;
        if (txtRemarks.Text.Trim() == "")
        {
            base.Message("Enter Remarks");
            return;
        }
        string strLengthCheck = txtRemarks.Text.Trim().Replace("'", "''");
        if (strLengthCheck.Length > 1000)
        {
            Message("Maximum character for Reason is 1000");
            return;
        }
        //Intimation Type
        string intimationType = string.Empty;
        // get inputs from UI
        if (rbtnP.Checked)
        {
            intimationType = rbtnP.Text;
            intimationType = "P";
        }
        else if (rbtnUPWI.Checked)
        {
            intimationType = rbtnUPWI.Text;
        }
        else if (rbtnUPWOI.Checked)
        {
            intimationType = rbtnUPWOI.Text;
        }
        LeaveApplication_Id = Convert.ToInt32(Request.QueryString["LeaveApplication_Id"]);
        dtSanctionView = objLeaveApplicationEventData.GetLeaveApplicationByLeaveApplicationId(LeaveApplication_Id);
        dtLeaveavailedinMonth = objLeaveApplicationEventData.LoadEmployeeLeaveAvailedinMonth(LeaveApplication_Id);
        EmployeeName = dtSanctionView.Rows[0]["Employee_FirstName"].ToString();
        Employee_Id = Convert.ToInt32(dtSanctionView.Rows[0]["Employee_Id"]);
        EmployeeEamilId = dtSanctionView.Rows[0]["EmailId"].ToString();
        strLeaveApplicationDate = dtSanctionView.Rows[0]["Leave_ApplicationDate"].ToString();
        strNoOfDays = dtSanctionView.Rows[0]["NumberOfDays"].ToString();
        Leave_FromDate = dtSanctionView.Rows[0]["LeaveFrom"].ToString();
        Leave_ToDate = dtSanctionView.Rows[0]["LeaveTo"].ToString();
        // Added by Gopinath for not allow approval after the applied date crossed  on 15-Feb-2016.
        //  string strFromDate = (DateTime.Parse(dtSanctionView.Rows[0]["Leave_FromDate"].ToString())).ToString(Session["MDateFormat"].ToString());
        string strTodaysDate = DateTime.Now.ToString(Session["MDateFormat"].ToString());
        Leave_FromDate = (DateTime.Parse(dtSanctionView.Rows[0]["LeaveFrom"].ToString())).ToString(Session["MDateFormat"].ToString());
        Leave_ToDate = (DateTime.Parse(dtSanctionView.Rows[0]["LeaveTo"].ToString())).ToString(Session["MDateFormat"].ToString());
        if (((Convert.ToDateTime(Leave_FromDate) < Convert.ToDateTime(strTodaysDate)) || (Convert.ToDateTime(Leave_ToDate) < Convert.ToDateTime(strTodaysDate))) && Session["UserGroupName"].ToString() != "SuperAdmin" && Session["AllowLeaveApprovalPastEntry"].ToString() != "True" && intimationType == "P")
        {
            Message("Leave Approvals should not be done for past days");
            return;
        }
        levelName = dtSanctionView.Rows[0]["LevelName"].ToString();
        string leaveType = dtSanctionView.Rows[0]["LeaveType"].ToString();
        string strTypeOfLeave = dtSanctionView.Rows[0]["Type"].ToString();
        NumberOfDays = Convert.ToDouble(dtSanctionView.Rows[0]["NumberOfDays"]);
        LeaveTypeId = Convert.ToInt32(dtSanctionView.Rows[0]["LeaveType_id"]);
        Remarks = txtRemarks.Text.Trim().Replace("'", "''");
        // To find Reporting To & Leave Sanction Authority Email_ID
        // Gets the Reporting To Authority Id and Email Id
        int intFirstLevelAuthorityId = 0, intSecondLevelAuthorityId = 0;
        DataSet ds_ReportingTo = new DataSet();
        ds_ReportingTo = objPermissionEventData.SelectMailIdOfReportingTo(Employee_Id);
        if (ds_ReportingTo.Tables[0].Rows.Count > 0)
        {
            if (ds_ReportingTo.Tables[0].Rows[0]["EmailId"] != DBNull.Value && ds_ReportingTo.Tables[0].Rows[0]["EmailId"].ToString() != string.Empty)
            {
                intFirstLevelAuthorityId = int.Parse(ds_ReportingTo.Tables[0].Rows[0]["Employee_Id"].ToString());
                strEmailIdReportingTo = ds_ReportingTo.Tables[0].Rows[0]["EmailId"].ToString();
            }
        }
        // Gets the Sanctioning Authority Id and 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 && ds_EmailIdOfSanctionAuthority.Tables[0].Rows[0]["EmailId"].ToString() != string.Empty)
            {
                intSecondLevelAuthorityId = int.Parse(ds_EmailIdOfSanctionAuthority.Tables[0].Rows[0]["Employee_Id"].ToString());
                strEmailIdSanctionAuthority = ds_EmailIdOfSanctionAuthority.Tables[0].Rows[0]["EmailId"].ToString();
            }
        }
        if (strEmailIdSanctionAuthority == null)
        {
            strEmailIdSanctionAuthority = string.Empty;
        }
        if (strEmailIdReportingTo == null)
        {
            strEmailIdReportingTo = string.Empty;
        }
        if (strEmailIdSanctionAuthority == string.Empty && strEmailIdReportingTo == string.Empty && txtApprovalCC.Text == string.Empty && txtApprovalTO.Text == string.Empty)
        {
            checkEmail = false;
        }
        grv_LeaveApplication.DataSource = dtSanctionView;
        grv_LeaveApplication.DataBind();
        //Leave Details
        DataTable dtEmployeeLeaveDetails = new DataTable();
        DataTable dtTest = (DataTable)grv_LeaveApplication.DataSource;
        dtEmployeeLeaveDetails = (DataTable)grv_LeaveApplication.DataSource;
        if (((DataTable)Session["vSLeaveDetails"]).Columns.Count == dtEmployeeLeaveDetails.Columns.Count)
        {
            dtEmployeeLeaveDetails.Columns.Remove("LeaveApplication_Id");
            dtEmployeeLeaveDetails.Columns.Remove("Employee_Id");
            dtEmployeeLeaveDetails.Columns.Remove("Emp_Id");
            dtEmployeeLeaveDetails.Columns.Remove("IntimationType");
            dtEmployeeLeaveDetails.Columns.Remove("Employee_Code_Id");
            dtEmployeeLeaveDetails.Columns.Remove("emailId");
            dtEmployeeLeaveDetails.Columns.Remove("Employee_FirstName");
            dtEmployeeLeaveDetails.Columns.Remove("Leave_ApplicationDate");
            dtEmployeeLeaveDetails.Columns.Remove("LeaveType_Id");
            dtEmployeeLeaveDetails.Columns.Remove("Reason");
            dtEmployeeLeaveDetails.Columns.Remove("Status");
            dtEmployeeLeaveDetails.Columns.Remove("IsDeleted");
            dtEmployeeLeaveDetails.Columns.Remove("Remarks");
            dtEmployeeLeaveDetails.Columns.Remove("IsBorrow");
            dtEmployeeLeaveDetails.Columns.Remove("LevelName");
            dtEmployeeLeaveDetails.Columns.Remove("levelid");
            dtEmployeeLeaveDetails.Columns.Remove("CCMail");
            dtEmployeeLeaveDetails.Columns.Remove("LeaveAvailedMonth");
            dtEmployeeLeaveDetails.Columns.Remove("LeaveAvailedYear");
            dtEmployeeLeaveDetails.Columns.Remove("CheckedIDs");
            dtEmployeeLeaveDetails.Columns.Remove("DesignationID");
            dtEmployeeLeaveDetails.Columns.Remove("YearSettings_Id");
            dtEmployeeLeaveDetails.Columns.Add("From");
            dtEmployeeLeaveDetails.Columns.Add("To");
            //  dtEmployeeLeaveDetails.Columns[7].SetOrdinal(2);
            //   dtEmployeeLeaveDetails.Columns[8].SetOrdinal(3);
            foreach (DataRow dRowEmployeeLeaveDetails in dtEmployeeLeaveDetails.Rows)
            {
                DateTime dtmLeaveFromDate = Convert.ToDateTime(DateTime.Parse(dRowEmployeeLeaveDetails["LeaveFrom"].ToString()).ToShortDateString());
                strFromDate = dtmLeaveFromDate.ToString(Session["MDateFormat"].ToString());
                //ADDED by Manjula.p on 13-May-2014 for general datetime format.
                strFromDate = objClassCommon.DateConvertion(gstrDateFormat, strFromDate);
                dRowEmployeeLeaveDetails["From"] = strFromDate;
                DateTime dtmLeaveToDate = Convert.ToDateTime(DateTime.Parse(dRowEmployeeLeaveDetails["LeaveTo"].ToString()).ToShortDateString());
                strToDate = dtmLeaveToDate.ToString(Session["MDateFormat"].ToString());
                //ADDED by Manjula.p on 13-May-2014 for general datetime format.
                strToDate = objClassCommon.DateConvertion(gstrDateFormat, strToDate);
                dRowEmployeeLeaveDetails["To"] = strToDate;
                strTodaysDate = DateTime.Now.ToString(Session["MDateFormat"].ToString());
                //if (rblStatus.SelectedValue != "")
                //{
                //    Status = rblStatus.SelectedValue;
                //}
                //else
                //{
                //    Status = "";
                //}
                if (rbApproved.Checked == true)
                    Status = "Approved";
                else if (rbForwarded.Checked == true)
                    Status = "Forwarded";
                else if (rbPending.Checked == true)
                    Status = "Pending";
                else if (rbRejected.Checked == true)
                    Status = "Rejected";
                else if (rbReply.Checked == true)
                    Status = "Reply";
                else if (rbResend.Checked == true)
                    Status = "Resend";
                else
                    Status = string.Empty;
                if (Status == string.Empty)
                {
                    //lbl_Error.Text = "Choose an option";
                    base.Message("Choose an option");
                    return;
                }
                //if (((Convert.ToDateTime(strFromDate) < Convert.ToDateTime(strTodaysDate)) || (Convert.ToDateTime(strToDate) < Convert.ToDateTime(strTodaysDate))) && (Session["UserGroupName"].ToString() != "SuperAdmin" || Session["HasSpecialRights"].ToString() != "True") && intimationType == "P" && (Status=="Pending" || Status=="Approved" || Status=="Forwarded"))
                //{
                //    Message("Leave Approvals should not be done for past days");
                //    return;
                //}
                if (strMonthValue == "")
                {
                    strMonthValue = Convert.ToDateTime(strFromDate).Month.ToString();
                }
                else if (strMonthValue != "")
                {
                    if (strMonthValue != Convert.ToDateTime(strFromDate).Month.ToString())
                    {
                        strCrossdate = "Yes";
                    }
                }
            }
            if (dtLeaveavailedinMonth.Rows.Count > 0)
            {
                if (strCrossdate == "Yes")
                {
                    strLeaveavailedinFirstMonth = dtLeaveavailedinMonth.Rows[0]["NumberofDays"].ToString();
                    strLeaveavailedinSecondMonth = dtLeaveavailedinMonth.Rows[1]["NumberofDays"].ToString();
                    strLeaveavailedinFirstMonthName = dtLeaveavailedinMonth.Rows[0]["MonthName"].ToString();
                    strLeaveavailedinSecondMonthName = dtLeaveavailedinMonth.Rows[1]["MonthName"].ToString();
                }
                else
                {
                    strLeaveavailedinFirstMonth = dtLeaveavailedinMonth.Rows[0]["NumberofDays"].ToString();
                    strLeaveavailedinFirstMonthName = dtLeaveavailedinMonth.Rows[0]["MonthName"].ToString();
                }
            }
            dtEmployeeLeaveDetails.Columns.Remove("LeaveFrom");
            dtEmployeeLeaveDetails.Columns.Remove("LeaveTo");
            dtEmployeeLeaveDetails.Columns.Remove("InformTo");
            dtEmployeeLeaveDetails.Columns[0].ColumnName = "Leave Category";
            dtEmployeeLeaveDetails.Columns[1].ColumnName = "Leave Type";
            dtEmployeeLeaveDetails.Columns[5].SetOrdinal(2);
            dtEmployeeLeaveDetails.Columns[6].SetOrdinal(3);
            //dtEmployeeLeaveDetails.Columns[2].ColumnName = "From";
            //dtEmployeeLeaveDetails.Columns[3].ColumnName = "To";
            dtEmployeeLeaveDetails.Columns[4].ColumnName = "Session From";
            dtEmployeeLeaveDetails.Columns[5].ColumnName = "Session To";
            dtEmployeeLeaveDetails.Columns[6].ColumnName = "No. of Days";
            DataRow[] rowList = dtEmployeeLeaveDetails.Select("[Leave Category] = 'LOP'");
            foreach (DataRow dr in rowList)
            {
                dr["Leave Type"] = "-";
            }
        }
        strHtmlLeaveDetails = buildPage("LeaveDetails", dtEmployeeLeaveDetails);
        if (chkBoxPrivateNotes.Checked == true)
        {
            string strScript = string.Empty;
            if (txtApprovalTO.Text.Trim() == "")
            {
                base.Message("Select To Mail Id");
                return;
            }
            if (txtApprovalCC.Text.Contains(EmployeeEamilId) || txtApprovalTO.Text.Contains(EmployeeEamilId))
            {
                base.Message("Private notes cannot be sent to the applicant");
                return;
            }
            //Send Mail only
            Status = "";
            ViewState["vsStrApprovalCC"] = "";
            //Store the Private Note Details in Table
            objLeaveApplicationEventData.UpdateLeaveApplicationPrivateNotes(LeaveApplication_Id, Status, Convert.ToInt32(Session["EmpAutoId"]), Remarks, Convert.ToInt32(Session["EmpAutoId"]), txtApprovalTO.Text, txtApprovalCC.Text);
            PrivateNotesControlCreation();
            SendPrivateNotes(intFirstLevelAuthorityId, intSecondLevelAuthorityId, strEmailIdReportingTo, strEmailIdSanctionAuthority, EmployeeEamilId, ViewState["Employee_code_Id"].ToString(), EmployeeName, Status, txtRemarks.Text.Trim().Replace("'", "''"), strLeaveApplicationDate, strNoOfDays, leaveType, levelName, ViewState["vsStrApprovalCC"].ToString(), ViewState["vsIntimationType"].ToString());
            strScript = strScript + "<script language='javascript'>";
            strScript = strScript + "alert('Private sent successfully');";
            strScript = strScript + "RedirectionFunction();";
            // above line added and below line hided for Bug numb 23970 by Gopinath for Angler migration.
            // strScript = strScript + "location.replace('TA_UI_Transactions_LeaveSanctionView.aspx?LeaveApplication_Id=" + Request.QueryString["LeaveApplication_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_LeaveSanction.aspx');";                
            strScript = strScript + "</script>";
            //Dispaly alert messsage.
            //Response.Redirect("../Transactions/TA_UI_Transactions_LeaveSanctionView.aspx?LeaveApplication_Id=" + Request.QueryString["LeaveApplication_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());       
            Page.RegisterStartupScript("AlertPsaved36774", strScript);
            return;
        }
        //if (rblStatus.SelectedValue != "")
        //{
        //    Status = rblStatus.SelectedValue;
        //}
        //else
        //{
        //    Status = "";
        //}
        if (rbApproved.Checked == true)
            Status = "Approved";
        else if (rbForwarded.Checked == true)
            Status = "Forwarded";
        else if (rbPending.Checked == true)
            Status = "Pending";
        else if (rbRejected.Checked == true)
            Status = "Rejected";
        else if (rbReply.Checked == true)
            Status = "Reply";
        else if (rbResend.Checked == true)
            Status = "Resend";
        else
            Status = string.Empty;
        if (Status == string.Empty)
        {
            //lbl_Error.Text = "Choose an option";
            base.Message("Choose an option");
            return;
        }
        bool boolChkLeave = true;
        int intBorrowCount = 0;
        int intLeaveCount = 0;
        if (ViewState["StatusOnLoad"].ToString() == Status)
        {
            boolChkLeave = false;
            base.Message("Please change the status");
            return;
        }
        try
        {
            //update Leave Application
            if (strTypeOfLeave == "Leave")
            {
                if (ViewState["StatusBorrow"].ToString() == "False")
                {
                    if (ViewState["StatusOnLoad"].ToString() != Status)
                    {
                        if (Status == "Approved")
                        {
                            // update the status,remareks(only) of leave application
                            //insert into TA_Tbl_LeaveConversation
                            //objLeaveApplicationEventData.UpdateLeaveApplicationConversation(LeaveApplication_Id, Status, Convert.ToInt32(ViewState["vsCommentsBy"].ToString()), Remarks, Convert.ToInt32(Session["EmpAutoId"]));
                            //objLeaveApplicationEventData.UpdateYearClosureByLeaveSanction(NumberOfDays, LeaveTypeId, Employee_Id, "A", Convert.ToInt32(Session["EmpAutoId"]));
                        }
                        else if ((Status == "Rejected" || Status == "Forwarded" || Status == "Pending") && ViewState["StatusOnLoad"].ToString() == "Approved")
                        {
                            //Check Borrow Leave Exists after normal leaves
                            //int intBorrowCount = 0;
                            intBorrowCount = objLeaveApplicationEventData.CheckBorrowLeaveExists(Leave_FromDate, Leave_ToDate, LeaveTypeId, Employee_Id);
                            if (intBorrowCount > 0)
                            {
                                boolChkLeave = false;
                                //lbl_Error.Text = "Borrow Leaves are available to approve/reject";
                                base.Message("Borrow Leaves are available to approve/reject");
                                return;
                            }
                            else
                            {
                                // update the status,remareks(only) of leave application
                                //insert into TA_Tbl_LeaveConversation
                                //objLeaveApplicationEventData.UpdateLeaveApplicationConversation(LeaveApplication_Id, Status, Convert.ToInt32(ViewState["vsCommentsBy"].ToString()), Remarks, Convert.ToInt32(Session["EmpAutoId"]));
                                //objLeaveApplicationEventData.UpdateYearClosureByLeaveSanction(NumberOfDays, LeaveTypeId, Employee_Id, "R", Convert.ToInt32(Session["EmpAutoId"]));
                            }
                        }
                        else if (Status == "Resend")
                        {
                            // update the status,remareks(only) of leave application
                            //insert into TA_Tbl_LeaveConversation
                            //objLeaveApplicationEventData.UpdateLeaveApplicationConversation(LeaveApplication_Id, Status, Convert.ToInt32(ViewState["vsCommentsBy"].ToString()), Remarks, Convert.ToInt32(Session["EmpAutoId"]));
                        }
                        else if (Status == "Reply" && ViewState["StatusOnLoad"].ToString() == "Reply")
                        {
                            boolChkLeave = false;
                            base.Message("Cannot Reply");
                            return;
                        }
                    }
                    else
                    {
                        boolChkLeave = false;
                        base.Message("Please change the status");
                        return;
                    }
                }
                if (ViewState["StatusBorrow"].ToString() == "True")
                {
                    DataSet dsRemainingNoOfleaves = new DataSet();
                    double dblCurrLeave = 0.0;
                    // if condt needs to be chnaged based on reply, resend
                    if (ViewState["StatusOnLoad"].ToString() != Status)
                    {
                        if ((Status == "Forwarded" || Status == "Pending") && ViewState["StatusOnLoad"].ToString() == "Rejected")
                        {
                            dsRemainingNoOfleaves = objLeaveApplicationEventData.GetRemainingNumberOfLeaves(Employee_Id, LeaveTypeId, Convert.ToInt32(ViewState["vsLeaveApplication_Id"]), "01/01/1900");
                            dsRemainingNoOfleaves.Tables[0].TableName = "Details";
                            if (dsRemainingNoOfleaves.Tables.Count > 0)
                            {
                                if (dsRemainingNoOfleaves.Tables[0].Rows.Count > 0)
                                {
                                    dblCurrLeave = Convert.ToDouble(dsRemainingNoOfleaves.Tables["Details"].Rows[0]["RemainingNoOfLeaves"]);
                                }
                            }
                            if (dblCurrLeave > 0)
                            {
                                boolChkLeave = false;
                                //lbl_Error.Text = "Current year quota available for this leave type";
                                base.Message("Current year quota available for this leave type");
                                return;
                            }
                        }
                        else if (Status == "Approved")
                        {
                            //Check other leaves exists before borrow leave
                            intLeaveCount = objLeaveApplicationEventData.CheckLeaveExistsBeforeBorrow(Leave_FromDate, Leave_ToDate, LeaveTypeId, Employee_Id);
                            if (intLeaveCount > 0)
                            {
                                boolChkLeave = false;
                                //lbl_Error.Text = "Already current year leave applications are available to approve/reject";
                                base.Message("Already current year leave applications are available to approve/reject");
                                return;
                            }
                            else
                            {
                                dsRemainingNoOfleaves = objLeaveApplicationEventData.GetRemainingNumberOfLeaves(Employee_Id, LeaveTypeId, Convert.ToInt32(ViewState["vsLeaveApplication_Id"]), "01/01/1900");
                                dsRemainingNoOfleaves.Tables[0].TableName = "Details";
                                if (dsRemainingNoOfleaves.Tables.Count > 0)
                                {
                                    if (dsRemainingNoOfleaves.Tables[0].Rows.Count > 0)
                                    {
                                        dblCurrLeave = Convert.ToDouble(dsRemainingNoOfleaves.Tables["Details"].Rows[0]["RemainingNoOfLeaves"]);
                                    }
                                }
                                if (dblCurrLeave > 0)
                                {
                                    boolChkLeave = false;
                                    //lbl_Error.Text = "Current year quota available for this leave type";
                                    base.Message("Current year quota available for this leave type");
                                    return;
                                }
                                // update the status,remareks(only) of leave application
                                //insert into TA_Tbl_LeaveConversation
                                //objLeaveApplicationEventData.UpdateLeaveApplicationConversation(LeaveApplication_Id, Status, Convert.ToInt32(ViewState["vsCommentsBy"].ToString()), Remarks, Convert.ToInt32(Session["EmpAutoId"]));                                
                                //objLeaveApplicationEventData.UpdateYearClosureByLeaveSanction(NumberOfDays, LeaveTypeId, Employee_Id, "AB", Convert.ToInt32(Session["EmpAutoId"]));                                
                            }
                        }
                        else if ((Status == "Rejected" || Status == "Forwarded" || Status == "Pending") && ViewState["StatusOnLoad"].ToString() == "Approved")
                        {
                            // update the status,remareks(only) of leave application
                            //insert into TA_Tbl_LeaveConversation
                            //objLeaveApplicationEventData.UpdateLeaveApplicationConversation(LeaveApplication_Id, Status, Convert.ToInt32(ViewState["vsCommentsBy"].ToString()), Remarks, Convert.ToInt32(Session["EmpAutoId"]));
                            //objLeaveApplicationEventData.UpdateYearClosureByLeaveSanction(NumberOfDays, LeaveTypeId, Employee_Id, "RB", Convert.ToInt32(Session["EmpAutoId"]));
                        }
                        else if (Status == "Resend")
                        {
                            // update the status,remareks(only) of leave application
                            //insert into TA_Tbl_LeaveConversation
                            //objLeaveApplicationEventData.UpdateLeaveApplicationConversation(LeaveApplication_Id, Status, Convert.ToInt32(ViewState["vsCommentsBy"].ToString()), Remarks, Convert.ToInt32(Session["EmpAutoId"]));
                        }
                        else if (Status == "Reply" && ViewState["StatusOnLoad"].ToString() == "Reply")
                        {
                            boolChkLeave = false;
                            base.Message("Cannot Reply");
                            return;
                        }
                    }
                    else
                    {
                        boolChkLeave = false;
                        base.Message("Please change the status");
                        return;
                    }
                }
            }
            if (boolChkLeave == true)
            {
                if (strTypeOfLeave != "Leave")
                {
                    //insert into TA_Tbl_LeaveConversation
                    //objLeaveApplicationEventData.UpdateLeaveApplicationConversation(LeaveApplication_Id, Status, Convert.ToInt32(ViewState["vsCommentsBy"].ToString()), Remarks, Convert.ToInt32(Session["EmpAutoId"]));
                }
                objLeaveApplicationEventData.UpdateLeaveApplicationSanction(LeaveApplication_Id, Status, Remarks, Convert.ToInt32(Session["EmpAutoId"]), intimationType);
                Session["LeaveApplicationIDs"] = null;
            }
            //common to all status
            objLeaveApplicationEventData.UpdateLeaveApplicationConversation(LeaveApplication_Id, Status, Convert.ToInt32(ViewState["vsCommentsBy"].ToString()), Remarks, Convert.ToInt32(Session["EmpAutoId"]));
            // Update Processed Data Flag
            //objLeaveApplicationEventData.UpdateProcessedDataFlag(Employee_Id, Leave_FromDate, Leave_ToDate, 0);
            ControlCreation();
            if (checkEmail == true)
            {
                if (Status == "Approved" || Status == "Forwarded" || Status == "Rejected" || Status == "Resend")
                {
                    SendMail(intFirstLevelAuthorityId, intSecondLevelAuthorityId, strEmailIdReportingTo, strEmailIdSanctionAuthority, EmployeeEamilId, ViewState["Employee_code_Id"].ToString(), EmployeeName, Status, txtRemarks.Text.Trim().Replace("'", "''"), strLeaveApplicationDate, strNoOfDays, leaveType, levelName, Convert.ToString(ViewState["vsStrApprovalCC"]), intimationType); //ViewState["vsStrApprovalCC"].ToString()
                }
            }
            if (checkEmail == true)
            {
                string strScript = string.Empty;
                strScript = strScript + "<script language='javascript'>";
                strScript = strScript + "alert('Leave Application saved');";
                strScript = strScript + "RedirectionFunction();";
                //strScript = strScript + "location.replace('TA_UI_Transactions_LeaveSanctionView.aspx?LeaveApplication_Id=" + Request.QueryString["LeaveApplication_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_LeaveSanction.aspx');";                
                strScript = strScript + "</script>";
                //Dispaly alert messsage.
                //Response.Redirect("../Transactions/TA_UI_Transactions_LeaveSanctionView.aspx?LeaveApplication_Id=" + Request.QueryString["LeaveApplication_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());       
                Page.RegisterStartupScript("AlertPsaved36774", strScript);
            }
            else
            {
                string strScript = string.Empty;
                strScript = strScript + "<script language='javascript'>";
                strScript = strScript + "alert('Leave Application saved,Email not sent');";
                strScript = strScript + "RedirectionFunction();";
                //strScript = strScript + "location.replace('TA_UI_Transactions_LeaveSanctionView.aspx?LeaveApplication_Id=" + Request.QueryString["LeaveApplication_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_LeaveSanction.aspx');";
                strScript = strScript + "</script>";
                //Dispaly alert messsage.
                Page.RegisterStartupScript("AlertPAdd3674", strScript);
            }
            //btn_Save.Enabled = true;
            //btn_Save.Text = "Save";
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    #endregion
}
