using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Resources;
using System.Globalization;
using System.Threading;
using System.Net.Mail;
using System.Net;
public partial class Transactions_TA_UI_Transactions_LeavePermissionView : System.Web.UI.Page
{
    int gintPermissionId;
    DataSet ds_PermissionApplication = new DataSet();
    PermissionEventData_Angler objPermissionEventData = new PermissionEventData_Angler();
    ResourceManager rm;
    CultureInfo ci;
    Cls_CheckUser objCheckUser = new Cls_CheckUser();
    DataSet ds_Checkuser = new DataSet();
    LeaveApplicationEventData_Angler objLeaveApplicationEventData = new LeaveApplicationEventData_Angler();
    CCGroupEventData_Angler objCCGroup = new CCGroupEventData_Angler();
    bool checkEmail = true;
    cls_Common objClassCommon = new cls_Common();
    string gstrDateFormat;
    string gstrTimeFormat;
    protected void Page_Load(object sender, EventArgs e)
    {
        gintPermissionId = Convert.ToInt32(Request.QueryString["Permission_Id"]);
        gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
        gstrTimeFormat = Session["MTimeFormat"].ToString();
        //// session checking
        //base.Page_Load(sender, e);
        if (Request.UrlReferrer != null)
        {
            string GetURL = Request.UrlReferrer.ToString();
        }
        else
        {
            Response.Redirect("TA_UI_Transactions_LeavePermission.aspx");
        }
        //get the culture info to set the language      
        string source_Language;
        source_Language = Session["Session_ActiveLanguage"].ToString();
        rm = new ResourceManager(source_Language, System.Reflection.Assembly.Load("App_GlobalResources"));
        ci = Thread.CurrentThread.CurrentCulture;
        LoadStrings(ci);
        if (!IsPostBack)
        {
            ViewState["vsPermissionId"] = Request.QueryString["Permission_Id"].ToString();
            //Set UserRights
            UserRights();
            ViewDetails();
            ControlCreation();
        }
    }
    protected void btnModify_Click(object sender, EventArgs e)
    {
        //Convert Date Format to MM/dd/yyyy Format
        string strTimeFormat = Session["MTimeFormat"].ToString();
        //Not allow to modify permission before current date & time for narmal users except resend status.
        string strPermission_GraceHours = System.Configuration.ConfigurationManager.AppSettings["PermissionApplyHours_Grace"].ToString();
        TimeSpan tsPermission_GraceHours = new TimeSpan();
        tsPermission_GraceHours = TimeSpan.Parse(strPermission_GraceHours);
        if (Session["UserGroupName"].ToString() != "SuperAdmin")
        {
            if (ViewState["StatusOfApplication"].ToString() != "Resend")
            {
                //Changed datetime converstions in general as like product
                string strStartTime = objClassCommon.DateTimeConvertion((gstrDateFormat + " " + gstrTimeFormat), lblPermissionFromTime.Text, "B");
                if ((Convert.ToDateTime(strStartTime)) < Convert.ToDateTime(DateTime.Now.ToString(strTimeFormat)).Subtract(tsPermission_GraceHours))
                {
                    Message("Cannot Modify the Permission for past Date & Time");
                    return;
                }
            }
        }
        DataSet dsEmailIdOfReportingTo = objPermissionEventData.SelectMailIdOfReportingTo(Convert.ToInt32(ViewState["EmployeeID"]));
        DataSet ds_EmailIdOfSanctionAuthority = objPermissionEventData.SelectMailIdOfSanctionAuthority(Convert.ToInt32(ViewState["EmployeeID"]));
        bool blnAllowModify = false;
        if (dsEmailIdOfReportingTo.Tables[0].Rows.Count > 0 && ds_EmailIdOfSanctionAuthority.Tables[0].Rows.Count > 0)
        {
            if (dsEmailIdOfReportingTo.Tables[0].Rows[0]["EmailId"] != DBNull.Value && ds_EmailIdOfSanctionAuthority.Tables[0].Rows[0]["EmailId"] != DBNull.Value)
            {
                if (dsEmailIdOfReportingTo.Tables[0].Rows[0]["EmailId"].ToString() != "" && ds_EmailIdOfSanctionAuthority.Tables[0].Rows[0]["EmailId"].ToString() != "")
                {
                    if (dsEmailIdOfReportingTo.Tables[0].Rows[0]["EmailId"].ToString() == ds_EmailIdOfSanctionAuthority.Tables[0].Rows[0]["EmailId"].ToString())
                    {
                        blnAllowModify = true;
                    }
                }
            }
        }
        string strLengthCheck = txtReasonForCancel.Text.Trim().Replace("'", "''");
        if (strLengthCheck.Length > 1000)
        {
            Message("Maximum character for Reason is 1000");
            return;
        }
        if (lblStatus.Text == "Pending" || lblStatus.Text == "Resend")
        {
            Response.Redirect("TA_UI_Transactions_LeavePermissionModify.aspx?Permission_Id=" + gintPermissionId.ToString());
        }
        else if (blnAllowModify == true && lblStatus.Text != "Approved")
        {
            Response.Redirect("TA_UI_Transactions_LeavePermissionModify.aspx?Permission_Id=" + gintPermissionId.ToString());
        }
        else
        {
            string strScript = string.Empty;
            strScript = strScript + "<script language='javascript'>";
            strScript = strScript + "alert('" + rm.GetString("Alert_CannotModifythePermission", ci) + "');";
            strScript = strScript + "</script>";
            Page.RegisterStartupScript("AlertLeavePermission", strScript);
        }
    }
    protected void btnBack_Click(object sender, EventArgs e)
    {
        Response.Redirect("TA_UI_Transactions_LeavePermission.aspx");
    }
    /// <summary>
    /// Diplay the permission Details
    /// </summary>
    public void ViewDetails()
    {
        string strEmployeeID;
        int intPermissionType = 0;
        ds_PermissionApplication = objPermissionEventData.SelectLeavePermissionByPermissionId(gintPermissionId);
        lblAppliedHours.Text = ds_PermissionApplication.Tables[0].Rows[0]["Permission_Hours"].ToString();
        //Commneted by Manjula.P on 19-Apr-2014 for unknown codes
        ViewState["LevelId"] = ds_PermissionApplication.Tables[0].Rows[0]["LevelId"].ToString();
        ViewState["DesignationId"] = ds_PermissionApplication.Tables[0].Rows[0]["DesignationId"].ToString();
        //**************************************************k
        strEmployeeID = ds_PermissionApplication.Tables[0].Rows[0]["Employee_Id"].ToString();
        ViewState["EmployeeID"] = Convert.ToString(strEmployeeID);
        lblEmployeeIdData.Text = ds_PermissionApplication.Tables[0].Rows[0]["Employee_Code_Id"].ToString();
        //Commneted by Manjula.P on 19-Apr-2014 for unknown codes
        ViewState["vsEmployeeEamilId"] = ds_PermissionApplication.Tables[0].Rows[0]["emailId"].ToString();
        ViewState["vsLevelName"] = ds_PermissionApplication.Tables[0].Rows[0]["name"].ToString();
        ViewState["vsStrApprovalToDept"] = ds_PermissionApplication.Tables[0].Rows[0]["ToMailIds"].ToString();
        ViewState["vsStrApprovalCCDept"] = ds_PermissionApplication.Tables[0].Rows[0]["CCMailIds"].ToString();
        //********************************************************
        //To store the Audit Employee id
        //ViewState["auEmpId"] = Convert.ToInt32(ds_PermissionApplication.Tables[0].Rows[0]["Emp_Id"]);
        if (ds_PermissionApplication.Tables[0].Rows[0]["UnPlanned"] != null)
        {
            intPermissionType = Convert.ToInt16(ds_PermissionApplication.Tables[0].Rows[0]["UnPlanned"]);
        }
        string strEmployeeName = ds_PermissionApplication.Tables[0].Rows[0]["Employee_FirstName"].ToString();
        //lbl_EmployeeName.Text = ds_PermissionApplication.Tables[0].Rows[0]["Employee_FirstName"].ToString();
        lbl_EmployeeName.Text = strEmployeeName + " " + ds_PermissionApplication.Tables[0].Rows[0]["Employee_LastName"].ToString();
        lbl_PermissionApplicationDate.Text = (DateTime.Parse(ds_PermissionApplication.Tables[0].Rows[0]["Permission_AppliedDate"].ToString())).ToString(Session["MDateFormat"].ToString() + " " + Session["MTimeFormat"].ToString());
        txtApprovalCC.Text = ds_PermissionApplication.Tables[0].Rows[0]["CCMail"].ToString();
        ViewState["StatusOfApplication"] = ds_PermissionApplication.Tables[0].Rows[0]["Permission_Status"].ToString();
        ViewState["IntimationType"] = ds_PermissionApplication.Tables[0].Rows[0]["UnPlanned"].ToString();
        lblPermissionDate.Text = (DateTime.Parse(ds_PermissionApplication.Tables[0].Rows[0]["Permission_Date"].ToString())).ToString(Session["MDateFormat"].ToString());
        if (ds_PermissionApplication.Tables[0].Rows[0]["Permission_Status"].ToString() == "Rejected")
        {
            btn_Delete.Enabled = false;
        }
        string strTodaysDate = objClassCommon.DateConvertion(gstrDateFormat, DateTime.Now.ToString(Convert.ToString(Session["MDateFormat"])));
        string strPermissionDate = objClassCommon.DateConvertion(gstrDateFormat, lblPermissionDate.Text);
        //DateTime.Now.ToString(Session["MDateFormat"].ToString());
        //Changed from convert.todatetime into datetime.parse by Manjula.P on 21-Apr-2014
        if (DateTime.Parse(strPermissionDate) < DateTime.Parse(strTodaysDate))
        //if (Convert.ToDateTime(lblPermissionDate.Text) < Convert.ToDateTime(strTodaysDate))
        {
            if (Session["UserGroupName"].ToString() == "SuperAdmin" || Session["HasSpecialRights"].ToString() == "True")
            {
                btn_Delete.Enabled = true;
            }
            else
            {
                btn_Delete.Enabled = false;
            }
        }
        string[] PerTime = ds_PermissionApplication.Tables[0].Rows[0]["Permission_FromTime"].ToString().Split(" ".ToCharArray());
        string timePart1 = PerTime[1].ToString() + " " + PerTime[2].ToString();
        lblPermissionFromTime.Text = (Convert.ToDateTime(PerTime[0])).ToString(Session["MDateFormat"].ToString()) + " " + DateTime.Parse(timePart1).ToString(Session["MTimeFormat"].ToString());
        string[] PerTime1 = ds_PermissionApplication.Tables[0].Rows[0]["Permission_ToTime"].ToString().Split(" ".ToCharArray());
        string timePart2 = PerTime1[1].ToString() + " " + PerTime1[2].ToString();
        lblPermissionToTime.Text = (Convert.ToDateTime(PerTime1[0])).ToString(Session["MDateFormat"].ToString()) + " " + DateTime.Parse(timePart2).ToString(Session["MTimeFormat"].ToString());
        lblReason.Text = ds_PermissionApplication.Tables[0].Rows[0]["Permission_Reason"].ToString();
        lblRemarks.Text = ds_PermissionApplication.Tables[0].Rows[0]["Remarks"].ToString();
        lblStatus.Text = ds_PermissionApplication.Tables[0].Rows[0]["Permission_Status"].ToString();
        // Get the Parent Company Id for the Employee by passing the Level Id
        org_levelsEventData getOrg = new org_levelsEventData();
        LeaveSettingsEventData_Angler objLeaveSettingsEventData = new LeaveSettingsEventData_Angler();
        DataSet ds_getOrg = new DataSet();
        DataSet ds_PermissionSettings = new DataSet();
        DataTable dt_PermissionSettings = new DataTable();
        getOrg.GetOrgParentLevels_FromID(Convert.ToInt32(ds_PermissionApplication.Tables[0].Rows[0]["LevelId"]));
        ds_getOrg = getOrg.GetOrgParentLevels();
        ds_PermissionSettings = objLeaveSettingsEventData.GetLeaveSettingsByComId(Convert.ToInt32(ds_getOrg.Tables[0].Rows[0]["LevelID"].ToString()));
        if (ds_PermissionSettings.Tables.Count > 0)
        {
            dt_PermissionSettings = ds_PermissionSettings.Tables[0];
        }
        if (dt_PermissionSettings.Rows.Count > 0)
        {
            if (dt_PermissionSettings.Rows[0]["Approval"] != DBNull.Value && dt_PermissionSettings.Rows[0]["Approval"].ToString() != string.Empty)
            {
                if (dt_PermissionSettings.Rows[0]["Approval"].ToString() == "False")
                {
                    // Both First and Second Level Authority Approval
                    //intApproval = 0;
                }
                else if (dt_PermissionSettings.Rows[0]["Approval"].ToString() == "True")
                {
                    // First or Second Level Authority Approval - Either or one
                    //intApproval = 1;
                }
                else
                {
                    // Nothing
                }
            }
            if (dt_PermissionSettings.Rows[0]["ApprovalCC"] != DBNull.Value && dt_PermissionSettings.Rows[0]["ApprovalCC"].ToString() != string.Empty)
            {
                if (lblStatus.Text == "Approved")
                {
                    ViewState["vsStrApprovalCC"] = dt_PermissionSettings.Rows[0]["ApprovalCC"].ToString();
                }
                else
                {
                    ViewState["vsStrApprovalCC"] = string.Empty;
                }
            }
            else
            {
                ViewState["vsStrApprovalCC"] = string.Empty;
            }
        }
        //For Unplanned Pending Leave modification -- by admin only validation
        //if (Convert.ToInt32(ViewState["auEmpId"]) != Convert.ToInt32(Session["EmpAutoID"]) && Session["UserGroupName"].ToString() != "SuperAdmin" && Session["HasSpecialRights"].ToString() != "True")
        if (intPermissionType == 1 && Session["UserGroupName"].ToString() != "SuperAdmin" && Session["HasSpecialRights"].ToString() != "True")
        {
            if (ViewState["StatusOfApplication"].ToString() != "Resend")
            {
                btnModify.Enabled = false;
            }
            btn_Delete.Enabled = false;
        }
        if (ViewState["StatusOfApplication"].ToString() == "Reply")
        {
            if (Session["UserGroupName"].ToString() == "SuperAdmin")
            {
                btn_Delete.Enabled = true;
            }
            else
            {
                btn_Delete.Enabled = false;
            }
            btnModify.Enabled = 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_Status.Text = rm.GetString("email_Status", ci);
        btnModify.Text = rm.GetString("btn_Modify", ci);
        btnBack.Text = rm.GetString("btn_Back", ci);
    }
    private void ControlCreation()
    {
        string reportingToEmployee = null;
        string sanctioningEmployee = null;
        DataTable dt_ApprovalAuthority = new DataTable();
        dt_ApprovalAuthority = objLeaveApplicationEventData.GetApprovalAuthorityIds(Convert.ToInt32(ViewState["EmployeeID"]));
        if (dt_ApprovalAuthority.Rows.Count > 0)
        {
            if (dt_ApprovalAuthority.Rows[0]["Reporting_To"] != DBNull.Value && dt_ApprovalAuthority.Rows[0]["Reporting_To"].ToString() != string.Empty)
            {
                //intFirstLevelAuthorityId = int.Parse(dt_ApprovalAuthority.Rows[0]["Reporting_To"].ToString());
                reportingToEmployee = dt_ApprovalAuthority.Rows[0]["ReportingToEmployee"].ToString();
            }
            if (dt_ApprovalAuthority.Rows[0]["Leave_Sanc_Authority"] != DBNull.Value && dt_ApprovalAuthority.Rows[0]["Leave_Sanc_Authority"].ToString() != string.Empty)
            {
                //intSecondLevelAuthorityId = int.Parse(dt_ApprovalAuthority.Rows[0]["Leave_Sanc_Authority"].ToString());
                sanctioningEmployee = dt_ApprovalAuthority.Rows[0]["SanctioningEmployee"].ToString();
            }
        }
        DataSet ds_PermissionConversation = new DataSet();
        if (!IsPostBack)
        {
            // getting leave conversation 
            ds_PermissionConversation = objPermissionEventData.GetPermissionConversation(gintPermissionId);
            ViewState["PermissionConversation"] = ds_PermissionConversation;
        }
        if (ViewState["PermissionConversation"] != null)
        {
            ds_PermissionConversation = (DataSet)ViewState["PermissionConversation"];
        }
        if (ds_PermissionConversation != null && ds_PermissionConversation.Tables[0].Rows.Count > 0)
        {
            Table leaveConversation = new Table();
            leaveConversation.BorderWidth = 1;
            leaveConversation.CellPadding = 5;
            leaveConversation.CellSpacing = 0;
            leaveConversation.Width = Unit.Pixel(465);
            leaveConversation.CssClass = "td";
            leaveConversation.Attributes.Add("border", "1");
            TableHeaderRow leaveConversationHr = new TableHeaderRow();
            TableHeaderCell leaveConversationHeading3 = new TableHeaderCell();
            leaveConversationHeading3.Text = rm.GetString("TerminalDataType_Date_And_Time", ci);
            leaveConversationHeading3.HorizontalAlign = HorizontalAlign.Left;
            leaveConversationHr.Cells.Add(leaveConversationHeading3);
            TableHeaderCell leaveConversationHeading1 = new TableHeaderCell();
            //leaveConversationHeading1.Width = Unit.Pixel(230);
            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 = Unit.Pixel(230);
            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)
                {
                    TableRow trLeaveConversation = new TableRow();
                    TableCell tcLeaveConversationRepliedOn = new TableCell();
                    Label lblLeaveConversationRepliedOn = new Label();
                    tcLeaveConversationRepliedOn.BorderWidth = 1;
                    tcLeaveConversationRepliedOn.Width = 120;
                    lblLeaveConversationRepliedOn.ID = "lblLeaveConversationRepliedOn" + rowIndex;
                    lblLeaveConversationRepliedOn.Text = Convert.ToDateTime(drLeaveConversation["TimeStamp"]).ToString(Session["MDateFormat"].ToString()) + " " + Convert.ToDateTime(drLeaveConversation["TimeStamp"]).ToString(Session["MTimeFormat"].ToString());
                    tcLeaveConversationRepliedOn.Controls.Add(lblLeaveConversationRepliedOn);
                    trLeaveConversation.Cells.Add(tcLeaveConversationRepliedOn);
                    TableCell tcLeaveConversationCommentsBy = new TableCell();
                    Label lblLeaveConversationCommentsBy = new Label();
                    tcLeaveConversationCommentsBy.Width = 95;
                    lblLeaveConversationCommentsBy.ID = "lblLeaveConversationCommentsBy" + rowIndex;
                    if (drLeaveConversation["CommentsBy"].ToString() == "0")
                    {
                        lblLeaveConversationCommentsBy.Text = lbl_EmployeeName.Text;
                    }
                    else if (drLeaveConversation["CommentsBy"].ToString() == "1")
                    {
                        lblLeaveConversationCommentsBy.Text = objLeaveApplicationEventData.GetEmployeeName(Convert.ToInt32(drLeaveConversation["Emp_Id"].ToString()));
                    }
                    else if (drLeaveConversation["CommentsBy"].ToString() == "2")
                    {
                        lblLeaveConversationCommentsBy.Text = objLeaveApplicationEventData.GetEmployeeName(Convert.ToInt32(drLeaveConversation["Emp_Id"].ToString()));
                    }
                    else if (drLeaveConversation["CommentsBy"].ToString() == "3")
                    {
                        lblLeaveConversationCommentsBy.Text = 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();
                    tcLeaveConversationComments.Controls.Add(lblLeaveConversationComments);
                    trLeaveConversation.Cells.Add(tcLeaveConversationComments);
                    leaveConversation.Rows.Add(trLeaveConversation);
                    rowIndex += 1;
                }
            }
            divLeaveConversation.Controls.Add(leaveConversation);
        }
        else
        {
        }
    }
    private void UserRights()
    {
        ds_Checkuser = objCheckUser.checkRights(23, Convert.ToInt32(Session["userGroup_Id"]), "");
        //if (ds_Checkuser.Tables[0].Rows.Count == 0)
        //  {
        //       Response.Redirect("TransactionLandingPage.aspx");
        //  }
        //else
        //  {
        //        //   
        //  }      
        if (ds_Checkuser.Tables[0].Rows.Count > 0)
        {
            if (ds_Checkuser.Tables[0].Rows[0]["modifyPrv"] == DBNull.Value || Convert.ToInt32(ds_Checkuser.Tables[0].Rows[0]["modifyPrv"]) != 1)
            {
                Response.Redirect("TransactionLandingPage.aspx");
            }
            if (ds_Checkuser.Tables[0].Rows[0]["deletePrv"] != DBNull.Value && Convert.ToInt32(ds_Checkuser.Tables[0].Rows[0]["deletePrv"]) == 1)
            {
                this.btn_Delete.Visible = true;
            }
            else
            {
                this.btn_Delete.Visible = false;
            }
        }
        else
        {
            Response.Redirect("TransactionLandingPAge.aspx");
        }
    }
    protected void btn_Delete_Click(object sender, EventArgs e)
    {
        objPermissionEventData.Delete_PermissionApplication(Convert.ToInt32(ViewState["vsPermissionId"].ToString()), Convert.ToInt32(Session["EmpAutoId"].ToString()));
        checkEmail = true;
        //if (lblStatus.Text == "Approved")
        //{
        //Mail Sending
        if (Convert.ToInt32(ConfigurationManager.AppSettings.Get("isRequiredEmail")) == 1)
        {
            SendMail();
        }
        //}
        string strScript = string.Empty;
        strScript = strScript + "<script language='javascript'>";
        if (checkEmail == false)
        {
            strScript = strScript + "alert('" + rm.GetString("Alert_PermissionApplicationCancelledEmailnotsent", ci) + "');";
        }
        else
        {
            strScript = strScript + "alert('" + rm.GetString("Alert_PermissionApplicationCancelled", ci) + "');";
        }
        strScript = strScript + "location.replace('TA_UI_Transactions_LeavePermission.aspx');";
        strScript = strScript + "</script>";
        //Dispaly alert messsage.
        Page.RegisterStartupScript("AlertPAdd", strScript);
    }
    private void SendMail()
    {
        try
        {
            MailMessage mailMessage = new MailMessage();
            string scriptText;
            DataTable dtTableScript = new DataTable();
            dtTableScript = objLeaveApplicationEventData.GetEmailScripts("New Permission Form");
            if (dtTableScript.Rows.Count > 0)
            {
                string status = "Cancelled";
                scriptText = dtTableScript.Rows[0]["ScriptText"].ToString();
                string strNoOfHours = CalculateNumberOfHoursApplied(lblPermissionFromTime.Text, lblPermissionToTime.Text);
                DataSet ds_EmailIdOfReportingTo = new DataSet();
                DataSet ds_EmailIdOfSanctionAuthority = new DataSet();
                if (ViewState["EmployeeID"] != null && ViewState["EmployeeID"].ToString() != string.Empty)
                {
                    ds_EmailIdOfReportingTo = objPermissionEventData.SelectMailIdOfReportingTo(Convert.ToInt32(ViewState["EmployeeID"]));
                    ds_EmailIdOfSanctionAuthority = objPermissionEventData.SelectMailIdOfSanctionAuthority(Convert.ToInt32(ViewState["EmployeeID"]));
                }
                string strEmailIdReportingTo = string.Empty;
                string strEmailIdSanctionAuthority = string.Empty;
                if (ds_EmailIdOfReportingTo != null)
                {
                    if (ds_EmailIdOfReportingTo.Tables.Count > 0)
                    {
                        if (ds_EmailIdOfReportingTo.Tables[0].Rows.Count > 0)
                        {
                            if (ds_EmailIdOfReportingTo.Tables[0].Rows[0]["EmailId"] != DBNull.Value)
                            {
                                if (ds_EmailIdOfReportingTo.Tables[0].Rows[0]["EmailId"].ToString() != string.Empty)
                                {
                                    strEmailIdReportingTo = ds_EmailIdOfReportingTo.Tables[0].Rows[0]["EmailId"].ToString();
                                }
                            }
                        }
                    }
                }
                if (ds_EmailIdOfSanctionAuthority != null)
                {
                    if (ds_EmailIdOfSanctionAuthority.Tables.Count > 0)
                    {
                        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() != string.Empty)
                                {
                                    strEmailIdSanctionAuthority = ds_EmailIdOfSanctionAuthority.Tables[0].Rows[0]["EmailId"].ToString();
                                    ViewState["EmailId_SanctioningAuthority"] = strEmailIdSanctionAuthority;
                                }
                            }
                        }
                    }
                }
                string strEmailIdSanAuthority_Forwarded = string.Empty;
                if (lblStatus.Text == "Forwarded")
                {
                    strEmailIdSanAuthority_Forwarded = strEmailIdSanctionAuthority;
                }
                if (lblStatus.Text != "Approved")
                {
                    strEmailIdSanctionAuthority = string.Empty;
                }
                if (strEmailIdReportingTo != string.Empty && strEmailIdSanctionAuthority != string.Empty && strEmailIdReportingTo == strEmailIdSanctionAuthority)
                {
                    mailMessage.To.Add(new MailAddress(strEmailIdReportingTo));
                }
                else
                {
                    if (strEmailIdSanctionAuthority != string.Empty)
                    {
                        mailMessage.To.Add(new MailAddress(strEmailIdSanctionAuthority));
                    }
                    else if (strEmailIdReportingTo != string.Empty && strEmailIdSanAuthority_Forwarded == string.Empty)
                    {
                        mailMessage.To.Add(new MailAddress(strEmailIdReportingTo));
                    }
                    if (lblStatus.Text == "Approved" && strEmailIdReportingTo != string.Empty)
                    {
                        mailMessage.CC.Add(new MailAddress(strEmailIdReportingTo));
                    }
                    if (strEmailIdSanAuthority_Forwarded != string.Empty)
                    {
                        mailMessage.To.Add(new MailAddress(strEmailIdSanAuthority_Forwarded));
                        mailMessage.CC.Add(new MailAddress(strEmailIdReportingTo));
                    }
                }
                //mailMessage.Subject = "TimeCheck : " + Convert.ToString(ViewState["vsLevelName"]) + " | " + lbl_EmployeeName.Text + " " + lblEmployeeIdData.Text + " | Permission  | " + status;
                mailMessage.Subject = "Permission Application - " + lbl_PermissionApplicationDate.Text + " | " + lblEmployeeIdData.Text + " - " + lbl_EmployeeName.Text + " | " + status;
                // As per elite partner requisition, mail should be trigger from admin id, whatever we configured in setting page.
                //25-Dec-2019 02:06 PM
                //if (Session["loginEmailId"].ToString() != string.Empty || Session["loginEmailId"] != null)
                //{
                //    if (Session["loginEmailId"].ToString() != ViewState["vsEmployeeEamilId"].ToString())
                //    {
                //        mailMessage.From = new MailAddress(Session["loginEmailId"].ToString());
                //    }
                //    else if (ViewState["vsEmployeeEamilId"].ToString() != string.Empty)
                //    {
                //        mailMessage.From = new MailAddress(ViewState["vsEmployeeEamilId"].ToString());
                //    }
                //    else
                //    {
                //        mailMessage.From = new MailAddress(ConfigurationManager.AppSettings.Get("FromId"));
                //    }
                //}
                //else
                //{
                mailMessage.From = new MailAddress(ConfigurationManager.AppSettings.Get("FromId"));
                //}
                mailMessage.CC.Add(new MailAddress(ViewState["vsEmployeeEamilId"].ToString()));
                //CC mails based on user group
                DataSet dsCCEmailIds = new DataSet();
                bool blnMailToSecondLevel = false;
                //For Planned Permission
                if (ViewState["IntimationType"].ToString() == "0")
                {
                    dsCCEmailIds = objCCGroup.GetCCEmailIds(Convert.ToInt16(ViewState["LevelId"].ToString()), Convert.ToInt16(ViewState["DesignationId"].ToString()), "P");
                    if (dsCCEmailIds != null)
                    {
                        if (dsCCEmailIds.Tables.Count > 0)
                        {
                            if (dsCCEmailIds.Tables[1].Rows.Count > 0)
                            {
                                if (Convert.ToBoolean(dsCCEmailIds.Tables[1].Rows[0]["MailTo_SecondLevel_Planned"].ToString()) == true)
                                {
                                    blnMailToSecondLevel = true;
                                }
                            }
                        }
                    }
                }
                //For UnPlanned Permission
                else
                {
                    dsCCEmailIds = objCCGroup.GetCCEmailIds(Convert.ToInt16(ViewState["LevelId"].ToString()), Convert.ToInt16(ViewState["DesignationId"].ToString()), "U");
                    if (dsCCEmailIds != null)
                    {
                        if (dsCCEmailIds.Tables.Count > 0)
                        {
                            if (dsCCEmailIds.Tables[1].Rows.Count > 0)
                            {
                                if (Convert.ToBoolean(dsCCEmailIds.Tables[1].Rows[0]["MailTo_SecondLevel_UnPlanned"].ToString()) == true)
                                {
                                    blnMailToSecondLevel = true;
                                }
                            }
                        }
                    }
                }
                //If status is pending and mail to up-line supervisor is true then sanction authorities email will be added in CC.
                if (ViewState["StatusOfApplication"].ToString() == "Pending")
                {
                    if (blnMailToSecondLevel == true)
                    {
                        mailMessage.CC.Add(ViewState["EmailId_SanctioningAuthority"].ToString());
                    }
                }
                //If status is approved the CC mail IDs
                if (ViewState["StatusOfApplication"].ToString() == "Approved")
                {
                    DataSet dsCCEmailIds_Approved = new DataSet();
                    DataTable dtCCEmailIds = new DataTable();
                    dsCCEmailIds_Approved = objCCGroup.GetCCEmailIds(Convert.ToInt16(ViewState["LevelId"].ToString()), Convert.ToInt16(ViewState["DesignationId"].ToString()), "O");
                    if (dsCCEmailIds_Approved.Tables.Count > 0)
                    {
                        dtCCEmailIds = dsCCEmailIds_Approved.Tables[0];
                        foreach (DataRow drCCMail in dtCCEmailIds.Rows)
                        {
                            dsCCEmailIds.Tables[0].Rows.Add(drCCMail["EmailId"].ToString());
                        }
                    }
                }
                if (dsCCEmailIds != null)
                {
                    if (dsCCEmailIds.Tables.Count > 0)
                    {
                        if (dsCCEmailIds.Tables[0].Rows.Count > 0)
                        {
                            foreach (DataRow drCcEmailId in dsCCEmailIds.Tables[0].Rows)
                            {
                                MailAddressCollection MailAddrCollectionCC = mailMessage.CC;
                                // added by Gopinath.k for Mantis Bug no.24059 & 24098
                                if (drCcEmailId["EmailId"].ToString() != string.Empty)
                                {
                                    MailAddress newCC = new MailAddress(drCcEmailId["EmailId"].ToString());
                                    MailAddrCollectionCC.Add(newCC);
                                }
                            }
                        }
                    }
                }
                //check for duplicate mail Ids
                //included by sashma on 20-Oct-2010
                Hashtable htToMails = new Hashtable();
                Hashtable htCCMails = new Hashtable();
                int intToMailCount = 0;
                int intCCMailCount = 0;
                //inserts the TO mailIds in the hashtable
                foreach (MailAddress ToMail in mailMessage.To)
                {
                    if (htToMails.ContainsValue(ToMail) == false)
                    {
                        htToMails.Add(intToMailCount++, ToMail);
                    }
                }
                //inserts the CC mailIds in the hashtable
                foreach (MailAddress CCMail in mailMessage.CC)
                {
                    //check whether the mail alredy exists in CC mails.
                    if (htCCMails.ContainsValue(CCMail) == false)
                    {
                        //check whether the mail alredy exists in TO mails.
                        if (htToMails.ContainsValue(CCMail) == false)
                        {
                            htCCMails.Add(intCCMailCount++, CCMail);
                        }
                    }
                }
                mailMessage.To.Clear();
                mailMessage.CC.Clear();
                //Adds the TO mails from the hastable.
                foreach (DictionaryEntry ToMails in htToMails)
                {
                    mailMessage.To.Add(ToMails.Value.ToString());
                }
                //Adds the CC mails from the hastable.
                foreach (DictionaryEntry CCMails in htCCMails)
                {
                    mailMessage.CC.Add(CCMails.Value.ToString());
                }
                mailMessage.Body = scriptText.Replace("<<PermissionForm>>", rm.GetString("email_PermissionForm", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<EmployeeId>>", lblEmployeeIdData.Text);
                mailMessage.Body = mailMessage.Body.Replace("<<lblEmployeeId>>", rm.GetString("email_EmployeeId", ci));
                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("<<lblDepartment>>", "Department");
                mailMessage.Body = mailMessage.Body.Replace("<<Department>>", ViewState["vsLevelName"].ToString());
                mailMessage.Body = mailMessage.Body.Replace("<<lblApplicationDate>>", "Application Date");
                mailMessage.Body = mailMessage.Body.Replace("<<ApplicationDate>>", lbl_PermissionApplicationDate.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>>", lblAppliedHours.Text);
                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>>", "Remarks");
                mailMessage.Body = mailMessage.Body.Replace("<<Reason>>", txtReasonForCancel.Text.Trim().Replace(",", "''"));
                string strReplaceText = "<a href=\"<<LinkData>>\">Click here for approval</a>";
                mailMessage.Body = mailMessage.Body.Replace(strReplaceText, string.Empty);
                objClassCommon.SendMail(mailMessage);
            }
            else
            {
                checkEmail = false;
            }
        }
        catch
        {
            //Response.Write(ex.Message);           
            checkEmail = false;
        }
    }
    /// <summary>
    /// Calculate the Number of permission hours applied
    /// </summary>
    /// <returns></returns>
    public string CalculateNumberOfHoursApplied(string startTime, string EndTime)
    {
        //TimeSpan tsStartTime = DateTime.Parse(txt_StartTime.Text).TimeOfDay;
        //TimeSpan tsEndTime = DateTime.Parse(txt_EndTime.Text).TimeOfDay;
        TimeSpan tsDiff = new TimeSpan();
        startTime = objClassCommon.DateConvertion(gstrDateFormat, startTime);
        EndTime = objClassCommon.DateConvertion(gstrDateFormat, EndTime);
        DateTime dtmIn = DateTime.Parse(startTime);
        DateTime dtmOut = DateTime.Parse(EndTime);
        tsDiff = dtmOut.Subtract(dtmIn);
        string s = tsDiff.ToString();
        int sReturn = s.LastIndexOf(':');
        string RemainHours = s.Remove(sReturn);
        //tsDiff = tsEndTime.Subtract(tsStartTime);
        //int iDays = DateDifference(DateTime.Parse(txtToDate.Text), DateTime.Parse(txtFromDate.Text));
        //  double dDays = Double.Parse(iDays.ToString());
        return (RemainHours);
    }
    #region Split Mail ids
    private string[] SplitCCTo(string CCTo)
    {
        string[] strArrEmailAddressForCC;
        strArrEmailAddressForCC = CCTo.Split(';');
        return (strArrEmailAddressForCC);
    }
    #endregion
    /// <summary>
    /// Messages the specified message content.
    /// </summary>
    /// <param name="messageContent">Content of the message.</param>
    private void Message(string messageContent)
    {
        string strScript = "<script language='javascript' type='text/javascript'>";
        strScript += "alert('" + messageContent + "');";
        strScript += " </script>";
        this.RegisterStartupScript("setScript", strScript);
    }
}
