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.Globalization;
using System.Threading;
using System.Reflection;
using System.Resources;
using System.Net.Mail;
using System.Net;
using System.Text;
public partial class Transactions_TA_UI_Transactions_MultipleLeaveApplicationView : Base.BasePage
{
    ResourceManager rm;
    CultureInfo ci;
    Cls_CheckUser objCheckUser = new Cls_CheckUser();
    DataSet ds_Checkuser = new DataSet();
    DataSet ds_EmployeeDetails = new DataSet();
    LeaveApplicationEventData_Angler objLeaveApplicationEventData = new LeaveApplicationEventData_Angler();
    EmployeeEventData objEmployeeEventData = new EmployeeEventData();
    PermissionEventData objPermissionEventData = new PermissionEventData();
    CCGroupEventData_Angler objCCGroup = new CCGroupEventData_Angler();
    int iLeaveApplication_Id, iEmployeeID;
    string strHtmlLeaveDetails = string.Empty;
    string strHtml = string.Empty;
    //Added by Manjula.P on 13-May-2014 for getting datetime common format
    string gstrDateFormat = string.Empty;
    cls_Common objClassCommon = new cls_Common();
    bool blnCheckEmail;
    /// <summary>
    /// Instance of Resource Manager to get Resource file contents
    /// </summary>
    ResourceManager objResourceManager;
    /// <summary>
    /// Instance of Culture Info to set the current culture
    /// </summary>
    CultureInfo objCultureInfo;
    protected override void Page_Load(object sender, EventArgs e)
    {
        // session checking
        base.Page_Load(sender, e);
        if (Request.UrlReferrer != null)
        {
            string GetURL = Request.UrlReferrer.ToString();
        }
        else
        {
            Response.Redirect("TA_UI_Transactions_LeaveApplication.aspx");
        }
        //get the culture info to set the language
        //Added by Manjula.P on 13-may-2014
        gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
        string source_Language;
        source_Language = Session["Session_ActiveLanguage"].ToString();
        rm = new ResourceManager(source_Language, System.Reflection.Assembly.Load("App_GlobalResources"));
        ci = Thread.CurrentThread.CurrentCulture;
        site.SiteMapProvider = Convert.ToString(Session["SiteMapProvider"]);
        LoadStrings(ci);
        //Set UserRights
        UserRights();
        if (Session["User"] == null)
        {
            Response.Redirect("../index.aspx");
        }
        if (Session["User"].ToString() == "")
        {
            Response.Redirect("../index.aspx");
        }
        iLeaveApplication_Id = int.Parse(Request.QueryString["LeaveApplication_Id"].ToString());
        ViewState["vsLeaveApplicationId"] = iLeaveApplication_Id;
        if (!Page.IsPostBack)
        {
            ViewDetails();
            GetEmployeeName();
            //dynamic controls for leave conversation
            ControlCreation();
        }    
    }
    private void ControlCreation()
    {
        // getting leave conversation 
        DataSet dsLeaveConversation = objLeaveApplicationEventData.GetLeaveConversation(iLeaveApplication_Id);
        if (dsLeaveConversation.Tables[0].Rows.Count > 0)
        {
            Table leaveConversation = new Table();
            //leaveConversation.BorderWidth = 1;
            //leaveConversation.CellPadding = 5;
            //leaveConversation.CellSpacing = 0;
            //leaveConversation.BorderColor = System.Drawing.Color.White;
            leaveConversation.Width = Unit.Percentage(100);
            leaveConversation.CssClass = "table das-table1";
            //leaveConversation.Attributes.Add("border", "1");
            TableHeaderRow leaveConversationHr = new TableHeaderRow();
            TableHeaderCell leaveConversationHeading3 = new TableHeaderCell();
            leaveConversationHeading3.Text = rm.GetString("TerminalDataType_Date_And_Time", ci); 
            leaveConversationHeading3.HorizontalAlign = HorizontalAlign.Left;
            leaveConversationHr.Cells.Add(leaveConversationHeading3);
            TableHeaderCell leaveConversationHeading1 = new TableHeaderCell();
            leaveConversationHeading1.Text = rm.GetString("leaveConversationHeading1", ci);
            leaveConversationHeading1.HorizontalAlign = HorizontalAlign.Left;
            leaveConversationHr.Cells.Add(leaveConversationHeading1);
            TableHeaderCell leaveConversationHeading2 = new TableHeaderCell();
            leaveConversationHeading2.Text = rm.GetString("leaveConversationHeading2", ci);
            leaveConversationHeading2.HorizontalAlign = HorizontalAlign.Left;
            leaveConversationHr.Cells.Add(leaveConversationHeading2);
            leaveConversationHr.CssClass = "empheader";
            leaveConversation.Rows.Add(leaveConversationHr);
            if (dsLeaveConversation != null && dsLeaveConversation.Tables.Count > 0)
            {
                if (dsLeaveConversation.Tables[0].Rows.Count > 0)
                {
                    int rowIndex = 0;
                    foreach (DataRow drLeaveConversation in dsLeaveConversation.Tables[0].Rows)
                    {
                        TableRow trLeaveConversation = new TableRow();
                        TableCell tcLeaveConversationRepliedOn = new TableCell();
                        //tcLeaveConversationRepliedOn.BorderColor = System.Drawing.Color.White;
                        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();
                        //tcLeaveConversationCommentsBy.BorderColor = System.Drawing.Color.White;
                        Label lblLeaveConversationCommentsBy = new Label();
                        //tcLeaveConversationCommentsBy.BorderWidth = 1;
                        //tcLeaveConversationCommentsBy.Width = 153;
                        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();
                        //tcLeaveConversationComments.BorderColor = System.Drawing.Color.White;
                        Label lblLeaveConversationComments = new Label();
                        //tcLeaveConversationComments.BorderWidth = 1;
                        //tcLeaveConversationComments.ColumnSpan = 2;
                        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);
        }
    }
    /// <summary>
    /// Using Resource file, here the label and button text are changed
    /// </summary>
    /// <param name="ci"></param>
    private void LoadStrings(CultureInfo ci)
    {
        lbl_EmployeeID1.Text = rm.GetString("email_EmployeeId", ci);
        lbl_EmployeeName1.Text = rm.GetString("email_EmployeeName", ci);
        //lbl_From.Text = rm.GetString("email_FromDate", ci);
        //lbl_Leave.Text = rm.GetString("LeaveApplication_Leave", ci);
        //lbl_LeaveApplicationDate1.Text = rm.GetString("LeaveApplication_LeaveApplicationDate", ci);
        //lbl_LeaveRestrictedHoliday.Text = rm.GetString("LeaveApplication_LeaveRestrictedHoliday", ci);
        //lbl_LeaveType.Text = rm.GetString("lbl_leavetype", ci);
        //lbl_Numberofdaysapplied.Text = rm.GetString("LeaveApplication_NumberOfDaysApplied", ci);
        lbl_Reason.Text = rm.GetString("email_Reason", ci);
        //lbl_To.Text = rm.GetString("email_ToDate", ci);
        lbl_HeaderLeaveApplication.Text = rm.GetString("Transactions_LeaveApplication", ci);
        //lbl_FromSession.Text = rm.GetString("Transactions_FromSession", ci);
        //lbl_ToSession.Text = rm.GetString("Transactions_ToSession", ci);
        btn_Cancel.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Back", ci);
        btn_Delete.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Delete", ci);
        btn_Delete.Text = "&nbsp;&nbsp;" + rm.GetString("lbl_CancelLeave", ci);
    }
    protected void btn_Delete_Click(object sender, EventArgs e)
    {
        if (txtReasonForCancel.Text.Trim() == string.Empty)
        {
            Message("Enter Reason");
            return;
        }
        string strLengthCheck = txtReasonForCancel.Text.Trim().Replace("'", "''");
        if (strLengthCheck.Length > 1000)
        {
            Message("Maximum character for Reason is 1000");
            return;
        }
        DataSet dsIsDeleteCount = new DataSet();
        //Delete Leave Application
        dsIsDeleteCount = objLeaveApplicationEventData.Delete_LeaveApplication(Convert.ToInt32(iLeaveApplication_Id), Convert.ToInt32(Session["EmpAutoId"]), Convert.ToDateTime(DateTime.Now.ToString()), Convert.ToDateTime(DateTime.Now.ToString()), string.Empty, string.Empty, "A");
        if (ViewState["StatusOfApplication"].ToString() == "Approved")
        {
            if (Convert.ToInt32(ConfigurationManager.AppSettings.Get("isRequiredEmail")) == 1)
            {
                SendMail(Convert.ToInt32(ViewState["vsLeaveApplicationId"]), 1, 1, 1, "Reporting Mail", "Sanction Mail");
            }
        }
        else
        {
            if (Convert.ToInt32(ConfigurationManager.AppSettings.Get("isRequiredEmail")) == 1)
            {
                SendMail(Convert.ToInt32(ViewState["vsLeaveApplicationId"]), 1, 1, 1, "Reporting Mail", null);
            }
        }
        string strScript = "";
        strScript = strScript + "<script language='javascript'>";
        strScript = strScript + "alert('Leave Application Cancelled');";
        strScript = strScript + "location.replace('TA_UI_Transactions_LeaveApplication.aspx');";
        strScript = strScript + "</script>";
        //Dispaly alert messsage.
        Page.RegisterStartupScript("AlertLDel65507866", strScript);
        //Declare Leave Status
        //string strLeaveStatus = string.Empty; 
        //if (Session["Edition"].ToString() == "0" || Session["Edition"].ToString() == "3")
        //{
        //    //Get Compnay Id of the Employeee
        //    int intCompanyId = base.GetCompanyId(Convert.ToInt32(ViewState["iEmployeeID"]));
        //    //Get Approval Settings Based on Company Id
        //    DataSet dsApprovalSettings = new DataSet();
        //    ShiftEvenData objShift = new ShiftEvenData();
        //    dsApprovalSettings = objShift.SelectApprovalSettings(intCompanyId);
        //    if (dsApprovalSettings != null)
        //    {
        //        if (dsApprovalSettings.Tables.Count > 0)
        //        {
        //            if (dsApprovalSettings.Tables[0].Rows.Count > 0)
        //            {
        //                if (Convert.ToBoolean(dsApprovalSettings.Tables[0].Rows[0]["LeaveSanction"]) == false)
        //                {
        //                    strLeaveStatus = "ApprovalNotRequired";
        //                }
        //            }
        //            else
        //            {
        //                base.Message("Approval Settings yet to defined for this company");
        //                return;
        //            }
        //        }
        //    }
        //}
        //else if (Session["Edition"].ToString() == "1")
        //{
        //    strLeaveStatus = "ApprovalNotRequired";
        //}        
        //if (ViewState["StatusOfApplication"].ToString() == "Pending" || strLeaveStatus == "ApprovalNotRequired")
        //{
        //    //Check Borrow Leave Exists after normal leaves
        //    int intBorrowCount = objLeaveApplicationEventData.CheckBorrowLeaveExists(ViewState["LeaveFromDate"].ToString(), ViewState["LeaveToDate"].ToString(), Convert.ToInt32(ViewState["LeaveTypeId"]), Convert.ToInt32(ViewState["iEmployeeID"]));
        //    if (intBorrowCount > 0)
        //    {
        //        base.Message("Borrow Leaves are available to delete");
        //        return;
        //    }
        //    DataSet dsIsDeleteCount = new DataSet();
        //    //Delete Leave Application
        //    dsIsDeleteCount = objLeaveApplicationEventData.Delete_LeaveApplication(Convert.ToInt32(iLeaveApplication_Id), Convert.ToInt32(Session["EmpAutoId"]),Convert.ToDateTime(DateTime.Now.ToString()),Convert.ToDateTime(DateTime.Now.ToString()), string.Empty, string.Empty, "A");
        //    if (dsIsDeleteCount.Tables[0].Rows[0]["LeaveCount"].ToString().Equals("0"))
        //    {
        //        Response.Redirect("TA_UI_Transactions_LeaveApplication.aspx");
        //    }
        //    //Update Year Closure
        //    //YearClosureUpdate(strLeaveStatus);
        //    //MailToReportingTo();
        //    string strScript = "";
        //    strScript = strScript + "<script language='javascript'>";
        //    strScript = strScript + "alert('Leave Application Canceled');";
        //    strScript = strScript + "location.replace('TA_UI_Transactions_LeaveApplication.aspx');";
        //    strScript = strScript + "</script>";
        //    //Dispaly alert messsage.
        //    Page.RegisterStartupScript("AlertLDel65507866", strScript);
        //    //Response.Redirect("TA_UI_Transactions_LeaveApplication.aspx");
        //}
        //else
        //{
        //    Page.RegisterStartupScript("statusalert", "<script language='javascript'>alert('Cannot cancel this Leave');</script>");
        //}
    }
    //public void YearClosureUpdate(string strLeaveStatus)
    //{
    //    if (strLeaveStatus == "ApprovalNotRequired")
    //    {
    //        int Employee_Id = Convert.ToInt32(ViewState["iEmployeeID"]);
    //        string strTypeOfLeave = lblType.Text;
    //        if (strTypeOfLeave == "Leave")
    //        {
    //            double NumberOfDays = Convert.ToDouble(lblNumberofdaysapplied.Text);
    //            int LeaveTypeId = Convert.ToInt32(ViewState["LeaveTypeId"]);
    //            if (Convert.ToBoolean(ViewState["IsBorrow"]) == false)
    //            {
    //                objLeaveApplicationEventData.UpdateYearClosureByLeaveSanction(NumberOfDays, LeaveTypeId, Employee_Id, "R", Convert.ToInt32(Session["EmpAutoId"]));
    //            }
    //            else
    //            {
    //                objLeaveApplicationEventData.UpdateYearClosureByLeaveSanction(NumberOfDays, LeaveTypeId, Employee_Id, "RB", Convert.ToInt32(Session["EmpAutoId"]));
    //            }
    //        }
    //        // Update Processed Data Flag for Re-Processing
    //        objLeaveApplicationEventData.UpdateProcessedDataFlag(Employee_Id, ViewState["LeaveFromDate"].ToString(), ViewState["LeaveToDate"].ToString(), 0);
    //    }
    //}
    /// <summary>
    /// Display Leave Application Details Based on Leave Application Id
    /// </summary>
    public void ViewDetails()
    {
        DataSet ds_LeaveApplication = new DataSet();
        ds_LeaveApplication = objLeaveApplicationEventData.SelectLeaveApplication(iLeaveApplication_Id);
        if (ds_LeaveApplication.Tables[0].Rows.Count > 0)
        {
        DataTable dtLeaveSort = new DataTable();
        DataTable dtLeaveTable2 = new DataTable();
        dtLeaveSort = ds_LeaveApplication.Tables[0];
        dtLeaveTable2 = ds_LeaveApplication.Tables[1];
        dtLeaveSort.DefaultView.Sort = "LeaveFrom asc";
        ds_LeaveApplication.Tables.Clear();
        ds_LeaveApplication.Tables.Add(dtLeaveSort.DefaultView.ToTable());
        ds_LeaveApplication.Tables.Add(dtLeaveTable2);
        iEmployeeID = Convert.ToInt32(ds_LeaveApplication.Tables[0].Rows[0]["Employee_Id"]);
        string strLeaveAppliedType = ds_LeaveApplication.Tables[0].Rows[0]["Intimationtype"].ToString();
        ViewState["iEmployeeID"] = iEmployeeID.ToString();
        //To store the Audit Employee id
        ViewState["auEmpId"] = Convert.ToInt32(ds_LeaveApplication.Tables[0].Rows[0]["Emp_Id"]);
        DataSet dsEmailIdOfReportingTo = objPermissionEventData.SelectMailIdOfReportingTo(Convert.ToInt32(ViewState["iEmployeeID"]));
        DataSet ds_EmailIdOfSanctionAuthority = objPermissionEventData.SelectMailIdOfSanctionAuthority(Convert.ToInt32(ViewState["iEmployeeID"]));
        bool blnEnableModify = 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() != "")
                {
                    ViewState["EmailId_SanctioningAuthority"] = ds_EmailIdOfSanctionAuthority.Tables[0].Rows[0]["EmailId"].ToString();
                    if (dsEmailIdOfReportingTo.Tables[0].Rows[0]["EmailId"].ToString() == ds_EmailIdOfSanctionAuthority.Tables[0].Rows[0]["EmailId"].ToString())
                    {
                        blnEnableModify = true;
                    }
                }
            }
        }
        //TODO: Karthikeyan
        //blnEnableModify = true;
        ViewState["StatusOfApplication"] = ds_LeaveApplication.Tables[1].Rows[0]["Status"].ToString();
        txtApprovalCC.Text = ds_LeaveApplication.Tables[0].Rows[0]["CCMail"].ToString();
        if (ds_LeaveApplication.Tables[1].Rows[0]["Status"].ToString() == "Reply")
        {
            if (Session["UserGroupName"].ToString() == "SuperAdmin")
            {
                btn_Delete.Enabled = true;
            }
            else
            {
                btn_Delete.Enabled = false;
                btn_Delete.OnClientClick = null;
            }
            btnModify.Enabled = false;
        }
        if (ds_LeaveApplication.Tables[1].Rows[0]["Status"].ToString() == "Rejected")
        {
            btn_Delete.Enabled = false;
            btn_Delete.OnClientClick = null;
        }
        if (ds_LeaveApplication.Tables[1].Rows[0]["Status"].ToString() == "Pending" || ds_LeaveApplication.Tables[1].Rows[0]["Status"].ToString() == "Resend")
        {
            btnModify.Enabled = true;
        }
        else if (blnEnableModify == true && ds_LeaveApplication.Tables[1].Rows[0]["Status"].ToString() != "Approved")
        {
            btnModify.Enabled = true;
        }
        else
        {
            btnModify.Enabled = false;
        }
        grv_LeaveApplication.DataSource = ds_LeaveApplication;
        grv_LeaveApplication.DataBind();
        //if (ds_LeaveApplication.Tables[0].Rows.Count > 1)
        //{
        //    btn_Delete.Visible = true;
        //}
        //    else
        //{
        //    btn_Delete.Visible = false;
        //}
        //lblType.Text = ds_LeaveApplication.Tables[0].Rows[0]["Type"].ToString();
        //lblLeaveType.Text = ds_LeaveApplication.Tables[0].Rows[0]["LeaveType"].ToString();
        ViewState["EmployeeEmailId"] = ds_LeaveApplication.Tables[0].Rows[0]["emailId"].ToString();
        ViewState["LeaveTypeId"] = ds_LeaveApplication.Tables[0].Rows[0]["LeaveType_Id"].ToString();
        //lbl_LeaveApplicationDate.Text = (DateTime.Parse(ds_LeaveApplication.Tables[0].Rows[0]["Leave_ApplicationDate"].ToString())).ToString(Session["MDateFormat"].ToString());
        //lblFromDate.Text  = (DateTime.Parse(ds_LeaveApplication.Tables[0].Rows[0]["Leave_FromDate"].ToString())).ToString(Session["MDateFormat"].ToString());
        ViewState["LeaveFromDate"] = ds_LeaveApplication.Tables[0].Rows[0]["LeaveFrom"].ToString();
        //lblToDate.Text = (DateTime.Parse(ds_LeaveApplication.Tables[0].Rows[0]["Leave_ToDate"].ToString())).ToString(Session["MDateFormat"].ToString());
        ViewState["LeaveToDate"] = ds_LeaveApplication.Tables[0].Rows[0]["LeaveTo"].ToString();
        // ddl_Type.SelectedItem.Text = ds_LeaveApplication.Tables[0].Rows[0]["Type"].ToString();
        //lblSessionFrom.Text  = ds_LeaveApplication.Tables[0].Rows[0]["Leave_SessionFrom"].ToString();
        //lblSessionTo.Text = ds_LeaveApplication.Tables[0].Rows[0]["Leave_SessionTo"].ToString();
        lblReason.Text = ds_LeaveApplication.Tables[0].Rows[0]["Reason"].ToString();
        //lblNumberofdaysapplied.Text  = ds_LeaveApplication.Tables[0].Rows[0]["NumberOfDays"].ToString();
        ViewState["IsBorrow"] = ds_LeaveApplication.Tables[0].Rows[0]["IsBorrow"].ToString();
        LblLevelData.Text = ds_LeaveApplication.Tables[0].Rows[0]["LevelName"].ToString();
        //Company Level Approval Mail Ids
        // 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();
        DataSet dsDepartmentMailIds = new DataSet();
        dsDepartmentMailIds = objLeaveSettingsEventData.GetDepartmentMailIds(Convert.ToInt32(ds_LeaveApplication.Tables[0].Rows[0]["LevelId"]));
        ViewState["vsStrApprovalToDept"] = dsDepartmentMailIds.Tables[0].Rows[0]["ToMailIds"].ToString();
        ViewState["vsStrApprovalCCDept"] = dsDepartmentMailIds.Tables[0].Rows[0]["CCMailIds"].ToString();
        getOrg.GetOrgParentLevels_FromID(Convert.ToInt32(ds_LeaveApplication.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 (ds_LeaveApplication.Tables[1].Rows[0]["Status"].ToString() == "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 (strLeaveAppliedType != "P" && Session["UserGroupName"].ToString() != "SuperAdmin" && Session["HasSpecialRights"].ToString() != "True")
            {
                if (ViewState["StatusOfApplication"].ToString() != "Resend")
                {
                    btnModify.Enabled = false;
                }
                btn_Delete.Enabled = false;
                btn_Delete.OnClientClick = null;
            }
        }
    }
    /// <summary>
    /// Get Employee Name Based on EmployeeId
    /// </summary>
    public void GetEmployeeName()
    {
        if (Session["user"] == null || Session["user"].ToString() == "")
        {
            Response.Redirect("../Index.aspx");
        }
        else
        {
            string strEmpFirstName, strEmpLastName;
            ds_EmployeeDetails = objEmployeeEventData.Select_EmployeeDetailsNewbyId(iEmployeeID);
            ViewState["ds_EmployeeDetails"] = ds_EmployeeDetails;
            strEmpFirstName = ds_EmployeeDetails.Tables[0].Rows[0]["Employee_FirstName"].ToString();
            strEmpLastName = ds_EmployeeDetails.Tables[0].Rows[0]["Employee_LastName"].ToString();
            lbl_EmployeeID.Text = ds_EmployeeDetails.Tables[0].Rows[0]["Employee_Code_Id"].ToString();
            lbl_EmployeeName.Text = strEmpFirstName + " " + strEmpLastName;
        }
    }
    protected void btn_Cancel_Click(object sender, EventArgs e)
    {
        Response.Redirect("TA_UI_Transactions_LeaveApplication.aspx");
    }
    private void UserRights()
    {
        ds_Checkuser = objCheckUser.checkRights(22, Convert.ToInt32(Session["userGroup_Id"]), "");
        if (ds_Checkuser.Tables[0].Rows.Count > 0)
        {
            if (ds_Checkuser.Tables[0].Rows[0]["viewPrv"] == DBNull.Value || Convert.ToInt32(ds_Checkuser.Tables[0].Rows[0]["viewPrv"]) != 1)
            {
                Response.Redirect("TA_UI_Transactions_LeaveApplication.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");
        }
    }
    private void SendMail(Int64 LeaveApplicationId, Int64 LevelId, int intFirstLevelAuthorityId, int intSecondLevelAuthorityId, string strEmailIdReportingTo, string strEmailIdSanctionAuthority)
    {
        //To Get the Leave Details with the Cancelled Leave
        DataSet dsLeave = new DataSet();
        dsLeave = objLeaveApplicationEventData.SelectLeaveApplicationWithCancellation(Convert.ToInt32(ViewState["vsLeaveApplicationId"]));
        string strIntimationType = dsLeave.Tables[0].Rows[0]["IntimationType"].ToString();
        string strLeaveStatus = dsLeave.Tables[0].Rows[0]["Status"].ToString();
        if (strIntimationType == "P")
        { 
        }
        foreach (DataRow dRow in dsLeave.Tables[0].Rows)
        {
            if (dRow["IsDeleted"].ToString() == "True")
            {
                dRow["Status"] = "Cancelled";
            }
            if (dRow["Leave Category"].ToString() == "LOP")
            {
                dRow["Leave Type"] = "-";
            }
            DateTime dtmFromDate = Convert.ToDateTime(DateTime.Parse(dRow["LeaveFrom"].ToString()));
            DateTime dtmToDate = Convert.ToDateTime(DateTime.Parse(dRow["LeaveTo"].ToString()));
            string strLeaveFrom = dtmFromDate.ToString(Session["MDateFormat"].ToString());
            string strLeaveTo = dtmToDate.ToString(Session["MDateFormat"].ToString());
            dRow["From"] = strLeaveFrom;
            dRow["To"] = strLeaveTo;
        }
        dsLeave.Tables[0].Columns.Remove("IsDeleted");
        dsLeave.Tables[0].Columns.Remove("LeaveFrom");
        dsLeave.Tables[0].Columns.Remove("LeaveTo");
        dsLeave.Tables[0].Columns.Remove("IntimationType");
        strHtmlLeaveDetails = buildPage("Leave Details", dsLeave.Tables[0]);
        //To find Leave Sanction Authorities Email_ID
        DataSet dsEmailIdOfReportingTo = objPermissionEventData.SelectMailIdOfReportingTo(Convert.ToInt32(ViewState["iEmployeeID"]));
        if (dsEmailIdOfReportingTo != null)
        {
            if (dsEmailIdOfReportingTo.Tables.Count > 0)
            {
                if (dsEmailIdOfReportingTo.Tables[0].Rows.Count > 0)
                {
                    if (dsEmailIdOfReportingTo.Tables[0].Rows[0]["EmailId"] != DBNull.Value)
                    {
                        if (dsEmailIdOfReportingTo.Tables[0].Rows[0]["EmailId"].ToString() != "")
                        {
                            intFirstLevelAuthorityId = int.Parse(dsEmailIdOfReportingTo.Tables[0].Rows[0]["Employee_Id"].ToString());
                            strEmailIdReportingTo = dsEmailIdOfReportingTo.Tables[0].Rows[0]["EmailId"].ToString();
                        }
                        else
                        {
                            blnCheckEmail = false;
                        }
                    }
                    else
                    {
                        blnCheckEmail = false;
                    }
                }
                else
                {
                    blnCheckEmail = false;
                }
            }
        }
        // Gets the Sanctioning Authority Id and Email Id
        if (strEmailIdSanctionAuthority != null)
        {
            //DataSet ds_EmailIdOfSanctionAuthority = objPermissionEventData.SelectMailIdOfSanctionAuthority(Convert.ToInt32(ViewState["iEmployeeID"]));
            //if (ds_EmailIdOfSanctionAuthority.Tables[0].Rows.Count > 0)
            //{
            //    if (ds_EmailIdOfSanctionAuthority.Tables[0].Rows[0]["EmailId"] != DBNull.Value && ds_EmailIdOfSanctionAuthority.Tables[0].Rows[0]["EmailId"].ToString() != string.Empty)
            //    {
            //        intSecondLevelAuthorityId = int.Parse(ds_EmailIdOfSanctionAuthority.Tables[0].Rows[0]["Employee_Id"].ToString());
            //        strEmailIdSanctionAuthority = ds_EmailIdOfSanctionAuthority.Tables[0].Rows[0]["EmailId"].ToString();
            //    }
            //}
            if (ViewState["EmailId_SanctioningAuthority"] != null)
            {
                strEmailIdSanctionAuthority = ViewState["EmailId_SanctioningAuthority"].ToString();
            }
        }
        string strEmailIdSancAuthority_Forwarded = string.Empty;
        if (ViewState["StatusOfApplication"].ToString() == "Forwarded")
        {
            strEmailIdSancAuthority_Forwarded =Convert.ToString( ViewState["EmailId_SanctioningAuthority"]);
        }
        if (strEmailIdSanctionAuthority == null)
        {
            strEmailIdSanctionAuthority = string.Empty;
        }
        if (strEmailIdReportingTo == null)
        {
            strEmailIdReportingTo = string.Empty;
        }
        if (strEmailIdSanctionAuthority == string.Empty && strEmailIdReportingTo == string.Empty && txtApprovalCC.Text == string.Empty)
        {
            blnCheckEmail = false;
        }
        if (blnCheckEmail == true)
        {
        string FromDate = string.Empty, ToDate = string.Empty;
        double NumberOfDaysApplied = 0.0;
            try
            {
                MailMessage mailMessage = new MailMessage();
                SmtpClient loSMTPServer = new SmtpClient();
                System.Net.Mime.ContentType loTextType = new System.Net.Mime.ContentType("text/plain");
                System.Net.Mime.ContentType loHTMLType = new System.Net.Mime.ContentType("text/html");
                AlternateView loTextView = null;
                AlternateView loHTMLView = null;
                string scriptText, status;
                DataTable dtTableScript = new DataTable();
                string ScriptType = "Leave Cancellation";
                dtTableScript = objLeaveApplicationEventData.GetEmailScripts(ScriptType);
                scriptText = dtTableScript.Rows[0]["ScriptText"].ToString();
                if (Session["loginEmailId"].ToString() != string.Empty || Session["loginEmailId"] != null)
                {
                    if (Session["loginEmailId"].ToString() != ViewState["EmployeeEmailId"].ToString())
                    {
                        mailMessage.From = new MailAddress(Session["loginEmailId"].ToString());
                        //mailMessage.CC.Add(new MailAddress(ViewState["EmployeeEmailId"].ToString()));
                    }
                    else if (ViewState["EmployeeEmailId"].ToString() != string.Empty)
                    {
                        mailMessage.From = new MailAddress(ViewState["EmployeeEmailId"].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["EmployeeEmailId"].ToString()));
                status = "Cancelled";
                mailMessage.Subject = "TimeCheck : " + LblLevelData.Text + " | " + lbl_EmployeeName.Text + " " + lbl_EmployeeID.Text + " | Leave  - " + status;
                string strCcMails = txtApprovalCC.Text;
                //CC Mails          
                if (strEmailIdReportingTo != string.Empty && strEmailIdSanctionAuthority != string.Empty && strEmailIdReportingTo == strEmailIdSanctionAuthority)
                {
                    mailMessage.To.Add(strEmailIdReportingTo);
                }
                else
                {
                    if (strEmailIdSanctionAuthority != string.Empty)
                    {
                        mailMessage.To.Add(strEmailIdSanctionAuthority);
                    }
                    else if (strEmailIdReportingTo != string.Empty && strEmailIdSancAuthority_Forwarded == string.Empty)
                    {
                        mailMessage.To.Add(strEmailIdReportingTo);
                    }
                    if (ViewState["StatusOfApplication"].ToString() == "Approved" && strEmailIdReportingTo != string.Empty)
                    {
                        mailMessage.CC.Add(new MailAddress(strEmailIdReportingTo));
                    }
                    if (ViewState["StatusOfApplication"].ToString() == "Forwarded")
                    {
                        mailMessage.To.Add(new MailAddress(strEmailIdSancAuthority_Forwarded));
                        mailMessage.CC.Add(new MailAddress(strEmailIdReportingTo));
                    }
                }
                //CC mails based on user group
                DataSet dsCCEmailIds = new DataSet();
                ds_EmployeeDetails = (DataSet)ViewState["ds_EmployeeDetails"];
                bool blnMailToSecondLevel = false;
                //For Planned Leave
                if (strIntimationType == "P")
                {
                    dsCCEmailIds = objCCGroup.GetCCEmailIds(Convert.ToInt16(ds_EmployeeDetails.Tables[0].Rows[0]["LevelId"].ToString()), Convert.ToInt16(ds_EmployeeDetails.Tables[0].Rows[0]["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 Leave
                else
                {
                    dsCCEmailIds = objCCGroup.GetCCEmailIds(Convert.ToInt16(ds_EmployeeDetails.Tables[0].Rows[0]["LevelId"].ToString()), Convert.ToInt16(ds_EmployeeDetails.Tables[0].Rows[0]["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 (strLeaveStatus == "Pending")
                {
                    if (blnMailToSecondLevel == true)
                    {
                        mailMessage.CC.Add(ViewState["EmailId_SanctioningAuthority"].ToString());
                    }
                }
                //If status is approved the CC mail IDs
                if (strLeaveStatus == "Approved")
                {
                    DataSet dsCCEmailIds_Approved = new DataSet();
                    DataTable dtCCEmailIds = new DataTable();
                    dsCCEmailIds_Approved = objCCGroup.GetCCEmailIds(Convert.ToInt16(ds_EmployeeDetails.Tables[0].Rows[0]["LevelId"].ToString()), Convert.ToInt16(ds_EmployeeDetails.Tables[0].Rows[0]["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("<<lblLeaveApplicationForm>>", rm.GetString("email_LeaveApplicationForm", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<ltr_rtl>>", rm.GetString("Direction", objCultureInfo));
                mailMessage.Body = mailMessage.Body.Replace("<<lblEmployeeId>>", rm.GetString("email_EmployeeId", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<EmployeeId>>", lbl_EmployeeID.Text);
                mailMessage.Body = mailMessage.Body.Replace("<<EmployeeName>>", lbl_EmployeeName.Text);
                mailMessage.Body = mailMessage.Body.Replace("<<lblEmployeeName>>", rm.GetString("email_EmployeeName", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<Department>>", LblLevelData.Text);
                mailMessage.Body = mailMessage.Body.Replace("<<lblDepartment>>", "Department");
                mailMessage.Body = mailMessage.Body.Replace("<<NoOfLeaveAvailedMonth>>", "");
                mailMessage.Body = mailMessage.Body.Replace("<<lblNoOfLeaveAvailedMonth>>", "");
                mailMessage.Body = mailMessage.Body.Replace("<<NoOfLeaveAvailedYear>>", "");
                mailMessage.Body = mailMessage.Body.Replace("<<lblNoOfLeaveAvailedYear>>", "");
                DateTime dtmTodaysDate = Convert.ToDateTime(DateTime.Now.ToShortDateString());
                mailMessage.Body = mailMessage.Body.Replace("<<ApplicationDate>>", dtmTodaysDate.ToString(Session["MDateFormat"].ToString()));
                mailMessage.Body = mailMessage.Body.Replace("<<lblApplicationDate>>", rm.GetString("email_LeaveApplicationDate", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<NumberDaysApplied>>", Convert.ToString(NumberOfDaysApplied));
                mailMessage.Body = mailMessage.Body.Replace("<<lblNumberDaysApplied>>", rm.GetString("email_NumberOfDaysApplied", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<lblLeaveDate>>", rm.GetString("email_LeaveDate", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<FromDate>>", FromDate);
                mailMessage.Body = mailMessage.Body.Replace("<<lblFromDate>>", rm.GetString("email_FromDate", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<ToDate>>", ToDate);
                mailMessage.Body = mailMessage.Body.Replace("<<lblToDate>>", rm.GetString("email_ToDate", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<lblSession>>", rm.GetString("email_Session", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<FromSession>>", "First Half");
                mailMessage.Body = mailMessage.Body.Replace("<<lblFromSession>>", rm.GetString("email_FromDate", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<ToSession>>", "Second Half");
                mailMessage.Body = mailMessage.Body.Replace("<<lblToSession>>", rm.GetString("email_ToDate", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<lblStatus>>", rm.GetString("email_Status", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<Status>>", status);
                mailMessage.Body = mailMessage.Body.Replace("<<Reason>>", txtReasonForCancel.Text.Replace("'", "''"));
                mailMessage.Body = mailMessage.Body.Replace("<<lblReason>>", "Reason for Cancellation");
                mailMessage.Body = mailMessage.Body.Replace("<<divMailThread>>", strHtmlLeaveDetails);
                mailMessage.Body = mailMessage.Body.Replace("<<LinkData>>", "");
                objClassCommon.SendMail(mailMessage);
            }
            catch
            {
                blnCheckEmail = false;
            }
        }
    }
    protected void btnModify_Click(object sender, EventArgs e)
    {
        DataSet dsEmailIdOfReportingTo = objPermissionEventData.SelectMailIdOfReportingTo(Convert.ToInt32(ViewState["iEmployeeID"]));
        DataSet ds_EmailIdOfSanctionAuthority = objPermissionEventData.SelectMailIdOfSanctionAuthority(Convert.ToInt32(ViewState["iEmployeeID"]));
        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;
                    }
                }
            }
        }
        //TODO: Karthikeyan
        //blnAllowModify = true;
        if (ViewState["StatusOfApplication"].ToString() == "Pending" || ViewState["StatusOfApplication"].ToString() == "Resend")
        {
            Response.Redirect("TA_UI_Transactions_MultipleLeaveApplicationModify.aspx?leaveApplicationId=" + ViewState["vsLeaveApplicationId"].ToString());
        }
        else if (blnAllowModify == true)
        {
            Response.Redirect("TA_UI_Transactions_MultipleLeaveApplicationModify.aspx?leaveApplicationId=" + ViewState["vsLeaveApplicationId"].ToString());
        }
        else
        {
            ControlCreation();
            base.Message("Cannot modify this Leave");
        }
    }
    protected void grv_LeaveApplication_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            Label lblLeaveFrom = (Label)e.Row.Cells[0].FindControl("lblLeaveFrom");
            lblLeaveFrom.Text = (Convert.ToDateTime(lblLeaveFrom.Text)).ToString(Session["MDateFormat"].ToString());
            Label lblLeaveTo = (Label)e.Row.Cells[0].FindControl("lblLeaveTo");
            lblLeaveTo.Text = (Convert.ToDateTime(lblLeaveTo.Text)).ToString(Session["MDateFormat"].ToString());
             LinkButton lbCancelButton = e.Row.Cells[0].FindControl("lbCancel") as LinkButton;
             lbCancelButton.Text = "&nbsp;&nbsp;Cancel Leave";
            if (Convert.ToString(ViewState["StatusOfApplication"]).Trim() == "Rejected")
            {
                lbCancelButton.OnClientClick = "";
                lbCancelButton.Enabled = false;
                btn_Delete.Enabled = false;
                btn_Delete.OnClientClick = null;
            }
            if (Convert.ToInt32(ViewState["auEmpId"]) != Convert.ToInt32(Session["EmpAutoID"]) && Session["UserGroupName"].ToString() != "SuperAdmin" && Session["HasSpecialRights"].ToString() != "True")
            {
                lbCancelButton.OnClientClick = "";
                lbCancelButton.Enabled = false;
                btn_Delete.Enabled = false;
                btn_Delete.OnClientClick = null;
            }
            string strTodaysDate = DateTime.Now.ToString(Session["MDateFormat"].ToString());
            //To enable and disable cancel link button according to user. (included by sashma)
            //Changin g the datetime with common format by Manjula.P on 13-May-2014 Bug : Code 0023974 
            string strLeaveFrom = objClassCommon.DateConvertion(gstrDateFormat, lblLeaveFrom.Text);
            strTodaysDate = objClassCommon.DateConvertion(gstrDateFormat, strTodaysDate);
            string strLeaveTo = objClassCommon.DateConvertion(gstrDateFormat, lblLeaveTo.Text);
            if ((Convert.ToDateTime(strLeaveFrom) < Convert.ToDateTime(strTodaysDate)) || (Convert.ToDateTime(strLeaveTo) < Convert.ToDateTime(strTodaysDate)))
            //if ((Convert.ToDateTime(lblLeaveFrom.Text) < Convert.ToDateTime(strTodaysDate)) || (Convert.ToDateTime(lblLeaveTo.Text) < Convert.ToDateTime(strTodaysDate)))
            {
                if (Session["UserGroupName"].ToString() == "SuperAdmin" || Session["HasSpecialRights"].ToString() == "True")
                {
                    lbCancelButton.Enabled = true;
                    btn_Delete.Enabled = true;
                }
                else
                {
                    lbCancelButton.OnClientClick = "javascript:alert('Cannot cancel this leave')";
                    lbCancelButton.OnClientClick = "";
                    lbCancelButton.Enabled = false;
                    btn_Delete.Enabled = false;
                    btn_Delete.OnClientClick = null;
                }
            }
        }
    }
    protected void grv_LeaveApplication_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Cancel")
        {
            string[] strCommandArgsCancel = e.CommandArgument.ToString().Split(new char[] { ',' });
            string strLeaveID = strCommandArgsCancel[0].ToString();//it gives leave ID.
            string strLeaveFromDate = strCommandArgsCancel[1].ToString();//it gives leave from date.
            string strLeaveToDate = strCommandArgsCancel[2].ToString();//it gives leave to date.
            string strSessionFrom = strCommandArgsCancel[3].ToString();//it gives session from.
            string strSessionTo = strCommandArgsCancel[4].ToString();//it gives session to.
            DataSet dsIsDeleteCount = new DataSet();
            //Delete Leave Application
            dsIsDeleteCount = objLeaveApplicationEventData.Delete_LeaveApplication(Convert.ToInt32(strLeaveID), Convert.ToInt32(Session["EmpAutoId"]), Convert.ToDateTime(strLeaveFromDate), Convert.ToDateTime(strLeaveToDate), strSessionFrom, strSessionTo, "I");
            if (ViewState["StatusOfApplication"].ToString() == "Approved")
            {
                if (Convert.ToInt32(ConfigurationManager.AppSettings.Get("isRequiredEmail")) == 1)
                {
                    SendMail(Convert.ToInt32(ViewState["vsLeaveApplicationId"]), 1, 1, 1, "Reporting Mail", "Sanction Mail");
                }
            }
            else
            {
                if (Convert.ToInt32(ConfigurationManager.AppSettings.Get("isRequiredEmail")) == 1)
                {
                    SendMail(Convert.ToInt32(ViewState["vsLeaveApplicationId"]), 1, 1, 1, "Reporting Mail", null);
                }
            }
            if (dsIsDeleteCount.Tables[0].Rows[0]["LeaveCount"].ToString().Equals("0"))
            {
                // Response.Redirect("TA_UI_Transactions_LeaveApplication.aspx");
                string strScript = "";
                strScript = strScript + "<script language='javascript'>";
                strScript = strScript + "alert('Leave Application Cancelled');";
                strScript = strScript + "location.replace('TA_UI_Transactions_LeaveApplication.aspx');";
                strScript = strScript + "</script>";
                Page.RegisterStartupScript("AlertLDel65507866", strScript);
            }
        }
    }
    protected void grv_LeaveApplication_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        grv_LeaveApplication.EditIndex = -1;
        txtReasonForCancel.Text = string.Empty;
        ViewDetails();
    }
    #region Split Mail ids
    private string[] SplitCCTo(string CCTo)
    {
        string[] strArrEmailAddressForCC;
        strArrEmailAddressForCC = CCTo.Split(';');
        return (strArrEmailAddressForCC);
    }
    #endregion
    public string buildPage(string strPageTitle, DataTable myDT)
    {
        StringBuilder sb = new StringBuilder();
        //HTML header
        sb.Append("<html>");
        sb.Append("<head>");
        sb.Append("<title>");
        sb.Append(strPageTitle);
        sb.Append("</title>");
        sb.Append("<style type='text/css'>");
        sb.Append(".Header {color: #FFFFFF; font-family: Arial;font-size: x-small;font-weight: bold;}");
        sb.Append(".rows {font-family: Arial; font-size: x-small;background-color:#FFE3B9}");
        sb.Append(".rowsNew {font-family: Arial; font-size: x-small;background-color:#FFEED5}");
        sb.Append("</style>");
        sb.Append("</head>");
        sb.Append("<body>");
        sb.Append("<table border='1' cellpadding='2' style='border-collapse: collapse' bordercolor='#666666' width='700'>");
        sb.Append("  <tr bgcolor='#003466' >");
        //Table header       
        foreach (DataColumn Col in myDT.Columns)
        {
            sb.Append("<td><span class='Header'>" + Col.ColumnName.ToString() + "</span></td>");
        }
        sb.Append("  </tr>");
        //add rows to the table for the length of the dataset
        int intWidth = 0;
        int intIncrement = 0;
        foreach (DataRow Row in myDT.Rows)
        {
            //intWidth = 0;
            if (intIncrement % 2 == 0)
            {
                sb.Append("<tr>");
            }
            else
            {
                sb.Append("<tr>");
            }
            foreach (DataColumn Col in myDT.Columns)
            {
                //if (intWidth == 0)
                //{
                sb.Append("<td><font face='Arial' size='2'>" + Row[Col.ColumnName].ToString() + "</font></td>");
                //intWidth = 1;
                //}
                //else if (intWidth != 0)
                //{
                //    sb.Append("<td width='70%'>" + Row[Col.ColumnName].ToString() + "</td>");
                //    intWidth = 0;
                //}
            }
            sb.Append("  </tr>");
            intIncrement = intIncrement + 1;
        }
        //Close the html string
        sb.Append("</table>");
        sb.Append("</body>");
        sb.Append("</html>");
        return sb.ToString();
    }
}
