using System;
using System.Data;
using System.Globalization;
using System.Resources;
using System.Threading;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Net.Mail;
using System.IO;

public partial class Transactions_TA_UI_Transactions_OnDutyAdd : Base.BasePage
{
    #region Eastman
    string strScript = "";
    FileStream aFile = null;
    int intShiftId = 0, gintAlreadyInsertCount = 0;
    string strIsINPunchPresent = "N", strRowValue = "";
    #endregion
    #region Variable Declaration
    ResourceManager rm;
    Cls_CheckUser objCheckUser = new Cls_CheckUser();
    DataSet ds_Checkuser = new DataSet();
    CultureInfo ci;
    ManualEntryEventData objManualEntry = new ManualEntryEventData();
    SMSNotification objsms = new SMSNotification();
    LeaveApplicationEventData objLeaveApplicationEventData = new LeaveApplicationEventData();
    EntranceEventData objEntrance = new EntranceEventData();
    ShiftAllocationEvendata objShiftAllocation = new ShiftAllocationEvendata();
    EmployeeEventData objEmployee = new EmployeeEventData();
    cls_Master_Transportation objRoute = new cls_Master_Transportation();
    ShiftExchangeEventData objShiftExchange = new ShiftExchangeEventData();
    cls_Common objCommon = new cls_Common();
    ShiftEvenData objShift = new ShiftEvenData();
    DiscrepancyEventData objDis = new DiscrepancyEventData();
    LeaveApplicationEventData objLeave = new LeaveApplicationEventData();
    PunchTypesEventdata objPunchTypes = new PunchTypesEventdata();
    HolidayEventData objHolidayEventData = new HolidayEventData();
    MonthClosureEventData objMonthClosure = new MonthClosureEventData();
    DataSet ds = new DataSet();
    DateTime dttShiftIn = new DateTime();
    DateTime dttShiftOut = new DateTime();
    bool blnCheckOndutyHoliday = false, blnCheckSMS = true;
    string strEmpFirstName, strEmpLastName, strEmployeeCodeId, strlevelName, OndutyType;
    int LevelID;
    int daysCount;
    string strEmployeeEmailId = string.Empty, strIncludeWeekOff;
    string TimeFormat = string.Empty;
    string TimeFormatMail = string.Empty;
    int count;
    int gintUserId;
    string gstrDateFormat, gstrEmployeeIds = string.Empty, gstrUserGroupName = string.Empty;
    string gstrDOJValidation = string.Empty, gstrPermissionValidation = string.Empty, gstrShiftValidation = string.Empty;
    string strEmployeeIds = string.Empty, strEmailIdSanctioningAuthority = string.Empty, strEmailIdReportingTo = string.Empty;
    string strEmployeeName = string.Empty;
    int gintInsertCount = 0;
    string onDuty = string.Empty;
    int manualEntryExists = 0;
    bool blnCheckEmail = true;
    int approvalSettingsPageExists = 0, IntOndutyID = 0;
    DateTime dtmIn = new DateTime();
    DateTime dtmOut = new DateTime();
    string strIn = string.Empty, strOut = string.Empty;
    bool chkHolidayOnduty = false;
    DataTable dtOndutyRecords = new DataTable();
    string strManualTimeEntryStatus = "Pending";
    int isNightShift = 0;
    #endregion
    #region Page Load Events
    /// <summary>
    /// On page load
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected override void Page_Load(object sender, EventArgs e)
    {
        base.Page_Load(sender, e);
        string source_Language;
        string strSetAlert = "";
        source_Language = Convert.ToString(Session["Session_ActiveLanguage"]);
        rm = new ResourceManager(source_Language, System.Reflection.Assembly.Load("App_GlobalResources"));
        ci = Thread.CurrentThread.CurrentCulture;
        if (!Page.IsPostBack)
        {
            objCommon.menu("OnDuty", "173");
            UserRights();
            LoadStrings(ci);
            strSetAlert = strSetAlert + "<script language='javascript'>";
            strSetAlert = strSetAlert + "MaxLengthh('" + rm.GetString("Alert_MaximumLengthis", ci) + "','" + rm.GetString("Select", ci) + "');";
            strSetAlert = strSetAlert + "SetAlertCheckDate('" + rm.GetString("Alert_Validmonthdatefourdigit", ci) + "','" + rm.GetString("Alert_Validdatemonthfourdigit", ci) + "','" + rm.GetString("Alert_Invalidyearentry", ci) + "','" + rm.GetString("Alert_Invalidmonthentry", ci) + "','" + rm.GetString("Alert_Invaliddateentry", ci) + "','" + rm.GetString("Alert_IncorrectdateformatDDMONYYYY", ci) + "','" + rm.GetString("Alert_Entertime", ci) + "','" + rm.GetString("Alert_Invalidvalueforhours", ci) + "','" + rm.GetString("Alert_Invalidvalueforminites", ci) + "','" + rm.GetString("Alert_Invalidtimeformat1", ci) + "','" + rm.GetString("Alert_PleaseentervalidDateandTime", ci) + "','" + rm.GetString("Alert_ValiddatemonthMMDDYYHHMM", ci) + "','" + rm.GetString("Alert_ValiddatemonthMMDDYYHHMMTT", ci) + "','" + rm.GetString("Alert_PleaseentervalidDateandTime", ci) + "','" + rm.GetString("Alert_Invalidvalueforhours", ci) + "','" + rm.GetString("Alert_Invalidvalueforminites", ci) + "');";
            strSetAlert = strSetAlert + "SetAlertMessages('" + rm.GetString("Alert_InValidTime", ci) + "','" + rm.GetString("Alert_InValidTimeFormat", ci) + "','" + rm.GetString("Alert_InvalidTimeMoreThan24", ci) + "','" + rm.GetString("Alert_InvalidTimeMoreThan59", ci) + "','" + rm.GetString("Alert_SelectInTerminal", ci) + "','" + rm.GetString("Alert_SelectPunchType", ci) + "','" + rm.GetString("Alert_FillInDate", ci) + "','" + rm.GetString("Alert_FillInTime", ci) + "','" + rm.GetString("Alert_SelectOutTerminal", ci) + "','" + rm.GetString("Alert_RouteName", ci) + "','" + rm.GetString("Alert_InTimeCorrectFormat", ci) + "','" + rm.GetString("Alert_InTimeCorrectFormat", ci) + "','" + rm.GetString("Alert_Are_you_sure_to_Save", ci) + "','" + rm.GetString("Alert_OutDate", ci) + "','" + rm.GetString("Alert_OutTime", ci) + "','" + rm.GetString("Alert_SelectInDate", ci) + "','" + rm.GetString("Alert_SelecttheRouteName", ci) + "','" + rm.GetString("Alert_Norecordsfound", ci) + "','" + rm.GetString("Alert_Errorinretrivingdetails", ci) + "','" + rm.GetString("Alert_SelectEntranceID", ci) + "','" + rm.GetString("Alert_SelectOutPunchType", ci) + "','" + rm.GetString("Alert_EntertheEmployeeID", ci) + "','" + rm.GetString("Alert_Selectshiftdate", ci) + "','" + rm.GetString("Alert_SelectStartTime", ci) + "','" + rm.GetString("Alert_SelectEndTime", ci) + "','" + rm.GetString("Validator_ManualTimeEntry_Reason", ci) + "','" + rm.GetString("Alert_SelectFromDate", ci) + "','" + rm.GetString("Alert_FromSession", ci) + "','" + rm.GetString("Alert_SelectToDate", ci) + "','" + rm.GetString("Alert_ToSession", ci) + "');";
            strSetAlert = strSetAlert + "</script>";
            Page.RegisterStartupScript("SetAlertMessages", strSetAlert);
            LoadSingleDayControls();
            FillEntranceDropDown();
            ViewState["DayType"] = "1";
            rbtGroup.Checked = true;
            rbtOnDuty.Checked = true;
            this.Page.RegisterStartupScript("Show", "<script> show()</script>");
            if (Session["CheckRecordsAddInPopUP"] != null)
            {
                Session["CheckRecordsAddInPopUP"] = null;
            }
            else
            {
                objShiftAllocation.DeleteEmpShiftDetails(gintUserId);
                Session["EmpDetails"] = null;
            }
        }
        site.SiteMapProvider = Convert.ToString(Session["SiteMapProvider"]);
        grvImportDetails.Styles.CssFilePath = Convert.ToString(Session["GridCSS"]);
        Hidden1.Value = Convert.ToString(Session["IDateFormat"]);
        TimeFormat = Hidden2.Value = Convert.ToString(Session["ITimeFormat"]);
        hiddenTime.Value = "HH:mm";
        switch (TimeFormat)
        {
            case "HH:mm":
                hiddenTime.Value = "HH:mm";
                lbl_InTime.Text = rm.GetString("OnDuty_InTime", ci);
                lbl_OutTime.Text = rm.GetString("OnDuty_OutTime", ci);
                break;
            default:
                hiddenTime.Value = "LT";
                lbl_InTime.Text = rm.GetString("OnDuty_InTime", ci);
                lbl_OutTime.Text = rm.GetString("OnDuty_OutTime", ci);
                break;
        }
        gintUserId = Int32.Parse(Convert.ToString(Session["EmpAutoID"]));
        gstrUserGroupName = Convert.ToString(Session["UserGroupName"]);
        if (Convert.ToString(Session["UserGroupName"]) != "SuperAdmin" && Convert.ToString(Session["IndividualUsers"]) != "True")
        {
            trEmployeeID.Visible = false;
            txt_EmployeeId.Text = Convert.ToString(Session["EmployeeCodeId"]);
            txt_Name.Text = Convert.ToString(Session["user"]);
            hdnEmployeeId.Value = Convert.ToString(Session["EmpAutoId"]);
        }
        int fl = Convert.ToInt16(Request.QueryString["fl"]);
        lbl_EntryDate.Text = DateTime.Now.ToString(Session["MDateFormat"].ToString());
        manualEntryExists = objCommon.CheckPageExistsInLicense(98);
        //Checking grade module is available or not and changed the id value from 110 to 228
        approvalSettingsPageExists = objCommon.CheckPageExistsInLicense(228);
        rbtGroup.Checked = true;
        rbtOnDuty.Checked = true;
        if (rbtGroup.Checked && rbtOnDuty.Checked)
        {
            rbtSingle.Checked = false;
            rbtBusLate.Checked = false;
            //this.Page.RegisterStartupScript("Show", "<script> show()</script>");
            if (Session["CheckRecordsAddInPopUP"] != null)
            {
                Session["CheckRecordsAddInPopUP"] = null;
            }
        }
        if (rbtnImport.Checked)
            this.Page.RegisterStartupScript("EmployeeName", "<script> ModeOfAllocation('')</script>");
        else
            this.Page.RegisterStartupScript("EmployeeName", "<script> EmpName('Onduty')</script>");

        #region Eastman
        if (Convert.ToString(Session["packageID"]) != "")
            if (Convert.ToString(Session["packageID"]) == "155")
            {
                if (Convert.ToString(Session["IndividualUsers"]) != "True")
                {
                    divmode_Allocation.Style.Add("display", "");
                }
            }
        #endregion
    }
    #endregion
    #region User Defined Function
    /// <summary>
    /// The FillEntranceDropDown Method is used to fill the Entrance Names in the Entrance Name DropDown List
    /// </summary>
    public void FillEntranceDropDown()
    {
        DataSet ds_Entrance = new DataSet();
        ds_Entrance = objEntrance.SelectEntranceDetailsForManualTimeEntry();
        string strEntranceId = string.Empty;
        if (ds_Entrance.Tables[0].Rows.Count > 0)
        {
            strEntranceId = ds_Entrance.Tables[0].Rows[0]["Entrance_Id"].ToString();
            ddlEntranceName.DataSource = ds_Entrance;
            ddlEntranceName.DataTextField = "Entrance_Name";
            ddlEntranceName.DataValueField = "Entrance_Id";
            ddlEntranceName.DataBind();
            ddlEntranceName.SelectedValue = strEntranceId;
            FillTerminals(strEntranceId);
        }
        ds_Entrance.Dispose();
    }
    public void FillTerminals(string strEntranceId)
    {
        DataSet dsInTerminals = new DataSet();
        dsInTerminals = objEntrance.SelectEntranceINOUTDetailsByIDview(Convert.ToInt32(strEntranceId), "In");
        dsInTerminals.Tables[0].TableName = "InTerminals";
        string strInTerminalId = string.Empty;
        if (dsInTerminals.Tables["InTerminals"].Rows.Count > 0)
        {
            strInTerminalId = dsInTerminals.Tables["InTerminals"].Rows[0]["Reader_Id"].ToString();
            ddlInTerminals.DataSource = dsInTerminals;
            ddlInTerminals.DataTextField = "Terminal_Name";
            ddlInTerminals.DataValueField = "Reader_Id";
            ddlInTerminals.DataBind();
            FillPunchTypes(strInTerminalId);
            hdn_InTerminal.Value = ddlInTerminals.SelectedItem.Value;
        }
        dsInTerminals.Dispose();
        DataSet dsOutTerminals = new DataSet();
        dsOutTerminals = objEntrance.SelectEntranceINOUTDetailsByIDview(Convert.ToInt32(strEntranceId), "Out");
        dsOutTerminals.Tables[0].TableName = "OutTerminals";
        string strOutTerminalId = string.Empty;
        if (dsOutTerminals.Tables[0].Rows.Count > 0)
        {
            strOutTerminalId = dsOutTerminals.Tables["OutTerminals"].Rows[0]["Reader_Id"].ToString();
            ddlOutTerminals.DataSource = dsOutTerminals;
            ddlOutTerminals.DataTextField = "Terminal_Name";
            ddlOutTerminals.DataValueField = "Reader_Id";
            ddlOutTerminals.DataBind();
            FillPunchTypes(strOutTerminalId);
            hdn_OutTerminal.Value = ddlOutTerminals.SelectedItem.Value;
        }
        dsOutTerminals.Dispose();
    }
    public void FillPunchTypes(string strEntranceId)
    {
        DataSet dsInPunchTypes = new DataSet();
        dsInPunchTypes = objPunchTypes.Select_PunchTypeDetailsByTerminalId(Convert.ToInt32(strEntranceId), "I");
        dsInPunchTypes.Tables[0].TableName = "InPunchTypes";
        if (dsInPunchTypes.Tables["InPunchTypes"].Rows.Count > 0)
        {
            ddlInPunchTypes.DataSource = dsInPunchTypes;
            ddlInPunchTypes.DataTextField = "PunchType";
            ddlInPunchTypes.DataValueField = "PunchType_Id";
            ddlInPunchTypes.DataBind();
            ddlInTerminals.SelectedIndex = 1;
            hdn_InPunchType.Value = ddlInPunchTypes.SelectedItem.Text;
        }
        DataSet dsOutPunchTypes = new DataSet();
        dsOutPunchTypes = objPunchTypes.Select_PunchTypeDetailsByTerminalId(Convert.ToInt32(strEntranceId), "O");
        dsOutPunchTypes.Tables[0].TableName = "OutPunchTypes";
        if (dsOutPunchTypes.Tables["OutPunchTypes"].Rows.Count > 0)
        {
            ddlOutPunchTypes.DataSource = dsOutPunchTypes;
            ddlOutPunchTypes.DataTextField = "PunchType";
            ddlOutPunchTypes.DataValueField = "PunchType_Id";
            ddlOutPunchTypes.DataBind();
            ddlOutTerminals.SelectedIndex = 1;
            hdn_OutPunchType.Value = ddlOutPunchTypes.SelectedItem.Text;
        }
    }
    public void SaveOndutyEntryDetails(string EmployeeId, string Type, int EmployeeAutoId)
    {
        DataSet ds_EntranceDetails = new DataSet();
        int intInReaderId = 0, intOutReaderId = 0, intRouteId = 0, intShiftId = 0;
        string strInDate = string.Empty, strOutDate = string.Empty, 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 strEntryDate = objCommon.DateConvertion(gstrDateFormat, lbl_EntryDate.Text);
                    int intIncludeWeekOff = 1;
                    intIncludeWeekOff = (rbIncludingWeeklyOff.Checked == true) ? 1 : 2;
                    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;
                    ds_Onduty = objManualEntry.InsertOnDutyEntryForTable
                        ("I", 0, EmployeeId,
                        DateTime.Parse(strEntryDate),
                        Convert.ToInt32(ViewState["DayType"]),
                        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;
        }
        DataSet dsShiftDetails = new DataSet();
        for (DateTime dtmDate = Convert.ToDateTime(strInDate); dtmDate <= Convert.ToDateTime(strOutDate); dtmDate = dtmDate.AddDays(1))
        {
            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;
            }
            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
            {
                dsShiftDetails = objShift.SelectShiftById(intShiftId);
            }
            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, lbl_EntryDate.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);
                    }
                    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
                {
                    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
            {
                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);
                }
            }
            if (Convert.ToInt32(ViewState["ODInsertStatus"]) == 0)
            {
                ViewState["ODInsertStatus"] = gintInsertCount;
            }
        }
    }

    private void ToConvertProperFormat(ref string strInDate, ref string strOutDate)
    {
        switch (rbSingleDayYes.Checked)
        {
            case true:
                strInDate = objCommon.DateConvertion(gstrDateFormat, txt_ShiftDate.Text);
                strOutDate = objCommon.DateConvertion(gstrDateFormat, txt_ShiftDate.Text);
                break;
            case false:
                strInDate = objCommon.DateConvertion(gstrDateFormat, txt_InDate.Text);
                strOutDate = objCommon.DateConvertion(gstrDateFormat, txt_OutDate.Text);
                break;
        }
    }

    public Boolean Validation(string EmployeeId, string Type, int EmployeeAutoId)
    {
        daysCount = 0;
        DataSet ds_EntranceDetails = new DataSet();
        int intShiftId = 0, IntWeekoffallow = 0;
        string strInDate = string.Empty, strOutDate = string.Empty, 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();
            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)
            {
                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);
                            txt_InDate.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);
                                txt_InDate.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;
    }


    /// <summary>
    /// To get the status of the manual entry based on the reporting to sanctioning persons
    /// </summary>
    /// <param name="inEmployeeCodeId"></param>
    /// <returns></returns>
    public string GetManualTimeEntryStatus(string inEmployeeCodeId)
    {
        DataSet dsReportingPersons = new DataSet();
        DataTable dtReportingPersons = new DataTable();
        string strManualTimeEntryStatus = string.Empty;
        Int64 intReportTo = 0, intLeave_Sanc_Authority = 0;
        dsReportingPersons = objEmployee.GetReportingToSanctionAuthorityByCodeID(inEmployeeCodeId);
        dtReportingPersons = dsReportingPersons.Tables[0];
        if (dtReportingPersons.Rows.Count > 0)
        {
            if (dtReportingPersons.Rows[0]["Reporting_To"] != DBNull.Value && dtReportingPersons.Rows[0]["Reporting_To"].ToString() != string.Empty)
            {
                intReportTo = Int64.Parse(dtReportingPersons.Rows[0]["Reporting_To"].ToString());
            }
            if (dtReportingPersons.Rows[0]["Leave_Sanc_Authority"] != DBNull.Value && dtReportingPersons.Rows[0]["Leave_Sanc_Authority"].ToString() != string.Empty)
            {
                intLeave_Sanc_Authority = Int64.Parse(dtReportingPersons.Rows[0]["Leave_Sanc_Authority"].ToString());
            }
        }
        if (intReportTo != 0 && intLeave_Sanc_Authority != 0 && intReportTo == intLeave_Sanc_Authority)
        {
            strManualTimeEntryStatus = "Forwarded";
        }
        else if (intReportTo == 0 && intLeave_Sanc_Authority != 0)
        {
            strManualTimeEntryStatus = "Forwarded";
        }
        else if (intReportTo != 0 && intLeave_Sanc_Authority == 0)
        {
            strManualTimeEntryStatus = "Forwarded";
        }
        else if (intReportTo == 0 && intLeave_Sanc_Authority == 0)
        {
            strManualTimeEntryStatus = "Forwarded";
        }
        else
        {
            strManualTimeEntryStatus = "Pending";
        }
        return (strManualTimeEntryStatus);
    }
    /// <summary>
    /// To display alert messages.
    /// </summary>
    /// <param name="Message"></param>
    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);
    }
    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);
    }
    /// <summary>
    /// Compare Current Date with In Date
    /// </summary>
    /// <param name="s"></param>
    /// <param name="e"></param>
    public void CheckInDate(object s, ServerValidateEventArgs e)
    {
        if (rbtOnDuty.Checked == false)
        {
            string strInDate = "";
            if (txt_InDate.Text != "")
            {
                gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
                strInDate = objCommon.DateConvertion(gstrDateFormat, txt_InDate.Text);
                DateTime dtCurrent = DateTime.Now;
                DateTime dtInDate = DateTime.Parse(strInDate);
                int Days = dtCurrent.CompareTo(dtInDate);
                if (Days > 0)
                {
                    e.IsValid = true;
                }
                else
                {
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("Validator_ManualTimeEntry_InDate", ci) + "');", true);
                    txt_InDate.Focus();
                    e.IsValid = false;
                }
            }
            else
            {
                e.IsValid = true;
            }
        }
    }
    /// <summary>
    /// Compare Current Date with Out Date
    /// </summary>
    /// <param name="s"></param>
    /// <param name="e"></param>
    public void CheckOutDate(object s, ServerValidateEventArgs e)
    {
        if (rbtOnDuty.Checked == false)
        {
            string strOutDate = "";
            if (txt_OutDate.Text != "")
            {
                gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
                strOutDate = objCommon.DateConvertion(gstrDateFormat, txt_OutDate.Text);
                DateTime dtCurrent = DateTime.Now;
                DateTime dtOutDate = DateTime.Parse(strOutDate);
                int Days = dtCurrent.CompareTo(dtOutDate);
                if (Days > 0)
                {
                    e.IsValid = true;
                }
                else
                {
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("Validator_ManualTimeEntry_OutDate", ci) + "');", true);
                    txt_OutDate.Focus();
                    e.IsValid = false;
                }
            }
            else
            {
                e.IsValid = true;
            }
        }
    }
    /// <summary>
    /// Compare InTime and OutTime
    /// </summary>
    /// <param name="s"></param>
    /// <param name="e"></param>
    public void CheckTime(object s, ServerValidateEventArgs e)
    {
        if ((txt_ShiftIn.Text != "") && (txt_ShiftOut.Text != ""))
        {
            DateTime dtmInTime = DateTime.Parse(txt_ShiftIn.Text);
            DateTime dtmOutTime = DateTime.Parse(txt_ShiftOut.Text);
            int day = dtmOutTime.CompareTo(dtmInTime);
            if (day > 0)
                e.IsValid = true;
            else
                e.IsValid = false;
        }
    }
    /// <summary>
    /// Getting Information from resource file and display it in label
    /// </summary>
    /// <param name="ci"></param>
    private void LoadStrings(CultureInfo ci)
    {
        lbl_OttHoliday.Text = rm.GetString("lbl_Include_WeekOff", ci);
        lbl_Header.Text = rm.GetString("UserGroups_ManualODEntry", ci);
        lbl_GroupEntryType.Text = rm.GetString("ManualTimeEntry_GroupEntryType", ci);
        lbl_EmployeeId.Text = rm.GetString("email_EmployeeId", ci);
        lbl_EmployeeName.Text = rm.GetString("email_EmployeeName", ci);
        lbl_EntranceName.Text = rm.GetString("EntranceMaster_Entrance_Name", ci);
        lbl_InDate.Text = "Shift - " + rm.GetString("OnDuty_InDate", ci);
        lbl_InTime.Text = rm.GetString("OnDuty_InTime", ci);
        lbl_InTerminal.Text = rm.GetString("Label_InTerminals", ci);
        lbl_InPunchType.Text = rm.GetString("ManualTimeEntry_InPunchType", ci);
        lbl_ManualTimeEntryDate.Text = rm.GetString("LeaveApplication_LeaveApplicationDate", ci);
        lbl_OutDate.Text = "Shift - " + rm.GetString("OnDuty_OutDate", ci);
        lbl_OutTime.Text = rm.GetString("OnDuty_OutTime", ci);
        lbl_OutTerminal.Text = rm.GetString("Label_OutTerminals", ci);
        lbl_OutPunchType.Text = rm.GetString("ManualTimeEntry_OutPunchType", ci);
        lbl_Reason.Text = rm.GetString("email_Reason", ci);
        lbl_RouteName.Text = rm.GetString("Transportation_Route_RouteName", ci);
        lbl_TypeOfManualEntry.Text = rm.GetString("ManualTimeEntry_TypeOfManualEntry", ci);
        lbl_IndicatesMandatoryFields.Text = rm.GetString("IndicatesMandatoryFields", ci);
        CustomValidator1.ErrorMessage = rm.GetString("Validator_ManualTimeEntry_InDate", ci);
        CustomValidator3.ErrorMessage = rm.GetString("Validator_ManualTimeEntry_OutDate", ci);
        rbtSingle.Text = rm.GetString("rbtn_EmployeeMaster_Single", ci);
        rbtGroup.Text = rm.GetString("rbtn_ManualTimeEntry_Group", ci);
        rbtBusLate.Text = rm.GetString("rbtn_ManualTimeEntry_BusLate", ci);
        rbtOnDuty.Text = rm.GetString("Dash_OnDuty", ci);
        btn_Add.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Save", ci);
        btn_Cancel.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Back", ci);
        btn_View.Text = rm.GetString("btn_View", ci);
        //btn_Search.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Search", ci);
        lbl_Employees.Text = rm.GetString("ManualTimeEntry_EmployeesAdd", ci);
        btn_ViewEmployees.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Add", ci);
        ddlRouteName.Items[0].Text = rm.GetString("Select", ci);
        ddlEntranceName.Items[0].Text = rm.GetString("Select", ci);
        lblLoading.Text = rm.GetString("ProgressBarText", ci);
        rbExcludingWeeklyOff.Text = rm.GetString("ShiftSetting_No", ci);
        rbIncludingWeeklyOff.Text = rm.GetString("ShiftSetting_Yes", ci);
        rbSingleDayNo.Text = rm.GetString("rbSingleDayNo", ci);
        rbSingleDayYes.Text = rm.GetString("rbSingleDayYes", ci);
        lbl_SingleDay.Text = rm.GetString("lbl_SingleDay", ci);
        lblSelectEmployee.Text = rm.GetString("lblSelectEmployee", ci);
        lbl_ShiftDate.Text = rm.GetString("OnDutyDate", ci);
        lblSessionstart.Text = rm.GetString("lbl_FromSession", ci);
        lblSessionEnd.Text = rm.GetString("lbl_ToSession", ci);

    }
    /// <summary>
    /// To check rights of the logged in user.
    /// </summary>
    private void UserRights()
    {
        ds_Checkuser = objCheckUser.checkRights(173, Convert.ToInt32(Session["userGroup_Id"]), "addPrv");
        if (ds_Checkuser.Tables[0].Rows.Count == 0)
        {
            Response.Redirect("TransactionLandingPage.aspx");
        }
    }
    /// <summary>
    /// To Display controls for single day OnDuty
    /// </summary>
    public void LoadSingleDayControls()
    {
        tr_ShiftDate.Visible = true;
        tr_InTime.Visible = true;
        tr_OutTime.Visible = true;
        tr_InDate.Visible = false;
        tr_Start_Session.Visible = false;
        tr_OutDate.Visible = false;
        tr_End_Session.Visible = false;
    }
    /// <summary>
    /// To Display controls for Multiple day OnDuty
    /// </summary>
    public void LoadMultipleDayControls()
    {
        tr_ShiftDate.Visible = false;
        tr_InTime.Visible = false;
        tr_OutTime.Visible = false;
        tr_InDate.Visible = true;
        tr_Start_Session.Visible = true;
        tr_OutDate.Visible = true;
        tr_End_Session.Visible = true;
    }
    protected void rbSingleDayYes_CheckedChanged(object sender, EventArgs e)
    {
        ViewState["DayType"] = "1";
        LoadSingleDayControls();
    }
    protected void rbSingleDayNo_CheckedChanged(object sender, EventArgs e)
    {
        ViewState["DayType"] = "2";
        LoadMultipleDayControls();
    }
    // Function to check Additional Weekly Off
    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 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);
    }
    #endregion
    #region Button Events
    /// <summary>
    /// Add Button - Click Event
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btn_Add_Click(object sender, EventArgs e)
    {
        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 (rbtOnDuty.Checked == true)
        {
            if (rbSingleDayYes.Checked == true)
            {
                #region SingleDateValidation
                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);
                    //Commented by Manikandan.R if any alert comes and then save the record means, punch types are not saving into database due to below two lines.
                    //hdn_InPunchType.Value = "";
                    //hdn_OutPunchType.Value = "";
                    txt_InDate.Focus();
                    return;
                }
                if (txt_ShiftDate.Text != "" && txt_ShiftDate.Text != string.Empty)
                {
                    strInDate = objCommon.DateConvertion(gstrDateFormat, txt_ShiftDate.Text);
                    strOutDate = objCommon.DateConvertion(gstrDateFormat, txt_ShiftDate.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_InDate.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_InDate.Focus();
                                    return;
                                }
                            }
                        }
                    }
                }
                #endregion
            }
            else if (rbSingleDayNo.Checked == true)
            {
                #region MultipleDateValidation
                if ((txt_InDate.Text == "") || (ddl_SessionFrom.SelectedIndex == 0) || (txt_OutDate.Text == "") || (ddl_SessionTo.SelectedIndex == 0) || (txt_Reason.Text == ""))
                {
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('Fill all mandatory field values')", true);
                    string scrt = "<script>ManualTimeEntry()</script>";
                    this.Page.RegisterStartupScript("a", scrt);
                    txt_InDate.Focus();
                    return;
                }
                //Commented by manikanan.rr on 09-07-2020
                //if ((txt_InDate.Text != "") && (ddl_SessionFrom.SelectedIndex == 0))
                //{
                //    ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("Msg_IntimeEmpty", ci) + "');", true);
                //    string scrt = "<script>ManualTimeEntry()</script>";
                //    this.Page.RegisterStartupScript("a", scrt);
                //    //hdn_InPunchType.Value = "";
                //    //hdn_OutPunchType.Value = "";
                //    txt_ShiftIn.Focus();
                //    return;
                //}
                //if ((txt_InDate.Text == string.Empty) && (ddl_SessionFrom.SelectedItem.Text != "-Select-"))
                //{
                //    ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("Msg_InDate", ci) + "');", true);
                //    string scrt = "<script>ManualTimeEntry()</script>";
                //    this.Page.RegisterStartupScript("a", scrt);
                //    //hdn_InPunchType.Value = "";
                //    //hdn_OutPunchType.Value = "";
                //    txt_InDate.Focus();
                //    return;
                //}
                //if ((txt_OutDate.Text != "") && (ddl_SessionTo.SelectedIndex == 0))
                //{
                //    ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("Msg_OutTimeEmpty", ci) + "');", true);
                //    string scrt = "<script>ManualTimeEntry()</script>";
                //    this.Page.RegisterStartupScript("a", scrt);
                //    //hdn_InPunchType.Value = "";
                //    //hdn_OutPunchType.Value = "";
                //    txt_ShiftOut.Focus();
                //    return;
                //}
                //if ((txt_OutDate.Text == "") && (ddl_SessionTo.SelectedItem.Text != "-Select-"))
                //{
                //    ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("Msg_OutDateEmpty", ci) + "');", true);
                //    string scrt = "<script>ManualTimeEntry()</script>";
                //    this.Page.RegisterStartupScript("a", scrt);
                //    //hdn_InPunchType.Value = "";
                //    //hdn_OutPunchType.Value = "";
                //    txt_OutDate.Focus();
                //    return;
                //}
                if (txt_InDate.Text != string.Empty && txt_InDate.Text != "" && txt_OutDate.Text != string.Empty && txt_OutDate.Text != "")
                {
                    strInDate = objCommon.DateConvertion(gstrDateFormat, txt_InDate.Text);
                    strOutDate = objCommon.DateConvertion(gstrDateFormat, txt_OutDate.Text);
                }
                if (txt_InDate.Text != string.Empty)
                {
                    DateTime dtmInDate = DateTime.Parse(strInDate);
                    if ((dtmFromDate <= dtmInDate) && (dtmInDate <= dtmToDate))
                    {
                    }
                    else
                    {
                        ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("Msg_ActiveYear", ci) + "');", true);
                        string scrt = "<script>ManualTimeEntry()</script>";
                        this.Page.RegisterStartupScript("a", scrt);
                        //hdn_InPunchType.Value = "";
                        //hdn_OutPunchType.Value = "";
                        txt_InDate.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);
                                    //hdn_InPunchType.Value = "";
                                    //hdn_OutPunchType.Value = "";
                                    txt_InDate.Focus();
                                    return;
                                }
                            }
                        }
                    }
                }
                if (txt_OutDate.Text != "")
                {
                    DateTime dtmOutDate = DateTime.Parse(strOutDate);
                    if ((dtmFromDate <= dtmOutDate) && (dtmOutDate <= dtmToDate))
                    {
                    }
                    else
                    {
                        ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("Msg_OutdateSetting", ci) + "');", true);
                        string scrt = "<script>ManualTimeEntry()</script>";
                        this.Page.RegisterStartupScript("a", scrt);
                        //hdn_InPunchType.Value = "";
                        //hdn_OutPunchType.Value = "";
                        txt_OutDate.Focus();
                        return;
                    }
                    if (gstrUserGroupName != "SuperAdmin")
                    {
                        if (Convert.ToString(Session["HasSpecialRights"]) != "True")
                        {
                            if (strMaxPayrollClosureDate != "")
                            {
                                DateTime dtmMaxPayrollClosureDate = DateTime.Parse(strMaxPayrollClosureDate);
                                if (dtmOutDate <= dtmMaxPayrollClosureDate)
                                {
                                    ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("Msg_InvalidPayroll", ci) + "');", true);
                                    string scrt = "<script>ManualTimeEntry()</script>";
                                    this.Page.RegisterStartupScript("a", scrt);
                                    //hdn_InPunchType.Value = "";
                                    //hdn_OutPunchType.Value = "";
                                    txt_OutDate.Focus();
                                    return;
                                }
                            }
                        }
                    }
                }
            }
            #endregion
        }
        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 (rbtGroup.Checked == true)
        {
            if (rbtOnDuty.Checked == true)
            {
                DataSet dsEmployees = new DataSet();
                DataTable dtEmpDetails = new DataTable();
                dsEmployees = objCommon.getEmployeeAutoId(txt_EmployeeId.Text);
                dtEmpDetails = dsEmployees.Tables[0];
                gintInsertCount = 0;
                int shiftID = 0;
                if (dtEmpDetails.Rows.Count > 0)
                {
                    if (strInDate == strOutDate && (rbSingleDayNo.Checked == true))
                    {
                        if (ddl_SessionFrom.SelectedItem.Text == "Second half" && ddl_SessionTo.SelectedItem.Text == "First half")
                        {
                            DisplayShiftTimingMessage("Select Valid Session");
                            return;
                        }
                    }
                    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)
                                {
                                    if (rbSingleDayNo.Checked == true)
                                    {
                                        if (ddl_SessionFrom.SelectedItem.Text == "First half")
                                        {
                                            txt_ShiftIn.Text = (dtActualShift.Rows[0]["Shift_StartTime"].ToString());
                                        }
                                        else if (ddl_SessionFrom.SelectedItem.Text == "Second half")
                                        {
                                            txt_ShiftIn.Text = (dtActualShift.Rows[0]["Shift_SecondHalf_StartTime"].ToString());
                                        }
                                        if (ddl_SessionTo.SelectedItem.Text == "First half")
                                        {
                                            txt_ShiftOut.Text = (dtActualShift.Rows[0]["Shift_FirstHalf_EndTime"].ToString());
                                        }
                                        else if (ddl_SessionTo.SelectedItem.Text == "Second half")
                                        {
                                            txt_ShiftOut.Text = (dtActualShift.Rows[0]["Shift_EndTime"].ToString());
                                        }
                                    }
                                    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);
                                            }
                                        }
                                    }
                                    //if (!(dttShiftIn >= dttActualShiftIn))
                                    //{
                                    //    gintInsertCount = 0;
                                    //    if (dtEmpDetails.Rows.Count > 1)
                                    //    {
                                    //        onDuty = rm.GetString("AlertCheckalltheEmployeeswithinshifttiming");
                                    //    }
                                    //    else
                                    //    {
                                    //        onDuty = rm.GetString("AlertSelectedintimeandouttime");
                                    //    }
                                    //    DisplayShiftTimingMessage(onDuty);
                                    //    return;
                                    //}
                                }
                                else if (dtActualShift.Rows.Count == 0)
                                {
                                    gintInsertCount = 0;
                                    onDuty = rm.GetString("AlertShiftnotallocated");
                                    DisplayShiftTimingMessage(onDuty);
                                    return;
                                }
                            }
                            else
                            {
                                gintInsertCount = 0;
                                onDuty = rm.GetString("AlertShiftnotallocated");
                                DisplayShiftTimingMessage(onDuty);
                                return;
                            }
                        }

                        dttShiftIn = DateTime.Parse(strInDate + " " + txt_ShiftIn.Text);
                        dttShiftOut = DateTime.Parse(strOutDate + " " + txt_ShiftOut.Text);


                        //if ((txt_ShiftIn.Text != "") && (txt_ShiftOut.Text != ""))
                        //{
                        //    strIn = Convert.ToString(dttShiftIn);
                        //    strOut = Convert.ToString(dttShiftOut);
                        //    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_Selectvalidfromsessionandtosession", ci) + "');", true);
                        //        string scrt = "<script>ManualTimeEntry()</script>";
                        //        this.Page.RegisterStartupScript("a", scrt);
                        //        //hdn_InPunchType.Value = "";
                        //        //hdn_OutPunchType.Value = "";
                        //        txt_InDate.Focus();
                        //        return;
                        //    }
                        //}
                    }
                    #region InsertingOnduty
                    foreach (DataRow drEmployee in dtEmpDetails.Rows)
                    {
                        if (drEmployee["Employee_Id"] != DBNull.Value)
                        {
                            SaveOndutyEntryDetails(drEmployee["Employee_code_Id"].ToString(), "GB", Convert.ToInt32(drEmployee["Employee_Id"]));
                        }
                    }
                    #endregion
                    objShiftAllocation.DeleteEmpShiftDetails(gintUserId);
                    if (IntOndutyID != 0)
                    {
                        //This below function added by karthikeyan for the send mail.
                        DataSet dsEmployeeDetails = new DataSet();
                        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 (Convert.ToInt32(ConfigurationManager.AppSettings.Get("isRequiredEmail")) == 1)
                        {
                            if (strEmailIdSanctioningAuthority != "" || strEmailIdReportingTo != "")
                            {
                                if (rbSingleDayYes.Checked == true)
                                {
                                    OndutyType = rm.GetString("rbSingleDayYes", ci);
                                    strInDate = txt_ShiftDate.Text;
                                    strOutDate = txt_ShiftDate.Text;
                                }
                                else if (rbSingleDayNo.Checked == true)
                                {
                                    strInDate = txt_InDate.Text;
                                    strOutDate = txt_OutDate.Text;
                                    OndutyType = rm.GetString("rbSingleDayNo", ci);
                                }
                                if (rbIncludingWeeklyOff.Checked == true)
                                    strIncludeWeekOff = rm.GetString("ShiftSetting_Yes", ci);
                                else
                                    strIncludeWeekOff = rm.GetString("ShiftSetting_No", ci);
                                string strEntryDate = lbl_EntryDate.Text;

                                SendMail(IntOndutyID, LevelID, strEmployeeEmailId, strEmailIdReportingTo, strEmailIdSanctioningAuthority, OndutyType, strInDate, hdfStartTime.Value, strOutDate, hdfStartEnd.Value, strEntryDate, strEmployeeName, strEmployeeCodeId, txt_Reason.Text.Trim().Replace("'", "''"), strlevelName, Convert.ToString(Session["OndutyStatus"]), strlevelName);

                            }
                        }
                        #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 (rbtOnDuty.Checked == false)
                {
                    if (strEmployeeIds == string.Empty)
                    {
                        DisplayMessage(rm.GetString("Msg_groupManual"));
                    }
                    else
                    {
                        strMessage = rm.GetString("Msg_groupMannual") + " " + strEmployeeIds;
                        DisplayMessage(strMessage);
                    }
                }
                else
                {
                    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 (txt_EmployeeId.Text == "")
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("Msg_FillEmployee", ci) + "');", true);
                string scrt = "<script>ManualTimeEntry()</script>";
                this.Page.RegisterStartupScript("a", scrt);
                //hdn_InPunchType.Value = "";
                //hdn_OutPunchType.Value = "";
                txt_EmployeeId.Focus();
                return;
            }
            DataSet dsEmpAutoId = new DataSet();
            dsEmpAutoId = objCommon.getEmployeeAutoId(txt_EmployeeId.Text);
            int EmployeeAutoId = Convert.ToInt32(dsEmpAutoId.Tables[0].Rows[0]["Employee_Id"]);
        }
    }

    /// <summary>
    ///  Cancel Button - Click Event
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btn_Cancel_Click(object sender, EventArgs e)
    {
        objShiftAllocation.DeleteEmpShiftDetails(gintUserId);
        Session["EmpDetails"] = null;
        Response.Redirect("../Transactions/TA_UI_Transactions_OnDutyList.aspx");
    }
    #endregion
    #region MessageWithRedirect.
    /// <summary>
    /// Messages the with redirect.
    /// </summary>
    /// <param name="messageContent">Content of the message.</param>
    /// <param name="ToPage">To page.</param>
    private void MessageWithRedirect(string messageContent, string ToPage)
    {
        string strScript = "<script language='javascript' type='text/javascript'>";
        strScript += "alert('" + messageContent + "');";
        strScript += "location.href='" + ToPage + "';";
        strScript += " </script>";
        ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", strScript, false);
    }
    #endregion
    #region Sending mail to the reporting to person.
    private void SendMail(int OnDutyID, int LevelID, string strEmployeeEmailId, string ToMailId, string SanctionMailId, string OndutyType, 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();
        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"]);
                //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));
                }

                TimeFormatMail = Convert.ToString(Session["ITimeFormat"]);
                if (TimeFormatMail == "HH:mm")
                {
                    TimeFormatMail = "HH:mm";
                }
                else
                {
                    TimeFormatMail = "hh:mm tt";
                }
                //}
                mailMessage.Subject = rm.GetString("email_OndutyApplicationForm", 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("<<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("Menu_OnDuty", ci)); 
                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);

                //Added by Karthikeyan.R for the link on mail purpose 
                //mailMessage.Body = mailMessage.Body.Replace("<<LinkData>>", strServerIP + "Transactions/TA_UI_Transactions_PermissionSanctionModify.aspx?Permission_Id=" + PermissionId + "&LevelId=" + LevelId + "&ApprovalType=Permission&Status=All&From_Date=&To_Date=strSwipeCardNo=&strEmployeeName=&strEmployeeCodeId=");
                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&ParentID=" + Convert.ToString(Session["parentLevelId"]) + "");
                }
                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);
                }
                objCommon.SendMail(mailMessage);
            }
            else
            {
                blnCheckEmail = false;
            }
        }
        catch (Exception Ex)
        {
            blnCheckEmail = false;
            Message(Ex.ToString());
        }
    }
    #endregion
    private DataTable ManualEntryImportCSV(FileInfo fileInfo)
    {
        char chrImportDelimiter;
        string strLine;
        string[] strArray;
        gstrDateFormat = "dd-MMM-yyyy";
        char[] charArray = new char[] { chrImportDelimiter = ',', ';' };
        DataSet ds = new DataSet("Onduty");
        DataTable dt = ds.Tables.Add("Data");
        aFile = new FileStream(fileInfo.FullName.ToString(), FileMode.Open);
        StreamReader sr = new StreamReader(aFile);
        strLine = sr.ReadLine();
        strArray = strLine.Split(charArray);
        int totalColumnCount = strArray.Length;
        string firstLevelColumnName = string.Empty;
        for (int x = 0; x <= strArray.GetUpperBound(0); x++)
        {
            dt.Columns.Add(strArray[x].Trim().Replace("\"", "").Replace("*", "").Replace(" ", "").Split('(')[0]);
        }
        dt.Columns.Add("flag", typeof(int));
        dt.Columns.Add("Errormessage", typeof(string));
        dt.Columns.Add("recordNumber", typeof(int));
        dt.Columns.Add("ShiftID", typeof(int));
        dt.Columns.Add("Userid", typeof(double));
        dt.Columns.Add("Status", typeof(string));
        strLine = sr.ReadLine();
        int recordnumber = 0;
        while (strLine != null)
        {
            recordnumber += 1;
            strArray = strLine.Split(charArray);
            gstrDateFormat = "dd-MMM-yyyy";
            if (strArray.Length > totalColumnCount)
            {
                Message(rm.GetString("Alert_Commashouldnotbeusedinanyofthedata", ci));
                sr.Dispose();
                aFile.Dispose();
                return null;
            }
            if (strArray.Length <= 1)
            {
                Message(rm.GetString("ImportFiles_Separation", ci));
                sr.Dispose();
                aFile.Dispose();
                return null;
            }
            DataRow dr = dt.NewRow();
            for (int i = 0; i <= strArray.GetUpperBound(0); i++)
            {
                dr[i] = strArray[i].Trim().Replace("\"", "");
            }
            dr["recordNumber"] = recordnumber;
            dr["flag"] = 1;
            dr["Errormessage"] = "";
            dr["Userid"] = gintUserId;
            dt.Rows.Add(dr);
            strLine = sr.ReadLine();
        }
        sr.Dispose();
        aFile.Dispose();
        if (ds.Tables[0].Rows.Count == 0)
        {
            Message(rm.GetString("Alert_ThereisnorecordintheImportfile", ci));
            sr.Dispose();
            aFile.Dispose();
            return null;
        }
        DataRow[] rows = ds.Tables[0].Select("EmployeeId IS NULL OR EmployeeId = ''");
        if (rows.Length > 0)
        {
            foreach (DataRow dr in rows)
            {
                dr["flag"] = 0;
                dr["Errormessage"] = rm.GetString("Alert_PleasefillEmployeeCodeforallemployees", ci);
            }
        }
        DataRow[] daterows = ds.Tables[0].Select("(Date IS NULL OR Date = '') and flag='1'");
        if (daterows.Length > 0)
        {
            foreach (DataRow dr in daterows)
            {
                dr["flag"] = 0;
                dr["Errormessage"] = (Convert.ToString(dr["Errormessage"]) != "") ? Convert.ToString(dr["Errormessage"]) + ";" + "Please fill the date for all employees in correct format" : "Please fill the date for all employees in correct format";
            }
        }
        ds.Tables[0].DefaultView.RowFilter = "flag=0";
        if (ds.Tables[0].DefaultView.Count > 0)
        {
            return ds.Tables[0].DefaultView.ToTable();
        }
        else
        {
            ds.Tables[0].DefaultView.RowFilter = "flag='1'";
            foreach (DataRowView dr in ds.Tables[0].DefaultView)
            {
                DataSet ds_EmpName = new DataSet();
                string LevelId = string.Empty;
                string level;
                txt_EmployeeId.Text = dr[1].ToString();
                txt_InDate.Text = Convert.ToString(dr[2]).Replace("'", "");
                txt_Reason.Text = dr[3].ToString();
                string EmployeeId = dr[1].ToString();
                string strInDate = "";
                Rpt_Common rptcommon = new Rpt_Common();
                level = rptcommon.getNodes(Convert.ToInt32(0), Convert.ToString(Session["LevelRights"]));
                ds_EmpName = objManualEntry.SelectEmpName(Convert.ToInt32(Session["EmpAutoId"]), EmployeeId, Convert.ToString(Session["UserGroupName"]), Convert.ToString(Session["GradeLevel"]), level, 0, "");
                if (ds_EmpName != null)
                {
                    if (ds_EmpName.Tables[0].Rows.Count == 0)
                    {
                        dr["flag"] = 0;
                        dr["Errormessage"] = "Invalid Employee id / You are not eligible to apply onduty for this employee.";
                        continue;
                    }
                }
                try
                {
                    strInDate = objCommon.DateConvertion(gstrDateFormat, txt_InDate.Text);
                }
                catch (Exception Ex)
                {
                    dr["flag"] = 0;
                    dr["Errormessage"] = (Convert.ToString(dr["Errormessage"]) != "") ? Convert.ToString(dr["Errormessage"]) + ";Date - Invalid Date Format" : "Date - Invalid Date Format";
                    continue;
                }
                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(ds_Year.Tables[0].Rows[0]["FromDate"].ToString());
                        if (ds_Year.Tables[0].Rows[0]["ToDate"] != DBNull.Value)
                            dtmToDate = DateTime.Parse(ds_Year.Tables[0].Rows[0]["ToDate"].ToString());
                        ViewState["YearSettings_Id"] = ds_Year.Tables[0].Rows[0]["YearSettings_Id"].ToString();
                    }
                }
                string strMaxPayrollClosureDate = objManualEntry.SelectMaxPayrollClosureDate();
                if (txt_InDate.Text != string.Empty && strInDate != string.Empty)
                {
                    DateTime dtmInDate = DateTime.Parse(strInDate);
                    if (!((dtmFromDate <= dtmInDate) && (dtmInDate <= dtmToDate)))
                    {
                        string Message = rm.GetString("Msg_ActiveYear", ci);
                        dr["flag"] = 0;
                        dr["Errormessage"] = (Convert.ToString(dr["Errormessage"]) != "") ? Convert.ToString(dr["Errormessage"]) + ";" + Message : Message;
                        continue;
                    }
                    if (gstrUserGroupName != "SuperAdmin")
                    {
                        if (strMaxPayrollClosureDate != "")
                        {
                            DateTime dtmMaxPayrollClosureDate = DateTime.Parse(strMaxPayrollClosureDate);
                            if (dtmInDate <= dtmMaxPayrollClosureDate)
                            {
                                string Message = rm.GetString("Msg_InDateProcessed", ci);
                                dr["flag"] = 0;
                                dr["Errormessage"] = (Convert.ToString(dr["Errormessage"]) != "") ? Convert.ToString(dr["Errormessage"]) + ";" + Message : Message;
                                continue;
                            }
                        }
                    }
                }
                DataSet dsEmpAutoId = new DataSet();
                dsEmpAutoId = objManualEntry.getEmployeeAutoIdForImport(txt_EmployeeId.Text);
                if (dsEmpAutoId.Tables[0].Rows.Count == 0)
                {
                    string Message = "Unable to Upload.Employee ID - " + txt_EmployeeId.Text + " is not Active Status ";
                    dr["flag"] = 0;
                    dr["Errormessage"] = (Convert.ToString(dr["Errormessage"]) != "") ? Convert.ToString(dr["Errormessage"]) + ";" + Message : Message;
                    continue;
                }
                else
                {
                    int EmployeeAutoId = Convert.ToInt32(dsEmpAutoId.Tables[0].Rows[0]["Employee_Id"]);
                    string status = getStatus(EmployeeAutoId);
                    dr["Status"] = status;
                }
                string strDateOfJoining = string.Empty;
                DataSet dsEmployeeDOJ = new DataSet();
                dsEmployeeDOJ = objEmployee.GetEmployeeDateOfJoining(txt_EmployeeId.Text, "", "", "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();
                    }
                }
                if (strDateOfJoining != string.Empty)
                {
                    DateTime dtmDateOfJoining = DateTime.Parse(strDateOfJoining);
                    if (strInDate != string.Empty)
                    {
                        strIsINPunchPresent = "Y";
                        DateTime dtmInDate = DateTime.Parse(strInDate);
                        if (dtmInDate < dtmDateOfJoining)
                        {
                            string Message = rm.GetString("Msg_IndateGreaterThanEmpDOJ", ci);
                            dr["flag"] = 0;
                            dr["Errormessage"] = (Convert.ToString(dr["Errormessage"]) != "") ? Convert.ToString(dr["Errormessage"]) + ";" + Message : Message;
                            continue;
                        }
                        intShiftId = objShiftExchange.SelectShiftId(EmployeeId, dtmInDate.Year.ToString(), dtmInDate.Month.ToString(), dtmInDate.Day.ToString());
                        if (intShiftId == 0)
                        {
                            string Message = rm.GetString("Msg_ManualTimeEntry", ci);
                            dr["flag"] = 0;
                            dr["Errormessage"] = (Convert.ToString(dr["Errormessage"]) != "") ? Convert.ToString(dr["Errormessage"]) + ";" + Message : Message;
                            continue;
                        }
                        else
                        {
                            dr["ShiftID"] = intShiftId;
                            count = objManualEntry.CheckManualODEntry(txt_EmployeeId.Text, intShiftId, strInDate);
                            if (count > 0)
                            {
                                dr["flag"] = 0;
                                dr["Errormessage"] = "Onduty entry already available for " + strInDate;
                                continue;
                            }
                        }
                    }
                }
            }
            ds.Tables[0].DefaultView.RowFilter = "flag=0";
            if (ds.Tables[0].DefaultView.Count > 0)
            {
                return ds.Tables[0].DefaultView.ToTable();
            }
            else
            {
                StringWriter strwr_importData = new StringWriter();
                ds.Tables[0].DefaultView.RowFilter = "flag=1";
                ds.Tables[0].DefaultView.ToTable().WriteXml(strwr_importData);
                string str_importData = Convert.ToString(strwr_importData);
                aFile.Dispose();
                return objManualEntry.InsertOnDutyEntry(str_importData);
            }
        }
    }
    protected void btn_Upload_Click(object sender, EventArgs e)
    {
        try
        {
            if (fup_ShiftImport.HasFile)
            {
                string filename = fup_ShiftImport.FileName.Substring(fup_ShiftImport.FileName.LastIndexOf("\\") + 1);
                string fileType = System.IO.Path.GetExtension(filename);
                if (fileType == ".csv")
                {
                    string strFilePath = Server.MapPath("Uploads");
                    FileInfo fileInfo = new System.IO.FileInfo(strFilePath + "\\" + fup_ShiftImport.FileName);
                    fup_ShiftImport.SaveAs(strFilePath + "\\" + fup_ShiftImport.FileName);
                    if (fup_ShiftImport.PostedFile.ContentLength == fileInfo.Length)
                    {
                        if (fileType == ".csv")
                        {
                            dtOndutyRecords = ManualEntryImportCSV(fileInfo);
                            if (dtOndutyRecords.Rows.Count > 0)
                            {
                                if (dtOndutyRecords.Columns.Contains("message"))
                                {
                                    grvImportDetails.DataSource = null;
                                    grvImportDetails.DataBind();
                                    commonAlertMessage("Onduty Data Imported Successfully");
                                    return;
                                }
                                grdControl.Style.Add("display", "");
                                if (dtOndutyRecords.Columns.Contains("EmployeeId"))
                                {
                                    grvImportDetails.DataSource = dtOndutyRecords;
                                    grvImportDetails.DataBind();
                                    commonAlertMessage("Some invalid data found in the imported file,please Correct it first and then import the file once again");
                                    ViewState["OndutyRecords"] = dtOndutyRecords;
                                }
                            }
                        }
                    }
                    else
                    {
                        commonAlertMessage(rm.GetString("Alert_ErrorinImportingEmployee", ci));
                    }
                }
                else
                {
                    commonAlertMessage(rm.GetString("Alert_TheUploadedfileisnotExcelfile", ci));
                }
            }
            else
            {
                commonAlertMessage(rm.GetString("Alert_Youhavenotspecifiedafile", ci));
            }
        }
        catch (Exception Ex)
        {
            string strErr = Convert.ToString(Ex.Message);
            commonAlertMessage(strErr.Replace("\r", "").Replace("\n", ""));
        }
        finally
        {
            try
            {
                if (fup_ShiftImport.HasFile)
                {
                    string StrFilePath = Convert.ToString(Server.MapPath("Uploads")) + "\\" + fup_ShiftImport.FileName;
                    System.IO.File.Delete(StrFilePath);
                }
            }
            catch (Exception Ex)
            {
            }
            if (aFile != null)
                aFile.Dispose();
        }
    }

    private void commonAlertMessage(string alertmsg)
    {
        divImport.Style.Add("display", "block");
        divManual.Style.Add("display", "none");
        Message(alertmsg);
        if (aFile != null) aFile.Dispose();
    }

    protected void btn_Template_Click(object sender, EventArgs e)
    {
        try
        {
            string strPath = Server.MapPath("Uploads/OndutyImport.xls");
            if (File.Exists(strPath))
            {
                byte[] data = System.IO.File.ReadAllBytes(strPath);
                Response.Clear();
                Response.AddHeader("Content-Type", "application/Excel");
                Response.AddHeader("Content-Disposition", "attachment;filename=OndutyImport.csv");
                Response.BinaryWrite(data);
                Response.End();
            }
            else
            {
                base.Message("Template file is not available in the source file");
                return;
            }
        }
        catch (Exception Ex)
        {
            throw Ex;
        }
    }

    public string getStatus(int loginempID)
    {
        string strManualTimeEntryStatus = "Pending";
        if (manualEntryExists == 1)
        {
            if (approvalSettingsPageExists == 1)
            {
                int intCompanyId = base.GetCompanyId(loginempID);
                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
                                strManualTimeEntryStatus = objShift.GetApprovalStatus(Convert.ToInt32(Session["EmpAutoID"]), Convert.ToString(loginempID), Convert.ToBoolean(Session["ReportsBasedOn"]));
                        }
            }
        }
        else
            strManualTimeEntryStatus = "Approved";
        return (strManualTimeEntryStatus == "") ? "Pending" : strManualTimeEntryStatus;
    }

    protected void lnkbtnRemove_Click(object sender, EventArgs e)
    {
        if (ViewState["OndutyRecords"] != null)
        {
            ViewState["OndutyRecords"] = null;
            dtOndutyRecords = null;
            grvImportDetails.DataSource = ViewState["OndutyRecords"];
            grvImportDetails.DataBind();
            grdControl.Style.Add("display", "none");
        }
    }
}
