using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Resources;
using System.Globalization;
using System.Threading;
using System.Net.Mail;
using System.Net;
using DevExpress.Web;
using System.Text;
/*
 * Modified By      :   Manjula.P
 * Modified On      :   28-Sep-2013
 * Descriptinos     :   To resolve the bug from mantis : 	0019022
 * */
public partial class Transactions_TA_UI_Transactions_LeaveSanctionViewForBulkApproval_Angler : Base.BasePage
{
    #region Variable Declaration
    string source_Language;
    ResourceManager rm;
    CultureInfo ci;
    Cls_CheckUser objCheckUser = new Cls_CheckUser();
    DataSet ds_Checkuser = new DataSet();
    LeaveApplicationEventData_Angler objLeaveApplicationEventData = new LeaveApplicationEventData_Angler();
    YearSettingsEventData objYearSettingsEventData = new YearSettingsEventData();
    cls_Common objcls_Common = new cls_Common();
    Rpt_Common rptcommon = new Rpt_Common();
    DataTable dtLeaveTransactionView = new DataTable();
    DataSet dsYearSetting = new DataSet();
    int vmonthValue;
    string startDate;
    bool checkRecordExists;
    string endDate, gstrDateFormat, LevelId, Status, From_Date, To_Date, StartMonth, EndMonth, StartYear, EndYear;
    string strSwipeCardNo = string.Empty;
    string strEmployeeName = string.Empty;
    string strEmployeeCodeId = string.Empty;
    PermissionEventData objPermissionEventData = new PermissionEventData();
    DataTable dtSanctionView = new DataTable();
    DataSet ds_EmailIdOfSanctionAuthority = new DataSet();
    DataSet dsEmailIdOfReportingTo = new DataSet();
    DataSet dsRecordsCount = new DataSet();
    int intCount;
    int LeaveApplication_Id, Employee_Id, LeaveTypeId;
    string Remarks, strEmailIdSanctionAuthority, strEmailIdReportingTo, EmployeeName, EmployeeEamilId, strLeaveApplicationDate, strNoOfDays, Leave_FromDate, Leave_ToDate;
    double NumberOfDays;
    bool checkEmail = true;
    string NotSendedEmployeeCodeId = "";
    DataSet ds_ReportingToSanctionAuthorityList = new DataSet();
    //Added by Manjula.P on 28-Sep-2013 for displaying message like employee code id instead of employee id
    string Employee_Code_Id = string.Empty;
    int intApproval = 0, intAuthorityLevel = 0, intFirstLevelAuthorityId = 0, intSecondLevelAuthorityId = 0;
    CCGroupEventData_Angler objCCGroup = new CCGroupEventData_Angler();
    string strHtml = string.Empty;
    string ChkBoxIDs = string.Empty;
    string[] chkBoxIDs;
    LeaveEventData objLeave = new LeaveEventData();
    DataTable dtLeaveavailedinMonth = new DataTable();
    string leaveType = string.Empty, strTypeOfLeave = string.Empty, intimationType = string.Empty;
    string strCrossDate = string.Empty;
    string strLeaveavailedinFirstMonth = string.Empty;
    string strLeaveavailedinSecondMonth = string.Empty;
    string strLeaveavailedinFirstMonthName = string.Empty;
    string strLeaveavailedinSecondMonthName = string.Empty;
    string strMonthValue = string.Empty;
    string strLeaveStatus = string.Empty;
    string strLeaveAvailedYear = string.Empty;
    // DataTable dtLeaveavailedinMonth = new DataTable();
    double dblLeaveAvailedYear;
    int intLoginEmpId = 0;
    string strApprovalCC = string.Empty;
    org_levelsEventData getOrg = new org_levelsEventData();
    DataSet ds_getOrg = new DataSet();
    DataSet ds_LeaveSanctionSettings = new DataSet();
    DataTable dt_LeaveSettings = new DataTable();
    DataTable dt_ApprovalAuthority = new DataTable();
    DataSet dsDepartmentMailIds = new DataSet();
    string levelName = string.Empty;
    string strYearSettingsFromdate, strYearSettingsTodate;
    int gintCompanyId = 0;
    string strHtmlLeaveDetails = string.Empty;
    bool boolChkLeave = true;
    DataSet dsYear = new DataSet();
    int intCommentsBy = 0;
    DataSet dsLeaveConversation = new DataSet();
    int payrollConfig;
    #endregion
    #region PageLoad
    protected override void Page_Load(object sender, EventArgs e)
    {
        // session checking
        base.Page_Load(sender, e);
        ////if Standar Edition set the visibility to false
        //if (Session["Edition"].ToString() == "1")
        //{
        //    Response.Redirect("TransactionLandingPage.aspx");
        //}
        //get the culture info to set the language
        payrollConfig = objcls_Common.CheckPageExistsInLicense(185);
        if (!IsPostBack)
        {
            if (payrollConfig == 0)
            {
                objcls_Common.menu("LeaveTransaction", "248");
            }
            else
            {
                objcls_Common.menu("LeaveTransaction", "260");
            }
            //objcls_Common.menu("LeaveTransaction", "Leave Sanction ");
        }
        source_Language = Session["Session_ActiveLanguage"].ToString();
        rm = new ResourceManager(source_Language, System.Reflection.Assembly.Load("App_GlobalResources"));
        ci = Thread.CurrentThread.CurrentCulture;
        LoadStrings(ci);
        //Set UserRights
        UserRights();
        //To check the user is in SuperAdmin Group
        // Check the dropdownlist are filled or not
        if (Session["levelId"] == string.Empty || Session["levelId"] == null)
        {
            if (Request.QueryString["LevelId"] != null)
            {
                LevelId = Request.QueryString["LevelId"].ToString();
                LevelId = rptcommon.getNodes(Convert.ToInt16(LevelId), Convert.ToString("0"));
            }
            else
            {
                LevelId = "";
            }
            Session["levelId"] = LevelId;
        }
        else
        {
            LevelId = Convert.ToString(Session["levelId"]);
        }
        if (Session["LeaveSanctionStatus"] == string.Empty || Session["LeaveSanctionStatus"] == null)
        {
            if (Request.QueryString["Status"] != null)
            {
                Status = Request.QueryString["Status"].ToString();
            }
            else
            {
                Status = "";
            }
            Session["LeaveSanctionStatus"] = Status;
        }
        else
        {
            Status = Convert.ToString(Session["LeaveSanctionStatus"]);
        }
        if (Session["strSwipeCardNo"] == string.Empty || Session["strSwipeCardNo"] == null)
        {
            if (Request.QueryString["strSwipeCardNo"] != null)
            {
                strSwipeCardNo = Request.QueryString["strSwipeCardNo"].ToString();
            }
            else
            {
                strSwipeCardNo = "";
            }
            Session["strSwipeCardNo"] = strSwipeCardNo;
        }
        else
        {
            strSwipeCardNo = Convert.ToString(Session["strSwipeCardNo"]);
        }
        if (Session["strEmployeeName"] == string.Empty || Session["strEmployeeName"] == null)
        {
            if (Request.QueryString["strEmployeeName"] != null)
            {
                strEmployeeName = Request.QueryString["strEmployeeName"].ToString();
            }
            else
            {
                strEmployeeName = "";
            }
            Session["strEmployeeName"] = strEmployeeName;
        }
        else
        {
            strEmployeeName = Convert.ToString(Session["strEmployeeName"]);
        }
        if (Session["strEmployeeCodeId"] == string.Empty || Session["strEmployeeCodeId"] == null)
        {
            if (Request.QueryString["strEmployeeName"] != null)
            {
                strEmployeeCodeId = Request.QueryString["strEmployeeCodeId"].ToString();
            }
            else
            {
                strEmployeeCodeId = "";
            }
            Session["strEmployeeCodeId"] = strEmployeeCodeId;
        }
        else
        {
            strEmployeeCodeId = Convert.ToString(Session["strEmployeeCodeId"]);
        }
        //Checking and Convert to Date Format MM/dd/yyyy
        gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
        if (Session["LeaveFrom_Date"] == null || Session["LeaveFrom_Date"] == string.Empty)
        {
            if (Request.QueryString["From_Date"] != null)
            {
                From_Date = Request.QueryString["From_Date"].ToString();
            }
            else
            {
                From_Date = "";
            }
            Session["LeaveFrom_Date"] = From_Date;
        }
        else
        {
            From_Date = Convert.ToString(Session["LeaveFrom_Date"]);
        }
        if (Session["LeaveTo_Date"] == null || Session["LeaveTo_Date"] == string.Empty)
        {
            if (Request.QueryString["To_Date"] != null)
            {
                To_Date = Request.QueryString["To_Date"].ToString();
            }
            else
            {
                To_Date = "";
            }
            Session["LeaveTo_Date"] = To_Date;
        }
        else
        {
            To_Date = Convert.ToString(Session["LeaveTo_Date"]);
        }
        if (From_Date != "")
        {
            From_Date = objcls_Common.DateConvertion(gstrDateFormat, From_Date);
        }
        if (To_Date != "")
        {
            To_Date = objcls_Common.DateConvertion(gstrDateFormat, To_Date);
        }
        //Adding by Manjula.P on 26-Apr-2014 for getting year settings start and end date
        dsYear = objcls_Common.GetYearsetting();
        if (dsYear.Tables[0].Rows.Count <= 0)
        {
            string strScript = "";
            strScript = strScript + "<script language='javascript'>";
            strScript = strScript + "alert('" + rm.GetString("Alert_DefineYearSettinginOrganizationSettings", ci) + "');location.replace('../Organization Settings/Organization_YearSetting.aspx')";
            strScript = strScript + "</script>";
            Page.RegisterStartupScript("AlertLeavePolicyYear", strScript);
        }
        else
        {
            strYearSettingsFromdate = dsYear.Tables[0].Rows[0]["FromDate"].ToString();
            strYearSettingsTodate = dsYear.Tables[0].Rows[0]["ToDate"].ToString();
            dsYear.Dispose();
        }
        //**************End here ******************************************************
        dsYearSetting = objYearSettingsEventData.GetActiveYearSettings();
        if (dsYearSetting.Tables[0].Rows.Count <= 0)
        {
            return;
        }
        else
        {
            StartMonth = dsYearSetting.Tables[0].Rows[0]["StartMonth"].ToString();
            StartYear = dsYearSetting.Tables[0].Rows[0]["StartYear"].ToString();
            vmonthValue = MonthValue(StartMonth);
            startDate = vmonthValue.ToString() + "/1/" + StartYear;
            EndMonth = dsYearSetting.Tables[0].Rows[0]["EndMonth"].ToString();
            EndYear = dsYearSetting.Tables[0].Rows[0]["EndYear"].ToString();
            vmonthValue = MonthValue(EndMonth);
            endDate = vmonthValue.ToString() + "/31/" + EndYear;
        }
        if (LevelId == "0")
        {
            LevelId = null;
        }
        if (Status == "-Select Status-")
        {
            Status = null;
        }
        else if (Status == "All")
        {
            Status = "All";
        }
        if (From_Date == "")
        {
            From_Date = startDate;
        }
        if (To_Date == "")
        {
            To_Date = endDate;
        }
        ///Added by Manjula.P on 25-Apr-2014 when the status is in forwarded.
        if (Status == "Forwarded")
        {
            btnForward.Enabled = false;
        }
        //Fill the Leave Sanction Details in datagrid
        bindLeaveSanctionDetails();
        if (!IsPostBack)
        {
            Session["LeaveChecked"] = null;
            //Added by Manjula.P on 25-Apr-2014 for migrating PRODUCT to ANGLER
            dvRemarks.Visible = false;
            divMandatory.Visible = false;
            btnForward.Visible = false;
            btnApprove.Visible = false;
            int EmpID = Convert.ToInt32(Session["EmpAutoID"].ToString());
            DataSet ds = new DataSet();
            DataSet ds1 = new DataSet();
            //if the user login is sanctiona authority then approve button visibleing
            ds = objPermissionEventData.CheckSanctioningPerson(EmpID);
            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                if (ds.Tables[0].Rows[0][0] != DBNull.Value && Convert.ToInt16(ds.Tables[0].Rows[0][0]) > 0)
                {
                    btnApprove.Visible = true;
                    dvRemarks.Visible = true;
                    divMandatory.Visible = true;
                }
                else
                {
                    btnApprove.Visible = false;
                    //if the user login is forward authority then forward button visible.
                    ds1 = objPermissionEventData.CheckReportingPerson(EmpID);
                    if (ds1.Tables[0].Rows[0][0] != DBNull.Value && Convert.ToInt16(ds1.Tables[0].Rows[0][0]) > 0 && Request.QueryString["Status"].ToString() != "Forwarded")
                    {
                        btnForward.Visible = true;
                        dvRemarks.Visible = true;
                        divMandatory.Visible = true;
                    }
                    else
                    {
                        btnForward.Visible = false;
                        gdLeaveSanctionView.Columns[0].Visible = false;
                    }
                }
            }
            if (gdLeaveSanctionView.VisibleRowCount == 0)
            {
                dvRemarks.Visible = false;
                divMandatory.Visible = false;
                btnForward.Visible = false;
                btnApprove.Visible = false;
                gdLeaveSanctionView.Columns[0].Visible = false;
            }
            if (Request.QueryString["Status"].ToString() == "All" || Request.QueryString["Status"].ToString() == "Approved" || Request.QueryString["Status"].ToString() == "Rejected" || Request.QueryString["Status"].ToString() == "Resend" || Request.QueryString["Status"].ToString() == "Reply")
            {
                dvRemarks.Visible = false;
                divMandatory.Visible = false;
                btnForward.Visible = false;
                btnApprove.Visible = false;
                gdLeaveSanctionView.Columns[0].Visible = false;
            }
            if (Request.QueryString["Status"].ToString() != "Pending" && Request.QueryString["Status"].ToString() != "Forwarded")
            {
                dvRemarks.Visible = false;
                divMandatory.Visible = false;
                btnForward.Visible = false;
                btnApprove.Visible = false;
                gdLeaveSanctionView.Columns[0].Visible = false;
            }
            //**************************************************************************
        }
    }
    #endregion
    #region userDefined function
    #region control creation   
    private void ControlCreation()
    {
        //New Data table definition
        DataTable dtReplyResend = new DataTable();
        dtReplyResend.TableName = "dtReplyResend";
        DataColumn dcDate = new DataColumn("Date");
        DataColumn dcCommentsBy = new DataColumn("Comments By");
        DataColumn dcComments = new DataColumn("Comments");
        dtReplyResend.Columns.Add(dcDate);
        dtReplyResend.Columns.Add(dcCommentsBy);
        dtReplyResend.Columns.Add(dcComments);
        DataRow dRowReplyResend;
        // getting leave conversation 
        dsLeaveConversation = objLeaveApplicationEventData.GetLeaveConversation(LeaveApplication_Id);
        if (dsLeaveConversation.Tables[0].Rows.Count > 0)
        {
            Table leaveConversation = new Table();
            leaveConversation.BorderWidth = 1;
            leaveConversation.BorderColor = System.Drawing.Color.White;
            leaveConversation.CellPadding = 5;
            leaveConversation.CellSpacing = 0;
            leaveConversation.Width = Unit.Pixel(720);
            leaveConversation.CssClass = "td";
            leaveConversation.Attributes.Add("border", "1");
            TableHeaderRow leaveConversationHr = new TableHeaderRow();
            TableHeaderCell leaveConversationHeading3 = new TableHeaderCell();
            leaveConversationHeading3.Text = rm.GetString("TerminalDataType_Date_And_Time", ci);
            leaveConversationHeading3.Width = 120;
            leaveConversationHeading3.HorizontalAlign = HorizontalAlign.Left;
            leaveConversationHr.Cells.Add(leaveConversationHeading3);
            TableHeaderCell leaveConversationHeading1 = new TableHeaderCell();
            leaveConversationHeading1.Width = 100;
            leaveConversationHeading1.Text = rm.GetString("leaveConversationHeading1", ci);
            leaveConversationHeading1.HorizontalAlign = HorizontalAlign.Left;
            leaveConversationHr.Cells.Add(leaveConversationHeading1);
            TableHeaderCell leaveConversationHeading2 = new TableHeaderCell();
            leaveConversationHeading2.Text = rm.GetString("leaveConversationHeading2", ci);
            leaveConversationHeading2.Width = 500;
            leaveConversationHeading2.HorizontalAlign = HorizontalAlign.Left;
            leaveConversationHr.Cells.Add(leaveConversationHeading2);
            leaveConversation.Rows.Add(leaveConversationHr);
            if (dsLeaveConversation != null && dsLeaveConversation.Tables.Count > 0)
            {
                if (dsLeaveConversation.Tables[0].Rows.Count > 0)
                {
                    int rowIndex = 0;
                    foreach (DataRow drLeaveConversation in dsLeaveConversation.Tables[0].Rows)
                    {
                        dRowReplyResend = dtReplyResend.NewRow();
                        TableRow trLeaveConversation = new TableRow();
                        TableCell tcLeaveConversationRepliedOn = new TableCell();
                        Label lblLeaveConversationRepliedOn = new Label();
                        tcLeaveConversationRepliedOn.BorderWidth = 1;
                        tcLeaveConversationRepliedOn.BorderColor = System.Drawing.Color.White;
                        //tcLeaveConversationRepliedOn.Width =100;
                        lblLeaveConversationRepliedOn.ID = "lblLeaveConversationRepliedOn" + rowIndex;
                        lblLeaveConversationRepliedOn.Text = Convert.ToDateTime(drLeaveConversation["TimeStamp"]).ToString(Session["MDateFormat"].ToString()) + " " + Convert.ToDateTime(drLeaveConversation["TimeStamp"]).ToString(Session["MTimeFormat"].ToString());
                        dRowReplyResend["Date"] = Convert.ToDateTime(drLeaveConversation["TimeStamp"]).ToString(Session["MDateFormat"].ToString()) + " " + Convert.ToDateTime(drLeaveConversation["TimeStamp"]).ToString(Session["MTimeFormat"].ToString());
                        tcLeaveConversationRepliedOn.Controls.Add(lblLeaveConversationRepliedOn);
                        trLeaveConversation.Cells.Add(tcLeaveConversationRepliedOn);
                        TableCell tcLeaveConversationCommentsBy = new TableCell();
                        Label lblLeaveConversationCommentsBy = new Label();
                        tcLeaveConversationCommentsBy.BorderWidth = 1;
                        tcLeaveConversationCommentsBy.BorderColor = System.Drawing.Color.White;
                        // tcLeaveConversationCommentsBy.Width =100;
                        lblLeaveConversationCommentsBy.ID = "lblLeaveConversationCommentsBy" + rowIndex;
                        if (drLeaveConversation["CommentsBy"].ToString() == "0")
                        {
                            //lblLeaveConversationCommentsBy.Text = lbl_EmployeeName.Text;
                            //dRowReplyResend["Comments By"] = lbl_EmployeeName.Text;
                            lblLeaveConversationCommentsBy.Text = objLeaveApplicationEventData.GetEmployeeName(Convert.ToInt32(drLeaveConversation["Emp_Id"].ToString()));
                            dRowReplyResend["Comments By"] = objLeaveApplicationEventData.GetEmployeeName(Convert.ToInt32(drLeaveConversation["Emp_Id"].ToString()));
                        }
                        else if (drLeaveConversation["CommentsBy"].ToString() == "1")
                        {
                            lblLeaveConversationCommentsBy.Text = objLeaveApplicationEventData.GetEmployeeName(Convert.ToInt32(drLeaveConversation["Emp_Id"].ToString()));
                            dRowReplyResend["Comments By"] = objLeaveApplicationEventData.GetEmployeeName(Convert.ToInt32(drLeaveConversation["Emp_Id"].ToString()));
                        }
                        else if (drLeaveConversation["CommentsBy"].ToString() == "2")
                        {
                            lblLeaveConversationCommentsBy.Text = objLeaveApplicationEventData.GetEmployeeName(Convert.ToInt32(drLeaveConversation["Emp_Id"].ToString()));
                            dRowReplyResend["Comments By"] = objLeaveApplicationEventData.GetEmployeeName(Convert.ToInt32(drLeaveConversation["Emp_Id"].ToString()));
                        }
                        else if (drLeaveConversation["CommentsBy"].ToString() == "3")
                        {
                            lblLeaveConversationCommentsBy.Text = objLeaveApplicationEventData.GetEmployeeName(Convert.ToInt32(drLeaveConversation["Emp_Id"].ToString()));
                            dRowReplyResend["Comments By"] = objLeaveApplicationEventData.GetEmployeeName(Convert.ToInt32(drLeaveConversation["Emp_Id"].ToString()));
                        }
                        tcLeaveConversationCommentsBy.Controls.Add(lblLeaveConversationCommentsBy);
                        trLeaveConversation.Cells.Add(tcLeaveConversationCommentsBy);
                        TableCell tcLeaveConversationComments = new TableCell();
                        Label lblLeaveConversationComments = new Label();
                        tcLeaveConversationComments.BorderWidth = 1;
                        tcLeaveConversationComments.BorderColor = System.Drawing.Color.White;
                        //tcLeaveConversationComments.ColumnSpan = 2;
                        // tcLeaveConversationComments.Width = 500;
                        lblLeaveConversationComments.ID = "lblLeaveConversationComments" + rowIndex;
                        lblLeaveConversationComments.Text = drLeaveConversation["Comments"].ToString();
                        dRowReplyResend["Comments"] = drLeaveConversation["Comments"].ToString();
                        tcLeaveConversationComments.Controls.Add(lblLeaveConversationComments);
                        trLeaveConversation.Cells.Add(tcLeaveConversationComments);
                        leaveConversation.Rows.Add(trLeaveConversation);
                        rowIndex += 1;
                        dtReplyResend.Rows.Add(dRowReplyResend);
                    }
                }
            }
            // divLeaveConversation.Controls.Add(leaveConversation);
        }
        else
        {
            // divLeaveConversation.Visible = false;
        }
        if (dsLeaveConversation.Tables[0].Rows.Count > 0)
        {
            strHtml = buildPage("ReplyResend", dtReplyResend);
        }
    }
    #endregion
    #region build page
    public string buildPage(string strPageTitle, DataTable myDT)
    {
        StringBuilder sb = new StringBuilder();
        //HTML header
        sb.Append("<html>");
        sb.Append("<head>");
        sb.Append("<title>");
        sb.Append(strPageTitle);
        sb.Append("</title>");
        sb.Append("<style type='text/css'>");
        sb.Append(".Header {color: #FFFFFF; font-family: Arial;font-size: x-small;font-weight: bold;}");
        sb.Append(".rows {font-family: Arial; font-size: x-small;background-color:#FFE3B9}");
        sb.Append(".rowsNew {font-family: Arial; font-size: x-small;background-color:#FFEED5}");
        sb.Append("</style>");
        sb.Append("</head>");
        sb.Append("<body>");
        sb.Append("<table border='1' cellpadding='2' style='border-collapse: collapse' bordercolor='#666666' width='700'>");
        sb.Append("  <tr bgcolor='#003466'>");
        //Table header       
        foreach (DataColumn Col in myDT.Columns)
        {
            sb.Append("<td><span class='Header'>" + Col.ColumnName.ToString() + "</span></td>");
        }
        sb.Append("  </tr>");
        //add rows to the table for the length of the dataset
        int intWidth = 0;
        int intIncrement = 0;
        foreach (DataRow Row in myDT.Rows)
        {
            intWidth = 0;
            if (intIncrement % 2 == 0)
            {
                sb.Append("  <tr>");
            }
            else
            {
                sb.Append("  <tr>");
            }
            foreach (DataColumn Col in myDT.Columns)
            {
                if (intWidth == 2)
                {
                    sb.Append("<td><font face='Arial' size='2'>" + Row[Col.ColumnName].ToString() + "</font></td>");
                    //intWidth = 1;
                }
                else
                {
                    sb.Append("<td><font face='Arial' size='2'>" + Row[Col.ColumnName].ToString() + "</font></td>");
                    //intWidth = 0;
                }
                intWidth = intWidth + 1;
            }
            sb.Append("  </tr>");
            intIncrement = intIncrement + 1;
        }
        //Close the html string
        sb.Append("</table>");
        sb.Append("</body>");
        sb.Append("</html>");
        return sb.ToString();
    }
    private string[] SplitCCTo(string CCTo)
    {
        string[] strArrEmailAddressForCC;
        strArrEmailAddressForCC = CCTo.Split(';');
        return (strArrEmailAddressForCC);
    }
    #endregion
    #region send mail
    private void SendMail(int FirstLevelAuthorityId, int SecondLevelAuthorityId, string FirstLevelAuthorityEmailId, string SecondLevelAuthorityEmailId, string ApplicantEmailId, string EmployeeCodeId, string EmployeeName, string Status, string Remarks, string LeaveApplicationDate, string NoOfDays, string strLeaveType, string levelName, string ApprovalCC, string IntimationType)
    {
        try
        {
            // Get the Application Root Path
            string strApplicationPath = Request.UrlReferrer.ToString();
            int intLastIndex = strApplicationPath.LastIndexOf('/');
            strApplicationPath = strApplicationPath.Substring(0, (intLastIndex - 1));
            intLastIndex = strApplicationPath.LastIndexOf('/');
            strApplicationPath = strApplicationPath.Substring(0, (intLastIndex + 1));
            string[] strSysName;
            strSysName = strApplicationPath.Split('/');
            string strServerIP = string.Empty;
            //= GetIPAddress();
            strServerIP = System.Configuration.ConfigurationManager.AppSettings["ServerIP"].ToString();
            strApplicationPath = strApplicationPath.Replace(strSysName[2].ToString(), strServerIP);
            MailMessage mailMessage = new MailMessage();
            SmtpClient loSMTPServer = new SmtpClient();
            System.Net.Mime.ContentType loTextType = new System.Net.Mime.ContentType("text/plain");
            System.Net.Mime.ContentType loHTMLType = new System.Net.Mime.ContentType("text/html");
            AlternateView loTextView = null;
            AlternateView loHTMLView = null;
            string scriptText;
            DataTable dtTableScript = new DataTable();
            string Employee_Code_Id = ViewState["Employee_code_Id"].ToString();
            string ScriptType = string.Empty;
            if (strCrossDate == "Yes")
            {
                ScriptType = "Forwarded CrossDate Leave Application Sanction";
            }
            else
            {
                ScriptType = "Forwarded Leave Application Sanction";
            }
            dtTableScript = objLeaveApplicationEventData.GetEmailScripts(ScriptType);
            scriptText = dtTableScript.Rows[0]["ScriptText"].ToString();
            mailMessage.From = new MailAddress(ConfigurationManager.AppSettings.Get("FromId"));
            // Select the Recipient for To and CC based on the Approval Authority and Status
            int intLoginEmpId = 0;
            string strCCTo = string.Empty;
            // Get the Employee Auto Id who have Logged In from Session
            intLoginEmpId = Convert.ToInt32(Session["EmpAutoId"]);
            if (intLoginEmpId == SecondLevelAuthorityId)
            {
                if (Status == "Pending")
                {
                    mailMessage.From = new MailAddress(SecondLevelAuthorityEmailId);
                    mailMessage.To.Add(new MailAddress(ApplicantEmailId));
                    //strCCTo = SecondLevelAuthorityEmailId;
                    strCCTo = FirstLevelAuthorityEmailId;
                }
                else if (Status == "Rejected")
                {
                    mailMessage.From = new MailAddress(SecondLevelAuthorityEmailId);
                    mailMessage.To.Add(new MailAddress(ApplicantEmailId));
                    //strCCTo = SecondLevelAuthorityEmailId + ";" + FirstLevelAuthorityEmailId;
                    strCCTo = FirstLevelAuthorityEmailId;
                }
                else if (Status == "Approved")
                {
                    mailMessage.From = new MailAddress(SecondLevelAuthorityEmailId);
                    mailMessage.To.Add(new MailAddress(ApplicantEmailId));
                    //strCCTo = SecondLevelAuthorityEmailId + ";" + FirstLevelAuthorityEmailId;
                    strCCTo = FirstLevelAuthorityEmailId;
                }
                else if (Status == "Resend")
                {
                    mailMessage.From = new MailAddress(SecondLevelAuthorityEmailId);
                    mailMessage.To.Add(new MailAddress(ApplicantEmailId));
                    //strCCTo = SecondLevelAuthorityEmailId + ";" + FirstLevelAuthorityEmailId;
                    strCCTo = FirstLevelAuthorityEmailId;
                }
                else if (Status == "Forwarded")
                {
                    mailMessage.From = new MailAddress(SecondLevelAuthorityEmailId);
                    mailMessage.To.Add(new MailAddress(ApplicantEmailId));
                    strCCTo = FirstLevelAuthorityEmailId;
                }
                else
                {
                    // Nothing
                }
            }
            else if (intLoginEmpId == FirstLevelAuthorityId)
            {
                if (Status == "Forwarded")
                {
                    mailMessage.From = new MailAddress(FirstLevelAuthorityEmailId);
                    mailMessage.To.Add(new MailAddress(SecondLevelAuthorityEmailId));
                    strCCTo = ApplicantEmailId;
                }
                else if (Status == "Resend")
                {
                    mailMessage.From = new MailAddress(FirstLevelAuthorityEmailId);
                    mailMessage.To.Add(new MailAddress(ApplicantEmailId));
                    //strCCTo = SecondLevelAuthorityEmailId + ";" + FirstLevelAuthorityEmailId;
                }
                else if (Status == "Rejected")
                {
                    mailMessage.From = new MailAddress(FirstLevelAuthorityEmailId);
                    mailMessage.To.Add(new MailAddress(ApplicantEmailId));
                    //strCCTo = SecondLevelAuthorityEmailId + ";" + FirstLevelAuthorityEmailId;
                }
            }
            else
            {
                if (Status == "Pending" || Status == "Rejected")
                {
                    mailMessage.To.Add(new MailAddress(ApplicantEmailId));
                    strCCTo = FirstLevelAuthorityEmailId;
                }
                else if (Status == "Forwarded")
                {
                    mailMessage.To.Add(new MailAddress(SecondLevelAuthorityEmailId));
                    strCCTo = FirstLevelAuthorityEmailId + ";" + ApplicantEmailId;
                }
                else if (Status == "Approved")
                {
                    mailMessage.To.Add(new MailAddress(ApplicantEmailId));
                    strCCTo = SecondLevelAuthorityEmailId + ";" + FirstLevelAuthorityEmailId;
                }
                else if (Status == "Resend")
                {
                    mailMessage.To.Add(new MailAddress(ApplicantEmailId));
                    strCCTo = SecondLevelAuthorityEmailId + ";" + FirstLevelAuthorityEmailId;
                }
                else
                {
                    // Nothing
                }
                if (Session["loginEmailId"].ToString() != string.Empty || Session["loginEmailId"] != null)
                {
                    mailMessage.From = new MailAddress(Session["loginEmailId"].ToString());
                }
                else
                {
                    mailMessage.From = new MailAddress(ConfigurationManager.AppSettings.Get("FromId"));
                }
            }
            if (Status == "Approved")
            {
                //if (ApprovalCC != string.Empty)
                //{
                //    strCCTo = strCCTo + ";" + ApprovalCC;
                //}
                DataSet dsCCEmailIds = new DataSet();
                dtSanctionView = (DataTable)Session["dtSanctionView"];
                dsCCEmailIds = objCCGroup.GetCCEmailIds(Convert.ToInt16(dtSanctionView.Rows[0]["levelid"].ToString()), Convert.ToInt16(dtSanctionView.Rows[0]["DesignationID"].ToString()), "O");
                if (dsCCEmailIds != null)
                {
                    if (dsCCEmailIds.Tables[0].Rows.Count > 0)
                    {
                        foreach (DataRow drCcEmailId in dsCCEmailIds.Tables[0].Rows)
                        {
                            MailAddressCollection MailAddrCollectionCC = mailMessage.CC;
                            // added by Gopinath.k for Mantis Bug no.24059 & 24098
                            if (drCcEmailId["EmailId"].ToString() != string.Empty)
                            {
                                MailAddress newCC = new MailAddress(drCcEmailId["EmailId"].ToString());
                                MailAddrCollectionCC.Add(newCC);
                            }
                        }
                    }
                }
            }
            #region Code By A.K.T.MOORTHI For Pervious Leave Details
            string strLeaveDetails = string.Empty;
            if (Convert.ToString(Employee_Code_Id) != string.Empty)
            {
                //   DataSet dstLeave = objLeaveApplicationEventData.GetPreviousLeaveDetails(Convert.ToInt16(hdnEmployeeId.Value), string.Empty, "M");
                DataSet dstLeave = objLeaveApplicationEventData.GetPreviousLeaveDetails(Convert.ToInt16(0), Employee_Code_Id, "M");
                strLeaveDetails = dstLeave.Tables.Count > 0 ? dstLeave.Tables[0].Rows.Count > 0 ? Convert.ToString(dstLeave.Tables[0].Rows[0][0]) : string.Empty : string.Empty;
            }
            #endregion
            if (strCCTo != string.Empty)
            {
                string[] strArrEmailAddressForCC;
                strArrEmailAddressForCC = SplitCCTo(strCCTo);
                MailAddressCollection MailAddrCollectionCC = mailMessage.CC;
                for (int iLoop = 0; iLoop < strArrEmailAddressForCC.Length; iLoop++)
                {
                    MailAddress newCC = new MailAddress(strArrEmailAddressForCC[iLoop]);
                    MailAddrCollectionCC.Add(newCC);
                }
            }
            //Send mails by selection Emails
            string strToMails = txtApprovalTO.Text;
            string strCcMails = txtApprovalCC.Text;
            //TO mail Ids
            if (strToMails != string.Empty)
            {
                string[] strArrEmailAddressForTO;
                strArrEmailAddressForTO = SplitCCTo(strToMails);
                MailAddressCollection MailAddrCollectionTO = mailMessage.To;
                for (int iLoop = 0; iLoop < strArrEmailAddressForTO.Length; iLoop++)
                {
                    MailAddress newCC = new MailAddress(strArrEmailAddressForTO[iLoop]);
                    MailAddrCollectionTO.Add(newCC);
                }
            }
            //CC Mails
            if (strCcMails != string.Empty)
            {
                string[] strArrEmailAddressForCC;
                strArrEmailAddressForCC = SplitCCTo(strCcMails);
                MailAddressCollection MailAddrCollectionCC = mailMessage.CC;
                for (int iLoop = 0; iLoop < strArrEmailAddressForCC.Length; iLoop++)
                {
                    MailAddress newCC = new MailAddress(strArrEmailAddressForCC[iLoop]);
                    MailAddrCollectionCC.Add(newCC);
                }
            }
            //check for duplicate mail Ids
            //included by sashma on 20-Oct-2010
            Hashtable htToMails = new Hashtable();
            Hashtable htCCMails = new Hashtable();
            int intToMailCount = 0;
            int intCCMailCount = 0;
            //inserts the TO mailIds in the hashtable
            foreach (MailAddress ToMail in mailMessage.To)
            {
                if (htToMails.ContainsValue(ToMail) == false)
                {
                    htToMails.Add(intToMailCount++, ToMail);
                }
            }
            //inserts the CC mailIds in the hashtable
            foreach (MailAddress CCMail in mailMessage.CC)
            {
                //check whether the mail alredy exists in CC mails.
                if (htCCMails.ContainsValue(CCMail) == false)
                {
                    //check whether the mail alredy exists in TO mails.
                    if (htToMails.ContainsValue(CCMail) == false)
                    {
                        htCCMails.Add(intCCMailCount++, CCMail);
                    }
                }
            }
            mailMessage.To.Clear();
            mailMessage.CC.Clear();
            //Adds the TO mails from the hastable.
            foreach (DictionaryEntry ToMails in htToMails)
            {
                mailMessage.To.Add(ToMails.Value.ToString());
            }
            //Adds the CC mails from the hastable.
            foreach (DictionaryEntry CCMails in htCCMails)
            {
                mailMessage.CC.Add(CCMails.Value.ToString());
            }
            if (IntimationType == "P")
            {
                IntimationType = "Planned";
            }
            mailMessage.Subject = "TimeCheck : " + levelName + " | " + EmployeeName + " - " + Employee_Code_Id + " | Leave  - " + Status + " | " + IntimationType;
            mailMessage.Body = scriptText.Replace("<<lblLeaveApplicationForm>>", rm.GetString("email_LeaveApplicationForm", ci));
            mailMessage.Body = mailMessage.Body.Replace("<<lblEmployeeId>>", rm.GetString("email_EmployeeId", ci));
            mailMessage.Body = mailMessage.Body.Replace("<<EmployeeId>>", Employee_Code_Id);
            mailMessage.Body = mailMessage.Body.Replace("<<lblEmployeeName>>", rm.GetString("email_EmployeeName", ci));
            mailMessage.Body = mailMessage.Body.Replace("<<EmployeeName>>", EmployeeName);
            mailMessage.Body = mailMessage.Body.Replace("<<lblDepartment>>", "Department");
            mailMessage.Body = mailMessage.Body.Replace("<<Department>>", levelName);
            if (strCrossDate != "Yes")
            {
                mailMessage.Body = mailMessage.Body.Replace("<<NoOfLeaveAvailedMonth>>", strLeaveavailedinFirstMonth);
                mailMessage.Body = mailMessage.Body.Replace("<<lblNoOfLeaveAvailedMonth>>", "Leave availed in " + strLeaveavailedinFirstMonthName);
            }
            else
            {
                mailMessage.Body = mailMessage.Body.Replace("<<NoOfLeaveAvailedInFirstMonth>>", strLeaveavailedinFirstMonth);
                mailMessage.Body = mailMessage.Body.Replace("<<lblNoOfLeaveAvailedinFirstMonth>>", "Leave availed in " + strLeaveavailedinFirstMonthName);
                mailMessage.Body = mailMessage.Body.Replace("<<NoOfLeaveAvailedinsecondMonth>>", strLeaveavailedinSecondMonth);
                mailMessage.Body = mailMessage.Body.Replace("<<lblNoOfLeaveAvailedinsecondMonth>>", "Leave availed in " + strLeaveavailedinSecondMonthName);
            }
            //mailMessage.Body = mailMessage.Body.Replace("<<NoOfLeaveAvailedYear>>", strLeaveAvailedYear);
            //mailMessage.Body = mailMessage.Body.Replace("<<lblNoOfLeaveAvailedYear>>", "Leave availed in this Year");
            mailMessage.Body = mailMessage.Body.Replace("<<lblApplicationDate>>", rm.GetString("email_LeaveApplicationDate", ci));
            DateTime dtmTodaysDate = Convert.ToDateTime(LeaveApplicationDate);
            mailMessage.Body = mailMessage.Body.Replace("<<ApplicationDate>>", dtmTodaysDate.ToString(Session["MDateFormat"].ToString()));
            mailMessage.Body = mailMessage.Body.Replace("<<lblLeaveType>>", rm.GetString("lbl_leavetype", ci));
            mailMessage.Body = mailMessage.Body.Replace("<<LeaveType>>", strLeaveType);
            mailMessage.Body = mailMessage.Body.Replace("<<lblLeaveDate>>", rm.GetString("email_LeaveDate", ci));
            mailMessage.Body = mailMessage.Body.Replace("<<lblFromDate>>", rm.GetString("email_FromDate", ci));
            //mailMessage.Body = mailMessage.Body.Replace("<<FromDate>>", lblFromDate.Text);
            mailMessage.Body = mailMessage.Body.Replace("<<lblToDate>>", rm.GetString("email_ToDate", ci));
            //mailMessage.Body = mailMessage.Body.Replace("<<ToDate>>", lblToDate.Text);
            mailMessage.Body = mailMessage.Body.Replace("<<lblSession>>", rm.GetString("email_Session", ci));
            //mailMessage.Body = mailMessage.Body.Replace("<<FromSession>>", lblSessionFrom.Text);
            mailMessage.Body = mailMessage.Body.Replace("<<lblFromSession>>", rm.GetString("email_FromDate", ci));
            //mailMessage.Body = mailMessage.Body.Replace("<<ToSession>>", lblSessionTo.Text);
            mailMessage.Body = mailMessage.Body.Replace("<<lblToSession>>", rm.GetString("email_ToDate", ci));
            mailMessage.Body = mailMessage.Body.Replace("<<lblNumberDaysApplied>>", rm.GetString("email_NumberOfDaysApplied", ci));
            mailMessage.Body = mailMessage.Body.Replace("<<NumberDaysApplied>>", NoOfDays);
            mailMessage.Body = mailMessage.Body.Replace("<<lblStatus>>", rm.GetString("email_Status", ci));
            mailMessage.Body = mailMessage.Body.Replace("<<Status>>", Status);
            mailMessage.Body = mailMessage.Body.Replace("<<lblReason>>", "Reason");
            mailMessage.Body = mailMessage.Body.Replace("<<Reason>>", ViewState["vwReason"].ToString());
            //mailMessage.Body = mailMessage.Body.Replace("<<lblRemarks>>", rm.GetString("email_Remarks", ci));
            //mailMessage.Body = mailMessage.Body.Replace("<<Remarks>>", txtRemarks.Text);
            mailMessage.Body = mailMessage.Body.Replace("<<divMailLeaveThread>>", strHtmlLeaveDetails);
            mailMessage.Body = mailMessage.Body.Replace("<<divLeaveThread>>", strLeaveDetails);
            //mailMessage.Body = mailMessage.Body.Replace("<<divMailThread>>", strHtml.Replace("width='70%'", " ").Replace("width='30%'", " ").Replace("<td><span class='Header'>Comments</span></td>","<td style='width:40%'><span class='Header'>Comments</span></td>"));
            mailMessage.Body = mailMessage.Body.Replace("<<divMailThread>>", strHtml);
            if (Status == "Forwarded")
            {
                string LevelId = "1";
                //mailMessage.Body = mailMessage.Body.Replace("<<LinkData>>", strServerIP + "Index.aspx?LeaveApplication_Id=" + LeaveApplication_Id.ToString() + "&LevelId=" + LevelId + "&ApprovalType=Leave");
                mailMessage.Body = mailMessage.Body.Replace("<<LinkData>>", strServerIP + "Transactions/TA_UI_Transactions_LeaveSanctionModify_Angler.aspx?LeaveApplication_Id=" + LeaveApplication_Id.ToString() + "&LevelId=" + LevelId + "&ApprovalType=Leave&Status=All&From_Date=&To_Date=&strSwipeCardNo=&strEmployeeName=&strEmployeeCodeId=&Angler=1");
            }
            else
            {
                //string strReplaceText = "<font face='Arial' size='2'><a href='<<LinkData>>'>Click here for approval</a></font>";
                string strReplaceText = "<font face=\"Arial\" size=\"2\"><a href=\"<<LinkData>>\">Click here for approval</a></font>";
                mailMessage.Body = mailMessage.Body.Replace(strReplaceText, string.Empty);
            }
            objcls_Common.SendMail(mailMessage);
        }
        catch
        {
            checkEmail = false;
        }
    }
    #endregion
    public void SortGrid(string SortColumn, string SortOrder)
    {
        DataTable dtSrch = new DataTable();
        DataView dvSearch = new DataView();
        dtSrch = (DataTable)ViewState["DataLeaveSanction"];
        dvSearch.Table = dtSrch;
        dvSearch.Sort = SortColumn + " " + SortOrder;
        gdLeaveSanctionView.DataSource = dvSearch;
        gdLeaveSanctionView.DataBind();
    }
    public void GetEmptyText(object sender, EventArgs e)
    {
        Label lblNoRecords = (Label)sender;
        lblNoRecords.Text = rm.GetString("Alert_Norecordsfound", ci);
    }
    private void LoadStrings(CultureInfo ci)
    {
        lbl_Header.Text = rm.GetString("Menu_Transactions_LeaveSanction", ci);
        btnBack.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Back", ci);
        gdLeaveSanctionView.Columns[1].Caption = rm.GetString("email_EmployeeName", ci);
        gdLeaveSanctionView.Columns[2].Caption = rm.GetString("LeaveApplication_LeaveApplicationDate", ci);
        gdLeaveSanctionView.Columns[3].Caption = rm.GetString("Report_Duration", ci);
        gdLeaveSanctionView.Columns[4].Caption = rm.GetString("Type_Of_Leave", ci);
        gdLeaveSanctionView.Columns[4].CellStyle.ForeColor = System.Drawing.ColorTranslator.FromHtml("#5D5D5D");
        gdLeaveSanctionView.Columns[5].Caption = rm.GetString("email_Status", ci);
        btnSave.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Save", ci);
        //Added by Manjula.P on 25-Apr-2014 for getting forward and approve status buttons.
        btnForward.Text = "&nbsp;&nbsp;" + rm.GetString("Sanction_Forward", ci);
        btnApprove.Text = "&nbsp;&nbsp;" + rm.GetString("Sanction_Approve", ci);
    }
    public int MonthValue(string monthName)
    {
        if (monthName == "January")
            return 1;
        else if (monthName == "February")
            return 2;
        else if (monthName == "March")
            return 3;
        else if (monthName == "April")
            return 4;
        else if (monthName == "May")
            return 5;
        else if (monthName == "June")
            return 6;
        else if (monthName == "July")
            return 7;
        else if (monthName == "August")
            return 8;
        else if (monthName == "September")
            return 9;
        else if (monthName == "October")
            return 10;
        else if (monthName == "November")
            return 11;
        else if (monthName == "December")
            return 12;
        else
            return 0;
    }
    private void UserRights()
    {
        ds_Checkuser = objCheckUser.checkRights(260, Convert.ToInt32(Session["userGroup_Id"]), "viewPrv");
        if (ds_Checkuser.Tables[0].Rows.Count == 0)
        {
            Response.Redirect("TransactionLandingPage.aspx");
        }
        else
        {
            //   
        }
    }
    public void bindLeaveSanctionDetails()
    {
        //To check the user is in SuperAdmin Group
        //DataSet dsEmployeeGroup = new DataSet();
        //dsEmployeeGroup = objLeaveApplicationEventData.GetEmployeeGroupName(Convert.ToInt32(Session["EmpAutoId"]));
        if (Session["UserGroupName"].ToString() == "SuperAdmin" || Session["HasSpecialRights"].ToString() == "True")
        {
            dtLeaveTransactionView = objLeaveApplicationEventData.GetLeaveSanctionDetailsForSuperAdmin(LevelId, Session["LeaveSanctionStatus"].ToString(), From_Date, To_Date, strSwipeCardNo, strEmployeeName, strEmployeeCodeId, Session["UserGroupName"].ToString(), Convert.ToInt16(LevelId));
            gdLeaveSanctionView.DataSource = dtLeaveTransactionView;
            ViewState["DataLeaveSanction"] = dtLeaveTransactionView;
            Session["TotalLeaveApplication_Id"] = dtLeaveTransactionView.Rows.Count;
            gdLeaveSanctionView.DataBind();
            if (dtLeaveTransactionView.Rows.Count == 0)
            {
                checkRecordExists = false;
            }
        }
        else
        {
            // Modified the datetime format conversion due to Bug no.24001
            dtLeaveTransactionView = objLeaveApplicationEventData.GetLeaveSanctionDetails(Convert.ToInt32(Session["EmpAutoId"]), Convert.ToString(LevelId), Convert.ToString(Session["LeaveSanctionStatus"]), From_Date, To_Date, strSwipeCardNo, strEmployeeName, strEmployeeCodeId, Convert.ToString(Session["UserGroupName"]), Convert.ToInt32(LevelId));
            gdLeaveSanctionView.DataSource = dtLeaveTransactionView;
            ViewState["DataLeaveSanction"] = dtLeaveTransactionView;
            Session["TotalLeaveApplication_Id"] = dtLeaveTransactionView.Rows.Count;
            gdLeaveSanctionView.DataBind();
            if (dtLeaveTransactionView.Rows.Count == 0)
            {
                checkRecordExists = false;
            }
        }
        //Added by Manjula.P on 26-Apr-2014 for getting leave sanctions details in sessinos used for forwarding and approving
        Session["vSLeaveDetails"] = (DataTable)gdLeaveSanctionView.DataSource;
        //if (checkRecordExists == true)
        //{
        //    CheckBox chkSelect = new CheckBox();
        //    chkSelect = (CheckBox)gdLeaveSanctionView.HeaderRow.Cells[0].FindControl("checkall");
        //    if (Session["SelectAllStatus"] != string.Empty && Session["SelectAllStatus"] != null)
        //    {
        //        chkSelect.Checked = Convert.ToBoolean(Session["SelectAllStatus"].ToString());
        //    }
        //}
        //if (dtLeaveTransactionView.Rows.Count == 0)
        //{
        //    clearAllSession();
        //    btnSave.Enabled = false;
        //    //string strMsg;
        //    //strMsg = "<script language='javascript'>";
        //    //strMsg = strMsg + "alert('" + rm.GetString("Alert_Thereisnorecord", ci) + "'); location.href='TA_UI_Transactions_LeaveSanction.aspx'";
        //    //strMsg = strMsg + "</script>";
        //    //Page.RegisterStartupScript("Display Message", strMsg);
        //    //return;
        //}
    }
    public void clearAllSession()
    {
        Session["levelId"] = string.Empty;
        Session["LeaveSanctionStatus"] = string.Empty;
        Session["strSwipeCardNo"] = string.Empty;
        Session["strEmployeeName"] = string.Empty;
        Session["strEmployeeCodeId"] = string.Empty;
        Session["LeaveFrom_Date "] = null;
        Session["LeaveTo_Date"] = null;
    }
    private void SanctionViewDetails()
    {
        //dtSanctionView = objLeaveApplicationEventData.GetLeaveApplicationByLeaveApplicationId(LeaveApplication_Id);
        ViewState["Employee_code_Id"] = dtSanctionView.Rows[0]["Employee_code_Id"].ToString();
        ViewState["StatusOnLoad"] = dtSanctionView.Rows[0]["Status"].ToString();
        ViewState["StatusBorrow"] = dtSanctionView.Rows[0]["IsBorrow"].ToString();
    }
    private void SanctionViewDetails(int LeaveApplication_Id)
    {
        dtSanctionView = objLeaveApplicationEventData.GetLeaveApplicationByLeaveApplicationId(LeaveApplication_Id);
        ViewState["Employee_code_Id"] = dtSanctionView.Rows[0]["Employee_code_Id"].ToString();
        ViewState["StatusOnLoad"] = dtSanctionView.Rows[0]["Status"].ToString();
        ViewState["StatusBorrow"] = dtSanctionView.Rows[0]["IsBorrow"].ToString();
        ViewState["LeaveType"] = dtSanctionView.Rows[0]["LeaveType"].ToString();
    }
    private void SendMailToApplicant(string EmployeeEamilId, string strEmailIdReportingTo, string strEmailIdSanctionAuthority, string EmployeeName, string Status, string Remarks, string LeaveApplicationDate, string NoOfDays, string strLeaveType, string FromDate, string Todate, string FromSession, string ToSession)
    {
        MailMessage mailMessage = new MailMessage();
        SmtpClient loSMTPServer = new SmtpClient();
        System.Net.Mime.ContentType loTextType = new System.Net.Mime.ContentType("text/plain");
        System.Net.Mime.ContentType loHTMLType = new System.Net.Mime.ContentType("text/html");
        AlternateView loTextView = null;
        AlternateView loHTMLView = null;
        string scriptText;
        DataTable dtTableScript = new DataTable();
        string strFromEmailId = string.Empty;
        try
        {
            if (strLeaveType == "Restricted Holiday")
            {
                strLeaveType = rm.GetString("Holiday_RestrictedHoliday", ci);
            }
            else if (strLeaveType == "Comp Off")
            {
                strLeaveType = rm.GetString("Caption_CompOff", ci);
            }
            else if (strLeaveType.Contains("LOP"))
            {
                strLeaveType = strLeaveType.Replace("LOP", rm.GetString("lbl_LOP", ci));
            }
            else if (strLeaveType == "ESI")
            {
                strLeaveType = rm.GetString("Caption_ESI", ci);
            }
            else if (strLeaveType.Contains("Leave"))
            {
                strLeaveType = strLeaveType.Replace("Leave", rm.GetString("LeaveApplication_Leave", ci));
            }
            string ScriptType = "Leave Application Sanction By Reporting to Person";
            dtTableScript = objLeaveApplicationEventData.GetEmailScripts(ScriptType);
            scriptText = dtTableScript.Rows[0]["ScriptText"].ToString();
            string Employee_Code_Id = ViewState["Employee_code_Id"].ToString();
            if (Session["loginEmailId"] != null && Session["loginEmailId"].ToString() != string.Empty)
            {
                mailMessage.From = new MailAddress(Convert.ToString(Session["loginEmailId"]));
                strFromEmailId = Convert.ToString(Session["loginEmailId"]);
            }
            else
            {
                mailMessage.From = new MailAddress(ConfigurationManager.AppSettings.Get("FromId"));
                strFromEmailId = Convert.ToString(ConfigurationManager.AppSettings.Get("FromId"));
            }
            if (Session["loginEmailId"] != null && Session["loginEmailId"].ToString() != string.Empty)
            {
                if (strEmailIdSanctionAuthority != strEmailIdReportingTo)
                {
                    if (Status != "Forwarded")
                    {
                        if (Session["loginEmailId"].ToString() == strEmailIdSanctionAuthority)
                        {
                            if (EmployeeEamilId != string.Empty)
                            {
                                mailMessage.To.Add(new MailAddress(EmployeeEamilId));
                            }
                            if (strEmailIdReportingTo != string.Empty)
                            {
                                mailMessage.CC.Add(new MailAddress(strEmailIdReportingTo));
                            }
                        }
                        if (Session["loginEmailId"].ToString() == strEmailIdReportingTo)
                        {
                            if (EmployeeEamilId != string.Empty)
                            {
                                mailMessage.To.Add(new MailAddress(EmployeeEamilId));
                            }
                        }
                    }
                }
                else
                {
                    if (Status != "Forwarded")
                    {
                        if (EmployeeEamilId != string.Empty)
                        {
                            mailMessage.To.Add(new MailAddress(EmployeeEamilId));
                        }
                    }
                }
            }
            else
            {
                if (Status != "Forwarded")
                {
                    if (EmployeeEamilId != string.Empty)
                    {
                        mailMessage.To.Add(new MailAddress(EmployeeEamilId));
                    }
                }
            }
            //if (Status == "Approved")
            //{
            Status = rm.GetString("btn_Approved", ci);
            //}
            //else if (Status == "Forwarded")
            //{
            //    Status = rm.GetString("btn_Forwarded", ci);
            //}
            //else if (Status == "Pending")
            //{
            //    Status = rm.GetString("btn_Pending", ci);
            //}
            //else if (Status == "Rejected")
            //{
            //    Status = rm.GetString("btn_Reject", ci);
            //}
            mailMessage.Subject = rm.GetString("email_YourLeaveApplicationFor", ci) + " - " + " | " + Status;
            //+ lblFromDate.Text + " - " + lblToDate.Text +
            mailMessage.Body = scriptText.Replace("<<lblLeaveApplicationForm>>", rm.GetString("email_LeaveApplicationForm", ci));
            mailMessage.Body = mailMessage.Body.Replace("<<lblEmployeeId>>", rm.GetString("email_EmployeeId", ci));
            mailMessage.Body = mailMessage.Body.Replace("<<EmployeeId>>", Employee_Code_Id);
            mailMessage.Body = mailMessage.Body.Replace("<<lblEmployeeName>>", rm.GetString("email_EmployeeName", ci));
            mailMessage.Body = mailMessage.Body.Replace("<<EmployeeName>>", EmployeeName);
            mailMessage.Body = mailMessage.Body.Replace("<<lblApplicationDate>>", rm.GetString("email_LeaveApplicationDate", ci));
            mailMessage.Body = mailMessage.Body.Replace("<<ApplicationDate>>", LeaveApplicationDate);
            mailMessage.Body = mailMessage.Body.Replace("<<lblLeaveType>>", rm.GetString("lbl_leavetype", ci));
            mailMessage.Body = mailMessage.Body.Replace("<<LeaveType>>", strLeaveType);
            mailMessage.Body = mailMessage.Body.Replace("<<lblLeaveDate>>", rm.GetString("email_LeaveDate", ci));
            mailMessage.Body = mailMessage.Body.Replace("<<lblFromDate>>", rm.GetString("email_FromDate", ci));
            mailMessage.Body = mailMessage.Body.Replace("<<FromDate>>", FromDate);
            mailMessage.Body = mailMessage.Body.Replace("<<lblToDate>>", rm.GetString("email_ToDate", ci));
            mailMessage.Body = mailMessage.Body.Replace("<<ToDate>>", Todate);
            mailMessage.Body = mailMessage.Body.Replace("<<lblSession>>", rm.GetString("email_Session", ci));
            mailMessage.Body = mailMessage.Body.Replace("<<FromSession>>", FromSession);
            mailMessage.Body = mailMessage.Body.Replace("<<lblFromSession>>", rm.GetString("email_FromDate", ci));
            mailMessage.Body = mailMessage.Body.Replace("<<ToSession>>", ToSession);
            mailMessage.Body = mailMessage.Body.Replace("<<lblToSession>>", rm.GetString("email_ToDate", ci));
            mailMessage.Body = mailMessage.Body.Replace("<<lblNumberDaysApplied>>", rm.GetString("email_NumberOfDaysApplied", ci));
            mailMessage.Body = mailMessage.Body.Replace("<<NumberDaysApplied>>", NoOfDays);
            mailMessage.Body = mailMessage.Body.Replace("<<lblStatus>>", rm.GetString("email_Status", ci));
            mailMessage.Body = mailMessage.Body.Replace("<<Status>>", Status);
            mailMessage.Body = mailMessage.Body.Replace("<<lblReason>>", "Reason");
            //mailMessage.Body = mailMessage.Body.Replace("<<Reason>>", lblReason.Text);
            mailMessage.Body = mailMessage.Body.Replace("<<lblRemarks>>", rm.GetString("email_Remarks", ci));
            mailMessage.Body = mailMessage.Body.Replace("<<Remarks>>", Remarks);
            loHTMLView = AlternateView.CreateAlternateViewFromString(mailMessage.Body, loHTMLType);
            mailMessage.AlternateViews.Add(loHTMLView);
            loSMTPServer.DeliveryMethod = SmtpDeliveryMethod.Network;
            loSMTPServer.Send(mailMessage);
            //System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient();
            //smtpClient.Host = "192.168.0.210";
            //smtpClient.Send(mailMessage);
        }
        catch
        {
            checkEmail = false;
            objLeaveApplicationEventData.InsertLeaveApplicationDetailsInEmailTrigger(LeaveApplication_Id, strFromEmailId, EmployeeEamilId, strEmailIdReportingTo, rm.GetString("email_YourLeaveApplicationFor", ci) + " - " + Convert.ToDateTime(FromDate).ToShortDateString() + " - " + Convert.ToDateTime(Todate).ToShortDateString() + " | " + Status, mailMessage.Body.ToString(), "", "LeaveSanction");
        }
    }
    private string[] commaStringToArray(string strComma)
    {
        string[] strArray;
        strArray = strComma.Split(new char[] { ',' });
        string[] intArray = new string[strArray.Length];
        for (int i = 0; i < strArray.Length; i++)
            intArray[i] = Convert.ToString(strArray[i]);
        return intArray;
    }
    #endregion
    #region ButtonEvents
    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (hdnSelectRow.Value != string.Empty && hdnSelectRow.Value != null)
        {
            #region SaveLeaveDetails
            string[] test;
            test = commaStringToArray(hdnSelectRow.Value);
            DataTable dsCheckedItem;
            dsCheckedItem = (DataTable)Session["LeaveChecked"];
            for (int i = 0; i < test.Length; i++)
            {
                //Added by Manjula.P on 25-Apr-2014 for getting intimation type for migrating from product ot ANGLER
                string intIntimationType = string.Empty;
                //**************************************************************
                LeaveApplication_Id = Convert.ToInt32(test[i]);
                dtSanctionView = objLeaveApplicationEventData.GetLeaveApplicationByLeaveApplicationId(LeaveApplication_Id);
                SanctionViewDetails(LeaveApplication_Id);
                EmployeeName = dtSanctionView.Rows[0]["Employee_FirstName"].ToString();
                Employee_Id = Convert.ToInt32(dtSanctionView.Rows[0]["Employee_Id"]);
                //Changing Employee Id into Employee Code Id for viewing to the user by Manjula.P on 28-Sep-2013 Employee_Id <>Employee_Code_Id
                Employee_Code_Id = Convert.ToString(dtSanctionView.Rows[0]["Employee_Code_Id"]);
                EmployeeEamilId = dtSanctionView.Rows[0]["EmailId"].ToString();
                strLeaveApplicationDate = (DateTime.Parse(dtSanctionView.Rows[0]["Leave_ApplicationDate"].ToString())).ToString(Session["MDateFormat"].ToString());
                strNoOfDays = dtSanctionView.Rows[0]["NumberOfDays"].ToString();
                Leave_FromDate = dtSanctionView.Rows[0]["Leave_FromDate"].ToString();
                Leave_ToDate = dtSanctionView.Rows[0]["Leave_ToDate"].ToString();
                ViewState["LevelName"] = dtSanctionView.Rows[0]["LevelName"].ToString();
                Status = dtSanctionView.Rows[0]["Status"].ToString();
                string strTypeOfLeave = dtSanctionView.Rows[0]["Type"].ToString();
                int YearSettingID = Convert.ToInt16(dtSanctionView.Rows[0]["YearSettings_Id"]);
                //Added by Manjula.P on 25-Apr-2014 for getting intimation type for migrating from product ot ANGLER
                intIntimationType = dtSanctionView.Rows[0]["IntimationType"].ToString();
                // Added by Gopinath for not allow approval after the applied date crossed on 15-Feb-2016.
                string strFromDate = (DateTime.Parse(dtSanctionView.Rows[0]["Leave_FromDate"].ToString())).ToString(Session["MDateFormat"].ToString());
                string strToDate = (DateTime.Parse(dtSanctionView.Rows[0]["Leave_ToDate"].ToString())).ToString(Session["MDateFormat"].ToString());
                string strTodaysDate = DateTime.Now.ToString(Session["MDateFormat"].ToString());
                if (((Convert.ToDateTime(strFromDate) < Convert.ToDateTime(strTodaysDate)) || (Convert.ToDateTime(strToDate) < Convert.ToDateTime(strTodaysDate))) && Session["UserGroupName"].ToString() != "SuperAdmin" && Session["AllowLeaveApprovalPastEntry"].ToString() != "True" && intIntimationType == "P" && (Status == "Pending" || Status == "Approved" || Status == "Forwarded"))
                {
                    Message("Leave Approvals should not be done for past days");
                    return;
                }
                //**************************************************************
                ds_ReportingToSanctionAuthorityList = objLeaveApplicationEventData.SelectReportingToSanctionAuthority(LeaveApplication_Id);
                if (Session["UserGroupName"].ToString() != "SuperAdmin")
                {
                    if (ds_ReportingToSanctionAuthorityList.Tables.Count > 0)
                    {
                        if (ds_ReportingToSanctionAuthorityList.Tables[0].Rows.Count > 0)
                        {
                            if (Convert.ToString(Session["EmpAutoId"]) == Convert.ToString(ds_ReportingToSanctionAuthorityList.Tables[0].Rows[0]["Reporting_To"]) && Convert.ToString(Session["EmpAutoId"]) == Convert.ToString(ds_ReportingToSanctionAuthorityList.Tables[0].Rows[0]["Leave_Sanc_Authority"]))
                            {
                                Status = "Approved";
                            }
                            else if (Convert.ToString(Session["EmpAutoId"]) == Convert.ToString(ds_ReportingToSanctionAuthorityList.Tables[0].Rows[0]["Reporting_To"]))
                            {
                                Status = "Forwarded";
                            }
                            else if (Convert.ToString(Session["EmpAutoId"]) == Convert.ToString(ds_ReportingToSanctionAuthorityList.Tables[0].Rows[0]["Leave_Sanc_Authority"]))
                            {
                                Status = "Approved";
                            }
                        }
                    }
                }
                else
                {
                    if (Status == "Forwarded")
                    {
                        Status = "Approved";
                    }
                    if (Status == "Pending")
                    {
                        Status = "Forwarded";
                    }
                }
                NumberOfDays = Convert.ToDouble(dtSanctionView.Rows[0]["NumberOfDays"]);
                LeaveTypeId = Convert.ToInt32(dtSanctionView.Rows[0]["LeaveType_id"]);
                bool boolChkLeave = true;
                int intLeaveCount = 0;
                #region SavingLeaveApplication
                try
                {
                    //update Leave Application
                    if (strTypeOfLeave == "Leave")
                    {
                        if (ViewState["StatusBorrow"].ToString() == "False")
                        {
                            if (Status == "Approved")
                            {
                                objLeaveApplicationEventData.UpdateYearClosureByLeaveSanction(NumberOfDays, LeaveTypeId, Employee_Id, "A", Convert.ToInt32(Session["EmpAutoId"]), YearSettingID);
                            }
                            //if (ViewState["StatusOnLoad"].ToString() != Status)
                            //{
                            //if ((Status == "Forwarded" || Status == "Pending"))
                            //{
                            //    //Check Borrow Leave Exists after normal leaves
                            //    intBorrowCount = objLeaveApplicationEventData.CheckBorrowLeaveExists(Leave_FromDate, Leave_ToDate, LeaveTypeId, Employee_Id);
                            //    if (intBorrowCount > 0)
                            //    {
                            //        boolChkLeave = false;
                            //        //lbl_Error.Text = "Borrow Leaves are available to approve/reject";
                            //        base.Message(rm.GetString("Msg_BorrowLeavesareavailabletoapprovereject", ci));
                            //        return;
                            //    }
                            //    else
                            //    {
                            //        //ManiobjLeaveApplicationEventData.UpdateYearClosureByLeaveSanction(NumberOfDays, LeaveTypeId, Employee_Id, "R", Convert.ToInt32(Session["EmpAutoId"]));
                            //    }
                            //}
                        }
                        if (ViewState["StatusBorrow"].ToString() == "True")
                        {
                            DataSet dsRemainingNoOfleaves = new DataSet();
                            double dblCurrLeave = 0.0;
                            if (ViewState["StatusOnLoad"].ToString() != Status)
                            {
                                if (Status == "Approved")
                                {
                                    //Check other leaves exists before borrow leave
                                    intLeaveCount = objLeaveApplicationEventData.CheckLeaveExistsBeforeBorrow(Leave_FromDate, Leave_ToDate, LeaveTypeId, Employee_Id);
                                    if (intLeaveCount > 0)
                                    {
                                        boolChkLeave = false;
                                        //lbl_Error.Text = "Already current year leave applications are available to approve/reject";
                                        base.Message(rm.GetString("Msg_Alreadycurrentyearleaveapplicationsareavailabletoapprovereject", ci));
                                        return;
                                    }
                                    else
                                    {
                                        dsRemainingNoOfleaves = objLeaveApplicationEventData.GetRemainingNumberOfLeaves(Employee_Id, LeaveTypeId);
                                        dsRemainingNoOfleaves.Tables[0].TableName = "Details";
                                        if (dsRemainingNoOfleaves.Tables.Count > 0)
                                        {
                                            if (dsRemainingNoOfleaves.Tables[0].Rows.Count > 0)
                                            {
                                                dblCurrLeave = Convert.ToDouble(dsRemainingNoOfleaves.Tables["Details"].Rows[0]["RemainingNoOfLeaves"]);
                                            }
                                        }
                                        if (dblCurrLeave > 0)
                                        {
                                            boolChkLeave = false;
                                            //lbl_Error.Text = "Current year quota available for this leave type";
                                            base.Message(rm.GetString("Msg_Currentyearquotaavailableforthisleavetype", ci));
                                            return;
                                        }
                                        objLeaveApplicationEventData.UpdateYearClosureByLeaveSanction(NumberOfDays, LeaveTypeId, Employee_Id, "AB", Convert.ToInt32(Session["EmpAutoId"]), YearSettingID);
                                    }
                                }
                            }
                        }
                    }
                    if (boolChkLeave == true)
                    {
                        objLeaveApplicationEventData.UpdateLeaveApplicationSanction(LeaveApplication_Id, Status, "Ok", Convert.ToInt32(Session["EmpAutoId"]), intIntimationType);
                    }
                    //Update Processed Data Flag
                    objLeaveApplicationEventData.UpdateProcessedDataFlag(Employee_Id, Leave_FromDate, Leave_ToDate, 0);
                    //if (ViewState["StatusOnLoad"].ToString() != Status)
                    //{
                    if (EmployeeEamilId != string.Empty)
                    {
                        //SendMailToApplicant(EmployeeEamilId, EmployeeName, Status, txtRemarks.Text, strLeaveApplicationDate, strNoOfDays, lblLeaveType.Text);
                    }
                    //To find Leave Sanction Authorities Email_ID
                    ds_EmailIdOfSanctionAuthority = objPermissionEventData.SelectMailIdOfSanctionAuthority(Employee_Id);
                    if (ds_EmailIdOfSanctionAuthority.Tables[0].Rows.Count > 0)
                    {
                        if (ds_EmailIdOfSanctionAuthority.Tables[0].Rows[0]["EmailId"] != DBNull.Value)
                        {
                            if (ds_EmailIdOfSanctionAuthority.Tables[0].Rows[0]["EmailId"].ToString() != string.Empty)
                            {
                                strEmailIdSanctionAuthority = ds_EmailIdOfSanctionAuthority.Tables[0].Rows[0]["EmailId"].ToString();
                                //if (Status == "Forwarded")
                                //{
                                //SendMailToSanctionAuthority(strEmailIdSanctionAuthority, Status, Employee_Id, EmployeeName, txtRemarks.Text, strLeaveApplicationDate, strNoOfDays, lblLeaveType.Text);
                                //}
                            }
                            else
                            {
                                //checkEmail = false;
                            }
                        }
                        else
                        {
                            //checkEmail = false;
                        }
                    }
                    else
                    {
                        //checkEmail = false;
                    }
                    dsEmailIdOfReportingTo = objPermissionEventData.SelectMailIdOfReportingTo(Employee_Id);
                    if (dsEmailIdOfReportingTo.Tables[0].Rows.Count > 0)
                    {
                        if (dsEmailIdOfReportingTo.Tables[0].Rows[0]["EmailId"] != DBNull.Value)
                        {
                            if (dsEmailIdOfReportingTo.Tables[0].Rows[0]["EmailId"].ToString() != string.Empty)
                            {
                                strEmailIdReportingTo = dsEmailIdOfReportingTo.Tables[0].Rows[0]["EmailId"].ToString();
                                //SendMailToSanctionAuthority(dsEmailIdOfReportingTo.Tables[0].Rows[0]["EmailId"].ToString(), Status, Employee_Id, EmployeeName, txtRemarks.Text, strLeaveApplicationDate, strNoOfDays, lblLeaveType.Text);
                            }
                        }
                    }
                    //SendMailToApplicant("manikandan.rr@angleritech.com", "angeswaran@angleritech.com", "manikandan.rr@angleritech.com", EmployeeName, "Approved", "Ok", strLeaveApplicationDate, strNoOfDays, "Leave", dtSanctionView.Rows[0]["Leave_FromDate"].ToString(), dtSanctionView.Rows[0]["Leave_ToDate"].ToString(), dtSanctionView.Rows[0]["Leave_SessionFrom"].ToString(), dtSanctionView.Rows[0]["Leave_SessionTo"].ToString());
                    SendMailToApplicant(EmployeeEamilId, strEmailIdReportingTo, strEmailIdSanctionAuthority, EmployeeName, "Approved", "Ok", strLeaveApplicationDate, strNoOfDays, Convert.ToString(ViewState["LeaveType"]), dtSanctionView.Rows[0]["Leave_FromDate"].ToString(), dtSanctionView.Rows[0]["Leave_ToDate"].ToString(), dtSanctionView.Rows[0]["Leave_SessionFrom"].ToString(), dtSanctionView.Rows[0]["Leave_SessionTo"].ToString());
                    //}
                    if (checkEmail == true)
                    {
                        // Response.Redirect("../Transactions/TA_UI_Transactions_LeaveSanction.aspx");
                        string strScript = string.Empty;
                        strScript = strScript + "<script language='javascript'>";
                        strScript = strScript + "alert('" + rm.GetString("Alert_LeaveSanctionApplicationSaved", ci) + "');";
                        strScript = strScript + "location.replace('TA_UI_Transactions_LeaveSanction_Angler.aspx');";
                        strScript = strScript + "</script>";
                        //Dispaly alert messsage.
                        Page.RegisterStartupScript("AlertPAdd9975466", strScript);
                    }
                    //Changing Employee Id into Employee Code Id for viewing to the user by Manjula.P on 28-Sep-2013 Employee_Id <>Employee_Code_Id
                    else
                    {
                        if (NotSendedEmployeeCodeId == "")
                        {
                            //Changing Employee Id into Employee Code Id for viewing to the user by Manjula.P on 28-Sep-2013 Employee_Id <>Employee_Code_Id
                            NotSendedEmployeeCodeId = Convert.ToString(Employee_Code_Id);
                        }
                        else
                        {
                            //Changing Employee Id into Employee Code Id for viewing to the user by Manjula.P on 28-Sep-2013 Employee_Id <>Employee_Code_Id  
                            string[] ExistEmployeeCode = NotSendedEmployeeCodeId.Split(',');
                            if (ExistEmployeeCode.Length > 0)
                            {
                                //To avoiding duplicate employee codes in message
                                int pos = Array.IndexOf(ExistEmployeeCode, Employee_Code_Id);
                                if (pos <= -1)
                                {
                                    NotSendedEmployeeCodeId = NotSendedEmployeeCodeId + ',' + Convert.ToString(Employee_Code_Id);
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                #endregion
            }
            if (NotSendedEmployeeCodeId != null)
            {
                string strScript = string.Empty;
                strScript = strScript + "<script language='javascript'>";
                strScript = strScript + "alert('" + rm.GetString("Alert_LeaveSanctionApplicationSavedEmailnotsent_Bulk", ci) + NotSendedEmployeeCodeId + "');";
                strScript = strScript + "</script>";
                //Dispaly alert messsage.
                Page.RegisterStartupScript("AlertPAdd3674", strScript);
            }
            else
            {
                string strScript = string.Empty;
                strScript = strScript + "<script language='javascript'>";
                strScript = strScript + "alert('" + rm.GetString("PleaseSelectAnyOneLeaveApplication", ci) + "');";
                strScript = strScript + "</script>";
                Page.RegisterStartupScript("AlertPAdd3674", strScript);
            }
            if (test.Length == gdLeaveSanctionView.VisibleRowCount)
            {
                Session["LeaveChecked"] = null;
                bindLeaveSanctionDetails();
                //clearAllSession();
            }
            else
            {
                bindLeaveSanctionDetails();
                Session["LeaveChecked"] = null;
            }
            #endregion
        }
        else
        {
            string strScript = string.Empty;
            strScript = strScript + "<script language='javascript'>";
            strScript = strScript + "alert('" + rm.GetString("PleaseSelectAnyOneLeaveApplication", ci) + "');";
            //strScript = strScript + "location.replace('TA_UI_Transactions_LeaveSanctionViewForBulkApproval.aspx');";
            strScript = strScript + "</script>";
            //Dispaly alert messsage.            
            Page.RegisterStartupScript("AlertPAdd996266", strScript);
        }
    }
    protected void btnBack_Click(object sender, EventArgs e)
    {
        clearAllSession();
        if (Convert.ToString(Session["isDashBoard"]) != "Yes")
        {
            Response.Redirect("TA_UI_Transactions_LeaveSanction_Angler.aspx");
        }
        else
        {
            Response.Redirect("../Landing.aspx");
        }
    }
    protected void btnForward_Click(object sender, EventArgs e)
    {
        {
            string strReason = "";
            cls_Common objClassCommon = new cls_Common();
            DataSet dsEmailIdOfReportingTo = new DataSet();
            DataSet ds_EmailIdOfSanctionAuthority = new DataSet();
            LeaveSettingsEventData_Angler objLeaveSettingsEventData = new LeaveSettingsEventData_Angler();
            DataTable dtSanctionView = new DataTable();
            if (txtRemarks.Text == string.Empty)
            {
                base.Message("Remarks is required");
                return;
            }
            else
            {
                string strLengthCheck = txtRemarks.Text.Trim().Replace("'", "''");
                if (strLengthCheck.Length > 1000)
                {
                    Message("Maximum character for Reason is 1000");
                    return;
                }
                #region LeaveUpdation
                if (hdnSelectRow.Value != "")
                {
                    chkBoxIDs = objLeave.commaStringToArray(hdnSelectRow.Value);
                    for (int i = 0; i < chkBoxIDs.Length; i++)
                    {
                        //foreach (GridViewRow i in gdLeaveSanctionView.Rows)
                        //{
                        //CheckBox ChkBxItem = (CheckBox)i.FindControl("deletethis");
                        //Label lblCheckedIDs = (Label)i.FindControl("lblCheckedIDs");
                        //if (ChkBxItem.Checked)
                        //{
                        LeaveApplication_Id = Convert.ToInt32(chkBoxIDs[i]);
                        //Convert.ToInt16(((Label)i.FindControl("lblLeaveApplicationId")).Text);
                        ViewState["Permission_Id"] = LeaveApplication_Id;
                        dtSanctionView = objLeaveApplicationEventData.GetLeaveApplicationByLeaveApplicationId(LeaveApplication_Id);
                        dtLeaveavailedinMonth = objLeaveApplicationEventData.LoadEmployeeLeaveAvailedinMonth(LeaveApplication_Id);
                        ViewState["dtSanctionView"] = dtSanctionView;
                        int s = dtSanctionView.Rows.Count;
                        SanctionViewDetails(LeaveApplication_Id);
                        for (int RowCount = 0; RowCount < dtSanctionView.Rows.Count; RowCount++)
                        {
                            Status = "Forwarded";
                            if (dtSanctionView.Rows[RowCount]["Employee_FirstName"] != DBNull.Value)
                            {
                                EmployeeName = dtSanctionView.Rows[RowCount]["Employee_FirstName"].ToString();
                            }
                            if (dtSanctionView.Rows[RowCount]["Employee_Id"] != DBNull.Value)
                            {
                                Employee_Id = Convert.ToInt32(dtSanctionView.Rows[RowCount]["Employee_Id"]);
                            }
                            if (dtSanctionView.Rows[RowCount]["EmailId"] != DBNull.Value)
                            {
                                EmployeeEamilId = dtSanctionView.Rows[RowCount]["EmailId"].ToString();
                            }
                            if (dtSanctionView.Rows[RowCount]["Leave_ApplicationDate"] != DBNull.Value)
                            {
                                strLeaveApplicationDate = dtSanctionView.Rows[RowCount]["Leave_ApplicationDate"].ToString();
                            }
                            if (dtSanctionView.Rows[RowCount]["NumberOfDays"] != DBNull.Value)
                            {
                                strNoOfDays = dtSanctionView.Rows[RowCount]["NumberOfDays"].ToString();
                            }
                            if (dtSanctionView.Rows[RowCount]["LeaveFrom"] != DBNull.Value)
                            {
                                Leave_FromDate = dtSanctionView.Rows[RowCount]["LeaveFrom"].ToString();
                            }
                            if (dtSanctionView.Rows[RowCount]["LeaveTo"] != DBNull.Value)
                            {
                                Leave_ToDate = dtSanctionView.Rows[RowCount]["LeaveTo"].ToString();
                            }
                            if (dtSanctionView.Rows[RowCount]["LevelName"] != DBNull.Value)
                            {
                                levelName = dtSanctionView.Rows[RowCount]["LevelName"].ToString();
                            }
                            if (dtSanctionView.Rows[RowCount]["LeaveType"] != DBNull.Value)
                            {
                                leaveType = dtSanctionView.Rows[RowCount]["LeaveType"].ToString();
                            }
                            if (dtSanctionView.Rows[RowCount]["Type"] != DBNull.Value)
                            {
                                strTypeOfLeave = dtSanctionView.Rows[RowCount]["Type"].ToString();
                            }
                            if (dtSanctionView.Rows[RowCount]["NumberOfDays"] != DBNull.Value)
                            {
                                NumberOfDays = Convert.ToDouble(dtSanctionView.Rows[RowCount]["NumberOfDays"]);
                            }
                            if (dtSanctionView.Rows[RowCount]["LeaveType_id"] != DBNull.Value)
                            {
                                LeaveTypeId = Convert.ToInt32(dtSanctionView.Rows[RowCount]["LeaveType_id"]);
                            }
                            if (dtSanctionView.Rows[RowCount]["IntimationType"] != DBNull.Value)
                            {
                                intimationType = dtSanctionView.Rows[RowCount]["IntimationType"].ToString();
                            }
                            Remarks = txtRemarks.Text.Trim().Replace("'", "''");
                            // Added by Gopinath for not allow approval after the applied date crossed  on 15-Feb-2016.
                            string strFromDate = (DateTime.Parse(dtSanctionView.Rows[0]["LeaveFrom"].ToString())).ToString(Session["MDateFormat"].ToString());
                            string strToDate = (DateTime.Parse(dtSanctionView.Rows[0]["LeaveTo"].ToString())).ToString(Session["MDateFormat"].ToString());
                            string strTodaysDate = DateTime.Now.ToString(Session["MDateFormat"].ToString());
                            if (((Convert.ToDateTime(strFromDate) < Convert.ToDateTime(strTodaysDate)) || (Convert.ToDateTime(strToDate) < Convert.ToDateTime(strTodaysDate))) && Session["UserGroupName"].ToString() != "SuperAdmin" && Session["AllowLeaveApprovalPastEntry"].ToString() != "True" && intimationType == "P" && (Status == "Pending" || Status == "Approved" || Status == "Forwarded"))
                            {
                                Message("Leave Approvals should not be done for past days");
                                return;
                            }
                            if (dtSanctionView.Rows[0]["LeaveAvailedMonth"].ToString() != string.Empty)
                            {
                                ViewState["vwLeaveAvailedMonthData"] = dtSanctionView.Rows[RowCount]["LeaveAvailedMonth"].ToString();
                            }
                            else
                            {
                                ViewState["vwLeaveAvailedMonthData"] = "0.0";
                            }
                            if (dtSanctionView.Rows[0]["LeaveAvailedYear"].ToString() != string.Empty)
                            {
                                ViewState["vwLeaveAvailedYearData"] = dtSanctionView.Rows[RowCount]["LeaveAvailedYear"].ToString();
                            }
                            else
                            {
                                ViewState["vwLeaveAvailedYearData"] = "0.0";
                            }
                            ViewState["vwReason"] = dtSanctionView.Rows[RowCount]["Reason"].ToString();
                            string strFromdate = string.Empty;
                            string strTodate = string.Empty;
                            dblLeaveAvailedYear = objLeaveApplicationEventData.GetLeaveSummary(DateTime.Parse(strYearSettingsFromdate), DateTime.Parse(strYearSettingsTodate), Employee_Id);
                            strLeaveAvailedYear = dblLeaveAvailedYear.ToString();
                            for (int RowCount1 = 0; RowCount1 < dtSanctionView.Rows.Count; RowCount1++)
                            {
                                if (dtSanctionView.Rows[RowCount1]["LeaveFrom"] != DBNull.Value)
                                {
                                    strFromdate = dtSanctionView.Rows[RowCount1]["LeaveFrom"].ToString();
                                }
                                if (strMonthValue == "")
                                {
                                    strMonthValue = Convert.ToDateTime(strFromdate).Month.ToString();
                                }
                                else if (strMonthValue != "")
                                {
                                    if (strMonthValue != Convert.ToDateTime(strFromdate).Month.ToString())
                                    {
                                        strCrossDate = "Yes";
                                    }
                                }
                            }
                            if (dtLeaveavailedinMonth.Rows.Count > 0)
                            {
                                if (strCrossDate == "Yes")
                                {
                                    strLeaveavailedinFirstMonth = dtLeaveavailedinMonth.Rows[0]["NumberofDays"].ToString();
                                    strLeaveavailedinSecondMonth = dtLeaveavailedinMonth.Rows[1]["NumberofDays"].ToString();
                                    strLeaveavailedinFirstMonthName = dtLeaveavailedinMonth.Rows[0]["MonthName"].ToString();
                                    strLeaveavailedinSecondMonthName = dtLeaveavailedinMonth.Rows[1]["MonthName"].ToString();
                                }
                                else
                                {
                                    strLeaveavailedinFirstMonth = dtLeaveavailedinMonth.Rows[0]["NumberofDays"].ToString();
                                    strLeaveavailedinFirstMonthName = dtLeaveavailedinMonth.Rows[0]["MonthName"].ToString();
                                }
                            }
                            //Intimation Type
                            // To find Reporting To & Leave Sanction Authority Email_ID
                            // Gets the Reporting To Authority Id and Email Id
                            //int intFirstLevelAuthorityId = 0, intSecondLevelAuthorityId = 0;
                            DataSet ds_ReportingTo = new DataSet();
                            ds_ReportingTo = objPermissionEventData.SelectMailIdOfReportingTo(Employee_Id);
                            //if (Status == "Forwarded")
                            //{
                            //Status = "Approved";
                            //}
                            //if (Status == "Pending")
                            //{
                            //  Status = "Forwarded";
                            //}
                            intLoginEmpId = Convert.ToInt32(Session["EmpAutoId"]);
                            dsDepartmentMailIds = objLeaveSettingsEventData.GetDepartmentMailIds(Convert.ToInt32(dtSanctionView.Rows[0]["LevelId"]));
                            ViewState["vsStrApprovalToDept"] = dsDepartmentMailIds.Tables[0].Rows[0]["ToMailIds"].ToString();
                            ViewState["vsStrApprovalCCDept"] = dsDepartmentMailIds.Tables[0].Rows[0]["CCMailIds"].ToString();
                            getOrg.GetOrgParentLevels_FromID(Convert.ToInt32(dtSanctionView.Rows[0]["LevelId"]));
                            ds_getOrg = getOrg.GetOrgParentLevels();
                            gintCompanyId = Convert.ToInt32(ds_getOrg.Tables[0].Rows[0]["LevelID"].ToString());
                            ViewState["CompanyId"] = gintCompanyId;
                            ds_LeaveSanctionSettings = objLeaveSettingsEventData.GetLeaveSettingsByComId(gintCompanyId);
                            if (ds_LeaveSanctionSettings.Tables.Count > 0)
                            {
                                dt_LeaveSettings = ds_LeaveSanctionSettings.Tables[0];
                            }
                            if (dt_LeaveSettings.Rows.Count > 0)
                            {
                                if (dt_LeaveSettings.Rows[0]["Approval"] != DBNull.Value && dt_LeaveSettings.Rows[0]["Approval"].ToString() != string.Empty)
                                {
                                    if (dt_LeaveSettings.Rows[0]["Approval"].ToString() == "False")
                                    {
                                        // Both First and Second Level Authority Approval
                                        intApproval = 0;
                                    }
                                    else if (dt_LeaveSettings.Rows[0]["Approval"].ToString() == "True")
                                    {
                                        // First or Second Level Authority Approval - Either or one
                                        intApproval = 1;
                                    }
                                    else
                                    {
                                        // Nothing
                                    }
                                }
                                if (dt_LeaveSettings.Rows[0]["ApprovalCC"] != DBNull.Value && dt_LeaveSettings.Rows[0]["ApprovalCC"].ToString() != string.Empty)
                                {
                                    strApprovalCC = dt_LeaveSettings.Rows[0]["ApprovalCC"].ToString();
                                    ViewState["vsStrApprovalCC"] = strApprovalCC;
                                }
                                else
                                {
                                    ViewState["vsStrApprovalCC"] = string.Empty;
                                }
                            }
                            ds_ReportingTo = objPermissionEventData.SelectMailIdOfReportingTo(Employee_Id);
                            if (ds_ReportingTo.Tables[0].Rows.Count > 0)
                            {
                                if (ds_ReportingTo.Tables[0].Rows[0]["EmailId"] != DBNull.Value && ds_ReportingTo.Tables[0].Rows[0]["EmailId"].ToString() != string.Empty)
                                {
                                    intFirstLevelAuthorityId = int.Parse(ds_ReportingTo.Tables[0].Rows[0]["Employee_Id"].ToString());
                                    strEmailIdReportingTo = ds_ReportingTo.Tables[0].Rows[0]["EmailId"].ToString();
                                }
                            }
                            // Gets the Sanctioning Authority Id and Email Id
                            ds_EmailIdOfSanctionAuthority = objPermissionEventData.SelectMailIdOfSanctionAuthority(Employee_Id);
                            if (ds_EmailIdOfSanctionAuthority.Tables[0].Rows.Count > 0)
                            {
                                if (ds_EmailIdOfSanctionAuthority.Tables[0].Rows[0]["EmailId"] != DBNull.Value && ds_EmailIdOfSanctionAuthority.Tables[0].Rows[0]["EmailId"].ToString() != string.Empty)
                                {
                                    intSecondLevelAuthorityId = int.Parse(ds_EmailIdOfSanctionAuthority.Tables[0].Rows[0]["Employee_Id"].ToString());
                                    strEmailIdSanctionAuthority = ds_EmailIdOfSanctionAuthority.Tables[0].Rows[0]["EmailId"].ToString();
                                }
                            }
                            // Check whether the Login Employee Id is whether First or Second Level Sanctioning Authority
                            if (intFirstLevelAuthorityId != intSecondLevelAuthorityId)
                            {
                                if (intLoginEmpId == intFirstLevelAuthorityId)
                                {
                                    intAuthorityLevel = 1;
                                }
                                else if (intLoginEmpId == intSecondLevelAuthorityId)
                                {
                                    intAuthorityLevel = 2;
                                }
                                else
                                {
                                    // Nothing
                                }
                            }
                            else if (intFirstLevelAuthorityId == intSecondLevelAuthorityId)
                            {
                                if (intLoginEmpId == intSecondLevelAuthorityId)
                                {
                                    intAuthorityLevel = 2;
                                }
                                else
                                {
                                    intAuthorityLevel = 3;
                                }
                            }
                            else
                            {
                                intAuthorityLevel = 3;
                            }
                            ViewState["vsCommentsBy"] = intAuthorityLevel;
                            if (strEmailIdSanctionAuthority == null)
                            {
                                strEmailIdSanctionAuthority = string.Empty;
                            }
                            if (strEmailIdReportingTo == null)
                            {
                                strEmailIdReportingTo = string.Empty;
                            }
                            if (strEmailIdSanctionAuthority == string.Empty && strEmailIdReportingTo == string.Empty && txtApprovalCC.Text == string.Empty && txtApprovalTO.Text == string.Empty)
                            {
                                checkEmail = false;
                            }
                            DataTable dtEmployeeLeaveDetails = new DataTable();
                            dtEmployeeLeaveDetails = dtSanctionView.Copy();
                            if (((DataTable)Session["vSLeaveDetails"]).Columns.Count <= dtEmployeeLeaveDetails.Columns.Count)
                            {
                                dtEmployeeLeaveDetails.Columns.Remove("LeaveApplication_Id");
                                dtEmployeeLeaveDetails.Columns.Remove("Employee_Id");
                                dtEmployeeLeaveDetails.Columns.Remove("Emp_Id");
                                dtEmployeeLeaveDetails.Columns.Remove("IntimationType");
                                dtEmployeeLeaveDetails.Columns.Remove("Employee_Code_Id");
                                dtEmployeeLeaveDetails.Columns.Remove("emailId");
                                dtEmployeeLeaveDetails.Columns.Remove("Employee_FirstName");
                                dtEmployeeLeaveDetails.Columns.Remove("Leave_ApplicationDate");
                                dtEmployeeLeaveDetails.Columns.Remove("LeaveType_Id");
                                dtEmployeeLeaveDetails.Columns.Remove("Reason");
                                dtEmployeeLeaveDetails.Columns.Remove("Status");
                                dtEmployeeLeaveDetails.Columns.Remove("IsDeleted");
                                dtEmployeeLeaveDetails.Columns.Remove("Remarks");
                                dtEmployeeLeaveDetails.Columns.Remove("IsBorrow");
                                dtEmployeeLeaveDetails.Columns.Remove("LevelName");
                                dtEmployeeLeaveDetails.Columns.Remove("levelid");
                                dtEmployeeLeaveDetails.Columns.Remove("CCMail");
                                dtEmployeeLeaveDetails.Columns.Remove("LeaveAvailedMonth");
                                dtEmployeeLeaveDetails.Columns.Remove("LeaveAvailedYear");
                                dtEmployeeLeaveDetails.Columns.Remove("DesignationID");
                                dtEmployeeLeaveDetails.Columns.Remove("CheckedIDs");
                                dtEmployeeLeaveDetails.Columns.Remove("YearSettings_Id");
                                dtEmployeeLeaveDetails.Columns.Add("From");
                                dtEmployeeLeaveDetails.Columns.Add("To");
                                //   dtEmployeeLeaveDetails.Columns[7].SetOrdinal(2);
                                //   dtEmployeeLeaveDetails.Columns[8].SetOrdinal(3);
                                foreach (DataRow dRowEmployeeLeaveDetails in dtEmployeeLeaveDetails.Rows)
                                {
                                    DateTime dtmLeaveFromDate = Convert.ToDateTime(DateTime.Parse(dRowEmployeeLeaveDetails["LeaveFrom"].ToString()).ToShortDateString());
                                    strFromDate = dtmLeaveFromDate.ToString(Session["MDateFormat"].ToString());
                                    dRowEmployeeLeaveDetails["From"] = strFromDate;
                                    DateTime dtmLeaveToDate = Convert.ToDateTime(DateTime.Parse(dRowEmployeeLeaveDetails["LeaveTo"].ToString()).ToShortDateString());
                                    strToDate = dtmLeaveToDate.ToString(Session["MDateFormat"].ToString());
                                    dRowEmployeeLeaveDetails["To"] = strToDate;
                                }
                                dtEmployeeLeaveDetails.Columns.Remove("LeaveFrom");
                                dtEmployeeLeaveDetails.Columns.Remove("LeaveTo");
                                dtEmployeeLeaveDetails.Columns.Remove("InformTo");
                                dtEmployeeLeaveDetails.Columns[0].ColumnName = "Leave Category";
                                dtEmployeeLeaveDetails.Columns[1].ColumnName = "Leave Type";
                                dtEmployeeLeaveDetails.Columns[5].SetOrdinal(2);
                                dtEmployeeLeaveDetails.Columns[6].SetOrdinal(3);
                                //dtEmployeeLeaveDetails.Columns[2].ColumnName = "From";
                                //dtEmployeeLeaveDetails.Columns[3].ColumnName = "To";
                                dtEmployeeLeaveDetails.Columns[4].ColumnName = "Session From";
                                dtEmployeeLeaveDetails.Columns[5].ColumnName = "Session To";
                                dtEmployeeLeaveDetails.Columns[6].ColumnName = "No. of Days";
                                DataRow[] rowList = dtEmployeeLeaveDetails.Select("[Leave Category] = 'LOP'");
                                foreach (DataRow dr in rowList)
                                {
                                    dr["Leave Type"] = "-";
                                }
                            }
                            strHtmlLeaveDetails = buildPage("LeaveDetails", dtEmployeeLeaveDetails);
                            int intLeaveCount = 0;
                            try
                            {
                            }
                            catch (Exception ex)
                            {
                                throw ex;
                            }
                        }
                        if (boolChkLeave == true)
                        {
                            if (strTypeOfLeave != "Leave")
                            {
                            }
                            objLeaveApplicationEventData.UpdateLeaveApplicationSanction(LeaveApplication_Id, Status, Remarks, Convert.ToInt32(Session["EmpAutoId"]), intimationType);
                        }
                        //common to all status
                        objLeaveApplicationEventData.UpdateLeaveApplicationConversation(LeaveApplication_Id, Status, Convert.ToInt32(ViewState["vsCommentsBy"].ToString()), Remarks, Convert.ToInt32(Session["EmpAutoId"]));
                        //Update Processed Data Flag
                        objLeaveApplicationEventData.UpdateProcessedDataFlag(Employee_Id, Leave_FromDate, Leave_ToDate, 0);
                        if (checkEmail == true)
                        {
                            if (Status == "Approved" || Status == "Forwarded" || Status == "Rejected" || Status == "Resend")
                            {
                                ControlCreation();
                                if (Convert.ToInt32(ConfigurationManager.AppSettings.Get("isRequiredEmail")) == 1)
                                {
                                    SendMail(intFirstLevelAuthorityId, intSecondLevelAuthorityId, strEmailIdReportingTo, strEmailIdSanctionAuthority, EmployeeEamilId, Convert.ToString(ViewState["Employee_code_Id"]), EmployeeName, Status, txtRemarks.Text.Trim().Replace("'", "''"), strLeaveApplicationDate, strNoOfDays, leaveType, levelName, Convert.ToString(ViewState["vsStrApprovalCC"]), intimationType);
                                }
                            }
                        }
                        strMonthValue = string.Empty;
                        strCrossDate = string.Empty;
                        if (checkEmail == true)
                        {
                            string strScript = string.Empty;
                            strScript = strScript + "<script language='javascript'>";
                            strScript = strScript + "alert('Leave Application saved');";
                            strScript = strScript + "RedirectionFunction();";
                            strScript = strScript + "</script>";
                            Page.RegisterStartupScript("AlertPsaved36774", strScript);
                        }
                        else
                        {
                            string strScript = string.Empty;
                            strScript = strScript + "<script language='javascript'>";
                            strScript = strScript + "alert('Leave Application saved,Email not sent');";
                            strScript = strScript + "RedirectionFunction();";
                            strScript = strScript + "</script>";
                            //Dispaly alert messsage.
                            Page.RegisterStartupScript("AlertPAdd3674", strScript);
                        }
                        //}
                    }
                }
                else
                {
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('Select any entry to change status.');", true);
                    return;
                }
                #endregion
            }
        }
    }
    protected void btnApprove_Click(object sender, EventArgs e)
    {
        {
            string strReason = "";
            cls_Common objClassCommon = new cls_Common();
            DataSet dsEmailIdOfReportingTo = new DataSet();
            DataSet ds_EmailIdOfSanctionAuthority = new DataSet();
            LeaveSettingsEventData_Angler objLeaveSettingsEventData = new LeaveSettingsEventData_Angler();
            //int Permission_Id, Employee_Id, gintCompanyId;
            //string Status, Remarks, EmployeeEamilId, strEmailIdReportingTo, strEmailIdSanctionAuthority, EmployeeName, Employee_Code_Id, gstrDateFormat, strlevelName, gstrTimeFormat, reportingToEmployee, sanctioningEmployee;
            DataTable dtSanctionView = new DataTable();
            if (txtRemarks.Text == string.Empty)
            {
                base.Message("Remarks is required");
                return;
            }
            else
            {
                string strLengthCheck = txtRemarks.Text.Trim().Replace("'", "''");
                if (strLengthCheck.Length > 1000)
                {
                    Message("Maximum character for Reason is 1000");
                    return;
                }
                #region LeaveUpdation
                if (hdnSelectRow.Value != "")
                {
                    chkBoxIDs = objLeave.commaStringToArray(hdnSelectRow.Value);
                    for (int i = 0; i < chkBoxIDs.Length; i++)
                    {
                        //foreach (GridViewRow i in gdLeaveSanctionView.Rows)
                        //{
                        //    CheckBox ChkBxItem = (CheckBox)i.FindControl("deletethis");
                        //if (ChkBxItem.Checked)
                        //{
                        LeaveApplication_Id = Convert.ToInt32(chkBoxIDs[i]);
                        //Convert.ToInt16(((Label)i.FindControl("lblLeaveApplicationId")).Text);
                        ViewState["Permission_Id"] = LeaveApplication_Id;
                        //Label lblCheckedIDs = (Label)i.FindControl("lblCheckedIDs");
                        dtSanctionView = objLeaveApplicationEventData.GetLeaveApplicationByLeaveApplicationId(LeaveApplication_Id);
                        dtLeaveavailedinMonth = objLeaveApplicationEventData.LoadEmployeeLeaveAvailedinMonth(LeaveApplication_Id);
                        Session["dtSanctionView"] = dtSanctionView;
                        SanctionViewDetails(LeaveApplication_Id);
                        #region LeaveApplicationSave
                        for (int RowCount = 0; RowCount < dtSanctionView.Rows.Count; RowCount++)
                        {
                            if (dtSanctionView.Rows[RowCount]["Employee_FirstName"] != DBNull.Value)
                            {
                                EmployeeName = dtSanctionView.Rows[RowCount]["Employee_FirstName"].ToString();
                            }
                            if (dtSanctionView.Rows[RowCount]["Employee_Id"] != DBNull.Value)
                            {
                                Employee_Id = Convert.ToInt32(dtSanctionView.Rows[RowCount]["Employee_Id"]);
                            }
                            if (dtSanctionView.Rows[RowCount]["EmailId"] != DBNull.Value)
                            {
                                EmployeeEamilId = dtSanctionView.Rows[RowCount]["EmailId"].ToString();
                            }
                            if (dtSanctionView.Rows[RowCount]["Leave_ApplicationDate"] != DBNull.Value)
                            {
                                strLeaveApplicationDate = dtSanctionView.Rows[RowCount]["Leave_ApplicationDate"].ToString();
                            }
                            if (dtSanctionView.Rows[RowCount]["NumberOfDays"] != DBNull.Value)
                            {
                                strNoOfDays = dtSanctionView.Rows[RowCount]["NumberOfDays"].ToString();
                            }
                            if (dtSanctionView.Rows[RowCount]["LeaveFrom"] != DBNull.Value)
                            {
                                Leave_FromDate = dtSanctionView.Rows[RowCount]["LeaveFrom"].ToString();
                            }
                            if (dtSanctionView.Rows[RowCount]["LeaveTo"] != DBNull.Value)
                            {
                                Leave_ToDate = dtSanctionView.Rows[RowCount]["LeaveTo"].ToString();
                            }
                            if (dtSanctionView.Rows[RowCount]["LevelName"] != DBNull.Value)
                            {
                                levelName = dtSanctionView.Rows[RowCount]["LevelName"].ToString();
                            }
                            if (dtSanctionView.Rows[RowCount]["LeaveType"] != DBNull.Value)
                            {
                                leaveType = dtSanctionView.Rows[RowCount]["LeaveType"].ToString();
                            }
                            if (dtSanctionView.Rows[RowCount]["Type"] != DBNull.Value)
                            {
                                strTypeOfLeave = dtSanctionView.Rows[RowCount]["Type"].ToString();
                            }
                            if (dtSanctionView.Rows[RowCount]["NumberOfDays"] != DBNull.Value)
                            {
                                NumberOfDays = Convert.ToDouble(dtSanctionView.Rows[RowCount]["NumberOfDays"]);
                            }
                            if (dtSanctionView.Rows[RowCount]["LeaveType_id"] != DBNull.Value)
                            {
                                LeaveTypeId = Convert.ToInt32(dtSanctionView.Rows[RowCount]["LeaveType_id"]);
                            }
                            if (dtSanctionView.Rows[RowCount]["status"] != DBNull.Value)
                            {
                                strLeaveStatus = dtSanctionView.Rows[RowCount]["status"].ToString();
                            }
                            if (dtSanctionView.Rows[RowCount]["IntimationType"] != DBNull.Value)
                            {
                                intimationType = dtSanctionView.Rows[RowCount]["IntimationType"].ToString();
                            }
                            Remarks = txtRemarks.Text.Trim().Replace("'", "''");
                            int YearSettingID = Convert.ToInt16(dtSanctionView.Rows[RowCount]["YearSettings_Id"]);
                            // Added by Gopinath for not allow approval after the applied date crossed  on 15-Feb-2016.
                            string strFromDate = (DateTime.Parse(dtSanctionView.Rows[0]["LeaveFrom"].ToString())).ToString(Session["MDateFormat"].ToString());
                            string strToDate = (DateTime.Parse(dtSanctionView.Rows[0]["LeaveTo"].ToString())).ToString(Session["MDateFormat"].ToString());
                            string strTodaysDate = DateTime.Now.ToString(Session["MDateFormat"].ToString());
                            if (((Convert.ToDateTime(strFromDate) < Convert.ToDateTime(strTodaysDate)) || (Convert.ToDateTime(strToDate) < Convert.ToDateTime(strTodaysDate))) && Session["UserGroupName"].ToString() != "SuperAdmin" && Session["AllowLeaveApprovalPastEntry"].ToString() != "True" && intimationType == "P" && (Status == "Pending" || Status == "Approved" || Status == "Forwarded"))
                            {
                                Message("Leave Approvals should not be done for past days");
                                return;
                            }
                            ViewState["vwReason"] = dtSanctionView.Rows[RowCount]["Reason"].ToString();
                            string strFromdate = string.Empty;
                            for (int RowCount1 = 0; RowCount1 < dtSanctionView.Rows.Count; RowCount1++)
                            {
                                if (dtSanctionView.Rows[RowCount1]["LeaveFrom"] != DBNull.Value)
                                {
                                    strFromdate = dtSanctionView.Rows[RowCount1]["LeaveFrom"].ToString();
                                }
                                if (strMonthValue == "")
                                {
                                    strMonthValue = Convert.ToDateTime(strFromdate).Month.ToString();
                                }
                                else if (strMonthValue != "")
                                {
                                    if (strMonthValue != Convert.ToDateTime(strFromdate).Month.ToString())
                                    {
                                        strCrossDate = "Yes";
                                    }
                                }
                            }
                            if (dtLeaveavailedinMonth.Rows.Count > 0)
                            {
                                if (strCrossDate == "Yes")
                                {
                                    strLeaveavailedinFirstMonth = dtLeaveavailedinMonth.Rows[0]["NumberofDays"].ToString();
                                    strLeaveavailedinSecondMonth = dtLeaveavailedinMonth.Rows[1]["NumberofDays"].ToString();
                                    strLeaveavailedinFirstMonthName = dtLeaveavailedinMonth.Rows[0]["MonthName"].ToString();
                                    strLeaveavailedinSecondMonthName = dtLeaveavailedinMonth.Rows[1]["MonthName"].ToString();
                                }
                                else
                                {
                                    strLeaveavailedinFirstMonth = dtLeaveavailedinMonth.Rows[0]["NumberofDays"].ToString();
                                    strLeaveavailedinFirstMonthName = dtLeaveavailedinMonth.Rows[0]["MonthName"].ToString();
                                }
                            }
                            if (dtSanctionView.Rows[0]["LeaveAvailedMonth"].ToString() != string.Empty)
                            {
                                ViewState["vwLeaveAvailedMonthData"] = dtSanctionView.Rows[RowCount]["LeaveAvailedMonth"].ToString();
                            }
                            else
                            {
                                ViewState["vwLeaveAvailedMonthData"] = "0.0";
                            }
                            if (dtSanctionView.Rows[0]["LeaveAvailedYear"].ToString() != string.Empty)
                            {
                                ViewState["vwLeaveAvailedYearData"] = dtSanctionView.Rows[RowCount]["LeaveAvailedYear"].ToString();
                            }
                            else
                            {
                                ViewState["vwLeaveAvailedYearData"] = "0.0";
                            }
                            dblLeaveAvailedYear = objLeaveApplicationEventData.GetLeaveSummary(DateTime.Parse(strYearSettingsFromdate), DateTime.Parse(strYearSettingsTodate), Employee_Id);
                            strLeaveAvailedYear = dblLeaveAvailedYear.ToString();
                            DataSet ds_ReportingTo = new DataSet();
                            Status = "Approved";
                            string strPermissionStatus = dtSanctionView.Rows[RowCount]["status"].ToString();
                            if (strPermissionStatus == "Pending")
                            {
                                Status = "Forwarded";
                                intCommentsBy = 1;
                            }
                            else if (strPermissionStatus == "Forwarded")
                            {
                                Status = "Approved";
                                intCommentsBy = 2;
                            }
                            //}
                            //if (Status == "Pending")
                            //{
                            //    Status = "Forwarded";
                            //}
                            int intLoginEmpId = 0;
                            // Get the Employee Auto Id who have Logged In from Session
                            intLoginEmpId = Convert.ToInt32(Session["EmpAutoId"]);
                            dsDepartmentMailIds = objLeaveSettingsEventData.GetDepartmentMailIds(Convert.ToInt32(dtSanctionView.Rows[0]["LevelId"]));
                            ViewState["vsStrApprovalToDept"] = dsDepartmentMailIds.Tables[0].Rows[0]["ToMailIds"].ToString();
                            ViewState["vsStrApprovalCCDept"] = dsDepartmentMailIds.Tables[0].Rows[0]["CCMailIds"].ToString();
                            getOrg.GetOrgParentLevels_FromID(Convert.ToInt32(dtSanctionView.Rows[0]["LevelId"]));
                            ds_getOrg = getOrg.GetOrgParentLevels();
                            //int YearSettingID = Convert.ToInt16(dtSanctionView.Rows[0]["YearSettings_Id"]);
                            dsDepartmentMailIds = objLeaveSettingsEventData.GetDepartmentMailIds(Convert.ToInt32(dtSanctionView.Rows[0]["LevelId"]));
                            ViewState["vsStrApprovalToDept"] = dsDepartmentMailIds.Tables[0].Rows[0]["ToMailIds"].ToString();
                            ViewState["vsStrApprovalCCDept"] = dsDepartmentMailIds.Tables[0].Rows[0]["CCMailIds"].ToString();
                            gintCompanyId = Convert.ToInt32(ds_getOrg.Tables[0].Rows[0]["LevelID"].ToString());
                            ViewState["CompanyId"] = gintCompanyId;
                            ds_LeaveSanctionSettings = objLeaveSettingsEventData.GetLeaveSettingsByComId(gintCompanyId);
                            if (ds_LeaveSanctionSettings.Tables.Count > 0)
                            {
                                dt_LeaveSettings = ds_LeaveSanctionSettings.Tables[0];
                            }
                            if (dt_LeaveSettings.Rows.Count > 0)
                            {
                                if (dt_LeaveSettings.Rows[0]["Approval"] != DBNull.Value && dt_LeaveSettings.Rows[0]["Approval"].ToString() != string.Empty)
                                {
                                    if (dt_LeaveSettings.Rows[0]["Approval"].ToString() == "False")
                                    {
                                        // Both First and Second Level Authority Approval
                                        intApproval = 0;
                                    }
                                    else if (dt_LeaveSettings.Rows[0]["Approval"].ToString() == "True")
                                    {
                                        // First or Second Level Authority Approval - Either or one
                                        intApproval = 1;
                                    }
                                    else
                                    {
                                        // Nothing
                                    }
                                }
                                if (dt_LeaveSettings.Rows[0]["ApprovalCC"] != DBNull.Value && dt_LeaveSettings.Rows[0]["ApprovalCC"].ToString() != string.Empty)
                                {
                                    strApprovalCC = dt_LeaveSettings.Rows[0]["ApprovalCC"].ToString();
                                    ViewState["vsStrApprovalCC"] = strApprovalCC;
                                }
                                else
                                {
                                    ViewState["vsStrApprovalCC"] = string.Empty;
                                }
                            }
                            ds_ReportingTo = objPermissionEventData.SelectMailIdOfReportingTo(Employee_Id);
                            if (ds_ReportingTo.Tables[0].Rows.Count > 0)
                            {
                                if (ds_ReportingTo.Tables[0].Rows[0]["EmailId"] != DBNull.Value && ds_ReportingTo.Tables[0].Rows[0]["EmailId"].ToString() != string.Empty)
                                {
                                    intFirstLevelAuthorityId = int.Parse(ds_ReportingTo.Tables[0].Rows[0]["Employee_Id"].ToString());
                                    strEmailIdReportingTo = ds_ReportingTo.Tables[0].Rows[0]["EmailId"].ToString();
                                }
                            }
                            // Gets the Sanctioning Authority Id and Email Id
                            ds_EmailIdOfSanctionAuthority = objPermissionEventData.SelectMailIdOfSanctionAuthority(Employee_Id);
                            if (ds_EmailIdOfSanctionAuthority.Tables[0].Rows.Count > 0)
                            {
                                if (ds_EmailIdOfSanctionAuthority.Tables[0].Rows[0]["EmailId"] != DBNull.Value && ds_EmailIdOfSanctionAuthority.Tables[0].Rows[0]["EmailId"].ToString() != string.Empty)
                                {
                                    intSecondLevelAuthorityId = int.Parse(ds_EmailIdOfSanctionAuthority.Tables[0].Rows[0]["Employee_Id"].ToString());
                                    strEmailIdSanctionAuthority = ds_EmailIdOfSanctionAuthority.Tables[0].Rows[0]["EmailId"].ToString();
                                }
                            }
                            // Check whether the Login Employee Id is whether First or Second Level Sanctioning Authority
                            if (intFirstLevelAuthorityId != intSecondLevelAuthorityId)
                            {
                                if (intLoginEmpId == intFirstLevelAuthorityId)
                                {
                                    intAuthorityLevel = 1;
                                }
                                else if (intLoginEmpId == intSecondLevelAuthorityId)
                                {
                                    intAuthorityLevel = 2;
                                }
                                else
                                {
                                    // Nothing
                                }
                            }
                            else if (intFirstLevelAuthorityId == intSecondLevelAuthorityId)
                            {
                                if (intLoginEmpId == intSecondLevelAuthorityId)
                                {
                                    intAuthorityLevel = 2;
                                }
                                else
                                {
                                    intAuthorityLevel = 3;
                                }
                            }
                            else
                            {
                                intAuthorityLevel = 3;
                            }
                            ViewState["vsCommentsBy"] = intAuthorityLevel;
                            if (strLeaveStatus == "Pending")
                            {
                                Status = "Forwarded";
                                intCommentsBy = 1;
                            }
                            else if (strLeaveStatus == "Forwarded")
                            {
                                Status = "Approved";
                                intCommentsBy = 2;
                            }
                            if (strEmailIdSanctionAuthority == null)
                            {
                                strEmailIdSanctionAuthority = string.Empty;
                            }
                            if (strEmailIdReportingTo == null)
                            {
                                strEmailIdReportingTo = string.Empty;
                            }
                            if (strEmailIdSanctionAuthority == string.Empty && strEmailIdReportingTo == string.Empty && txtApprovalCC.Text == string.Empty && txtApprovalTO.Text == string.Empty)
                            {
                                checkEmail = false;
                            }
                            DataTable dtEmployeeLeaveDetails = new DataTable();
                            dtEmployeeLeaveDetails = dtSanctionView.Copy();
                            if (((DataTable)Session["vSLeaveDetails"]).Columns.Count <= dtEmployeeLeaveDetails.Columns.Count)
                            {
                                dtEmployeeLeaveDetails.Columns.Remove("LeaveApplication_Id");
                                dtEmployeeLeaveDetails.Columns.Remove("Employee_Id");
                                dtEmployeeLeaveDetails.Columns.Remove("Emp_Id");
                                dtEmployeeLeaveDetails.Columns.Remove("IntimationType");
                                dtEmployeeLeaveDetails.Columns.Remove("Employee_Code_Id");
                                dtEmployeeLeaveDetails.Columns.Remove("emailId");
                                dtEmployeeLeaveDetails.Columns.Remove("Employee_FirstName");
                                dtEmployeeLeaveDetails.Columns.Remove("Leave_ApplicationDate");
                                dtEmployeeLeaveDetails.Columns.Remove("LeaveType_Id");
                                dtEmployeeLeaveDetails.Columns.Remove("Reason");
                                dtEmployeeLeaveDetails.Columns.Remove("Status");
                                dtEmployeeLeaveDetails.Columns.Remove("IsDeleted");
                                dtEmployeeLeaveDetails.Columns.Remove("Remarks");
                                dtEmployeeLeaveDetails.Columns.Remove("IsBorrow");
                                dtEmployeeLeaveDetails.Columns.Remove("LevelName");
                                dtEmployeeLeaveDetails.Columns.Remove("levelid");
                                dtEmployeeLeaveDetails.Columns.Remove("CCMail");
                                dtEmployeeLeaveDetails.Columns.Remove("LeaveAvailedMonth");
                                dtEmployeeLeaveDetails.Columns.Remove("LeaveAvailedYear");
                                dtEmployeeLeaveDetails.Columns.Remove("DesignationID");
                                dtEmployeeLeaveDetails.Columns.Add("From");
                                dtEmployeeLeaveDetails.Columns.Remove("CheckedIDs");
                                dtEmployeeLeaveDetails.Columns.Remove("YearSettings_Id");
                                dtEmployeeLeaveDetails.Columns.Add("To");
                                //   dtEmployeeLeaveDetails.Columns[7].SetOrdinal(2);
                                //   dtEmployeeLeaveDetails.Columns[8].SetOrdinal(3);
                                foreach (DataRow dRowEmployeeLeaveDetails in dtEmployeeLeaveDetails.Rows)
                                {
                                    DateTime dtmLeaveFromDate = Convert.ToDateTime(DateTime.Parse(dRowEmployeeLeaveDetails["LeaveFrom"].ToString()).ToShortDateString());
                                    strFromDate = dtmLeaveFromDate.ToString(Session["MDateFormat"].ToString());
                                    dRowEmployeeLeaveDetails["From"] = strFromDate;
                                    DateTime dtmLeaveToDate = Convert.ToDateTime(DateTime.Parse(dRowEmployeeLeaveDetails["LeaveTo"].ToString()).ToShortDateString());
                                    strToDate = dtmLeaveToDate.ToString(Session["MDateFormat"].ToString());
                                    dRowEmployeeLeaveDetails["To"] = strToDate;
                                }
                                dtEmployeeLeaveDetails.Columns.Remove("LeaveFrom");
                                dtEmployeeLeaveDetails.Columns.Remove("LeaveTo");
                                dtEmployeeLeaveDetails.Columns.Remove("InformTo");
                                dtEmployeeLeaveDetails.Columns[0].ColumnName = "Leave Category";
                                dtEmployeeLeaveDetails.Columns[1].ColumnName = "Leave Type";
                                dtEmployeeLeaveDetails.Columns[5].SetOrdinal(2);
                                dtEmployeeLeaveDetails.Columns[6].SetOrdinal(3);
                                //dtEmployeeLeaveDetails.Columns[2].ColumnName = "From";
                                //dtEmployeeLeaveDetails.Columns[3].ColumnName = "To";
                                dtEmployeeLeaveDetails.Columns[4].ColumnName = "Session From";
                                dtEmployeeLeaveDetails.Columns[5].ColumnName = "Session To";
                                dtEmployeeLeaveDetails.Columns[6].ColumnName = "No. of Days";
                                DataRow[] rowList = dtEmployeeLeaveDetails.Select("[Leave Category] = 'LOP'");
                                foreach (DataRow dr in rowList)
                                {
                                    dr["Leave Type"] = "-";
                                }
                            }
                            strHtmlLeaveDetails = buildPage("LeaveDetails", dtEmployeeLeaveDetails);
                            int intLeaveCount = 0;
                            try
                            {
                                //update Leave Application
                                if (strTypeOfLeave == "Leave")
                                {
                                    if (ViewState["StatusBorrow"].ToString() == "False")
                                    {
                                        if (Status == "Approved")
                                        {
                                            objLeaveApplicationEventData.UpdateYearClosureByLeaveSanction(NumberOfDays, LeaveTypeId, Employee_Id, "A", Convert.ToInt32(Session["EmpAutoId"]), YearSettingID);
                                        }
                                    }
                                    if (ViewState["StatusBorrow"].ToString() == "True")
                                    {
                                        DataSet dsRemainingNoOfleaves = new DataSet();
                                        double dblCurrLeave = 0.0;
                                        // if condt needs to be chnaged based on reply, resend
                                        if (ViewState["StatusOnLoad"].ToString() != Status)
                                        {
                                            if (Status == "Approved")
                                            {
                                                //Check other leaves exists before borrow leave
                                                intLeaveCount = objLeaveApplicationEventData.CheckLeaveExistsBeforeBorrow(Leave_FromDate, Leave_ToDate, LeaveTypeId, Employee_Id);
                                                if (intLeaveCount > 0)
                                                {
                                                    boolChkLeave = false;
                                                    //lbl_Error.Text = "Already current year leave applications are available to approve/reject";
                                                    base.Message("Already current year leave applications are available to approve/reject");
                                                    return;
                                                }
                                                else
                                                {
                                                    dsRemainingNoOfleaves = objLeaveApplicationEventData.GetRemainingNumberOfLeaves(Employee_Id, LeaveTypeId, Convert.ToInt32(ViewState["vsLeaveApplication_Id"]), "01/01/1900");
                                                    dsRemainingNoOfleaves.Tables[0].TableName = "Details";
                                                    if (dsRemainingNoOfleaves.Tables.Count > 0)
                                                    {
                                                        if (dsRemainingNoOfleaves.Tables[0].Rows.Count > 0)
                                                        {
                                                            dblCurrLeave = Convert.ToDouble(dsRemainingNoOfleaves.Tables["Details"].Rows[0]["RemainingNoOfLeaves"]);
                                                        }
                                                    }
                                                    if (dblCurrLeave > 0)
                                                    {
                                                        boolChkLeave = false;
                                                        //lbl_Error.Text = "Current year quota available for this leave type";
                                                        base.Message("Current year quota available for this leave type");
                                                        return;
                                                    }
                                                    objLeaveApplicationEventData.UpdateYearClosureByLeaveSanction(NumberOfDays, LeaveTypeId, Employee_Id, "AB", Convert.ToInt32(Session["EmpAutoId"]), YearSettingID);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                throw ex;
                            }
                        }
                        if (boolChkLeave == true)
                        {
                            if (strTypeOfLeave != "Leave")
                            {
                            }
                            objLeaveApplicationEventData.UpdateLeaveApplicationSanction(LeaveApplication_Id, Status, Remarks, Convert.ToInt32(Session["EmpAutoId"]), intimationType);
                        }
                        //common to all status
                        objLeaveApplicationEventData.UpdateLeaveApplicationConversation(LeaveApplication_Id, Status, Convert.ToInt32(ViewState["vsCommentsBy"].ToString()), Remarks, Convert.ToInt32(Session["EmpAutoId"]));
                        //Update Processed Data Flag
                        objLeaveApplicationEventData.UpdateProcessedDataFlag(Employee_Id, Leave_FromDate, Leave_ToDate, 0);
                        if (checkEmail == true)
                        {
                            if (Status == "Approved" || Status == "Forwarded" || Status == "Rejected" || Status == "Resend")
                            {
                                ControlCreation();
                                if (Convert.ToInt32(ConfigurationManager.AppSettings.Get("isRequiredEmail")) == 1)
                                {
                                    SendMail(intFirstLevelAuthorityId, intSecondLevelAuthorityId, strEmailIdReportingTo, strEmailIdSanctionAuthority, EmployeeEamilId, Convert.ToString(ViewState["Employee_code_Id"]), EmployeeName, Status, txtRemarks.Text.Trim().Replace("'", "''"), strLeaveApplicationDate, strNoOfDays, leaveType, levelName, Convert.ToString(ViewState["vsStrApprovalCC"]), intimationType);
                                }
                            }
                        }
                        strMonthValue = string.Empty;
                        strCrossDate = string.Empty;
                        if (checkEmail == true)
                        {
                            string strScript = string.Empty;
                            strScript = strScript + "<script language='javascript'>";
                            strScript = strScript + "alert('Leave Application saved');";
                            strScript = strScript + "RedirectionFunction();";
                            strScript = strScript + "</script>";
                            Page.RegisterStartupScript("AlertPsaved36774", strScript);
                        }
                        else
                        {
                            string strScript = string.Empty;
                            strScript = strScript + "<script language='javascript'>";
                            strScript = strScript + "alert('Leave Application saved,Email not sent');";
                            strScript = strScript + "RedirectionFunction();";
                            strScript = strScript + "</script>";
                            //Dispaly alert messsage.
                            Page.RegisterStartupScript("AlertPAdd3674", strScript);
                        }
                        #endregion
                        //}
                    }
                }
                else
                {
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('Select any entry to change status.');", true);
                    return;
                }
                #endregion
            }
        }
    }
    #endregion
    #region Gridview Events
    //public void chkbox_OnCheckedChanged(object sender, EventArgs e)
    //{
    //    CheckBox chkbox = (CheckBox)sender;
    //    GridViewRow gvrow = (GridViewRow)chkbox.NamingContainer;
    //    SaveCheckedValues();
    //    CheckBox chkSelect = new CheckBox();
    //    CheckBox chkSelectAll = new CheckBox();
    //    int intGridPageSize = gdLeaveSanctionView.PageSize;
    //    int intGridTotalPages = gdLeaveSanctionView.PageCount;
    //    chkSelectAll = (CheckBox)gdLeaveSanctionView.HeaderRow.Cells[0].FindControl("checkall");
    //    if (((CheckBox)sender).Checked == false)
    //    {
    //        chkSelectAll.Checked = false;
    //    }
    //    else
    //    {
    //        if (intCount > 0 && Convert.ToInt32(Session["TotalLeaveApplication_Id"].ToString()) >= intCount && Convert.ToInt32(Session["TotalLeaveApplication_Id"].ToString()) > intGridTotalPages)
    //        {
    //            //Paging is present.
    //            if (intCount <= intGridPageSize)
    //            {
    //                if (Session["LeaveChecked"] != string.Empty && Session["LeaveChecked"] != null)
    //                {
    //                    int Total = Convert.ToInt16(Session["TotalLeaveApplication_Id"]);
    //                    DataTable CheckedItem = (DataTable)Session["LeaveChecked"];
    //                    if (Total == CheckedItem.Rows.Count)
    //                    {
    //                        chkSelectAll.Checked = true;
    //                    }
    //                }
    //            }
    //        }
    //    }
    //}
    //public void gdLeaveSanctionView_CheckAll_CheckedChanged(object sender, EventArgs e)
    //{
    //    CheckBox chkSelect = new CheckBox();
    //    chkSelect = (CheckBox)gdLeaveSanctionView.HeaderRow.Cells[0].FindControl("checkall");
    //    DataTable ChkBoxIDs = new DataTable();
    //    if (chkSelect.Checked == true)
    //    {
    //        GetLeaveApplicationIDsInOtherPagesOfGrid();
    //    }
    //    else
    //    {
    //        Session["LeaveChecked"] = string.Empty;
    //    }
    //    foreach (GridViewRow gr in gdLeaveSanctionView.Rows)
    //    {
    //        chkSelect = (CheckBox)gr.Cells[0].FindControl("chkbox");
    //        chkSelect.Checked = ((CheckBox)sender).Checked;
    //        if (chkSelect.Checked == true)
    //        {
    //            SaveCheckedValues();
    //        }
    //    }
    //}
    protected void gdLeaveSanctionView_PageIndexChanged(object sender, EventArgs e)
    {
        try
        {
            // To display the sorted records in the new page if the Vendor has Sorted the Gridview by clicking any header
            if ((ViewState["SortExpression"]) != null)
            {
                string SortColumn = Convert.ToString(ViewState["SortExpression"]);
                string SortOrder = Convert.ToString(Session["SortOrderLeaveSanction"]);
                SortGrid(SortColumn, SortOrder);
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    protected void gdLeaveSanctionView_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            Label lbl = (Label)e.Row.Cells[1].FindControl("Label1");
            //lbl.ID = "Label1";
            string date1 = (Convert.ToDateTime(lbl.Text)).ToString(Session["MDateFormat"].ToString());
            lbl.Text = date1;
            //e.Row.Cells[1].Controls.Add(lbl);
            Label lbldur = (Label)e.Row.Cells[1].FindControl("Label3");
            //lbldur.ID = "Label3";
            string[] duration = lbldur.Text.Split(" - ".ToCharArray());
            string datedur = (Convert.ToDateTime(duration[0])).ToString(Session["MDateFormat"].ToString());
            string datedur1 = (Convert.ToDateTime(duration[3])).ToString(Session["MDateFormat"].ToString());
            lbldur.Text = datedur + " - " + datedur1;
            //e.Row.Cells[2].Controls.Add(lbldur);
            Label lblStatus = (Label)e.Row.Cells[1].FindControl("Label2");
            if (lblStatus.Text == "Approved")
            {
                lblStatus.Text = rm.GetString("btn_Approved", ci);
            }
            else if (lblStatus.Text == "Forwarded")
            {
                lblStatus.Text = rm.GetString("btn_Forwarded", ci);
            }
            else if (lblStatus.Text == "Pending")
            {
                lblStatus.Text = rm.GetString("btn_Pending", ci);
            }
            else if (lblStatus.Text == "Rejected")
            {
                lblStatus.Text = rm.GetString("btn_Reject", ci);
            }
        }
    }
    protected void gdLeaveSanctionView_Sorting(object sender, GridViewSortEventArgs e)
    {
        ViewState["SortExpression"] = e.SortExpression;
        if (Convert.ToString(Session["SortOrderLeaveSanction"]) == string.Empty)
        {
            Session["SortOrderLeaveSanction"] = "Asc";
        }
        else if (Convert.ToString(Session["SortOrderLeaveSanction"]) == "Asc")
        {
            Session["SortOrderLeaveSanction"] = "Desc";
        }
        else
        {
            Session["SortOrderLeaveSanction"] = "Asc";
        }
        SortGrid(e.SortExpression, Convert.ToString(Session["SortOrderLeaveSanction"]));
    }
    protected void gdLeaveSanctionView_HtmlRowCreated(object sender, ASPxGridViewTableRowEventArgs e)
    {
        if (e.RowType == GridViewRowType.Data)
        {
            source_Language = Session["Session_ActiveLanguage"].ToString();
            rm = new ResourceManager(source_Language, System.Reflection.Assembly.Load("App_GlobalResources"));
            ci = Thread.CurrentThread.CurrentCulture;
            Label lbl = (Label)gdLeaveSanctionView.FindRowCellTemplateControl(e.VisibleIndex, null, "Label1");
            string date1 = (Convert.ToDateTime(lbl.Text)).ToString(Session["MDateFormat"].ToString());
            e.Row.Cells[2].Text = date1;
            string lbldur = Convert.ToString(e.GetValue("Duration"));
            string[] duration = lbldur.Split(" - ".ToCharArray());
            string datedur = (Convert.ToDateTime(duration[0])).ToString(Session["MDateFormat"].ToString());
            string datedur1 = (Convert.ToDateTime(duration[3])).ToString(Session["MDateFormat"].ToString());
            lbldur = datedur + " - " + datedur1;
            //e.Row.Cells[3].Text = lbldur;
            Label lblStatus = (Label)gdLeaveSanctionView.FindRowCellTemplateControl(e.VisibleIndex, null, "Label2");
            if (lblStatus.Text == "Approved")
            {
                lblStatus.Text = rm.GetString("btn_Approved", ci);
            }
            else if (lblStatus.Text == "Forwarded")
            {
                lblStatus.Text = rm.GetString("btn_Forwarded", ci);
            }
            else if (lblStatus.Text == "Pending")
            {
                lblStatus.Text = rm.GetString("btn_Pending", ci);
            }
            else if (lblStatus.Text == "Rejected")
            {
                lblStatus.Text = rm.GetString("btn_Reject", ci);
            }
            //Added by Manjula.P on 25-Apr-2014
            HtmlInputCheckBox cbDeleteThis = (HtmlInputCheckBox)gdLeaveSanctionView.FindRowCellTemplateControl(e.VisibleIndex, null, "chkSelect");
            if (cbDeleteThis != null)
            {
                e.Row.Cells[4].Text = lbldur;
            }
            else
            {
                e.Row.Cells[3].Text = lbldur;
            }
        }
    }
    #endregion
}