using System;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Resources;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Threading;
using System.Net.Mail;
using System.Net.Mime;
using System.Text.RegularExpressions;
using System.Configuration;

public partial class MyCalendar : Base.BasePage
{
    #region Variable Declaration
    string finalfile = "";
    ResourceManager rm;
    string gstrUserGroupName = string.Empty;
    int gintInsertCount = 0;

    ManualEntryEventData objManualTimeEntry = new ManualEntryEventData();
    string strInDate, strInTime, strOutDate, strOutTime, strEntryDate, strEmployeeEmailId;
    string TimeFormatMail = string.Empty;
    ManualEntryEventData objManualEntry = new ManualEntryEventData();
    cls_Common objCommon = new cls_Common();
    DateTime dttShiftIn = new DateTime();
    DateTime dttShiftOut = new DateTime();
    Dashboard objDashh = new Dashboard();
    string onDuty = string.Empty, OndutyType;
    int daysCount;
    ShiftAllocationEvendata objShiftAllocation = new ShiftAllocationEvendata();
    int gintUserId;
    string strManualTimeEntryStatus = "Pending";
    int approvalSettingsPageExists = 0, IntOndutyID = 0;
    int manualEntryExists = 0;
    bool chkHolidayOnduty = false;
    HolidayEventData objHolidayEventData = new HolidayEventData();
    DateTime dtmIn = new DateTime();
    DateTime dtmOut = new DateTime();
    string strIn = string.Empty, strOut = string.Empty , gstrEmployeeIds = string.Empty;
    ShiftEvenData objShift = new ShiftEvenData();
    MonthClosureEventData objMonthClosure = new MonthClosureEventData();
    ShiftExchangeEventData objShiftExchange = new ShiftExchangeEventData();
    string gstrDOJValidation = string.Empty, gstrPermissionValidation = string.Empty, gstrShiftValidation = string.Empty;
    EmployeeEventData objEmployee = new EmployeeEventData();
    EmployeeEventData ObjEmployeeEventData = new EmployeeEventData();
    //EmployeeEventData objEmployeeEventData = new EmployeeEventData();
    userRightsEventData objUserRight = new userRightsEventData();
    Dashboard objDash = new Dashboard();
    DataSet dstMyCalendar = new DataSet();
    DataSet dstMyCalendarTeam = new DataSet();
    CultureInfo ci;
    GetReports rptEmp = new GetReports();
    Rpt_Common rptcommon = new Rpt_Common();
    DataSet ds_Checkuser = new DataSet();
    Cls_CheckUser objCheckUser = new Cls_CheckUser();
    string testing = null;
    DataSet dsEmployeeDetails = new DataSet();
    DataSet dsMaxNoOfLeaves = new DataSet();
    // Leave Application 
    LeaveApplicationEventData objLeaveApplicationEventData = new LeaveApplicationEventData();
    LeaveEventData objLeaveEventData = new LeaveEventData();
    PermissionEventData objPermissionEventData = new PermissionEventData();
    HolidayEventData objHoliday = new HolidayEventData();
    cls_Common objClassCommon = new cls_Common();
    SMSNotification objsms = new SMSNotification();
    DataSet dsLeaveType = new DataSet();
    DataSet dsRemainingDays = new DataSet();
    DataSet dsLeaveApplication = new DataSet();
    DataSet dsLeavePolicyDetails = new DataSet();
    DataSet dsSpellCount = new DataSet();
    DataSet dsEmailIdOfSanctionAuthority = new DataSet();
    DataSet dsEmailIdOfReportingTo = new DataSet();
    DataSet dsHolidayDetails = new DataSet();
    DataSet dsYear = new DataSet();
    DataSet ds_EmailIdOfReportingTo = new DataSet();
    string strApplicationDate, strTypeOfLeave, strFromDate, strToDate, strSessionFrom, strSessionTo, strReason, strEmailIdReportingTo, strEmailIdSanctioningAuthority, strEmployeeName, strEmployeeCodeId, strEmpFirstName, strEmpLastName, gstrDateFormat, strFromDateTime, strToDateTime, strlevelName, strDateofJoining;
    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 iLeaveApplication_Id, iEmployeeID, YearSettingID;
    int LevelID;
    string LeaveApplicationStatus = string.Empty;
    string gstrTimeFormat, strStatusType;
    int payrollConfig = 0;
    DataSet ds_EmployeeDetails = new DataSet();
    #endregion
    #region PageLoad
    protected override void Page_Load(object sender, EventArgs e)
    {
        string TimeFormat = string.Empty;
        base.Page_Load(sender, e);
        if (Session["Session_ActiveLanguage"] == null)
            Response.Redirect("Index.aspx");
        if (!Page.IsPostBack)
        {
            objCommon.menu("Dashboard", "246");
        }

        //  string source_Language = string.Empty;
        UserRights();
        Hidden1.Value = Convert.ToString(Session["IDateFormat"]);
        Hidden2.Value = Convert.ToString(Session["ITimeFormat"]);
        string source_Language;
        source_Language = Convert.ToString(Session["Session_ActiveLanguage"]);
        rm = new ResourceManager(source_Language, System.Reflection.Assembly.Load("App_GlobalResources"));
        ci = Thread.CurrentThread.CurrentCulture;
        LoadStrings(ci);
        if (Session["Session_ActiveLanguage"] != null)
        {
            source_Language = Convert.ToString(Session["Session_ActiveLanguage"]);
            rm = new ResourceManager(source_Language, System.Reflection.Assembly.Load("App_GlobalResources"));
            ci = Thread.CurrentThread.CurrentCulture;
        }
        dstMyCalendar = objDash.GetMyCalendarData(Convert.ToString(Session["UserGroupName"]), Convert.ToString(Session["EmpAutoID"]));
        string MyCalendarDataString = Convert.ToString(dstMyCalendar.Tables[0].Rows[0]["MyCalendarOutput"]);
        string strSetAlert = "";
        strSetAlert = strSetAlert + "<script language='javascript'>";
        strSetAlert = strSetAlert + "MyCalendarData('" + MyCalendarDataString + "');";
        strSetAlert = strSetAlert + "</script>";
        Page.RegisterStartupScript("SetAlertMessages", strSetAlert);
        DataSet dsIsSanction = new DataSet();
        dsIsSanction = objDash.GetIsSanctionUser(Convert.ToString(Session["EmpAutoID"]));
        if (dsIsSanction.Tables.Count > 0)
            if (dsIsSanction.Tables[0].Rows.Count > 0)
                liTeamcalendar.Visible = true;
        if (Convert.ToString(Session["UserGroupName"]) == "SuperAdmin")
        {
            liTeamcalendar.Visible = true;
            if (Convert.ToString(Session["EmployeeCodeId"]) == "18000000")
                liUserMycalendar.Visible = false;
        }
        strSetAlert = "";
        dstMyCalendarTeam = objDash.GetMyCalendarDataTeam(Convert.ToString(Session["UserGroupName"]), Convert.ToString(Session["EmpAutoID"]));
        MyCalendarDataString = Convert.ToString(dstMyCalendarTeam.Tables[0].Rows[0]["MyCalendarOutput"]);
        strSetAlert = "";
        strSetAlert = strSetAlert + "<script language='javascript'>";
        strSetAlert = strSetAlert + "clickTeamcalendar();MyCalendarDataTeam('" + MyCalendarDataString + "');clickUserMycalendar();";
        strSetAlert = strSetAlert + "</script>";
        Session["MyData"] = MyCalendarDataString;
        Page.RegisterStartupScript("CallCalendar", strSetAlert);
        hdnDateFormat.Value = Session["MDateFormat"].ToString();
        //if (hdnFromDate.Value != "")
        //{
        //    DateTime dt = Convert.ToDateTime(hdnFromDate);
        //    txtLeaveDate.Text = dt.ToString(Session["MDateFormat"].ToString());

        //}
        
        if (!IsPostBack)
        {
            string strdate = DateTime.Now.ToString("yyyy-MM-dd");
            strSetAlert = "";
            strSetAlert = strSetAlert + "<script language='javascript'>";
            strSetAlert = strSetAlert + "ajaxGetmyCalendar('" + strdate + "');";
            strSetAlert = strSetAlert + "</script>";
            Page.RegisterStartupScript("CallCalendarDataLoad", strSetAlert);
            Session["MyCalendarEmployeeID"] = Session["EmpAutoID"];
            LoadEmployee();
            lblUserName1.Text = Convert.ToString(Session["user"]);
            lblUserName2.Text = Convert.ToString(Session["user"]);
            strSetAlert = "";
            strSetAlert = strSetAlert + "<script language='javascript'>";
            strSetAlert = strSetAlert + "clickIndividualUser();";
            strSetAlert = strSetAlert + "</script>";
            Page.RegisterStartupScript("IndividualUser", strSetAlert);
            strSetAlert = "";
            strSetAlert = strSetAlert + "<script language='javascript'>";
            strSetAlert = strSetAlert + "clickIndividualUsers();";
            strSetAlert = strSetAlert + "</script>";
            Page.RegisterStartupScript("IndividualUser", strSetAlert);
        }
        //---------- Lable names-------------
        Hidden1.Value = Convert.ToString(Session["IDateFormat"]);//DD-MMM-YYYY Format
        TimeFormat = Hidden2.Value = Convert.ToString(Session["ITimeFormat"]);
        hiddenTime.Value = "HH:mm";
        if (TimeFormat == "HH:mm")
        {
            hiddenTime.Value = "HH:mm";
            lbl_InTime.Text = rm.GetString("OnDuty_InTime", ci);
            lbl_OutTimes.Text = rm.GetString("OnDuty_OutTime", ci);
        }
        else
        {
            hiddenTime.Value = "LT";
            lbl_InTime.Text = rm.GetString("OnDuty_InTime", ci);
            lbl_OutTimes.Text = rm.GetString("OnDuty_OutTime", ci);
        }
        Btn_OnDutyDelete.Text = rm.GetString("btn_Delete", ci);

        Session["UserImageURL"] = "LoginImage/defaultPhoto.png";

    }
    #endregion
    #region UserDefinedFunctions
    private void LoadStrings(CultureInfo ci)
    {
        lblteamLeave.Text = lblLeave.Text = rm.GetString("MyCalendar_Leave", ci);
        lblteamAbsent.Text = lblAbsent.Text = rm.GetString("MyCalendar_Absent", ci);
        lblHoliday.Text = rm.GetString("MyCalendar_Holiday", ci);
        lblWeeklyOff.Text = rm.GetString("MyCalendar_WeekOff", ci);
        lblEHlegend.Text = rm.GetString("MyCalendar_EHlegend", ci);
        lblEHrs.Text = rm.GetString("MyCalendar_EHrs", ci);
        lblHw.Text = rm.GetString("MyCalendar_Hw", ci);
        lblteamPresent.Text = 
        lblPresents.Text = lblPresent.Text = "Present";
        lblAbsents.Text = lblAbsent.Text = rm.GetString("MyCalendar_Absent", ci);
        lblLeaves.Text = lblLeave.Text = rm.GetString("MyCalendar_Leave", ci);
        lblHolidays.Text = rm.GetString("MyCalendar_Holiday", ci);
        lblWeeklyOffs.Text = rm.GetString("MyCalendar_WeekOff", ci);
        lblImportNote.Text = "Note";
        //chkLeaveApplication.Text = rm.GetString("LeaveApplicationconfiguration",ci);
        lblReason.Text = rm.GetString("email_Reason", ci);
        lbl_FromTime.Text = rm.GetString("AllSwipes_FromTime", ci);
        lbl_EndTime.Text = rm.GetString("AllSwipes_ToTime", ci);
        lbl_NumberofHoursapplied.Text = rm.GetString("email_NumberOfHoursApplied", ci);
        //lbl_PermissionApplicationDate1.Text = rm.GetString("LeaveApplication_LeaveApplicationDate", ci);
        lbl_Reason.Text = rm.GetString("email_Reason", ci);
        lbl_RemainingNumberofHours.Text = rm.GetString("Permission_RemaininigNumberOfHours", ci);
        lblLeaveRestrictedHoliday.Text = rm.GetString("LeaveApplication_LeaveRestrictedHoliday", ci);
        lblLeaveApplicationDate.Text = rm.GetString("LeaveApplication_LeaveDate", ci);
        lblRemainingNumberofLeave.Text = rm.GetString("LeaveApplication_RemainingNumberOfLeave", ci);
        lblNumberofdaysapplied.Text = rm.GetString("LeaveApplication_NumberOfDaysApplied", ci);
        btnLeaveAdd.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Save", ci);
        btnCancel.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Back", ci);
        btnDelete.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Delete", ci);
        lbl_ManualTimeEntryDate.Text = rm.GetString("LeaveApplication_LeaveApplicationDate", ci);
        Btn_OnDuty.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Save", ci);
        //lbl_InTime.Text = rm.GetString("OnDuty_InTime", ci);
        //lbl_OutTimes.Text = rm.GetString("OnDuty_OutTime", ci);
        lbl_Reasons.Text = rm.GetString("email_Reason", ci);
    }
    private void UserRights()
    {
        ds_Checkuser = objCheckUser.checkRights(246, Convert.ToInt32(Session["userGroup_Id"]), "");
        if (ds_Checkuser.Tables[0].Rows.Count == 0)
            Response.Redirect("Landing.aspx");
    }
    #endregion
    protected void btnApply_Click(object sender, EventArgs e)
    {
        if (rbtLeaveApplication.Checked == true)
            Response.Redirect("Transactions/TA_UI_Transactions_LeaveApplicationAdd.aspx");
        else if (rbtPermissionApplication.Checked == true)
            Response.Redirect("Transactions/TA_UI_Transactions_LeavePermissionAdd.aspx");
        else if (rbtOnduty.Checked == true)
            Response.Redirect("Transactions/TA_UI_Transactions_OnDutyAdd.aspx");
    }

    protected Stream Base64ToImageStream(string base64String)
    {
        byte[] imageBytes = Convert.FromBase64String(base64String);
        MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
        return ms;
    }
    protected void btnSendMail_Click(object sender, EventArgs e)
    {
        EmbeddedImagesLinked();
    }
    //protected void btnApply_Click(object sender, EventArgs e)
    //{
    //    EmbeddedImagesLinked();
    //}
    protected void LoadEmployee()
    {
        try
        {
            DataSet ds = new DataSet();
            ds = ObjEmployeeEventData.SelectUserandReporting(Convert.ToInt32(Session["EmpAutoID"]));
            ddlUser.Items.Clear();
            if (ds.Tables.Count > 0)
            {
                if (ds.Tables[0].Rows.Count > 0)
                {
                    ddlUser.DataTextField = "EmployeeName";
                    ddlUser.DataValueField = "Employee_Id";
                    ddlUser.DataSource = ds.Tables[0];
                    ddlUser.DataBind();
                    ddlUser.SelectedIndex = 0;
                }
                else
                {
                    divUserList.Style.Add("display", "none");
                }
                if (ds.Tables[0].Rows.Count == 1)
                {
                    liUserMyCalenderIndividual.Style.Add("display", "none");
                    divUserList.Style.Add("display", "none");
                }
                    
            }
            else
            {
                divUserList.Style.Add("display", "none");
                liUserMyCalenderIndividual.Style.Add("display", "none");
            }
        }
        catch (Exception ex)
        {
            throw;
        }
    }
    protected void EmbeddedImagesLinked()
    {
        MailMessage mail = new MailMessage();
        mail.From = new MailAddress("admin@angleritech.com", "no-reply");
        string[] strEmail;
        strEmail = txtEmail.Text.Split(',');
        foreach (var item in strEmail)
        {
            if (item.ToString() != "")
            {
                Regex regex = new Regex(@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$", RegexOptions.CultureInvariant | RegexOptions.Singleline);
                bool isValidEmail = regex.IsMatch(item.ToString().Trim());
                if (!isValidEmail)
                {
                    Message("The email is invalid: " + item.ToString().Trim());
                    txtEmail.Text = "";
                    return;
                }
                else
                {
                    mail.To.Add(item.ToString().Trim());
                }
            }
        }
        // set the content
        mail.Subject = "My Calendar | " + Convert.ToString(Session["user"]) + " | " + Convert.ToString(DateTime.Now.ToString("dd-MMM-yyyy"));

        string htmlBody = "<b>Dear " + Session["MyCalendarEmployeeID"] == Session["EmpAutoID"] ? Convert.ToString(Session["user"]) : ddlUser.SelectedItem.Text + "</b><br/><DIV> Kindly find the below image for your my Calendar. </DIV>";
        htmlBody += "<img alt=\"\" hspace=0  src=\"cid:uniqueId\" align=baseline border=0 >";
        htmlBody += "<br/>Regards, <br/>TimeCheck";
        AlternateView htmlView = AlternateView.CreateAlternateViewFromString(htmlBody, null, "text/html");

        string str = hdnImage.Value;
        str = str.Replace("data:image/octet-stream;base64,", "");
        str = str.Replace("data:image/jpeg;base64,", "");

        Stream streamBitmap = Base64ToImageStream(str);
        LinkedResource imageResource = new LinkedResource(streamBitmap, MediaTypeNames.Image.Jpeg);
        imageResource.ContentId = "uniqueId";
        imageResource.TransferEncoding = TransferEncoding.Base64;

        htmlView.LinkedResources.Add(imageResource);

        // add the views
        mail.AlternateViews.Add(htmlView);

        // send mail
        string strMsg = objCommon.SendMail(mail).ToString();

        if (strMsg == "Success")
            Message("Mail Send Successfully");
        else
            Message("Mail configuration missing. Please configure the mail.");
        txtEmail.Text = "";
    } // End EmbeddedImagesLinked
    protected void ddlUser_SelectedIndexChanged(object sender, EventArgs e)
    {
        Session["MyCalendarEmployeeID"] = ddlUser.SelectedValue.ToString();
        
        Session["MyCalendarEmployeeIDSelected"] = ddlUser.SelectedValue.ToString();
        string strdate = DateTime.Now.ToString("yyyy-MM-dd");
        string strSetAlert = "";
        strSetAlert = strSetAlert + "<script language='javascript'>";
        strSetAlert = strSetAlert + "ajaxGetmyCalendars('" + strdate + "');";
        strSetAlert = strSetAlert + "</script>";
        Page.RegisterStartupScript("CallCalendarDataLoad", strSetAlert);
        //string strdate = DateTime.Now.ToString("yyyy-MM-dd");
        //strSetAlert = "";
        //strSetAlert = strSetAlert + "<script language='javascript'>";
        //strSetAlert = strSetAlert + "ajaxGetmyCalendar('" + strdate + "');";
        //strSetAlert = strSetAlert + "</script>";
        //Page.RegisterStartupScript("CallCalendarDataLoad", strSetAlert);
        lblUserNames3.Text = Convert.ToString(ddlUser.SelectedItem.Text);
        lblUserNames4.Text = Convert.ToString(ddlUser.SelectedItem.Text);
    }

    //protected void btn_Cancel1_Click(object sender, EventArgs e)
    //{

    //}
    protected void btn_Cancel_Click(object sender, EventArgs e)
    {

    }

    private void AddJavascriptCode()
    {
        string strScript = "";
        if (blnCheckEmail == true)
        {
            strScript = rm.GetString("Alert_LeaveApplicationSaved", ci);
        }
        else if (blnCheckEmail == false)
        {
            strScript = rm.GetString("Alert_LeaveApplicationSavedEmailnotsent", ci);
        }
        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


    private void AssignDefaultLeaveValues()
    {
        ViewState["vsLeaveBal"] = 0;
        ViewState["vsAvailedLeave"] = 0;
        ViewState["vsAvailedLOPLeave"] = 0;
        ViewState["vsTotalLeaveTaken"] = 0;
        ViewState["vsWaiveoff"] = 0;
    }

    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", ci));
        }
        gintCount = 0;
    }

