using DevExpress.Web;
using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Resources;
using System.Threading;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;

public partial class Transactions_TA_UI_Transaction_NearestShiftAllocation : Base.BasePage
{
    #region Variable Declaration
    Cls_CheckUser objCheckUser = new Cls_CheckUser();
    GetReports rptEmp = new GetReports();
    DataSet ds_Checkuser = new DataSet();
    HeaderInformation hdrTable = new HeaderInformation();
    ResourceManager rm;
    ShiftPatternEventData objShiftPatternOverLap = new ShiftPatternEventData();
    ShiftAllocationEvendata objShiftAllocation = new ShiftAllocationEvendata();
    CultureInfo ci;
    cls_Common objCommon = new cls_Common();
    EmployeeEventData objEmployee = new EmployeeEventData();
    string strFromdate, gstrDateFormat, strTodate;
    Rpt_Common rptcommon = new Rpt_Common();
    int intIndividualUser = 0;
    string strEmpAutoId = "0";
    DiscrepancyEventData objDis = new DiscrepancyEventData();
    ShiftEvenData objShift = new ShiftEvenData();
    bool chkShiftAllocationExists;
    DataSet dsOverLapping = new DataSet();
    DataSet ds_Empdetails = new DataSet();
    DataSet ds_ShiftAllocdetails = new DataSet();
    DataSet ds = new DataSet();
    DataSet ds_ShiftPattern = new DataSet();
    DataTable dtEmpDetails = new DataTable();
    int PatternDaysCount = 0;
    #endregion
    protected override void Page_Load(object sender, EventArgs e)
    {
        // session checking
        base.Page_Load(sender, e);
        //get the culture info to set the language     
        grdNearestShift.Styles.CssFilePath = Convert.ToString(Session["GridCSS"]);
        if (!Page.IsPostBack)
        {
            base.CheckPages(0);
        }
        string source_Language;
        source_Language = Convert.ToString(Session["Session_ActiveLanguage"]);
        rm = new ResourceManager(source_Language, System.Reflection.Assembly.Load("App_GlobalResources"));
        ci = Thread.CurrentThread.CurrentCulture;
        site.SiteMapProvider = Convert.ToString(Session["SiteMapProvider"]);
        LoadStrings(ci);
        string strSetAlert = "";
        strSetAlert = strSetAlert + "<script language='javascript'>";
        strSetAlert = strSetAlert + "MaxLengthh('" + rm.GetString("Alert_MaximumLengthis", ci) + "');";
        strSetAlert = strSetAlert + "SetAlertMessages('" + rm.GetString("Alert_EnterValidFromDate", 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 + "</script>";
        Page.RegisterStartupScript("SetAlertMessages", strSetAlert);
        //Set UserRights
        UserRights();
        //grdNearestShift.Settings.HorizontalScrollBarMode = ScrollBarMode.Hidden;

        if (!IsPostBack)
        {
            Hidden1.Value = Convert.ToString(Session["IDateFormat"]);
            Hidden2.Value = Convert.ToString(Session["IDateFormat"]);
            // Bindings the employee category and type.
            BindingEmployeeCategoryandType();
            FillDesignation();
            fillShift();
            ddlDesignation.PreRender += LB_PreRender;
            txtFromDate.Text = (Convert.ToDateTime(objCommon.CurrentMonthStartDate())).ToString(Session["MDateFormat"].ToString());
            txtToDate.Text = (Convert.ToDateTime(System.DateTime.Now.ToShortDateString())).ToString(Convert.ToString(Session["MDateFormat"]));
            if (Session["parentLevelId"] != null || Convert.ToInt16(Session["parentLevelId"]) != 0)
            {
                Session["parentLevelId"] = null;
            }
            //Todo: need to change id and name
            objCommon.menu("ShiftTransaction", "255");
        }
        //Convert date time to MM/dd/YYYY format
        gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
        strFromdate = txtFromDate.Text;
        strFromdate = objCommon.DateConvertion(gstrDateFormat, strFromdate);
        strTodate = txtToDate.Text;
        strTodate = objCommon.DateConvertion(gstrDateFormat, strTodate);
    }
    /// <summary>
    /// Fills the designation in the drop down
    /// </summary>
    private void FillDesignation()
    {
        DataSet ds_designation = new DataSet();
        ds_designation = objEmployee.select_CommonDesignation();
        if (ds_designation != null)
        {
            if (ds_designation.Tables[0].Rows.Count > 0)
            {
                ddlDesignation.DataSource = ds_designation;
                ddlDesignation.DataTextField = "TitleName";
                ddlDesignation.DataValueField = "TitleId";
                ddlDesignation.DataBind();
            }
            ds_designation.Dispose();
            foreach (ListItem item in ddlDesignation.Items)
            {
                item.Attributes.Add("title", item.Text);
            }
        }
    }
    /// <summary>
    /// Bindings the employee category and type.
    /// </summary>
    private void BindingEmployeeCategoryandType()
    {
        // employee category binding
        DataSet dsCategory = new DataSet();
        dsCategory = objEmployee.SelectCategoryDetailsEmployee("");
        if (dsCategory != null)
        {
            if (dsCategory.Tables[0].Rows.Count > 0)
            {
                ddlEmpCatagory.DataSource = dsCategory;
                ddlEmpCatagory.DataTextField = "CategoryName";
                ddlEmpCatagory.DataValueField = "CategoryId";
                ddlEmpCatagory.DataBind();
            }
            dsCategory.Dispose();
            foreach (ListItem item in ddlEmpCatagory.Items)
            {
                item.Attributes.Add("title", item.Text);
            }
        }
        // employee type binding
        DataSet dsType = new DataSet();
        dsType = objEmployee.SelectTypeDetailsEmployee("");
        if (dsType != null)
        {
            if (dsType.Tables[0].Rows.Count > 0)
            {
                ddlEmpType.DataSource = dsType;
                ddlEmpType.DataTextField = "TypeName";
                ddlEmpType.DataValueField = "TypeId";
                ddlEmpType.DataBind();
            }
            dsType.Dispose();
            foreach (ListItem item in ddlEmpType.Items)
            {
                item.Attributes.Add("title", item.Text);
            }
        }
    }
    /// <summary>
    /// Getting Information from resource file and display it in label
    /// </summary>
    /// <param name="ci"></param>
    private void LoadStrings(CultureInfo ci)
    {
        btn_View.Text = "&nbsp;&nbsp;" + rm.GetString("btn_View", ci);
        //Todo: need to add data in resource file
        lblShiftReport.Text = rm.GetString("NearestShiftAllocatinHeader", ci);
        lblTimePeriod.Text = rm.GetString("Reports_TimePeriod", ci);
        lblFrom.Text = rm.GetString("email_FromDate", ci);
        lblTo.Text = rm.GetString("email_ToDate", ci);
        lblEmployeeName.Text = rm.GetString("email_EmployeeName", ci);
        lblEmployeeId.Text = rm.GetString("email_EmployeeId", ci);
        lblEmpCategory.Text = rm.GetString("Master_Category", ci);
        lblEmpType.Text = rm.GetString("Master_Type", ci);
        lblShift.Text = rm.GetString("Menu_Reports_Shift", ci);
        reqFromDate.ErrorMessage = rm.GetString("Alert_PleaseselectFromDate", ci);
        ddlEmpCatagory.Items[0].Text = rm.GetString("Select", ci);
        ddlEmpType.Items[0].Text = rm.GetString("Select", ci);
        lblDesignation.Text = rm.GetString("EmployeeMaster_Designation", ci);
        lblGender.Text = rm.GetString("EmployeeMaster_Gender", ci);
        ddlGender.Items[0].Text = rm.GetString("Caption_Both", ci);
        ddlGender.Items[1].Text = rm.GetString("rbtn_EmployeeMaster_Male", ci);
        ddlGender.Items[2].Text = rm.GetString("rbtn_EmployeeMaster_Female", ci);
        ddlDesignation.Items[0].Text = rm.GetString("ExportData_All", ci);
        lblFilter.Text = rm.GetString("lblFilter", ci);
        btnSave.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Save", ci);
        grdNearestShift.Columns[1].Caption = rm.GetString("email_EmployeeId", ci);
        grdNearestShift.Columns[2].Caption = rm.GetString("email_EmployeeName", ci);
        grdNearestShift.Columns[3].Caption = rm.GetString("ShiftDate", ci);
        grdNearestShift.Columns[4].Caption = rm.GetString("NearestShiftAllocation_ASIT", ci);
        grdNearestShift.Columns[5].Caption = rm.GetString("NearestShiftAllocation_SST", ci);
        grdNearestShift.Columns[6].Caption = rm.GetString("NearestShiftAllocation_NMS", ci);
        grdNearestShift.Columns[7].Caption = rm.GetString("NearestShiftAllocation_Shifts", ci);
        lblASIT.Text = rm.GetString("NearestShiftAllocation_Label_ASIT", ci);
        lblSST.Text = rm.GetString("NearestShiftAllocation_Label_SST", ci);
        lblNMS.Text = rm.GetString("NearestShiftAllocation_Label_NMS", ci);
    }
    /// <summary>
    /// To check rights for the logged in user
    /// </summary>
    private void UserRights()
    {
        ds_Checkuser = objCheckUser.checkRights(255, Convert.ToInt32(Session["userGroup_Id"]), "viewPrv");
        if (ds_Checkuser.Tables[0].Rows.Count > 0)
        {
            if (ds_Checkuser.Tables[0].Rows[0]["viewPrv"] == DBNull.Value || Convert.ToInt32(ds_Checkuser.Tables[0].Rows[0]["viewPrv"]) == 1)
            {
                btn_View.Visible = true;
            }
            else
            {
                btn_View.Visible = false;
            }
        }
        else
        {
            Response.Redirect("TransactionLandingPage.aspx");
        }
    }
    /// <summary>
    /// To apply tooltip for the designation in the drop down
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void LB_PreRender(object sender, System.EventArgs e)
    {
        foreach (ListItem item in ddlDesignation.Items)
        {
            item.Attributes.Add("title", item.Text);
        }
    }
    /// <summary>
    /// Load Shift Dropdown
    /// </summary>
    public void fillShift()
    {
        ShiftEvenData getShift = new ShiftEvenData();
        DataSet ds = new DataSet();
        string strusergroup = string.Empty;
        ds = getShift.SelectShift(Convert.ToString(Session["UserGroupName"]), Convert.ToString(Session["LevelRights"]), 0);
        foreach (DataRow drRow in ds.Tables[0].Rows)
        {
            switch (drRow["Shift_Name"].ToString())
            {
                case "No Shift":
                    drRow["Shift_Name"] = rm.GetString("Caption_NoShift", ci);
                    break;
            }
        }
        if (ds.Tables[0].Rows.Count > 0)
        {
            this.ddlShift.DataSource = ds;
            this.ddlShift.DataTextField = "Shift_Name";
            this.ddlShift.DataValueField = "Shift_Id";
            this.ddlShift.DataBind();
        }
        ListItem lstItem = new ListItem();
        lstItem.Value = "0";
        //lstItem.Text = "All";
        lstItem.Text = rm.GetString("ExportData_All", ci);
        ddlShift.Items.Insert(0, lstItem);
        foreach (ListItem item in ddlShift.Items)
        {
            item.Attributes.Add("title", item.Text);
        }
    }
    /// <summary>
    /// Validate the FromDate
    /// </summary>
    /// <param name="s"></param>
    /// <param name="e"></param>
    public void ValidateFromDate(object s, ServerValidateEventArgs e)
    {
        try
        {
            strFromdate = txtFromDate.Text;
            if (Session["MDateFormat"] != null)
            {
                gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
            }
            strFromdate = objCommon.DateConvertion(gstrDateFormat, strFromdate);
            DateTime dtCurrentDate = Convert.ToDateTime(DateTime.Today.Date);
            DateTime dtFromDate = DateTime.Parse(strFromdate);
            TimeSpan diff = dtFromDate.Subtract(dtCurrentDate);
            int day = diff.Days;
            if (day <= 0)
                e.IsValid = true;
            else
            {
                base.Message(rm.GetString("Alert_EnterValidFromDate", ci));
                e.IsValid = false;
            }
        }
        catch
        {            //
        }
    }
    /// <summary>
    /// Validate the ToDate
    /// </summary>
    /// <param name="s"></param>
    /// <param name="e"></param>
    public void ValidateToDate(object s, ServerValidateEventArgs e)
    {
        try
        {
            if (Session["MDateFormat"] != null)
            {
                gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
            }
            strTodate = txtToDate.Text;
            strTodate = objCommon.DateConvertion(gstrDateFormat, strTodate);
            DateTime dtCurrentDate = Convert.ToDateTime(DateTime.Today.Date);
            DateTime dtFromDate = DateTime.Parse(strTodate);
            TimeSpan diff = dtFromDate.Subtract(dtCurrentDate);
            int day = diff.Days;
            if (day <= 0)
                e.IsValid = true;
            else
            {
                base.Message(rm.GetString("Alert_EnterValidToDate", ci));
                e.IsValid = false;
            }
        }
        catch
        {            //
        }
    }
    /// <summary>
    /// Compare ToDate with FromDate
    /// </summary>
    /// <param name="s"></param>
    /// <param name="e"></param>
    public void CompareDate(object s, ServerValidateEventArgs e)
    {
        try
        {
            strFromdate = txtFromDate.Text;
            strTodate = txtToDate.Text;
            if (Session["MDateFormat"] != null)
            {
                gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
            }
            strTodate = objCommon.DateConvertion(gstrDateFormat, strTodate);
            strFromdate = objCommon.DateConvertion(gstrDateFormat, strFromdate);
            DateTime dtToDate = DateTime.Parse(strTodate);
            DateTime dtFromDate = DateTime.Parse(strFromdate);
            TimeSpan diff = dtToDate.Subtract(dtFromDate);
            int day = diff.Days;
            if (day >= 0)
                e.IsValid = true;
            else
            {
                base.Message(rm.GetString("Msg_SelectvaliddatecomparewithFromdate", ci));
                e.IsValid = false;
            }
        }
        catch
        {            //
        }
    }
    protected void btn_View_Click(object sender, EventArgs e)
    {
        int employeeCategory = 0, employeeType = 0;
        try
        {
            if (Page.IsValid == true)
            {
                string dtFrom = "";
                string dtTo = "";
                if (txtFromDate.Text != "")
                    dtFrom = strFromdate;
                if (txtToDate.Text != "")
                    dtTo = strTodate;
                if (Convert.ToInt32(ddlEmpCatagory.SelectedValue) != 0)
                {
                    employeeCategory = Convert.ToInt32(ddlEmpCatagory.SelectedValue);
                }
                else
                {
                    employeeCategory = 0;
                }
                if (Convert.ToInt32(ddlEmpType.SelectedValue) != 0)
                {
                    employeeType = Convert.ToInt32(ddlEmpType.SelectedValue);
                }
                else
                {
                    employeeType = 0;
                }
                if (Session["ReportsBasedOn"] != null)
                {
                    strEmpAutoId = (Convert.ToString(Session["ReportsBasedOn"]) == "False") ? "0" : Convert.ToString(Session["EmpAutoID"]);
                }
                int shft = 0;
                shft = Convert.ToInt16(this.ddlShift.SelectedValue);
                string Level = string.Empty;
                string employeeName = string.Empty;
                string empName = string.Empty;
                string empId = string.Empty;
                string EmployeeId = string.Empty;
                if (intIndividualUser >= 1)
                {
                    empName = string.Empty;
                    Level = string.Empty;
                    empId = Convert.ToString(Session["EmployeeCodeId"]);
                    EmployeeId = Convert.ToString(Session["EmployeeCodeId"]);
                }
                else
                {
                    EmployeeId = txtEmployeeId.Text.Trim();
                    empName = txtEmployeeName.Text.ToString();
                    empId = txtEmployeeId.Text.Trim().ToString();
                    employeeName = this.txtEmployeeName.Text.Replace("'", "''");
                    Level = rptcommon.getNodes(Convert.ToInt16(Session["parentLevelId"]), Convert.ToString(Session["LevelRights"]));
                }
                GetNearestShiftDetails(dtFrom, empId, shft, empName, employeeCategory, employeeType, Convert.ToString(Session["UserGroupName"]), Convert.ToString(Session["GradeLevel"]), Convert.ToInt16(Session["parentLevelId"]), Convert.ToInt32(ddlDesignation.SelectedValue), Convert.ToString(ddlGender.SelectedValue), Convert.ToInt64(strEmpAutoId), dtTo);
            }
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (hdnSelectRow.Value != string.Empty && hdnSelectRow.Value != null)
        {
            #region SaveLeaveDetails
            int ddlID = 0;
            bool isInserted = false;
            int empAutoID = 0;
            DateTime shftDate = new DateTime();
            for (int i = 0; i < grdNearestShift.VisibleRowCount; i++)
            {
                HtmlInputCheckBox chkbox = (HtmlInputCheckBox)grdNearestShift.FindRowCellTemplateControl(i, (GridViewDataColumn)grdNearestShift.Columns["AutoID"], "chkSelect");
                if (chkbox != null)
                {
                    if (chkbox.Checked == true)
                    {
                        DropDownList grddlshift = (DropDownList)grdNearestShift.FindRowCellTemplateControl(i, null, "ddlshift");
                        if (grddlshift != null)
                        {
                            ddlID = Convert.ToInt16(grddlshift.SelectedItem.Value);
                        }
                        Label lblEmployeeAutoID = (Label)grdNearestShift.FindRowCellTemplateControl(i, (GridViewDataColumn)grdNearestShift.Columns["EmployeeAutoID"], "lblEmployeeAutoID");
                        if (lblEmployeeAutoID != null)
                        {
                            empAutoID = Convert.ToInt16(lblEmployeeAutoID.Text);
                        }
                        Label lblFormat = (Label)grdNearestShift.FindRowCellTemplateControl(i, (GridViewDataColumn)grdNearestShift.Columns["Format"], "lblFormat");
                        if (lblFormat != null)
                        {
                            shftDate = Convert.ToDateTime(lblFormat.Text);
                        }
                        if (grddlshift != null && lblEmployeeAutoID != null & lblFormat != null)
                        {
                            //int overLapped= OverLappedValidation(shftDate, empAutoID, ddlID, ddlID);
                            objShiftAllocation.InsertNearestShiftDetails(empAutoID, shftDate, ddlID);
                            isInserted = true;
                        }
                    }
                }
            }
            if (isInserted)
            {
                string strScript = "<script language='javascript' type='text/javascript'>";
                strScript += "alert('" + rm.GetString("NearestShiftAllocation_SavedSuccessfully", ci) + "');";
                strScript += " </script>";
                ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", strScript, false);
                divNearestShift.Style.Add("display", "none");
                grdNearestShift.DataSource = "";
                grdNearestShift.Visible = false;
                hdnSelectRow.Value = "";
                btnSave.Visible = false;
            }
            else
            {
                return;
            }
            #endregion
        }
        else
        {
            string strScript = string.Empty;
            strScript = strScript + "<script language='javascript'>";
            strScript = strScript + "alert('" + rm.GetString("NearestShiftAllocation_SelectItem", ci) + "');";
            strScript = strScript + "</script>";
            Page.RegisterStartupScript("AlertPAdd996266", strScript);
        }
    }
    protected void GetNearestShiftDetails(string dtFromDate, string EmployeeId, int shift, string empName, int employeeCategory, int employeeType, string UserGroupName, string GradeLevel, int ParentId, int DesignationId, string Gender, Int64 EmpAutoID, string dtTodate)
    {
        DataSet dsNearShiftDetails = new DataSet();
        dsNearShiftDetails = rptEmp.GetNearestShiftDetails_ShiftAllocation(dtFromDate, EmployeeId, shift, empName, employeeCategory, employeeType, UserGroupName, GradeLevel, ParentId, DesignationId, Gender, EmpAutoID, dtTodate);
        if (dsNearShiftDetails.Tables.Count > 0)
        {
            if (dsNearShiftDetails.Tables[0].Rows.Count == 0)
            {
                string strMsg;
                grdNearestShift.DataSource = "";
                grdNearestShift.DataBind();
                btnSave.Visible = false;
                grdNearestShift.Visible = false;
                divNearestShift.Style.Add("display", "none");
                strMsg = "<script language='javascript'>";
                strMsg = strMsg + "alert('" + rm.GetString("Alert_Thereisnorecord", ci) + "');window.close();";
                strMsg = strMsg + "</script>";
                Page.RegisterStartupScript("Display", strMsg);
                return;
            }
            else
            {
                divNearestShift.Style.Add("display", "block");
                btnSave.Visible = true;
                grdNearestShift.Visible = true;
                grdNearestShift.DataSource = dsNearShiftDetails;
                grdNearestShift.DataBind();
                ViewState["Dataset_NearingShift"] = dsNearShiftDetails;
            }
        }
    }

    public int OverLappedValidation(DateTime dtmStartDate, int EmpID, int StartDateShiftId, int EndDateShiftId)
    {
        int intOverLapped = 0;
        intOverLapped = ConstructPermanentShiftAllocation(EmpID, dtmStartDate, dtmStartDate, StartDateShiftId, EndDateShiftId);
        return intOverLapped;
    }
    public int ConstructPermanentShiftAllocation(int EmployeeId, DateTime dtmStartDate, DateTime dtmToDate, int StartDateShiftId, int EndDateShiftId)
    {
        chkShiftAllocationExists = false;
        int PreviousDayShiftId = 0;
        int NextDayShiftId = 0;
        dtmStartDate = dtmStartDate.AddDays(-1);
        dtmToDate = dtmToDate.AddDays(1);
        DataSet dsPermanentTemporaryShift = new DataSet();
        dsPermanentTemporaryShift = objShiftAllocation.SelectPermanentTemporaryShiftDates(dtmStartDate, dtmToDate, EmployeeId.ToString());
        if (dsPermanentTemporaryShift.Tables[0].Rows.Count > 0)
        {
            if (dsPermanentTemporaryShift.Tables[0].Rows[0]["P_FromShiftId"] != null && dsPermanentTemporaryShift.Tables[0].Rows[0]["P_FromShiftId"].ToString() != string.Empty)
            {
                chkShiftAllocationExists = true;
                PreviousDayShiftId = Convert.ToInt32(dsPermanentTemporaryShift.Tables[0].Rows[0]["P_FromShiftId"]);
            }
            if (dsPermanentTemporaryShift.Tables[0].Rows[0]["P_ToShiftId"] != null && dsPermanentTemporaryShift.Tables[0].Rows[0]["P_ToShiftId"].ToString() != string.Empty)
            {
                chkShiftAllocationExists = true;
                NextDayShiftId = Convert.ToInt32(dsPermanentTemporaryShift.Tables[0].Rows[0]["P_ToShiftId"]);
            }
            if (dsPermanentTemporaryShift.Tables[0].Rows[0]["T_FromShiftId"] != null && dsPermanentTemporaryShift.Tables[0].Rows[0]["T_FromShiftId"].ToString() != string.Empty)
            {
                chkShiftAllocationExists = true;
                PreviousDayShiftId = Convert.ToInt32(dsPermanentTemporaryShift.Tables[0].Rows[0]["T_FromShiftId"]);
            }
            if (dsPermanentTemporaryShift.Tables[0].Rows[0]["T_ToShiftId"] != null && dsPermanentTemporaryShift.Tables[0].Rows[0]["T_ToShiftId"].ToString() != string.Empty)
            {
                chkShiftAllocationExists = true;
                NextDayShiftId = Convert.ToInt32(dsPermanentTemporaryShift.Tables[0].Rows[0]["T_ToShiftId"]);
            }
        }
        if (chkShiftAllocationExists == true)
        {
            int intOverLap = 0;
            int ShiftId1 = PreviousDayShiftId;
            int ShiftId2 = StartDateShiftId;
            dsOverLapping = objShiftPatternOverLap.CheckShiftOverLapping(ShiftId1, ShiftId2);
            if (dsOverLapping.Tables.Count > 0)
            {
                if (dsOverLapping.Tables[0].Rows.Count > 0)
                {
                    intOverLap = Convert.ToInt32(dsOverLapping.Tables[0].Rows[0]["ShiftOverLapping"]);
                }
            }
            if (intOverLap > 0)
            {
                return intOverLap;
            }
            dsOverLapping.Tables.Clear();
            ShiftId1 = EndDateShiftId;
            ShiftId2 = NextDayShiftId;
            dsOverLapping = objShiftPatternOverLap.CheckShiftOverLapping(ShiftId1, ShiftId2);
            if (dsOverLapping.Tables.Count > 0)
            {
                if (dsOverLapping.Tables[0].Rows.Count > 0)
                {
                    intOverLap = Convert.ToInt32(dsOverLapping.Tables[0].Rows[0]["ShiftOverLapping"]);
                }
            }
            if (intOverLap > 0)
            {
                return intOverLap;
            }
        }
        return 0;
    }
    /// <summary>

    protected void grdNearestShift_HtmlRowCreated(object sender, DevExpress.Web.ASPxGridViewTableRowEventArgs e)
    {
        if (e.RowType == DevExpress.Web.GridViewRowType.Data)
        {
            DataSet dsNearestShift = new DataSet();
            DropDownList ddlshift = (DropDownList)grdNearestShift.FindRowCellTemplateControl(e.VisibleIndex, null, "ddlshift");
            string lbl_Companyid = Convert.ToString(e.GetValue("CompanyId"));
            string lblNearestShiftid = Convert.ToString(e.GetValue("ShiftID"));
            if (ddlshift != null)
            {
                dsNearestShift = objShift.SelectShiftByCompany(Convert.ToInt32(lbl_Companyid));
                if (dsNearestShift != null)
                {
                    if (dsNearestShift.Tables.Count > 0)
                    {
                        if (dsNearestShift.Tables[0].Rows.Count > 0)
                        {
                            DataRow[] drow = dsNearestShift.Tables[0].Select("Shift_Name='No Shift'");
                            if (drow.Length > 0)
                            {
                                foreach (DataRow r in drow)
                                {
                                    r.Delete();
                                }
                                dsNearestShift.Tables[0].AcceptChanges();
                            }
                            ddlshift.DataSource = dsNearestShift;
                            ddlshift.DataTextField = "Shift_ShortName";
                            ddlshift.DataValueField = "Shift_Id";
                            ddlshift.DataBind();
                        }
                        dsNearestShift.Dispose();
                        foreach (ListItem item in ddlshift.Items)
                        {
                            item.Attributes.Add("title", item.Text);
                        }
                        if (lblNearestShiftid != null)
                        {
                            ddlshift.SelectedValue = Convert.ToString(lblNearestShiftid);
                        }
                    }
                }
            }
        }
    }
}