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.Net.Mail;
using System.IO;
/****************************************************************************************************************************
* Project Name    : TimeCheck                              Started Date  : 12-Aug-2007
* Module          : Permission Sanction                    Last Modified : 14-Aug-2007
* Programmer      : Prabakaran.P
* Current Storage : \\Angler56\Projects\Inprogress\SCREEN1206\code\Time_AttendanceApp
* BackUp          :
* 
* Modified By      :   Manjula.P
* Modified On      :   28-Sep-2013
* Descriptinos     :   Condition added for getting when the forward authority is in super admin group. Code : 0019023
****************************************************************************************************************************/
public partial class Transactions_TA_UI_Transactions_PermissionSanctionModify : Base.BasePage
{
    #region VariableDeclaration
    DataSet ds_RecordsCountLeaveReportingTo = new DataSet();
    DataSet ds_ReportingToSanctionAuthorityList = new DataSet();
    SMSNotification objsms = new SMSNotification();
    bool blnCheckSMS = true;
    GetReports rptEmp = new GetReports();
    GetReports EmailEmpUpdate = new GetReports();
    ResourceManager rm;
    CultureInfo objCultureInfo;
    CultureInfo ci;
    DataTable dtSanctionView = new DataTable();
    GetReports getMail = new GetReports();
    LeaveApplicationEventData objLeaveApplicationEventData = new LeaveApplicationEventData();
    PermissionEventData objPermissionEventData = new PermissionEventData();
    cls_Common objClassCommon = new cls_Common();
    int PermissionApplication_Id;
    DataSet ds_EmailIdOfSanctionAuthority = new DataSet();
    DataSet dsEmailIdOfReportingTo = new DataSet();
    DataSet dsRecordsCount = new DataSet();
    int Permission_Id, Employee_Id;
    string Status, Remarks, EmployeeEamilId, strEmailIdSanctionAuthority, EmployeeName, Employee_Code_Id, gstrDateFormat, strlevelName, gstrTimeFormat;
    bool checkEmail = true;
    DataSet dsLeaveConversation = new DataSet(); string strHtml = string.Empty;
    #endregion
    #region PageLoad
    protected override void Page_Load(object sender, EventArgs e)
    {
        
        base.Page_Load(sender, e);
        string source_Language;
        source_Language = Convert.ToString(Session["Session_ActiveLanguage"]);
        rm = new ResourceManager(source_Language, System.Reflection.Assembly.Load("App_GlobalResources"));
        ci = Thread.CurrentThread.CurrentCulture;
        site.SiteMapProvider = Convert.ToString(Session["SiteMapProvider"]);
        LoadStrings(ci);
        string strSetAlert = "";
        strSetAlert = strSetAlert + "<script language='javascript'>";
        strSetAlert = strSetAlert + "MaxLengthh('" + rm.GetString("Alert_MaximumLengthis", ci) + "');";
        strSetAlert = strSetAlert + "SetAlertMessages('" + rm.GetString("Alert_LeaveType", ci) + "','" + rm.GetString("Alert_LeaveRestictHoliday", ci) + "','" + rm.GetString("Alert_Fromdate", ci) + "','" + rm.GetString("Alert_ToDate", ci) + "','" + rm.GetString("Alert_FillReasons", ci) + "','" + rm.GetString("Alert_Are_you_sure_to_Save", ci) + "');";
        strSetAlert = strSetAlert + "</script>";
        PermissionApplication_Id = Convert.ToInt32(Request.QueryString["Permission_Id"]);
        Page.RegisterStartupScript("SetAlertMessages", strSetAlert);
        UserRights();
        Session["SanctionSelected"] = "2";
        if (!IsPostBack)
        {
            objClassCommon.menu("Approvals", "248");
            if (Session["SanctionUrl"] != null)
            {
                Session["SanctionUrl"] = null;
            }
            if (Convert.ToString(Session["UserGroupName"]) != "SuperAdmin")
            {
                ds_RecordsCountLeaveReportingTo = objLeaveApplicationEventData.GetRecordsCountLeaveReportingTo(Convert.ToInt32(Session["EmpAutoId"]));
                if (Convert.ToInt32(ds_RecordsCountLeaveReportingTo.Tables[0].Rows[0]["RecordsCount"]) > 0)
                {
                    //rblStatus.Items[0].Enabled = false;
                    rbApproved.Enabled = false;
                }
                dsRecordsCount = objLeaveApplicationEventData.GetRecordsCountLeaveSanction(Convert.ToInt32(Session["EmpAutoId"]));
                if (Convert.ToInt32(dsRecordsCount.Tables[0].Rows[0]["RecordsCount"]) > 0)
                {
                    //rblStatus.Items[1].Enabled = false;
                    //rblStatus.Items[2].Enabled = false;
                    rbForwarded.Enabled = false;
                    rbPending.Enabled = false;
                }
            }
            Status = Request.QueryString["Status"];


            String EmpID = Session["hdnEmpID"].ToString();
            String ReportName = Session["HdnReportName"].ToString();
            String FromDate = Session["HdnFrom"].ToString();
            String TO = Session["HdnTo"].ToString();
            String ReportNo = Session["HdnReport"].ToString();
            String Authority = Session["HdnAuthority"].ToString();
            
            if(ReportNo=="" & Authority == "")
            {
            SanctionViewDetails();
            ds_ReportingToSanctionAuthorityList = objLeaveApplicationEventData.SelectReportingToSanctionAuthorityForPermission(PermissionApplication_Id);
            }
                if (Status != "Approved" && Status != "Rejected")
                {
                    if (Convert.ToString(Session["UserGroupName"]) != "SuperAdmin")
                    {
                        if (Convert.ToString(Session["EmpAutoId"]) == Convert.ToString(ds_ReportingToSanctionAuthorityList.Tables[0].Rows[0]["Reporting_To"]) && Convert.ToString(Session["EmpAutoId"]) == Convert.ToString(ds_ReportingToSanctionAuthorityList.Tables[0].Rows[0]["Leave_Sanc_Authority"]))
                        {
                            rbApproved.Enabled = true;
                            //rblStatus.Items[0].Enabled = true;
                        }
                        else if (Convert.ToString(Session["EmpAutoId"]) == Convert.ToString(ds_ReportingToSanctionAuthorityList.Tables[0].Rows[0]["Reporting_To"]))
                        {

                            rbApproved.Enabled = false;
                            rbForwarded.Enabled = true;
                            rbPending.Enabled = false;
                            //rblStatus.Items[0].Enabled = false;
                            //rblStatus.Items[1].Enabled = true;
                            //rblStatus.Items[2].Enabled = false;
                            if (Status == "Forwarded")
                            {
                                btn_Save.Enabled = false;
                                btn_Save.OnClientClick = null;
                            }
                        }
                        else if (Convert.ToString(Session["EmpAutoId"]) == Convert.ToString(ds_ReportingToSanctionAuthorityList.Tables[0].Rows[0]["Leave_Sanc_Authority"]))
                        {
                            //rblStatus.Enabled = true;
                            //rblStatus.Items[0].Enabled = true;
                            rbApproved.Enabled = true;
                        }
                    }
                    else
                    {
                        //rblStatus.Enabled = true;
                        //rblStatus.Items[0].Enabled = true;
                        //rblStatus.Items[1].Enabled = true;
                        //rblStatus.Items[2].Enabled = true;
                        //rblStatus.Items[3].Enabled = true;
                        rbApproved.Enabled = true;
                        rbForwarded.Enabled = true;
                        rbPending.Enabled = true;
                        rbRejected.Enabled = true;
                    }
                }
                else if (Status == "Approved")
                {
                    if (Convert.ToString(Session["EmpAutoId"]) == Convert.ToString(ds_ReportingToSanctionAuthorityList.Tables[0].Rows[0]["Reporting_To"]))
                    {
                        btn_Save.Enabled = false;
                        btn_Save.OnClientClick = null;
                    }
                    else if (Convert.ToString(Session["EmpAutoId"]) == Convert.ToString(ds_ReportingToSanctionAuthorityList.Tables[0].Rows[0]["Leave_Sanc_Authority"]))
                    {
                        btn_Save.Enabled = false;
                        btn_Save.OnClientClick = null;
                    }
                }
                if (Convert.ToString(Session["TopMenuPrevious"]) == "")
                {
                    LoadYear();
                    GenerateMenu();
                    loadMenu();
                }
                objClassCommon.menu("Approvals", "248");
                ControlCreation();

            ApprovalforEmailtrigger();

        }



        
    }