    protected void btnLeaveAdd_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, txtFromDate.Value);
            strApplicationDate = DateTime.Parse(strApplicationDate).ToShortDateString();
            ViewState["vsApplicationDate"] = strApplicationDate;
            strFromDate = objClassCommon.DateConvertion(gstrDateFormat, txtFromDate.Value);
            strFromDate = DateTime.Parse(strFromDate).ToShortDateString();
            ViewState["vsFromdate"] = strFromDate;
            strToDate = objClassCommon.DateConvertion(gstrDateFormat, txtToDate.Value);
            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", ci) + "');", 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", ci) + "');", true);
                    ddl_Type.SelectedIndex = 0;
                    return;
                }
            }
            else
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("lblSelectEmployee", ci) + "');", 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", ci) + "');", 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", ci) + "');", true);
                    intInsertFlag = -1;
                    ddl_Type.SelectedIndex = 0;
                    return;
                }
            }
            else if (hdnTxtLeaveTypeId.Value == "")
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("Msg_SelLeaveType", ci) + "');", 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", ci) + "');", true);
                int InsertFlag = -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", ci) + "');", 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", ci) + "');", 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", ci) + "');", true);
                                                ddl_Type.SelectedIndex = 0;
                                                return;
                                            }
                                        }
                                    }
                                    else
                                    {
                                        intInsertFlag = -1;
                                        ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("Msg_Maxdaysexceed", ci) + "');", 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", ci) + "');", 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", ci) + "');", true);
                                        ddl_Type.SelectedIndex = 0;
                                        return;
                                    }
                                }
                                else
                                {
                                    intInsertFlag = 0;
                                }
                            }
                            else
                            {
                                intInsertFlag = -1;
                                ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("Msg_exceedLeave", ci) + "');", true);
                                ddl_Type.SelectedIndex = 0;
                            }
                        }
                    }
                    else
                    {
                        intInsertFlag = -1;
                        ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("Msg_NoPolicyLeave", ci) + "');", 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", ci) + "');", true);
                                }
                            }
                            else
                            {
                                intInsertFlag = -1;
                                ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("Msg_SelectHolidayToDate", ci) + "');", true);
                            }
                        }
                        else
                        {
                            intInsertFlag = -1;
                            ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("Msg_SelectValidHoliday", ci) + "');", 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", ci));
                                    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", ci));
                                        return;
                                    }
                                }
                                else
                                {
                                    if (Convert.ToString(ddl_SessionTo.SelectedValue) != "First half")
                                    {
                                        Message(rm.GetString("Msg_LeaveBeforePermission", ci));
                                        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", ci));
                    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", ci) + "');", 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", ci) + "');", 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), 1);
                            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", ci) + "');", true);
                            return;
                        }
                    }
                    else
                    {
                        ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("Alert_ApplyLeaveonavailableYearsettingsDays", ci) + "');", 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.Value, txtToDate.Value, txtLeaveDate.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", ci) + "');";
                        strScript = strScript + "location.replace('MyCalendar.aspx');";
                        strScript = strScript + "</script>";
                    }
                    else if (blnCheckEmail == false && blnCheckSMS == true)
                    {
                        strScript = strScript + "<script language='javascript'>";
                        strScript = strScript + "alert('" + rm.GetString("Alert_LeaveApplicationSavedEmailnotsent", ci) + "');";
                        strScript = strScript + "location.replace('MyCalendar.aspx');";
                        strScript = strScript + "</script>";
                    }
                    else if (blnCheckEmail == true && blnCheckSMS == false)
                    {
                        strScript = strScript + "<script language='javascript'>";
                        strScript = strScript + "alert('" + rm.GetString("Alert_LeaveApplicationSavedbutSMSisnottriggered", ci) + "');";
                        strScript = strScript + "location.replace('MyCalendar.aspx');";
                        strScript = strScript + "</script>";
                    }
                    else
                    {
                        strScript = strScript + "<script language='javascript'>";
                        strScript = strScript + "alert('" + rm.GetString("Alert_LeaveApplicationSavedEmailnotsent", ci) + "');";
                        strScript = strScript + "location.replace('MyCalendar.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", ci) + "');", true);
                    ddl_Type.SelectedIndex = 0;
                }
            }
            else
            {
                return;
            }
        }
    }
    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(hdnEmployeeId.Value);
        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;
    }

    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", ci);
                        break;
                    case "Comp Off":
                        strLeaveType = rm.GetString("Caption_CompOff", ci);
                        break;
                    case "LOP":
                        strLeaveType = strLeaveType.Replace("LOP", rm.GetString("lbl_LOP", ci));
                        break;
                    case "ESI":
                        strLeaveType = rm.GetString("Caption_ESI", ci);
                        break;
                    default:
                        if (strLeaveType.Contains("Leave"))
                            strLeaveType = strLeaveType.Replace("Leave", rm.GetString("LeaveApplication_Leave", ci));
                        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", ci) + " - " + ApplicationDate + " | " + Employee_Code_Id + " - " + EmployeeName + " | " + strlevelName + " - " + LeaveApplicationStatus;
                    mailMessage.Body = scriptText.Replace("<<lblleaveapplicationform>>", rm.GetString("email_WFHApplicationForm", ci));
                    mailMessage.Body = mailMessage.Body.Replace("<<lblapplicationdate>>", rm.GetString("email_WFHApplicationDate", ci));
                    mailMessage.Body = mailMessage.Body.Replace("<<lblleavetype>>", rm.GetString("lbl_WFHtype", ci));
                    mailMessage.Body = mailMessage.Body.Replace("<<lblleavedate>>", rm.GetString("email_WFHDate", ci));
                }
                else
                {
                    mailMessage.Subject = rm.GetString("email_LeaveApplicationForm", ci) + " - " + ApplicationDate + " | " + Employee_Code_Id + " - " + EmployeeName + " | " + strlevelName + " - " + LeaveApplicationStatus;
                    mailMessage.Body = scriptText.Replace("<<lblleaveapplicationform>>", rm.GetString("email_LeaveApplicationForm", ci));
                    mailMessage.Body = mailMessage.Body.Replace("<<lblapplicationdate>>", rm.GetString("email_LeaveApplicationDate", ci));
                    mailMessage.Body = mailMessage.Body.Replace("<<lblleavetype>>", rm.GetString("lbl_leavetype", ci));
                    mailMessage.Body = mailMessage.Body.Replace("<<lblleavedate>>", rm.GetString("email_LeaveDate", ci));
                }
                mailMessage.Body = mailMessage.Body.Replace("<<ltr_rtl>>", rm.GetString("Direction", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<lblemployeeid>>", rm.GetString("email_EmployeeId", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<employeeid>>", Employee_Code_Id);
                mailMessage.Body = mailMessage.Body.Replace("<<employeename>>", EmployeeName);
                mailMessage.Body = mailMessage.Body.Replace("<<lblemployeename>>", rm.GetString("email_EmployeeName", ci));
                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", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<fromdate>>", FromDate);
                mailMessage.Body = mailMessage.Body.Replace("<<lblfromdate>>", rm.GetString("email_FromDate", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<todate>>", ToDate);
                mailMessage.Body = mailMessage.Body.Replace("<<lbltodate>>", rm.GetString("email_ToDate", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<lblsession>>", rm.GetString("email_Session", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<fromsession>>", ddl_SessionFrom.SelectedItem.Text);
                mailMessage.Body = mailMessage.Body.Replace("<<lblfromsession>>", rm.GetString("email_FromDate", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<tosession>>", ddl_SessionTo.SelectedItem.Text);
                mailMessage.Body = mailMessage.Body.Replace("<<lbltosession>>", rm.GetString("email_ToDate", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<reason>>", strReason);
                mailMessage.Body = mailMessage.Body.Replace("<<lblreason>>", rm.GetString("email_Reason", ci));
                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", ci) + " - " + ApplicationDate + " | " + Employee_Code_Id + " - " + EmployeeName + " | " + strlevelName + " - " + LeaveApplicationStatus, Convert.ToString(mailMessage.Body), "", "LeaveApplication");
        }
    }

    protected void btnCancel_Click(object sender, EventArgs e)
    {

    }

    protected void btnDelete_Click(object sender, EventArgs e)
    {
        LinkButton btn = sender as LinkButton;
        iLeaveApplication_Id = Convert.ToInt32(hdnLeaveApplicationID.Value);
        ViewDetails();
        ViewState["EmpID"] = btn.ValidationGroup.ToString();
        ViewState["EmpName"] = btn.CommandArgument;
        string strLeaveStatus = string.Empty;
        int approvalSettingsPageExists = 0;
        switch (payrollConfig)
        {
            case 1:
                approvalSettingsPageExists = objClassCommon.CheckPageExistsInLicense(110);
                break;
            default:
                approvalSettingsPageExists = objClassCommon.CheckPageExistsInLicense(228);
                break;
        }
        if (approvalSettingsPageExists == 1)
        {
            //Get Compnay Id of the Employeee
            int intCompanyId = base.GetCompanyId(Convert.ToInt32(ViewState["iEmployeeID"]));
            //Get Approval Settings Based on Company Id
            DataSet dsApprovalSettings = new DataSet();
            ShiftEvenData objShift = new ShiftEvenData();
            dsApprovalSettings = objShift.SelectApprovalSettings(intCompanyId);
            if (dsApprovalSettings != null)
            {
                if (dsApprovalSettings.Tables.Count > 0)
                {
                    if (dsApprovalSettings.Tables[0].Rows.Count > 0)
                    {
                        if (Convert.ToBoolean(dsApprovalSettings.Tables[0].Rows[0]["LeaveSanction"]) == false)
                        {
                            strLeaveStatus = "ApprovalNotRequired";
                        }
                    }
                    else
                    {
                        base.Message(rm.GetString("Msg_ApprovalSettings", ci));
                        return;
                    }
                }
            }
        }
        else
        {
            strLeaveStatus = "ApprovalNotRequired";
        }
        if (Convert.ToString(ViewState["StatusOfApplication"]) == "Rejected")
        {
            if (Convert.ToString(Session["UserGroupName"]) == "SuperAdmin" || Convert.ToString(Session["HasSpecialRights"]) == "True")
            {
                switch (payrollConfig)
                {
                    case 1:
                        objLeaveApplicationEventData.Delete_LeaveApplication(iLeaveApplication_Id, Convert.ToInt32(Session["EmpAutoId"]));
                        //Update Year Closure
                        DeleteAlertMessage();
                        break;
                    default:
                        if (Convert.ToString(Session["IndividualUsers"]) == "True")
                        {
                            Page.RegisterStartupScript("statusalert", "<script language='javascript'>alert('Rejected Leave Application Cannot be Deleted');</script>");
                        }
                        else
                        {
                            objLeaveApplicationEventData.Delete_LeaveApplication(iLeaveApplication_Id, Convert.ToInt32(Session["EmpAutoId"]));
                            DeleteAlertMessage();
                        }
                        break;
                }
                RemoveUploadedFiles(iLeaveApplication_Id);
            }
            else
            {
                Page.RegisterStartupScript("statusalert", "<script language='javascript'>alert('Rejected Leave Application Cannot be Deleted');</script>");
            }
        }
        else if (Convert.ToString(ViewState["StatusOfApplication"]) == "Pending" || strLeaveStatus == "ApprovalNotRequired")
        {
            //Check Borrow Leave Exists after normal leaves
            int intBorrowCount = objLeaveApplicationEventData.CheckBorrowLeaveExists(ViewState["LeaveFromDate"].ToString(), ViewState["LeaveToDate"].ToString(), Convert.ToInt32(ViewState["LeaveTypeId"]), Convert.ToInt32(ViewState["iEmployeeID"]));
            if (intBorrowCount > 0)
            {
                base.Message(rm.GetString("Msg_BorrowLeavesareavailabletodelete", ci));
                return;
            }
            //Delete Leave Application
            objLeaveApplicationEventData.Delete_LeaveApplication(iLeaveApplication_Id, Convert.ToInt32(Session["EmpAutoId"]));
            RemoveUploadedFiles(iLeaveApplication_Id);
            //Update Year Closure
            YearClosureUpdate(strLeaveStatus);
            //Added Newly by Manikandan.RR on 10-06-2015 11.38 AM
            MailToReportingTo();
            DeleteAlertMessage();
        }
        else
        {
            if (Convert.ToString(Session["UserGroupName"]) == "SuperAdmin" || Convert.ToString(Session["HasSpecialRights"]) == "True")
            {
                if (payrollConfig == 1)
                {
                    //Check Borrow Leave Exists after normal leaves
                    int intBorrowCount = objLeaveApplicationEventData.CheckBorrowLeaveExists(ViewState["LeaveFromDate"].ToString(), ViewState["LeaveToDate"].ToString(), Convert.ToInt32(ViewState["LeaveTypeId"]), Convert.ToInt32(ViewState["iEmployeeID"]));
                    if (intBorrowCount > 0)
                    {
                        base.Message(rm.GetString("Msg_BorrowLeavesareavailabletodelete", ci));
                        return;
                    }
                    //Delete Leave Application
                    objLeaveApplicationEventData.Delete_LeaveApplication(iLeaveApplication_Id, Convert.ToInt32(Session["EmpAutoId"]));
                    //Update Year Closure
                    YearClosureUpdate(strLeaveStatus);
                    MailToReportingTo();
                    DeleteAlertMessage();
                }
                else
                {
                    if (Convert.ToString(Session["IndividualUsers"]) == "True")
                    {
                        Page.RegisterStartupScript("statusalert", "<script language='javascript'>alert('" + rm.GetString("Alert_Cannotdeletethisrecordd", ci) + "');</script>");
                    }
                    else
                    {
                        //Check Borrow Leave Exists after normal leaves
                        int intBorrowCount = objLeaveApplicationEventData.CheckBorrowLeaveExists(ViewState["LeaveFromDate"].ToString(), ViewState["LeaveToDate"].ToString(), Convert.ToInt32(ViewState["LeaveTypeId"]), Convert.ToInt32(ViewState["iEmployeeID"]));
                        if (intBorrowCount > 0)
                        {
                            base.Message(rm.GetString("Msg_BorrowLeavesareavailabletodelete", ci));
                            return;
                        }
                        //Delete Leave Application
                        objLeaveApplicationEventData.Delete_LeaveApplication(iLeaveApplication_Id, Convert.ToInt32(Session["EmpAutoId"]));
                        //Update Year Closure
                        YearClosureUpdate(strLeaveStatus);
                        MailToReportingTo();
                        DeleteAlertMessage();
                    }
                }
                RemoveUploadedFiles(iLeaveApplication_Id);
            }
            else
            {
                Page.RegisterStartupScript("statusalert", "<script language='javascript'>alert('" + rm.GetString("Alert_Cannotdeletethisrecordd", ci) + "');</script>");
            }
        }
    }

    private void MailToReportingTo()
    {
        string strEmployeeEmailId = string.Empty;
        string strEmailIdSanctioningAuthority = string.Empty;
        gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
        gstrTimeFormat = Session["MTimeFormat"].ToString();
        strStatusType = "deleted";
        ds_EmployeeDetails = objLeaveApplicationEventData.GetEmployeeDetails(Convert.ToInt32(ViewState["iEmployeeID"]));
        if (ds_EmployeeDetails.Tables[0].Rows.Count > 0)
        {
            strlevelName = ds_EmployeeDetails.Tables[0].Rows[0]["levelName"].ToString();
            strEmployeeEmailId = ds_EmployeeDetails.Tables[0].Rows[0]["emailId"].ToString();
            ViewState["EmpID"] = Convert.ToString(ds_EmployeeDetails.Tables[0].Rows[0]["Employee_Code_Id"]);
            ViewState["EmpName"] = Convert.ToString(ds_EmployeeDetails.Tables[0].Rows[0]["Employee_FirstName"]) + " " + Convert.ToString(ds_EmployeeDetails.Tables[0].Rows[0]["Employee_LastName"]);
            strlevelName = Convert.ToString(ds_EmployeeDetails.Tables[0].Rows[0]["levelName"]);
        }
        ds_EmailIdOfReportingTo = objPermissionEventData.SelectMailIdOfReportingTo(Convert.ToInt32(ViewState["iEmployeeID"]));
        dsEmailIdOfSanctionAuthority = objPermissionEventData.SelectMailIdOfSanctionAuthority(Convert.ToInt32(ViewState["iEmployeeID"]));
        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 (dsEmailIdOfSanctionAuthority.Tables[0].Rows[0]["EmailId"].ToString() != "")
                        {
                            strEmailIdSanctioningAuthority = dsEmailIdOfSanctionAuthority.Tables[0].Rows[0]["EmailId"].ToString();
                        }
                    }
                }
            }
        }
        if (ds_EmailIdOfReportingTo.Tables[0].Rows.Count > 0)
        {
            if (ds_EmailIdOfReportingTo.Tables[0].Rows[0]["EmailId"] != DBNull.Value)
            {
                if (ds_EmailIdOfReportingTo.Tables[0].Rows[0]["EmailId"].ToString() != string.Empty)
                {
                    strEmailIdReportingTo = ds_EmailIdOfReportingTo.Tables[0].Rows[0]["EmailId"].ToString();
                    if (Convert.ToInt32(ConfigurationManager.AppSettings.Get("isRequiredEmail")) == 1)
                    {
                        //SendMail(strEmployeeEmailId, strEmailIdReportingTo, strEmailIdSanctioningAuthority, Convert.ToDouble(ViewState["NumberOfDays"]), Convert.ToString(ViewState["LeaveFromDate"]), Convert.ToString(ViewState["LeaveToDate"]), Convert.ToString(ViewState["Application_Date"]), Convert.ToString(ViewState["EmpID"]), Convert.ToString(ViewState["EmpName"]), Convert.ToString(ViewState["Leave_Reason"]), strlevelName, Convert.ToString(ViewState["Leave_Type"]));
                    }
                }
            }
        }
    }

    //private void SendMail(string strEmployeeEmailId, string strEmailIdReportingTo, string strEmailIdSanctioningAuthority, double v1, string v2, string v3, string v4, string v5, string v6, string v7, string strlevelName, string v8)
    //{
    //    string strFromEmailId = string.Empty;
    //    MailMessage mailMessage = new MailMessage();
    //    string strMailStatus = "Deleted";
    //    try
    //    {
    //        string scriptText;
    //        DataTable dtTableScript = new DataTable();
    //        dtTableScript = objLeaveApplicationEventData.GetEmailScripts("New Leave Application Form");
    //        if (dtTableScript.Rows.Count > 0)
    //        {
    //            switch (strLeaveType)
    //            {
    //                case "Restricted Holiday":
    //                    strLeaveType = rm.GetString("Holiday_RestrictedHoliday", ci);
    //                    break;
    //                case "Comp Off":
    //                    strLeaveType = rm.GetString("Caption_CompOff", ci);
    //                    break;
    //                case "LOP":
    //                    strLeaveType = strLeaveType.Replace("LOP", rm.GetString("lbl_LOP", ci));
    //                    break;
    //                case "ESI":
    //                    strLeaveType = rm.GetString("Caption_ESI", ci);
    //                    break;
    //                default:
    //                    if (strLeaveType.Contains("Leave"))
    //                        strLeaveType = strLeaveType.Replace("Leave", rm.GetString("LeaveApplication_Leave", ci));
    //                    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"));
    //            //}
    //            if (ToMailId != string.Empty)
    //            {
    //                mailMessage.To.Add(new MailAddress(ToMailId));
    //            }
    //            if (strEmployeeEmailId != string.Empty)
    //            {
    //                mailMessage.CC.Add(new MailAddress(strEmployeeEmailId));
    //            }
    //            if (Convert.ToString(ViewState["isWFH"]) == "1")
    //            {
    //                mailMessage.Subject = rm.GetString("email_WorkFromHomeApplicationForm", ci) + " - " + (DateTime.Parse(ApplicationDate)).ToString(Session["MDateFormat"].ToString()) + " | " + Employee_Code_Id + " - " + EmployeeName + " | " + strMailStatus;
    //                mailMessage.Body = scriptText.Replace("<<lblleaveapplicationform>>", rm.GetString("email_WFHApplicationForm", ci));
    //                mailMessage.Body = mailMessage.Body.Replace("<<lblapplicationdate>>", rm.GetString("email_WFHApplicationDate", ci));
    //                mailMessage.Body = mailMessage.Body.Replace("<<lblleavetype>>", rm.GetString("lbl_WFHtype", ci));
    //                mailMessage.Body = mailMessage.Body.Replace("<<lblleavedate>>", rm.GetString("email_WFHDate", ci));
    //            }
    //            else
    //            {
    //                mailMessage.Subject = rm.GetString("email_YourLeaveApplicationFor", ci) + " - " + (DateTime.Parse(ApplicationDate)).ToString(Session["MDateFormat"].ToString()) + " | " + Employee_Code_Id + " - " + EmployeeName + " | " + strMailStatus;
    //                mailMessage.Body = scriptText.Replace("<<lblleaveapplicationform>>", rm.GetString("email_LeaveApplicationForm", ci));
    //                mailMessage.Body = mailMessage.Body.Replace("<<lblapplicationdate>>", rm.GetString("email_LeaveApplicationDate", ci));
    //                mailMessage.Body = mailMessage.Body.Replace("<<lblleavetype>>", rm.GetString("lbl_leavetype", ci));
    //                mailMessage.Body = mailMessage.Body.Replace("<<lblleavedate>>", rm.GetString("email_LeaveDate", ci));
    //            }
    //            mailMessage.Body = mailMessage.Body.Replace("<<ltr_rtl>>", rm.GetString("Direction", ci));
    //            mailMessage.Body = mailMessage.Body.Replace("<<lblemployeeid>>", rm.GetString("email_EmployeeId", ci));
    //            mailMessage.Body = mailMessage.Body.Replace("<<employeeid>>", Employee_Code_Id);
    //            mailMessage.Body = mailMessage.Body.Replace("<<employeename>>", EmployeeName);
    //            mailMessage.Body = mailMessage.Body.Replace("<<lblemployeename>>", rm.GetString("email_EmployeeName", ci));
    //            mailMessage.Body = mailMessage.Body.Replace("<<applicationdate>>", (DateTime.Parse(ApplicationDate)).ToString(Session["MDateFormat"].ToString()));
    //            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", ci));
    //            mailMessage.Body = mailMessage.Body.Replace("<<fromdate>>", (DateTime.Parse(FromDate)).ToString(Session["MDateFormat"].ToString()));
    //            mailMessage.Body = mailMessage.Body.Replace("<<lblfromdate>>", rm.GetString("email_FromDate", ci));
    //            mailMessage.Body = mailMessage.Body.Replace("<<todate>>", (DateTime.Parse(ToDate)).ToString(Session["MDateFormat"].ToString()));
    //            mailMessage.Body = mailMessage.Body.Replace("<<lbltodate>>", rm.GetString("email_ToDate", ci));
    //            mailMessage.Body = mailMessage.Body.Replace("<<lblsession>>", rm.GetString("email_Session", ci));
    //            mailMessage.Body = mailMessage.Body.Replace("<<fromsession>>", Convert.ToString(ViewState["From_session"]));
    //            mailMessage.Body = mailMessage.Body.Replace("<<lblfromsession>>", rm.GetString("email_FromDate", ci));
    //            mailMessage.Body = mailMessage.Body.Replace("<<tosession>>", Convert.ToString(ViewState["To_session"]));
    //            mailMessage.Body = mailMessage.Body.Replace("<<lbltosession>>", rm.GetString("email_ToDate", ci));
    //            mailMessage.Body = mailMessage.Body.Replace("<<reason>>", strReason);
    //            mailMessage.Body = mailMessage.Body.Replace("<<lblreason>>", rm.GetString("email_Reason", ci));
    //            string strReplaceText = "<a href=<<LinkData>>><font face=\"Arial\" size=\"2\">Click here for approval</font></a>";
    //            mailMessage.Body = mailMessage.Body.Replace(strReplaceText, string.Empty);
    //            objClassCommon.SendMail(mailMessage);
    //        }
    //        else
    //        {
    //            blnCheckEmail = false;
    //            objLeaveApplicationEventData.InsertLeaveApplicationDetailsInEmailTrigger(iLeaveApplication_Id, strFromEmailId, ToMailId, strEmployeeEmailId, rm.GetString("email_LeaveApplicationForm", ci) + " - " + ApplicationDate + " | " + Employee_Code_Id + " - " + EmployeeName + " | " + strlevelName + " - " + strMailStatus, Convert.ToString(mailMessage.Body), "", "LeaveApplication");
    //        }
    //    }
    //    catch
    //    {
    //        blnCheckEmail = false;
    //        objLeaveApplicationEventData.InsertLeaveApplicationDetailsInEmailTrigger(iLeaveApplication_Id, strFromEmailId, ToMailId, strEmployeeEmailId, rm.GetString("email_LeaveApplicationForm", ci) + " - " + ApplicationDate + " | " + Employee_Code_Id + " - " + EmployeeName + " | " + strlevelName + " - " + strMailStatus, Convert.ToString(mailMessage.Body), "", "LeaveApplication");
    //    }

    //}

    private void YearClosureUpdate(string strLeaveStatus)
    {
        throw new NotImplementedException();
    }

    private bool RemoveUploadedFiles(int LeaveApplication_ID)
    {
        string GetType = "SelectMedicalCertificate";
        bool fileflage = false;
        int LeaveApplication_Id = LeaveApplication_ID;
        DataSet dsFileDetails = objLeaveApplicationEventData.EditLeaveApplication_FileUpload(LeaveApplication_Id, GetType);
        if (dsFileDetails.Tables[0].Rows.Count > 0)
        {
            string GetPath = dsFileDetails.Tables[0].Rows[0]["FilePath"].ToString();
            string filename = Path.GetFileName(GetPath);
            string FilePath = Server.MapPath("~/Transactions/LeaveApplicationUploadFiles/" + filename);
            FileInfo fileInfo = new FileInfo(FilePath);
            if (fileInfo.Exists)
            {
                File.Delete(FilePath);
                //ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('" + rm.GetString("MsgDeleteMedicalCertificate", ci) + "');", true);
                fileflage = true;
            }
            else
            {
                fileflage = false;
            }
        }
        else
        {
            fileflage = false;
        }
        return fileflage;
    }

    public void ViewDetails()
    {
        DataSet ds_LeaveApplication = new DataSet();
        ds_LeaveApplication = objLeaveApplicationEventData.SelectLeaveApplication(iLeaveApplication_Id);
        if (ds_LeaveApplication.Tables.Count > 0)
        {
            if (ds_LeaveApplication.Tables[0].Rows.Count > 0)
            {
                iEmployeeID = Convert.ToInt32(ds_LeaveApplication.Tables[0].Rows[0]["Employee_Id"]);
                YearSettingID = Convert.ToInt32(ds_LeaveApplication.Tables[0].Rows[0]["YearSettings_Id"]);
                ViewState["iEmployeeID"] = iEmployeeID.ToString();
                ViewState["StatusOfApplication"] = Convert.ToString(ds_LeaveApplication.Tables[0].Rows[0]["Status"]);
                ViewState["lblType"] = Convert.ToString(ds_LeaveApplication.Tables[0].Rows[0]["Type"]);
                ViewState["LeaveTypeId"] = Convert.ToString(ds_LeaveApplication.Tables[0].Rows[0]["LeaveType_Id"]);
                ViewState["LeaveFromDate"] = Convert.ToString(ds_LeaveApplication.Tables[0].Rows[0]["Leave_FromDate"]);
                ViewState["LeaveToDate"] = Convert.ToString(ds_LeaveApplication.Tables[0].Rows[0]["Leave_ToDate"]);
                ViewState["IsBorrow"] = Convert.ToString(ds_LeaveApplication.Tables[0].Rows[0]["IsBorrow"]);
                ViewState["NumberOfDays"] = Convert.ToString(ds_LeaveApplication.Tables[0].Rows[0]["NumberOfDays"]);
                ViewState["Application_Date"] = Convert.ToString(ds_LeaveApplication.Tables[0].Rows[0]["Leave_ApplicationDate"]);
                ViewState["Leave_Reason"] = Convert.ToString(ds_LeaveApplication.Tables[0].Rows[0]["Reason"]);
                ViewState["Leave_Type"] = Convert.ToString(ds_LeaveApplication.Tables[0].Rows[0]["LeaveType"]);
                ViewState["From_session"] = Convert.ToString(ds_LeaveApplication.Tables[0].Rows[0]["Leave_SessionFrom"]);
                ViewState["To_session"] = Convert.ToString(ds_LeaveApplication.Tables[0].Rows[0]["Leave_SessionTo"]);
                ViewState["isWFH"] = Convert.ToString(ds_LeaveApplication.Tables[0].Rows[0]["isWFH"]);
            }
        }
    }

    private void DeleteAlertMessage()
    {
        string strScript = "";
        strScript = strScript + "<script language='javascript'>";
        strScript = strScript + "alert('" + rm.GetString("Alert_LeaveApplicationDeleted", ci) + "');";
        strScript = strScript + "location.replace('TA_UI_Transactions_LeaveApplication.aspx');";
        strScript = strScript + "</script>";
        //Dispaly alert messsage.
        Page.RegisterStartupScript("AlertLDel65507866", strScript);
        return;

    }

    private void GetEmployeeDetails(int EmpID)
    {
        DataSet dsEmployeeDetails = new DataSet();
        dsEmployeeDetails = objLeaveApplicationEventData.GetEmployeeDetails(Convert.ToInt32(EmpID));
        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"]);
            strEmployeeName = strEmpFirstName + " " + strEmpLastName;
            strlevelName = Convert.ToString(dsEmployeeDetails.Tables[0].Rows[0]["levelName"]);
            strEmployeeEmailId = Convert.ToString(dsEmployeeDetails.Tables[0].Rows[0]["EmailID"]);
            strEmailIdSanctioningAuthority = Convert.ToString(dsEmployeeDetails.Tables[0].Rows[0]["ApprovalAuthorityEmailID"]);
            strEmailIdReportingTo = Convert.ToString(dsEmployeeDetails.Tables[0].Rows[0]["ReportingToEmailID"]);
            LevelID = Convert.ToInt32(dsEmployeeDetails.Tables[0].Rows[0]["LevelID"]);
        }
    }

    protected void Btn_OnDutyDelete_Click(object sender, EventArgs e)
    {


        dsEmployeeDetails = objLeaveApplicationEventData.GetEmployeeDetails(Convert.ToInt32(hdnEmployeeId.Value));
        if (dsEmployeeDetails.Tables.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;

            DataSet ds = objDashh.GetIndividualEmployeeLeavePolicy( TxtOnDuty.Text, strEmployeeCodeId, "OD");


            int gintManualTimeEntryId = Convert.ToInt32(ds.Tables[0].Rows[0]["Onduty_ID"]);
            int EmpID = Convert.ToInt32(ds.Tables[0].Rows[0]["Employee_Id"]);
            string ManuStatus = Convert.ToString(ds.Tables[0].Rows[0]["Onduty_Status"]);
            int gintUserId= Convert.ToInt32(ds.Tables[0].Rows[0]["Employee_Id"]);

            LinkButton btn = sender as LinkButton;
            //int gintManualTimeEntryId = Convert.ToInt32(btn.CommandName);
            //int EmpID = Convert.ToInt32(btn.ValidationGroup);
            //string ManuStatus = btn.CommandArgument;
            //int gintUserId = Int32.Parse(Session["EmpAutoID"].ToString());
            string strScript = string.Empty;
            DataSet dsSanctionView = new DataSet();
            string strLeaveStatus = string.Empty;
            int approvalSettingsPageExists = 0;
            //Checking grade module is available or not and changed the id value from 110 to 228
            approvalSettingsPageExists = objClassCommon.CheckPageExistsInLicense(228);
            if (approvalSettingsPageExists == 1)
            {
                //Get Compnay Id of the Employeee
                int intCompanyId = base.GetCompanyId(EmpID);
                //Get Approval Settings Based on Company Id
                DataSet dsApprovalSettings = new DataSet();
                ShiftEvenData objShift = new ShiftEvenData();
                dsApprovalSettings = objShift.SelectApprovalSettings(intCompanyId);
                if (dsApprovalSettings != null)
                {
                    if (dsApprovalSettings.Tables.Count > 0)
                    {
                        if (dsApprovalSettings.Tables[0].Rows.Count > 0)
                        {
                            if (Convert.ToBoolean(dsApprovalSettings.Tables[0].Rows[0]["ODEntry"]) == false)
                            {
                                ManuStatus = "ApprovalNotRequired";
                            }
                        }
                        else
                        {
                            base.Message(rm.GetString("Msg_ApprovalSettings", ci));
                            return;
                        }
                    }
                }
            }
            else
            {
                ManuStatus = "ApprovalNotRequired";
            }
            dsSanctionView = objManualTimeEntry.SelectODEntryById(gintManualTimeEntryId);
            if (dsSanctionView.Tables.Count > 0)
            {
                if (dsSanctionView.Tables[0].Rows.Count > 0)
                {
                    strInDate = Convert.ToString(dsSanctionView.Tables[0].Rows[0]["Onduty_FromDate"]);
                    strInTime = Convert.ToString(dsSanctionView.Tables[0].Rows[0]["Onduty_FromTime"]);
                    strOutDate = Convert.ToString(dsSanctionView.Tables[0].Rows[0]["Onduty_ToDate"]);
                    strOutTime = Convert.ToString(dsSanctionView.Tables[0].Rows[0]["Onduty_ToTime"]);
                    strEntryDate = Convert.ToString(dsSanctionView.Tables[0].Rows[0]["Onduty_EntryDate"]);
                    strReason = Convert.ToString(dsSanctionView.Tables[0].Rows[0]["Onduty_Reason"]);
                }
            }
            if (Convert.ToString(Session["UserGroupName"]) != "SuperAdmin" && Convert.ToString(Session["HasSpecialRights"]) != "True")
            {
                if (ManuStatus != "ApprovalNotRequired")
                {
                    if (ManuStatus == "Approved" || ManuStatus == "Forwarded")
                    {
                        base.Message(rm.GetString("Msg_ApprovedOnDutyEntryCannotbeDeleted", ci));
                        return;
                    }
                    else
                    {
                        objManualTimeEntry.DeleteOndutyEntry(gintManualTimeEntryId, gintUserId);
                        GetEmployeeDetails(EmpID);
                        if (Convert.ToInt32(ConfigurationManager.AppSettings.Get("isRequiredEmail")) == 1)
                        {
                            SendMail(Convert.ToInt32(gintManualTimeEntryId), LevelID, strEmployeeEmailId, strEmailIdReportingTo, strEmailIdSanctioningAuthority, strInDate, strInTime, strOutDate, strOutTime, strEntryDate, strEmployeeName, strEmployeeCodeId, "", strlevelName, "Delete", strlevelName);
                        }
                        Message(rm.GetString("Alert_OnDutyEntryhasbeendeletedsucessfully", ci));
                        //BindGridView();
                        return;
                    }
                }
                else
                {
                    objManualTimeEntry.DeleteOndutyEntry(gintManualTimeEntryId, gintUserId);
                    GetEmployeeDetails(EmpID);
                    if (Convert.ToInt32(ConfigurationManager.AppSettings.Get("isRequiredEmail")) == 1)
                    {
                        SendMail(Convert.ToInt32(gintManualTimeEntryId), LevelID, strEmployeeEmailId, strEmailIdReportingTo, strEmailIdSanctioningAuthority, strInDate, strInTime, strOutDate, strOutTime, strEntryDate, strEmployeeName, strEmployeeCodeId, "", strlevelName, "Delete", strlevelName);
                    }
                    Message(rm.GetString("Alert_OnDutyEntryhasbeendeletedsucessfully", ci));
                    //BindGridView();
                    return;
                }
            }
            else
            {
                objManualTimeEntry.DeleteOndutyEntry(gintManualTimeEntryId, gintUserId);
                GetEmployeeDetails(EmpID);
                if (Convert.ToInt32(ConfigurationManager.AppSettings.Get("isRequiredEmail")) == 1)
                {
                    SendMail(Convert.ToInt32(gintManualTimeEntryId), LevelID, strEmployeeEmailId, strEmailIdReportingTo, strEmailIdSanctioningAuthority, strInDate, strInTime, strOutDate, strOutTime, strEntryDate, strEmployeeName, strEmployeeCodeId, strReason, strlevelName, "Deleted", strlevelName);
                }
                Message(rm.GetString("Alert_OnDutyEntryhasbeendeletedsucessfully", ci));
                //BindGridView();
                return;
            }



        }


        
    }

    private void SendMail(int OnDutyID, int LevelID, string strEmployeeEmailId, string ToMailId, string SanctionMailId, string FromDate, string FromTime, string ToDate, string ToTime, string ApplicationDate, string EmployeeName, string Employee_Code_Id, string strReason, string strlevelName, string OndutyStatus, string Levelname)
    {
        string strFromEmailId = string.Empty;
        MailMessage mailMessage = new MailMessage();
        string strMailStatus = string.Empty;
        try
        {
            string scriptText;
            DataTable dtTableScript = new DataTable();
            string ScriptType = "Onduty Application From";
            dtTableScript = objLeaveApplicationEventData.GetEmailScripts(ScriptType);
            if (dtTableScript.Rows.Count > 0)
            {
                scriptText = Convert.ToString(dtTableScript.Rows[0]["ScriptText"]);
                mailMessage.From = new MailAddress(ConfigurationManager.AppSettings.Get("FromId"));
                strFromEmailId = Convert.ToString(ConfigurationManager.AppSettings.Get("FromId"));
                if (ToMailId != SanctionMailId)
                {
                    strMailStatus = rm.GetString("btn_Pending", ci);
                }
                else
                {
                    strMailStatus = rm.GetString("btn_Forwarded", ci);
                }
                if (OndutyStatus == "Deleted")
                {
                    if (SanctionMailId != string.Empty)
                    {
                        mailMessage.To.Add(new MailAddress(SanctionMailId));
                    }
                    if (strEmployeeEmailId != string.Empty)
                    {
                        mailMessage.CC.Add(new MailAddress(strEmployeeEmailId));
                    }
                }
                TimeFormatMail = Convert.ToString(Session["ITimeFormat"]);
                if (TimeFormatMail == "HH:mm")
                {
                    TimeFormatMail = "HH:mm";
                }
                else
                {
                    TimeFormatMail = "hh:mm tt";
                }
                mailMessage.Subject = rm.GetString("email_YourOndutyApplicationFor", ci) + " - " + ApplicationDate + " | " + Employee_Code_Id + " - " + EmployeeName + " | " + strlevelName + " - " + OndutyStatus;
                mailMessage.Body = scriptText.Replace("<<lblOndutyForm>>", rm.GetString("email_OndutyApplicationForm", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<ltr_rtl>>", rm.GetString("Direction", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<lblEmployeeID>>", rm.GetString("email_EmployeeId", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<EmployeeID>>", Employee_Code_Id);
                mailMessage.Body = mailMessage.Body.Replace("<<lblEmployeeName>>", rm.GetString("email_EmployeeName", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<EmployeeName>>", EmployeeName);
                mailMessage.Body = mailMessage.Body.Replace("<<EmployeeName>>", EmployeeName);
                mailMessage.Body = mailMessage.Body.Replace("<<lbldepartment>>", "Department");
                mailMessage.Body = mailMessage.Body.Replace("<<department>>", Levelname);
                mailMessage.Body = mailMessage.Body.Replace("<<lblApplicationDate>>", rm.GetString("ODEntry_ODEntryDate", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<ApplicationDate>>", ApplicationDate);
                mailMessage.Body = mailMessage.Body.Replace("<<lblODDate>>", rm.GetString("OnDutyDate", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<lblFromDate>>", rm.GetString("email_FromDate", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<FromDate>>", FromDate + " " + Convert.ToDateTime(FromTime).ToString(TimeFormatMail));
                mailMessage.Body = mailMessage.Body.Replace("<<lblToDate>>", rm.GetString("email_ToDate", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<ToDate>>", ToDate + " " + Convert.ToDateTime(ToTime).ToString(TimeFormatMail));
                mailMessage.Body = mailMessage.Body.Replace("<<lblStatus>>", rm.GetString("email_Status", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<Status>>", OndutyStatus);
                mailMessage.Body = mailMessage.Body.Replace("<<lblReason>>", rm.GetString("email_Reason", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<Reason>>", strReason);
                if (OndutyStatus == "Forwarded" || OndutyStatus == "Pending")
                {
                    mailMessage.Body = mailMessage.Body.Replace("<<LinkData>>", Convert.ToString(Session["HostServerURL"]) + "?ODID=" + Convert.ToString(OnDutyID) + "&LevelId=" + LevelID + "&Status=" + OndutyStatus + "&ApprovalType=Onduty");
                }
                else
                {
                    string strReplaceText = "<font face=\"Arial\" size=\"2\"><a href=\"<<LinkData>>\">Click here for approval </a></font>";
                    mailMessage.Body = mailMessage.Body.Replace(strReplaceText, string.Empty);
                }
                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 + " - " + strMailStatus, Convert.ToString(mailMessage.Body), "", "LeaveApplication");
        }
    }
    protected void Btn_OnDuty_Click(object sender, EventArgs e)
    {

        if ((TxtOnDuty.Text == "") || (txt_ShiftIn.Text=="") || (txt_ShiftOut.Text=="") || (txtReason.Text==""))
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('Enter InDate, Shift IN,Shift Out and Reason')", true);
            string scrt = "<script>ManualTimeEntry()</script>";
            this.Page.RegisterStartupScript("a", scrt);
         
            return;
        }
        else
        {
            lbl_Error.Text = string.Empty;
            string strInDate = "", strOutDate = "";
            gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
            DateTime dtmCurrentDateTime = DateTime.Parse(DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString());
            DateTime dtmFromDate = new DateTime();
            DateTime dtmToDate = new DateTime();
            DataSet ds_Year = new DataSet();
            ds_Year = objCommon.GetYearsetting();
            if (ds_Year != null)
            {
                if (ds_Year.Tables[0].Rows.Count > 0)
                {
                    if (ds_Year.Tables[0].Rows[0]["FromDate"] != DBNull.Value)
                    {
                        dtmFromDate = DateTime.Parse(Convert.ToString(ds_Year.Tables[0].Rows[0]["FromDate"]));
                    }
                    if (ds_Year.Tables[0].Rows[0]["ToDate"] != DBNull.Value)
                    {
                        dtmToDate = DateTime.Parse(Convert.ToString(ds_Year.Tables[0].Rows[0]["ToDate"]));
                    }
                    ViewState["YearSettings_Id"] = Convert.ToString(ds_Year.Tables[0].Rows[0]["YearSettings_Id"]);
                }
            }
            string strMaxPayrollClosureDate = objManualEntry.SelectMaxPayrollClosureDate();
            if (rbtOnDutys.Checked == true)
            {
                if (rbSingleDayYes.Checked == true)
                {
                    if ((txt_ShiftDate.Text == "") && (txt_ShiftIn.Text == "") && (txt_ShiftOut.Text == "") && (txt_Reason.Text == ""))
                    {
                        ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('Enter ShiftDate, InTime, OutTime and Reason')", true);
                        string scrt = "<script>ManualTimeEntry()</script>";
                        this.Page.RegisterStartupScript("a", scrt);
                        txt_ShiftIn.Focus();
                        return;
                    }
                    if (txt_ShiftDate.Text != "" && txt_ShiftDate.Text != string.Empty)
                    {
                        String D = lbl_ManualTimeEntryDate.Text;
                        strInDate = objCommon.DateConvertion(gstrDateFormat, TxtOnDuty.Text);
                        strOutDate = objCommon.DateConvertion(gstrDateFormat, TxtOnDuty.Text);
                    }
                    if (txt_ShiftDate.Text != string.Empty)
                    {
                        DateTime dtmInDate = DateTime.Parse(strInDate);
                        if ((dtmInDate < dtmFromDate) && (dtmInDate < dtmToDate))
                        {
                            ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("Msg_ActiveYear", ci) + "');", true);
                            string scrt = "<script>ManualTimeEntry()</script>";
                            this.Page.RegisterStartupScript("a", scrt);
                            txt_ShiftIn.Focus();
                            return;
                        }
                        if (gstrUserGroupName != "SuperAdmin")
                        {
                            if (Convert.ToString(Session["HasSpecialRights"]) != "True")
                            {
                                if (strMaxPayrollClosureDate != "")
                                {
                                    DateTime dtmMaxPayrollClosureDate = DateTime.Parse(strMaxPayrollClosureDate);
                                    if (dtmInDate <= dtmMaxPayrollClosureDate)
                                    {
                                        ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("Msg_InDateProcessed", ci) + "');", true);
                                        string scrt = "<script>ManualTimeEntry()</script>";
                                        this.Page.RegisterStartupScript("a", scrt);
                                        txt_ShiftIn.Focus();
                                        return;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            if (Convert.ToDateTime(strOutDate).Date < Convert.ToDateTime(strInDate).Date)
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("Alert_FromDateShouldLesser", ci) + "');", true);
                return;
            }
            if (Convert.ToString(Session["UserGroupName"]) != "SuperAdmin")
            {
                if (Convert.ToString(Session["HasSpecialRights"]) != "True")
                {
                    string strTodaysDate = DateTime.Now.ToString(Session["MDateFormat"].ToString());
                    strTodaysDate = objCommon.DateConvertion(gstrDateFormat, strTodaysDate);
                    if ((Convert.ToDateTime(strInDate) < Convert.ToDateTime(strTodaysDate)) || (Convert.ToDateTime(strOutDate) < Convert.ToDateTime(strTodaysDate)))
                    {
                        ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("Alert_OnDutyentryisnotallowedforpastdate", ci) + "');", true);
                        return;
                    }
                }
            }

            if (rbtOnDutys.Checked == true)
            {
                DataSet dsEmployees = new DataSet();
                DataTable dtEmpDetails = new DataTable();

                dsEmployeeDetails = objLeaveApplicationEventData.GetEmployeeDetails(Convert.ToInt32(hdnEmployeeId.Value));
                if (dsEmployeeDetails.Tables.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;


                    dsEmployees = objCommon.getEmployeeAutoId(strEmployeeCodeId);
                    dtEmpDetails = dsEmployees.Tables[0];
                }

                gintInsertCount = 0;
                int shiftID = 0;
                if (dtEmpDetails.Rows.Count > 0)
                {
                    foreach (DataRow drEmployee in dtEmpDetails.Rows)
                    {
                        for (DateTime dtmDates = Convert.ToDateTime(strInDate); dtmDates <= Convert.ToDateTime(strOutDate); dtmDates = dtmDates.AddDays(1))
                        {
                            DataSet dsActualShift = new DataSet();
                            DataTable dtActualShift = new DataTable();
                            dsActualShift = objManualEntry.SelectShiftIdforOnduty(Convert.ToString(drEmployee["Employee_code_Id"]), dtmDates.Year.ToString(), dtmDates.Month.ToString(), dtmDates.Day.ToString());
                            if (dsActualShift.Tables.Count > 0)
                            {
                                dtActualShift = dsActualShift.Tables[0];
                                if (dtActualShift.Rows.Count > 0 && Convert.ToInt64(dtActualShift.Rows[0]["ShiftId"]) != -1)
                                {

                                    string strActualShiftIn = (dtActualShift.Rows[0]["Shift_StartTime"].ToString());
                                    string strActualShiftOut = (dtActualShift.Rows[0]["Shift_EndTime"].ToString());
                                    DateTime dttActualShiftIn = DateTime.Parse(strActualShiftIn);
                                    DateTime dttAcutalShiftOut = DateTime.Parse(strActualShiftOut);
                                    dttShiftIn = DateTime.Parse(txt_ShiftIn.Text);
                                    dttShiftOut = DateTime.Parse(txt_ShiftOut.Text);
                                    int intAddDays = 0;
                                    // Allowed Employees To enter more than Shift hours.
                                    if (hdnAllowMax != null)
                                    {
                                        if (hdnAllowMax.Value != null)
                                        {
                                            dttAcutalShiftOut = dttAcutalShiftOut.AddHours(Convert.ToInt32(hdnAllowMax.Value));
                                        }
                                        else
                                        {
                                            dttAcutalShiftOut = dttAcutalShiftOut.AddHours(2);
                                        }
                                    }
                                    if (dtActualShift.Rows[0]["Shift_StartTime"].ToString().Contains("PM") && dtActualShift.Rows[0]["Shift_EndTime"].ToString().Contains("AM"))
                                    {
                                        dttAcutalShiftOut = dttAcutalShiftOut.AddDays(1);
                                        if (txt_ShiftIn.Text.Contains("AM"))
                                        {
                                            dttShiftIn = dttShiftIn.AddDays(1);
                                            dttShiftOut = dttShiftOut.AddDays(1);
                                        }
                                        else
                                        {
                                            if (txt_ShiftOut.Text.Contains("AM"))
                                            {
                                                dttShiftOut = dttShiftOut.AddDays(1);
                                            }
                                        }
                                    }

                                }

                            }
                            else
                            {
                                gintInsertCount = 0;
                                onDuty = rm.GetString("AlertShiftnotallocated");
                                DisplayShiftTimingMessage(onDuty);
                                return;
                            }
                        }
                        dttShiftIn = DateTime.Parse(strInDate + " " + txt_ShiftIn.Text);
                        dttShiftOut = DateTime.Parse(strOutDate + " " + txt_ShiftOut.Text);
                    }
                    #region InsertingOnduty
                    foreach (DataRow drEmployee in dtEmpDetails.Rows)
                    {
                        if (drEmployee["Employee_Id"] != DBNull.Value)
                        {
                            AddManualEntryDetails_ODEntry(drEmployee["Employee_code_Id"].ToString(), "GB", Convert.ToInt32(drEmployee["Employee_Id"]));
                        }
                    }
                    #endregion
                    objShiftAllocation.DeleteEmpShiftDetails(gintUserId);
                    if (IntOndutyID != 0)
                    {

                        dsEmployeeDetails = objLeaveApplicationEventData.GetEmployeeDetails(Convert.ToInt32(hdnEmployeeId.Value));
                        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"]);
                            strEmployeeName = strEmpFirstName + " " + strEmpLastName;
                            strlevelName = Convert.ToString(dsEmployeeDetails.Tables[0].Rows[0]["levelName"]);
                            //strEmployeeEmailId = Convert.ToString(dsEmployeeDetails.Tables[0].Rows[0]["EmailID"]);
                            strEmailIdSanctioningAuthority = Convert.ToString(dsEmployeeDetails.Tables[0].Rows[0]["ApprovalAuthorityEmailID"]);
                            strEmailIdReportingTo = Convert.ToString(dsEmployeeDetails.Tables[0].Rows[0]["ReportingToEmailID"]);
                            LevelID = Convert.ToInt32(dsEmployeeDetails.Tables[0].Rows[0]["LevelID"]);
                        }
                        if (strEmailIdSanctioningAuthority != "" || strEmailIdReportingTo != "")
                        {
                            if (rbSingleDayYes.Checked == true)
                            {
                                OndutyType = rm.GetString("rbSingleDayYes", ci);
                                strInDate = txt_ShiftDate.Text;
                                strOutDate = txt_ShiftDate.Text;
                            }

                        }
                        #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 = objCommon.CheckPageExistsInLicense(244);
                            if (smsIsRequired > 0)
                            {
                                DataSet dsGateway = new DataSet();
                                DataSet dsStatus = new DataSet();
                                bool isSmsEnabled = false;
                                string destinationKey = string.Empty;
                                string MessageKey = string.Empty;
                                string ServiceUrl = string.Empty;
                                string mobileNo = string.Empty;
                                string strTemplateName = string.Empty;
                                string strODEntryStatus = string.Empty;
                                string EmployeeName = string.Empty;
                                strODEntryStatus = strManualTimeEntryStatus;
                                if (strODEntryStatus == "Pending")
                                    strTemplateName = "OnDuty - Apply";
                                else if (strODEntryStatus == "Forwarded")
                                    strTemplateName = "OnDuty - Forward";
                                else if (strODEntryStatus == "Approved")
                                    strTemplateName = "OnDuty - Approved";
                                bool isApplyAndReceiverSame = false;
                                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)
                                                {
                                                    isSmsEnabled = Convert.ToBoolean(dsStatus.Tables[0].Rows[0]["ToEmployee"]);
                                                }
                                                if (isSmsEnabled)
                                                {
                                                    if (dsEmployeeDetails.Tables.Count > 0)
                                                    {
                                                        if (dsEmployeeDetails.Tables[0].Rows.Count > 0)
                                                        {
                                                            mobileNo = Convert.ToString(dsEmployeeDetails.Tables[0].Rows[0]["Mobile_Number"]);
                                                        }
                                                    }
                                                }
                                                if (dsEmployeeDetails.Tables.Count > 0)
                                                {
                                                    if (dsEmployeeDetails.Tables[0].Rows.Count > 0)
                                                    {
                                                        EmployeeName = Convert.ToString(dsEmployeeDetails.Tables[0].Rows[0]["Employee_FirstName"]);
                                                    }
                                                }
                                                DataSet dsReceivers = new DataSet();
                                                dsReceivers = objsms.GetReceiversDetails(strTemplateName, strEmployeeCodeId, strEmpFirstName, strInDate + " " + txt_ShiftIn.Text + " To " + strOutDate + " " + txt_ShiftOut.Text, "", Convert.ToString(""));
                                                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 (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");
                                                            }
                                                        }
                                                    }
                                                }
                                                if (mobileNo != string.Empty && isApplyAndReceiverSame != true)
                                                {
                                                    blnCheckSMS = objsms.SendSMSNotifications
                                                                    (
                                                                        ServiceUrl,
                                                                        destinationKey,
                                                                        MessageKey,
                                                                        EmployeeName,
                                                                        Convert.ToString(dsReceivers.Tables[0].Rows[0]["Message"]),
                                                                        Convert.ToString(mobileNo),
                                                                        strEmployeeCodeId,
                                                                         strTemplateName,
                                                                    Convert.ToString(strEmployeeCodeId)
                                                                    );
                                                }
                                                else if (mobileNo == string.Empty && isApplyAndReceiverSame != true)
                                                {
                                                    if (isSmsEnabled)
                                                    {
                                                        objsms.InsertLogDetails(strTemplateName, Convert.ToString(strEmployeeCodeId), strEmployeeCodeId, false, Convert.ToString(dsReceivers.Tables[0].Rows[0]["Message"]), "Mobile Number is not configured in employee master");
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Message(ex.ToString());
                        }
                        #endregion
                        //End
                    }
                    Session["EmpDetails"] = null;
                }
                string strMessage = string.Empty;

                if (gstrShiftValidation == string.Empty && gstrDOJValidation == string.Empty && gstrEmployeeIds == string.Empty)
                {
                    strMessage = rm.GetString("Msg_MannualODEntryAdded");
                    if (gintInsertCount >= 1)
                    {
                        if (blnCheckEmail == false && blnCheckSMS == true)
                        {
                            strMessage = strMessage + " ,but email not sent";
                        }
                        else if (blnCheckEmail == true && blnCheckSMS == false)
                        {
                            strMessage = strMessage + " ,but SMS is not triggered";
                        }
                        else if (blnCheckEmail == false && blnCheckSMS == false)
                        {
                            strMessage = strMessage + " ,but email not sent";
                        }
                        ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + strMessage + "'); location.replace('TA_UI_Transactions_OnDutyList.aspx');", true);
                    }
                    else
                    {
                        if (blnCheckEmail == true && blnCheckSMS == true)
                        {
                            DisplayMessage(strMessage);
                        }
                        else if (blnCheckEmail == false && blnCheckSMS == true)
                        {
                            DisplayMessage(strMessage + " ,but email not sent");
                        }
                        else if (blnCheckEmail == true && blnCheckSMS == false)
                        {
                            DisplayMessage(strMessage + " ,but SMS is not triggered");
                        }
                        else if (blnCheckEmail == false && blnCheckSMS == false)
                        {
                            DisplayMessage(strMessage + " ,but email not sent");
                        }
                        else
                        {
                            DisplayMessage(strMessage);
                        }
                    }
                }
                else if (gintInsertCount == 0)
                {
                    if (gstrDOJValidation != string.Empty)
                    {
                        strMessage = rm.GetString("Msg_MannualODDateOFJoining");
                    }
                    else if (gstrShiftValidation != string.Empty)
                    {
                        strMessage = rm.GetString("Manual_ShiftNotAllocated");
                    }
                    else if (gstrEmployeeIds != string.Empty)
                    {
                        strMessage = rm.GetString("Manual_AlreadyExists") + " " + gstrEmployeeIds;
                    }
                    else if (onDuty != string.Empty)
                    {
                        strMessage = rm.GetString("AlertSelectedintimeandouttime");
                    }
                    if (gintInsertCount >= 1)
                    {
                        ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + strMessage + "'); location.replace('TA_UI_Transactions_OnDutyList.aspx');", true);
                    }
                    else
                    {
                        DisplayMessage(strMessage);
                    }
                }
                else
                {
                    if (gstrShiftValidation == string.Empty && gstrDOJValidation != string.Empty && gstrEmployeeIds == string.Empty)
                    {
                        strMessage = "Manual OD entry added successfully except for " + gstrDOJValidation + " as entry date is before date of joining";
                    }
                    else if (gstrShiftValidation != string.Empty && gstrDOJValidation == string.Empty && gstrEmployeeIds == string.Empty)
                    {
                        strMessage = "Manual OD entry added successfully except for " + gstrShiftValidation + " as shift is not allocated";
                    }
                    else if (gstrShiftValidation == string.Empty && gstrDOJValidation == string.Empty && gstrEmployeeIds != string.Empty)
                    {
                        strMessage = "Manual OD entry added successfully except for " + gstrEmployeeIds + " as OD entry is already added";
                    }
                    else
                    {
                        strMessage = "Manual OD entry added successfully except for " + gstrShiftValidation + " " + gstrDOJValidation + " " + gstrEmployeeIds;
                    }
                    if (gintInsertCount >= 1)
                    {
                        ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + strMessage + "'); location.replace('TA_UI_Transactions_OnDutyList.aspx');", true);
                    }
                    else
                    {
                        DisplayMessage(strMessage);
                    }
                    strManualTimeEntryStatus = string.Empty;
                }

            }

            else if (rbtSingle.Checked == true)
            {
                if (TxtOnDuty.Text == "")
                {
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("Msg_FillEmployee", ci) + "');", true);
                    string scrt = "<script>ManualTimeEntry()</script>";
                    this.Page.RegisterStartupScript("a", scrt);

                    TxtOnDuty.Focus();
                    return;
                }
                DataSet dsEmpAutoId = new DataSet();

            }




            Page_Load(sender, e);
        }
        

    }


    private void DisplayShiftTimingMessage(string Message)
    {
        string strScript = "<script language='javascript' type='text/javascript'>";
        strScript += "alert('" + Message + "');";
        strScript += " </script>";
        ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", strScript, false);
    }


    public void AddManualEntryDetails_ODEntry(string EmployeeId, string Type, int EmployeeAutoId)
    {
        DataSet ds_EntranceDetails = new DataSet();
        int intInReaderId = 0, intOutReaderId = 0, intRouteId = 0, intShiftId = 0, IntWeekoffallow = 0;
        string strInDate = TxtOnDuty.Text, strOutDate = TxtOnDuty.Text, strManualTimeEntryStatusNew = string.Empty;
        gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
        Boolean ondutyEntryvalidation = new Boolean();
        ondutyEntryvalidation = Validation(EmployeeId, Type, EmployeeAutoId);
        if (ondutyEntryvalidation == true)
        {
            //if (chkHolidayOnduty == true && rbExcludingWeeklyOff.Checked == true && daysCount == 1)
            //{
            //}
            //else
            //{
                if (daysCount != 1 || chkHolidayOnduty == false)
                {
                ////ToConvertProperFormat(ref strInDate, ref strOutDate);
                string Today = DateTime.Now.ToString("dd-MMM-yyyy");
                string strEntryDate = Today;
                //string strEntryDate = objCommon.DateConvertion(gstrDateFormat,TxtOnDuty.Text );
                int intIncludeWeekOff = 2;
                manualEntryExists = objCommon.CheckPageExistsInLicense(98);
                approvalSettingsPageExists = objCommon.CheckPageExistsInLicense(228);
                if (manualEntryExists == 1)
                    {
                        if (approvalSettingsPageExists == 1)
                        {
                            int intCompanyId = base.GetCompanyId(EmployeeAutoId);
                            DataSet dsApprovalSettings = new DataSet();
                            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]["ODEntry"]) == false)
                                        {
                                            strManualTimeEntryStatus = "Approved";
                                        }
                                        else
                                        {
                                            strManualTimeEntryStatusNew = objShift.GetApprovalStatus(Convert.ToInt32(Session["EmpAutoID"]), Convert.ToString(hdnEmployeeId.Value), Convert.ToBoolean(Session["ReportsBasedOn"]));
                                            if (strManualTimeEntryStatusNew != string.Empty && strManualTimeEntryStatusNew != null)
                                            {
                                                strManualTimeEntryStatus = strManualTimeEntryStatusNew;
                                            }
                                        }
                                    }
                                    else
                                    {
                                        ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("Msg_ApprovalSettings", ci) + "');", true);
                                        return;
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        strManualTimeEntryStatus = "Approved";
                    }
                    Session["OndutyStatus"] = strManualTimeEntryStatus;
                    DataSet ds_Onduty = new DataSet();
                    hdfStartTime.Value = txt_ShiftIn.Text;
                    hdfStartEnd.Value = txt_ShiftOut.Text;
                gintUserId = Int32.Parse(Session["EmpAutoID"].ToString());


                ds_Onduty = objManualEntry.InsertOnDutyEntryForTable
                        ("I", 0, EmployeeId,
                        DateTime.Parse(strEntryDate),
                        Convert.ToInt32("1"),
                        intIncludeWeekOff,
                        strInDate,
                        txt_ShiftIn.Text,
                        strOutDate,
                        txt_ShiftOut.Text, txt_Reason.Text.Trim().Replace("'", "''"), strManualTimeEntryStatus, gintUserId, 
                        ddl_SessionFrom.SelectedValue.ToString(), ddl_SessionTo.SelectedValue.ToString());
                    if (ds_Onduty.Tables[0].Rows.Count > 0)
                    {
                        IntOndutyID = Convert.ToInt32(ds_Onduty.Tables[0].Rows[0][0]);
                    }
                }
            //}
        }
        else
        {
            return;
        }
        ////ToConvertProperFormat(ref strInDate, ref strOutDate);
        string strDateOfJoining = string.Empty;
        DataSet dsEmployeeDOJ = new DataSet();
        dsEmployeeDOJ = objEmployee.GetEmployeeDateOfJoining(EmployeeId, "", "", "S");
        if (dsEmployeeDOJ.Tables[0].Rows.Count > 0)
        {
            if (dsEmployeeDOJ.Tables[0].Rows[0]["DateOfJoining"] != DBNull.Value)
            {
                strDateOfJoining = dsEmployeeDOJ.Tables[0].Rows[0]["DateOfJoining"].ToString();
            }
        }
        DataSet dsShiftDetails = new DataSet();
        for (DateTime dtmDate = Convert.ToDateTime(strInDate); dtmDate <= Convert.ToDateTime(strOutDate); dtmDate = dtmDate.AddDays(1))
        {
            string strFlag = "Y";
            if (strDateOfJoining != string.Empty)
            {
                DateTime dtmDateOfJoining = DateTime.Parse(strDateOfJoining);
                if (dtmDate < dtmDateOfJoining)
                {
                    strFlag = "N";
                    if (gstrDOJValidation == string.Empty)
                    {
                        gstrDOJValidation = EmployeeId + "(" + dtmDate.ToString(gstrDateFormat) + ")";
                    }
                    else
                    {
                        gstrDOJValidation = gstrDOJValidation + "," + EmployeeId + "(" + dtmDate.ToString(gstrDateFormat) + ")";
                    }
                }
            }
            int count = 0;
            intShiftId = objShiftExchange.SelectShiftId(EmployeeId, dtmDate.Year.ToString(), dtmDate.Month.ToString(), dtmDate.Day.ToString());
            count = CheckAdditionalWeekOff(dtmDate, EmployeeId);
            if (count == 1)
            {
                intShiftId = -1;
            }
            if (intShiftId == 0)
            {
                strFlag = "N";
                if (gstrShiftValidation == string.Empty)
                {
                    gstrShiftValidation = EmployeeId + "(" + dtmDate.ToString(gstrDateFormat) + ")";
                }
                else
                {
                    gstrShiftValidation = gstrShiftValidation + "," + EmployeeId + "(" + dtmDate.ToString(gstrDateFormat) + ")";
                }
            }
            else if (intShiftId == -1)
            {
                //----CheckDefault Test Condition no need ---
                if (intShiftId == -1)
                {
                    DateTime dtClockDate = new DateTime();
                    dtClockDate = dtmDate;
                    do
                    {
                        if (count == 1)
                        {
                            intShiftId = -1;
                            count = 0;
                        }
                        else
                        {
                            intShiftId = objShiftExchange.SelectShiftId(EmployeeId, dtClockDate.Year.ToString(), dtClockDate.Month.ToString(), dtClockDate.Day.ToString());
                        }
                        dtClockDate = dtClockDate.AddDays(-1);
                    }
                    while (intShiftId == -1);
                    dsShiftDetails = objShift.SelectShiftById(intShiftId);
                }
                else
                {
                    IntWeekoffallow = 1;
                }
            }
            else
            {
                dsShiftDetails = objShift.SelectShiftById(intShiftId);
            }
            int intIsLeave = 0;
            if ( intShiftId != -1 && intShiftId != 0)
            {
                dsShiftDetails = objShift.SelectShiftById(intShiftId);
                DataTable dtLeaveMultiple;
                dtLeaveMultiple = objManualEntry.CheckLeaveForOnDuty(dtmDate.ToShortDateString(), Convert.ToString(EmployeeId));
                #region Getting the Shift Start time and End Time For multiple Days entries
                if (strInDate == strOutDate)
                {
                    if (dtLeaveMultiple.Rows.Count > 0)
                    {
                        if (dtLeaveMultiple.Rows[0][0].ToString() != "NoLeave" && dtLeaveMultiple.Rows[0][1].ToString() != "NoLeave")
                        {
                            if (dtLeaveMultiple.Rows[0]["Leave_SessionFrom"].ToString() == "First half" && dtLeaveMultiple.Rows[0]["Leave_SessionTo"].ToString() == "First half")
                            {
                                if (ddl_SessionFrom.SelectedItem.Text == "First half" && ddl_SessionTo.SelectedItem.Text == "First half")
                                {
                                    intIsLeave = 2;
                                }
                                else if (ddl_SessionFrom.SelectedItem.Text == "Second half" && ddl_SessionTo.SelectedItem.Text == "Second half")
                                {
                                    txt_ShiftIn.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_SecondHalf_StartTime"].ToString();
                                    txt_ShiftOut.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_EndTime"].ToString();
                                }
                                if (ddl_SessionFrom.SelectedItem.Text == "First half" && ddl_SessionTo.SelectedItem.Text == "Second half")
                                {
                                    txt_ShiftIn.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_SecondHalf_StartTime"].ToString();
                                    txt_ShiftOut.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_EndTime"].ToString();
                                }
                            }
                            else if (dtLeaveMultiple.Rows[0]["Leave_SessionFrom"].ToString() == "Second half" && dtLeaveMultiple.Rows[0]["Leave_SessionTo"].ToString() == "Second half")
                            {
                                if (ddl_SessionFrom.SelectedItem.Text == "First half" && ddl_SessionTo.SelectedItem.Text == "First half")
                                {
                                    txt_ShiftIn.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_StartTime"].ToString();
                                    txt_ShiftOut.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_FirstHalf_EndTime"].ToString();
                                }
                                else if (ddl_SessionFrom.SelectedItem.Text == "Second half" && ddl_SessionTo.SelectedItem.Text == "Second half")
                                {
                                    intIsLeave = 2;
                                }
                                if (ddl_SessionFrom.SelectedItem.Text == "First half" && ddl_SessionTo.SelectedItem.Text == "Second half")
                                {
                                    txt_ShiftIn.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_StartTime"].ToString();
                                    txt_ShiftOut.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_FirstHalf_EndTime"].ToString();
                                }
                            }
                            else
                            {
                                intIsLeave = 2;
                            }
                        }
                        else
                        {
                            if (ddl_SessionFrom.SelectedItem.Text == "First half" && ddl_SessionTo.SelectedItem.Text == "First half")
                            {
                                txt_ShiftIn.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_StartTime"].ToString();
                                txt_ShiftOut.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_FirstHalf_EndTime"].ToString();
                            }
                            else if (ddl_SessionFrom.SelectedItem.Text == "Second half" && ddl_SessionTo.SelectedItem.Text == "Second half")
                            {
                                txt_ShiftIn.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_SecondHalf_StartTime"].ToString();
                                txt_ShiftOut.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_EndTime"].ToString();
                            }
                            if (ddl_SessionFrom.SelectedItem.Text == "First half" && ddl_SessionTo.SelectedItem.Text == "Second half")
                            {
                                txt_ShiftIn.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_StartTime"].ToString();
                                txt_ShiftOut.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_EndTime"].ToString();
                            }
                        }
                    }
                }
                else
                {
                    if (dtmDate < Convert.ToDateTime(strOutDate))
                    {
                        if (dtmDate == Convert.ToDateTime(strInDate))
                        {
                            if (dtLeaveMultiple.Rows.Count > 0)
                            {
                                if (dtLeaveMultiple.Rows[0][0].ToString() != "NoLeave" && dtLeaveMultiple.Rows[0][1].ToString() != "NoLeave")
                                {
                                    if (dtLeaveMultiple.Rows[0]["Leave_SessionFrom"].ToString() == "First half" && dtLeaveMultiple.Rows[0]["Leave_SessionTo"].ToString() == "First half")
                                    {
                                        if (ddl_SessionFrom.SelectedItem.Text == "First half" && ddl_SessionTo.SelectedItem.Text == "First half")
                                        {
                                            txt_ShiftIn.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_SecondHalf_StartTime"].ToString();
                                            txt_ShiftOut.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_EndTime"].ToString();
                                        }
                                        else if (ddl_SessionFrom.SelectedItem.Text == "Second half" && ddl_SessionTo.SelectedItem.Text == "Second half")
                                        {
                                            txt_ShiftIn.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_SecondHalf_StartTime"].ToString();
                                            txt_ShiftOut.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_EndTime"].ToString();
                                        }
                                        else if (ddl_SessionFrom.SelectedItem.Text == "First half" && ddl_SessionTo.SelectedItem.Text == "Second half")
                                        {
                                            txt_ShiftIn.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_SecondHalf_StartTime"].ToString();
                                            txt_ShiftOut.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_EndTime"].ToString();
                                        }
                                        else if (ddl_SessionFrom.SelectedItem.Text == "Second half" && ddl_SessionTo.SelectedItem.Text == "First half")
                                        {
                                            txt_ShiftIn.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_SecondHalf_StartTime"].ToString();
                                            txt_ShiftOut.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_EndTime"].ToString();
                                        }
                                    }
                                    else if (dtLeaveMultiple.Rows[0]["Leave_SessionFrom"].ToString() == "Second half" && dtLeaveMultiple.Rows[0]["Leave_SessionTo"].ToString() == "Second half")
                                    {
                                        if (ddl_SessionFrom.SelectedItem.Text == "First half" && ddl_SessionTo.SelectedItem.Text == "First half")
                                        {
                                            txt_ShiftIn.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_StartTime"].ToString();
                                            txt_ShiftOut.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_FirstHalf_EndTime"].ToString();
                                        }
                                        else if (ddl_SessionFrom.SelectedItem.Text == "Second half" && ddl_SessionTo.SelectedItem.Text == "Second half")
                                        {
                                            intIsLeave = 2;
                                        }
                                        else if (ddl_SessionFrom.SelectedItem.Text == "First half" && ddl_SessionTo.SelectedItem.Text == "Second half")
                                        {
                                            txt_ShiftIn.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_StartTime"].ToString();
                                            txt_ShiftOut.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_FirstHalf_EndTime"].ToString();
                                        }
                                        else if (ddl_SessionFrom.SelectedItem.Text == "Second half" && ddl_SessionTo.SelectedItem.Text == "First half")
                                        {
                                            intIsLeave = 2;
                                        }
                                    }
                                    else
                                    {
                                        intIsLeave = 2;
                                    }
                                }
                                else
                                {
                                    if (ddl_SessionFrom.SelectedItem.Text == "First half" && ddl_SessionTo.SelectedItem.Text == "First half")
                                    {
                                        txt_ShiftIn.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_StartTime"].ToString();
                                        txt_ShiftOut.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_EndTime"].ToString();
                                    }
                                    else if (ddl_SessionFrom.SelectedItem.Text == "Second half" && ddl_SessionTo.SelectedItem.Text == "Second half")
                                    {
                                        txt_ShiftIn.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_SecondHalf_StartTime"].ToString();
                                        txt_ShiftOut.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_EndTime"].ToString();
                                    }
                                    if (ddl_SessionFrom.SelectedItem.Text == "First half" && ddl_SessionTo.SelectedItem.Text == "Second half")
                                    {
                                        txt_ShiftIn.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_StartTime"].ToString();
                                        txt_ShiftOut.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_EndTime"].ToString();
                                    }
                                    if (ddl_SessionFrom.SelectedItem.Text == "Second half" && ddl_SessionTo.SelectedItem.Text == "First half")
                                    {
                                        txt_ShiftIn.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_SecondHalf_StartTime"].ToString();
                                        txt_ShiftOut.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_EndTime"].ToString();
                                    }
                                }
                            }
                        }
                        else
                        {
                            if (dtLeaveMultiple.Rows.Count > 0)
                            {
                                if (dtLeaveMultiple.Rows[0][0].ToString() != "NoLeave" && dtLeaveMultiple.Rows[0][1].ToString() != "NoLeave")
                                {
                                    if (dtLeaveMultiple.Rows[0]["Leave_SessionFrom"].ToString() == "First half" && dtLeaveMultiple.Rows[0]["Leave_SessionTo"].ToString() == "First half")
                                    {
                                        if (ddl_SessionFrom.SelectedItem.Text == "First half" && ddl_SessionTo.SelectedItem.Text == "First half")
                                        {
                                            txt_ShiftIn.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_SecondHalf_StartTime"].ToString();
                                            txt_ShiftOut.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_EndTime"].ToString();
                                        }
                                        else if (ddl_SessionFrom.SelectedItem.Text == "Second half" && ddl_SessionTo.SelectedItem.Text == "Second half")
                                        {
                                            txt_ShiftIn.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_SecondHalf_StartTime"].ToString();
                                            txt_ShiftOut.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_EndTime"].ToString();
                                        }
                                        else if (ddl_SessionFrom.SelectedItem.Text == "First half" && ddl_SessionTo.SelectedItem.Text == "Second half")
                                        {
                                            txt_ShiftIn.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_SecondHalf_StartTime"].ToString();
                                            txt_ShiftOut.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_EndTime"].ToString();
                                        }
                                        else if (ddl_SessionFrom.SelectedItem.Text == "Second half" && ddl_SessionTo.SelectedItem.Text == "First half")
                                        {
                                            txt_ShiftIn.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_SecondHalf_StartTime"].ToString();
                                            txt_ShiftOut.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_EndTime"].ToString();
                                        }
                                    }
                                    else if (dtLeaveMultiple.Rows[0]["Leave_SessionFrom"].ToString() == "Second half" && dtLeaveMultiple.Rows[0]["Leave_SessionTo"].ToString() == "Second half")
                                    {
                                        if (ddl_SessionFrom.SelectedItem.Text == "First half" && ddl_SessionTo.SelectedItem.Text == "First half")
                                        {
                                            txt_ShiftIn.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_StartTime"].ToString();
                                            txt_ShiftOut.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_FirstHalf_EndTime"].ToString();
                                        }
                                        else if (ddl_SessionFrom.SelectedItem.Text == "Second half" && ddl_SessionTo.SelectedItem.Text == "Second half")
                                        {
                                            intIsLeave = 2;
                                        }
                                        else if (ddl_SessionFrom.SelectedItem.Text == "First half" && ddl_SessionTo.SelectedItem.Text == "Second half")
                                        {
                                            txt_ShiftIn.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_StartTime"].ToString();
                                            txt_ShiftOut.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_FirstHalf_EndTime"].ToString();
                                        }
                                        else if (ddl_SessionFrom.SelectedItem.Text == "Second half" && ddl_SessionTo.SelectedItem.Text == "First half")
                                        {
                                            intIsLeave = 2;
                                        }
                                    }
                                    else
                                    {
                                        intIsLeave = 2;
                                    }
                                }
                                else
                                {
                                    txt_ShiftIn.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_StartTime"].ToString();
                                    txt_ShiftOut.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_EndTime"].ToString();
                                }
                            }
                        }
                    }
                    else
                    {
                        if (dtLeaveMultiple.Rows.Count > 0)
                        {
                            if (dtLeaveMultiple.Rows[0][0].ToString() != "NoLeave" && dtLeaveMultiple.Rows[0][1].ToString() != "NoLeave")
                            {
                                if (dtLeaveMultiple.Rows[0]["Leave_SessionFrom"].ToString() == "First half" && dtLeaveMultiple.Rows[0]["Leave_SessionTo"].ToString() == "First half")
                                {
                                    if (ddl_SessionFrom.SelectedItem.Text == "First half" && ddl_SessionTo.SelectedItem.Text == "First half")
                                    {
                                        intIsLeave = 2;
                                    }
                                    else if (ddl_SessionFrom.SelectedItem.Text == "Second half" && ddl_SessionTo.SelectedItem.Text == "Second half")
                                    {
                                        txt_ShiftIn.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_SecondHalf_StartTime"].ToString();
                                        txt_ShiftOut.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_EndTime"].ToString();
                                    }
                                    if (ddl_SessionFrom.SelectedItem.Text == "First half" && ddl_SessionTo.SelectedItem.Text == "Second half")
                                    {
                                        txt_ShiftIn.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_SecondHalf_StartTime"].ToString();
                                        txt_ShiftOut.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_EndTime"].ToString();
                                    }
                                }
                                else if (dtLeaveMultiple.Rows[0]["Leave_SessionFrom"].ToString() == "Second half" && dtLeaveMultiple.Rows[0]["Leave_SessionTo"].ToString() == "Second half")
                                {
                                    if (ddl_SessionFrom.SelectedItem.Text == "First half" && ddl_SessionTo.SelectedItem.Text == "First half")
                                    {
                                        txt_ShiftIn.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_StartTime"].ToString();
                                        txt_ShiftOut.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_FirstHalf_EndTime"].ToString();
                                    }
                                    else if (ddl_SessionFrom.SelectedItem.Text == "Second half" && ddl_SessionTo.SelectedItem.Text == "Second half")
                                    {
                                        intIsLeave = 2;
                                    }
                                    if (ddl_SessionFrom.SelectedItem.Text == "First half" && ddl_SessionTo.SelectedItem.Text == "Second half")
                                    {
                                        txt_ShiftIn.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_StartTime"].ToString();
                                        txt_ShiftOut.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_EndTime"].ToString();
                                    }
                                    // Below line is added by gopi for Mantis Bug.No.31981
                                    if (ddl_SessionFrom.SelectedItem.Text == "Second half" && ddl_SessionTo.SelectedItem.Text == "First half")
                                    {
                                        txt_ShiftIn.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_StartTime"].ToString();
                                        txt_ShiftOut.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_FirstHalf_EndTime"].ToString();
                                    }
                                }
                                else
                                {
                                    intIsLeave = 2;
                                }
                            }
                            else
                            {
                                if (ddl_SessionFrom.SelectedItem.Text == "First half" && ddl_SessionTo.SelectedItem.Text == "First half")
                                {
                                    txt_ShiftIn.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_StartTime"].ToString();
                                    txt_ShiftOut.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_FirstHalf_EndTime"].ToString();
                                }
                                else if (ddl_SessionFrom.SelectedItem.Text == "Second half" && ddl_SessionTo.SelectedItem.Text == "Second half")
                                {
                                    txt_ShiftIn.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_StartTime"].ToString();
                                    txt_ShiftOut.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_EndTime"].ToString();
                                }
                                if (ddl_SessionFrom.SelectedItem.Text == "First half" && ddl_SessionTo.SelectedItem.Text == "Second half")
                                {
                                    txt_ShiftIn.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_StartTime"].ToString();
                                    txt_ShiftOut.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_EndTime"].ToString();
                                }
                                if (ddl_SessionFrom.SelectedItem.Text == "Second half" && ddl_SessionTo.SelectedItem.Text == "First half")
                                {
                                    txt_ShiftIn.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_StartTime"].ToString();
                                    txt_ShiftOut.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_FirstHalf_EndTime"].ToString();
                                }
                            }
                        }
                    }
                }
            }
            #endregion
            int intIsPermission = 0, ShiftId_Before = 0, ShiftId_After = 0;
            DateTime dtCurrentDate = dtmDate;
            if (intShiftId != 0 && intShiftId != -1)
            {
                if (dsShiftDetails.Tables[0].Rows[0]["Shift_StartTime"].ToString().Contains("PM") && dsShiftDetails.Tables[0].Rows[0]["Shift_EndTime"].ToString().Contains("AM"))
                {
                    if (strInDate == objCommon.DateConvertion(gstrDateFormat, dtmDate.ToString(gstrDateFormat)))
                    {
                        if (txt_ShiftIn.Text.Contains("PM") && txt_ShiftOut.Text.Contains("AM"))
                        {
                            intIsPermission = objManualEntry.CheckPermissionForOnDuty(EmployeeId, dtmDate.ToShortDateString(), txt_ShiftIn.Text, dtmDate.AddDays(1).ToShortDateString(), txt_ShiftOut.Text);
                        }
                        else if (txt_ShiftIn.Text.Contains("AM") && txt_ShiftOut.Text.Contains("AM"))
                        {
                            intIsPermission = objManualEntry.CheckPermissionForOnDuty(EmployeeId, dtmDate.AddDays(1).ToShortDateString(), txt_ShiftIn.Text, dtmDate.AddDays(1).ToShortDateString(), txt_ShiftOut.Text);
                        }
                        else
                        {
                            intIsPermission = objManualEntry.CheckPermissionForOnDuty(EmployeeId, dtmDate.ToShortDateString(), txt_ShiftIn.Text, dtmDate.ToShortDateString(), txt_ShiftOut.Text);
                        }
                    }
                    else if (strOutDate == objCommon.DateConvertion(gstrDateFormat, dtmDate.ToString(gstrDateFormat)))
                    {
                        if (txt_ShiftIn.Text.Contains("PM") && txt_ShiftOut.Text.Contains("AM"))
                        {
                            intIsPermission = objManualEntry.CheckPermissionForOnDuty(EmployeeId, dtmDate.ToShortDateString(), dsShiftDetails.Tables[0].Rows[0]["Shift_StartTime"].ToString(), dtmDate.AddDays(1).ToShortDateString(), txt_ShiftOut.Text);
                        }
                        else if (txt_ShiftIn.Text.Contains("AM") && txt_ShiftOut.Text.Contains("AM"))
                        {
                            intIsPermission = objManualEntry.CheckPermissionForOnDuty(EmployeeId, dtmDate.AddDays(1).ToShortDateString(), dsShiftDetails.Tables[0].Rows[0]["Shift_StartTime"].ToString(), dtmDate.AddDays(1).ToShortDateString(), txt_ShiftOut.Text);
                        }
                        else
                        {
                            intIsPermission = objManualEntry.CheckPermissionForOnDuty(EmployeeId, dtmDate.ToShortDateString(), dsShiftDetails.Tables[0].Rows[0]["Shift_StartTime"].ToString(), dtmDate.ToShortDateString(), txt_ShiftOut.Text);
                        }
                    }
                    else
                    {
                        if (txt_ShiftIn.Text.Contains("PM") && txt_ShiftOut.Text.Contains("AM"))
                        {
                            intIsPermission = objManualEntry.CheckPermissionForOnDuty(EmployeeId, dtmDate.ToShortDateString(), dsShiftDetails.Tables[0].Rows[0]["Shift_StartTime"].ToString(), dtmDate.AddDays(1).ToShortDateString(), dsShiftDetails.Tables[0].Rows[0]["Shift_EndTime"].ToString());
                        }
                        else if (txt_ShiftIn.Text.Contains("AM") && txt_ShiftOut.Text.Contains("AM"))
                        {
                            intIsPermission = objManualEntry.CheckPermissionForOnDuty(EmployeeId, dtmDate.AddDays(1).ToShortDateString(), dsShiftDetails.Tables[0].Rows[0]["Shift_StartTime"].ToString(), dtmDate.AddDays(1).ToShortDateString(), dsShiftDetails.Tables[0].Rows[0]["Shift_EndTime"].ToString());
                        }
                        else
                        {
                            intIsPermission = objManualEntry.CheckPermissionForOnDuty(EmployeeId, dtmDate.ToShortDateString(), dsShiftDetails.Tables[0].Rows[0]["Shift_StartTime"].ToString(), dtmDate.ToShortDateString(), dsShiftDetails.Tables[0].Rows[0]["Shift_EndTime"].ToString());
                        }
                    }
                }
                else
                {
                    if (strInDate == objCommon.DateConvertion(gstrDateFormat, dtmDate.ToString(gstrDateFormat)))
                    {
                        intIsPermission = objManualEntry.CheckPermissionForOnDuty(EmployeeId, dtmDate.ToShortDateString(), txt_ShiftIn.Text, dtmDate.ToShortDateString(), txt_ShiftOut.Text);
                    }
                    else if (strOutDate == objCommon.DateConvertion(gstrDateFormat, dtmDate.ToString(gstrDateFormat)))
                    {
                        intIsPermission = objManualEntry.CheckPermissionForOnDuty(EmployeeId, dtmDate.ToShortDateString(), dsShiftDetails.Tables[0].Rows[0]["Shift_StartTime"].ToString(), dtmDate.ToShortDateString(), txt_ShiftOut.Text);
                    }
                    else
                    {
                        intIsPermission = objManualEntry.CheckPermissionForOnDuty(EmployeeId, dtmDate.ToShortDateString(), dsShiftDetails.Tables[0].Rows[0]["Shift_StartTime"].ToString(), dtmDate.ToShortDateString(), dsShiftDetails.Tables[0].Rows[0]["Shift_EndTime"].ToString());
                    }
                }
            }
            int IntIsHolidayEntry = 0;
            DataTable dtHoliday;
            dtHoliday = objHolidayEventData.CheckDateForHoliday(dtmDate.ToShortDateString(), EmployeeId);
            if (dtHoliday.Rows.Count > 0)
            {
                //if (rbExcludingWeeklyOff.Checked == true)
                //{
                //    IntIsHolidayEntry = 1;
                //}
            }
            if (rbSingleDayYes.Checked == true && intShiftId != -1 && intShiftId != 0)
            {
                DataTable dtLeave;
                dtLeave = objManualEntry.CheckLeaveForOnDuty(dtmDate.ToShortDateString(), Convert.ToString(EmployeeId));
                if (dtLeave.Rows.Count > 0)
                {
                    if (dtLeave.Rows[0]["Leave_SessionFrom"].ToString() == "First half" && dtLeave.Rows[0]["Leave_SessionTo"].ToString() == "First half")
                    {
                        if (dsShiftDetails.Tables[0].Rows[0]["Shift_StartTime"].ToString().Contains("PM") && dsShiftDetails.Tables[0].Rows[0]["Shift_EndTime"].ToString().Contains("AM"))
                        {
                            if (DateTime.Parse(txt_ShiftIn.Text.ToString()) >= DateTime.Parse(dsShiftDetails.Tables[0].Rows[0]["Shift_StartTime"].ToString()))
                            {
                                intIsLeave = 1;
                            }
                        }
                        else if ((DateTime.Parse(txt_ShiftIn.Text.ToString()) >= DateTime.Parse(dsShiftDetails.Tables[0].Rows[0]["Shift_StartTime"].ToString()))
                             && (DateTime.Parse(txt_ShiftIn.Text.ToString()) <= DateTime.Parse(dsShiftDetails.Tables[0].Rows[0]["Shift_FirstHalf_EndTime"].ToString())))
                        {
                            intIsLeave = 1;
                        }
                    }
                    else if (dtLeave.Rows[0]["Leave_SessionFrom"].ToString() == "Second half" && dtLeave.Rows[0]["Leave_SessionTo"].ToString() == "Second half")
                    {
                        if (dsShiftDetails.Tables[0].Rows[0]["Shift_StartTime"].ToString().Contains("PM") && dsShiftDetails.Tables[0].Rows[0]["Shift_EndTime"].ToString().Contains("AM"))
                        {
                            if (DateTime.Parse(txt_ShiftIn.Text.ToString()) <= DateTime.Parse(dsShiftDetails.Tables[0].Rows[0]["Shift_EndTime"].ToString()))
                            {
                                intIsLeave = 1;
                            }
                        }
                        else if ((DateTime.Parse(txt_ShiftOut.Text.ToString()) >= DateTime.Parse(dsShiftDetails.Tables[0].Rows[0]["Shift_SecondHalf_StartTime"].ToString()))
                        && (DateTime.Parse(txt_ShiftIn.Text.ToString()) <= DateTime.Parse(dsShiftDetails.Tables[0].Rows[0]["Shift_EndTime"].ToString())))
                        {
                            intIsLeave = 1;
                        }
                    }
                    else if (dtLeave.Rows[0]["Leave_SessionFrom"].ToString() == "First half" && dtLeave.Rows[0]["Leave_SessionTo"].ToString() == "Second half")
                    {
                        intIsLeave = 2;
                    }
                }
            }
            if (IntWeekoffallow == 1)
            {
                intShiftId = -1;
            }
            if (intShiftId != 0)
            {
                if (IntIsHolidayEntry == 0)
                {
                    if (intIsLeave < 2)
                    {
                        if (intIsPermission != 0)
                        {
                            if (gintInsertCount >= 1)
                            {
                                string TESTPermission = "Permission entry is already availed For this Duration " + dtmDate.ToString(gstrDateFormat);
                                ScriptManager.RegisterStartupScript(this, GetType(), "Alert", "alert('" + TESTPermission + "'); location.replace('TA_UI_Transactions_OnDutyList.aspx');", true);
                            }
                            else
                            {
                                string TESTPermission = "Permission entry is already availed For this Duration " + dtmDate.ToString(gstrDateFormat);
                                ScriptManager.RegisterStartupScript(this, GetType(), "Alert", "alert('" + TESTPermission + "');", true);
                            }
                        }
                        else
                        {
                            if (intShiftId != -1)
                            {
                                if (intShiftId != 0)
                                {
                                    if ((strInDate == objCommon.DateConvertion(gstrDateFormat, dtmDate.ToString(gstrDateFormat))) && (strOutDate == objCommon.DateConvertion(gstrDateFormat, dtmDate.ToString(gstrDateFormat))))
                                    {
                                        if (txt_ShiftIn.Text.Contains("PM") && txt_ShiftOut.Text.Contains("AM"))
                                        {
                                            count = objManualEntry.CheckManualODEntry(EmployeeId, dtmDate.ToShortDateString(), txt_ShiftIn.Text, dtmDate.AddDays(1).ToShortDateString(), txt_ShiftOut.Text);
                                        }
                                        else if (txt_ShiftIn.Text.Contains("AM") && txt_ShiftOut.Text.Contains("AM"))
                                        {
                                            if (Convert.ToDateTime(dsShiftDetails.Tables[0].Rows[0]["Shift_StartTime"]).ToString("hh:mm:ss tt").Contains("PM") && Convert.ToDateTime(dsShiftDetails.Tables[0].Rows[0]["Shift_EndTime"]).ToString("hh:mm:ss tt").Contains("AM"))
                                            {
                                                count = objManualEntry.CheckManualODEntry(EmployeeId, dtmDate.AddDays(1).ToShortDateString(), txt_ShiftIn.Text, dtmDate.AddDays(1).ToShortDateString(), txt_ShiftOut.Text);
                                            }
                                            else
                                            {
                                                count = objManualEntry.CheckManualODEntry(EmployeeId, dtmDate.ToShortDateString(), txt_ShiftIn.Text, dtmDate.ToShortDateString(), txt_ShiftOut.Text);
                                            }
                                        }
                                        else
                                        {
                                            count = objManualEntry.CheckManualODEntry(EmployeeId, dtmDate.ToShortDateString(), txt_ShiftIn.Text, dtmDate.ToShortDateString(), txt_ShiftOut.Text);
                                        }
                                    }
                                    else if (strInDate == objCommon.DateConvertion(gstrDateFormat, dtmDate.ToString(gstrDateFormat)))
                                    {
                                        if (txt_ShiftIn.Text.Contains("PM") && txt_ShiftOut.Text.Contains("AM"))
                                        {
                                            count = objManualEntry.CheckManualODEntry(EmployeeId, dtmDate.ToShortDateString(), txt_ShiftIn.Text, dtmDate.AddDays(1).ToShortDateString(), (strOutDate == objCommon.DateConvertion(gstrDateFormat, dtmDate.AddDays(1).ToString(gstrDateFormat))) ? txt_ShiftOut.Text : Convert.ToString(dsShiftDetails.Tables[0].Rows[0]["Shift_EndTime"]));
                                        }
                                        else if (txt_ShiftIn.Text.Contains("AM") && txt_ShiftOut.Text.Contains("AM"))
                                        {
                                            if (Convert.ToDateTime(dsShiftDetails.Tables[0].Rows[0]["Shift_StartTime"]).ToString("hh:mm:ss tt").Contains("PM") && Convert.ToDateTime(dsShiftDetails.Tables[0].Rows[0]["Shift_EndTime"]).ToString("hh:mm:ss tt").Contains("AM"))
                                            {
                                                count = objManualEntry.CheckManualODEntry(EmployeeId, dtmDate.AddDays(1).ToShortDateString(), txt_ShiftIn.Text, dtmDate.AddDays(1).ToShortDateString(), (strOutDate == objCommon.DateConvertion(gstrDateFormat, dtmDate.AddDays(1).ToString(gstrDateFormat))) ? txt_ShiftOut.Text : Convert.ToString(dsShiftDetails.Tables[0].Rows[0]["Shift_EndTime"]));
                                            }
                                            else
                                            {
                                                count = objManualEntry.CheckManualODEntry(EmployeeId, dtmDate.AddDays(1).ToShortDateString(), txt_ShiftIn.Text, dtmDate.AddDays(1).ToShortDateString(), txt_ShiftOut.Text);
                                            }
                                        }
                                        else
                                        {
                                            count = objManualEntry.CheckManualODEntry(EmployeeId, dtmDate.ToShortDateString(), txt_ShiftIn.Text, dtmDate.ToShortDateString(), (strOutDate == objCommon.DateConvertion(gstrDateFormat, dtmDate.AddDays(1).ToString(gstrDateFormat))) ? txt_ShiftOut.Text : Convert.ToString(dsShiftDetails.Tables[0].Rows[0]["Shift_EndTime"]));
                                        }
                                    }
                                    else if (strOutDate == objCommon.DateConvertion(gstrDateFormat, dtmDate.ToString(gstrDateFormat)))
                                    {
                                        if (txt_ShiftIn.Text.Contains("PM") && txt_ShiftOut.Text.Contains("AM"))
                                        {
                                            count = objManualEntry.CheckManualODEntry(EmployeeId, dtmDate.ToShortDateString(), Convert.ToDateTime(dsShiftDetails.Tables[0].Rows[0]["Shift_StartTime"]).ToString("hh:mm:ss tt"), dtmDate.AddDays(1).ToShortDateString(), txt_ShiftOut.Text);
                                        }
                                        else if (txt_ShiftIn.Text.Contains("AM") && txt_ShiftOut.Text.Contains("AM"))
                                        {
                                            if (Convert.ToDateTime(dsShiftDetails.Tables[0].Rows[0]["Shift_StartTime"]).ToString("hh:mm:ss tt").Contains("PM") && Convert.ToDateTime(dsShiftDetails.Tables[0].Rows[0]["Shift_EndTime"]).ToString("hh:mm:ss tt").Contains("AM"))
                                            {
                                                count = objManualEntry.CheckManualODEntry(EmployeeId, dtmDate.AddDays(1).ToShortDateString(), txt_ShiftIn.Text, dtmDate.AddDays(1).ToShortDateString(), txt_ShiftOut.Text);
                                            }
                                            else
                                            {
                                                count = objManualEntry.CheckManualODEntry(EmployeeId, dtmDate.ToShortDateString(), txt_ShiftIn.Text, dtmDate.ToShortDateString(), txt_ShiftOut.Text);
                                            }
                                        }
                                        else
                                        {
                                            count = objManualEntry.CheckManualODEntry(EmployeeId, dtmDate.ToShortDateString(), txt_ShiftIn.Text, dtmDate.ToShortDateString(), txt_ShiftOut.Text);
                                        }
                                    }
                                    else
                                    {
                                        if (txt_ShiftIn.Text.Contains("PM") && txt_ShiftOut.Text.Contains("AM"))
                                        {
                                            count = objManualEntry.CheckManualODEntry(EmployeeId, dtmDate.ToShortDateString(), Convert.ToDateTime(dsShiftDetails.Tables[0].Rows[0]["Shift_StartTime"]).ToString("hh:mm:ss tt"), dtmDate.AddDays(1).ToShortDateString(), (strOutDate == objCommon.DateConvertion(gstrDateFormat, dtmDate.AddDays(1).ToString(gstrDateFormat))) ? txt_ShiftOut.Text : Convert.ToString(dsShiftDetails.Tables[0].Rows[0]["Shift_EndTime"]));
                                        }
                                        else if (txt_ShiftIn.Text.Contains("AM") && txt_ShiftOut.Text.Contains("AM"))
                                        {
                                            if (Convert.ToDateTime(dsShiftDetails.Tables[0].Rows[0]["Shift_StartTime"]).ToString("hh:mm:ss tt").Contains("PM") && Convert.ToDateTime(dsShiftDetails.Tables[0].Rows[0]["Shift_EndTime"]).ToString("hh:mm:ss tt").Contains("AM"))
                                            {
                                                count = objManualEntry.CheckManualODEntry(EmployeeId, dtmDate.AddDays(1).ToShortDateString(), txt_ShiftIn.Text, dtmDate.AddDays(1).ToShortDateString(), txt_ShiftOut.Text);
                                            }
                                            else
                                            {
                                                count = objManualEntry.CheckManualODEntry(EmployeeId, dtmDate.ToShortDateString(), txt_ShiftIn.Text, dtmDate.ToShortDateString(), txt_ShiftOut.Text);
                                            }
                                        }
                                        else
                                        {
                                            count = objManualEntry.CheckManualODEntry(EmployeeId, dtmDate.ToShortDateString(), txt_ShiftIn.Text, dtmDate.ToShortDateString(), txt_ShiftOut.Text);
                                        }
                                    }
                                }

                                string strActualShiftIn1 = (dsShiftDetails.Tables[0].Rows[0]["Shift_StartTime"].ToString());
                                string strActualShiftOut1 = (dsShiftDetails.Tables[0].Rows[0]["Shift_EndTime"].ToString());
                                DateTime dttActualShiftIn1 = DateTime.Parse(strActualShiftIn1);
                                DateTime dttAcutalShiftOut1 = DateTime.Parse(strActualShiftOut1);
                                DateTime dttShiftIn1 = DateTime.Parse(txt_ShiftIn.Text);
                                DateTime dttShiftOut1 = DateTime.Parse(txt_ShiftOut.Text);
                                if (Convert.ToString(dsShiftDetails.Tables[0].Rows[0]["Shift_StartTime"]).Contains("PM") && Convert.ToString(dsShiftDetails.Tables[0].Rows[0]["Shift_EndTime"]).Contains("AM"))
                                {
                                    dttAcutalShiftOut1 = dttAcutalShiftOut1.AddDays(1);
                                    if (txt_ShiftIn.Text.Contains("AM"))
                                    {
                                        dttShiftIn1 = dttShiftIn1.AddDays(1);
                                        dttShiftOut1 = dttShiftOut1.AddDays(1);
                                    }
                                    else
                                    {
                                        if (txt_ShiftOut.Text.Contains("AM"))
                                        {
                                            dttShiftOut1 = dttShiftOut1.AddDays(1);
                                        }
                                    }
                                }
                                if (hdnAllowMax != null)
                                {
                                    if (hdnAllowMax.Value != null)
                                    {
                                        dttAcutalShiftOut1 = dttAcutalShiftOut1.AddHours(Convert.ToInt32(hdnAllowMax.Value));
                                    }
                                    else
                                    {
                                        dttAcutalShiftOut1 = dttAcutalShiftOut1.AddHours(2);
                                    }
                                }
                                if (dttShiftIn1 >= dttActualShiftIn1 && dttShiftOut1 <= dttAcutalShiftOut1)
                                {
                                    if (txt_ShiftIn.Text.Contains("AM") && txt_ShiftOut.Text.Contains("AM"))
                                    {
                                        if (dttShiftOut1 < dttShiftIn1)
                                        {
                                            string onDuty1 = rm.GetString("AlertSelectedintimeandouttime");
                                            DisplayShiftTimingMessage(onDuty1);
                                            return;
                                        }
                                    }
                                }
                                else
                                {
                                    if (Convert.ToDateTime(dsShiftDetails.Tables[0].Rows[0]["Shift_StartTime"]).ToString("hh:mm:ss tt").Contains("PM") && Convert.ToDateTime(dsShiftDetails.Tables[0].Rows[0]["Shift_EndTime"]).ToString("hh:mm:ss tt").Contains("AM"))
                                    {
                                        if (txt_ShiftIn.Text.Contains("AM") && txt_ShiftOut.Text.Contains("AM"))
                                        {
                                            if (dttShiftIn1 >= dttActualShiftIn1.AddDays(-1) && dttShiftOut1 <= dttAcutalShiftOut1)
                                            {
                                                if (dttShiftOut1 < dttShiftIn1)
                                                {
                                                    string onDuty1 = rm.GetString("AlertSelectedintimeandouttime");
                                                    DisplayShiftTimingMessage(onDuty1);
                                                    return;
                                                }
                                            }
                                            else
                                            {
                                                string onDuty1 = rm.GetString("AlertSelectedintimeandouttime");
                                                DisplayShiftTimingMessage(onDuty1);
                                                return;
                                            }
                                        }
                                        else if (txt_ShiftIn.Text.Contains("PM") && txt_ShiftOut.Text.Contains("AM"))
                                        {
                                            if (dttShiftIn1 >= dttActualShiftIn1 && dttShiftOut1.AddDays(1) <= dttAcutalShiftOut1)
                                            {
                                            }
                                            else
                                            {
                                                string onDuty1 = rm.GetString("AlertSelectedintimeandouttime");
                                                DisplayShiftTimingMessage(onDuty1);
                                                return;
                                            }
                                        }
                                    }
                                    else
                                    {
                                        string onDuty1 = rm.GetString("AlertSelectedintimeandouttime");
                                        DisplayShiftTimingMessage(onDuty1);
                                        return;
                                    }
                                }
                                if (count == 0)
                                {
                                    if (strFlag == "Y")
                                    {
                                        string strInPunchType = hdn_InPunchType.Value;
                                        string strOutPunchType = hdn_OutPunchType.Value;
                                        if (hdn_InTerminal.Value != "")
                                        {
                                            intInReaderId = Convert.ToInt32(hdn_InTerminal.Value);
                                        }
                                        else
                                        {
                                            intInReaderId = 0;
                                        }
                                        if (hdn_OutTerminal.Value != "")
                                        {
                                            intOutReaderId = Convert.ToInt32(hdn_OutTerminal.Value);
                                        }
                                        else
                                        {
                                            intOutReaderId = 0;
                                        }
                                        string strEntryDate = objCommon.DateConvertion(gstrDateFormat, TxtOnDuty.Text);
                                        if (txt_ShiftIn.Text != string.Empty)
                                        {
                                            txt_ShiftIn.Text = Convert.ToDateTime(txt_ShiftIn.Text).ToString("hh:mm:ss tt");
                                        }
                                        if (txt_ShiftOut.Text != string.Empty)
                                        {
                                            txt_ShiftOut.Text = Convert.ToDateTime(txt_ShiftOut.Text).ToString("hh:mm:ss tt");
                                        }
                                        if (dsShiftDetails.Tables[0].Rows[0]["Shift_StartTime"].ToString().Contains("PM") && dsShiftDetails.Tables[0].Rows[0]["Shift_EndTime"].ToString().Contains("AM"))
                                        {
                                            if ((strInDate == objCommon.DateConvertion(gstrDateFormat, dtmDate.ToString(gstrDateFormat))) && (strOutDate == objCommon.DateConvertion(gstrDateFormat, dtmDate.ToString(gstrDateFormat))))
                                            {
                                                gintInsertCount = gintInsertCount + 1;
                                                if (txt_ShiftIn.Text.Contains("PM") && txt_ShiftOut.Text.Contains("AM"))
                                                {
                                                    objManualEntry.InsertOnDutyEntry(EmployeeId, DateTime.Parse(strEntryDate), dtmDate.ToShortDateString(), txt_ShiftIn.Text, strInPunchType, dtmDate.AddDays(1).ToShortDateString(), txt_ShiftOut.Text, strOutPunchType, intInReaderId, intOutReaderId, txt_Reason.Text.Trim().Replace("'", "''"), intRouteId, strManualTimeEntryStatus, gintUserId, ViewState["YearSettings_Id"].ToString(), 1, Convert.ToString(intShiftId), dtmDate.ToShortDateString(), IntOndutyID);
                                                }
                                                else if (txt_ShiftIn.Text.Contains("AM") && txt_ShiftOut.Text.Contains("AM"))
                                                {
                                                    objManualEntry.InsertOnDutyEntry(EmployeeId, DateTime.Parse(strEntryDate), dtmDate.AddDays(1).ToShortDateString(), txt_ShiftIn.Text, strInPunchType, dtmDate.AddDays(1).ToShortDateString(), txt_ShiftOut.Text, strOutPunchType, intInReaderId, intOutReaderId, txt_Reason.Text.Trim().Replace("'", "''"), intRouteId, strManualTimeEntryStatus, gintUserId, ViewState["YearSettings_Id"].ToString(), 1, Convert.ToString(intShiftId), dtmDate.ToShortDateString(), IntOndutyID);
                                                }
                                                else
                                                {
                                                    objManualEntry.InsertOnDutyEntry(EmployeeId, DateTime.Parse(strEntryDate), dtmDate.ToShortDateString(), txt_ShiftIn.Text, strInPunchType, dtmDate.ToShortDateString(), txt_ShiftOut.Text, strOutPunchType, intInReaderId, intOutReaderId, txt_Reason.Text.Trim().Replace("'", "''"), intRouteId, strManualTimeEntryStatus, gintUserId, ViewState["YearSettings_Id"].ToString(), 1, Convert.ToString(intShiftId), dtmDate.ToShortDateString(), IntOndutyID);
                                                }
                                            }
                                            else if (strInDate == objCommon.DateConvertion(gstrDateFormat, dtmDate.ToString(gstrDateFormat)))
                                            {
                                                gintInsertCount = gintInsertCount + 1;
                                                if (txt_ShiftIn.Text.Contains("PM") && txt_ShiftOut.Text.Contains("AM"))
                                                {
                                                    objManualEntry.InsertOnDutyEntry(EmployeeId, DateTime.Parse(strEntryDate), dtmDate.ToShortDateString(), txt_ShiftIn.Text, strInPunchType,
                                                        dtmDate.AddDays(1).ToShortDateString(), txt_ShiftOut.Text, strOutPunchType, intInReaderId, intOutReaderId, txt_Reason.Text.Trim().Replace("'", "''"), intRouteId, strManualTimeEntryStatus, gintUserId, ViewState["YearSettings_Id"].ToString(), 1, Convert.ToString(intShiftId), dtmDate.ToShortDateString(), IntOndutyID);
                                                    //if (rbSingleDayNo.Checked == true)
                                                    //{
                                                    //    dtmDate = dtmDate.AddDays(1);
                                                    //}
                                                }
                                                else if (txt_ShiftIn.Text.Contains("AM") && txt_ShiftOut.Text.Contains("AM"))
                                                {
                                                    objManualEntry.InsertOnDutyEntry(EmployeeId, DateTime.Parse(strEntryDate), dtmDate.AddDays(1).ToShortDateString(), txt_ShiftIn.Text, strInPunchType, dtmDate.AddDays(1).ToShortDateString(), txt_ShiftOut.Text, strOutPunchType, intInReaderId, intOutReaderId, txt_Reason.Text.Trim().Replace("'", "''"), intRouteId, strManualTimeEntryStatus, gintUserId, ViewState["YearSettings_Id"].ToString(), 1, Convert.ToString(intShiftId), dtmDate.ToShortDateString(), IntOndutyID);
                                                    //if (rbSingleDayNo.Checked == true)
                                                    //{
                                                    //    dtmDate = dtmDate.AddDays(1);
                                                    //}
                                                }
                                                else
                                                {
                                                    objManualEntry.InsertOnDutyEntry(EmployeeId, DateTime.Parse(strEntryDate), dtmDate.ToShortDateString(), txt_ShiftIn.Text, strInPunchType, dtmDate.ToShortDateString(), txt_ShiftOut.Text, strOutPunchType, intInReaderId, intOutReaderId, txt_Reason.Text.Trim().Replace("'", "''"), intRouteId, strManualTimeEntryStatus, gintUserId, ViewState["YearSettings_Id"].ToString(), 1, Convert.ToString(intShiftId), dtmDate.ToShortDateString(), IntOndutyID);
                                                }
                                            }
                                            else
                                            {
                                                gintInsertCount = gintInsertCount + 1;
                                                if (txt_ShiftIn.Text.Contains("PM") && txt_ShiftOut.Text.Contains("AM"))
                                                {
                                                    objManualEntry.InsertOnDutyEntry(EmployeeId, DateTime.Parse(strEntryDate), dtmDate.ToShortDateString(),
                                                        txt_ShiftIn.Text,
                                                        strInPunchType, dtmDate.AddDays(1).ToShortDateString(),
                                                        txt_ShiftOut.Text, strOutPunchType, intInReaderId, intOutReaderId, txt_Reason.Text.Trim().Replace("'", "''"),
                                                        intRouteId, strManualTimeEntryStatus, gintUserId, ViewState["YearSettings_Id"].ToString(), 1, Convert.ToString(intShiftId), dtmDate.ToShortDateString(), IntOndutyID);
                                                    //if (rbSingleDayNo.Checked == true)
                                                    //{
                                                    //    dtmDate = dtmDate.AddDays(1);
                                                    //}
                                                }
                                                else if (txt_ShiftIn.Text.Contains("AM") && txt_ShiftOut.Text.Contains("AM"))
                                                {
                                                    objManualEntry.InsertOnDutyEntry(EmployeeId, DateTime.Parse(strEntryDate), dtmDate.AddDays(1).ToShortDateString(), txt_ShiftIn.Text, strInPunchType, dtmDate.AddDays(1).ToShortDateString(), txt_ShiftOut.Text, strOutPunchType, intInReaderId, intOutReaderId, txt_Reason.Text.Trim().Replace("'", "''"), intRouteId, strManualTimeEntryStatus, gintUserId, ViewState["YearSettings_Id"].ToString(), 1, Convert.ToString(intShiftId), dtmDate.ToShortDateString(), IntOndutyID);
                                                    //if (rbSingleDayNo.Checked == true)
                                                    //{
                                                    //    dtmDate = dtmDate.AddDays(1);
                                                    //}
                                                }
                                                else
                                                {
                                                    objManualEntry.InsertOnDutyEntry(EmployeeId, DateTime.Parse(strEntryDate), dtmDate.ToShortDateString(), txt_ShiftIn.Text, strInPunchType, dtmDate.ToShortDateString(), txt_ShiftOut.Text, strOutPunchType, intInReaderId, intOutReaderId, txt_Reason.Text.Trim().Replace("'", "''"), intRouteId, strManualTimeEntryStatus, gintUserId, ViewState["YearSettings_Id"].ToString(), 1, Convert.ToString(intShiftId), dtmDate.ToShortDateString(), IntOndutyID);
                                                }
                                            }
                                        }
                                        else
                                        {
                                            gintInsertCount = gintInsertCount + 1;
                                            //if (rbIncludingWeeklyOff.Checked == false)
                                            //{
                                            if (intShiftId != -1)
                                            {
                                                objManualEntry.InsertOnDutyEntry(EmployeeId, DateTime.Parse(strEntryDate), dtmDate.ToShortDateString(), txt_ShiftIn.Text,
                                                    strInPunchType, dtmDate.ToShortDateString(), 
                                                    txt_ShiftOut.Text, strOutPunchType, intInReaderId, intOutReaderId, txt_Reason.Text.Trim().Replace("'", "''"),
                                                    intRouteId, strManualTimeEntryStatus, gintUserId, Convert.ToString(ViewState["YearSettings_Id"]),
                                                    1, Convert.ToString(intShiftId), dtmDate.ToShortDateString(), IntOndutyID);
                                            }
                                            //}
                                            else
                                            {
                                                objManualEntry.InsertOnDutyEntry(EmployeeId, DateTime.Parse(strEntryDate), dtmDate.ToShortDateString(), txt_ShiftIn.Text, strInPunchType, dtmDate.ToShortDateString(), txt_ShiftOut.Text, strOutPunchType, intInReaderId, intOutReaderId, txt_Reason.Text.Trim().Replace("'", "''"), intRouteId, strManualTimeEntryStatus, gintUserId, Convert.ToString(ViewState["YearSettings_Id"]), 1, Convert.ToString(intShiftId), dtmDate.ToShortDateString(), IntOndutyID);
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    if (gstrEmployeeIds == string.Empty)
                                    {
                                        gstrEmployeeIds = EmployeeId + "(" + dtmDate.ToString(gstrDateFormat) + ")";
                                    }
                                    else
                                    {
                                        gstrEmployeeIds = gstrEmployeeIds + "," + EmployeeId + "(" + dtmDate.ToString(gstrDateFormat) + ")";
                                    }
                                }
                            }
                            else
                            {
                                IntWeekoffallow = 0;
                                if (IntIsHolidayEntry == 1)
                                {
                                    IntIsHolidayEntry = 0;
                                }
                                if (Convert.ToInt32(ViewState["ODInsertStatus"]) >= 1)
                                {
                                    string TESTPermission = "No OnDuty Entry added on WeeklyOff/Holiday " + dtmDate.ToString(gstrDateFormat);
                                    ScriptManager.RegisterStartupScript(this, GetType(), "Alert", "alert('" + TESTPermission + "'); location.replace('TA_UI_Transactions_OnDutyList.aspx');", true);
                                }
                                else
                                {
                                    string TESTPermission = "No OnDuty Entry added on WeeklyOff/Holiday " + dtmDate.ToString(gstrDateFormat);
                                    ScriptManager.RegisterStartupScript(this, GetType(), "Alert", "alert('" + TESTPermission + "');", true);
                                }
                            }
                        }
                    }
                    else
                    {
                        if (gintInsertCount >= 1)
                        {
                            string TESTLeave = "Leave entry is already availed For this Duration " + dtmDate.ToString(gstrDateFormat);
                            ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + TESTLeave + "'); location.replace('TA_UI_Transactions_OnDutyList.aspx');", true);
                        }
                        else
                        {
                            string TESTLeave = "Leave entry is already availed For this Duration " + dtmDate.ToString(gstrDateFormat);
                            ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + TESTLeave + "');", true);
                        }
                    }
                }
                else
                {
                    if (Convert.ToInt32(ViewState["ODInsertStatus"]) >= 1)
                    {
                        string TESTLeave = "Holiday is already availed For this Duration " + dtmDate.ToString(gstrDateFormat);
                        ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + TESTLeave + "'); location.replace('TA_UI_Transactions_OnDutyList.aspx');", true);
                    }
                    else
                    {
                        string TESTLeave = "Holiday is already availed For this Duration " + dtmDate.ToString(gstrDateFormat);
                        ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + TESTLeave + "');", true);
                    }
                }
            }
            if (Convert.ToInt32(ViewState["ODInsertStatus"]) == 0)
            {
                ViewState["ODInsertStatus"] = gintInsertCount;
            }
        }
    }

    private void ToConvertProperFormat(ref string strInDate, ref string strOutDate)
    {
        if (rbSingleDayYes.Checked == true)
        {
            strInDate = objCommon.DateConvertion(gstrDateFormat, txt_ShiftDate.Text);
            strOutDate = objCommon.DateConvertion(gstrDateFormat, txt_ShiftDate.Text);
        }

    }
    public int GetWeekDay(string WeekDayName)
    {
        int intWeekDay = 0;
        switch (WeekDayName)
        {
            case "Sunday":
                intWeekDay = 1;
                break;
            case "Monday":
                intWeekDay = 2;
                break;
            case "Tuesday":
                intWeekDay = 3;
                break;
            case "Wednesday":
                intWeekDay = 4;
                break;
            case "Thursday":
                intWeekDay = 5;
                break;
            case "Friday":
                intWeekDay = 6;
                break;
            case "Saturday":
                intWeekDay = 7;
                break;
        }
        return (intWeekDay);
    }
    public int CheckAdditionalWeekOff(DateTime dtmDate, string EmployeeId)
    {
        DateTime startOfMonth;
        string strStartOfMonth;
        int DaysToAdd, NthWeek = 0, TargetDayOfWeek = 0;
        string flag = "NE";
        try
        {
            DataTable dtAdditionalWeekOff = new DataTable();
            dtAdditionalWeekOff = objMonthClosure.GetAdditionalWeekOff(EmployeeId, dtmDate.ToShortDateString());
            if (dtAdditionalWeekOff.Rows.Count > 0)
            {
                foreach (DataRow drRow in dtAdditionalWeekOff.Rows)
                {
                    if (drRow["Addl_WeekOff_Day"] != DBNull.Value && drRow["Addl_WeekOff_Day"].ToString() != string.Empty)
                    {
                        TargetDayOfWeek = GetWeekDay(drRow["Addl_WeekOff_Day"].ToString());
                    }
                    if (drRow["Addl_WeekOff_Week"] != DBNull.Value && drRow["Addl_WeekOff_Week"].ToString() != string.Empty)
                    {
                        string strTargetDayOfWeek = drRow["Addl_WeekOff_Week"].ToString();
                        if (strTargetDayOfWeek == "First Week")
                        {
                            NthWeek = 1;
                        }
                        else if (strTargetDayOfWeek == "Second Week")
                        {
                            NthWeek = 2;
                        }
                        else if (strTargetDayOfWeek == "Third Week")
                        {
                            NthWeek = 3;
                        }
                        else if (strTargetDayOfWeek == "Fourth Week")
                        {
                            NthWeek = 4;
                        }
                        else if (strTargetDayOfWeek == "Fifth Week")
                        {
                            NthWeek = 5;
                        }
                    }
                    if (NthWeek != 0 && TargetDayOfWeek != 0)
                    {
                        strStartOfMonth = dtmDate.Month + "/01/" + dtmDate.Year;
                        startOfMonth = DateTime.Parse(strStartOfMonth);
                        string WeekDayName = startOfMonth.DayOfWeek.ToString();
                        int WeekDay = GetWeekDay(WeekDayName);
                        DaysToAdd = (7 - (WeekDay + (7 - TargetDayOfWeek)) % 7) % 7;
                        DateTime dtmResult = startOfMonth.AddDays(DaysToAdd + ((NthWeek - 1) * 7));
                        if (dtmResult == dtmDate)
                        {
                            flag = "E";
                        }
                    }
                }
            }
            if (flag == "E")
            {
                return (1);
            }
            else
            {
                return (0);
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }


    public Boolean Validation(string EmployeeId, string Type, int EmployeeAutoId)
    {
        daysCount = 0;
        DataSet ds_EntranceDetails = new DataSet();
        int intShiftId = 0, IntWeekoffallow = 0;
        string strInDate = TxtOnDuty.Text, strOutDate = TxtOnDuty.Text, strManualTimeEntryStatus = string.Empty;
        gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
        //ToConvertProperFormat(ref strInDate, ref strOutDate);
        string strDateOfJoining = string.Empty;
        DataSet dsEmployeeDOJ = new DataSet();
        dsEmployeeDOJ = objEmployee.GetEmployeeDateOfJoining(EmployeeId, "", "", "S");
        if (dsEmployeeDOJ.Tables[0].Rows.Count > 0)
        {
            if (dsEmployeeDOJ.Tables[0].Rows[0]["DateOfJoining"] != DBNull.Value)
            {
                strDateOfJoining = Convert.ToString(dsEmployeeDOJ.Tables[0].Rows[0]["DateOfJoining"]);
            }
        }
        for (DateTime dtmDate = Convert.ToDateTime(strInDate); dtmDate <= Convert.ToDateTime(strOutDate); dtmDate = dtmDate.AddDays(1))
        {
            string strFlag = "Y";
            if (strDateOfJoining != string.Empty)
            {
                DateTime dtmDateOfJoining = DateTime.Parse(strDateOfJoining);
                if (dtmDate < dtmDateOfJoining)
                {
                    strFlag = "N";
                    if (gstrDOJValidation == string.Empty)
                    {
                        gstrDOJValidation = EmployeeId + "(" + dtmDate.ToString(gstrDateFormat) + ")";
                    }
                    else
                    {
                        gstrDOJValidation = gstrDOJValidation + "," + EmployeeId + "(" + dtmDate.ToString(gstrDateFormat) + ")";
                    }
                }
            }
            DataSet dsShiftDetails = new DataSet();
            intShiftId = objShiftExchange.SelectShiftId(EmployeeId, dtmDate.Year.ToString(), dtmDate.Month.ToString(), dtmDate.Day.ToString());
            int count = 0;
            count = CheckAdditionalWeekOff(dtmDate, EmployeeId);
            if (count == 1)
            {
                intShiftId = -1;
            }
            if (intShiftId == 0)
            {
                strFlag = "N";
                if (gstrShiftValidation == string.Empty)
                {
                    gstrShiftValidation = EmployeeId + "(" + dtmDate.ToString(gstrDateFormat) + ")";
                }
                else
                {
                    gstrShiftValidation = gstrShiftValidation + "," + EmployeeId + "(" + dtmDate.ToString(gstrDateFormat) + ")";
                }
            }
            else if (intShiftId == -1)
            {
                ////if (rbIncludingWeeklyOff.Checked == true)
                ////{
                ////    DateTime dtClockDate = new DateTime();
                ////    dtClockDate = dtmDate;
                ////    do
                ////    {
                ////        if (count == 1)
                ////        {
                ////            intShiftId = -1;
                ////            count = 0;
                ////        }
                ////        else
                ////        {
                ////            intShiftId = objShiftExchange.SelectShiftId(EmployeeId, dtClockDate.Year.ToString(), dtClockDate.Month.ToString(), dtClockDate.Day.ToString());
                ////        }
                ////        dtClockDate = dtClockDate.AddDays(-1);
                ////    }
                ////    while (intShiftId == -1);
                ////    dsShiftDetails = objShift.SelectShiftById(intShiftId);
                ////}
                ////else
                ////{
                ////    IntWeekoffallow = 1;
                ////    continue;
                ////}
            }
            else
            {
                dsShiftDetails = objShift.SelectShiftById(intShiftId);
            }
            int intIsLeave = 0;
            //if (rbSingleDayNo.Checked == true && intShiftId != -1 && intShiftId != 0)
            //{
            //    dsShiftDetails = objShift.SelectShiftById(intShiftId);
            //    DataTable dtLeaveMultiple;
            //    dtLeaveMultiple = objManualEntry.CheckLeaveForOnDuty(dtmDate.ToShortDateString(), Convert.ToString(EmployeeId));
            //    #region Getting the Shift Start time and End Time For multiple Days entries
            //    if (strInDate == strOutDate)
            //    {
            //        if (dtLeaveMultiple.Rows.Count > 0)
            //        {
            //            if (dtLeaveMultiple.Rows[0][0].ToString() != "NoLeave" && dtLeaveMultiple.Rows[0][1].ToString() != "NoLeave")
            //            {
            //                if (dtLeaveMultiple.Rows[0]["Leave_SessionFrom"].ToString() == "First half" && dtLeaveMultiple.Rows[0]["Leave_SessionTo"].ToString() == "First half")
            //                {
            //                    if (ddl_SessionFrom.SelectedItem.Text == "First half" && ddl_SessionTo.SelectedItem.Text == "First half")
            //                    {
            //                        intIsLeave = 2;
            //                    }
            //                    else if (ddl_SessionFrom.SelectedItem.Text == "Second half" && ddl_SessionTo.SelectedItem.Text == "Second half")
            //                    {
            //                        txt_ShiftIn.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_SecondHalf_StartTime"].ToString();
            //                        txt_ShiftOut.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_EndTime"].ToString();
            //                    }
            //                    if (ddl_SessionFrom.SelectedItem.Text == "First half" && ddl_SessionTo.SelectedItem.Text == "Second half")
            //                    {
            //                        txt_ShiftIn.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_SecondHalf_StartTime"].ToString();
            //                        txt_ShiftOut.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_EndTime"].ToString();
            //                    }
            //                }
            //                else if (dtLeaveMultiple.Rows[0]["Leave_SessionFrom"].ToString() == "Second half" && dtLeaveMultiple.Rows[0]["Leave_SessionTo"].ToString() == "Second half")
            //                {
            //                    if (ddl_SessionFrom.SelectedItem.Text == "First half" && ddl_SessionTo.SelectedItem.Text == "First half")
            //                    {
            //                        txt_ShiftIn.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_StartTime"].ToString();
            //                        txt_ShiftOut.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_FirstHalf_EndTime"].ToString();
            //                    }
            //                    else if (ddl_SessionFrom.SelectedItem.Text == "Second half" && ddl_SessionTo.SelectedItem.Text == "Second half")
            //                    {
            //                        intIsLeave = 2;
            //                    }
            //                    if (ddl_SessionFrom.SelectedItem.Text == "First half" && ddl_SessionTo.SelectedItem.Text == "Second half")
            //                    {
            //                        txt_ShiftIn.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_StartTime"].ToString();
            //                        txt_ShiftOut.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_FirstHalf_EndTime"].ToString();
            //                    }
            //                }
            //                else
            //                {
            //                    intIsLeave = 2;
            //                }
            //            }
            //            else
            //            {
            //                if (ddl_SessionFrom.SelectedItem.Text == "First half" && ddl_SessionTo.SelectedItem.Text == "First half")
            //                {
            //                    txt_ShiftIn.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_StartTime"].ToString();
            //                    txt_ShiftOut.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_FirstHalf_EndTime"].ToString();
            //                }
            //                else if (ddl_SessionFrom.SelectedItem.Text == "Second half" && ddl_SessionTo.SelectedItem.Text == "Second half")
            //                {
            //                    txt_ShiftIn.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_SecondHalf_StartTime"].ToString();
            //                    txt_ShiftOut.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_EndTime"].ToString();
            //                }
            //                if (ddl_SessionFrom.SelectedItem.Text == "First half" && ddl_SessionTo.SelectedItem.Text == "Second half")
            //                {
            //                    txt_ShiftIn.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_StartTime"].ToString();
            //                    txt_ShiftOut.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_EndTime"].ToString();
            //                }
            //            }
            //        }
            //    }
            //    else
            //    {
            //        if (dtmDate < Convert.ToDateTime(strOutDate))
            //        {
            //            if (dtmDate == Convert.ToDateTime(strInDate))
            //            {
            //                if (dtLeaveMultiple.Rows.Count > 0)
            //                {
            //                    if (dtLeaveMultiple.Rows[0][0].ToString() != "NoLeave" && dtLeaveMultiple.Rows[0][1].ToString() != "NoLeave")
            //                    {
            //                        if (dtLeaveMultiple.Rows[0]["Leave_SessionFrom"].ToString() == "First half" && dtLeaveMultiple.Rows[0]["Leave_SessionTo"].ToString() == "First half")
            //                        {
            //                            if (ddl_SessionFrom.SelectedItem.Text == "First half" && ddl_SessionTo.SelectedItem.Text == "First half")
            //                            {
            //                                txt_ShiftIn.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_SecondHalf_StartTime"].ToString();
            //                                txt_ShiftOut.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_EndTime"].ToString();
            //                            }
            //                            else if (ddl_SessionFrom.SelectedItem.Text == "Second half" && ddl_SessionTo.SelectedItem.Text == "Second half")
            //                            {
            //                                txt_ShiftIn.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_SecondHalf_StartTime"].ToString();
            //                                txt_ShiftOut.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_EndTime"].ToString();
            //                            }
            //                            else if (ddl_SessionFrom.SelectedItem.Text == "First half" && ddl_SessionTo.SelectedItem.Text == "Second half")
            //                            {
            //                                txt_ShiftIn.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_SecondHalf_StartTime"].ToString();
            //                                txt_ShiftOut.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_EndTime"].ToString();
            //                            }
            //                            else if (ddl_SessionFrom.SelectedItem.Text == "Second half" && ddl_SessionTo.SelectedItem.Text == "First half")
            //                            {
            //                                txt_ShiftIn.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_SecondHalf_StartTime"].ToString();
            //                                txt_ShiftOut.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_EndTime"].ToString();
            //                            }
            //                        }
            //                        else if (dtLeaveMultiple.Rows[0]["Leave_SessionFrom"].ToString() == "Second half" && dtLeaveMultiple.Rows[0]["Leave_SessionTo"].ToString() == "Second half")
            //                        {
            //                            if (ddl_SessionFrom.SelectedItem.Text == "First half" && ddl_SessionTo.SelectedItem.Text == "First half")
            //                            {
            //                                txt_ShiftIn.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_StartTime"].ToString();
            //                                txt_ShiftOut.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_FirstHalf_EndTime"].ToString();
            //                            }
            //                            else if (ddl_SessionFrom.SelectedItem.Text == "Second half" && ddl_SessionTo.SelectedItem.Text == "Second half")
            //                            {
            //                                intIsLeave = 2;
            //                            }
            //                            else if (ddl_SessionFrom.SelectedItem.Text == "First half" && ddl_SessionTo.SelectedItem.Text == "Second half")
            //                            {
            //                                txt_ShiftIn.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_StartTime"].ToString();
            //                                txt_ShiftOut.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_FirstHalf_EndTime"].ToString();
            //                            }
            //                            else if (ddl_SessionFrom.SelectedItem.Text == "Second half" && ddl_SessionTo.SelectedItem.Text == "First half")
            //                            {
            //                                intIsLeave = 2;
            //                            }
            //                        }
            //                        else
            //                        {
            //                            intIsLeave = 2;
            //                        }
            //                    }
            //                    else
            //                    {
            //                        if (ddl_SessionFrom.SelectedItem.Text == "First half" && ddl_SessionTo.SelectedItem.Text == "First half")
            //                        {
            //                            txt_ShiftIn.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_StartTime"].ToString();
            //                            txt_ShiftOut.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_EndTime"].ToString();
            //                        }
            //                        else if (ddl_SessionFrom.SelectedItem.Text == "Second half" && ddl_SessionTo.SelectedItem.Text == "Second half")
            //                        {
            //                            txt_ShiftIn.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_SecondHalf_StartTime"].ToString();
            //                            txt_ShiftOut.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_EndTime"].ToString();
            //                        }
            //                        if (ddl_SessionFrom.SelectedItem.Text == "First half" && ddl_SessionTo.SelectedItem.Text == "Second half")
            //                        {
            //                            txt_ShiftIn.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_StartTime"].ToString();
            //                            txt_ShiftOut.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_EndTime"].ToString();
            //                        }
            //                        if (ddl_SessionFrom.SelectedItem.Text == "Second half" && ddl_SessionTo.SelectedItem.Text == "First half")
            //                        {
            //                            txt_ShiftIn.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_SecondHalf_StartTime"].ToString();
            //                            txt_ShiftOut.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_EndTime"].ToString();
            //                        }
            //                    }
            //                }
            //            }
            //            else
            //            {
            //                if (dtLeaveMultiple.Rows.Count > 0)
            //                {
            //                    if (dtLeaveMultiple.Rows[0][0].ToString() != "NoLeave" && dtLeaveMultiple.Rows[0][1].ToString() != "NoLeave")
            //                    {
            //                        if (dtLeaveMultiple.Rows[0]["Leave_SessionFrom"].ToString() == "First half" && dtLeaveMultiple.Rows[0]["Leave_SessionTo"].ToString() == "First half")
            //                        {
            //                            if (ddl_SessionFrom.SelectedItem.Text == "First half" && ddl_SessionTo.SelectedItem.Text == "First half")
            //                            {
            //                                txt_ShiftIn.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_SecondHalf_StartTime"].ToString();
            //                                txt_ShiftOut.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_EndTime"].ToString();
            //                            }
            //                            else if (ddl_SessionFrom.SelectedItem.Text == "Second half" && ddl_SessionTo.SelectedItem.Text == "Second half")
            //                            {
            //                                txt_ShiftIn.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_SecondHalf_StartTime"].ToString();
            //                                txt_ShiftOut.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_EndTime"].ToString();
            //                            }
            //                            else if (ddl_SessionFrom.SelectedItem.Text == "First half" && ddl_SessionTo.SelectedItem.Text == "Second half")
            //                            {
            //                                txt_ShiftIn.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_SecondHalf_StartTime"].ToString();
            //                                txt_ShiftOut.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_EndTime"].ToString();
            //                            }
            //                            else if (ddl_SessionFrom.SelectedItem.Text == "Second half" && ddl_SessionTo.SelectedItem.Text == "First half")
            //                            {
            //                                txt_ShiftIn.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_SecondHalf_StartTime"].ToString();
            //                                txt_ShiftOut.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_EndTime"].ToString();
            //                            }
            //                        }
            //                        else if (dtLeaveMultiple.Rows[0]["Leave_SessionFrom"].ToString() == "Second half" && dtLeaveMultiple.Rows[0]["Leave_SessionTo"].ToString() == "Second half")
            //                        {
            //                            if (ddl_SessionFrom.SelectedItem.Text == "First half" && ddl_SessionTo.SelectedItem.Text == "First half")
            //                            {
            //                                txt_ShiftIn.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_StartTime"].ToString();
            //                                txt_ShiftOut.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_FirstHalf_EndTime"].ToString();
            //                            }
            //                            else if (ddl_SessionFrom.SelectedItem.Text == "Second half" && ddl_SessionTo.SelectedItem.Text == "Second half")
            //                            {
            //                                intIsLeave = 2;
            //                            }
            //                            else if (ddl_SessionFrom.SelectedItem.Text == "First half" && ddl_SessionTo.SelectedItem.Text == "Second half")
            //                            {
            //                                txt_ShiftIn.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_StartTime"].ToString();
            //                                txt_ShiftOut.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_FirstHalf_EndTime"].ToString();
            //                            }
            //                            else if (ddl_SessionFrom.SelectedItem.Text == "Second half" && ddl_SessionTo.SelectedItem.Text == "First half")
            //                            {
            //                                intIsLeave = 2;
            //                            }
            //                        }
            //                        else
            //                        {
            //                            intIsLeave = 2;
            //                        }
            //                    }
            //                    else
            //                    {
            //                        txt_ShiftIn.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_StartTime"].ToString();
            //                        txt_ShiftOut.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_EndTime"].ToString();
            //                    }
            //                }
            //            }
            //        }
            //        else
            //        {
            //            if (dtLeaveMultiple.Rows.Count > 0)
            //            {
            //                if (dtLeaveMultiple.Rows[0][0].ToString() != "NoLeave" && dtLeaveMultiple.Rows[0][1].ToString() != "NoLeave")
            //                {
            //                    if (dtLeaveMultiple.Rows[0]["Leave_SessionFrom"].ToString() == "First half" && dtLeaveMultiple.Rows[0]["Leave_SessionTo"].ToString() == "First half")
            //                    {
            //                        if (ddl_SessionFrom.SelectedItem.Text == "First half" && ddl_SessionTo.SelectedItem.Text == "First half")
            //                        {
            //                            intIsLeave = 2;
            //                        }
            //                        else if (ddl_SessionFrom.SelectedItem.Text == "Second half" && ddl_SessionTo.SelectedItem.Text == "Second half")
            //                        {
            //                            txt_ShiftIn.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_SecondHalf_StartTime"].ToString();
            //                            txt_ShiftOut.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_EndTime"].ToString();
            //                        }
            //                        if (ddl_SessionFrom.SelectedItem.Text == "First half" && ddl_SessionTo.SelectedItem.Text == "Second half")
            //                        {
            //                            txt_ShiftIn.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_SecondHalf_StartTime"].ToString();
            //                            txt_ShiftOut.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_EndTime"].ToString();
            //                        }
            //                    }
            //                    else if (dtLeaveMultiple.Rows[0]["Leave_SessionFrom"].ToString() == "Second half" && dtLeaveMultiple.Rows[0]["Leave_SessionTo"].ToString() == "Second half")
            //                    {
            //                        if (ddl_SessionFrom.SelectedItem.Text == "First half" && ddl_SessionTo.SelectedItem.Text == "First half")
            //                        {
            //                            txt_ShiftIn.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_StartTime"].ToString();
            //                            txt_ShiftOut.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_FirstHalf_EndTime"].ToString();
            //                        }
            //                        else if (ddl_SessionFrom.SelectedItem.Text == "Second half" && ddl_SessionTo.SelectedItem.Text == "Second half")
            //                        {
            //                            intIsLeave = 2;
            //                        }
            //                        if (ddl_SessionFrom.SelectedItem.Text == "First half" && ddl_SessionTo.SelectedItem.Text == "Second half")
            //                        {
            //                            txt_ShiftIn.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_StartTime"].ToString();
            //                            txt_ShiftOut.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_EndTime"].ToString();
            //                        }
            //                        // Below line is added by gopi for Mantis Bug.No.31981
            //                        if (ddl_SessionFrom.SelectedItem.Text == "Second half" && ddl_SessionTo.SelectedItem.Text == "First half")
            //                        {
            //                            txt_ShiftIn.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_StartTime"].ToString();
            //                            txt_ShiftOut.Text = dsShiftDetails.Tables[0].Rows[0]["Shift_FirstHalf_EndTime"].ToString();
            //                        }
            //                    }
            //                    else
            //                    {
            //                        intIsLeave = 2;
            //                    }
            //                }
            //                else
            //                {
            //                    if (ddl_SessionFrom.SelectedItem.Text == "First half")
            //                    {
            //                        txt_ShiftIn.Text = (dsShiftDetails.Tables[0].Rows[0]["Shift_StartTime"].ToString());
            //                    }
            //                    else if (ddl_SessionFrom.SelectedItem.Text == "Second half")
            //                    {
            //                        txt_ShiftIn.Text = (dsShiftDetails.Tables[0].Rows[0]["Shift_SecondHalf_StartTime"].ToString());
            //                    }
            //                    if (ddl_SessionTo.SelectedItem.Text == "First half")
            //                    {
            //                        txt_ShiftOut.Text = (dsShiftDetails.Tables[0].Rows[0]["Shift_FirstHalf_EndTime"].ToString());
            //                    }
            //                    else if (ddl_SessionTo.SelectedItem.Text == "Second half")
            //                    {
            //                        txt_ShiftOut.Text = (dsShiftDetails.Tables[0].Rows[0]["Shift_EndTime"].ToString());
            //                    }
            //                }
            //            }
            //        }
            //    }
            //    #endregion
            //}
            //else
            //{
                if (!dsShiftDetails.Tables[0].Rows[0]["Shift_StartTime"].ToString().Contains("PM"))
                {
                    if ((txt_ShiftDate.Text != "") && (txt_ShiftIn.Text != "") && (txt_ShiftOut.Text != ""))
                    {
                        strIn = strInDate + " " + txt_ShiftIn.Text;
                        strOut = strInDate + " " + txt_ShiftOut.Text;
                        dtmIn = DateTime.Parse(strIn);
                        dtmOut = DateTime.Parse(strOut);
                        TimeSpan tsDiff = dtmOut.Subtract(dtmIn);
                        double dTotalHrs = tsDiff.TotalHours;
                        if (dTotalHrs > 24)
                        {
                        }
                        else if (dTotalHrs < 0)
                        {
                            ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("Alert_StartTimeEndTime", ci) + "');", true);
                            string scrt = "<script>ManualTimeEntry()</script>";
                            this.Page.RegisterStartupScript("a", scrt);
                            TxtOnDuty.Focus();
                            return false;
                        }
                    }
                }
                else
                {
                    if ((txt_ShiftDate.Text != "") && (txt_ShiftIn.Text != "") && (txt_ShiftOut.Text != ""))
                    {
                        if (Convert.ToString(txt_ShiftIn.Text).Contains("PM") && Convert.ToString(txt_ShiftOut.Text).Contains("PM") || Convert.ToString(txt_ShiftIn.Text).Contains("AM") && Convert.ToString(txt_ShiftOut.Text).Contains("AM"))
                        {
                            strIn = strInDate + " " + txt_ShiftIn.Text;
                            strOut = strInDate + " " + txt_ShiftOut.Text;
                            dtmIn = DateTime.Parse(strIn);
                            dtmOut = DateTime.Parse(strOut);
                            TimeSpan tsDiff = dtmOut.Subtract(dtmIn);
                            double dTotalHrs = tsDiff.TotalHours;
                            if (dTotalHrs < 0)
                            {
                                ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("Alert_StartTimeEndTime", ci) + "');", true);
                                string scrt = "<script>ManualTimeEntry()</script>";
                                this.Page.RegisterStartupScript("a", scrt);
                                TxtOnDuty.Focus();
                                return false;
                            }
                        }
                    }
                }
            //}
            int intIsPermission = 0;
            DateTime dtCurrentDate = dtmDate;
            if (intShiftId != 0 && intShiftId != -1)
            {
                if (dsShiftDetails.Tables[0].Rows[0]["Shift_StartTime"].ToString().Contains("PM") && dsShiftDetails.Tables[0].Rows[0]["Shift_EndTime"].ToString().Contains("AM"))
                {
                    if (strInDate == objCommon.DateConvertion(gstrDateFormat, dtmDate.ToString(gstrDateFormat)))
                    {
                        if (txt_ShiftIn.Text.Contains("PM") && txt_ShiftOut.Text.Contains("AM"))
                        {
                            intIsPermission = objManualEntry.CheckPermissionForOnDuty(EmployeeId, dtmDate.ToShortDateString(), txt_ShiftIn.Text, dtmDate.AddDays(1).ToShortDateString(), txt_ShiftOut.Text);
                        }
                        else if (txt_ShiftIn.Text.Contains("AM") && txt_ShiftOut.Text.Contains("AM"))
                        {
                            intIsPermission = objManualEntry.CheckPermissionForOnDuty(EmployeeId, dtmDate.AddDays(1).ToShortDateString(), txt_ShiftIn.Text, dtmDate.AddDays(1).ToShortDateString(), txt_ShiftOut.Text);
                        }
                        else
                        {
                            intIsPermission = objManualEntry.CheckPermissionForOnDuty(EmployeeId, dtmDate.ToShortDateString(), txt_ShiftIn.Text, dtmDate.ToShortDateString(), txt_ShiftOut.Text);
                        }
                    }
                    else if (strOutDate == objCommon.DateConvertion(gstrDateFormat, dtmDate.ToString(gstrDateFormat)))
                    {
                        if (txt_ShiftIn.Text.Contains("PM") && txt_ShiftOut.Text.Contains("AM"))
                        {
                            intIsPermission = objManualEntry.CheckPermissionForOnDuty(EmployeeId, dtmDate.ToShortDateString(), dsShiftDetails.Tables[0].Rows[0]["Shift_StartTime"].ToString(), dtmDate.AddDays(1).ToShortDateString(), txt_ShiftOut.Text);
                        }
                        else if (txt_ShiftIn.Text.Contains("AM") && txt_ShiftOut.Text.Contains("AM"))
                        {
                            intIsPermission = objManualEntry.CheckPermissionForOnDuty(EmployeeId, dtmDate.AddDays(1).ToShortDateString(), dsShiftDetails.Tables[0].Rows[0]["Shift_StartTime"].ToString(), dtmDate.AddDays(1).ToShortDateString(), txt_ShiftOut.Text);
                        }
                        else
                        {
                            intIsPermission = objManualEntry.CheckPermissionForOnDuty(EmployeeId, dtmDate.ToShortDateString(), dsShiftDetails.Tables[0].Rows[0]["Shift_StartTime"].ToString(), dtmDate.ToShortDateString(), txt_ShiftOut.Text);
                        }
                    }
                    else
                    {
                        if (txt_ShiftIn.Text.Contains("PM") && txt_ShiftOut.Text.Contains("AM"))
                        {
                            intIsPermission = objManualEntry.CheckPermissionForOnDuty(EmployeeId, dtmDate.ToShortDateString(), dsShiftDetails.Tables[0].Rows[0]["Shift_StartTime"].ToString(), dtmDate.AddDays(1).ToShortDateString(), dsShiftDetails.Tables[0].Rows[0]["Shift_EndTime"].ToString());
                        }
                        else if (txt_ShiftIn.Text.Contains("AM") && txt_ShiftOut.Text.Contains("AM"))
                        {
                            intIsPermission = objManualEntry.CheckPermissionForOnDuty(EmployeeId, dtmDate.AddDays(1).ToShortDateString(), dsShiftDetails.Tables[0].Rows[0]["Shift_StartTime"].ToString(), dtmDate.AddDays(1).ToShortDateString(), dsShiftDetails.Tables[0].Rows[0]["Shift_EndTime"].ToString());
                        }
                        else
                        {
                            intIsPermission = objManualEntry.CheckPermissionForOnDuty(EmployeeId, dtmDate.ToShortDateString(), dsShiftDetails.Tables[0].Rows[0]["Shift_StartTime"].ToString(), dtmDate.ToShortDateString(), dsShiftDetails.Tables[0].Rows[0]["Shift_EndTime"].ToString());
                        }
                    }
                }
                else
                {
                    if (strInDate == objCommon.DateConvertion(gstrDateFormat, dtmDate.ToString(gstrDateFormat)))
                    {
                        intIsPermission = objManualEntry.CheckPermissionForOnDuty(EmployeeId, dtmDate.ToShortDateString(), txt_ShiftIn.Text, dtmDate.ToShortDateString(), txt_ShiftOut.Text);
                    }
                    else if (strOutDate == objCommon.DateConvertion(gstrDateFormat, dtmDate.ToString(gstrDateFormat)))
                    {
                        intIsPermission = objManualEntry.CheckPermissionForOnDuty(EmployeeId, dtmDate.ToShortDateString(), dsShiftDetails.Tables[0].Rows[0]["Shift_StartTime"].ToString(), dtmDate.ToShortDateString(), txt_ShiftOut.Text);
                    }
                    else
                    {
                        intIsPermission = objManualEntry.CheckPermissionForOnDuty(EmployeeId, dtmDate.ToShortDateString(), dsShiftDetails.Tables[0].Rows[0]["Shift_StartTime"].ToString(), dtmDate.ToShortDateString(), dsShiftDetails.Tables[0].Rows[0]["Shift_EndTime"].ToString());
                    }
                }
            }
            int IntIsHolidayEntry = 0;
            DataTable dtHoliday;
            dtHoliday = objHolidayEventData.CheckDateForHoliday(dtmDate.ToShortDateString(), EmployeeId);
            if (dtHoliday.Rows.Count > 0)
            {
                //if (rbExcludingWeeklyOff.Checked == true)
                //{
                //    IntIsHolidayEntry = 1;
                //}
            }
            if (rbSingleDayYes.Checked == true && intShiftId != -1 && intShiftId != 0)
            {
                DataTable dtLeave;
                dtLeave = objManualEntry.CheckLeaveForOnDuty(dtmDate.ToShortDateString(), Convert.ToString(EmployeeId));
                if (dtLeave.Rows.Count > 0)
                {
                    if (dtLeave.Rows[0]["Leave_SessionFrom"].ToString() == "First half" && dtLeave.Rows[0]["Leave_SessionTo"].ToString() == "First half")
                    {
                        if (dsShiftDetails.Tables[0].Rows[0]["Shift_StartTime"].ToString().Contains("PM") && dsShiftDetails.Tables[0].Rows[0]["Shift_EndTime"].ToString().Contains("AM"))
                        {
                            if (DateTime.Parse(txt_ShiftIn.Text.ToString()) >= DateTime.Parse(dsShiftDetails.Tables[0].Rows[0]["Shift_StartTime"].ToString()))
                            {
                                intIsLeave = 1;
                            }
                        }
                        else if ((DateTime.Parse(txt_ShiftIn.Text.ToString()) >= DateTime.Parse(dsShiftDetails.Tables[0].Rows[0]["Shift_StartTime"].ToString()))
                             && (DateTime.Parse(txt_ShiftIn.Text.ToString()) <= DateTime.Parse(dsShiftDetails.Tables[0].Rows[0]["Shift_FirstHalf_EndTime"].ToString())))
                        {
                            intIsLeave = 1;
                        }
                    }
                    else if (dtLeave.Rows[0]["Leave_SessionFrom"].ToString() == "Second half" && dtLeave.Rows[0]["Leave_SessionTo"].ToString() == "Second half")
                    {
                        if (dsShiftDetails.Tables[0].Rows[0]["Shift_StartTime"].ToString().Contains("PM") && dsShiftDetails.Tables[0].Rows[0]["Shift_EndTime"].ToString().Contains("AM"))
                        {
                            if (DateTime.Parse(txt_ShiftIn.Text.ToString()) <= DateTime.Parse(dsShiftDetails.Tables[0].Rows[0]["Shift_EndTime"].ToString()))
                            {
                                intIsLeave = 1;
                            }
                        }
                        else if ((DateTime.Parse(txt_ShiftOut.Text.ToString()) >= DateTime.Parse(dsShiftDetails.Tables[0].Rows[0]["Shift_SecondHalf_StartTime"].ToString()))
                        && (DateTime.Parse(txt_ShiftIn.Text.ToString()) <= DateTime.Parse(dsShiftDetails.Tables[0].Rows[0]["Shift_EndTime"].ToString())))
                        {
                            intIsLeave = 1;
                        }
                    }
                    else if (dtLeave.Rows[0]["Leave_SessionFrom"].ToString() == "First half" && dtLeave.Rows[0]["Leave_SessionTo"].ToString() == "Second half")
                    {
                        intIsLeave = 2;
                    }
                }
            }
            if (IntWeekoffallow == 1)
            {
                intShiftId = -1;
            }
            if (intShiftId != 0)
            {
                if (IntIsHolidayEntry == 0)
                {
                    if (intIsLeave < 2)
                    {
                        if (intIsPermission != 0)
                        {
                            if (gintInsertCount >= 1)
                            {
                                string TESTPermission = "Permission entry is already availed For this Duration " + dtmDate.ToString(gstrDateFormat);
                                ScriptManager.RegisterStartupScript(this, GetType(), "Alert", "alert('" + TESTPermission + "'); location.replace('TA_UI_Transactions_OnDutyList.aspx');", true);
                                return false;
                            }
                            else
                            {
                                string TESTPermission = "Permission entry is already availed For this Duration " + dtmDate.ToString(gstrDateFormat);
                                ScriptManager.RegisterStartupScript(this, GetType(), "Alert", "alert('" + TESTPermission + "');", true);
                                return false;
                            }
                        }
                        else
                        {
                            if (intShiftId != -1)
                            {
                                if (intShiftId != 0)
                                {
                                    if ((strInDate == objCommon.DateConvertion(gstrDateFormat, dtmDate.ToString(gstrDateFormat))) && (strOutDate == objCommon.DateConvertion(gstrDateFormat, dtmDate.ToString(gstrDateFormat))))
                                    {
                                        if (txt_ShiftIn.Text.Contains("PM") && txt_ShiftOut.Text.Contains("AM"))
                                        {
                                            count = objManualEntry.CheckManualODEntry(EmployeeId, dtmDate.ToShortDateString(), txt_ShiftIn.Text, dtmDate.AddDays(1).ToShortDateString(), txt_ShiftOut.Text);
                                        }
                                        else if (txt_ShiftIn.Text.Contains("AM") && txt_ShiftOut.Text.Contains("AM"))
                                        {
                                            if (Convert.ToDateTime(dsShiftDetails.Tables[0].Rows[0]["Shift_StartTime"]).ToString("hh:mm:ss tt").Contains("PM") && Convert.ToDateTime(dsShiftDetails.Tables[0].Rows[0]["Shift_EndTime"]).ToString("hh:mm:ss tt").Contains("AM"))
                                            {
                                                count = objManualEntry.CheckManualODEntry(EmployeeId, dtmDate.AddDays(1).ToShortDateString(), txt_ShiftIn.Text, dtmDate.AddDays(1).ToShortDateString(), txt_ShiftOut.Text);
                                            }
                                            else
                                            {
                                                count = objManualEntry.CheckManualODEntry(EmployeeId, dtmDate.ToShortDateString(), txt_ShiftIn.Text, dtmDate.ToShortDateString(), txt_ShiftOut.Text);
                                            }
                                        }
                                        else
                                        {
                                            count = objManualEntry.CheckManualODEntry(EmployeeId, dtmDate.ToShortDateString(), txt_ShiftIn.Text, dtmDate.ToShortDateString(), txt_ShiftOut.Text);
                                        }
                                    }
                                    else if (strInDate == objCommon.DateConvertion(gstrDateFormat, dtmDate.ToString(gstrDateFormat)))
                                    {
                                        if (txt_ShiftIn.Text.Contains("PM") && txt_ShiftOut.Text.Contains("AM"))
                                        {
                                            count = objManualEntry.CheckManualODEntry(EmployeeId, dtmDate.ToShortDateString(), txt_ShiftIn.Text, dtmDate.AddDays(1).ToShortDateString(), (strOutDate == objCommon.DateConvertion(gstrDateFormat, dtmDate.AddDays(1).ToString(gstrDateFormat))) ? txt_ShiftOut.Text : Convert.ToString(dsShiftDetails.Tables[0].Rows[0]["Shift_EndTime"]));
                                        }
                                        else if (txt_ShiftIn.Text.Contains("AM") && txt_ShiftOut.Text.Contains("AM"))
                                        {
                                            if (Convert.ToDateTime(dsShiftDetails.Tables[0].Rows[0]["Shift_StartTime"]).ToString("hh:mm:ss tt").Contains("PM") && Convert.ToDateTime(dsShiftDetails.Tables[0].Rows[0]["Shift_EndTime"]).ToString("hh:mm:ss tt").Contains("AM"))
                                            {
                                                count = objManualEntry.CheckManualODEntry(EmployeeId, dtmDate.AddDays(1).ToShortDateString(), txt_ShiftIn.Text, dtmDate.AddDays(1).ToShortDateString(), (strOutDate == objCommon.DateConvertion(gstrDateFormat, dtmDate.AddDays(1).ToString(gstrDateFormat))) ? txt_ShiftOut.Text : Convert.ToString(dsShiftDetails.Tables[0].Rows[0]["Shift_EndTime"]));
                                            }
                                            else
                                            {
                                                count = objManualEntry.CheckManualODEntry(EmployeeId, dtmDate.AddDays(1).ToShortDateString(), txt_ShiftIn.Text, dtmDate.AddDays(1).ToShortDateString(), txt_ShiftOut.Text);
                                            }
                                        }
                                        else
                                        {
                                            count = objManualEntry.CheckManualODEntry(EmployeeId, dtmDate.ToShortDateString(), txt_ShiftIn.Text, dtmDate.ToShortDateString(), (strOutDate == objCommon.DateConvertion(gstrDateFormat, dtmDate.AddDays(1).ToString(gstrDateFormat))) ? txt_ShiftOut.Text : Convert.ToString(dsShiftDetails.Tables[0].Rows[0]["Shift_EndTime"]));
                                        }
                                    }
                                    else if (strOutDate == objCommon.DateConvertion(gstrDateFormat, dtmDate.ToString(gstrDateFormat)))
                                    {
                                        if (txt_ShiftIn.Text.Contains("PM") && txt_ShiftOut.Text.Contains("AM"))
                                        {
                                            count = objManualEntry.CheckManualODEntry(EmployeeId, dtmDate.ToShortDateString(), Convert.ToDateTime(dsShiftDetails.Tables[0].Rows[0]["Shift_StartTime"]).ToString("hh:mm:ss tt"), dtmDate.AddDays(1).ToShortDateString(), txt_ShiftOut.Text);
                                        }
                                        else if (txt_ShiftIn.Text.Contains("AM") && txt_ShiftOut.Text.Contains("AM"))
                                        {
                                            if (Convert.ToDateTime(dsShiftDetails.Tables[0].Rows[0]["Shift_StartTime"]).ToString("hh:mm:ss tt").Contains("PM") && Convert.ToDateTime(dsShiftDetails.Tables[0].Rows[0]["Shift_EndTime"]).ToString("hh:mm:ss tt").Contains("AM"))
                                            {
                                                count = objManualEntry.CheckManualODEntry(EmployeeId, dtmDate.AddDays(1).ToShortDateString(), txt_ShiftIn.Text, dtmDate.AddDays(1).ToShortDateString(), txt_ShiftOut.Text);
                                            }
                                            else
                                            {
                                                count = objManualEntry.CheckManualODEntry(EmployeeId, dtmDate.ToShortDateString(), txt_ShiftIn.Text, dtmDate.ToShortDateString(), txt_ShiftOut.Text);
                                            }
                                        }
                                        else
                                        {
                                            count = objManualEntry.CheckManualODEntry(EmployeeId, dtmDate.ToShortDateString(), txt_ShiftIn.Text, dtmDate.ToShortDateString(), txt_ShiftOut.Text);
                                        }
                                    }
                                    else
                                    {
                                        if (txt_ShiftIn.Text.Contains("PM") && txt_ShiftOut.Text.Contains("AM"))
                                        {
                                            count = objManualEntry.CheckManualODEntry(EmployeeId, dtmDate.ToShortDateString(), Convert.ToDateTime(dsShiftDetails.Tables[0].Rows[0]["Shift_StartTime"]).ToString("hh:mm:ss tt"), dtmDate.AddDays(1).ToShortDateString(), (strOutDate == objCommon.DateConvertion(gstrDateFormat, dtmDate.AddDays(1).ToString(gstrDateFormat))) ? txt_ShiftOut.Text : Convert.ToString(dsShiftDetails.Tables[0].Rows[0]["Shift_EndTime"]));
                                        }
                                        else if (txt_ShiftIn.Text.Contains("AM") && txt_ShiftOut.Text.Contains("AM"))
                                        {
                                            if (Convert.ToDateTime(dsShiftDetails.Tables[0].Rows[0]["Shift_StartTime"]).ToString("hh:mm:ss tt").Contains("PM") && Convert.ToDateTime(dsShiftDetails.Tables[0].Rows[0]["Shift_EndTime"]).ToString("hh:mm:ss tt").Contains("AM"))
                                            {
                                                count = objManualEntry.CheckManualODEntry(EmployeeId, dtmDate.AddDays(1).ToShortDateString(), txt_ShiftIn.Text, dtmDate.AddDays(1).ToShortDateString(), txt_ShiftOut.Text);
                                            }
                                            else
                                            {
                                                count = objManualEntry.CheckManualODEntry(EmployeeId, dtmDate.ToShortDateString(), txt_ShiftIn.Text, dtmDate.ToShortDateString(), txt_ShiftOut.Text);
                                            }
                                        }
                                        else
                                        {
                                            count = objManualEntry.CheckManualODEntry(EmployeeId, dtmDate.ToShortDateString(), txt_ShiftIn.Text, dtmDate.ToShortDateString(), txt_ShiftOut.Text);
                                        }
                                    }
                                }
                                if (count != 0)
                                {
                                    if (gstrEmployeeIds == string.Empty)
                                    {
                                        gstrEmployeeIds = EmployeeId + "(" + dtmDate.ToString(gstrDateFormat) + ")";
                                    }
                                    else
                                    {
                                        gstrEmployeeIds = gstrEmployeeIds + "," + EmployeeId + "(" + dtmDate.ToString(gstrDateFormat) + ")";
                                    }
                                }
                            }
                            else
                            {
                                IntWeekoffallow = 0;
                                if (IntIsHolidayEntry == 1)
                                {
                                    IntIsHolidayEntry = 0;
                                }
                                if (gintInsertCount >= 1)
                                {
                                    //chkHolidayOnduty = true;
                                }
                                else
                                {
                                    //chkHolidayOnduty = true;
                                }
                            }
                        }
                    }
                    else
                    {
                        if (gintInsertCount >= 1)
                        {
                            string TESTLeave = "Leave entry is already availed For this Duration " + dtmDate.ToString(gstrDateFormat);
                            ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + TESTLeave + "'); location.replace('TA_UI_Transactions_OnDutyList.aspx');", true);
                            return false;
                        }
                        else
                        {
                            string TESTLeave = "Leave entry is already availed For this Duration " + dtmDate.ToString(gstrDateFormat);
                            ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + TESTLeave + "');", true);
                            return false;
                        }
                    }
                }
                else
                {
                    string TESTLeave = "Holiday is already availed For this Duration " + dtmDate.ToString(gstrDateFormat);
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + TESTLeave + "');", true);
                    return false;
                }
            }
            daysCount = daysCount + 1;
        }
        //Check all 
        string strMessage = string.Empty;
        if (gstrDOJValidation != string.Empty)
        {
            strMessage = rm.GetString("Msg_MannualODDateOFJoining");
        }
        else if (gstrShiftValidation != string.Empty)
        {
            strMessage = rm.GetString("Manual_ShiftNotAllocated");
        }
        else if (gstrEmployeeIds != string.Empty)
        {
            strMessage = rm.GetString("Manual_AlreadyExists") + " " + gstrEmployeeIds;
        }
        else if (onDuty != string.Empty)
        {
            strMessage = rm.GetString("AlertSelectedintimeandouttime");
        }
        if (strMessage != "" || strMessage != string.Empty)
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + strMessage + "');", true);
            return false;
        }
        return true;
    }


    private void DisplayMessage(string Message)
    {
        string strScript = "<script language='javascript' type='text/javascript'>";
        strScript += "alert('" + Message + "');";
        strScript += " </script>";
        ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", strScript, false);
    }







}


