using System;
using System.Data;
using System.Globalization;
using System.IO;
using System.Resources;
using System.Text;
using System.Threading;
using System.Web.UI;
using System.Web.UI.WebControls;
/****************************************************************************************************************************
* Project Name    : TimeCheck                            Started Date  : 18-July-2007
* Module          : Permanent Shift Allocation           Last Modified : 29-Apr-2011
* Programmer      : Arun Vinoth & Kumuthini.L(ShiftPattern Allocation) ,Janakaraj (Shift Roaster Allocation)
* Modified by     : Sashma
****************************************************************************************************************************/
public partial class Transactions_TA_UI_Transaction_ShiftAllocationAdd : Base.BasePage
{
    #region "Variable Declaration"
    ResourceManager rm;
    CultureInfo ci;
    FileStream aFile;
    ShiftRoasterEventData objShiftRoaster = new ShiftRoasterEventData();
    ShiftAllocationEvendata objShiftAllocation = new ShiftAllocationEvendata();
    cls_Common objcls_Common = new cls_Common();
    ShiftPatternEventData objShiftPatternOverLap = new ShiftPatternEventData();
    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();
    DataTable dtMonthYear = new DataTable();
    StringBuilder strOverLappedEmployeeIds = new StringBuilder();
    Int32 gintUserId;
    string gstrIsValid = "T";
    string gstrDateFormat;
    string gstrUserGroupName = string.Empty;
    bool chkShiftAllocationExists;
    string strToDate = string.Empty;
    string strStartDate = string.Empty;
    int gintCompanyId;
    bool IsUnOverlappedEmployeeExists = false;
    string strAlert = string.Empty;
    int PatternDaysCount = 0;
    cls_Common objClassCommon = new cls_Common();
    DataSet dsYear = new DataSet();
    string strYearStartDate = string.Empty;
    string strYearEndDate = string.Empty;
    #endregion
    #region PageLoad events
    protected override void Page_Load(object sender, EventArgs e)
    {
        base.Page_Load(sender, e);
        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);
        fillLocation();
        gintUserId = Convert.ToInt32(Session["EmpAutoID"]);
        Hidden1.Value = Convert.ToString(Session["IDateFormat"]);
        dsYear = objClassCommon.GetYearsetting();
        grvImportDetails.Styles.CssFilePath = Convert.ToString(Session["GridCSS"]);
        if (dsYear.Tables[0].Rows.Count > 0)
        {
            strYearStartDate = (DateTime.Parse(dsYear.Tables[0].Rows[0]["FromDate"].ToString())).ToString(Session["MDateFormat"].ToString());
            strYearEndDate = (DateTime.Parse(dsYear.Tables[0].Rows[0]["ToDate"].ToString())).ToString(Session["MDateFormat"].ToString());
            dsYear.Dispose();
        }
        if (Convert.ToString(Session["ISSingleorMultiple"]) == "IsMultiple")
        {
            rbtnMultiple.Checked = true;
            rbtnSingle.Checked = false;
            Session["ISSingleorMultiple"] = "";
        }
        else if (Convert.ToString(Session["ISSingleorMultiple"]) == "IsSingle")
        {
            rbtnSingle.Checked = true;
            rbtnMultiple.Checked = false;
            Session["ISSingleorMultiple"] = "";
        }
        if (rbtnMultiple.Checked == true)
        {
            divMultiple.Style.Add("display", "block");
            divSingle.Style.Add("display", "none");
            lblcount.Text = "(3 No.)";
        }
        else
        {
            divMultiple.Style.Add("display", "none");
            divSingle.Style.Add("display", "block");
            lblcount.Text = "(4 No.)";
        }
        if (!Page.IsPostBack)
        {
            objcls_Common.menu("ShiftTransaction", "28");
            if (Session["CheckRecordsAddInPopUP"] != null)
            {
                Session["CheckRecordsAddInPopUP"] = null;
            }
            else
            {
                objShiftAllocation.DeleteEmpShiftDetails(gintUserId);
                Session["EmpDetails"] = null;
                Session["currentSession"] = null;
            }
            fillEmployee();
            if (Session["currentSession"] != null && Convert.ToString(Session["currentSession"]) != string.Empty)
            {
                org_levelsEventData getOrg = new org_levelsEventData();
                getOrg.GetOrgParentLevels_FromID(Convert.ToInt32(Session["currentSession"]));
                DataSet ds_getOrg = new DataSet();
                ds_getOrg = getOrg.GetOrgParentLevels();
                if (ds_getOrg != null)
                {
                    if (ds_getOrg.Tables[0].Rows.Count > 0)
                    {
                        int companyId = Convert.ToInt32(ds_getOrg.Tables[0].Rows[0]["LevelID"]);
                        gintCompanyId = companyId;
                        fillPatternddl(companyId);
                        fillShiftRoasterddl(companyId);
                        fillShiftddl(companyId);
                    }
                }
            }
        }
        string strSetAlert = "";
        strSetAlert = strSetAlert + "<script language='javascript'>";
        strSetAlert = strSetAlert + "SetAlertMessages('" + rm.GetString("Alert_SelectShiftPattern", ci) + "','" + rm.GetString("Alert_SelectStartday", ci) + "','" + rm.GetString("Alert_SelectShiftRoaster", ci) + "','" + rm.GetString("Alert_SelectShift", ci) + "','" + rm.GetString("Alert_SelectSheduleFrom", ci) + "','" + rm.GetString("Alert_SelectSheduleTo", ci) + "','" + rm.GetString("Alert_Are_you_sure_to_Save", ci) + "','" + rm.GetString("Alert_ClickAddButton", ci) + "','" + rm.GetString("Alert_EntertheEmployeeID", 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);
        lbl_Info.Text = string.Empty;
        if (Session["UserGroupName"] != null)
        {
            gstrUserGroupName = Convert.ToString(Session["UserGroupName"]);
        }
        int shiftPatternExists = 0;
        int shiftRosterExists = 0;
        int approvalSettingsPageExists = 0;
        shiftPatternExists = objcls_Common.CheckPageExistsInLicense(20);
        shiftRosterExists = objcls_Common.CheckPageExistsInLicense(69);
        //Checking grade module is available or not and changed the id value from 110 to 228
        approvalSettingsPageExists = objcls_Common.CheckPageExistsInLicense(228);
        if (shiftPatternExists == 0)
        {
            rbtnShifts.Checked = true;
            rbtnShiftPattern.Style.Add("display", "none");
        }
        if (shiftRosterExists == 0)
        {
            rbtnShifts.Checked = true;
            rbtnShiftRoaster.Style.Add("display", "none");
        }
        if (approvalSettingsPageExists == 1)
        {
            ShiftEvenData objShift = new ShiftEvenData();
            DataSet dsApprovalSettings = new DataSet();
            if (gintCompanyId > 0)
            {
                dsApprovalSettings = objShift.SelectApprovalSettings(gintCompanyId);
                if (dsApprovalSettings != null)
                {
                    if (dsApprovalSettings.Tables.Count > 0)
                    {
                        if (dsApprovalSettings.Tables[0].Rows.Count > 0)
                        {
                            if (Convert.ToBoolean(dsApprovalSettings.Tables[0].Rows[0]["Pattern"]) == false)
                            {
                                rbtnShifts.Checked = true;
                                rbtnShiftPattern.Style.Add("display", "none");
                            }
                            if (Convert.ToBoolean(dsApprovalSettings.Tables[0].Rows[0]["Roster"]) == false)
                            {
                                rbtnShifts.Checked = true;
                                rbtnShiftRoaster.Style.Add("display", "none");
                            }
                        }
                        else
                        {
                            base.Message(rm.GetString("Msg_ApprovalSettings", ci));
                            string strScripts = "<script language='javascript' type='text/javascript'>";
                            strScripts += "showPattern();";
                            strScripts += " </script>";
                            this.RegisterStartupScript("StatusTypeLoad", strScripts);
                            return;
                        }
                    }
                }
            }
        }
        string strScript = "<script language='javascript' type='text/javascript'>";
        strScript += "showPattern();";
        strScript += " </script>";
        this.RegisterStartupScript("StatusTypeLoad", strScript);
        //
        // TODO: Insert location value validation package Id
        //

