using System;
using System.Data;
using System.Configuration;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Mail;
using System.Globalization;
using System.Threading;
using System.Resources;
using System.IO;
using System.Text.RegularExpressions;
/****************************************************************************************************************************
* Project Name    : TimeCheck                    Started Date  : 12-Aug-2007
* Module          : Leave Application            Lbast Modified : 15-May-2009
* Programmer      : Prabakaran.P
* BackUp          :
****************************************************************************************************************************/
public partial class Transactions_TA_UI_Transactions_LeaveApplicationAdd : Base.BasePage
{
    #region ForEastman
    internal enum permissionHeader
    {
        FIRST = 1,
        SECOND = 2,
        THIRD = 3,
        FOURTH = 4,
        FIFTH = 5
    }
    Panel pn = new Panel();
    DataSet prevDs = new DataSet();
    #endregion
    #region VariableDeclaration
    string finalfile = "";
    ResourceManager rm;
    CultureInfo objCultureInfo;
    Cls_CheckUser objCheckUser = new Cls_CheckUser();
    DataSet dsCheckuser = new DataSet();
    EmployeeEventData objEmployeeEventData = new EmployeeEventData();
    LeaveApplicationEventData objLeaveApplicationEventData = new LeaveApplicationEventData();
    LeaveEventData objLeaveEventData = new LeaveEventData();
    PermissionEventData objPermissionEventData = new PermissionEventData();
    HolidayEventData objHoliday = new HolidayEventData();
    SMSNotification objsms = new SMSNotification();
    cls_Common objClassCommon = new cls_Common();
    DataSet dsLeaveType = new DataSet();
    DataSet dsRemainingDays = new DataSet();
    DataSet dsLeaveApplication = new DataSet();
    DataSet dsLeavePolicyDetails = new DataSet();
    DataSet dsSpellCount = new DataSet();
    DataSet dsEmployeeDetails = new DataSet();
    DataSet dsMaxNoOfLeaves = new DataSet();
    DataSet dsEmailIdOfSanctionAuthority = new DataSet();
    DataSet dsEmailIdOfReportingTo = new DataSet();
    DataSet dsYear = new DataSet();
    DataSet dsHolidayDetails = new DataSet();
    string strApplicationDate, strTypeOfLeave, strFromDate, strToDate, strSessionFrom, strSessionTo, strReason, strEmailIdReportingTo, strEmailIdSanctioningAuthority, strEmployeeName, strEmployeeCodeId, strEmpFirstName, strEmpLastName, gstrDateFormat, strFromDateTime, strToDateTime, strlevelName, strDateofJoining;
    DateTime dtCurrentDate;
    int intEmployeeId, intLeaveTypeId, gintCount, intStartYear, intEndYear, intInsertFlag = 0, intHalfDayCount = 0;
    double dblNumberOfDaysAppliedCurrently, dblRemainingLeaveDays_Year;
    int intSuccessiveyear = 0;
    bool blnCheckEmail = true, blnCheckSMS = true;
    DataSet ds = new DataSet();
    int intLeaveApplicationId = 0;
    int LevelID;
    string LeaveApplicationStatus = string.Empty;
    string TimeFormat = string.Empty;
    #endregion
    #region PageLoad.
    protected override void Page_Load(object sender, EventArgs e)
    {
        base.Page_Load(sender, e);
        if (!Page.IsPostBack)
        {
            objClassCommon.menu("LeaveTransaction", "22");
        }
        string strSourceLanguage;
        string strSetAlert = "";

        strSourceLanguage = Convert.ToString(Session["Session_ActiveLanguage"]);
        rm = new ResourceManager(strSourceLanguage, System.Reflection.Assembly.Load("App_GlobalResources"));
        objCultureInfo = Thread.CurrentThread.CurrentCulture;

        grv_LeaveApplication.Styles.CssFilePath = Convert.ToString(Session["GridCSS"]);
        site.SiteMapProvider = Convert.ToString(Session["SiteMapProvider"]);

        #region CommonAlertMessages
        strSetAlert = strSetAlert + "<script language='javascript'>";
        strSetAlert = strSetAlert + "MaxLengthh('" + rm.GetString("Alert_MaximumLengthis", objCultureInfo) + "');";
        strSetAlert = strSetAlert + "SelectEmployee('" + rm.GetString("Alert_SelectanEmployee", objCultureInfo) + "');";
        strSetAlert = strSetAlert + "Emp('" + rm.GetString("Alert_Norecordsfound", objCultureInfo) + "','" + rm.GetString("Alert_Errorinretrivingdetails", objCultureInfo) + "','" + rm.GetString("Select", objCultureInfo) + "','" + rm.GetString("Employee_Others", objCultureInfo) + "');";
        strSetAlert = strSetAlert + "SetAlertMessages('" + rm.GetString("Alert_LeaveType", objCultureInfo) + "','" + rm.GetString("Alert_LeaveRestictHoliday", objCultureInfo) + "','" + rm.GetString("Alert_Fromdate", objCultureInfo) + "','" + rm.GetString("Alert_ToDate", objCultureInfo) + "','" + rm.GetString("Alert_FromSession", objCultureInfo) + "','" + rm.GetString("Alert_ToSession", objCultureInfo) + "','" + rm.GetString("Alert_FillReasons", objCultureInfo) + "','" + rm.GetString("Alert_DayEmpty", objCultureInfo) + "','" + rm.GetString("Alert_DaysZero", objCultureInfo) + "','" + rm.GetString("Alert_RemainingZero", objCultureInfo) + "','" + rm.GetString("Alert_DaysNotExceed", objCultureInfo) + "','" + rm.GetString("InvalidApplicationDate", objCultureInfo) + "','" + rm.GetString("Alert_ConfirmSave", objCultureInfo) + "','" + rm.GetString("Alert_CompOffDaysNotExceed", objCultureInfo) + "');";
        strSetAlert = strSetAlert + "SetAlertMessagesAjax_Leave('" + rm.GetString("Alert_Selectvalidfromsessionandtosession", objCultureInfo) + "','" + rm.GetString("Alert_Halfdayisnotallowed", objCultureInfo) + "','" + rm.GetString("Master_Holiday_Select_Valid_Year", objCultureInfo) + "','" + rm.GetString("Alert_LeaveFromDateshouldnotbegreaterthanLeaveToDate", objCultureInfo) + "','" + rm.GetString("Alert_Leaveshouldnotbeappliedbeforedateofjoining", objCultureInfo) + "','" + rm.GetString("Alert_NoLeavePolicyexistsforthisLeaveFromDateorToDate", objCultureInfo) + "','" + rm.GetString("Alert_Leaveshouldbeappliedapplicableafterdays", objCultureInfo) + "','" + rm.GetString("Alert_YouareselectingHoliday", objCultureInfo) + "','" + rm.GetString("Alert_YouareselectingWeeklyOffinFromdate", objCultureInfo) + "','" + rm.GetString("Alert_YouareselectingWeeklyOffinTodate", objCultureInfo) + "','" + rm.GetString("Alert_YouareselectingWeeklyOff", objCultureInfo) + "','" + rm.GetString("Alert_LeaveApplicationcannotberaisedduringWeeklyOffGlobalHoliday", objCultureInfo) + "','" + rm.GetString("Alert_SelectLeaveandLeaveTypeId", objCultureInfo) + "','" + rm.GetString("Alert_Shiftnotallocated", objCultureInfo) + "','" + rm.GetString("ALert_SelectValidFromDateandToDate", objCultureInfo) + "','" + rm.GetString("Alert_YouhavechoosedafterweeklyOffOneDayAdded", objCultureInfo) + "','" + rm.GetString("ALert_YouhavechoosedBeforeweeklyOffOneDayAdded", objCultureInfo) + "','" + rm.GetString("Alert_YouhaveselectedInterveningweeklyOffGlobalHoliday", objCultureInfo) + "','" + rm.GetString("Alert_DayDeducted", objCultureInfo) + "','" + rm.GetString("Alert_Dayincluded", objCultureInfo) + "','" + rm.GetString("Alert_SelectanEmployee", objCultureInfo) + "','" + rm.GetString("Alert_LOPnotdefined", objCultureInfo) + "','" + rm.GetString("Alert_RestrictedHolidaynotdefined", objCultureInfo) + "','" + rm.GetString("Alert_LeavePolicynotdefined", objCultureInfo) + "','" + rm.GetString("Select_leavefrom_and_todate", objCultureInfo) + "','" + rm.GetString("Alert_Selectleavefromdate", objCultureInfo) + "','" + rm.GetString("Alert_Selectleavetodate", objCultureInfo) + "','" + rm.GetString("Alert_Theleavedurationcrossestheleavepolicy", objCultureInfo) + "');";
        strSetAlert = strSetAlert + "SetAlertCheckDate('" + rm.GetString("Alert_Validdatemonthfourdigit", objCultureInfo) + "','" + rm.GetString("Alert_Invalidyearentry", objCultureInfo) + "','" + rm.GetString("ExceedsSuccessiveDays", objCultureInfo) + "','" + rm.GetString("Alert_Invalidmonthentry", objCultureInfo) + "','" + rm.GetString("Alert_Invaliddateentry", objCultureInfo) + "','" + rm.GetString("Alert_IncorrectdateformatDDMONYYYY", objCultureInfo) + "','" + rm.GetString("Alert_Entertime", objCultureInfo) + "','" + rm.GetString("Alert_Invalidvalueforhours", objCultureInfo) + "','" + rm.GetString("Alert_Invalidvalueforminites", objCultureInfo) + "','" + rm.GetString("Alert_Invalidtimeformat1", objCultureInfo) + "','" + rm.GetString("Alert_PleaseentervalidDateandTime", objCultureInfo) + "','" + rm.GetString("Alert_ValiddatemonthMMDDYYHHMM", objCultureInfo) + "','" + rm.GetString("Alert_ValiddatemonthMMDDYYHHMMTT", objCultureInfo) + "','" + rm.GetString("Alert_PleaseentervalidDateandTime", objCultureInfo) + "','" + rm.GetString("Alert_Invalidvalueforhours", objCultureInfo) + "','" + rm.GetString("Alert_Invalidvalueforminites", objCultureInfo) + "');";
        strSetAlert = strSetAlert + "</script>";
        Page.RegisterStartupScript("SetAlertMessages", strSetAlert);
        #endregion

        LoadStrings(objCultureInfo);
        UserRights();
        dsYear = objClassCommon.GetYearsetting();
        if (dsYear.Tables[0].Rows.Count <= 0)
            MessageWithReplace(rm.GetString("Alert_DefineYearSettinginOrganizationSettings", objCultureInfo), "../Organization Settings/Organization_YearSetting.aspx");
        else
        {
            intStartYear = Convert.ToInt32(dsYear.Tables[0].Rows[0]["StartYear"]);
            intEndYear = Convert.ToInt32(dsYear.Tables[0].Rows[0]["EndYear"]);
            ViewState["YearSettings_Id"] = Convert.ToString(dsYear.Tables[0].Rows[0]["YearSettings_Id"]);
            dsYear.Dispose();
        }
        Hidden1.Value = Convert.ToString(Session["IDateFormat"]);
        //dtCurrentDate = Convert.ToDateTime(System.DateTime.Today.Date.ToShortDateString());
        //lblLeaveApplicationDateData.Text = dtCurrentDate.ToString(Session["MDateFormat"].ToString());
        TimeFormat = Convert.ToString(Session["ITimeFormat"]);
        if(!Page.IsPostBack)
        {
            if (Convert.ToString(TimeFormat) == "HH:mm")
            {
                //dtCurrentDate = Convert.ToDateTime(System.DateTime.Today.Date.ToShortDateString());
                lblLeaveApplicationDateData.Text = DateTime.Now.ToString(Convert.ToString(Session["MDateFormat"]) + " HH:mm");
            }

            else
            {
                lblLeaveApplicationDateData.Text = DateTime.Now.ToString(Convert.ToString(Session["MDateFormat"]) + " hh:mm tt");
            }
        }
    
        if (Session["User"] == null || Convert.ToString(Session["User"]) == "")
            Response.Redirect("../index.aspx");
        Page.RegisterStartupScript("HideBorrow", "<script>hidedivBorrow();</script>");
        Page.RegisterStartupScript("hideLeaveProcess", "<script>hidedivLeaveProcess();</script>");
        ds = objClassCommon.GetSuccessiveYearsetting();
        hdnApplicationYear.Value = Convert.ToString(ViewState["YearSettings_Id"]);
        if (Convert.ToString(Session["UserGroupName"]) == "SuperAdmin" || Convert.ToString(Session["IndividualUsers"]) != "True")
        {
            divEmployees.Visible = false;
            divAdmin.Visible = true;
            if (ds.Tables.Count > 0)
            {
                if (ds.Tables[0].Rows.Count > 0)
                {
                    hdnSuccessiveYear.Value = Convert.ToString(ds.Tables[0].Rows[0][0]);
                    rbtnSuccessiveYear.Enabled = true;
                }
                else
                    rbtnSuccessiveYear.Enabled = false;
            }
        }
        else
        {
            divEmployees.Visible = true;
            divAdmin.Visible = false;
            if (ds.Tables.Count > 0)
            {
                if (ds.Tables[0].Rows.Count > 0)
                {
                    hdnSuccessiveYear.Value = Convert.ToString(ds.Tables[0].Rows[0][0]);
                    if (rbtnCurrentYear.Checked == true)
                        hdnApplicationYear.Value = Convert.ToString(ViewState["YearSettings_Id"]);
                    else if (rbtnSuccessiveYear.Checked == true)
                        hdnSuccessiveYear.Value = Convert.ToString(ds.Tables[0].Rows[0][0]);
                    rbtnSuccessiveYear.Enabled = true;
                }
                else
                    rbtnSuccessiveYear.Enabled = false;
            }
            else
                rbtnSuccessiveYear.Enabled = false;
            hdnEmployeeCodeId.Value =Convert.ToString(txt_EmployeeId.Text);
            hdnEmployeeId.Value = Convert.ToString(Session["EmpAutoId"]);
            
            GetEmployeeName();

            string strScript = "";
            strScript = strScript + "<script language='javascript'>";
            strScript = strScript + "OpenWindowLeaveQuota(" + intEmployeeId + ");";
            strScript = strScript + "</script>";
            Page.RegisterStartupScript("AlertLeavePolicyYear", strScript);
        }
        btnAdd.Focus();
        if (!IsPostBack)
        {
            txtLeaveStartDate.Text = (Convert.ToDateTime(objClassCommon.CurrentMonthStartDate())).ToString(Convert.ToString(Session["MDateFormat"]));
            txtLeaveEndDate.Text = (Convert.ToDateTime(System.DateTime.Now.ToShortDateString())).ToString(Convert.ToString(Session["MDateFormat"]));
        }
        #region Eastman
        previewhead.Style.Add("display", "none");
        preview.Style.Add("display", "none");
        divclear.Style.Add("display", "none");
        divline.Style.Add("display", "none");
        if (Convert.ToString(Session["packageID"]) != "")
            if (Convert.ToString(Session["packageID"]) == "155") /*EastMan*/
            {
                if (Convert.ToString(Session["IndividualUsers"]) != "True")
                {
                    previewhead.Style.Add("display", "");
                    preview.Style.Add("display", "");
                    divclear.Style.Add("display", "");
                    divline.Style.Add("display", "");
                }
            }
        #endregion
    }
    #endregion
    #region Employee Name.
    public void GetEmployeeName()
    {
        if (Session["user"] == null || Convert.ToString(Session["user"]) == "")
        {
            Response.Redirect("../Index.aspx");
        }
        else
        {
            lblEmployeeIdData.Text = Convert.ToString(Session["EmployeeCodeId"]);
            hfEmployeeCode.Value = Convert.ToString(Session["EmployeeCodeId"]);
            intEmployeeId = Convert.ToInt32(Session["EmpAutoId"]);
            DataSet ds_EmployeeDetails = new DataSet();
            ds_EmployeeDetails = objEmployeeEventData.Select_EmployeeDetailsNewbyId(intEmployeeId);

            if (ds_EmployeeDetails.Tables.Count > 0)
                if (ds_EmployeeDetails.Tables[0].Rows.Count > 0)
                {
                    strEmpFirstName = Convert.ToString(ds_EmployeeDetails.Tables[0].Rows[0]["Employee_FirstName"]);
                    strEmpLastName = Convert.ToString(ds_EmployeeDetails.Tables[0].Rows[0]["Employee_LastName"]);
                    lblEmployeeNameData.Text = strEmpFirstName + " " + strEmpLastName;

                    lblLeaveApplicationDateData.Text = Convert.ToString(Session["CurrentCountryDatetime"]);
                    
                }
        }
    }
    #endregion
    #region Leave Application Save function.
    protected void btn_add_Click(object sender, EventArgs e)
    {
        if (Page.IsValid == true)
        {
            string hostUrl = Request.Url.Scheme + "://" + Request.Url.Host;
            gstrDateFormat = Convert.ToString(Session["MDateFormat"]);


            //strApplicationDate = objClassCommon.DateConvertion(gstrDateFormat, lblLeaveApplicationDateData.Text);
            //strApplicationDate = DateTime.Parse(strApplicationDate).ToShortDateString();

            //LeaveApplication UTC Timezone Convertsion Application Date by Maria Prasanth on 06-Jan-2024
            String EmployeeID = Convert.ToString(txt_EmployeeId.Text);
            org_levelsEventData getUtcEmployeeCheck = new org_levelsEventData();
            DataSet ds_UTC = new DataSet();
            ds_UTC = getUtcEmployeeCheck.GetUTCTimeZoneEmployeeCheck(EmployeeID);
            int Counts = ds_UTC.Tables[0].Rows.Count;
            //String UTC = Convert.ToString(Session["TimezoneId"]);

            //TimeZoneName,TimeZoneDesc,HoursToBeAdded,MinToBeAdded TimezoneId Created Maria Prasanth on 06-Dec-2024

            if (Counts != 0)
            {
                Session["TimezoneId"] = ds_UTC.Tables[0].Rows[0]["TimezoneId"].ToString();
                Session["TimeZoneName"] = ds_UTC.Tables[0].Rows[0]["TimeZoneName"].ToString();
                Session["TimeZoneDesc"] = ds_UTC.Tables[0].Rows[0]["TimeZoneDesc"].ToString();
                Session["HoursToBeAdded"] = ds_UTC.Tables[0].Rows[0]["HoursToBeAdded"].ToString();
                Session["MinToBeAdded"] = ds_UTC.Tables[0].Rows[0]["MinToBeAdded"].ToString();

                //var dt = DateTime.UtcNow;
                //var tz = TimeZoneInfo.FindSystemTimeZoneById(Convert.ToString(Session["TimeZoneName"]) + " Standard Time");
                //var DateTimeForCountry = TimeZoneInfo.ConvertTimeFromUtc(dt, tz);

                DateTime ConvertUTCTime = new DateTime();
                int hours = Convert.ToInt32(ds_UTC.Tables[0].Rows[0]["HoursToBeAdded"]);
                int Minutes = Convert.ToInt32(ds_UTC.Tables[0].Rows[0]["MinToBeAdded"]);
                ConvertUTCTime = objClassCommon.TimezoneGetDateTime(hours, Minutes);

                //strApplicationDate = Convert.ToString(ConvertUTCTime);
            }

            strApplicationDate = Convert.ToDateTime(Session["CurrentCountryDatetime"]).ToString();

            ViewState["vsApplicationDate"] = strApplicationDate;
            strFromDate = objClassCommon.DateConvertion(gstrDateFormat, txtFromDate.Text);
            strFromDate = DateTime.Parse(strFromDate).ToShortDateString();
            ViewState["vsFromdate"] = strFromDate;
            strToDate = objClassCommon.DateConvertion(gstrDateFormat, txtToDate.Text);
            strToDate = DateTime.Parse(strToDate).ToShortDateString();
            ViewState["vsTodate"] = strToDate;
            ViewState["vsReason"] = Convert.ToString(txtReason.Text);
            strSessionFrom = ddl_SessionFrom.SelectedValue;
            strSessionTo = ddl_SessionTo.SelectedValue;
            int intLeaveStartYear = DateTime.Parse(strFromDate).Year;
            int intLeaveEndYear = DateTime.Parse(strToDate).Year;
            intSuccessiveyear = (rbtnCurrentYear.Checked == true) ? 0 : (rbtnSuccessiveYear.Checked == true) ? 1 : 0;
            if (hdnEmployeeId.Value == "")
            {
                intInsertFlag = -1;
                ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("Alert_SelectanEmployee", objCultureInfo) + "');", true);
                ddl_Type.SelectedIndex = 0;
                return;
            }
            dsEmployeeDetails = objLeaveApplicationEventData.GetEmployeeDetails(Convert.ToInt32(hdnEmployeeId.Value));
            if (dsEmployeeDetails.Tables.Count > 0)
            {
                if (dsEmployeeDetails.Tables[0].Rows.Count > 0)
                {
                    strEmpFirstName = Convert.ToString(dsEmployeeDetails.Tables[0].Rows[0]["Employee_FirstName"]);
                    strEmpLastName = Convert.ToString(dsEmployeeDetails.Tables[0].Rows[0]["Employee_LastName"]);
                    strEmployeeCodeId = Convert.ToString(dsEmployeeDetails.Tables[0].Rows[0]["Employee_Code_Id"]);
                    ViewState["vsEmployeeID"] = strEmployeeCodeId;
                    strEmployeeName = strEmpFirstName + " " + strEmpLastName;
                    ViewState["vsEmployeeName"] = strEmployeeName;
                    strlevelName = Convert.ToString(dsEmployeeDetails.Tables[0].Rows[0]["levelName"]);
                    ViewState["vslevelName"] = strlevelName;
                    strDateofJoining = Convert.ToString(dsEmployeeDetails.Tables[0].Rows[0]["DateOfJoining"]);
                    ViewState["vsDateofJoining"] = strDateofJoining;
                }
                else
                {
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("lblSelectEmployee", objCultureInfo) + "');", true);
                    ddl_Type.SelectedIndex = 0;
                    return;
                }
            }
            else
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("lblSelectEmployee", objCultureInfo) + "');", true);
                ddl_Type.SelectedIndex = 0;
                return;
            }
            if (ddl_Type.SelectedValue == "Comp Off")
            {
                if (Convert.ToInt32(dsEmployeeDetails.Tables[0].Rows[0]["CompOff_Eligible"]) == 0)
                {
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("Msg_NoCompOff", objCultureInfo) + "');", true);
                    intInsertFlag = -1;
                    ddl_Type.SelectedIndex = 0;
                    return;
                }
            }
            else if (ddl_Type.SelectedValue == "ESI")
            {
                if (Convert.ToInt32(dsEmployeeDetails.Tables[0].Rows[0]["ESI_Eligible"]) == 0)
                {
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("Msg_NoESI", objCultureInfo) + "');", true);
                    intInsertFlag = -1;
                    ddl_Type.SelectedIndex = 0;
                    return;
                }
            }
            else if (hdnTxtLeaveTypeId.Value == "")
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("Msg_SelLeaveType", objCultureInfo) + "');", true);
                intInsertFlag = -1;
                ddl_Type.SelectedIndex = 0;
                return;
            }
            dblNumberOfDaysAppliedCurrently = Convert.ToDouble(hdnNumberofDaysApplied.Value);
            ViewState["vsNumberOfDaysApplied"] = dblNumberOfDaysAppliedCurrently;
            if (dblNumberOfDaysAppliedCurrently <= 0)
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("Msg_DaysShouldGreater", objCultureInfo) + "');", true);
                intInsertFlag = -1;
                ddl_Type.SelectedIndex = 0;
                return;
            }
            if (hdnFURequired.Value != null && hdnFURequired.Value != "" && hdnFURequired.Value == "1")
            {
                {
                    bool Flag = LeaveMedicalCertificateFileUpload();
                    if (Flag == false) return;
                }
                //Tajmeel client point
                //if (hdLeaveSelectedText.Value.ToString() == "BL")
                //{
                //    DataSet dsBL = new DataSet();
                //    dsBL = objLeaveApplicationEventData.ValidateBLLeavetype(Convert.ToInt32(ViewState["YearSettings_Id"]), strUAEType, Convert.ToInt32(hdnEmployeeId.Value));
                //    if (dsBL.Tables.Count > 0)
                //    {
                //        if (dsBL.Tables[0].Rows.Count > 0)
                //        {
                //            int balanceBL = Convert.ToInt32(dsBL.Tables[0].Rows[0]["balance"]);
                //            if (dblNumberOfDaysAppliedCurrently > balanceBL)
                //            {
                //                ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('Balance Leave for " + strUAEType + " is: " + balanceBL.ToString() + ". So you can apply only " + balanceBL.ToString() + " day(s) leave using " + strUAEType + " option');", true);
                //                intInsertFlag = -1;
                //                ddl_Type.SelectedIndex = 0;
                //                return;
                //            }
                //        }
                //    }
                //}
            }
            if (ddl_Type.SelectedValue != "Comp Off" && ddl_Type.SelectedValue != "ESI")
            {
                dblRemainingLeaveDays_Year = double.Parse(Convert.ToString(hdnleaveRemaining.Value));
                #region Eastman
                if (Convert.ToString(Session["packageID"]) != "")
                    if (Convert.ToString(Session["packageID"]) == "155") /*EastMan*/
                    {
                        DataSet dsTotalLeaveDays = new DataSet();
                        dsTotalLeaveDays = objLeaveApplicationEventData.GetTotalLeavesAvailedDetails_Employee(Convert.ToInt64(hdnEmployeeId.Value));
                        if (dsTotalLeaveDays.Tables.Count > 0)
                        {
                            if (dsTotalLeaveDays.Tables[0].Rows.Count > 0)
                            {
                                ViewState["vsLeaveBal"] = Convert.ToDecimal(dsTotalLeaveDays.Tables[0].Rows[0]["LeaveBal"]);
                                ViewState["vsAvailedLeave"] = Convert.ToDecimal(dsTotalLeaveDays.Tables[0].Rows[0]["EarnedLeave"]);
                                ViewState["vsAvailedLOPLeave"] = Convert.ToDecimal(dsTotalLeaveDays.Tables[0].Rows[0]["LOP"]);
                                ViewState["vsTotalLeaveTaken"] = Convert.ToDecimal(dsTotalLeaveDays.Tables[0].Rows[0]["LeaveTaken"]);
                                ViewState["vsWaiveoff"] = Convert.ToDecimal(dsTotalLeaveDays.Tables[0].Rows[0]["WaiveOff"]);
                                ViewState["vsConcernName"] = Convert.ToString(dsTotalLeaveDays.Tables[0].Rows[0]["ConcernName"]);
                            }
                            else
                                AssignDefaultLeaveValues();
                        }
                        else
                            AssignDefaultLeaveValues();
                    }
                #endregion
                if (dblRemainingLeaveDays_Year - double.Parse(hdnNumberofDaysApplied.Value) < 0)
                {
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("Msg_NoOfdayslessToRemining", objCultureInfo) + "');", true);
                    intInsertFlag = -1;
                    return;
                }
                if (ddl_Type.SelectedValue != "Restricted Holiday")
                {
                    dsLeavePolicyDetails = objLeaveApplicationEventData.GetLeavePolicyDetailsLeaveApplication(Convert.ToInt32(hdnEmployeeId.Value), Convert.ToInt32(hdnTxtLeaveTypeId.Value), DateTime.Parse(strFromDate), DateTime.Parse(strToDate));
                    if (dsLeavePolicyDetails.Tables[0].Rows.Count > 0)
                    {
                        if (ddl_Type.SelectedValue == "LOP")
                        {
                            if (dblRemainingLeaveDays_Year - double.Parse(hdnNumberofDaysApplied.Value) >= 0)
                                intInsertFlag = 0;
                            else
                            {
                                intInsertFlag = -1;
                                ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("Msg_exceedSpell", objCultureInfo) + "');", true);
                            }
                        }
                        else
                        {
                            if (Convert.ToDouble(dsLeavePolicyDetails.Tables[0].Rows[0]["Eligible"]) - double.Parse(hdnNumberofDaysApplied.Value) - double.Parse(hdnAvailedLeave.Value) >= 0)
                            {
                                if (Convert.ToInt32(dsLeavePolicyDetails.Tables[0].Rows[0]["Eligible"]) != 0)
                                {
                                    if (double.Parse(hdnNumberofDaysApplied.Value) <= Convert.ToDouble(dsLeavePolicyDetails.Tables[0].Rows[0]["Eligible"]) - double.Parse(hdnAvailedLeave.Value))
                                    {
                                        //As per the configuration, leave should be allowed to take only configured man day in a single days.
                                        if (Convert.ToInt32(dsLeavePolicyDetails.Tables[0].Rows[0]["MaxDays_Avail"]) != 0)
                                        {
                                            if (dblNumberOfDaysAppliedCurrently <= Convert.ToDouble(dsLeavePolicyDetails.Tables[0].Rows[0]["MaxDays_Avail"]))
                                            {
                                                //int appliedAlready_Prev = 0;
                                                //int appliedAlready_PrevHalf = 0;
                                                //int appliedAlready_Next = 0;
                                                //int appliedAlready_NextHalf = 0;
                                                //appliedAlready_Prev = objLeaveApplicationEventData.CheckLeaveApplication(Convert.ToInt32(hdnEmployeeId.Value), DateTime.Parse(strFromDate).AddDays(-1).ToString(), DateTime.Parse(strFromDate).AddDays(-1).ToString());
                                                //appliedAlready_PrevHalf = objLeaveApplicationEventData.CheckHalfDayLeave(Convert.ToInt32(hdnEmployeeId.Value), DateTime.Parse(strFromDate).AddDays(-1).ToString(), DateTime.Parse(strFromDate).AddDays(-1).ToString(), strSessionFrom, strSessionTo);
                                                //if (appliedAlready_Prev != 0 || appliedAlready_PrevHalf != 0)
                                                //{
                                                //    ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("Msg_AlreadyApplied", objCultureInfo) + "');", true);
                                                //    ddl_Type.SelectedIndex = 0;
                                                //    return;
                                                //}
                                                //else
                                                //{
                                                //    appliedAlready_Next = objLeaveApplicationEventData.CheckLeaveApplication(Convert.ToInt32(hdnEmployeeId.Value), DateTime.Parse(strFromDate).AddDays(1).ToString(), DateTime.Parse(strFromDate).AddDays(1).ToString());
                                                //    appliedAlready_NextHalf = objLeaveApplicationEventData.CheckHalfDayLeave(Convert.ToInt32(hdnEmployeeId.Value), DateTime.Parse(strFromDate).AddDays(1).ToString(), DateTime.Parse(strFromDate).AddDays(1).ToString(), strSessionFrom, strSessionTo);
                                                //    if (appliedAlready_Next != 0 || appliedAlready_NextHalf != 0)
                                                //    {
                                                //        ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("Msg_AlreadyApplied", objCultureInfo) + "');", true);
                                                //        ddl_Type.SelectedIndex = 0;
                                                //        return;
                                                //    }
                                                //    else
                                                //    {
                                                //        intInsertFlag = 0;
                                                //    }
                                                //}

                                                intInsertFlag = 0;
                                            }
                                            else
                                            {
                                                intInsertFlag = -1;
                                                ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("Msg_Maxdaysexceed", objCultureInfo) + "');", true);
                                                ddl_Type.SelectedIndex = 0;
                                                return;
                                            }
                                        }
                                    }
                                    else
                                    {
                                        intInsertFlag = -1;
                                        ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("Msg_Maxdaysexceed", objCultureInfo) + "');", true);
                                        ddl_Type.SelectedIndex = 0;
                                        return;
                                    }
                                }
                                //while working for Vaighai, they required maxdays per spell validation. we did correction in procedure. so the below coding enable is not required

                                //if (Convert.ToInt32(dsLeavePolicyDetails.Tables[0].Rows[0]["MaxDays_Avail"]) != 0)
                                //{
                                //    if (dblNumberOfDaysAppliedCurrently <= Convert.ToDouble(dsLeavePolicyDetails.Tables[0].Rows[0]["MaxDays_Avail"]))
                                //        intInsertFlag = 0;
                                //    else
                                //    {
                                //        intInsertFlag = -1;
                                //        ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("Msg_Maxdaysexceed", objCultureInfo) + "');", true);
                                //        ddl_Type.SelectedIndex = 0;
                                //        return;
                                //    }
                                //}
                                if (dsLeavePolicyDetails.Tables[0].Rows[0]["MinDays_Avail"] != DBNull.Value || Convert.ToString(dsLeavePolicyDetails.Tables[0].Rows[0]["MinDays_Avail"]) != "" || Convert.ToString(dsLeavePolicyDetails.Tables[0].Rows[0]["MinDays_Avail"]) != "0")
                                {
                                    if (dblNumberOfDaysAppliedCurrently >= Convert.ToDouble(dsLeavePolicyDetails.Tables[0].Rows[0]["MinDays_Avail"]))
                                        intInsertFlag = 0;
                                    else
                                    {
                                        intInsertFlag = -1;
                                        ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("Msg_MinDayslimit", objCultureInfo) + "');", true);
                                        ddl_Type.SelectedIndex = 0;
                                        return;
                                    }
                                }
                                if (Convert.ToInt32(dsLeavePolicyDetails.Tables[0].Rows[0]["Spells"]) != 0)
                                {
                                    dsSpellCount = objLeaveApplicationEventData.GetSpellCountByLeaveType(Convert.ToInt32(hdnEmployeeId.Value), Convert.ToInt32(hdnTxtLeaveTypeId.Value));
                                    if (Convert.ToInt32(dsSpellCount.Tables[0].Rows[0]["SpellCount"]) < Convert.ToInt32(dsLeavePolicyDetails.Tables[0].Rows[0]["Spells"]))
                                    {
                                    }
                                    else
                                    {
                                        intInsertFlag = -1;
                                        ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("Msg_exceedSpell", objCultureInfo) + "');", true);
                                        ddl_Type.SelectedIndex = 0;
                                        return;
                                    }
                                }
                                else
                                {
                                    intInsertFlag = 0;
                                }
                            }
                            else
                            {
                                intInsertFlag = -1;
                                ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("Msg_exceedLeave", objCultureInfo) + "');", true);
                                ddl_Type.SelectedIndex = 0;
                            }
                        }
                    }
                    else
                    {
                        intInsertFlag = -1;
                        ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("Msg_NoPolicyLeave", objCultureInfo) + "');", true);
                        ddl_Type.SelectedIndex = 0;
                        return;
                    }
                }
                else if (ddl_Type.SelectedIndex == 2)
                {
                    int HolidayID = Convert.ToInt32(hdnTxtLeaveTypeId.Value);
                    string UserGroupName = string.Empty;
                    dsHolidayDetails = objHoliday.SelectHolidayDetailsById(HolidayID, UserGroupName, Convert.ToInt32(ViewState["YearSettings_Id"]));
                    if (dsHolidayDetails.Tables[0].Rows.Count > 0)
                    {
                        string HolidayFromDate = Convert.ToString(dsHolidayDetails.Tables[0].Rows[0]["Holiday_FromDate"]);
                        string HolidayToDate = Convert.ToString(dsHolidayDetails.Tables[0].Rows[0]["Holiday_ToDate"]);
                        if (DateTime.Parse(strFromDate) >= DateTime.Parse(HolidayFromDate) && DateTime.Parse(strFromDate) <= DateTime.Parse(HolidayToDate))
                        {
                            if (DateTime.Parse(strToDate) >= DateTime.Parse(HolidayFromDate) && DateTime.Parse(strToDate) <= DateTime.Parse(HolidayToDate))
                            {
                                if (dblRemainingLeaveDays_Year - double.Parse(hdnNumberofDaysApplied.Value) >= 0)
                                {
                                    intInsertFlag = 0;
                                    CheckRestrictedHolidayCount();
                                }
                                else
                                {
                                    intInsertFlag = -1;
                                    ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("Msg_exceedRestrictHoliday", objCultureInfo) + "');", true);
                                }
                            }
                            else
                            {
                                intInsertFlag = -1;
                                ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("Msg_SelectHolidayToDate", objCultureInfo) + "');", true);
                            }
                        }
                        else
                        {
                            intInsertFlag = -1;
                            ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("Msg_SelectValidHoliday", objCultureInfo) + "');", true);
                        }
                    }
                }
            }
            int intcount = 0;
            DataSet dsChecking = new DataSet();
            DataSet dsCheck = new DataSet();
            DataSet dsShiftId = new DataSet();
            DateTime dtPermissionDate = new DateTime();
            DateTime dtPermissionFromTime = new DateTime();
            DateTime dtPermissionToTime = new DateTime();
            int intShiftId;
            string strPermissionStatus = string.Empty;
            DataSet dsLeavePolicy = new DataSet();
            dsLeavePolicy = objPermissionEventData.GetMaxNoOfHours_ByLeavePolicy(Convert.ToInt32(hdnEmployeeId.Value));
            if (dsLeavePolicy.Tables[0].Rows.Count > 0)
            {
                if (Convert.ToString(dsLeavePolicy.Tables[0].Rows[0]["PermissionBeforeLeave"]) == "False")
                {
                    dsChecking = objLeaveApplicationEventData.CheckLeaveBeforeAfterWithPermission(DateTime.Parse(strFromDate).ToShortDateString(), DateTime.Parse(strToDate).ToShortDateString(), "LeaveAfterPermission", Convert.ToInt32(hdnEmployeeId.Value));
                    if (dsChecking.Tables.Count > 0)
                    {
                        if (dsChecking.Tables[0].Rows.Count > 0)
                        {
                            dtPermissionDate = Convert.ToDateTime(dsChecking.Tables[0].Rows[0]["permission_Date"]);
                            dtPermissionFromTime = Convert.ToDateTime(dsChecking.Tables[0].Rows[0]["Permission_FromTime"]);
                            dtPermissionToTime = Convert.ToDateTime(dsChecking.Tables[0].Rows[0]["Permission_ToTime"]);
                            dsShiftId = objPermissionEventData.GetShiftID(strEmployeeCodeId, dtPermissionDate.Year, dtPermissionDate.Month, dtPermissionDate.Day);
                            intShiftId = Convert.ToInt32(dsShiftId.Tables[0].Rows[0][0]);
                            string StatusPermissionDate = dtPermissionDate.ToShortDateString();
                            strPermissionStatus = PermissionStatusonShift(StatusPermissionDate, intShiftId, dtPermissionFromTime, dtPermissionToTime);
                            if (strPermissionStatus != "First Half")
                            {
                                if (Convert.ToString(ddl_SessionFrom.SelectedValue) == "First half")
                                {
                                    Message(rm.GetString("Msg_LeaveAfterPermission", objCultureInfo));
                                    return;
                                }
                            }
                        }
                    }
                }
            }
            if (dsLeavePolicy.Tables[0].Rows.Count > 0)
            {
                if (Convert.ToString(dsLeavePolicy.Tables[0].Rows[0]["PermissionAfterLeave"]) == "False")
                {
                    dsChecking = objLeaveApplicationEventData.CheckLeaveBeforeAfterWithPermission(DateTime.Parse(strFromDate).ToShortDateString(), DateTime.Parse(strToDate).ToShortDateString(), "LeaveBeforePermission", Convert.ToInt32(hdnEmployeeId.Value));
                    if (dsChecking.Tables.Count > 0)
                    {
                        if (dsChecking.Tables[0].Rows.Count > 0)
                        {
                            dtPermissionDate = Convert.ToDateTime(dsChecking.Tables[0].Rows[0]["permission_Date"]);
                            dtPermissionFromTime = Convert.ToDateTime(dsChecking.Tables[0].Rows[0]["Permission_FromTime"]);
                            dtPermissionToTime = Convert.ToDateTime(dsChecking.Tables[0].Rows[0]["Permission_ToTime"]);
                            dsShiftId = objPermissionEventData.GetShiftID(strEmployeeCodeId, dtPermissionDate.Year, dtPermissionDate.Month, dtPermissionDate.Day);
                            intShiftId = Convert.ToInt32(dsShiftId.Tables[0].Rows[0][0]);
                            string StatusPermissionDate = dtPermissionDate.ToShortDateString();
                            strPermissionStatus = PermissionStatusonShift(StatusPermissionDate, intShiftId, dtPermissionFromTime, dtPermissionToTime);
                            if (strPermissionStatus == "First Half")
                            {
                                if (strFromDate == strToDate)
                                {
                                    if (Convert.ToString(ddl_SessionFrom.SelectedValue) == "First half" && Convert.ToString(ddl_SessionTo.SelectedValue) == "First half")
                                    {
                                    }
                                    else
                                    {
                                        Message(rm.GetString("Msg_LeaveBeforePermission", objCultureInfo));
                                        return;
                                    }
                                }
                                else
                                {
                                    if (Convert.ToString(ddl_SessionTo.SelectedValue) != "First half")
                                    {
                                        Message(rm.GetString("Msg_LeaveBeforePermission", objCultureInfo));
                                        return;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            DataSet dsCheckLeave = new DataSet();
            dsCheckLeave = objLeaveApplicationEventData.CheckLeaveBeforeAfterWithPermission(DateTime.Parse(strFromDate).ToShortDateString(), DateTime.Parse(strToDate).ToShortDateString(), "LeaveOnPermission", Convert.ToInt32(hdnEmployeeId.Value));
            if (dsCheckLeave.Tables.Count > 0)
            {
                if (dsCheckLeave.Tables[0].Rows.Count > 0)
                {
                    Message(rm.GetString("Msg_PermissionApplied", objCultureInfo));
                    return;
                }
            }
            if (intInsertFlag == 0)
            {
                int leaveTypeID = 0;
                if (hdnTxtLeaveTypeId != null)
                {
                    leaveTypeID = Convert.ToInt32(hdnTxtLeaveTypeId.Value);
                }
                intcount = objLeaveApplicationEventData.CheckLeaveApplication(Convert.ToInt32(hdnEmployeeId.Value), strFromDate, strToDate, leaveTypeID);
                intHalfDayCount = objLeaveApplicationEventData.CheckHalfDayLeave(Convert.ToInt32(hdnEmployeeId.Value), strFromDate, strToDate, strSessionFrom, strSessionTo);
                int PermissionCount = 0;
                PermissionCount = objLeaveApplicationEventData.CheckLeaveWithPermission(strFromDate, strToDate, Convert.ToInt32(hdnEmployeeId.Value));
                if (PermissionCount > 0)
                {
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("Msg_PermissionappliedDates", objCultureInfo) + "');", true);
                    return;
                }
                if (intcount == 0 || intHalfDayCount == 0)
                {
                    intEmployeeId = Convert.ToInt32(hdnEmployeeId.Value);
                    if (ddl_Type.SelectedValue == "Comp Off" || ddl_Type.SelectedValue == "ESI")
                    {
                        intLeaveTypeId = 0;
                    }
                    else
                    {
                        intLeaveTypeId = Convert.ToInt32(hdnTxtLeaveTypeId.Value);
                    }
                    strTypeOfLeave = ddl_Type.SelectedValue;
                    strReason = txtReason.Text.Trim().Replace("'", "''");
                    int intIsBorrow = 0;
                    if (chkBorrowLeave.Checked == true)
                    {
                        intIsBorrow = 1;
                    }
                    string strLeaveStatus = string.Empty;
                    string strLeaveStatusNew = string.Empty;
                    int leaveSanctionExists = 0;
                    int approvalSettingsPageExists = 0;
                    leaveSanctionExists = objClassCommon.CheckPageExistsInLicense(248);
                    //Checking grade module is available or not and changed the id value from 110 to 228
                    approvalSettingsPageExists = objClassCommon.CheckPageExistsInLicense(228);
                    if (leaveSanctionExists == 1)
                    {
                        if (approvalSettingsPageExists == 1)
                        {
                            int intCompanyId = base.GetCompanyId(intEmployeeId);
                            DataSet dsApprovalSettings = new DataSet();
                            ShiftEvenData objShift = new ShiftEvenData();
                            dsApprovalSettings = objShift.SelectApprovalSettings(intCompanyId);
                            if (dsApprovalSettings != null)
                            {
                                if (dsApprovalSettings.Tables.Count > 0)
                                {
                                    if (dsApprovalSettings.Tables[0].Rows.Count > 0)
                                    {
                                        if (Convert.ToBoolean(dsApprovalSettings.Tables[0].Rows[0]["LeaveSanction"]) == false)
                                        {
                                            strLeaveStatus = "Approved";
                                        }
                                        else
                                        {
                                            strLeaveStatusNew = objShift.GetApprovalStatus(Convert.ToInt32(Session["EmpAutoID"]), Convert.ToString(hdnEmployeeId.Value), Convert.ToBoolean(Session["ReportsBasedOn"]));
                                            if (strLeaveStatusNew != string.Empty && strLeaveStatusNew != null)
                                            {
                                                strLeaveStatus = strLeaveStatusNew;
                                            }
                                        }
                                    }
                                    else
                                    {
                                        ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("Msg_ApprovalSettings", objCultureInfo) + "');", true);
                                        return;
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        strLeaveStatus = "Approved";
                    }
                    DataSet dsLeaveApp = new DataSet();
                    string strEmployeeEmailId = string.Empty;
                    DataSet dsYearSettingsid = new DataSet();
                    dsYearSettingsid = objEmployeeEventData.GetYearSettingsId(strFromDate, strToDate);
                    if (dsYearSettingsid.Tables[0].Rows.Count > 0)
                    {
                        if (Convert.ToString(dsYearSettingsid.Tables[0].Rows[0][0]) != "Apply Induvial records")
                        {
                            dsLeaveApp = objLeaveApplicationEventData.InsertLeaveApplication(intEmployeeId, strApplicationDate, intLeaveTypeId, strTypeOfLeave, strFromDate, strToDate, strSessionFrom, strSessionTo, Decimal.Parse(dblNumberOfDaysAppliedCurrently.ToString()), strReason, intIsBorrow, Convert.ToString(Session["EmpAutoId"]), Convert.ToString(dsYearSettingsid.Tables[0].Rows[0][0]), strLeaveStatus, intSuccessiveyear, Convert.ToString(Intervening.Value),0);                            
                            if (dsLeaveApp.Tables.Count > 0)
                            {
                                if (dsLeaveApp.Tables[0].Rows.Count > 0)
                                {
                                    if (dsLeaveApp.Tables[0].Rows[0]["LeaveApplicationId"] != null)
                                        intLeaveApplicationId = Convert.ToInt32(dsLeaveApp.Tables[0].Rows[0]["LeaveApplicationId"]);
                                    if (dsLeaveApp.Tables[0].Rows[0]["LeaveApplicationStatus"] != null)
                                        LeaveApplicationStatus = Convert.ToString(dsLeaveApp.Tables[0].Rows[0]["LeaveApplicationStatus"]);
                                    if (dsLeaveApp.Tables[0].Rows[0]["LevelID"] != null)
                                        LevelID = Convert.ToInt32(dsLeaveApp.Tables[0].Rows[0]["LevelID"]);
                                    DataSet UploadStatus = objLeaveApplicationEventData.InsertLeaveApplication_FileUpload(Convert.ToString(hdnDocName.Value), finalfile, intEmployeeId, intLeaveApplicationId, "InsertMedicalCertificate");
                                }
                            }
                        }
                        else
                        {
                            ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("Alert_ApplySeparateLeaveforFromdateandToDate", objCultureInfo) + "');", true);
                            return;
                        }
                    }
                    else
                    {
                        ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("Alert_ApplyLeaveonavailableYearsettingsDays", objCultureInfo) + "');", true);
                        return;
                    }
                    DataTable dtSanctionView = new DataTable();
                    string strLeaveCategoryType = string.Empty;
                    dtSanctionView = objLeaveApplicationEventData.GetLeaveApplicationByLeaveApplicationId(intLeaveApplicationId);
                    if (dtSanctionView.Rows.Count > 0)
                    {
                        strLeaveCategoryType = Convert.ToString(dtSanctionView.Rows[0]["LeaveType"]);
                        strEmployeeEmailId = Convert.ToString(dtSanctionView.Rows[0]["emailId"]);
                    }
                    if (strLeaveStatus == "Approved")
                    {
                        if (strTypeOfLeave == "Leave")
                        {
                            if (intIsBorrow == 0)
                            {
                                objLeaveApplicationEventData.UpdateYearClosureByLeaveSanction(Convert.ToDouble(dblNumberOfDaysAppliedCurrently), intLeaveTypeId, intEmployeeId, "A", Convert.ToInt32(Session["EmpAutoId"]), Convert.ToInt16(dsYearSettingsid.Tables[0].Rows[0][0]));
                            }
                            else
                            {
                                objLeaveApplicationEventData.UpdateYearClosureByLeaveSanction(Convert.ToDouble(dblNumberOfDaysAppliedCurrently), intLeaveTypeId, intEmployeeId, "AB", Convert.ToInt32(Session["EmpAutoId"]), Convert.ToInt16(dsYearSettingsid.Tables[0].Rows[0][0]));
                            }
                        }
                        objLeaveApplicationEventData.UpdateProcessedDataFlag(intEmployeeId, strFromDate, strToDate, 0);
                    }
                    dsEmailIdOfReportingTo = objPermissionEventData.SelectMailIdOfReportingTo(intEmployeeId);
                    dsEmailIdOfSanctionAuthority = objPermissionEventData.SelectMailIdOfSanctionAuthority(intEmployeeId);
                    #region EmailTriggering
                    strEmailIdSanctioningAuthority = string.Empty;
                    if (dsEmailIdOfSanctionAuthority != null)
                    {
                        if (dsEmailIdOfSanctionAuthority.Tables.Count > 0)
                        {
                            if (dsEmailIdOfSanctionAuthority.Tables[0].Rows.Count > 0)
                            {
                                if (dsEmailIdOfSanctionAuthority.Tables[0].Rows[0]["EmailId"] != DBNull.Value)
                                {
                                    if (Convert.ToString(dsEmailIdOfSanctionAuthority.Tables[0].Rows[0]["EmailId"]) != "")
                                    {
                                        strEmailIdSanctioningAuthority = Convert.ToString(dsEmailIdOfSanctionAuthority.Tables[0].Rows[0]["EmailId"]);
                                    }
                                }
                            }
                        }
                    }
                    if (dsEmailIdOfReportingTo != null)
                    {
                        if (dsEmailIdOfReportingTo.Tables.Count > 0)
                        {
                            if (dsEmailIdOfReportingTo.Tables[0].Rows.Count > 0)
                            {
                                if (dsEmailIdOfReportingTo.Tables[0].Rows[0]["EmailId"] != DBNull.Value)
                                {
                                    if (Convert.ToString(dsEmailIdOfReportingTo.Tables[0].Rows[0]["EmailId"]) != "")
                                    {
                                        strEmailIdReportingTo = Convert.ToString(dsEmailIdOfReportingTo.Tables[0].Rows[0]["EmailId"]);
                                        if (Convert.ToInt32(ConfigurationManager.AppSettings.Get("isRequiredEmail")) == 1)
                                        {
                                            SendMail(intLeaveApplicationId, LevelID, strEmployeeEmailId, strEmailIdReportingTo,
                                                strEmailIdSanctioningAuthority, dblNumberOfDaysAppliedCurrently, txtFromDate.Text,
                                                txtToDate.Text, lblLeaveApplicationDateData.Text, strEmployeeName,
                                                strEmployeeCodeId, strReason, strlevelName, strLeaveCategoryType, 
                                                LeaveApplicationStatus);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    #endregion

                    #region Eastman
                    if (Convert.ToString(Session["packageID"]) != "")
                        if (Convert.ToString(Session["packageID"]) == "155") /*EastMan*/
                        {
                            if (PolicyExistsEmployees.Value == string.Empty)
                            {
                                AddJavascriptCode();
                                return;
                            }
                        }
                    #endregion
                    #region SMSNotification
                    try
                    {
                        int smsIsRequired = 0;
                        //To check SMS Template is available in page table or not. if no then it will skip the SMS Triggering portion.
                        //244 is template page id
                        smsIsRequired = objClassCommon.CheckPageExistsInLicense(244);
                        if (smsIsRequired > 0)
                        {
                            DataSet dsGateway = new DataSet();
                            DataSet dsStatus = new DataSet();
                            bool isSmsEnabledForEmployee = false;
                            string destinationKey = string.Empty;
                            string MessageKey = string.Empty;
                            string ServiceUrl = string.Empty;
                            string mobileNo = string.Empty;
                            string strTemplateName = string.Empty;
                            bool isApplyAndReceiverSame = false;
                            string empName = string.Empty;
                            if (LeaveApplicationStatus == "Pending")
                            {
                                strTemplateName = "Leave Application - Apply";
                            }
                            else if (LeaveApplicationStatus == "Forwarded")
                            {
                                strTemplateName = "Leave Application - Forward";
                            }
                            else if (LeaveApplicationStatus == "Approved")
                            {
                                strTemplateName = "Leave Application - Approved";
                            }
                            dsStatus = objsms.GetTemplateStauts(strTemplateName);
                            string strConvertedMessage = string.Empty;
                            if (dsStatus.Tables.Count > 0)
                            {
                                if (dsStatus.Tables[0].Rows.Count > 0 && Convert.ToBoolean(dsStatus.Tables[0].Rows[0]["Status"]) != false)
                                {
                                    dsGateway = objsms.SelectGatewayDetails();
                                    if (dsGateway.Tables.Count > 0)
                                    {
                                        if (dsGateway.Tables[0].Rows.Count > 0)
                                        {
                                            if (dsGateway.Tables[0].Rows[0]["ServiceUrl"] != null)
                                            {
                                                ServiceUrl = Convert.ToString(dsGateway.Tables[0].Rows[0]["ServiceUrl"]);
                                            }
                                            if (dsGateway.Tables[0].Rows[0]["DestinationKey"] != null)
                                            {
                                                destinationKey = Convert.ToString(dsGateway.Tables[0].Rows[0]["DestinationKey"]);
                                            }
                                            if (dsGateway.Tables[0].Rows[0]["MessageKey"] != null)
                                            {
                                                MessageKey = Convert.ToString(dsGateway.Tables[0].Rows[0]["MessageKey"]);
                                            }
                                            if (dsStatus.Tables[0].Rows[0]["ToEmployee"] != null)
                                            {
                                                isSmsEnabledForEmployee = Convert.ToBoolean(dsStatus.Tables[0].Rows[0]["ToEmployee"]);
                                            }
                                            if (isSmsEnabledForEmployee)
                                            {
                                                if (dtSanctionView.Rows.Count > 0)
                                                {
                                                    if (dtSanctionView.Rows[0]["Mobile_Number"] != null)
                                                    {
                                                        mobileNo = Convert.ToString(dtSanctionView.Rows[0]["Mobile_Number"]);
                                                    }
                                                    if (dtSanctionView.Rows[0]["Employee_FirstName"] != null)
                                                    {
                                                        empName = Convert.ToString(dtSanctionView.Rows[0]["Employee_FirstName"]);
                                                    }
                                                }
                                            }
                                            DataSet dsReceivers = new DataSet();
                                            string[] strleaveType = strLeaveCategoryType.Split('/');
                                            dsReceivers = objsms.GetReceiversDetails(strTemplateName, strEmployeeCodeId, strEmployeeName, strFromDate + " To " + strToDate, strleaveType[0], Convert.ToString(dblNumberOfDaysAppliedCurrently));
                                            if (dsReceivers.Tables.Count > 0)
                                            {
                                                if (dsReceivers.Tables[1].Rows.Count > 0)
                                                {
                                                    foreach (DataRow dr in dsReceivers.Tables[1].Rows)
                                                    {
                                                        if (Convert.ToString(dr["Mobile_Number"]) != "")
                                                        {
                                                            blnCheckSMS = objsms.SendSMSNotifications
                                                                (
                                                                    ServiceUrl,
                                                                    destinationKey,
                                                                    MessageKey,
                                                                    Convert.ToString(dr["Receivers"]),
                                                                    Convert.ToString(dsReceivers.Tables[0].Rows[0]["Message"]),
                                                                    Convert.ToString(dr["Mobile_Number"]),
                                                                    strEmployeeCodeId,
                                                                    strTemplateName,
                                                                    Convert.ToString(dr["SwipeCardNo"])
                                                                );
                                                            if (Convert.ToString(dr["SwipeCardNo"]) == strEmployeeCodeId)
                                                            {
                                                                isApplyAndReceiverSame = true;
                                                            }
                                                        }
                                                        else
                                                        {
                                                            if (dsReceivers.Tables[0].Rows[0]["Message"] != null)
                                                            {
                                                                if (Convert.ToString(dsReceivers.Tables[0].Rows[0]["Message"]).Contains("{User Name}"))
                                                                {
                                                                    strConvertedMessage = Convert.ToString(dsReceivers.Tables[0].Rows[0]["Message"]).Replace("{User Name}", Convert.ToString(dr["Receivers"]));
                                                                }
                                                            }
                                                            objsms.InsertLogDetails(strTemplateName, Convert.ToString(dr["SwipeCardNo"]), strEmployeeCodeId, false, Convert.ToString(strConvertedMessage), "Mobile Number is not configured in employee master");
                                                            blnCheckSMS = false;
                                                        }
                                                    }
                                                }
                                            }
                                            //in add receiver textbox mentioned usergroups and employee usergroup is not same, that time we should check 
                                            //employee option has been enable in template for employees or not.
                                            if (mobileNo != string.Empty && isApplyAndReceiverSame != true)
                                            {
                                                blnCheckSMS = objsms.SendSMSNotifications
                                                                 (
                                                                    ServiceUrl,
                                                                    destinationKey,
                                                                    MessageKey,
                                                                    empName,
                                                                    Convert.ToString(dsReceivers.Tables[0].Rows[0]["Message"]),
                                                                    Convert.ToString(mobileNo),
                                                                    strEmployeeCodeId,
                                                                     strTemplateName,
                                                                Convert.ToString(strEmployeeCodeId)

                                                                );

                                            }
                                            else if (mobileNo == string.Empty && isApplyAndReceiverSame != true)
                                            {
                                                if (isSmsEnabledForEmployee)
                                                {
                                                    objsms.InsertLogDetails(strTemplateName, Convert.ToString(strEmployeeCodeId), strEmployeeCodeId, false, Convert.ToString(dsReceivers.Tables[0].Rows[0]["Message"]), "Mobile Number is not configured in employee master");
                                                    blnCheckSMS = false;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        else
                        {
                            blnCheckSMS = true;
                        }
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                    #endregion
                    string strScript = "";
                    if (blnCheckEmail == true && blnCheckSMS == true)
                    {
                        strScript = strScript + "<script language='javascript'>";
                        strScript = strScript + "alert('" + rm.GetString("Alert_LeaveApplicationSaved", objCultureInfo) + "');";
                        strScript = strScript + "location.replace('TA_UI_Transactions_LeaveApplication.aspx');";
                        strScript = strScript + "</script>";
                    }
                    else if (blnCheckEmail == false && blnCheckSMS == true)
                    {
                        strScript = strScript + "<script language='javascript'>";
                        strScript = strScript + "alert('" + rm.GetString("Alert_LeaveApplicationSavedEmailnotsent", objCultureInfo) + "');";
                        strScript = strScript + "location.replace('TA_UI_Transactions_LeaveApplication.aspx');";
                        strScript = strScript + "</script>";
                    }
                    else if (blnCheckEmail == true && blnCheckSMS == false)
                    {
                        strScript = strScript + "<script language='javascript'>";
                        strScript = strScript + "alert('" + rm.GetString("Alert_LeaveApplicationSavedbutSMSisnottriggered", objCultureInfo) + "');";
                        strScript = strScript + "location.replace('TA_UI_Transactions_LeaveApplication.aspx');";
                        strScript = strScript + "</script>";
                    }
                    else
                    {
                        strScript = strScript + "<script language='javascript'>";
                        strScript = strScript + "alert('" + rm.GetString("Alert_LeaveApplicationSavedEmailnotsent", objCultureInfo) + "');";
                        strScript = strScript + "location.replace('TA_UI_Transactions_LeaveApplication.aspx');";
                        strScript = strScript + "</script>";
                    }
                    hdnTxtLeaveTypeId.Value = "";
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", strScript, false);

                }
                else
                {
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("Msg_AlreadyApplied", objCultureInfo) + "');", true);
                    ddl_Type.SelectedIndex = 0;
                }
            }
            else
            {
                return;
            }
        }
    }

    private void AssignDefaultLeaveValues()
    {
        ViewState["vsLeaveBal"] = 0;
        ViewState["vsAvailedLeave"] = 0;
        ViewState["vsAvailedLOPLeave"] = 0;
        ViewState["vsTotalLeaveTaken"] = 0;
        ViewState["vsWaiveoff"] = 0;
    }
    #endregion
    private void AddJavascriptCode()
    {
        string strScript = "";
        if (blnCheckEmail == true)
        {
            strScript = rm.GetString("Alert_LeaveApplicationSaved", objCultureInfo);
        }
        else if (blnCheckEmail == false)
        {
            strScript = rm.GetString("Alert_LeaveApplicationSavedEmailnotsent", objCultureInfo);
        }
        string script = " objHiddenField = document.getElementById('" + PolicyExistsEmployees.ClientID + @"'); objSubmit = document.getElementById('" + btnCancel.ClientID + @"'); if(confirm('" + strScript + @", Do You want to print this application?') == true){ objHiddenField.value = 'true'; objSubmit.click();}else { objHiddenField.value = 'cancel'; objSubmit.click();}";
        ScriptManager.RegisterStartupScript(this, this.GetType(), "confirm1", script, true);
    }


    #region Permissions the statuson shift.
    protected string PermissionStatusonShift(string PermissionDate, int shiftId, DateTime PermissionFromTime, DateTime PermissionToTime)
    {
        DataSet dsShiftDetails = new DataSet();
        string ShiftStartTime = string.Empty;
        string ShiftEndTime = string.Empty;
        string ShiftFirstHalfStart = string.Empty;
        string ShiftFirstHalfEnd = string.Empty;
        string ShiftSecondHalfStart = string.Empty;
        string ShiftSecondHalfEnd = string.Empty;
        string status = string.Empty;
        DateTime dtShiftFirstHalfStart = new DateTime();
        DateTime dtShiftFirstHalfEnd = new DateTime();
        DateTime dtShiftSecondHalfStart = new DateTime();
        DateTime dtShiftSecondHalfEnd = new DateTime();
        dsShiftDetails = objPermissionEventData.GetShiftTime(shiftId);
        if (dsShiftDetails.Tables.Count > 0)
        {
            if (dsShiftDetails.Tables[0].Rows.Count > 0)
            {
                if (dsShiftDetails.Tables[0].Rows[0]["shift_StartTime"] != DBNull.Value)
                {
                    ShiftStartTime = Convert.ToString(dsShiftDetails.Tables[0].Rows[0]["shift_StartTime"]);
                }
                if (dsShiftDetails.Tables[0].Rows[0]["shift_EndTime"] != DBNull.Value)
                {
                    ShiftEndTime = Convert.ToString(dsShiftDetails.Tables[0].Rows[0]["shift_EndTime"]);
                }
                if (dsShiftDetails.Tables[0].Rows[0]["Shift_FirstHalf_StartTime"] != DBNull.Value)
                {
                    dtShiftFirstHalfStart = DateTime.Parse(PermissionDate + " " + Convert.ToString(dsShiftDetails.Tables[0].Rows[0]["Shift_FirstHalf_StartTime"]));
                    ShiftFirstHalfStart = Convert.ToString(dsShiftDetails.Tables[0].Rows[0]["Shift_FirstHalf_StartTime"]);
                }
                if (dsShiftDetails.Tables[0].Rows[0]["Shift_FirstHalf_EndTime"] != DBNull.Value)
                {
                    dtShiftFirstHalfEnd = DateTime.Parse(PermissionDate + " " + Convert.ToString(dsShiftDetails.Tables[0].Rows[0]["Shift_FirstHalf_EndTime"]));
                    ShiftFirstHalfEnd = Convert.ToString(dsShiftDetails.Tables[0].Rows[0]["Shift_FirstHalf_EndTime"]);
                }
                if (dsShiftDetails.Tables[0].Rows[0]["Shift_SecondHalf_StartTime"] != DBNull.Value)
                {
                    dtShiftSecondHalfStart = DateTime.Parse(PermissionDate + " " + Convert.ToString(dsShiftDetails.Tables[0].Rows[0]["Shift_SecondHalf_StartTime"]));
                    ShiftSecondHalfStart = Convert.ToString(dsShiftDetails.Tables[0].Rows[0]["Shift_SecondHalf_StartTime"]);
                }
                if (dsShiftDetails.Tables[0].Rows[0]["Shift_SecondHalf_EndTime"] != DBNull.Value)
                {
                    dtShiftSecondHalfEnd = DateTime.Parse(PermissionDate + " " + Convert.ToString(dsShiftDetails.Tables[0].Rows[0]["Shift_SecondHalf_EndTime"]));
                    ShiftSecondHalfEnd = Convert.ToString(dsShiftDetails.Tables[0].Rows[0]["Shift_SecondHalf_EndTime"]);
                }
                if (ShiftStartTime.Substring(6, 2) == "PM" && ShiftEndTime.Substring(6, 2) == "AM")
                {
                    if (ShiftFirstHalfEnd != string.Empty)
                    {
                        if (ShiftFirstHalfEnd.Substring(6, 2) == "AM")
                        {
                            dtShiftFirstHalfEnd.AddDays(1);
                        }
                    }
                    if (ShiftSecondHalfStart != string.Empty)
                    {
                        if (ShiftSecondHalfStart.Substring(6, 2) == "AM")
                        {
                            dtShiftSecondHalfStart.AddDays(1);
                        }
                    }
                    if (ShiftSecondHalfEnd != string.Empty)
                    {
                        if (ShiftSecondHalfEnd.Substring(6, 2) == "AM")
                        {
                            dtShiftSecondHalfEnd = dtShiftSecondHalfEnd.AddDays(1);
                        }
                    }
                }
            }
        }
        if ((PermissionFromTime >= dtShiftFirstHalfStart && PermissionFromTime <= dtShiftFirstHalfEnd) && (PermissionToTime >= dtShiftFirstHalfStart && PermissionToTime <= dtShiftFirstHalfEnd))
        {
            status = "First Half";
        }
        else if ((PermissionFromTime >= dtShiftSecondHalfStart && PermissionFromTime <= dtShiftSecondHalfEnd) && (PermissionToTime >= dtShiftSecondHalfStart && PermissionToTime <= dtShiftSecondHalfEnd))
        {
            status = "Second Half";
        }
        return status;
    }
    #endregion
    protected void btn_cancel_Click(object sender, EventArgs e)
    {
        #region Eastman
        if (Convert.ToString(Session["packageID"]) != "")
            if (Convert.ToString(Session["packageID"]) == "155") /*EastMan*/
            {
                if (PolicyExistsEmployees.Value == "true")
                {
                    GenerateLeaveApplicationTableControls();
                    return;
                }
            }
        #endregion
        Response.Redirect("TA_UI_Transactions_LeaveApplication.aspx");
    }
    #region Compare ToDate with FromDate
    public void CompareDate(object s, ServerValidateEventArgs e)
    {
        try
        {
            if (txtFromDate.Text != string.Empty && txtToDate.Text != string.Empty)
            {
                gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
                strFromDateTime = objClassCommon.DateTimeConvertion((gstrDateFormat), txtFromDate.Text, "D");
                strToDateTime = objClassCommon.DateTimeConvertion((gstrDateFormat), txtToDate.Text, "D");
                DateTime dtToDate = DateTime.Parse(strToDateTime);
                DateTime dtFromDate = DateTime.Parse(strFromDateTime);
                TimeSpan diff = dtToDate.Subtract(dtFromDate);
                int day = diff.Days;
                if (day >= 0)
                    e.IsValid = true;
                else
                {
                    e.IsValid = false;
                }
            }
        }
        catch (Exception ex)
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "Date time conversion error", true);
        }
    }

    #endregion
    #region Compare FromMonth With Current Month.
    public void CompareCurrentdate(object s, ServerValidateEventArgs e)
    {
        try
        {
            if (Convert.ToString(Session["UserGroupName"]) == "SuperAdmin" || Convert.ToString(Session["HasSpecialRights"]) == "True")
                e.IsValid = true;
            else
            {
                if (txtFromDate.Text != string.Empty)
                {
                    gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
                    strFromDateTime = objClassCommon.DateTimeConvertion((gstrDateFormat), txtFromDate.Text, "D");
                    DateTime dtCurrentDate = DateTime.Now;
                    DateTime dtFromDate = DateTime.Parse(strFromDateTime);
                    TimeSpan diff = dtFromDate.Subtract(dtCurrentDate);
                    int day = diff.Days;
                    if (day >= 0)
                        e.IsValid = true;
                    else
                    {
                        e.IsValid = false;
                    }
                }
            }
        }
        catch (Exception ex)
        {
            Response.Write(ex.ToString());
        }
    }
    #endregion
    #region Compare Tomonth with Current Month.
    public void CompareTodate(object s, ServerValidateEventArgs e)
    {
        try
        {
            if (Convert.ToString(Session["UserGroupName"]) == "SuperAdmin" || Convert.ToString(Session["HasSpecialRights"]) == "True")
                e.IsValid = true;
            else
            {
                if (txtToDate.Text != string.Empty)
                {
                    gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
                    strToDateTime = objClassCommon.DateTimeConvertion((gstrDateFormat), txtToDate.Text, "D");
                    DateTime dtCurrentDate = DateTime.Now;
                    DateTime dtToDate = DateTime.Parse(strToDateTime);
                    TimeSpan diff = dtToDate.Subtract(dtCurrentDate);
                    int day = diff.Days;
                    if (day >= 0)
                        e.IsValid = true;
                    else
                    {
                        e.IsValid = false;
                    }
                }
            }
        }
        catch (Exception ex)
        {
            Response.Write(ex.ToString());
        }

    }
    #endregion
    #region Checks the restricted holiday count.
    public void CheckRestrictedHolidayCount()
    {
        int HolidayId = Convert.ToInt32(hdnTxtLeaveTypeId.Value);
        gintCount = objLeaveApplicationEventData.CheckLeaveApplicationRestrictedHolidays(Convert.ToInt32(hdnEmployeeId.Value), HolidayId);
        if (gintCount > 0)
        {
            intInsertFlag = -1;
            base.Message(rm.GetString("Msg_RestirctHolidays", objCultureInfo));
        }
        gintCount = 0;
    }
    #endregion
    #region Sending mail to the reporting to person.
    private void SendMail(int LeaveApplicationID, int LevelID, string strEmployeeEmailId, string ToMailId, string SanctionMailId, double NumberOfDaysApplied, string FromDate, string ToDate, string ApplicationDate, string EmployeeName, string Employee_Code_Id, string strReason, string strlevelName, string strLeaveType, string LeaveApplicationStatus)
    {
        string strFromEmailId = string.Empty;
        MailMessage mailMessage = new MailMessage();
        AlternateView loHTMLView = null;
        try
        {
            DataTable dtTableScript = new DataTable();
            dtTableScript = objLeaveApplicationEventData.GetEmailScripts("New Leave Application Form");
            if (dtTableScript.Rows.Count > 0)
            {
                string scriptText = "";
                switch (strLeaveType)
                {
                    case "Restricted Holiday":
                        strLeaveType = rm.GetString("Holiday_RestrictedHoliday", objCultureInfo);
                        break;
                    case "Comp Off":
                        strLeaveType = rm.GetString("Caption_CompOff", objCultureInfo);
                        break;
                    case "LOP":
                        strLeaveType = strLeaveType.Replace("LOP", rm.GetString("lbl_LOP", objCultureInfo));
                        break;
                    case "ESI":
                        strLeaveType = rm.GetString("Caption_ESI", objCultureInfo);
                        break;
                    default:
                        if (strLeaveType.Contains("Leave"))
                            strLeaveType = strLeaveType.Replace("Leave", rm.GetString("LeaveApplication_Leave", objCultureInfo));
                        break;
                }
                scriptText = Convert.ToString(dtTableScript.Rows[0]["ScriptText"]);



                // As per elite partner requisition, mail should be trigger from admin id, whatever we configured in setting page.
                //25-Dec-2019 02:06 PM
                //if (Session["loginEmailId"] != null && Convert.ToString(Session["loginEmailId"]) != 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"));
                //}
                mailMessage.To.Add(new MailAddress(ToMailId));
                if (strEmployeeEmailId != string.Empty)
                {
                    mailMessage.CC.Add(new MailAddress(strEmployeeEmailId));
                }
                if (Convert.ToString(hdnisWFH.Value) == "1")
                {
                    mailMessage.Subject = rm.GetString("email_WorkFromHomeApplicationForm", objCultureInfo) + " - " + ApplicationDate + " | " + Employee_Code_Id + " - " + EmployeeName + " | " + strlevelName + " - " + LeaveApplicationStatus;
                    mailMessage.Body = scriptText.Replace("<<lblleaveapplicationform>>", rm.GetString("email_WFHApplicationForm", objCultureInfo));
                    mailMessage.Body = mailMessage.Body.Replace("<<lblapplicationdate>>", rm.GetString("email_WFHApplicationDate", objCultureInfo));
                    mailMessage.Body = mailMessage.Body.Replace("<<lblleavetype>>", rm.GetString("lbl_WFHtype", objCultureInfo));
                    mailMessage.Body = mailMessage.Body.Replace("<<lblleavedate>>", rm.GetString("email_WFHDate", objCultureInfo));
                }
                else
                {
                    mailMessage.Subject = rm.GetString("email_LeaveApplicationForm", objCultureInfo) + " - " + ApplicationDate + " | " + Employee_Code_Id + " - " + EmployeeName + " | " + strlevelName + " - " + LeaveApplicationStatus;
                    mailMessage.Body = scriptText.Replace("<<lblleaveapplicationform>>", rm.GetString("email_LeaveApplicationForm", objCultureInfo));
                    mailMessage.Body = mailMessage.Body.Replace("<<lblapplicationdate>>", rm.GetString("email_LeaveApplicationDate", objCultureInfo));
                    mailMessage.Body = mailMessage.Body.Replace("<<lblleavetype>>", rm.GetString("lbl_leavetype", objCultureInfo));
                    mailMessage.Body = mailMessage.Body.Replace("<<lblleavedate>>", rm.GetString("email_LeaveDate", objCultureInfo));
                }
                mailMessage.Body = mailMessage.Body.Replace("<<ltr_rtl>>", rm.GetString("Direction", objCultureInfo));
                mailMessage.Body = mailMessage.Body.Replace("<<lblemployeeid>>", rm.GetString("email_EmployeeId", objCultureInfo));
                mailMessage.Body = mailMessage.Body.Replace("<<employeeid>>", Employee_Code_Id);
                mailMessage.Body = mailMessage.Body.Replace("<<employeename>>", EmployeeName);
                mailMessage.Body = mailMessage.Body.Replace("<<lblemployeename>>", rm.GetString("email_EmployeeName", objCultureInfo));
                mailMessage.Body = mailMessage.Body.Replace("<<applicationdate>>", ApplicationDate);
                mailMessage.Body = mailMessage.Body.Replace("<<leavetype>>", strLeaveType);
                mailMessage.Body = mailMessage.Body.Replace("<<numberdaysapplied>>", Convert.ToString(NumberOfDaysApplied));
                mailMessage.Body = mailMessage.Body.Replace("<<lblnumberdaysapplied>>", rm.GetString("email_NumberOfDaysApplied", objCultureInfo));
                mailMessage.Body = mailMessage.Body.Replace("<<fromdate>>", FromDate);
                mailMessage.Body = mailMessage.Body.Replace("<<lblfromdate>>", rm.GetString("email_FromDate", objCultureInfo));
                mailMessage.Body = mailMessage.Body.Replace("<<todate>>", ToDate);
                mailMessage.Body = mailMessage.Body.Replace("<<lbltodate>>", rm.GetString("email_ToDate", objCultureInfo));
                mailMessage.Body = mailMessage.Body.Replace("<<lblsession>>", rm.GetString("email_Session", objCultureInfo));
                mailMessage.Body = mailMessage.Body.Replace("<<fromsession>>", ddl_SessionFrom.SelectedItem.Text);
                mailMessage.Body = mailMessage.Body.Replace("<<lblfromsession>>", rm.GetString("email_FromDate", objCultureInfo));
                mailMessage.Body = mailMessage.Body.Replace("<<tosession>>", ddl_SessionTo.SelectedItem.Text);
                mailMessage.Body = mailMessage.Body.Replace("<<lbltosession>>", rm.GetString("email_ToDate", objCultureInfo));
                mailMessage.Body = mailMessage.Body.Replace("<<reason>>", strReason);
                mailMessage.Body = mailMessage.Body.Replace("<<lblreason>>", rm.GetString("email_Reason", objCultureInfo));
                mailMessage.Body = mailMessage.Body.Replace("<<LinkData>>", Convert.ToString(Session["HostServerURL"]) + "?LeaveApplication_Id=" + Convert.ToString(LeaveApplicationID) + "&LevelId=" + LevelID + "&Status=" + LeaveApplicationStatus + "&ApprovalType=Leave");
                objClassCommon.SendMail(mailMessage);
            }
            else
            {
                blnCheckEmail = false;
            }
        }
        catch
        {
            blnCheckEmail = false;
            objLeaveApplicationEventData.InsertLeaveApplicationDetailsInEmailTrigger(intLeaveApplicationId, strFromEmailId, ToMailId, strEmployeeEmailId, rm.GetString("email_LeaveApplicationForm", objCultureInfo) + " - " + ApplicationDate + " | " + Employee_Code_Id + " - " + EmployeeName + " | " + strlevelName + " - " + LeaveApplicationStatus, Convert.ToString(mailMessage.Body), "", "LeaveApplication");
        }
    }
    #endregion
    #region Handles the SelectedIndexChanged event of the ddlEmployeeNames control.
    #endregion
    #region Getting Information from resource file and display it in label.
    private void LoadStrings(CultureInfo ci)
    {
        #region Eastman
        lbl_EmployeeName.Text = rm.GetString("email_EmployeeName", ci);
        lbl_EmployeeId.Text = rm.GetString("email_EmployeeId", ci);
        lblTimePeriod.Text = rm.GetString("ShiftExchange_DateRange", ci);
        lblLeaveStartDate.Text = rm.GetString("email_FromDate", ci);
        lblLeaveEndDate.Text = rm.GetString("email_ToDate", ci);
        grv_LeaveApplication.Columns[1].Caption = rm.GetString("LeaveApplication_LeaveApplicationDate", ci);
        grv_LeaveApplication.Columns[2].Caption = rm.GetString("email_EmployeeId", ci);
        grv_LeaveApplication.Columns[3].Caption = rm.GetString("email_EmployeeName", ci);
        grv_LeaveApplication.Columns[4].Caption = rm.GetString("LevelDetails_LevelName", ci);
        grv_LeaveApplication.Columns[5].Caption = rm.GetString("Report_Duration", ci);
        grv_LeaveApplication.Columns[6].Caption = rm.GetString("Type_Of_Leave", ci);
        grv_LeaveApplication.Columns[7].Caption = rm.GetString("email_Status", ci);
        grv_LeaveApplication.Columns[8].Caption = rm.GetString("email_Reason", ci);
        #endregion
        #region Product
        lblEmployeeId.Text = rm.GetString("email_EmployeeId", ci);
        lblEmployeeName.Text = rm.GetString("email_EmployeeName", ci);
        lblempname.Text = rm.GetString("email_EmployeeName", ci);
        lblFromDate.Text = rm.GetString("email_FromDate", ci);
        lblLeave.Text = rm.GetString("LeaveApplication_Leave", ci);
        lblLeaveApplicationDate.Text = rm.GetString("LeaveApplication_LeaveApplicationDate", ci);
        lblLeaveRestrictedHoliday.Text = rm.GetString("LeaveApplication_LeaveRestrictedHoliday", ci);
        lblLeaveType.Text = rm.GetString("lbl_leavetype", ci);
        lblNumberofdaysapplied.Text = rm.GetString("LeaveApplication_NumberOfDaysApplied", ci);
        lblReason.Text = rm.GetString("email_Reason", ci);
        lblRemainingNumberofLeave.Text = rm.GetString("LeaveApplication_RemainingNumberOfLeave", ci);
        lblToDate.Text = rm.GetString("email_ToDate", ci);
        lblIndicatesMandatoryFields.Text = rm.GetString("IndicatesMandatoryFields", ci);
        CustomValidator1.ErrorMessage = rm.GetString("Alert_SelectvalidFromDate", ci);
        cus_ComDate.ErrorMessage = rm.GetString("Msg_GrearterThanFrmDate", ci);
        CustomValidator2.ErrorMessage = rm.GetString("Alert_SelectvalidToDate", ci);
        lbl_HeaderLeaveApplication.Text = rm.GetString("Transactions_LeaveApplication", ci);
        chkBorrowLeave.Text = rm.GetString("Transactions_LeaveBorrow", ci);
        lblApplicationYear.Text = rm.GetString("Transactions_LeaveApplicationYear", ci);//mar19
        btnAdd.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Save", ci);
        btnCancel.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Back", ci);
        lblSelectEmployee.Text = rm.GetString("lblSelectEmployee", ci);
        btnQuota.Text = "";
        rbtnCurrentYear.Text = rm.GetString("YearSetting_CurrentYear", ci);//mar19
        rbtnSuccessiveYear.Text = rm.GetString("Transaction_SucessiveYear", ci);//mar19
        ddl_SessionFrom.Items[0].Text = rm.GetString("Select", ci);
        ddl_SessionFrom.Items[1].Text = rm.GetString("Caption_Firsthalf", ci);
        ddl_SessionFrom.Items[2].Text = rm.GetString("Caption_Secondhalf", ci);
        ddl_SessionTo.Items[0].Text = rm.GetString("Select", ci);
        ddl_SessionTo.Items[1].Text = rm.GetString("Caption_Firsthalf", ci);
        ddl_SessionTo.Items[2].Text = rm.GetString("Caption_Secondhalf", ci);
        lblSession.Text = rm.GetString("email_Session", ci);
        ddl_Type.Items[0].Text = rm.GetString("Select", ci);
        ddl_Type.Items[1].Text = rm.GetString("LeaveApplication_Leave", ci);
        ddl_Type.Items[2].Text = rm.GetString("Holiday_RestrictedHoliday", ci);
        ddl_Type.Items[3].Text = rm.GetString("Caption_CompOff", ci);
        ddl_Type.Items[4].Text = rm.GetString("lbl_LOP", ci);
        ddl_LeaveType.Items[0].Text = rm.GetString("Select", ci);
        lblLoading.Text = rm.GetString("ProgressBarText", ci);
        lblEmpId.Text = rm.GetString("email_EmployeeId", ci);
        #endregion
    }
    #endregion
    #region Users rights.
    private void UserRights()
    {
        dsCheckuser = objCheckUser.checkRights(22, Convert.ToInt32(Session["userGroup_Id"]), "addPrv");
        if (dsCheckuser.Tables[0].Rows.Count == 0)
        {
            Response.Redirect("TransactionLandingPage.aspx");
        }
    }
    #endregion
    private void GenerateLeaveApplicationTableControls()
    {
        string scriptText = "";
        DataTable dtTableScript = new DataTable();
        dtTableScript = objLeaveApplicationEventData.GetEmailScripts("LeaveApplication_Print");
        if (dtTableScript.Rows.Count > 0)
        {
            scriptText = Convert.ToString(dtTableScript.Rows[0]["ScriptText"]);
            scriptText = scriptText.Replace("<<applicationdatefield>>", Convert.ToString(ViewState["vsApplicationDate"]));
            scriptText = scriptText.Replace("<<pagenofield>>", Convert.ToString(""));
            scriptText = scriptText.Replace("<<namefield>>", Convert.ToString(ViewState["vsEmployeeName"]));
            scriptText = scriptText.Replace("<<dojfield>>", Convert.ToString(ViewState["vsDateofJoining"]));
            scriptText = scriptText.Replace("<<employeeidfield>>", Convert.ToString(ViewState["vsEmployeeID"]));
            scriptText = scriptText.Replace("<<departmentfield>>", Convert.ToString(ViewState["vslevelName"]));
            scriptText = scriptText.Replace("<<concernfield>>", Convert.ToString(ViewState["vsConcernName"]));

            scriptText = scriptText.Replace("<<leavetakenfield>>", Convert.ToString(ViewState["vsTotalLeaveTaken"]));
            scriptText = scriptText.Replace("<<earnedleavefield>>", Convert.ToString(ViewState["vsAvailedLeave"]));
            scriptText = scriptText.Replace("<<lopfield>>", Convert.ToString(ViewState["vsAvailedLOPLeave"]));
            scriptText = scriptText.Replace("<<leavebalancefield>>", Convert.ToString(ViewState["vsLeaveBal"]));
            scriptText = scriptText.Replace("<<accidentfield>>", Convert.ToString(ViewState["vsWaiveoff"]));

            scriptText = scriptText.Replace("<<numberofdaysfield>>", Convert.ToString(ViewState["vsNumberOfDaysApplied"]));
            scriptText = scriptText.Replace("<<fromdatefield>>", Convert.ToString(ViewState["vsFromdate"]));
            scriptText = scriptText.Replace("<<todatefield>>", Convert.ToString(ViewState["vsTodate"]));
            scriptText = scriptText.Replace("<<reasonfield>>", Convert.ToString(ViewState["vsReason"]));

            pn.Controls.Add(new LiteralControl(scriptText));
            Session["ctrl"] = pn;
            string strScript = "";
            strScript = strScript + "<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>";
            strScript = strScript + "<meta http-equiv='X-UA-Compatible' content='IE=edge' />";
            strScript = strScript + "<script language='javascript'>";
            strScript = strScript + "window.open('Print.aspx','','left=10px, top=60px, width=1000px, height=600px, scrollbars=yes, status=no, resizable=yes');";
            strScript = strScript + "location.replace('TA_UI_Transactions_LeaveApplication.aspx');";
            strScript = strScript + "</script>";
            Response.Write(strScript);
            return;
        }
        else
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('Table script is missing,contact support team of timecheck');", true);
            return;
        }

    }

    private void GenerateLeaveApplicationTableControls(string s)
    {
        int tot = 0;
        for (int i = tot; i < 1; i++)
        {
            Table tblEmployee = new Table();
            tblEmployee.CellPadding = 5;
            tblEmployee.CellSpacing = 0;
            if (i == 0)
            {
                tblEmployee.Attributes.Add("style", "width: 800px;height:60px;");
            }
            else
            {
                tblEmployee.Attributes.Add("style", "margin-top:-5px;width: 800px;height:60px;");
            }

            TableRow hr1 = new TableRow();
            TableCell tc11 = new TableCell();
            tc11.Text = "Date:";
            tc11.Attributes.Add("style", "width:120px;height:10px;border:1px solid black");
            TableCell tc12 = new TableCell();
            tc12.Text = Convert.ToString(ViewState["vsApplicationDate"]);
            tc12.Attributes.Add("style", "width:120px;height:10px;border:1px solid black");
            tc12.ColumnSpan = 2;
            TableCell tc13 = new TableCell();
            tc13.Text = "PAGE NO:";
            tc13.Attributes.Add("style", "width:120px;height:10px;border:1px solid black");
            TableCell tc14 = new TableCell();
            tc14.Text = "";
            tc14.Attributes.Add("style", "width:120px;height:10px;border:1px solid black");
            hr1.Cells.Add(tc11);
            hr1.Cells.Add(tc12);
            hr1.Cells.Add(tc13);
            hr1.Cells.Add(tc14);


            TableRow hr2 = new TableRow();
            TableCell tc21 = new TableCell();
            tc21.ColumnSpan = 5;
            tc21.Text = "LEAVE APPLICATION";
            tc21.Attributes.Add("style", "width: 120px; text-align: center; text-decoration: underline; font-weight: bold;border:1px solid black");
            hr2.Cells.Add(tc21);

            TableRow hr3 = new TableRow();
            TableCell tc31 = new TableCell();
            tc31.Text = "NAME";
            tc31.Attributes.Add("style", "width:120px;height:10px;border:1px solid black");
            TableCell tc32 = new TableCell();
            tc32.Text = Convert.ToString(ViewState["vsEmployeeName"]);
            tc32.Attributes.Add("style", "width:120px;height:10px;border:1px solid black");
            tc32.ColumnSpan = 2;
            TableCell tc34 = new TableCell();
            tc34.Text = "D.O.J:";
            tc34.Attributes.Add("style", "width:120px;height:10px;border:1px solid black");
            TableCell tc35 = new TableCell();
            tc35.Text = Convert.ToString(ViewState["vsDateofJoining"]);
            tc35.Attributes.Add("style", "width:120px;height:10px;border:1px solid black");
            hr3.Cells.Add(tc31);
            hr3.Cells.Add(tc32);
            hr3.Cells.Add(tc34);
            hr3.Cells.Add(tc35);


            TableRow hr4 = new TableRow();
            TableCell tc41 = new TableCell();
            tc41.Text = "REF CODE";
            tc41.Attributes.Add("style", "width:120px;height:10px;border:1px solid black");
            TableCell tc42 = new TableCell();
            tc42.Text = Convert.ToString(ViewState["vsEmployeeID"]);
            tc42.Attributes.Add("style", "width:120px;height:10px;border:1px solid black");
            TableCell tc44 = new TableCell();
            tc44.Text = "DEPT. & TEAM NAME:";
            tc44.Attributes.Add("style", "width:120px;height:10px;border:1px solid black");
            TableCell tc45 = new TableCell();
            tc45.Text = Convert.ToString(ViewState["vslevelName"]);
            tc45.ColumnSpan = 2;
            tc45.Attributes.Add("style", "width:120px;height:10px;border:1px solid black");
            hr4.Cells.Add(tc41);
            hr4.Cells.Add(tc42);
            hr4.Cells.Add(tc44);
            hr4.Cells.Add(tc45);

            TableRow hr5 = new TableRow();
            TableCell tc51 = new TableCell();
            tc51.Text = "CONCERN NAME";
            tc51.Attributes.Add("style", "width:120px;height:10px;border:1px solid black");
            TableCell tc52 = new TableCell();
            tc52.Text = "";
            tc52.ColumnSpan = 4;
            tc52.Attributes.Add("style", "width:120px;height:10px;border:1px solid black");
            hr5.Cells.Add(tc51);
            hr5.Cells.Add(tc52);

            TableRow hr6 = new TableRow();
            TableCell tc61 = new TableCell();
            tc61.Text = "LEAVE BALANCE DETAILS";
            tc61.Attributes.Add("style", "width:120px;height:10px;border:1px solid black");
            TableCell tc62 = new TableCell();
            tc62.Text = "";
            tc62.ColumnSpan = 4;
            tc62.Attributes.Add("style", "width:120px;height:10px;border:1px solid black");
            Label lbl1 = new Label();
            lbl1.Text = "LEAVE TAKEN&nbsp;&nbsp;&nbsp;";
            Label lbl2 = new Label();
            lbl2.Attributes.Add("style", "text-decoration:underline");
            lbl2.Text = Convert.ToString(ViewState["vsAvailedLeave"]);
            Label lbl3 = new Label();
            lbl3.Text = " &nbsp;&nbsp;&nbsp;EARNED LEAVE&nbsp;&nbsp;&nbsp;";
            Label lbl4 = new Label();
            lbl4.Attributes.Add("style", "text-decoration:underline");
            lbl4.Text = " ";
            Label lbl5 = new Label();
            lbl5.Text = " &nbsp;&nbsp;&nbsp;LOP&nbsp;&nbsp;&nbsp;";
            Label lbl6 = new Label();
            lbl6.Attributes.Add("style", "text-decoration:underline");
            lbl6.Text = " ";
            Label lbl7 = new Label();
            lbl7.Text = " &nbsp;&nbsp;&nbsp;LEAVE BAL&nbsp;&nbsp;&nbsp;";
            Label lbl8 = new Label();
            lbl8.Attributes.Add("style", "text-decoration:underline");
            lbl8.Text = Convert.ToString(ViewState["vsLeaveBal"]);
            Label lbl9 = new Label();
            lbl9.Text = "&nbsp;&nbsp;&nbsp;ACCIDENT&nbsp;&nbsp;&nbsp;";
            Label lbl10 = new Label();
            lbl10.Attributes.Add("style", "text-decoration:underline");
            lbl10.Text = "0";
            tc62.Controls.Add(lbl1);
            tc62.Controls.Add(lbl2);
            tc62.Controls.Add(lbl3);
            tc62.Controls.Add(lbl4);
            tc62.Controls.Add(lbl5);
            tc62.Controls.Add(lbl6);
            tc62.Controls.Add(lbl7);
            tc62.Controls.Add(lbl8);
            tc62.Controls.Add(lbl9);
            tc62.Controls.Add(lbl10);

            hr6.Cells.Add(tc61);
            hr6.Cells.Add(tc62);

            TableRow hr7 = new TableRow();
            TableCell tc71 = new TableCell();
            tc71.Text = "LEAVE REQUIRED";
            tc71.Attributes.Add("style", "width:120px;height:10px;border:1px solid black");
            TableCell tc72 = new TableCell();
            tc72.ColumnSpan = 4;
            tc72.Attributes.Add("style", "width:120px;height:10px;border:1px solid black");
            Label lblDay = new Label();
            lblDay.Text = "DAY / DAYS :&nbsp;&nbsp;&nbsp;";
            Label lblDayvalue = new Label();
            lblDayvalue.Text = Convert.ToString(ViewState["vsNumberOfDaysApplied"]);
            Label lblFrom = new Label();
            lblFrom.Text = " &nbsp;&nbsp;&nbsp;FROM :&nbsp;&nbsp;&nbsp;";
            Label lblFromvalue = new Label();
            lblFromvalue.Text = Convert.ToString(ViewState["vsFromdate"]);
            Label lblTo = new Label();
            lblTo.Text = " &nbsp;&nbsp;&nbsp;To :&nbsp;&nbsp;&nbsp;";
            Label lblTovalue = new Label();
            lblTovalue.Text = Convert.ToString(ViewState["vsTodate"]);
            tc72.Controls.Add(lblDay);
            tc72.Controls.Add(lblDayvalue);
            tc72.Controls.Add(lblFrom);
            tc72.Controls.Add(lblFromvalue);
            tc72.Controls.Add(lblTo);
            tc72.Controls.Add(lblTovalue);
            hr7.Cells.Add(tc71);
            hr7.Cells.Add(tc72);

            TableRow hr8 = new TableRow();
            TableCell tc81 = new TableCell();
            tc81.Text = "REASON FOR LEAVE ";
            tc81.Attributes.Add("style", "width:120px;height:10px;border:1px solid black");
            TableCell tc82 = new TableCell();
            tc82.Text = Convert.ToString(ViewState["vsReason"]);
            tc82.Attributes.Add("style", "width:120px;height:10px;border:1px solid black");
            tc82.ColumnSpan = 4;
            hr8.Cells.Add(tc81);
            hr8.Cells.Add(tc82);

            tblEmployee.Rows.Add(hr1);
            tblEmployee.Rows.Add(hr2);
            tblEmployee.Rows.Add(hr3);
            tblEmployee.Rows.Add(hr4);
            tblEmployee.Rows.Add(hr5);
            tblEmployee.Rows.Add(hr6);
            tblEmployee.Rows.Add(hr7);
            tblEmployee.Rows.Add(hr8);
            pn.Controls.Add(tblEmployee);
        }
        GenerateSignatureTableControls();
    }

    private void GenerateSignatureTableControls()
    {
        Table tblsign = new Table();
        tblsign.Attributes.Add("style", "width: 800px;height:60px;");
        tblsign.Height = Unit.Pixel(100);
        TableHeaderRow hrsign = new TableHeaderRow();
        TableCell tcemp = new TableCell();
        tcemp.Attributes.Add("style", "width:30%;padding-top:10%;");
        tcemp.Text = "EMPLOYEE";
        TableCell tchod = new TableCell();
        tchod.Attributes.Add("style", "width:30%;text-align: center;padding-top:10%;");
        tchod.Text = "HOD";
        TableCell tcgroup = new TableCell();
        tcgroup.Attributes.Add("style", "width:30%;text-align: center;padding-top:10%;");
        tcgroup.Text = "GROUP COO & CFO";

        hrsign.Cells.Add(tcemp);
        hrsign.Cells.Add(tchod);
        hrsign.Cells.Add(tcgroup);
        tblsign.Rows.Add(hrsign);

        Table tblEmployee = new Table();
        tblEmployee.Width = Unit.Pixel(800);
        tblEmployee.CellPadding = 5;
        tblEmployee.CellSpacing = 0;
        TableHeaderRow hrfirst = new TableHeaderRow();
        hrfirst.Attributes.Add("style", "width:10%;height:10px;border:1px solid black;text-align: center;");
        hrfirst.Font.Size = 10;
        TableCell thcfirst = new TableCell();
        thcfirst.Attributes.Add("style", "width:10%;height:10px;border:1px solid black;text-align: center;text-decoration:underline");
        thcfirst.Font.Size = 10;
        thcfirst.Font.Bold = true;
        thcfirst.ColumnSpan = 5;
        thcfirst.Text = "FOR HR USE ONLY";
        hrfirst.Cells.Add(thcfirst);
        tblEmployee.Rows.Add(hrfirst);

        TableHeaderRow hr = new TableHeaderRow();
        hr.Attributes.Add("style", "width:10%;height:10px;border:1px solid black;text-align: center;");
        hr.Font.Size = 10;

        TableCell thcEmployeeid = new TableCell();
        thcEmployeeid.Attributes.Add("style", "width:10%;height:10px;border:1px solid black;text-align: center;");
        thcEmployeeid.Font.Size = 10;
        TableCell thcName = new TableCell();
        thcName.Attributes.Add("style", "width:10%;height:10px;border:1px solid black;text-align: center;");
        thcName.Font.Size = 10;
        TableCell thcDepartment = new TableCell();
        thcDepartment.Attributes.Add("style", "width:10%;height:10px;border:1px solid black;text-align: center;");
        thcDepartment.Font.Size = 10;
        TableCell thcDivShortForm = new TableCell();
        thcDivShortForm.Attributes.Add("style", "width:10%;height:10px;border:1px solid black;text-align: center;");
        thcDivShortForm.Font.Size = 10;
        TableCell thcInternal = new TableCell();
        thcInternal.Attributes.Add("style", "width:10%;height:10px;border:1px solid black;text-align: center;");
        thcInternal.Font.Size = 10;

        thcEmployeeid.Text = "CHECKED BY";
        thcName.Text = "RECIEVED DATE";
        thcDepartment.Text = "SYSTEM ENTRY";
        thcDivShortForm.Text = "ATTENDANCE ENTRY";
        thcInternal.Text = "INTERNAL AUDIT";

        hr.Cells.Add(thcEmployeeid);
        hr.Cells.Add(thcName);
        hr.Cells.Add(thcDepartment);
        hr.Cells.Add(thcDivShortForm);
        hr.Cells.Add(thcInternal);
        tblEmployee.Rows.Add(hr);

        TableHeaderRow hrv = new TableHeaderRow();
        hrv.Style.Add("border", "1px solid black");


        hrv.Height = Unit.Point(80);
        TableCell thcEmployeeidValue = new TableCell();
        thcEmployeeidValue.Attributes.Add("style", "width:10%;height:10px;border:1px solid black");
        thcEmployeeidValue.Height = Unit.Point(40);
        TableCell thcNamevalue = new TableCell();
        thcNamevalue.Attributes.Add("style", "width:10%;height:10px;border:1px solid black");
        thcNamevalue.Height = Unit.Point(40);
        TableCell thcDepartmentvalue = new TableCell();
        thcDepartmentvalue.Attributes.Add("style", "width:10%;height:10px;border:1px solid black");
        thcDepartmentvalue.Height = Unit.Point(40);
        TableCell thcDivShortFormvalue = new TableCell();
        thcDivShortFormvalue.Attributes.Add("style", "width:10%;height:10px;border:1px solid black");
        thcDivShortFormvalue.Height = Unit.Point(40);
        TableCell thcInternalvalue = new TableCell();
        thcInternalvalue.Attributes.Add("style", "width:10%;height:10px;border:1px solid black");
        thcInternalvalue.Height = Unit.Point(40);

        hrv.Cells.Add(thcEmployeeidValue);
        hrv.Cells.Add(thcNamevalue);
        hrv.Cells.Add(thcDepartmentvalue);
        hrv.Cells.Add(thcDivShortFormvalue);
        hrv.Cells.Add(thcInternalvalue);
        tblEmployee.Rows.Add(hrv);
        pn.Controls.Add(tblsign);
        pn.Controls.Add(tblEmployee);
        pn.Controls.Add(new LiteralControl(""));
        Session["ctrl"] = pn;
        string strScript = "";
        strScript = strScript + "<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>";
        strScript = strScript + "<meta http-equiv='X-UA-Compatible' content='IE=edge' />";
        strScript = strScript + "<script language='javascript'>";
        strScript = strScript + "window.open('Print.aspx','','left=10px, top=60px, width=1000px, height=600px, scrollbars=yes, status=no, resizable=yes');";
        strScript = strScript + "location.replace('TA_UI_Transactions_LeaveApplication.aspx');";
        strScript = strScript + "</script>";
        Response.Write(strScript);
        return;
    }

    protected void lnkbtnSearch_Click(object sender, EventArgs e)
    {
        FillGrid_Search();
    }
    private void FillGrid_Search()
    {
        string empName = txt_EmpName.Text.Trim();
        txt_EmpName.Text = empName;
        string empId = txtEmployeeId.Text.Trim();
        txtEmployeeId.Text = empId;
        string strLeaveStartDate;
        string strLeaveEndDate;
        bool boolErrorStatus = true;
        string gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
        strLeaveStartDate = objClassCommon.DateConvertion(gstrDateFormat, Convert.ToString(txtLeaveStartDate.Text));
        strLeaveEndDate = objClassCommon.DateConvertion(gstrDateFormat, Convert.ToString(txtLeaveEndDate.Text));
        string strSwipeCard = "";
        strSwipeCard = Convert.ToString(txtSwipeCard.Text).Trim().Replace("'", "''");
        if (strLeaveStartDate == string.Empty && strLeaveEndDate == string.Empty)
            boolErrorStatus = false;
        else if (strLeaveStartDate != string.Empty && strLeaveEndDate != string.Empty)
        {
            if (Convert.ToDateTime(strLeaveEndDate).Date < Convert.ToDateTime(strLeaveStartDate).Date)
            {
                base.Message(rm.GetString("Alert_FromDateLessThanToDate"));
                grv_LeaveApplication.DataSourceID = "";
                boolErrorStatus = true;
                return;
            }
            else
                boolErrorStatus = false;
        }
        if (boolErrorStatus == true)
            grid_RestoreDefault();
        else
        {
            lbl_Error.Text = string.Empty;
            grv_LeaveApplication.PageIndex = 0;
            //if (Convert.ToString(Session["UserGroupName"]) == "SuperAdmin")
            grv_LeaveApplication.DataSourceID = ObjectDataSource2.ID;
            //else
            //    grv_LeaveApplication.DataSourceID = ObjectDataSource1.ID;
        }
    }
    private void grid_RestoreDefault()
    {
        txt_EmpName.Text = string.Empty;
        txtEmployeeId.Text = string.Empty;
        txtLeaveStartDate.Text = string.Empty;
        txtLeaveEndDate.Text = string.Empty;
        txtSwipeCard.Text = string.Empty;
        grv_LeaveApplication.PageIndex = 0;
        if (Convert.ToString(ViewState["UserGroupName"]) == "SuperAdmin")
            grv_LeaveApplication.DataSourceID = ObjectDataSource2.ID;
        else
            grv_LeaveApplication.DataSourceID = ObjectDataSource1.ID;
    }

    protected void btn_Clear_Click(object sender, EventArgs e)
    {
        grid_RestoreDefault();
    }
    #region File Upload Functionality
    private bool LeaveMedicalCertificateFileUpload()
    {
        int MaxFileSize = Convert.ToInt32(ConfigurationManager.AppSettings["MaxFileSize"]);
        string Ex_JPEG = ConfigurationManager.AppSettings["Ex_JPEG"];
        string Ex_JPG = ConfigurationManager.AppSettings["Ex_JPG"];
        string Ex_BMP = ConfigurationManager.AppSettings["Ex_BMP"];
        string Ex_PNG = ConfigurationManager.AppSettings["Ex_PNG"];
        string Ex_PDF = ConfigurationManager.AppSettings["Ex_PDF"];
        string Ex_DOC = ConfigurationManager.AppSettings["Ex_DOC"];
        string Ex_DOCX = ConfigurationManager.AppSettings["Ex_DOCX"];
        string GetCurrentDate = DateTime.Today.ToString("yyyyMMdd");
        string GetEmployeeId = Convert.ToString(txt_EmployeeId.Text);
        string GetLeaveApplicationId = string.Empty;
        bool result = false;
        string GetDash = "_";
        string GetSessionEmployeeID = Convert.ToString(Session["EmployeeCodeId"]);
        if (hdLeaveSelectedText.Value != null && hdLeaveSelectedText.Value != "")
        {
            if (GetEmployeeId == string.Empty)
            {
                if (GetSessionEmployeeID != string.Empty)
                    GetEmployeeId = GetSessionEmployeeID;
            }
            DataSet ds_LeaveID = objLeaveApplicationEventData.GetLeaveApplication_Id();
            if (ds_LeaveID.Tables[0].Rows.Count > 0)
                GetLeaveApplicationId = Convert.ToString(ds_LeaveID.Tables[0].Rows[0]["LeaveApplicationID"]);
            else
                GetLeaveApplicationId = ConfigurationManager.AppSettings["DefaultLeaveID"];
            if (GetCurrentDate != string.Empty && GetEmployeeId != string.Empty && GetLeaveApplicationId != string.Empty)
            {
                string LeaveApplicationName = string.Concat(GetCurrentDate, GetDash, GetEmployeeId, GetDash, GetLeaveApplicationId);
                if (FileUploadControl.HasFile)
                {
                    string fileExtension = System.IO.Path.GetExtension(FileUploadControl.FileName);
                    if (fileExtension != Ex_DOC && fileExtension != Ex_DOCX && fileExtension != Ex_PDF && fileExtension != Ex_JPG && fileExtension != Ex_JPEG)
                    {
                        ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('Please Upload only PDF,DOC,JPEG.JPG extension file format');", true);
                    }
                    else
                    {
                        int fileSize = FileUploadControl.PostedFile.ContentLength;
                        if (fileSize == 0 || fileSize > MaxFileSize)
                        {
                            ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('Maximum upload file size is 5MB.');", true);
                        }
                        else
                        {
                            try
                            {
                                string extension = Path.GetExtension(FileUploadControl.PostedFile.FileName);
                                DirectoryInfo isDirectExists = new DirectoryInfo(Server.MapPath("~/Transactions/LeaveApplicationUploadFiles"));
                                if (!isDirectExists.Exists)
                                {
                                    ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('The Application doest not contain Leave Application Upload Files folder, please create it');", true);
                                    result = false;
                                }
                                else
                                {
                                    string serverpath = Server.MapPath("~/Transactions/LeaveApplicationUploadFiles/") + LeaveApplicationName + extension;
                                    finalfile = AppendFileNumberIfExists(serverpath, extension);
                                    FileUploadControl.SaveAs(finalfile);
                                    result = true;
                                }
                            }
                            catch (Exception ex)
                            {
                                ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('File Could not be uploaded');", true);
                            }
                        }
                    }
                }
                else
                {
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('Upload the necessary document to avail this leave.');", true);
                    return false;
                }
            }
            else
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('File Could not be uploaded');", true);
            }
        }
        else
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('File Could not be uploaded');", true);
        }
        return result;
    }
    private string AppendFileNumberIfExists(string file, string ext)
    {
        // If the file exists, then do stuff. Otherwise, we just return the original file name.
        if (File.Exists(file))
        {
            string folderPath = Path.GetDirectoryName(file); // The path to the file. No sense in dealing with this unecessarily. 
            string fileName = Path.GetFileNameWithoutExtension(file); // The file name with no extension. 
            string extension = string.Empty; // The file extension. 
                                             // This lets us pass in an empty string for the file extension if required. i.e. It just makes this function a bit more versatile. 
            if (ext == string.Empty)
            {
                extension = Path.GetExtension(file);
            }
            else
            {
                extension = ext;
            }

            // at this point, find out if the fileName ends in a number, then get that number.
            int fileNumber = 0; // This stores the number as a number for us. 
                                // need a regex here - \(([0-9]+)\)$
            Regex r = new Regex(@"\(([0-9]+)\)$"); // This matches the pattern we are using, i.e. ~(#).ext
            Match m = r.Match(fileName); // We pass in the file name with no extension.
            string addSpace = " "; // We'll add a space when we don't have our pattern in order to pad the pattern.
            if (m.Success)
            {
                addSpace = string.Empty; // We have the pattern, so we don't add a space - it has already been added. 
                string s = m.Groups[1].Captures[0].Value; // This is the single capture that we are looking for. Stored as a string.
                                                          // set fileNumber to the new number.
                fileNumber = int.Parse(s); // Convert the number to an int.
                                           // remove the numbering from the string as we're constructing it again below.
                fileName = fileName.Replace("(" + s + ")", "");
            }

            // Start looping. 
            do
            {
                fileNumber += 1; // Increment the file number that we have above. 
                file = Path.Combine(folderPath, // Combine it all.
                                        String.Format("{0}{3}({1}){2}", // The pattern to combine.
                                                                  fileName,         // The file name with no extension. 
                                                                  fileNumber,       // The file number.
                                                                  extension,        // The file extension.
                                                                  addSpace));       // A space if needed to pad the initial ~(#).ext pattern.
            }
            while (File.Exists(file)); // As long as the file name exists, keep looping. 
        }
        return file;
    }
    #endregion

    protected void txt_EmployeeId_TextChanged(object sender, EventArgs e)
    {
        #region Timezone
        String EmployeeID = Convert.ToString(txt_EmployeeId.Text);
        org_levelsEventData getUtcEmployeeCheck = new org_levelsEventData();
        DataSet ds_UTC = new DataSet();
        ds_UTC = getUtcEmployeeCheck.GetUTCTimeZoneEmployeeCheck(EmployeeID);
        int Counts = ds_UTC.Tables[0].Rows.Count;
        if (Counts != 0)
        {
            Session["TimezoneId"] = ds_UTC.Tables[0].Rows[0]["TimezoneId"].ToString();
            Session["TimeZoneName"] = ds_UTC.Tables[0].Rows[0]["TimeZoneName"].ToString();
            Session["TimeZoneDesc"] = ds_UTC.Tables[0].Rows[0]["TimeZoneDesc"].ToString();
            Session["HoursToBeAdded"] = ds_UTC.Tables[0].Rows[0]["HoursToBeAdded"].ToString();
            Session["MinToBeAdded"] = ds_UTC.Tables[0].Rows[0]["MinToBeAdded"].ToString();

            //var dt = DateTime.UtcNow;
            //var tz = TimeZoneInfo.FindSystemTimeZoneById(Convert.ToString(Session["TimeZoneName"]) + " Standard Time");
            //var DateTimeForCountry = TimeZoneInfo.ConvertTimeFromUtc(dt, tz);

            DateTime ConvertUTCTime = new DateTime();
            int hours = Convert.ToInt32(ds_UTC.Tables[0].Rows[0]["HoursToBeAdded"]);
            int Minutes = Convert.ToInt32(ds_UTC.Tables[0].Rows[0]["MinToBeAdded"]);
            ConvertUTCTime = objClassCommon.TimezoneGetDateTime(hours, Minutes);

            ViewState["CountryGetDateTime"] = ConvertUTCTime;


            if (Convert.ToString(TimeFormat) == "HH:mm")
            {
                lblLeaveApplicationDateData.Text = ConvertUTCTime.ToString(Convert.ToString(Session["MDateFormat"]) + " HH:mm");
                //up1.Update();

            }
            else
            {
                lblLeaveApplicationDateData.Text = ConvertUTCTime.ToString(Convert.ToString(Session["MDateFormat"]) + " hh:mm tt");
                //up1.Update();
            }

            Session["CurrentCountryDatetime"] = ConvertUTCTime.ToString(Convert.ToString(Session["MDateFormat"]) + " HH:mm:ss tt");

            string d = Session["CurrentCountryDatetime"].ToString();
            DateTime parsedDateTime;

            if (DateTime.TryParseExact(d, "dd/MM/yyyy HH:mm:ss tt", CultureInfo.InvariantCulture, DateTimeStyles.None, out parsedDateTime))
            {
                string formattedDate = parsedDateTime.ToString(Convert.ToString(Session["MDateFormat"]));
                string formattedUtcTime = parsedDateTime.ToString("hh:mm tt", CultureInfo.InvariantCulture);
                //DateTime ddddd = DateTime.Parse(Convert.ToDateTime(formattedDate).ToShortTimeString());
                Session["CurrentCountryDatetimes"] = parsedDateTime;
                String A = Session["CurrentCountryDatetimes"].ToString();
                //dtmCurrentDateTime = parsedDateTime;
            }

        }
        else
        {
            if (Convert.ToString(TimeFormat) == "HH:mm")
            {

                lblLeaveApplicationDateData.Text = DateTime.Now.ToString(Convert.ToString(Session["MDateFormat"]) + " HH:mm");
            }

            else
            {
                lblLeaveApplicationDateData.Text = DateTime.Now.ToString(Convert.ToString(Session["MDateFormat"]) + " hh:mm tt");
            }
        }
        #endregion
        Page.ClientScript.RegisterStartupScript(this.GetType(), "CallMyFunction", "EmpName('Leave'); OpenWindowLeaveQuota(SelectanEmployee);", true);
        //txt_EmployeeId.Attributes.Add("onblur","");
    }
}