    private void ApprovalforEmailtrigger()
    {
        

        String EmpID = Session["hdnEmpID"].ToString();
        String ReportName = Session["HdnReportName"].ToString();
        String FromDate = Session["HdnFrom"].ToString();
        String TO = Session["HdnTo"].ToString();
        String ReportNo = Session["HdnReport"].ToString();
        String Authority = Session["HdnAuthority"].ToString();
        if (EmpID != "" & ReportName != "" & FromDate != "" || ReportNo != "" || Authority != "")
        {
            
            DataSet daAbsent = new DataSet();

            if (EmpID != "" & ReportName == "LateEntry" & FromDate != "" )
            {
                daAbsent = rptEmp.SelectAbsentForEmailNotification(EmpID, FromDate, "", "LateEntryApproval");
                
                string LateEntry = daAbsent.Tables[0].Rows[0]["LateEntry"].ToString();
                string LateHrs = daAbsent.Tables[0].Rows[0]["LateHrs"].ToString();
                lblPermissionFromTime.Text = daAbsent.Tables[0].Rows[0]["LateEntry"].ToString();
                lblPermissionToTime.Text = daAbsent.Tables[0].Rows[0]["LateHrs"].ToString();
                lbl_PermissionFromTime.Text = "";
                lbl_PermissionFromTime.Text = "In Time";
                lbl_PermissionToTime.Text = "";
                lbl_PermissionToTime.Text = "Late By";
                lbl_Header.Text = "";
                lbl_Header.Text = "Late Reason Entry Approval Sanction";
            }
            else if (EmpID != "" & ReportName == "Absent" & FromDate != "" )
            {
                daAbsent = rptEmp.SelectAbsentForEmailNotification(EmpID, FromDate, "", "AbsentApproval");
                string LateEntry = daAbsent.Tables[0].Rows[0]["AbsentAN"].ToString();
                string LateHrs = daAbsent.Tables[0].Rows[0]["AbsentFN"].ToString();
                lblPermissionFromTime.Text = daAbsent.Tables[0].Rows[0]["AbsentAN"].ToString();
                lblPermissionToTime.Text = daAbsent.Tables[0].Rows[0]["AbsentFN"].ToString();
                lbl_PermissionFromTime.Text = "";
                lbl_PermissionFromTime.Text = "First Session";
                lbl_PermissionToTime.Text = "";
                lbl_PermissionToTime.Text = "Secound Session";
                lbl_Header.Text = "";
                lbl_Header.Text = "Absent Reason Entry Approval Sanction";
            }
            else if (EmpID != "" & ReportName == "EarlyExit" & FromDate != "")
            {
                daAbsent = rptEmp.SelectAbsentForEmailNotification(EmpID, FromDate, "", "EarlyExitApproval");
                string LateEntry = daAbsent.Tables[0].Rows[0]["EarlyExit"].ToString();
                string LateHrs = daAbsent.Tables[0].Rows[0]["EarlyExitHrs"].ToString();
                lblPermissionFromTime.Text = daAbsent.Tables[0].Rows[0]["EarlyExit"].ToString();
                lblPermissionToTime.Text = daAbsent.Tables[0].Rows[0]["EarlyExitHrs"].ToString();
                lbl_PermissionFromTime.Text = "";
                lbl_PermissionFromTime.Text = "Out Time";
                lbl_PermissionToTime.Text = "";
                lbl_PermissionToTime.Text = "Early By";
                lbl_Header.Text = "";
                lbl_Header.Text = "Early Exit Reason Entry Approval Sanction";
            }

            //EmailtriggetID,EmployeeID,Employee_Code_ID,Employee_Name,ShiftDate,AbsentAN,AbsentFN,Reason,Status
            //EmailtriggetID,EmployeeID,Employee_Code_ID,Employee_Name,ShiftDate, EarlyExit, EarlyExitHrs,Reason,Status
            DataSet EmailGet = new DataSet();
            EmailGet = getMail.SelectTriggerEmail(EmpID);
            string EmployeeEmail = EmailGet.Tables[0].Rows[0]["EmployeeEmail"].ToString();
            string ReportPerEmail = EmailGet.Tables[0].Rows[1]["EmployeeEmail"].ToString();
            string AthorityEmail = EmailGet.Tables[0].Rows[2]["EmployeeEmail"].ToString();
            string Empdepartment = EmailGet.Tables[0].Rows[3]["EmployeeEmail"].ToString();
            string EmpReportNo = EmailGet.Tables[0].Rows[1]["EmployeeCodes"].ToString();
            string EmpAuthorityNo = EmailGet.Tables[0].Rows[2]["EmployeeCodes"].ToString();

            //EmailtriggetID,EmployeeID,Employee_Code_ID,Employee_Name,ShiftDate,LateEntry, LateHrs,Reason,Status
            string EmailtriggetID = daAbsent.Tables[0].Rows[0]["EmailtriggetID"].ToString();
            string EmployeeID = daAbsent.Tables[0].Rows[0]["EmployeeID"].ToString();
            string Employee_Code_ID = daAbsent.Tables[0].Rows[0]["Employee_Code_ID"].ToString();
            string Employee_Name = daAbsent.Tables[0].Rows[0]["Employee_Name"].ToString();
            string ShiftDate = daAbsent.Tables[0].Rows[0]["ShiftDate"].ToString();
            string Reason = daAbsent.Tables[0].Rows[0]["Reason"].ToString();
            string Statusss = daAbsent.Tables[0].Rows[0]["Status"].ToString();
            Session["EmailtriggetID"] = EmailtriggetID;

            lblempid.Text = daAbsent.Tables[0].Rows[0]["Employee_Code_ID"].ToString(); ;
            lbl_EmployeeName.Text = daAbsent.Tables[0].Rows[0]["Employee_Name"].ToString();
            EmployeeEamilId = EmailGet.Tables[0].Rows[0]["EmployeeEmail"].ToString();
            lblPermissionDate.Text = (Convert.ToDateTime(daAbsent.Tables[0].Rows[0]["ShiftDate"])).ToString(Session["MDateFormat"].ToString());
            ViewState["vPermissionFromTime"] = lblPermissionFromTime.Text;
            ViewState["vPermissionToTime"] = lblPermissionToTime.Text;
            lblReason.Text = daAbsent.Tables[0].Rows[0]["Reason"].ToString();
            
            
            btn_Cancel.Visible = false;
            if (Statusss == "Pending") 
            {
                rbForwarded.Enabled = true;
                rbPending.Checked = true;
                rbApproved.Enabled = false;
                rbRejected.Enabled = false;
            }
            else if (Statusss == "Forwarded")
            {
                rbForwarded.Checked = true;
                rbPending.Enabled = false;
                rbRejected.Enabled = true;
                rbForwarded.Enabled = false;

            }
            else if (Statusss == "Approved")
            {
                rbApproved.Checked = true;
                rbPending.Enabled = false;
                rbRejected.Enabled = false;
                rbForwarded.Enabled = false;
            }
            else if (Statusss == "Rejected")
            {
                rbRejected.Checked = true;
                rbPending.Enabled = false;
                rbForwarded.Enabled = false;
                rbApproved.Enabled = false;
            }


        }
    }

    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;
    }
    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;
        }
    }
    #endregion
    #region UserDefinedFunction
    /// <summary>
    /// Display permission Application Details
    /// </summary>
    private void SanctionViewDetails()
    {
        DataSet dsEmployeeGroup = new DataSet();
        dsEmployeeGroup = objLeaveApplicationEventData.GetEmployeeGroupName(Convert.ToInt32(Session["EmpAutoId"]));
        if (dsEmployeeGroup.Tables[0].Rows.Count > 0)
        {
            if (dsEmployeeGroup.Tables[0].Rows[0]["GroupName"].ToString() == "SuperAdmin")
            {
                //rblStatus.Enabled = true;
            }
            else
            {
            }
        }
        else
        {
        }
        Permission_Id = Convert.ToInt32(Request.QueryString["Permission_Id"]);
        dtSanctionView = objPermissionEventData.GetPermissionByPermissionId(Permission_Id);
        string LastName = "";
        if (dtSanctionView.Rows[0]["Employee_LastName"] != DBNull.Value)
        {
            LastName = dtSanctionView.Rows[0]["Employee_LastName"].ToString();
        }
        lblempid.Text = dtSanctionView.Rows[0]["Employee_code_id"].ToString();
        lbl_EmployeeName.Text = dtSanctionView.Rows[0]["Employee_FirstName"].ToString() + " " + LastName;
        EmployeeEamilId = dtSanctionView.Rows[0]["EmailId"].ToString();
        lblPermissionDate.Text = (Convert.ToDateTime(dtSanctionView.Rows[0]["Permission_Date"])).ToString(Session["MDateFormat"].ToString());
        string[] PerTime = dtSanctionView.Rows[0]["Permission_FromTime"].ToString().Split(" ".ToCharArray());
        string timePart1 = PerTime[0].ToString() + " " + PerTime[1].ToString();
        lblPermissionFromTime.Text = (Convert.ToDateTime(PerTime[0])).ToString(Session["MDateFormat"].ToString()) + " " + DateTime.Parse(timePart1).ToString(Session["MTimeFormat"].ToString());
        string[] PerTime1 = dtSanctionView.Rows[0]["Permission_ToTime"].ToString().Split(" ".ToCharArray());
        string timePart2 = PerTime1[0].ToString() + " " + PerTime1[1].ToString();
        lblPermissionToTime.Text = (Convert.ToDateTime(PerTime1[0])).ToString(Session["MDateFormat"].ToString()) + " " + DateTime.Parse(timePart2).ToString(Session["MTimeFormat"].ToString());
        ViewState["vPermissionFromTime"] = lblPermissionFromTime.Text;
        ViewState["vPermissionToTime"] = lblPermissionToTime.Text;
        lblReason.Text = dtSanctionView.Rows[0]["Permission_Reason"].ToString();
        //  txtRemarks.Text = dtSanctionView.Rows[0]["Remarks"].ToString();
        ViewState["StatusOnLoad"] = dtSanctionView.Rows[0]["Permission_Status"].ToString();
        if (dtSanctionView.Rows[0]["Permission_Status"].ToString() == "Pending")
        {
            //rblStatus.SelectedValue = "Pending";
            rbPending.Checked = true;
        }
        else if (dtSanctionView.Rows[0]["Permission_Status"].ToString() == "Forwarded")
        {
            //rblStatus.SelectedValue = "Forwarded";
            rbForwarded.Checked = true;
        }
        else if (dtSanctionView.Rows[0]["Permission_Status"].ToString() == "Rejected")
        {
            if (Status == "Approved")
                rbApproved.Checked = true;
            else if (Status == "Forwarded")
                rbForwarded.Checked = true;
            else if (Status == "Pending")
                rbPending.Checked = true;
            else if (Status == "Rejected")
                rbRejected.Checked = true;

            //rblStatus.SelectedValue = Status;
            ds_ReportingToSanctionAuthorityList = objLeaveApplicationEventData.SelectReportingToSanctionAuthorityForPermission(PermissionApplication_Id);
            if (Convert.ToString(Session["UserGroupName"]) != "SuperAdmin")
            {
                if (Convert.ToString(Session["EmpAutoId"]) == Convert.ToString(ds_ReportingToSanctionAuthorityList.Tables[0].Rows[0]["Reporting_To"]) && Convert.ToString(Session["EmpAutoId"]) == Convert.ToString(ds_ReportingToSanctionAuthorityList.Tables[0].Rows[0]["Leave_Sanc_Authority"]))
                {
                    string s = DateTime.Now.ToShortDateString();
                    if (Convert.ToDateTime(dtSanctionView.Rows[0]["Permission_Date"]) >= Convert.ToDateTime(s))
                    {
                        if (Status == "Approved")
                            rbApproved.Checked = true;
                        else if (Status == "Forwarded")
                            rbForwarded.Checked = true;
                        else if (Status == "Pending")
                            rbPending.Checked = true;
                        else if (Status == "Rejected")
                            rbRejected.Checked = true;
                        //rblStatus.SelectedValue = Status;
                        rbApproved.Enabled = true;
                        //rblStatus.Items[0].Enabled = true;
                    }
                    else
                    {
                        btn_Save.Enabled = false;
                        btn_Save.OnClientClick = null;
                        //rblStatus.Enabled = false;
                    }
                }
                else if (Convert.ToString(Session["EmpAutoId"]) == Convert.ToString(ds_ReportingToSanctionAuthorityList.Tables[0].Rows[0]["Reporting_To"]))
                {
                    string s = DateTime.Now.ToShortDateString();
                    if (Convert.ToDateTime(dtSanctionView.Rows[0]["Permission_Date"]) >= Convert.ToDateTime(s))
                    {
                        rbForwarded.Enabled = true;
                        rbPending.Enabled = false;
                        //rblStatus.Items[1].Enabled = true;
                        //rblStatus.Items[2].Enabled = false;
                    }
                    else
                    {
                        btn_Save.Enabled = false;
                        btn_Save.OnClientClick = null;
                        //rblStatus.Enabled = false;
                    }
                }
                else if (Convert.ToString(Session["EmpAutoId"]) == Convert.ToString(ds_ReportingToSanctionAuthorityList.Tables[0].Rows[0]["Leave_Sanc_Authority"]))
                {
                    string s = DateTime.Now.ToShortDateString();
                    if (Convert.ToDateTime(dtSanctionView.Rows[0]["Permission_Date"]) >= Convert.ToDateTime(s))
                    {
                        //rblStatus.Enabled = true;
                        rbApproved.Enabled = true;
                        rbPending.Enabled = true;
                        //rblStatus.Items[0].Enabled = true;
                        //rblStatus.Items[3].Enabled = true;
                        //rblStatus.SelectedValue = Status;
                        if (Status == "Approved")
                            rbApproved.Checked = true;
                        else if (Status == "Forwarded")
                            rbForwarded.Checked = true;
                        else if (Status == "Pending")
                            rbPending.Checked = true;
                        else if (Status == "Rejected")
                            rbRejected.Checked = true;
                    }
                    else
                    {
                        btn_Save.Enabled = false;
                        btn_Save.OnClientClick = null;
                        //rblStatus.Enabled = false;
                    }
                }
            }
            txtRemarks.ReadOnly = true;
        }
        else if (dtSanctionView.Rows[0]["Permission_Status"].ToString() == "Approved")
        {
            rbApproved.Checked = true;
            //rblStatus.SelectedValue = "Approved";
            //rblStatus.Enabled = false;
        }
        if (dsEmployeeGroup.Tables[0].Rows.Count > 0)
        {
            if (dsEmployeeGroup.Tables[0].Rows[0]["GroupName"].ToString() == "SuperAdmin")
            {
                //rblStatus.Enabled = true;
            }
            else
            {
            }
        }
        else
        {
        }
    }
    /// <summary>
    /// Calculate Number of hours applied
    /// </summary>
    /// <param name="startTime"></param>
    /// <param name="EndTime"></param>
    /// <returns></returns>
    public string CalculateNumberOfHoursApplied(string startTime, string EndTime)
    {
        TimeSpan tsDiff = new TimeSpan();
        DateTime dtmIn = DateTime.Parse(startTime);
        DateTime dtmOut = DateTime.Parse(EndTime);
        tsDiff = dtmOut.Subtract(dtmIn);
        string s = tsDiff.ToString();
        int sReturn = s.LastIndexOf(':');
        string RemainHours = s.Remove(sReturn);
        return (RemainHours);
    }
    /// <summary>
    /// Sending email to the Employee who applied for this permission
    /// </summary>
    /// <param name="empEmailId"></param>
    /// <param name="Status"></param>
    private void SendMailToApplicant(string empEmailId, string strReportingToEmailId, string strSanctionEmailId, string Status, string Remarks, string EmployeeCodeId, string TotalHours, string levelName)
    {
        MailMessage mailMessage = new MailMessage();
        string scriptText;
        DataTable dtTableScript = new DataTable();
        string strFromEmailId = string.Empty;
        try
        {
            string ScriptType = "Permission Application Sanction By Reporting to Person";
            dtTableScript = objLeaveApplicationEventData.GetEmailScripts(ScriptType);
            if (dtTableScript.Rows.Count > 0)
            {
                scriptText = dtTableScript.Rows[0]["ScriptText"].ToString();
                //if (Session["loginEmailId"] != null && Session["loginEmailId"].ToString() != string.Empty)
                //{
                //    mailMessage.From = new MailAddress(Session["loginEmailId"].ToString());
                //    strFromEmailId = Convert.ToString(Session["loginEmailId"]);
                //}
                //else
                //{
                mailMessage.From = new MailAddress(ConfigurationManager.AppSettings.Get("FromId"));
                strFromEmailId = Convert.ToString(ConfigurationManager.AppSettings.Get("FromId"));
                //}
                if (Status == "Forwarded")
                {
                    if (strSanctionEmailId != string.Empty)
                    {
                        mailMessage.To.Add(new MailAddress(strSanctionEmailId));
                    }
                    if (empEmailId != string.Empty)
                    {
                        mailMessage.CC.Add(new MailAddress(empEmailId));
                    }
                }
                if (Session["loginEmailId"] != null && Session["loginEmailId"].ToString() != string.Empty)
                {
                    if (strSanctionEmailId != strReportingToEmailId)
                    {
                        if (Status != "Forwarded")
                        {
                            if (Session["loginEmailId"].ToString() == strSanctionEmailId)
                            {
                                if (empEmailId != string.Empty)
                                {
                                    mailMessage.To.Add(new MailAddress(empEmailId));
                                }
                                if (strReportingToEmailId != string.Empty)
                                {
                                    mailMessage.CC.Add(new MailAddress(strReportingToEmailId));
                                }
                            }
                            if (Session["loginEmailId"].ToString() == strReportingToEmailId)
                            {
                                if (empEmailId != string.Empty)
                                {
                                    mailMessage.To.Add(new MailAddress(empEmailId));
                                }
                            }
                        }
                    }
                    else
                    {
                        if (Status != "Forwarded")
                        {
                            if (empEmailId != string.Empty)
                            {
                                mailMessage.To.Add(new MailAddress(empEmailId));
                            }
                        }
                    }
                }
                else
                {
                    if (Status != "Forwarded")
                    {
                        if (empEmailId != string.Empty)
                        {
                            mailMessage.To.Add(new MailAddress(empEmailId));
                        }
                    }
                }
                if (Status == "Approved")
                {
                    Status = rm.GetString("btn_Approved", ci);
                }
                else if (Status == "Forwarded")
                {
                    Status = rm.GetString("btn_Forwarded", ci);
                }
                else if (Status == "Pending")
                {
                    Status = rm.GetString("btn_Pending", ci);
                }
                else if (Status == "Rejected")
                {
                    Status = rm.GetString("btn_Reject", ci);
                }
                if (Convert.ToString(Session["LevelId"]) == string.Empty)
                    Session["LevelId"] = Request.QueryString["LevelId"].ToString();
                Permission_Id = Convert.ToInt32(Request.QueryString["Permission_Id"]);

                mailMessage.Subject = rm.GetString("email_YourPermissionApplicationFor", ci) + " - " + lblPermissionDate.Text + " | " + Employee_Code_Id + " - " + EmployeeName + " | " + levelName + " - " + Status;
                mailMessage.Body = scriptText.Replace("<<lblPermissionSanction>>", rm.GetString("email_PermissionForm", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<lblEmployeeId>>", rm.GetString("email_EmployeeId", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<EmployeeId>>", EmployeeCodeId);
                mailMessage.Body = mailMessage.Body.Replace("<<lblEmployeeName>>", rm.GetString("email_EmployeeName", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<EmployeeName>>", lbl_EmployeeName.Text);
                mailMessage.Body = mailMessage.Body.Replace("<<lblPermissionDate>>", rm.GetString("Permission_PermissionDate", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<PermissionDate>>", lblPermissionDate.Text);
                mailMessage.Body = mailMessage.Body.Replace("<<lblNumberOfHoursApplied>>", rm.GetString("email_NumberOfHoursApplied", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<NumberOfHoursApplied>>", TotalHours);
                mailMessage.Body = mailMessage.Body.Replace("<<lblPermission>>", rm.GetString("Dash_Permission", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<lblFromTime>>", rm.GetString("email_FromDate", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<FromTime>>", lblPermissionFromTime.Text);
                mailMessage.Body = mailMessage.Body.Replace("<<lblToTime>>", rm.GetString("email_ToDate", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<ToTime>>", lblPermissionToTime.Text);
                mailMessage.Body = mailMessage.Body.Replace("<<lblStatus>>", rm.GetString("email_Status", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<Status>>", Status);
                mailMessage.Body = mailMessage.Body.Replace("<<lblReason>>", rm.GetString("email_Reason", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<Reason>>", lblReason.Text);
                mailMessage.Body = mailMessage.Body.Replace("<<lblRemarks>>", rm.GetString("email_Remarks", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<Remarks>>", Remarks);
                if (Status == "Forwarded" || Status == "Pending")
                {
                    mailMessage.Body = mailMessage.Body.Replace("<<LinkData>>", Convert.ToString(Session["HostServerURL"]) + "?Permission_Id=" + Convert.ToString(Permission_Id) + "&LevelId=" + Session["LevelId"] + "&Status=" + Status + "&ApprovalType=Permission");
                }
                else
                {
                    string strReplaceText = "<a href=<<LinkData>>><font face=\"Arial\" size=\"2\">Click here for approval</font>";
                    mailMessage.Body = mailMessage.Body.Replace(strReplaceText, string.Empty);
                }
                objClassCommon.SendMail(mailMessage);
            }
            else
            {
                objLeaveApplicationEventData.InsertLeaveApplicationDetailsInEmailTrigger(Permission_Id, strFromEmailId, empEmailId, strReportingToEmailId, rm.GetString("email_YourPermissionApplicationFor", ci) + " - " + lblPermissionDate + " | " + Status, mailMessage.Body.ToString(), "", "PermissionSanction");
                checkEmail = false;
            }
        }
        catch
        {
            objLeaveApplicationEventData.InsertLeaveApplicationDetailsInEmailTrigger(Permission_Id, strFromEmailId, empEmailId, strReportingToEmailId, rm.GetString("email_YourPermissionApplicationFor", ci) + " - " + lblPermissionDate + " | " + Status, mailMessage.Body.ToString(), "", "PermissionSanction");
            checkEmail = false;
        }
    }

    private void LoadStrings(CultureInfo ci)
    {
        lbl_Header.Text = rm.GetString("Transaction_PermissionSanction_PermissionSanction", ci);
        lbl_EmpName.Text = rm.GetString("email_EmployeeName", ci);
        lbl_Permissiondate.Text = rm.GetString("Permission_PermissionDate", ci);
        lbl_PermissionFromTime.Text = rm.GetString("PermissionSanction_PermissionFromTime", ci);
        lbl_PermissionToTime.Text = rm.GetString("PermissionSanction_PermissionToTime", ci);
        lbl_Reason.Text = rm.GetString("email_Reason", ci);
        lbl_Remarks.Text = rm.GetString("email_Remarks", 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);
        lbl_empid.Text = rm.GetString("email_EmployeeId", ci);
        rbApproved.Text = rm.GetString("btn_Approved", ci);
        rbForwarded.Text = rm.GetString("btn_Forwarded", ci);
        rbPending.Text = rm.GetString("btn_Pending", ci);
        rbRejected.Text = rm.GetString("btn_Reject", ci);
        lblLoading.Text = rm.GetString("ProgressBarText", ci);
    }
    private void UserRights()
    {
        DataSet ds_Checkuser = new DataSet();
        Cls_CheckUser objCheckUser = new Cls_CheckUser();
        ds_Checkuser = objCheckUser.checkRights(248, Convert.ToInt32(Session["userGroup_Id"]), "viewPrv");
        if (ds_Checkuser.Tables[0].Rows.Count == 0)
        {
            if (Convert.ToString(Session["TopMenuPrevious"]) == "")
            {
                LoadYear();
                GenerateMenu();
                loadMenu();
            }
            objClassCommon.menu("PermissionTransaction", "25");
            Response.Redirect("TransactionLandingPage.aspx");
        }
    }

    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;

        divLeaveConversation.Controls.Clear();
        DataSet ds_PermissionConversation = new DataSet();
        ds_PermissionConversation = objPermissionEventData.GetPermissionConversation(Convert.ToInt32(Request.QueryString["Permission_Id"]));
        //if (!IsPostBack)
        //{
        //    // getting leave conversation 

        //    ViewState["PermissionConversation"] = ds_PermissionConversation;
        //}
        if (ds_PermissionConversation != null && ds_PermissionConversation.Tables[0].Rows.Count > 0)
        {
            //if (ViewState["PermissionConversation"] != null)
            //{
            //    ds_PermissionConversation =(DataSet) ViewState["PermissionConversation"];
            //}

            Table leaveConversation = new Table();
            leaveConversation.BorderWidth = 1;
            leaveConversation.CellPadding = 5;
            leaveConversation.CellSpacing = 0;
            // leaveConversation.Width = Unit.Pixel(600);
            leaveConversation.CssClass = "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.HorizontalAlign = HorizontalAlign.Left;
            leaveConversationHr.Cells.Add(leaveConversationHeading3);

            TableHeaderCell leaveConversationHeading1 = new TableHeaderCell();
            //leaveConversationHeading1.Width = 75;
            leaveConversationHeading1.Text = rm.GetString("leaveConversationHeading1", ci);
            leaveConversationHeading1.HorizontalAlign = HorizontalAlign.Left;
            leaveConversationHr.Cells.Add(leaveConversationHeading1);

            TableHeaderCell leaveConversationHeading2 = new TableHeaderCell();
            leaveConversationHeading2.Text = rm.GetString("leaveConversationHeading2", ci);
            //leaveConversationHeading2.Width = 200;
            leaveConversationHeading2.HorizontalAlign = HorizontalAlign.Left;
            leaveConversationHr.Cells.Add(leaveConversationHeading2);

            leaveConversation.Rows.Add(leaveConversationHr);


            if (ds_PermissionConversation.Tables[0].Rows.Count > 0)
            {
                int rowIndex = 0;
                foreach (DataRow drLeaveConversation in ds_PermissionConversation.Tables[0].Rows)
                {
                    dRowReplyResend = dtReplyResend.NewRow();
                    TableRow trLeaveConversation = new TableRow();

                    TableCell tcLeaveConversationRepliedOn = new TableCell();
                    Label lblLeaveConversationRepliedOn = new Label();
                    tcLeaveConversationRepliedOn.BorderWidth = 1;
                    tcLeaveConversationRepliedOn.Width = 200;
                    tcLeaveConversationRepliedOn.BorderColor = System.Drawing.Color.White;

                    lblLeaveConversationRepliedOn.ID = "lblLeaveConversationRepliedOn" + rowIndex;
                    lblLeaveConversationRepliedOn.Text = Convert.ToDateTime(drLeaveConversation["TimeStamp"]).ToString(Session["MDateFormat"].ToString()) + " " + Convert.ToDateTime(drLeaveConversation["TimeStamp"]).ToString(Session["MTimeFormat"].ToString());

                    dRowReplyResend["Date"] = Convert.ToDateTime(drLeaveConversation["TimeStamp"]).ToString(Session["MDateFormat"].ToString()) + " " + Convert.ToDateTime(drLeaveConversation["TimeStamp"]).ToString(Session["MTimeFormat"].ToString());

                    tcLeaveConversationRepliedOn.Controls.Add(lblLeaveConversationRepliedOn);
                    trLeaveConversation.Cells.Add(tcLeaveConversationRepliedOn);

                    TableCell tcLeaveConversationCommentsBy = new TableCell();
                    Label lblLeaveConversationCommentsBy = new Label();
                    tcLeaveConversationCommentsBy.Width = 200;

                    lblLeaveConversationCommentsBy.ID = "lblLeaveConversationCommentsBy" + rowIndex;

                    lblLeaveConversationCommentsBy.Text = objLeaveApplicationEventData.GetEmployeeName(Convert.ToInt32(drLeaveConversation["Emp_Id"].ToString()));
                    dRowReplyResend["Comments By"] = objLeaveApplicationEventData.GetEmployeeName(Convert.ToInt32(drLeaveConversation["Emp_Id"].ToString()));

                    tcLeaveConversationCommentsBy.Controls.Add(lblLeaveConversationCommentsBy);
                    trLeaveConversation.Cells.Add(tcLeaveConversationCommentsBy);

                    TableCell tcLeaveConversationComments = new TableCell();
                    Label lblLeaveConversationComments = new Label();
                    lblLeaveConversationComments.ID = "lblLeaveConversationComments" + rowIndex;
                    lblLeaveConversationComments.Text = drLeaveConversation["Comments"].ToString();
                    dRowReplyResend["Comments"] = drLeaveConversation["Comments"].ToString();

                    tcLeaveConversationComments.Controls.Add(lblLeaveConversationComments);
                    trLeaveConversation.Cells.Add(tcLeaveConversationComments);
                    leaveConversation.Rows.Add(trLeaveConversation);
                    rowIndex += 1;
                    dtReplyResend.Rows.Add(dRowReplyResend);
                }
            }
            divLeaveConversation.Controls.Add(leaveConversation);
        }

        if (ds_PermissionConversation.Tables[0].Rows.Count > 0)
        {
            strHtml = buildPage("Test", dtReplyResend);
        }
    }

    public string buildPage(string strPageTitle, DataTable myDT)
    {
        System.Text.StringBuilder sb = new System.Text.StringBuilder();

        //HTML header
        sb.Append("<html>");
        sb.Append("<head>");
        sb.Append("<title>");
        sb.Append(strPageTitle);
        sb.Append("</title>");
        sb.Append("<style type='text/css'>");
        sb.Append(".Header {color: #FFFFFF; font-family: Arial;font-size: x-small;font-weight: bold;}");
        sb.Append(".rows {font-family: Arial; font-size: x-small;background-color:#FFE3B9}");
        sb.Append(".rowsNew {font-family: Arial; font-size: x-small;background-color:#FFEED5}");
        sb.Append("</style>");
        sb.Append("</head>");
        sb.Append("<body>");
        sb.Append("<table border='1' cellpadding='2' style='border-collapse: collapse' bordercolor='#666666' width='700'>");
        sb.Append("  <tr bgcolor='#003466'>");
        //Table header       
        foreach (DataColumn Col in myDT.Columns)
        {
            sb.Append("<td><span class='Header'>" + Col.ColumnName.ToString() + "</span></td>");
        }

        sb.Append("  </tr>");
        //add rows to the table for the length of the dataset
        int intWidth = 0;

        int intIncrement = 0;
        foreach (DataRow Row in myDT.Rows)
        {
            intWidth = 0;
            if (intIncrement % 2 == 0)
            {
                sb.Append("  <tr>");
            }
            else
            {
                sb.Append("  <tr>");
            }
            foreach (DataColumn Col in myDT.Columns)
            {
                if (intWidth == 2)
                {

                    sb.Append("<td width='60%'><font face='Arial' size='2'>" + Row[Col.ColumnName].ToString() + "</font></td>");

                    //intWidth = 1;
                }
                else
                {

                    sb.Append("<td><font face='Arial' size='2'>" + Row[Col.ColumnName].ToString() + "</font></td>");

                    //intWidth = 0;
                }
                intWidth = intWidth + 1;
            }
            sb.Append("  </tr>");
            intIncrement = intIncrement + 1;
        }
        //Close the html string
        sb.Append("</table>");
        sb.Append("</body>");
        sb.Append("</html>");

        return sb.ToString();
    }


    #endregion
    #region ButtonEvents
    /// <summary>
    /// Save Permission sanction Details
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    /// 
    protected void btn_Save_Click(object sender, EventArgs e)
    {
        String EmpID = Session["hdnEmpID"].ToString();
        String ReportName = Session["HdnReportName"].ToString();
        String FromDate = Session["HdnFrom"].ToString();
        String TO = Session["HdnTo"].ToString();
        String ReportNo = Session["HdnReport"].ToString();
        String Authority = Session["HdnAuthority"].ToString();

        if (EmpID == "" & ReportName == "" & FromDate == "" & ReportNo == "" & Authority == "")
        {
            #region First
            string str = Request.QueryString["LevelId"];
            if (Convert.ToString(Request.QueryString["LevelId"]) == string.Empty || Convert.ToString(Request.QueryString["LevelId"]) == null)
            {
            }
            else
            {
                if (Convert.ToString(Session["LevelId"]) == string.Empty)
                    Session["LevelId"] = Request.QueryString["LevelId"].ToString();
                if (Convert.ToString(Session["PermissionFrom_Date"]) == string.Empty)
                    Session["PermissionFrom_Date"] = "";
                if (Convert.ToString(Session["To_Date"]) == string.Empty)
                    Session["To_Date"] = "";
                if (Convert.ToString(Session["PermissionSanctionStatus"]) == string.Empty)
                    Session["PermissionSanctionStatus"] = "All";
                if (Convert.ToString(Session["strSwipeCardNo"]) == string.Empty)
                    Session["strSwipeCardNo"] = "";
                if (Convert.ToString(Session["strEmployeeName"]) == string.Empty)
                    Session["strEmployeeName"] = "";
                if (Convert.ToString(Session["strEmployeeCodeId"]) == string.Empty)
                    Session["strEmployeeCodeId"] = "";
            }
            Permission_Id = Convert.ToInt32(Request.QueryString["Permission_Id"]);
            dtSanctionView = objPermissionEventData.GetPermissionByPermissionId(Permission_Id);
            if (Convert.ToString(Session["UserGroupName"]) != "SuperAdmin" || Convert.ToString(Session["HasSpecialRights"]) != "True")
            {
                if (dtSanctionView.Rows.Count > 0)
                {
                    if (dtSanctionView.Rows[0]["EmailId"] != DBNull.Value)
                    {
                        EmployeeEamilId = dtSanctionView.Rows[0]["EmailId"].ToString();
                    }
                    if (dtSanctionView.Rows[0]["Employee_Id"] != DBNull.Value)
                    {
                        Employee_Id = Convert.ToInt32(dtSanctionView.Rows[0]["Employee_Id"]);
                    }
                    if (dtSanctionView.Rows[0]["Employee_Code_Id"] != DBNull.Value)
                    {
                        Employee_Code_Id = dtSanctionView.Rows[0]["Employee_Code_Id"].ToString();
                    }
                    if (dtSanctionView.Rows[0]["Employee_FirstName"] != DBNull.Value)
                    {
                        EmployeeName = dtSanctionView.Rows[0]["Employee_FirstName"].ToString();
                    }
                    if (dtSanctionView.Rows[0]["name"] != DBNull.Value)
                    {
                        strlevelName = dtSanctionView.Rows[0]["name"].ToString();
                    }
                    gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
                    gstrTimeFormat = Convert.ToString(Session["MTimeFormat"]);
                    string strFromDateTime = string.Empty;
                    string strToDateTime = string.Empty;
                    strFromDateTime = objClassCommon.DateTimeConvertion((gstrDateFormat + " " + gstrTimeFormat), lblPermissionFromTime.Text, "B");
                    strToDateTime = objClassCommon.DateTimeConvertion((gstrDateFormat + " " + gstrTimeFormat), lblPermissionToTime.Text, "B");
                    string dNumberOfHoursApplied = string.Empty;
                    dNumberOfHoursApplied = CalculateNumberOfHoursApplied(strFromDateTime, strToDateTime);
                    //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
                    {
                        Status = string.Empty;
                    }

                    if (Status == "")
                    {
                        ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("Msg_ChooseOption", ci) + "');", true);
                        return;
                    }
                    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
                        Status = string.Empty;
                    if (Convert.ToString(Session["UserGroupName"]) == "SuperAdmin" || Convert.ToString(Session["HasSpecialRights"]) == "True")
                    {
                        if (Request.QueryString["Status"] == Status)
                        {
                            ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("Alert_SelectAnyOtherOption", ci) + "');", true);
                            return;
                        }
                    }
                    else
                    {
                        if (Request.QueryString["Status"] == Status)
                        {
                            ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("Alert_SelectAnyOtherOption", ci) + "');", true);
                            return;
                        }
                    }
                    Remarks = txtRemarks.Text.Trim().Replace("'", "''");
                    try
                    {
                        objPermissionEventData.UpdatePermissionApplicationConversation(Permission_Id, Status, Convert.ToInt32(Session["EmpAutoId"]), Remarks, Convert.ToInt32(Session["EmpAutoId"]));

                        objPermissionEventData.UpdatePermissionSanction(Permission_Id, Status, Remarks, Convert.ToInt32(Session["EmpAutoId"]));
                        cls_Common objclscommon = new cls_Common();
                        string strPermissionDate = objclscommon.DateConvertion(gstrDateFormat, lblPermissionDate.Text);
                        objLeaveApplicationEventData.UpdateProcessedDataFlag(Employee_Id, strPermissionDate, strPermissionDate, 0);
                        if (EmployeeEamilId != string.Empty)
                        {
                        }
                        ds_EmailIdOfSanctionAuthority = objPermissionEventData.SelectMailIdOfSanctionAuthority(Employee_Id);
                        if (ds_EmailIdOfSanctionAuthority.Tables[0].Rows.Count > 0)
                        {
                            if (ds_EmailIdOfSanctionAuthority.Tables[0].Rows[0]["EmailId"] != DBNull.Value)
                            {
                                if (ds_EmailIdOfSanctionAuthority.Tables[0].Rows[0]["EmailId"].ToString() != "")
                                {
                                    strEmailIdSanctionAuthority = ds_EmailIdOfSanctionAuthority.Tables[0].Rows[0]["EmailId"].ToString();
                                }
                            }
                        }
                        //mail to Reporting to person
                        dsEmailIdOfReportingTo = objPermissionEventData.SelectMailIdOfReportingTo(Employee_Id);
                        string strEmailIdReportingTo = string.Empty;
                        if (dsEmailIdOfReportingTo.Tables[0].Rows.Count > 0)
                        {
                            if (dsEmailIdOfReportingTo.Tables[0].Rows[0]["EmailId"] != DBNull.Value)
                            {
                                if (dsEmailIdOfReportingTo.Tables[0].Rows[0]["EmailId"].ToString() != string.Empty)
                                {
                                    strEmailIdReportingTo = dsEmailIdOfReportingTo.Tables[0].Rows[0]["EmailId"].ToString();
                                }
                            }
                        }
                        if (Convert.ToInt32(ConfigurationManager.AppSettings.Get("isRequiredEmail")) == 1)
                        {
                            SendMailToApplicant(EmployeeEamilId, strEmailIdReportingTo, strEmailIdSanctionAuthority, Status, txtRemarks.Text, Employee_Code_Id, dNumberOfHoursApplied, strlevelName);
                        }
                        #region SMSNotification
                        try
                        {
                            int smsIsRequired = 0;
                            //To check SMS Template is available in page table or not. if no then it will skip the SMS Triggering portion.
                            //244 is template page id
                            smsIsRequired = objClassCommon.CheckPageExistsInLicense(244);
                            if (smsIsRequired > 0)
                            {
                                DataSet dsGateway = new DataSet();
                                DataSet dsStatus = new DataSet();
                                bool isSmsEnabled = false;
                                string destinationKey = string.Empty;
                                string MessageKey = string.Empty;
                                string ServiceUrl = string.Empty;
                                string mobileNo = string.Empty;
                                string EmployeeName = string.Empty;
                                string strTemplateName = string.Empty;
                                bool isApplyAndReceiverSame = false;
                                if (Status == "Pending")
                                {
                                    strTemplateName = "Permission Application - Apply";
                                }
                                else if (Status == "Forwarded")
                                {
                                    strTemplateName = "Permission Application - Forward";
                                }
                                else if (Status == "Approved")
                                {
                                    strTemplateName = "Permission Application - Approved";
                                }
                                else if (Status == "Rejected")
                                {
                                    strTemplateName = "Permission Application - Rejected";
                                }
                                dsStatus = objsms.GetTemplateStauts(strTemplateName);
                                if (dsStatus.Tables.Count > 0)
                                {
                                    if (dsStatus.Tables[0].Rows.Count > 0 && Convert.ToBoolean(dsStatus.Tables[0].Rows[0]["Status"]) != false)
                                    {
                                        dsGateway = objsms.SelectGatewayDetails();
                                        if (dsGateway.Tables.Count > 0)
                                        {
                                            if (dsGateway.Tables[0].Rows.Count > 0)
                                            {
                                                if (dsGateway.Tables[0].Rows[0]["ServiceUrl"] != null)
                                                {
                                                    ServiceUrl = Convert.ToString(dsGateway.Tables[0].Rows[0]["ServiceUrl"]);
                                                }
                                                if (dsGateway.Tables[0].Rows[0]["DestinationKey"] != null)
                                                {
                                                    destinationKey = Convert.ToString(dsGateway.Tables[0].Rows[0]["DestinationKey"]);
                                                }
                                                if (dsGateway.Tables[0].Rows[0]["MessageKey"] != null)
                                                {
                                                    MessageKey = Convert.ToString(dsGateway.Tables[0].Rows[0]["MessageKey"]);
                                                }
                                                if (dsStatus.Tables[0].Rows[0]["ToEmployee"] != null)
                                                {
                                                    isSmsEnabled = Convert.ToBoolean(dsStatus.Tables[0].Rows[0]["ToEmployee"]);
                                                }
                                                if (isSmsEnabled)
                                                {
                                                    if (dtSanctionView.Rows.Count > 0)
                                                    {
                                                        if (dtSanctionView.Rows[0]["Mobile_Number"] != null)
                                                        {
                                                            mobileNo = Convert.ToString(dtSanctionView.Rows[0]["Mobile_Number"]);
                                                        }
                                                    }
                                                }
                                                if (dtSanctionView.Rows.Count > 0)
                                                {
                                                    if (dtSanctionView.Rows[0]["Employee_FirstName"] != null)
                                                    {
                                                        EmployeeName = Convert.ToString(dtSanctionView.Rows[0]["Employee_FirstName"]);
                                                    }
                                                }
                                                DataSet dsReceivers = new DataSet();
                                                dsReceivers = objsms.GetReceiversDetails(strTemplateName, Employee_Code_Id, EmployeeName, Convert.ToString(lblPermissionFromTime.Text) + " To " + Convert.ToString(lblPermissionToTime.Text), "", Convert.ToString(dNumberOfHoursApplied));
                                                if (dsReceivers.Tables.Count > 0)
                                                {
                                                    if (dsReceivers.Tables[1].Rows.Count > 0)
                                                    {
                                                        foreach (DataRow dr in dsReceivers.Tables[1].Rows)
                                                        {
                                                            if (Convert.ToString(dr["Mobile_Number"]) != "")
                                                            {
                                                                blnCheckSMS = objsms.SendSMSNotifications
                                                                (
                                                                    ServiceUrl,
                                                                    destinationKey,
                                                                    MessageKey,
                                                                    Convert.ToString(dr["Receivers"]),
                                                                    Convert.ToString(dsReceivers.Tables[0].Rows[0]["Message"]),
                                                                    Convert.ToString(dr["Mobile_Number"]),
                                                                    Employee_Code_Id,
                                                                    strTemplateName,
                                                                    Convert.ToString(dr["SwipeCardNo"])
                                                                );
                                                                if (isSmsEnabled)
                                                                {
                                                                    if (Convert.ToString(dr["SwipeCardNo"]) == Employee_Code_Id)
                                                                    {
                                                                        isApplyAndReceiverSame = true;
                                                                    }
                                                                }
                                                            }
                                                            else
                                                            {
                                                                objsms.InsertLogDetails(strTemplateName, Convert.ToString(dr["SwipeCardNo"]), Employee_Code_Id, false, Convert.ToString(dsReceivers.Tables[0].Rows[0]["Message"]), "Mobile Number is not configured in employee master");
                                                            }
                                                        }
                                                    }
                                                    else
                                                    {
                                                        objsms.InsertLogDetails(strTemplateName, "", Employee_Code_Id, false, Convert.ToString(dsReceivers.Tables[0].Rows[0]["Message"]), "Receivers are not having the configured usergroup");
                                                    }
                                                    if (isSmsEnabled)
                                                    {
                                                        if (mobileNo != string.Empty && isApplyAndReceiverSame != true)
                                                        {
                                                            blnCheckSMS = objsms.SendSMSNotifications
                                                                            (
                                                                                ServiceUrl,
                                                                                destinationKey,
                                                                                MessageKey,
                                                                                EmployeeName,
                                                                                Convert.ToString(dsReceivers.Tables[0].Rows[0]["Message"]),
                                                                                Convert.ToString(mobileNo),
                                                                                Employee_Code_Id,
                                                                                 strTemplateName,
                                                                            Convert.ToString(Employee_Code_Id)

                                                                            );

                                                        }
                                                        else if (mobileNo == string.Empty && isApplyAndReceiverSame != true)
                                                        {
                                                            objsms.InsertLogDetails(strTemplateName, Convert.ToString(Employee_Code_Id), Employee_Code_Id, false, Convert.ToString(dsReceivers.Tables[0].Rows[0]["Message"]), "Mobile Number is not configured in employee master");
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            throw ex;
                        }
                        #endregion
                        if (checkEmail == true)
                        {
                            string strScript = string.Empty;
                            strScript = strScript + "<script language='javascript'>";
                            strScript = strScript + "alert('" + rm.GetString("Alert_PermissionApplicationsavedSanction", ci) + "');";
                            strScript = strScript + "location.replace('TA_UI_Transaction_Sanctions.aspx?Type=Permission');";
                            strScript = strScript + "</script>";
                            ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", strScript, false);
                        }
                        else
                        {
                            string strScript = string.Empty;
                            strScript = strScript + "<script language='javascript'>";
                            strScript = strScript + "alert('" + rm.GetString("Alert_PermissionApplicationsavedEmailnotsentSanction", ci) + "');";
                            strScript = strScript + "location.replace('TA_UI_Transaction_Sanctions.aspx?Type=Permission');";
                            strScript = strScript + "</script>";
                            ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", strScript, false);
                        }
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }
                
            }
            #endregion
        }
        else
        {
            if(txtRemarks.Text !="")
            {
                int Triggerid = Convert.ToInt32(Session["EmailtriggetID"].ToString());
                //rbApproved.Checked = true;
                //rbPending.Enabled = false;
                //rbRejected.Enabled = false;
                //rbForwarded.Enabled = false;
                String StatusApproval = "";
                if (rbApproved.Checked == true)
                {
                    StatusApproval = "Approved";
                }
                else if (rbPending.Checked == true)
                {
                    StatusApproval = "Pending";
                }
                else if (rbRejected.Checked == true)
                {
                    StatusApproval = "Rejected";
                }
                if (rbForwarded.Checked == true)
                {
                    StatusApproval = "Forwarded";
                }


                MailSend();
                DataSet daUpdate = new DataSet();
                EmailEmpUpdate.ReasonEntry_ApprovalUpdateEmailTrigger(Triggerid, StatusApproval, txtRemarks.Text);
                Session["LateEmailSaves"] = "Reason Save successfully";
                string strScript;
                strScript = "<script language='javascript'>";
                strScript = strScript + "alert('" + "Reason Save successfully" + "');";
                strScript = strScript + "</script>";
                Page.RegisterStartupScript("Alert", strScript);

                Response.Redirect("../DashBoard.aspx");
            }
            else
            {
                string strScript;
                strScript = "<script language='javascript'>";
                strScript = strScript + "alert('" + "Enter the Reason" + "');";
                strScript = strScript + "</script>";
                Page.RegisterStartupScript("Alert", strScript);
            }
        }
        
    }

    private void MailSend()
    {
        DataTable dtTableScript = new DataTable();
        string FormName = "";
        string scriptText = "";
        String Status = "";
        String EmployeeName = "";
        DataSet EmailGet = new DataSet();
        String EmpID = Session["hdnEmpID"].ToString();
        String ReportName = Session["HdnReportName"].ToString();
        String FromDate = Session["HdnFrom"].ToString();
        String TO = Session["HdnTo"].ToString();
        String ReportNo = Session["HdnReport"].ToString();
        String Authority = Session["HdnAuthority"].ToString();
        MailMessage mailMessage = new MailMessage();
        EmailGet = getMail.SelectTriggerEmail(EmpID);
        string EmployeeEmail = EmailGet.Tables[0].Rows[0]["EmployeeEmail"].ToString();
        string ReportPerEmail = EmailGet.Tables[0].Rows[1]["EmployeeEmail"].ToString();
        string AthorityEmail = EmailGet.Tables[0].Rows[2]["EmployeeEmail"].ToString();
        string Empdepartment = EmailGet.Tables[0].Rows[3]["EmployeeEmail"].ToString();
        string EmpReportNo = EmailGet.Tables[0].Rows[1]["EmployeeCodes"].ToString();
        string EmpAuthorityNo = EmailGet.Tables[0].Rows[2]["EmployeeCodes"].ToString();

        DataSet daAbsent = new DataSet();
        daAbsent = rptEmp.SelectAbsentForEmailNotification(EmpID, FromDate, "", "LateEntryApproval");
        string Reason = daAbsent.Tables[0].Rows[0]["Reason"].ToString();
        string EmailtriggetID = daAbsent.Tables[0].Rows[0]["EmailtriggetID"].ToString();




       
        dtTableScript = objLeaveApplicationEventData.GetEmailScripts("Approval Mail Trigger");
        scriptText = Convert.ToString(dtTableScript.Rows[0]["ScriptText"]);


        String StatusApproval = "";
        if (rbApproved.Checked == true)
        {
            StatusApproval = "Approved";
        }
        else if (rbPending.Checked == true)
        {
            StatusApproval = "Pending";
        }
        else if (rbRejected.Checked == true)
        {
            StatusApproval = "Rejected";
        }
        if (rbForwarded.Checked == true)
        {
            StatusApproval = "Forwarded";
        }


        DataTable dtTableScripts = new DataTable();
        DateTime ShiftDateCofirm = Convert.ToDateTime(FromDate);
        DateTime ShiftD = Convert.ToDateTime(ShiftDateCofirm.ToString("dd/MMM/yyyy"));
       

        if(ReportPerEmail == AthorityEmail)
        {
            if (rbForwarded.Checked == true)
            {
                //Status = "Forwarded";
                //mailMessage.To.Add(new MailAddress(EmployeeEmail)); 
                 //mailMessage.CC.Add(new MailAddress(EmployeeEmail));
                 EmployeeName = lbl_EmployeeName.Text;
                FormName = "Timecheck Notification-Late Entry Reason -Forwarded";
                mailMessage.Subject = FormName + " | " + ShiftD.ToString("dd/MMM/yyyy") + " | " + EmpID + " - " + EmployeeName;

            }
            else if (rbApproved.Checked == true)
            {
                //mailMessage.To.Add(new MailAddress(AthorityEmail));
                //mailMessage.CC.Add(new MailAddress(EmployeeEmail));
                EmployeeName = lbl_EmployeeName.Text;
                FormName = "Timecheck Notification-Late Entry Reason -Approved";
                mailMessage.Subject = FormName + " | " + ShiftD.ToString("dd/MMM/yyyy") + " | " + EmpID + " - " + EmployeeName;

            }
            else if (rbPending.Checked == true)
            {
                //mailMessage.To.Add(new MailAddress(AthorityEmail));
                //mailMessage.CC.Add(new MailAddress(EmployeeEmail));
                EmployeeName = lbl_EmployeeName.Text;
                FormName = "Timecheck Notification-Late Entry Reason -Pending";
                mailMessage.Subject = FormName + " | " + ShiftD.ToString("dd/MMM/yyyy") + " | " + EmpID + " - " + EmployeeName;
            }
            else if (rbRejected.Checked == true)
            {
                //mailMessage.To.Add(new MailAddress(AthorityEmail));
                //mailMessage.CC.Add(new MailAddress(EmployeeEmail));
                EmployeeName = lbl_EmployeeName.Text;
                FormName = "Timecheck Notification-Late Entry Reason -Rejected";
                mailMessage.Subject = FormName + " | " + ShiftD.ToString("dd/MMM/yyyy") + " | " + EmpID + " - " + EmployeeName;
            }
        }
        else
        {
            //mailMessage.To.Add(new MailAddress(AthorityEmail));
            EmployeeName = lbl_EmployeeName.Text;
            FormName = "Timecheck Notification-Late Entry Reason -Forwarded";
            mailMessage.Subject = FormName + " | " + ShiftD.ToString("dd/MMM/yyyy") + " | " + EmpID + " - " + EmployeeName;
        }
        



        if (EmpID != "" & ReportName == "LateEntry" & FromDate != "" )
        {
            String LateIN = "";
            if (ReportPerEmail == AthorityEmail)
            {
                LateIN = "Notification for the Late IN occurence Form";
                mailMessage.From = new MailAddress(AthorityEmail);
                mailMessage.To.Add(new MailAddress(EmployeeEmail));
                mailMessage.Body = mailMessage.Body.Replace("<<ltr_rtl>>", rm.GetString("Direction", objCultureInfo));
                mailMessage.Body = scriptText.Replace("<<lblEmailNotificationapplicationform>>", "Notification for the Late IN occurence Form");

                mailMessage.Body = mailMessage.Body.Replace("<<lblemployeeid>>", "Employee ID");
                mailMessage.Body = mailMessage.Body.Replace("<<employeeid>>", EmpID);

                mailMessage.Body = mailMessage.Body.Replace("<<employeename>>", EmployeeName);
                mailMessage.Body = mailMessage.Body.Replace("<<lblemployeename>>", "Employee Name");

                mailMessage.Body = mailMessage.Body.Replace("<<lblDepartmentname>>", "Department");
                mailMessage.Body = mailMessage.Body.Replace("<<departmentname>>", Empdepartment);

                mailMessage.Body = mailMessage.Body.Replace("<<lblShiftdate>>", "Shift Date");
                mailMessage.Body = mailMessage.Body.Replace("<<Shiftdate>>", ShiftD.ToString("dd/MMM/yyyy"));

                mailMessage.Body = mailMessage.Body.Replace("<<lblPunchtime>>", "Shift In Time");
                mailMessage.Body = mailMessage.Body.Replace("<<punchtime>>", lblPermissionFromTime.Text);

                mailMessage.Body = mailMessage.Body.Replace("<<lblhours>>", "Late In Hours");
                mailMessage.Body = mailMessage.Body.Replace("<<hours>>", lblPermissionToTime.Text);

                mailMessage.Body = mailMessage.Body.Replace("<<lblReason>>", "Reason");
                mailMessage.Body = mailMessage.Body.Replace("<<Reason>>", Reason);

                mailMessage.Body = mailMessage.Body.Replace("<<lblStatus>>", "Status");
                mailMessage.Body = mailMessage.Body.Replace("<<Status>>", StatusApproval);

                //mailMessage.Body = mailMessage.Body.Replace("<<LinkData>>", Convert.ToString(Session["HostServerURL"]) +
                //    "?EmpID=" + EmpID + "&ReportName=" + ReportName + "&From=" + FromDate + "&Authority=" + EmpAuthorityNo);
                objClassCommon.SendMail(mailMessage);

            }
            else
            {
                scriptText = "";
                
                dtTableScripts = objLeaveApplicationEventData.GetEmailScripts("Late IN Reason Approval");
                scriptText = Convert.ToString(dtTableScripts.Rows[0]["ScriptText"]);
                LateIN = "Notification for the Late IN occurence Form";
                mailMessage.From = new MailAddress(ReportPerEmail);
                mailMessage.To.Add(new MailAddress(AthorityEmail));
                mailMessage.CC.Add(new MailAddress(EmployeeEmail));
                mailMessage.Body = mailMessage.Body.Replace("<<ltr_rtl>>", rm.GetString("Direction", objCultureInfo));
                mailMessage.Body = scriptText.Replace("<<lblEmailNotificationapplicationform>>", "Notification for the Late IN occurence Form");

                mailMessage.Body = mailMessage.Body.Replace("<<lblemployeeid>>", "Employee ID");
                mailMessage.Body = mailMessage.Body.Replace("<<employeeid>>", EmpID);

                mailMessage.Body = mailMessage.Body.Replace("<<employeename>>", EmployeeName);
                mailMessage.Body = mailMessage.Body.Replace("<<lblemployeename>>", "Employee Name");

                mailMessage.Body = mailMessage.Body.Replace("<<lblDepartmentname>>", "Department");
                mailMessage.Body = mailMessage.Body.Replace("<<departmentname>>", Empdepartment);

                mailMessage.Body = mailMessage.Body.Replace("<<lblShiftdate>>", "Shift Date");
                mailMessage.Body = mailMessage.Body.Replace("<<Shiftdate>>", ShiftD.ToString("dd/MMM/yyyy"));

                mailMessage.Body = mailMessage.Body.Replace("<<lblPunchtime>>", "Shift In Time");
                mailMessage.Body = mailMessage.Body.Replace("<<punchtime>>", lblPermissionFromTime.Text);

                mailMessage.Body = mailMessage.Body.Replace("<<lblhours>>", "Late In Hours");
                mailMessage.Body = mailMessage.Body.Replace("<<hours>>", lblPermissionToTime.Text);

                mailMessage.Body = mailMessage.Body.Replace("<<lblReason>>", "Reason");
                mailMessage.Body = mailMessage.Body.Replace("<<Reason>>", Reason);

                //mailMessage.Body = mailMessage.Body.Replace("<<lblStatus>>", "Status");
                //mailMessage.Body = mailMessage.Body.Replace("<<Status>>", StatusApproval);

                mailMessage.Body = mailMessage.Body.Replace("<<LinkData>>", Convert.ToString(Session["HostServerURL"]) +
                    "?EmpID=" + EmpID + "&ReportName=" + ReportName + "&From=" + FromDate + "&Authority=" + EmpAuthorityNo);
                objClassCommon.SendMail(mailMessage);

            }


        }
        else if (EmpID != "" & ReportName == "Absent" & FromDate != "")
        {
            //Session["lblAbsentANa"] = lblAbsentANa;
            //Session["lblAbsentFNa"] = lblAbsentFNa;
            String LateIN = "";
            if (ReportPerEmail == AthorityEmail)
            {
                LateIN = "Notification for the Absent occurence Form";
                mailMessage.From = new MailAddress(AthorityEmail);
                mailMessage.To.Add(new MailAddress(EmployeeEmail));
                mailMessage.Body = mailMessage.Body.Replace("<<ltr_rtl>>", rm.GetString("Direction", objCultureInfo));
                mailMessage.Body = scriptText.Replace("<<lblEmailNotificationapplicationform>>", LateIN);

                mailMessage.Body = mailMessage.Body.Replace("<<lblemployeeid>>", "Employee ID");
                mailMessage.Body = mailMessage.Body.Replace("<<employeeid>>", EmpID);

                mailMessage.Body = mailMessage.Body.Replace("<<employeename>>", EmployeeName);
                mailMessage.Body = mailMessage.Body.Replace("<<lblemployeename>>", "Employee Name");

                mailMessage.Body = mailMessage.Body.Replace("<<lblDepartmentname>>", "Department");
                mailMessage.Body = mailMessage.Body.Replace("<<departmentname>>", Empdepartment);

                mailMessage.Body = mailMessage.Body.Replace("<<lblShiftdate>>", "Shift Date");
                mailMessage.Body = mailMessage.Body.Replace("<<Shiftdate>>", ShiftD.ToString("dd/MMM/yyyy"));

                mailMessage.Body = mailMessage.Body.Replace("<<lblPunchtime>>", "First Session");
                mailMessage.Body = mailMessage.Body.Replace("<<punchtime>>", lblPermissionFromTime.Text);

                mailMessage.Body = mailMessage.Body.Replace("<<lblhours>>", "Secound Session");
                mailMessage.Body = mailMessage.Body.Replace("<<hours>>", lblPermissionToTime.Text);

                mailMessage.Body = mailMessage.Body.Replace("<<lblReason>>", "Reason");
                mailMessage.Body = mailMessage.Body.Replace("<<Reason>>", Reason);

                mailMessage.Body = mailMessage.Body.Replace("<<lblStatus>>", "Status");
                mailMessage.Body = mailMessage.Body.Replace("<<Status>>", StatusApproval);

                //mailMessage.Body = mailMessage.Body.Replace("<<LinkData>>", Convert.ToString(Session["HostServerURL"]) +
                //    "?EmpID=" + EmpID + "&ReportName=" + ReportName + "&From=" + HdnFrom + "&Authority=" + EmpAuthorityNo);
                objClassCommon.SendMail(mailMessage);

            }
            else
            {
                scriptText = "";
                dtTableScripts = objLeaveApplicationEventData.GetEmailScripts("Late IN Reason Approval");
                scriptText = Convert.ToString(dtTableScripts.Rows[0]["ScriptText"]);
                LateIN = "Notification for the Absent occurence Form";
                mailMessage.From = new MailAddress(ReportPerEmail);
                mailMessage.To.Add(new MailAddress(AthorityEmail));
                mailMessage.CC.Add(new MailAddress(EmployeeEmail));
                mailMessage.Body = mailMessage.Body.Replace("<<ltr_rtl>>", rm.GetString("Direction", objCultureInfo));
                mailMessage.Body = scriptText.Replace("<<lblEmailNotificationapplicationform>>", LateIN);

                mailMessage.Body = mailMessage.Body.Replace("<<lblemployeeid>>", "Employee ID");
                mailMessage.Body = mailMessage.Body.Replace("<<employeeid>>", EmpID);

                mailMessage.Body = mailMessage.Body.Replace("<<employeename>>", EmployeeName);
                mailMessage.Body = mailMessage.Body.Replace("<<lblemployeename>>", "Employee Name");

                mailMessage.Body = mailMessage.Body.Replace("<<lblDepartmentname>>", "Department");
                mailMessage.Body = mailMessage.Body.Replace("<<departmentname>>", Empdepartment);

                mailMessage.Body = mailMessage.Body.Replace("<<lblShiftdate>>", "Shift Date");
                mailMessage.Body = mailMessage.Body.Replace("<<Shiftdate>>", ShiftD.ToString("dd/MMM/yyyy"));

                mailMessage.Body = mailMessage.Body.Replace("<<lblPunchtime>>", "First Session");
                mailMessage.Body = mailMessage.Body.Replace("<<punchtime>>", lblPermissionFromTime.Text);

                mailMessage.Body = mailMessage.Body.Replace("<<lblhours>>", "Secound Session");
                mailMessage.Body = mailMessage.Body.Replace("<<hours>>", lblPermissionToTime.Text);

                mailMessage.Body = mailMessage.Body.Replace("<<lblReason>>", "Reason");
                mailMessage.Body = mailMessage.Body.Replace("<<Reason>>", Reason);

                //mailMessage.Body = mailMessage.Body.Replace("<<lblStatus>>", "Status");
                //mailMessage.Body = mailMessage.Body.Replace("<<Status>>", StatusApproval);

                mailMessage.Body = mailMessage.Body.Replace("<<LinkData>>", Convert.ToString(Session["HostServerURL"]) +
                          "?EmpID=" + EmpID + "&ReportName=" + ReportName + "&From=" + FromDate + "&Authority=" + EmpAuthorityNo);
                objClassCommon.SendMail(mailMessage);

            }


            // Session["lblEarlyExit"] = lblEarlyExit;
            //Session["lblEarlyExitHrs"] = lblEarlyExitHrs;
        }
        else
         if (EmpID != "" & ReportName == "EarlyExit" & FromDate != "")
        {
            String LateIN = "";
            if (ReportPerEmail == AthorityEmail)
            {
                LateIN = "Notification for the Early Exit occurence Form";
                mailMessage.From = new MailAddress(AthorityEmail);
                mailMessage.To.Add(new MailAddress(EmployeeEmail));
                mailMessage.Body = mailMessage.Body.Replace("<<ltr_rtl>>", rm.GetString("Direction", objCultureInfo));
                mailMessage.Body = scriptText.Replace("<<lblEmailNotificationapplicationform>>", LateIN);

                mailMessage.Body = mailMessage.Body.Replace("<<lblemployeeid>>", "Employee ID");
                mailMessage.Body = mailMessage.Body.Replace("<<employeeid>>", EmpID);

                mailMessage.Body = mailMessage.Body.Replace("<<employeename>>", EmployeeName);
                mailMessage.Body = mailMessage.Body.Replace("<<lblemployeename>>", "Employee Name");

                mailMessage.Body = mailMessage.Body.Replace("<<lblDepartmentname>>", "Department");
                mailMessage.Body = mailMessage.Body.Replace("<<departmentname>>", Empdepartment);

                mailMessage.Body = mailMessage.Body.Replace("<<lblShiftdate>>", "Shift Date");
                mailMessage.Body = mailMessage.Body.Replace("<<Shiftdate>>", ShiftD.ToString("dd/MMM/yyyy"));

                mailMessage.Body = mailMessage.Body.Replace("<<lblPunchtime>>", "Early Out");
                mailMessage.Body = mailMessage.Body.Replace("<<punchtime>>", lblPermissionFromTime.Text);

                mailMessage.Body = mailMessage.Body.Replace("<<lblhours>>", "Early Hrs");
                mailMessage.Body = mailMessage.Body.Replace("<<hours>>", lblPermissionToTime.Text);

                mailMessage.Body = mailMessage.Body.Replace("<<lblReason>>", "Reason");
                mailMessage.Body = mailMessage.Body.Replace("<<Reason>>", Reason);

                mailMessage.Body = mailMessage.Body.Replace("<<lblStatus>>", "Status");
                mailMessage.Body = mailMessage.Body.Replace("<<Status>>", StatusApproval);

                //mailMessage.Body = mailMessage.Body.Replace("<<LinkData>>", Convert.ToString(Session["HostServerURL"]) +
                //    "?EmpID=" + EmpID + "&ReportName=" + ReportName + "&From=" + HdnFrom + "&Authority=" + EmpAuthorityNo);
                objClassCommon.SendMail(mailMessage);
            }
            else
            {
                scriptText = "";
                dtTableScripts = objLeaveApplicationEventData.GetEmailScripts("Late IN Reason Approval");
                scriptText = Convert.ToString(dtTableScripts.Rows[0]["ScriptText"]);
                LateIN = "Notification for the Early Exit occurence Form";
                mailMessage.From = new MailAddress(ReportPerEmail);
                mailMessage.To.Add(new MailAddress(AthorityEmail));
                mailMessage.CC.Add(new MailAddress(EmployeeEmail));
                mailMessage.Body = mailMessage.Body.Replace("<<ltr_rtl>>", rm.GetString("Direction", objCultureInfo));
                mailMessage.Body = scriptText.Replace("<<lblEmailNotificationapplicationform>>", LateIN);

                mailMessage.Body = mailMessage.Body.Replace("<<lblemployeeid>>", "Employee ID");
                mailMessage.Body = mailMessage.Body.Replace("<<employeeid>>", EmpID);

                mailMessage.Body = mailMessage.Body.Replace("<<employeename>>", EmployeeName);
                mailMessage.Body = mailMessage.Body.Replace("<<lblemployeename>>", "Employee Name");

                mailMessage.Body = mailMessage.Body.Replace("<<lblDepartmentname>>", "Department");
                mailMessage.Body = mailMessage.Body.Replace("<<departmentname>>", Empdepartment);

                mailMessage.Body = mailMessage.Body.Replace("<<lblShiftdate>>", "Shift Date");
                mailMessage.Body = mailMessage.Body.Replace("<<Shiftdate>>", ShiftD.ToString("dd/MMM/yyyy"));

                mailMessage.Body = mailMessage.Body.Replace("<<lblPunchtime>>", "Early Out");
                mailMessage.Body = mailMessage.Body.Replace("<<punchtime>>", lblPermissionFromTime.Text);

                mailMessage.Body = mailMessage.Body.Replace("<<lblhours>>", "Early Hrs");
                mailMessage.Body = mailMessage.Body.Replace("<<hours>>", lblPermissionToTime.Text);

                mailMessage.Body = mailMessage.Body.Replace("<<lblReason>>", "Reason");
                mailMessage.Body = mailMessage.Body.Replace("<<Reason>>", Reason);

                //mailMessage.Body = mailMessage.Body.Replace("<<lblStatus>>", "Status");
                //mailMessage.Body = mailMessage.Body.Replace("<<Status>>", StatusApproval);

                mailMessage.Body = mailMessage.Body.Replace("<<LinkData>>", Convert.ToString(Session["HostServerURL"]) +
                   "?EmpID=" + EmpID + "&ReportName=" + ReportName + "&From=" + FromDate + "&Authority=" + EmpAuthorityNo);
                objClassCommon.SendMail(mailMessage);

            }


        }

        
    }

    protected void rbRejected_OnCheckedChanged(object sender, EventArgs e)
    {
        rbApproved.Checked = false;
        rbForwarded.Checked = false;
        rbPending.Checked = false;
        rbRejected.Checked = true;
    }
    protected void rbPending_OnCheckedChanged(object sender, EventArgs e)
    {
        rbApproved.Checked = false;
        rbForwarded.Checked = false;
        rbPending.Checked = true;
        rbRejected.Checked = false;
    }
    protected void rbForwarded_OnCheckedChanged(object sender, EventArgs e)
    {
        rbApproved.Checked = false;
        rbForwarded.Checked = true;
        rbPending.Checked = false;
        rbRejected.Checked = false;
    }
    protected void rbApproved_OnCheckedChanged(object sender, EventArgs e)
    {
        rbApproved.Checked = true;
        rbForwarded.Checked = false;
        rbPending.Checked = false;
        rbRejected.Checked = false;
    }
    protected void btn_Cancel_Click(object sender, EventArgs e)
    {
        string str = Request.QueryString["LevelId"];
        if (Convert.ToString(Request.QueryString["LevelId"]) == string.Empty || Convert.ToString(Request.QueryString["LevelId"]) == null)
        {
        }
        else
        {
            if (Convert.ToString(Session["LevelId"]) == string.Empty)
                Session["LevelId"] = Request.QueryString["LevelId"].ToString();
            if (Convert.ToString(Session["PermissionSanctionStatus"]) == string.Empty)
                Session["PermissionSanctionStatus"] = "All";
            if (Convert.ToString(Session["strSwipeCardNo"]) == string.Empty)
                Session["strSwipeCardNo"] = "";
            if (Convert.ToString(Session["strEmployeeName"]) == string.Empty)
                Session["strEmployeeName"] = "";
            if (Convert.ToString(Session["strEmployeeCodeId"]) == string.Empty)
                Session["strEmployeeCodeId"] = "";
            if (Convert.ToString(Session["PermissionFrom_Date"]) == string.Empty)
                Session["PermissionFrom_Date"] = "";
            if (Convert.ToString(Session["PermissionTo_Date"]) == string.Empty)
                Session["PermissionTo_Date"] = "";
        }
        Response.Redirect("../Transactions/TA_UI_Transaction_Sanctions.aspx?Type=Permission");
    }
    #endregion
}