        string temppackId = Convert.ToString(Session["packageID"]);
        if (Convert.ToString(Session["packageID"]) != "")
            if (Convert.ToInt32(Session["packageID"]) >= 158) /*Hotel Surguru -TimecheckV2.7*/
            {
                divShiftLocation.Style.Add("display", "");
                divShiftLocation.Style.Add("display", "block");
            }
            else
            {
                divShiftLocation.Style.Add("display", "");
                divShiftLocation.Style.Add("display", "none");
            }
    }
    #endregion
    #region User Procedures
    /// <summary>
    /// License checking
    /// </summary>
    private void CheckLicense()
    {
        DemoVersion objDemoVersion = new DemoVersion();
        string[] fileArr = Directory.GetFiles(Server.MapPath("../LicenseFile"), "*.lic");
        int arrCount = fileArr.Length;
        if (arrCount > 0)
        {
            string licenseFileName = Convert.ToString(fileArr[arrCount - 1]);
            FileStream licenseFileStream = new FileStream(licenseFileName, FileMode.Open);
            StreamReader licenseFileStreamReader = new StreamReader(licenseFileStream);
            string encryptedLicFileInfo = licenseFileStreamReader.ReadToEnd();
            licenseFileStreamReader.Close();
            licenseFileStream.Close();
            try
            {
                string decryptedLicFileInfo = Encryption.Decrypt(encryptedLicFileInfo, "");
            }
            catch
            {
                string strScript = "<script language='javascript' type='text/javascript'>";
                strScript += "alert('" + rm.GetString("Alert_Licenseinformationarenotcorrect", ci) + "');";
                strScript += "location.href='../Index.aspx';";
                strScript += " </script>";
                this.RegisterStartupScript(rm.GetString("Alert_AlertLicInfoNotCorrect", ci), strScript);
                return;
            }
        }
        else
        {
            bool demoContinue = false;
            demoContinue = objDemoVersion.CheckDVShiftAllocation(strStartDate, strToDate);
            if (demoContinue == true)
            {
            }
            else
            {
            }
        }
    }
    /// <summary>
    /// To fill selected employees in the pop up to the grid.
    /// </summary>
    private void fillEmployee()
    {
        Session["previousCompanyId"] = Session["currentSession"];
        ds = objShiftAllocation.SelectEmployeeDetails(gintUserId);
        if (ds != null && ds.Tables[0].Rows.Count > 0)
        {
            grv_Employees.DataSource = ds;
            grv_Employees.DataBind();
        }
        else
        {
            grv_Employees.DataSource = ds;
            grv_Employees.DataBind();
        }
    }
    /// <summary>
    /// TO fill the shift patterns in the drop down based on the company selected.
    /// </summary>
    /// <param name="companyId"></param>
    private void fillPatternddl(int companyId)
    {
        DataSet ds_Pattern = new DataSet();
        string usergroupname = string.Empty;
        ds_Pattern = objShiftAllocation.SelectShiftPatternForShiftAllocation(companyId);
        if (ds_Pattern.Tables[0].Rows.Count > 0)
        {
            ddl_Pattern.DataSource = ds_Pattern;
            ddl_Pattern.DataTextField = "Pattern_Name";
            ddl_Pattern.DataValueField = "ShiftPattern_Id";
            ddl_Pattern.DataBind();
        }
        ds_Pattern.Dispose();
        foreach (ListItem item in ddl_Pattern.Items)
        {
            item.Attributes.Add("title", item.Text);
        }
    }
    /// <summary>
    /// To fill the various shifts in the drop down based on the company selected.
    /// </summary>
    /// <param name="companyId"></param>
    private void fillShiftddl(int companyId)
    {
        ShiftEvenData objShift = new ShiftEvenData();
        DataSet ds = new DataSet();
        ds = objShift.SelectShiftByCompany(companyId);
        if (ds.Tables[0].Rows.Count > 0)
        {
            ddlShifts.DataSource = ds;
            ddlShifts.DataTextField = "Shift_ShortName";
            ddlShifts.DataValueField = "Shift_Id";
            ddlShifts.DataBind();
        }
        ddlShifts.Dispose();
        foreach (ListItem item in ddlShifts.Items)
        {
            item.Attributes.Add("title", item.Text);
        }
    }
    /// <summary>
    /// To fill the various shifts in the drop down based on the company selected.
    /// </summary>
    /// <param name="companyId"></param>
    private void fillLocation()
    {
        ShiftEvenData objShift = new ShiftEvenData();
        DataSet ds = new DataSet();
        ds = objShift.SelectLocation();
        if (ds.Tables[0].Rows.Count > 0)
        {
            ddlLocation.DataSource = ds;
            ddlLocation.DataTextField = "LocationName";
            ddlLocation.DataValueField = "LocationId";
            ddlLocation.DataBind();
        }
        ddlLocation.Dispose();
        foreach (ListItem item in ddlLocation.Items)
        {
            item.Attributes.Add("title", item.Text);
        }
    }
    /// <summary>
    /// To fill the start day in the drop down and show the pattern in the label 
    /// based on the shift pattern selected.
    /// </summary>
    /// <param name="PatternID"></param>
    private void fillStartDayddl(int PatternID)
    {
        ds_ShiftAllocdetails = objShiftAllocation.SelectShiftPattern_ShiftAllocDetails(PatternID);
        foreach (DataRow drRow in ds_ShiftAllocdetails.Tables[0].Rows)
        {
            switch (Convert.ToString(drRow["name"]))
            {
                case "Off":
                    drRow["name"] = rm.GetString("lbl_Off", ci);
                    break;
            }
        }
        int Days = ds_ShiftAllocdetails.Tables[0].Rows.Count;
        ddl_StartDay.Items.Clear();
        ListItem liSelect = new ListItem();
        liSelect.Value = "-Select-";
        liSelect.Text = rm.GetString("Select", ci);
        ddl_StartDay.Items.Insert(0, liSelect);
        for (int i = 1; i <= Days; i++)
        {
            ddl_StartDay.Items.Add(Convert.ToString(i));
        }
        string Pattern = string.Empty;
        DataTable dt_Pattern = new DataTable();
        dt_Pattern = ds_ShiftAllocdetails.Tables[0];
        foreach (DataRow dr_Pattern in dt_Pattern.Rows)
        {
            Pattern += " " + Convert.ToString(dr_Pattern["name"]);
        }
        lbl_Pattern.Text = Pattern;
    }
    /// <summary>
    /// To get the pattern for simple shift allocation.
    /// </summary>
    /// <returns></returns>
    private int[] ShiftPatternSequence()
    {
        int[] Pattern = new int[31];
        for (int i = 0; i < 7; i++)
        {
            if (lstWeeklyOffDays.Items[i].Selected)
            {
                Pattern[i] = -1;
            }
            else
            {
                Pattern[i] = Convert.ToInt32(ddlShifts.SelectedValue);
            }
        }
        return Pattern;
    }
    /// <summary>
    /// To get the start day based on the shift start date selected.
    /// </summary>
    /// <returns></returns>
    private int getStartDay()
    {
        string strWeekDayName;
        string strStartDate = objcls_Common.DateConvertion(gstrDateFormat, txt_StartDate.Text.Trim());
        DateTime dtFromDate = DateTime.Parse(strStartDate);
        strWeekDayName = Convert.ToString(dtFromDate.DayOfWeek);
        int intWeekDay = 0;
        switch (strWeekDayName)
        {
            case "Monday":
                intWeekDay = 1;
                break;
            case "Tuesday":
                intWeekDay = 2;
                break;
            case "Wednesday":
                intWeekDay = 3;
                break;
            case "Thursday":
                intWeekDay = 4;
                break;
            case "Friday":
                intWeekDay = 5;
                break;
            case "Saturday":
                intWeekDay = 6;
                break;
            case "Sunday":
                intWeekDay = 7;
                break;
        }
        return (intWeekDay);
    }
    /// <summary>
    /// To validate start data and To restrict users other than super admin or 
    /// user having special rights to allocate shift for back date
    /// </summary>
    /// <param name="s"></param>
    /// <param name="e"></param>
    public void CheckStartDate(object s, ServerValidateEventArgs e)
    {
        if (gstrUserGroupName == "SuperAdmin" || Convert.ToString(Session["HasSpecialRights"]) == "True")
        {
            e.IsValid = true;
        }
        else
        {
            if (txt_StartDate.Text != string.Empty)
            {
                if (txt_StartDate.Text.Length >= 10)
                {
                    string strStartDate = string.Empty;
                    gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
                    strStartDate = objcls_Common.DateConvertion(gstrDateFormat, txt_StartDate.Text);
                    DateTime dtCurrent = DateTime.Now;
                    DateTime dtStartDate = DateTime.Parse(strStartDate);
                    TimeSpan diff = dtCurrent.Subtract(dtStartDate);
                    int day = diff.Days;
                    if (day <= 0)
                        e.IsValid = true;
                    else
                    {
                        strAlert = string.Empty;
                        strAlert = "alert('" + rm.GetString("Validator_ShiftAllocation_ScheduleFrom", ci) + "')";
                        ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", strAlert, true);
                        e.IsValid = false;
                    }
                }
                else
                {
                    e.IsValid = true;
                }
            }
            else
            {
                e.IsValid = true;
            }
        }
    }
    /// <summary>
    /// To validate end data and To restrict users other than super admin or 
    /// user having special rights to allocate shift for back date
    /// </summary>
    /// <param name="s"></param>
    /// <param name="e"></param>
    public void CheckToDate(object s, ServerValidateEventArgs e)
    {
        if (gstrUserGroupName == "SuperAdmin" || Convert.ToString(Session["HasSpecialRights"]) == "True")
        {
            e.IsValid = true;
        }
        else
        {
            if (txt_ToDate.Text != string.Empty)
            {
                if (txt_ToDate.Text.Length >= 10)
                {
                    string strToDate = string.Empty;
                    gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
                    strToDate = objcls_Common.DateConvertion(gstrDateFormat, txt_ToDate.Text);
                    DateTime dtCurrent = DateTime.Now;
                    DateTime dtToDate = DateTime.Parse(strToDate);
                    TimeSpan diff = dtCurrent.Subtract(dtToDate);
                    int day = diff.Days;
                    if (day <= 0)
                        e.IsValid = true;
                    else
                    {
                        strAlert = string.Empty;
                        strAlert = "alert('" + rm.GetString("Validator_ShiftAllocation_ScheduleTo", ci) + "')";
                        ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", strAlert, true);
                        e.IsValid = false;
                    }
                }
                else
                {
                    e.IsValid = true;
                }
            }
            else
            {
                e.IsValid = true;
            }
        }
    }
    private DataSet ImportShiftData(FileInfo fileInfo)
    {
        string strLine;
        string strScript = String.Empty;
        string[] strArray;
        char[] charArray = new char[] { ',' };
        string[] strColumnName = { "Employee_Code_Id", "Employee_Name", "Company_Name", "Year", "Mon", "Day1", "Day2", "Day3", "Day4", "Day5", "Day6", "Day7", "Day8", "Day9", "Day10", "Day11", "Day12", "Day13", "Day14", "Day15", "Day16", "Day17", "Day18", "Day19", "Day20", "Day21", "Day22", "Day23", "Day24", "Day25", "Day26", "Day27", "Day28", "Day29", "Day30", "Day31" };
        DataSet dsShift = new DataSet("Dst_ShiftAlloc");
        DataTable dtShift = dsShift.Tables.Add("Tbl_ShiftAlloc");
        foreach (string str in strColumnName)
        {
            dtShift.Columns.Add(str);
        }
        aFile = new FileStream(fileInfo.FullName.ToString(), FileMode.Open);
        StreamReader sr = new StreamReader(aFile);
        strLine = sr.ReadLine();
        strArray = strLine.Split(charArray);
        if (strArray.Length != dtShift.Columns.Count)
        {
            strScript = "<script language='javascript'>";
            strScript = strScript + "ModeOfAllocation();";
            strScript = strScript + "alert('" + rm.GetString("Alert_ErrorinShiftImporting", ci) + "');";
            strScript = strScript + "</script>";
            Page.RegisterStartupScript("Alert", strScript);
            return null;
        }
        strLine = sr.ReadLine();
        strArray = null;
        while (strLine != null)
        {
            strArray = strLine.Split(charArray);
            dtShift.Rows.Add(strArray);
            strLine = sr.ReadLine();
        }
        string strWeekOff = string.Empty;
        //for (int i = 0; i < lstWeeklyOffDays.Items.Count; i++)
        //{
        //    strWeekOff = (lstWeeklyOffDays.Items[i].Selected ? ((strWeekOff.Trim() == string.Empty) ? lstWeeklyOffDays.Items[i].Value : strWeekOff + "," + lstWeeklyOffDays.Items[i].Value) : strWeekOff);
        //    lstWeeklyOffDays.Items[i].Selected = false;
        //}
        if (ChbMonday.Checked)
            strWeekOff = strWeekOff + "2,";
        if (ChbTuesday.Checked)
            strWeekOff = strWeekOff + "3,";
        if (ChbWednesday.Checked)
            strWeekOff = strWeekOff + "4,";
        if (ChbThuday.Checked)
            strWeekOff = strWeekOff + "5,";
        if (ChbFriday.Checked)
            strWeekOff = strWeekOff + "6,";
        if (ChbSaturday.Checked)
            strWeekOff = strWeekOff + "7,";
        if (ChbSunday.Checked)
            strWeekOff = strWeekOff + "1";
        StringWriter strShiftAlloc = new StringWriter();
        dsShift.WriteXml(strShiftAlloc);
        string strAlloc = Convert.ToString(strShiftAlloc);
        aFile.Dispose();
        return objShiftAllocation.EmployeeShiftAllcationImport(strAlloc, strWeekOff, (chkSkip.Checked));
    }
    /// <summary>
    /// Shift allocation based on the pattern
    /// Inserts and update the shift details in the shift allocation table.
    /// Reprocesses the datas for the duration selected from processed data,clockdetails,raw data and manual time entry
    /// </summary>
    /// <param name="pattern"></param>
    /// <param name="dtmStartDate"></param>
    /// <param name="dtmToDate"></param>
    /// <param name="intStartDay"></param>
    /// <param name="PatternDaysCount"></param>
    private void ShiftAllocation(int[] pattern, DateTime dtmStartDate, DateTime dtmToDate, int intStartDay, int PatternDaysCount)
    {
        try
        {
            StringWriter strWriteXML = new StringWriter();
            dtEmpDetails.DefaultView.RowFilter = "OverLapped=false";
            dtEmpDetails.DefaultView.ToTable().WriteXml(strWriteXML);
            dtMonthYear.TableName = "Table";
            dtMonthYear.Columns.Add("Month", typeof(int));
            dtMonthYear.Columns.Add("Year", typeof(int));
            if (dtmStartDate.Year == dtmToDate.Year)
            {
                FillMonthYearForShiftAllocation(dtmStartDate.Month, dtmToDate.Month, dtmStartDate.Year);
            }
            else
            {
                int startYear = dtmStartDate.Year;
                int endYear = dtmToDate.Year;
                int Year = 0;
                for (Year = startYear; Year <= endYear; Year++)
                {
                    if (Year == startYear)
                    {
                        FillMonthYearForShiftAllocation(dtmStartDate.Month, 12, Year);
                    }
                    else if (Year == endYear)
                    {
                        FillMonthYearForShiftAllocation(1, dtmToDate.Month, Year);
                    }
                    else
                    {
                        FillMonthYearForShiftAllocation(1, 12, Year);
                    }
                }
            }
            foreach (DataRow drRow in dtMonthYear.Rows)
            {
                string strDateShift = Convert.ToInt32(drRow["Month"]) + "/1/" + Convert.ToInt32(drRow["Year"]);
                objShiftAllocation.InsertShiftAllocation(Convert.ToInt32(drRow["Year"]), Convert.ToInt32(drRow["Month"]), gintUserId, DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss tt"), strDateShift, strWriteXML.ToString());
            }
        }
        catch (Exception ex)
        {
            Message(ex.ToString());
        }
        try
        {
            if (IsUnOverlappedEmployeeExists == true)
            {
                DataTable dtShiftIDs = new DataTable();
                int intMonth = 0, intYear = 0;
                int p = 0;
                if (rbtnShiftRoaster.Checked == true)
                {
                    p = 0;
                }
                else
                {
                    p = intStartDay - 1;
                }
                string strUpdate = "UPDATE TA_Tbl_PermanentShiftAllocation SET ";
                for (DateTime j = dtmStartDate; j <= dtmToDate; j = j.AddDays(1))
                {
                    if ((intMonth != j.Month) || (intYear != j.Year))
                    {
                        if ((intMonth != 0) || (intYear != 0))
                        {
                            strUpdate += " WHERE EmployeeId in (select EmpID from TA_Tbl_TempShiftAllocation where EmployeeId not in ('" + strOverLappedEmployeeIds + "') and LoginEmployeeId=" + Convert.ToString(Session["EmpAutoID"]) + ") AND Year = " + intYear + " AND Month = " + intMonth + "";
                            objShiftAllocation.UpdateShiftAllocation(strUpdate);
                            strUpdate = "UPDATE TA_Tbl_PermanentShiftAllocation SET ";
                        }
                    }
                    intMonth = j.Month;
                    intYear = j.Year;
                    if (strUpdate == "UPDATE TA_Tbl_PermanentShiftAllocation SET ")
                    {
                        strUpdate += "Day" + j.Day + "Shift = " + pattern[p];
                    }
                    else
                    {
                        strUpdate += ",Day" + j.Day + "Shift = " + pattern[p];
                    }
                    if (j == dtmToDate)
                    {
                        strUpdate += " WHERE EmployeeId in (select EmpID from TA_Tbl_TempShiftAllocation where EmployeeId not in ('" + strOverLappedEmployeeIds + "') and LoginEmployeeId=" + Convert.ToString(Session["EmpAutoID"]) + ") AND Year = " + intYear + " AND Month = " + intMonth + "";
                    }
                    if (p < (PatternDaysCount - 1))
                    {
                        p += 1;
                    }
                    else if (p >= (PatternDaysCount - 1))
                    {
                        p = 0;
                    }
                }
                objShiftAllocation.UpdateShiftAllocation(strUpdate);
                objShiftAllocation.ShiftAllocationReprocess_ProcessedData(dtmStartDate, dtmToDate, Convert.ToString(Session["EmpAutoID"]));
                objShiftAllocation.ShiftAllocationReprocess_ClockDetails(dtmStartDate, dtmToDate, Convert.ToString(Session["EmpAutoID"]));
                objShiftAllocation.ShiftAllocationReprocess_ManualEntry(dtmStartDate, dtmToDate, Convert.ToString(Session["EmpAutoID"]));
                objShiftAllocation.ShiftAllocationReprocess_RawData(dtmStartDate, dtmToDate, Convert.ToString(Session["EmpAutoID"]));
            }
        }
        catch (Exception ex)
        {
            Message(ex.ToString());
        }
        //location detail update hotel surguru
        if (Convert.ToString(Session["packageID"]) != "")
        {
            if (Convert.ToInt32(Session["packageID"]) >= 158) /*Hotel Surguru -TimecheckV2.7*/
            {
                try
                {
                    if (ddlLocation.SelectedValue != "-Select-")
                    {
                        int LocationId = 0;
                        LocationId = Convert.ToInt32(ddlLocation.SelectedValue);
                        DateTime Fromdate = dtmStartDate;
                        DateTime ToDate = dtmToDate;
                        while (Fromdate <= ToDate)
                        {
                            objShiftAllocation.UpdateShiftAddLocation(LocationId, Fromdate, gintUserId);
                            Fromdate = Fromdate.AddDays(1);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Message(ex.ToString());
                }
            }
        }
        objShiftAllocation.DeleteEmpShiftDetails(gintUserId);
        Session["EmpDetails"] = null;
    }
    /// <summary>
    /// To fill the month and year in the datatable for shift allocation
    /// </summary>
    /// <param name="StartMonth"></param>
    /// <param name="EndMonth"></param>
    /// <param name="Year"></param>
    private void FillMonthYearForShiftAllocation(int StartMonth, int EndMonth, int Year)
    {
        int exitLoop = 1;
        while (exitLoop == 1)
        {
            DataRow drData;
            drData = dtMonthYear.NewRow();
            drData["Month"] = StartMonth;
            drData["Year"] = Year;
            dtMonthYear.Rows.Add(drData);
            StartMonth = StartMonth + 1;
            if (StartMonth > EndMonth)
            {
                exitLoop = 0;
            }
        }
    }
    /// <summary>
    /// To fill the shift roasters in the drop down based on the company.
    /// </summary>
    /// <param name="companyId"></param>
    private void fillShiftRoasterddl(int companyId)
    {
        DataSet ds_ShiftRoaster = new DataSet();
        try
        {
            ds_ShiftRoaster = objShiftAllocation.SelectShiftRoasterForShiftAllocation(companyId);
            ddlShiftRoaster.DataTextField = "ShiftRoaster_Name";
            ddlShiftRoaster.DataValueField = "ShiftRoaster_Id";
            ddlShiftRoaster.DataSource = ds_ShiftRoaster;
            ddlShiftRoaster.DataBind();
            ds_ShiftRoaster.Dispose();
            foreach (ListItem item in ddlShiftRoaster.Items)
            {
                item.Attributes.Add("title", item.Text);
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    /// <summary>
    /// Getting Information from resource file and display it in label
    /// </summary>
    /// <param name="ci"></param>
    private void LoadStrings(CultureInfo ci)
    {
        lblImportNote.Text = rm.GetString("Field_ImportantNote", ci);
        lbl_Header.Text = rm.GetString("Menu_Transactions_ShiftAllocation", ci);
        lblEmployeeCode.Text = rm.GetString("email_EmployeeId", ci);
        lbl_ActualPattern.Text = rm.GetString("ShiftAllocation_ActualPattern", ci);
        lbl_ScheduleFrom.Text = rm.GetString("ShiftAllocation_ScheduleFrom", ci);
        lbl_ScheduleTo.Text = rm.GetString("ShiftAllocation_ScheduleTo", ci);
        lbl_ShiftPattern.Text = rm.GetString("Masters_ShiftPattern", ci);
        lbl_StartDay.Text = rm.GetString("ShiftAllocation_StartDay", ci);
        lbl_SelectedEmployees.Text = rm.GetString("ShiftAllocation_SelectedEmployees", ci);
        lbl_IndicatesMandatoryFields.Text = rm.GetString("IndicatesMandatoryFields", ci);
        CustomValidator1.ErrorMessage = rm.GetString("Validator_ShiftAllocation_ScheduleFrom", ci);
        CustomValidator3.ErrorMessage = rm.GetString("Validator_ShiftAllocation_ScheduleTo", ci);
        lblShiftRoaster.Text = rm.GetString("UserGroups_ShiftRoaster", ci);
        btn_Add.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Add", ci);
        btn_Save.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Save", ci);
        btn_Cancel.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Back", ci);
        btn_ShiftAllocationView.Text = "&nbsp;&nbsp;" + rm.GetString("btn_ShiftAllocationView", ci);
        rbtnShiftPattern.Text = rm.GetString("Masters_ShiftPattern", ci);
        rbtnShiftRoaster.Text = rm.GetString("Masters_ShiftRoster", ci);
        rbtnShifts.Text = rm.GetString("Menu_Reports_Shift", ci);
        grv_Employees.Columns[2].HeaderText = rm.GetString("email_EmployeeId", ci);
        grv_Employees.Columns[3].HeaderText = rm.GetString("email_EmployeeName", ci);
        lblShifts.Text = rm.GetString("Menu_Reports_Shift", ci);
        Label1.Text = lblWeeklyOffDays.Text = rm.GetString("ShiftAllocationWeeklyOffDays", ci);
        lstWeeklyOffDays.Items[0].Text = rm.GetString("Monday", ci);
        lstWeeklyOffDays.Items[1].Text = rm.GetString("Tuesday", ci);
        lstWeeklyOffDays.Items[2].Text = rm.GetString("Wednesday", ci);
        lstWeeklyOffDays.Items[3].Text = rm.GetString("Thursday", ci);
        lstWeeklyOffDays.Items[4].Text = rm.GetString("Friday", ci);
        lstWeeklyOffDays.Items[5].Text = rm.GetString("Saturday", ci);
        lstWeeklyOffDays.Items[6].Text = rm.GetString("Sunday", ci);
        ddlShifts.Items[0].Text = rm.GetString("Select", ci);
        ddl_Pattern.Items[0].Text = rm.GetString("Select", ci);
        ddl_StartDay.Items[0].Text = rm.GetString("Select", ci);
        ddlShiftRoaster.Items[0].Text = rm.GetString("Select", ci);
        lblLoading.Text = rm.GetString("ProgressBarText", ci);
        lblDataView.Text = rm.GetString("lblDataView", ci);
        lbl_Mandatory.Text = rm.GetString("IndicatesMandatoryFields", ci);
        lbl_Mandatory1.Text = rm.GetString("IndicatesMandatoryFields", ci);
        lblSelectEmployee.Text = rm.GetString("Shift_SelectEmployee", ci);
        btn_Upload.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Upload", ci);
        btn_Cancel.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Back", ci);
        btn_Template.Text = "&nbsp;&nbsp;" + rm.GetString("strDownloadTemplate", ci);
        lblWeeklyOffDays.Text = rm.GetString("ShiftAllocationWeeklyOffDays", ci);
        lblImportFilePath.Text = rm.GetString("SelectFileImport", ci);
        lblMode.Text = rm.GetString("lbl_ModeofAllocation", ci);
        rbtnManual.Text = rm.GetString("rbtnManual", ci);
        rbtnImport.Text = rm.GetString("rbtnImport", ci);
        ChbMonday.Text = rm.GetString("Monday", ci);
        ChbTuesday.Text = rm.GetString("Tuesday", ci);
        ChbWednesday.Text = rm.GetString("Wednesday", ci);
        ChbThuday.Text = rm.GetString("Thursday", ci);
        ChbFriday.Text = rm.GetString("Friday", ci);
        ChbSaturday.Text = rm.GetString("Saturday", ci);
        ChbSunday.Text = rm.GetString("Sunday", ci);
        lblUnProcess.Text = rm.GetString("lbl_UnProcessedRecord", ci);
        grvImportDetails.Columns[0].Caption = rm.GetString("email_EmployeeId", ci);
        grvImportDetails.Columns[1].Caption = rm.GetString("PayrollProcess_Year", ci);
        grvImportDetails.Columns[2].Caption = rm.GetString("PayrollProcess_Month", ci);
        grvImportDetails.Columns[3].Caption = rm.GetString("TerminalDataType_RawDataFormat", ci);
        lblAllocationType.Text = rm.GetString("lbl_EmpSelectMode", ci);
        rbtnSingle.Text = rm.GetString("rbtn_EmployeeMaster_Single", ci);
        rbtnMultiple.Text = rm.GetString("rpt_Multiple", ci);
        lblEmployeeCode.Text = rm.GetString("email_EmployeeId", ci);
    }
    /// <summary>
    /// To get the previous date adn next date shift Id from both permament and temporary shift allocation table
    /// TO check whether overlap occurs based on the start data and end date.
    /// </summary>
    /// <param name="EmployeeId"></param>
    /// <param name="dtmStartDate"></param>
    /// <param name="dtmToDate"></param>
    /// <param name="StartDateShiftId"></param>
    /// <param name="EndDateShiftId"></param>
    /// <returns></returns>
    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, Convert.ToString(EmployeeId));
        if (dsPermanentTemporaryShift.Tables[0].Rows.Count > 0)
        {
            if (dsPermanentTemporaryShift.Tables[0].Rows[0]["P_FromShiftId"] != null && Convert.ToString(dsPermanentTemporaryShift.Tables[0].Rows[0]["P_FromShiftId"]) != string.Empty)
            {
                chkShiftAllocationExists = true;
                PreviousDayShiftId = Convert.ToInt32(dsPermanentTemporaryShift.Tables[0].Rows[0]["P_FromShiftId"]);
            }
            if (dsPermanentTemporaryShift.Tables[0].Rows[0]["P_ToShiftId"] != null && Convert.ToString(dsPermanentTemporaryShift.Tables[0].Rows[0]["P_ToShiftId"]) != string.Empty)
            {
                chkShiftAllocationExists = true;
                NextDayShiftId = Convert.ToInt32(dsPermanentTemporaryShift.Tables[0].Rows[0]["P_ToShiftId"]);
            }
            if (dsPermanentTemporaryShift.Tables[0].Rows[0]["T_FromShiftId"] != null && Convert.ToString(dsPermanentTemporaryShift.Tables[0].Rows[0]["T_FromShiftId"]) != string.Empty)
            {
                chkShiftAllocationExists = true;
                PreviousDayShiftId = Convert.ToInt32(dsPermanentTemporaryShift.Tables[0].Rows[0]["T_FromShiftId"]);
            }
            if (dsPermanentTemporaryShift.Tables[0].Rows[0]["T_ToShiftId"] != null && Convert.ToString(dsPermanentTemporaryShift.Tables[0].Rows[0]["T_ToShiftId"]) != 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>
    /// check whether any shift overlapping occures
    /// </summary>
    /// <param name="dtmStartDate"></param>
    /// <param name="dtmToDate"></param>
    /// <param name="intStartDay"></param>
    /// <returns></returns>
    public int[] OverLappedValidation(DateTime dtmStartDate, DateTime dtmToDate, int intStartDay)
    {
        int StartDateShiftId = 0;
        int EndDateShiftId = 0;
        int p = 0;
        int[] Pattern = new int[310];
        int intOverLapped = 0;
        DataColumn dcEmployeeId = new DataColumn("OverLapped", System.Type.GetType("System.Boolean"));
        dtEmpDetails.Columns.Add(dcEmployeeId);
        if (rbtnShiftPattern.Checked == true || rbtnShifts.Checked == true)
        {
            DataTable dtShiftIDs = new DataTable();
            PatternDaysCount = 7;
            if (rbtnShiftPattern.Checked == true)
            {
                ds_ShiftAllocdetails = objShiftAllocation.SelectShiftPattern_ShiftAllocDetails(int.Parse(ddl_Pattern.SelectedValue));
                dtShiftIDs = ds_ShiftAllocdetails.Tables[0];
                PatternDaysCount = dtShiftIDs.Rows.Count;
                for (int i = 0; i < PatternDaysCount; i++)
                {
                    Pattern[i] = int.Parse(Convert.ToString(dtShiftIDs.Rows[i]["id"]));
                }
            }
            else if (rbtnShifts.Checked == true)
            {
                Pattern = ShiftPatternSequence();
            }
            p = intStartDay - 1;
        }
        else if (rbtnShiftRoaster.Checked == true)
        {
            int l = 0;
            // Fetching ShiftRoaster Details, Pattern Details and getting ShiftIDs in an array
            DataSet ds_ShiftRoaster = objShiftRoaster.SelectShiftRoasterById(Convert.ToInt32(ddlShiftRoaster.SelectedValue));
            foreach (DataRow drShiftRoster in ds_ShiftRoaster.Tables[0].Rows)
            {
                int intNoOfPatterns = int.Parse(Convert.ToString(drShiftRoster["NumberOfPatterns"]));
                string strPatternName = string.Empty;
                for (int m = 1; m <= intNoOfPatterns; m++)
                {
                    strPatternName = "Pattern" + m;
                    ds_ShiftPattern = objShiftAllocation.Shiftpattern(Convert.ToInt32(drShiftRoster[strPatternName]));
                    foreach (DataRow drShiftPattern in ds_ShiftPattern.Tables[0].Rows)
                    {
                        int intPatternDays = int.Parse(Convert.ToString(drShiftPattern["Shift_days"]));
                        string strShiftName = string.Empty;
                        PatternDaysCount = PatternDaysCount + intPatternDays;
                        for (int n = 1; n <= intPatternDays; n++)
                        {
                            strShiftName = "Day" + n + "_Shift";
                            Pattern[l] = Convert.ToInt32(drShiftPattern[strShiftName]);
                            if ((l + 1) != PatternDaysCount)
                            {
                                l = l + 1;
                            }
                        }
                    }
                    l = l + 1;
                }
            }
        }
        for (DateTime j = dtmStartDate; j <= dtmToDate; j = j.AddDays(1))
        {
            if (j == dtmStartDate)
            {
                StartDateShiftId = Pattern[p];
            }
            if (j == dtmToDate)
            {
                EndDateShiftId = Pattern[p];
            }
            if (p < (PatternDaysCount - 1))
            {
                p += 1;
            }
            else if (p >= (PatternDaysCount - 1))
            {
                p = 0;
            }
        }
        //Each employee check overlapping
        foreach (DataRow dRow in dtEmpDetails.Rows)
        {
            intOverLapped = ConstructPermanentShiftAllocation(Convert.ToInt32(dRow["EmpID"]), dtmStartDate, dtmToDate, StartDateShiftId, EndDateShiftId);
            if (intOverLapped > 0)
            {
                dRow["OverLapped"] = "True";
                if (Convert.ToString(strOverLappedEmployeeIds) == string.Empty)
                {
                    strOverLappedEmployeeIds.Append(Convert.ToString(dRow["EmployeeId"]));
                }
                else
                {
                    strOverLappedEmployeeIds.Append("," + Convert.ToString(dRow["EmployeeId"]));
                }
            }
            else
            {
                dRow["OverLapped"] = "False";
            }
        }
        return Pattern;
    }
    #endregion
    #region button events
    /// <summary>
    /// To validate and save the shift allocation details
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btn_Save_Click(object sender, EventArgs e)
    {
        lblError.Text = string.Empty;
        TimeSpan ts = new TimeSpan();
        gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
        strStartDate = objcls_Common.DateConvertion(gstrDateFormat, txt_StartDate.Text);
        strToDate = objcls_Common.DateConvertion(gstrDateFormat, txt_ToDate.Text);
        strYearStartDate = objcls_Common.DateConvertion(gstrDateFormat, strYearStartDate);
        strYearEndDate = objcls_Common.DateConvertion(gstrDateFormat, strYearEndDate);
        CheckLicense();
        int intStartDay = 0;
        DateTime dtLastyearEndDate = new DateTime();
        dtLastyearEndDate = Convert.ToDateTime(strYearStartDate).AddDays(-1);
        TimeSpan tsDifferenceDays = dtLastyearEndDate.Subtract(Convert.ToDateTime(strStartDate));
        int intdiffDays = tsDifferenceDays.Days;
        if (intdiffDays >= 0)
        {
            strAlert = string.Empty;
            strAlert = "alert('" + rm.GetString("Alert_ShiftallocationisnotallowedforPreviousyearsetting", ci) + "')";
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", strAlert, true);
            return;
        }
        if (rbtnShiftPattern.Checked == true)
        {
            ts = DateTime.Parse(strToDate).Subtract(DateTime.Parse(strStartDate));
            //During the support of iffco changed the value from 730 to 2500
            if (ts.Days > 2500)
            {
                strAlert = string.Empty;
                strAlert = "alert('" + rm.GetString("Msg_Shiftpatterncannotbeappliedformorethanyears", ci) + "')";
                ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", strAlert, true);
                return;
            }
            if (grv_Employees.Rows.Count == 0)
            {
                lblError.Text = rm.GetString("Alert_ClickAddButtontoselectEmployeesforShiftAllocation", ci);
                btn_Add.Focus();
                gstrIsValid = "F";
                return;
            }
            else if (txt_StartDate.Text == "")
            {
                lblError.Text = rm.GetString("Alert_ScheduleFromcannotbeEmpty", ci);
                gstrIsValid = "F";
                return;
            }
            else if (txt_ToDate.Text == "")
            {
                lblError.Text = rm.GetString("Alert_ScheduleFromcannotbeEmpty", ci);
                gstrIsValid = "F";
                return;
            }
            else if (txt_StartDate.Text.Length < 10)
            {
                lblError.Text = rm.GetString("Alert_InvalidScheduleFromDate", ci);
                gstrIsValid = "F";
                return;
            }
            else if (txt_ToDate.Text.Length < 10)
            {
                lblError.Text = rm.GetString("Alert_InvalidScheduleToDate", ci);
                gstrIsValid = "F";
                return;
            }
            intStartDay = int.Parse(ddl_StartDay.SelectedValue);
        }
        else if (rbtnShiftRoaster.Checked == true)
        {
            ts = DateTime.Parse(strToDate).Subtract(DateTime.Parse(strStartDate));
            //During the support of iffco changed the value from 730 to 2500
            if (ts.Days > 2500)
            {
                strAlert = string.Empty;
                strAlert = "alert('" + rm.GetString("Msg_Shiftrostercannotbeappliedformorethanyears", ci) + "')";
                ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", strAlert, true);
                return;
            }
            if (grv_Employees.Rows.Count == 0)
            {
                lblError.Text = rm.GetString("Alert_ClickAddButtontoselectEmployeesforShiftAllocation", ci);
                btn_Add.Focus();
                gstrIsValid = "F";
                return;
            }
            else if (txt_StartDate.Text == "")
            {
                lblError.Text = rm.GetString("Alert_ScheduleFromcannotbeEmpty", ci);
                gstrIsValid = "F";
                return;
            }
            else if (txt_ToDate.Text == "")
            {
                lblError.Text = rm.GetString("Alert_ScheduleFromcannotbeEmpty", ci);
                gstrIsValid = "F";
                return;
            }
            else if (txt_StartDate.Text.Length < 10)
            {
                lblError.Text = rm.GetString("Alert_InvalidScheduleFromDate", ci);
                gstrIsValid = "F";
                return;
            }
            else if (txt_ToDate.Text.Length < 10)
            {
                lblError.Text = rm.GetString("Alert_InvalidScheduleToDate", ci);
                gstrIsValid = "F";
                return;
            }
        }
        else if (rbtnShifts.Checked == true)
        {
            ts = DateTime.Parse(strToDate).Subtract(DateTime.Parse(strStartDate));
            //During the support of iffco changed the value from 730 to 2500
            if (ts.Days > 2500)
            {
                strAlert = string.Empty;
                strAlert = "alert('" + rm.GetString("Alert_Shiftcannotbeallocatedformorethanyears", ci) + "')";
                ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", strAlert, true);
                return;
            }
            if (grv_Employees.Rows.Count == 0)
            {
                lblError.Text = rm.GetString("Alert_ClickAddButtontoselectEmployeesforShiftAllocation", ci);
                btn_Add.Focus();
                gstrIsValid = "F";
                return;
            }
            else if (txt_StartDate.Text == "")
            {
                lblError.Text = rm.GetString("Alert_ScheduleFromcannotbeEmpty", ci);
                gstrIsValid = "F";
                return;
            }
            else if (txt_ToDate.Text == "")
            {
                lblError.Text = rm.GetString("Alert_ScheduleFromcannotbeEmpty", ci);
                gstrIsValid = "F";
                return;
            }
            else if (txt_StartDate.Text.Length < 10)
            {
                lblError.Text = rm.GetString("Alert_InvalidScheduleFromDate", ci);
                gstrIsValid = "F";
                return;
            }
            else if (txt_ToDate.Text.Length < 10)
            {
                lblError.Text = rm.GetString("Alert_InvalidScheduleToDate", ci);
                gstrIsValid = "F";
                return;
            }
            intStartDay = getStartDay();
        }
        gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
        strStartDate = objcls_Common.DateConvertion(gstrDateFormat, txt_StartDate.Text);
        strToDate = objcls_Common.DateConvertion(gstrDateFormat, txt_ToDate.Text);
        DateTime dtmStartDate = DateTime.Parse(strStartDate);
        DateTime dtmToDate = DateTime.Parse(strToDate);
        int Days = dtmToDate.CompareTo(dtmStartDate);
        if (Days < 0)
        {
            strAlert = string.Empty;
            strAlert = "alert('" + rm.GetString("Msg_ScheduleFromDateshouldbelesserthantheScheduleToDate", ci) + "')";
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", strAlert, true);
            gstrIsValid = "F";
            return;
        }
        ds = objShiftAllocation.SelectEmployeeDetails(gintUserId);
        dtEmpDetails = ds.Tables[0];
        int[] pattern = OverLappedValidation(dtmStartDate, dtmToDate, intStartDay);
        dtEmpDetails.DefaultView.RowFilter = "OverLapped=false";
        if (dtEmpDetails.DefaultView.ToTable().Rows.Count > 0)
        {
            IsUnOverlappedEmployeeExists = true;
        }
        ShiftAllocation(pattern, dtmStartDate, dtmToDate, intStartDay, PatternDaysCount);
        if (rbtnShifts.Checked == true)
        {
            if (gstrIsValid == "T")
            {
                string strScript = "<script language='javascript' type='text/javascript'>";
                if (Convert.ToString(strOverLappedEmployeeIds) != string.Empty && IsUnOverlappedEmployeeExists == false)
                {
                    strScript += "alert('" + rm.GetString("Alert_ShiftnotallocatedforemployeewithShiftOverLapping", ci) + " " + strOverLappedEmployeeIds + "');location.replace('TA_UI_Transaction_ShiftAllocationadd.aspx');";
                }
                else if (Convert.ToString(strOverLappedEmployeeIds) != string.Empty && IsUnOverlappedEmployeeExists == true)
                {
                    strScript += "alert('" + rm.GetString("Alert_ShiftAllocatedSuccessfullyExceptEmployeewithShiftOverLapping", ci) + " " + strOverLappedEmployeeIds + "');location.replace('TA_UI_Transaction_ShiftAllocationadd.aspx');";
                }
                else if (Convert.ToString(strOverLappedEmployeeIds) == string.Empty && IsUnOverlappedEmployeeExists == true)
                {
                    strScript += "alert('" + rm.GetString("Alert_ShiftAllocatedSuccessfully", ci) + "');location.replace('TA_UI_Transaction_ShiftAllocationadd.aspx');";
                }
                strScript += " </script>";
                ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", strScript, false);
                txt_StartDate.Text = string.Empty;
                txt_ToDate.Text = string.Empty;
            }
            else
            {
                return;
            }
        }
        else if (rbtnShiftRoaster.Checked == true)
        {
            if (gstrIsValid == "T")
            {
                string strScript = "<script language='javascript' type='text/javascript'>";
                if (Convert.ToString(strOverLappedEmployeeIds) != string.Empty && IsUnOverlappedEmployeeExists == false)
                {
                    strScript += "alert('" + rm.GetString("Alert_ShiftRosterNotAllocatedEmployeewithShiftOverLapping", ci) + " " + strOverLappedEmployeeIds + "');location.replace('TA_UI_Transaction_ShiftAllocationadd.aspx');";
                }
                else if (Convert.ToString(strOverLappedEmployeeIds) != string.Empty && IsUnOverlappedEmployeeExists == true)
                {
                    strScript += "alert('" + rm.GetString("Alert_ShiftRosterAllocatedSuccessfullyExceptEmployeewithShiftOverLapping", ci) + " " + strOverLappedEmployeeIds + "');location.replace('TA_UI_Transaction_ShiftAllocationadd.aspx');";
                }
                else if (Convert.ToString(strOverLappedEmployeeIds) == string.Empty && IsUnOverlappedEmployeeExists == true)
                {
                    strScript += "alert('" + rm.GetString("Alert_ShiftRosterAllocatedSuccessfully", ci) + "');location.replace('TA_UI_Transaction_ShiftAllocationadd.aspx');";
                }
                strScript += " </script>";
                ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", strScript, false);
                txt_StartDate.Text = string.Empty;
                txt_ToDate.Text = string.Empty;
            }
            else
            {
                return;
            }
        }
        else if (rbtnShiftPattern.Checked == true)
        {
            if (gstrIsValid == "T")
            {
                string strScript = "<script language='javascript' type='text/javascript'>";
                if (Convert.ToString(strOverLappedEmployeeIds) != string.Empty && IsUnOverlappedEmployeeExists == false)
                {
                    strScript += "alert('" + rm.GetString("Alert_ShiftnotallocatedforemployeewithShiftOverLapping", ci) + " " + strOverLappedEmployeeIds + "');location.replace('TA_UI_Transaction_ShiftAllocationadd.aspx');";
                }
                else if (Convert.ToString(strOverLappedEmployeeIds) != string.Empty && IsUnOverlappedEmployeeExists == true)
                {
                    strScript += "alert('" + rm.GetString("Alert_ShiftAllocatedSuccessfullyExceptEmployeewithShiftOverLapping", ci) + " " + strOverLappedEmployeeIds + "');location.replace('TA_UI_Transaction_ShiftAllocationadd.aspx');";
                }
                else if (Convert.ToString(strOverLappedEmployeeIds) == string.Empty && IsUnOverlappedEmployeeExists == true)
                {
                    strScript += "alert('" + rm.GetString("Alert_ShiftAllocatedSuccessfully", ci) + "');location.replace('TA_UI_Transaction_ShiftAllocationadd.aspx');";
                }
                strScript += " </script>";
                ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", strScript, false);
                txt_StartDate.Text = string.Empty;
                txt_ToDate.Text = string.Empty;
            }
            else
            {
                return;
            }
        }
        if (rbtnMultiple.Checked == true)
        {
            Session["ISSingleorMultiple"] = "IsMultiple";
        }
        else
        {
            Session["ISSingleorMultiple"] = "IsSingle";
        }
    }
    protected void btn_Add_Click(object sender, EventArgs e)
    {
    }
    protected void btnTemplate_Click(object sender, EventArgs e)
    {
        try
        {
            string strPath = Server.MapPath("Templates/Shift_Allocation_Import_Template.csv");
            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=Shift_Allocation_Import.csv");
                Response.BinaryWrite(data);
                Response.End();
            }
            else
            {
                base.Message("Template file is not available in the source file");
                return;
            }
        }
        catch (Exception Ex)
        {
            Message(Ex.ToString());
        }
    }
    protected void btn_btn_Upload(object sender, EventArgs e)
    {
        string strScript = string.Empty;
        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)
                    {
                        DataSet dstShiftAlloc = ImportShiftData(fileInfo);
                        if (dstShiftAlloc.Tables.Count > 0)
                        {
                            if (dstShiftAlloc.Tables[0].Columns.Contains("Employee_Id"))
                            {
                                divImport.Style.Add("display", "block");
                                divManual.Style.Add("display", "none");
                                Session["ShiftAllocaData"] = dstShiftAlloc;
                                grvImportDetails.DataSource = dstShiftAlloc;
                                grvImportDetails.DataBind();
                                strScript = "<script language='javascript'>";
                                strScript = strScript + "ModeOfAllocation();";
                                strScript = strScript + "alert('" + rm.GetString("Alert_ImportNotSuccessed", ci) + "');";
                                strScript = strScript + "</script>";
                                Page.RegisterStartupScript("Alert", strScript);
                            }
                            else
                            {
                                divImport.Style.Add("display", "block");
                                divManual.Style.Add("display", "none");
                                grvImportDetails.DataSource = null;
                                grvImportDetails.DataBind();
                                string strMsg = Convert.ToString(dstShiftAlloc.Tables[0].Rows[0]["Message"]);
                                strScript = "<script language='javascript'>";
                                strScript = strScript + "ModeOfAllocation();";
                                strScript = strScript + "alert('" + rm.GetString(strMsg.Contains("Msg:") ? "Alert_ImportSuccessed" : "Alert_ImportNotSuccessed", ci) + "');";
                                strScript = strScript + "</script>";
                                Page.RegisterStartupScript("Alert", strScript);
                            }
                        }
                    }
                    else
                    {
                        divImport.Style.Add("display", "block");
                        divManual.Style.Add("display", "none");
                        strScript = "<script language='javascript'>";
                        strScript = strScript + "ModeOfAllocation();";
                        strScript = strScript + "alert('" + rm.GetString("Alert_ErrorinShiftImporting", ci) + "');";
                        strScript = strScript + "</script>";
                        Page.RegisterStartupScript("Alert", strScript);
                    }
                }
                else
                {
                    divImport.Style.Add("display", "block");
                    divManual.Style.Add("display", "none");
                    strScript = "<script language='javascript'>";
                    strScript = strScript + "ModeOfAllocation();";
                    strScript = strScript + "alert('" + rm.GetString("Alert_TheUploadedfileisnotCsvfile", ci) + "');";
                    strScript = strScript + "</script>";
                    Page.RegisterStartupScript("Alert", strScript);
                }
            }
            else
            {
                divImport.Style.Add("display", "block");
                divManual.Style.Add("display", "none");
                strScript = "<script language='javascript'>";
                strScript = strScript + "ModeOfAllocation();";
                strScript = strScript + "alert('" + rm.GetString("Alert_Youhavenotspecifiedafile", ci) + "');";
                strScript = strScript + "</script>";
                Page.RegisterStartupScript("Alert", strScript);
            }
        }
        catch (Exception ex)
        {
            divImport.Style.Add("display", "block");
            divManual.Style.Add("display", "none");
            string strErr = Convert.ToString(ex.Message);
            strScript = "<script language='javascript' type='text/javascript'>";
            strScript = strScript + "ModeOfAllocation();";
            strScript = strScript + "alert('" + strErr.Replace("\r", "").Replace("\n", "") + "');";
            strScript = strScript + "</script>";
            Page.RegisterStartupScript("Alert", strScript);
            if (aFile != null) aFile.Dispose();
        }
        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();
        }
    }
    /// <summary>
    /// Cancel shift allocation
    /// </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("TA_UI_Transaction_ShiftAllocation.aspx");
    }
    #endregion
    #region dropdown events
    /// <summary>
    /// On selecting the shift pattern.
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void ddl_Pattern_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddl_Pattern.SelectedValue != "-Select-")
        {
            int index = Convert.ToInt32(ddl_Pattern.SelectedValue);
            fillStartDayddl(index);
        }
        else
        {
            ddl_StartDay.Items.Clear();
            ListItem liSelect = new ListItem();
            liSelect.Value = "-Select-";
            liSelect.Text = rm.GetString("Select", ci);
            ddl_StartDay.Items.Insert(0, liSelect);
            ddl_StartDay.Items[0].Value = "0";
            lbl_Pattern.Text = string.Empty;
        }
    }
    #endregion
    #region gridview events
    /// <summary>
    /// On page index changing, to load employee in the grid
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void grv_Employees_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        grv_Employees.PageIndex = e.NewPageIndex;
        fillEmployee();
    }
    /// <summary>
    /// To delete the employee from the grid.
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void grv_Employees_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        Label lblEmpAutoId = (Label)grv_Employees.Rows[e.RowIndex].FindControl("lbl_EmpAutoId");
        Label lblLoginEmployeeId = (Label)grv_Employees.Rows[e.RowIndex].FindControl("lbl_LoginEmployeeId");
        objShiftAllocation.DeleteEmpDetails(Convert.ToInt32(lblEmpAutoId.Text), Convert.ToInt32(lblLoginEmployeeId.Text));
        fillEmployee();
    }
    /// <summary>
    /// To change the name of the link button(delete) based on the language.
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void grv_Employees_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            LinkButton lbDelete = new LinkButton();
            lbDelete = (LinkButton)e.Row.Cells[0].Controls[0];
            e.Row.Cells[0].BorderColor = System.Drawing.Color.White;
            if (lbDelete.Text == "Delete")
            {
                lbDelete.Text = rm.GetString("btn_Delete", ci);
            }
        }
        if (e.Row.RowType == DataControlRowType.Header)
        {
            e.Row.Cells[0].BorderColor = System.Drawing.Color.White;
        }
    }
    #endregion
    #region NotUSed
    /// <summary>
    /// Allocating Shift Based on Shift Pattern
    /// </summary>
    private void ShiftpatternAllocation()
    {
        if (Page.IsValid)
        {
        }
    }
    private void SimpleShiftAllocation()
    {
        if (Page.IsValid)
        {
        }
    }
    /// <summary>
    /// Shift Roaster Allocation
    /// </summary>
    /// 
    private void ShiftroasterAllocation()
    {
        ds_Empdetails = objShiftAllocation.SelectEmployeeDetails(gintUserId);
        AllocateRoster(ds_Empdetails);
    }
    /// <summary>
    /// Fill ShiftRoaster dropdown
    /// </summary>   
    /// 
    public void OverLappedValidationShiftPattern(DateTime dtmStartDate, DateTime dtmToDate, int intStartDay)
    {
        int intOverLapped = 0;
        int StartDateShiftId = 0;
        int EndDateShiftId = 0;
        DataColumn dcEmployeeId = new DataColumn("OverLapped", System.Type.GetType("System.Boolean"));
        dtEmpDetails.Columns.Add(dcEmployeeId);
        DataTable dtShiftIDs = new DataTable();
        int[] Pattern = new int[31];
        int PatternDaysCount = 7;
        if (rbtnShiftPattern.Checked == true)
        {
            ds_ShiftAllocdetails = objShiftAllocation.SelectShiftPattern_ShiftAllocDetails(int.Parse(ddl_Pattern.SelectedValue));
            dtShiftIDs = ds_ShiftAllocdetails.Tables[0];
            PatternDaysCount = dtShiftIDs.Rows.Count;
            for (int i = 0; i < PatternDaysCount; i++)
            {
                Pattern[i] = int.Parse(Convert.ToString(dtShiftIDs.Rows[i]["id"]));
            }
        }
        else if (rbtnShifts.Checked == true)
        {
            Pattern = ShiftPatternSequence();
        }
        int p = intStartDay - 1;
        for (DateTime j = dtmStartDate; j <= dtmToDate; j = j.AddDays(1))
        {
            if (j == dtmStartDate)
            {
                StartDateShiftId = Pattern[p];
            }
            if (j == dtmToDate)
            {
                EndDateShiftId = Pattern[p];
            }
            if (p < (PatternDaysCount - 1))
            {
                p += 1;
            }
            else if (p >= (PatternDaysCount - 1))
            {
                p = 0;
            }
        }
        foreach (DataRow dRow in ds.Tables[0].Rows)
        {
            intOverLapped = ConstructPermanentShiftAllocation(Convert.ToInt32(dRow["EmpID"]), dtmStartDate, dtmToDate, StartDateShiftId, EndDateShiftId);
            if (intOverLapped > 0)
            {
                dRow["OverLapped"] = "True";
                if (Convert.ToString(strOverLappedEmployeeIds) == string.Empty)
                {
                    strOverLappedEmployeeIds.Append(Convert.ToString(dRow["EmployeeId"]));
                }
                else
                {
                    strOverLappedEmployeeIds.Append("," + Convert.ToString(dRow["EmployeeId"]));
                }
            }
            else
            {
                dRow["OverLapped"] = "False";
            }
        }
    }
    private void AllocateRoster(DataSet dsEmployee)
    {
    }
    public void OverLappedValidationRoster(DateTime dtmStartDate, DateTime dtmToDate)
    {
        int intOverLapped = 0;
        int[] Pattern = new int[310];
        int intTotalPatternDays = 0;
        int l = 0;
        DataColumn dcEmployeeId = new DataColumn("OverLapped", System.Type.GetType("System.Boolean"));
        dtEmpDetails.Columns.Add(dcEmployeeId);
        // Fetching ShiftRoaster Details, Pattern Details and getting ShiftIDs in an array
        DataSet ds_ShiftRoaster = objShiftRoaster.SelectShiftRoasterById(Convert.ToInt32(ddlShiftRoaster.SelectedValue));
        foreach (DataRow drShiftRoster in ds_ShiftRoaster.Tables[0].Rows)
        {
            int intNoOfPatterns = int.Parse(Convert.ToString(drShiftRoster["NumberOfPatterns"]));
            string strPatternName = string.Empty;
            for (int m = 1; m <= intNoOfPatterns; m++)
            {
                strPatternName = "Pattern" + m;
                ds_ShiftPattern = objShiftAllocation.Shiftpattern(Convert.ToInt32(drShiftRoster[strPatternName]));
                foreach (DataRow drShiftPattern in ds_ShiftPattern.Tables[0].Rows)
                {
                    int intPatternDays = int.Parse(Convert.ToString(drShiftPattern["Shift_days"]));
                    string strShiftName = string.Empty;
                    intTotalPatternDays = intTotalPatternDays + intPatternDays;
                    for (int n = 1; n <= intPatternDays; n++)
                    {
                        strShiftName = "Day" + n + "_Shift";
                        Pattern[l] = Convert.ToInt32(drShiftPattern[strShiftName]);
                        if ((l + 1) != intTotalPatternDays)
                        {
                            l = l + 1;
                        }
                    }
                }
                l = l + 1;
            }
        }
        int p = 0;
        int StartDateShiftId = 0;
        int EndDateShiftId = 0;
        for (DateTime j = dtmStartDate; j <= dtmToDate; j = j.AddDays(1))
        {
            if (j == dtmStartDate)
            {
                StartDateShiftId = Pattern[p];
            }
            if (j == dtmToDate)
            {
                EndDateShiftId = Pattern[p];
            }
            if (p < (intTotalPatternDays - 1))
            {
                p += 1;
            }
            else if (p >= (intTotalPatternDays - 1))
            {
                p = 0;
            }
        }
        foreach (DataRow dRow in ds_Empdetails.Tables[0].Rows)
        {
            intOverLapped = ConstructPermanentShiftAllocation(Convert.ToInt32(dRow["EmpID"]), dtmStartDate, dtmToDate, StartDateShiftId, EndDateShiftId);
            if (intOverLapped > 0)
            {
                dRow["OverLapped"] = "True";
                if (Convert.ToString(strOverLappedEmployeeIds) == string.Empty)
                {
                    strOverLappedEmployeeIds.Append(Convert.ToString(dRow["EmployeeId"]));
                }
                else
                {
                    strOverLappedEmployeeIds.Append("," + Convert.ToString(dRow["EmployeeId"]));
                }
            }
            else
            {
                dRow["OverLapped"] = "False";
            }
        }
    }
    #endregion
}
