using System;
using System.Data;
using System.Globalization;
using System.Resources;
using System.Threading;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class TA_UI_Transactions_GroupLeavePolicy : Base.BasePage
{
    #region Variable Declaration
    CultureInfo ci;
    ResourceManager rm;
    MonthlyLeaveClosureEventData objMonthlyLeaveClosure = new MonthlyLeaveClosureEventData();
    EmployeeEventData objEmployee = new EmployeeEventData();
    LeaveEventData objLeave = new LeaveEventData();
    GroupPolicyAllocationEventData objGroupPolicyAllocation = new GroupPolicyAllocationEventData();
    cls_Common objcls_Common = new cls_Common();
    YearSettingsEventData objYearsetting = new YearSettingsEventData();
    GroupPolicyAllocationEventData obj = new GroupPolicyAllocationEventData();
    DataSet ds_Empdetails = new DataSet();
    DataSet ds = new DataSet();
    DataTable dtEmpDetails = new DataTable();
    DateTime YearStart, YearEnd;
    int gintUserId, intYearSettingsId, count = 0, companyId = 0;
    int[] months = new int[120];
    bool IsMonthly = false;
    int[] LeaveTypeId;
    decimal[] Maxdays;
    string strfrom = string.Empty, strto = string.Empty, strScript = string.Empty, gstrDateFormat;
    float[] Month1, Month2, Month3, Month4, Month5, Month6, Month7, Month8, Month9, Month10, Month11, Month12;
    #endregion
    #region Page_Load.
    protected override void Page_Load(object sender, EventArgs e)
    {
        base.Page_Load(sender, e);
        lblError.Text = string.Empty;
        btn_Add.Focus();
        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 + "SetAlertMessages('" + rm.GetString("Alert_SelectLeavePolicy", 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);
        Hidden1.Value = Convert.ToString(Session["IDateFormat"]);
        if (!Page.IsPostBack)
        {
            objcls_Common.menu("LeaveTransaction", "108");
        }
        UserRights();
        gintUserId = Int32.Parse(Convert.ToString(Session["EmpAutoID"]));
        DataSet ds_Year = objYearsetting.GetActiveYearSettings();
        if (ds_Year.Tables.Count > 0)
        {
            if (ds_Year.Tables[0].Rows.Count > 0)
            {
                strfrom = Convert.ToString(ds_Year.Tables[0].Rows[0]["YearSettingFromDate"]);
                strto = Convert.ToString(ds_Year.Tables[0].Rows[0]["YearSettingToDate"]);
                DateTime dtFrom = Convert.ToDateTime(strfrom);
                DateTime dtTo = Convert.ToDateTime(strto);
                hdf_PolVal.Value = dtFrom.ToShortDateString() + "*" + dtTo.ToShortDateString();
                intYearSettingsId = Convert.ToInt32(ds_Year.Tables[0].Rows[0]["YearSettings_Id"]);
                YearStart = Convert.ToDateTime(Convert.ToString(ds_Year.Tables[0].Rows[0]["StartMonth"]) + " " + Convert.ToString(ds_Year.Tables[0].Rows[0]["StartYear"]));
                YearEnd = Convert.ToDateTime(Convert.ToString(ds_Year.Tables[0].Rows[0]["EndMonth"]) + " " + Convert.ToString(ds_Year.Tables[0].Rows[0]["EndYear"]));
                if (!IsPostBack)
                {
                    txt_StartDate.Text = Convert.ToDateTime(strfrom).ToString(Session["MDateFormat"].ToString());
                    txt_ToDate.Text = Convert.ToDateTime(strto).ToString(Session["MDateFormat"].ToString());
                }
            }
            else
            {
                strScript = "";
                strScript = strScript + "<script language='javascript'>";
                strScript = strScript + "alert('" + rm.GetString("Alert_DefineYearSettinginOrganizationSettings", ci) + "');location.replace('../Organization Settings/Organization_YearSetting.aspx')";
                strScript = strScript + "</script>";
                Page.RegisterStartupScript("AlertYearSetting", strScript);
            }
        }
        else
        {
            strScript = "";
            strScript = strScript + "<script language='javascript'>";
            strScript = strScript + "alert('" + rm.GetString("Alert_DefineYearSettinginOrganizationSettings", ci) + "');location.replace('../Organization Settings/Organization_YearSetting.aspx')";
            strScript = strScript + "</script>";
            Page.RegisterStartupScript("AlertYearSetting", strScript);
        }
        if (!Page.IsPostBack)
        {
            if (Session["CheckRecordsAddInPopUP"] != null)
            {
                Session["CheckRecordsAddInPopUP"] = null;
            }
            else
            {
                objGroupPolicyAllocation.DeleteEmpNameGroupPolicy(gintUserId);
                Session["EmpDetails"] = null;
                Session["currentSession"] = null;
            }
            FillEmployee();
            FillLeavePolicyddl();
            GetcompanyId();
            ddl_LeavePolicy.SelectedIndex = ddl_LeavePolicy.Items.IndexOf(ddl_LeavePolicy.Items.FindByText(Convert.ToString(Session["GPLeavePolicy"])));
        }
    }
    #endregion
    private void AddJavascriptCode(string AllocatedEmployees)
    {
        string script = " objHiddenField = document.getElementById('" + PolicyExistsEmployees.ClientID + @"'); objSubmit = document.getElementById('" + btn_Save.ClientID + @"'); if(confirm('" + rm.GetString("GroupLeavePolicyExists", ci) + " " + AllocatedEmployees + @",Do You want to replace?') == true){ objHiddenField.value = 'true'; objSubmit.click();}else { objHiddenField.value = 'cancel'; objSubmit.click();}";
        ScriptManager.RegisterStartupScript(this, this.GetType(), "confirm1", script, true);
    }
    #region btn_Save_Click.
    protected void btn_Save_Click(object sender, EventArgs e)
    {
        try
        {
            ScriptManager scriptManager = ScriptManager.GetCurrent(Page);
            cls_Common objCommon = new cls_Common();
            if (GroupPolicyValidation())
            {
                lblError.Text = string.Empty;
                string strToDate = string.Empty;
                string strStartDate = string.Empty;
                gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
                strStartDate = GetFirstDayOfMonth(Convert.ToDateTime(objCommon.DateConvertion(gstrDateFormat, txt_StartDate.Text))).ToString("MM/dd/yyyy");
                strToDate = GetTheLastDayOfMonth(Convert.ToDateTime(objCommon.DateConvertion(gstrDateFormat, txt_ToDate.Text))).ToString("MM/dd/yyyy");
                ds = objGroupPolicyAllocation.SelectEmployeeDetails(gintUserId);
                dtEmpDetails = ds.Tables[0];
                Session["dtEmpDetails"] = dtEmpDetails;
                string ExistsOrNot;
                string AllocatedEmployees = string.Empty;
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    ExistsOrNot = objGroupPolicyAllocation.dsSelectPolicyAllocatedEmployeeDetails(Convert.ToInt32(ds.Tables[0].Rows[i]["EmpID"]));
                    if (ExistsOrNot == "Exists")
                    {
                        if (AllocatedEmployees == string.Empty)
                        {
                            AllocatedEmployees = ds.Tables[0].Rows[i]["EmployeeId"].ToString();
                            count += 1;
                        }
                        else
                        {
                            AllocatedEmployees = AllocatedEmployees + ',' + ds.Tables[0].Rows[i]["EmployeeId"].ToString();
                            count += 1;
                        }
                    }
                }
                if (AllocatedEmployees != string.Empty)
                {
                    if (PolicyExistsEmployees.Value == string.Empty)
                    {
                        AddJavascriptCode(AllocatedEmployees);
                        return;
                    }
                }
                if (PolicyExistsEmployees.Value == "true")
                {
                }
                else if (PolicyExistsEmployees.Value == "cancel")
                {
                    string[] test = new string[count];
                    test = commaStringToArray(AllocatedEmployees);
                    for (int i = 0; i < test.Length; i++)
                    {
                        DataRow[] drow = dtEmpDetails.Select("EmployeeId='" + Convert.ToString(test[i]) + "'");
                        if (drow.Length > 0)
                        {
                            for (int mj = dtEmpDetails.Rows.Count - 1; mj >= 0; mj--)
                            {
                                if (Convert.ToString(dtEmpDetails.Rows[mj]["EmployeeId"]) == Convert.ToString(test[i]))
                                {
                                    DataRow theRowToDelete = dtEmpDetails.Rows[mj];
                                    dtEmpDetails.Rows.Remove(theRowToDelete);
                                }
                            }
                        }
                    }
                }
                if (dtEmpDetails.Rows.Count > 0)
                {
                    DateTime PolicyStartDate;
                    foreach (DataRow drEmpDetails in dtEmpDetails.Rows)
                    {
                        int EmpId = 0, intLevelID = 0;
                        if (Convert.ToDateTime(strStartDate) >= Convert.ToDateTime(drEmpDetails["DateOfJoining"].ToString()))
                        {
                            PolicyStartDate = Convert.ToDateTime(strStartDate);
                        }
                        else
                        {
                            DateTime DOJ = GetFirstDayOfMonth(Convert.ToDateTime(drEmpDetails["DateOfJoining"].ToString()));
                            if (DOJ == Convert.ToDateTime(drEmpDetails["DateOfJoining"].ToString()))
                            {
                                PolicyStartDate = DOJ;
                            }
                            else
                            {
                                PolicyStartDate = DOJ.AddMonths(1);
                            }
                        }
                        EmpId = Convert.ToInt32(drEmpDetails["EmpID"].ToString());
                        intLevelID = Convert.ToInt32(drEmpDetails["LevelId"].ToString());
                        if (IsMonthly)
                        {
                            GroupPolicyMonthly(EmpId, PolicyStartDate, strToDate, gintUserId, intYearSettingsId, intLevelID);
                        }
                        else
                        {
                            GroupPolicyYearly(EmpId, PolicyStartDate, strToDate, gintUserId, intYearSettingsId, intLevelID);
                        }
                    }
                    if (scriptManager != null && scriptManager.IsInAsyncPostBack)
                    {
                        ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("Alert_LeavePolicyassignedsucessfully", ci) + "');", true);
                    }
                    else
                    {
                        Page.ClientScript.RegisterStartupScript(Page.GetType(), "Alert", "alert('" + rm.GetString("Alert_LeavePolicyassignedsucessfully", ci) + "');", true);
                    }
                    ddl_LeavePolicy.SelectedIndex = 0;
                    PolicyExistsEmployees.Value = string.Empty;
                    txt_StartDate.Text = Convert.ToDateTime(strfrom).ToString(Session["MDateFormat"].ToString());
                    txt_ToDate.Text = Convert.ToDateTime(strto).ToString(Session["MDateFormat"].ToString());
                    grv_Employees.DataSource = null;
                    grv_Employees.DataBind();
                    grv_Employees.Visible = false;
                    lblLeavePolicy.Text = "";
                }
                else
                {
                    if (scriptManager != null && scriptManager.IsInAsyncPostBack)
                    {
                        ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("Alert_PolicyNotAllocated", ci) + "');", true);
                    }
                    else
                    {
                        Page.ClientScript.RegisterStartupScript(Page.GetType(), "Alert", "alert('" + rm.GetString("Alert_PolicyNotAllocated", ci) + "');", true);
                    }
                    ddl_LeavePolicy.SelectedIndex = 0;
                    txt_StartDate.Text = Convert.ToDateTime(strfrom).ToString(Session["MDateFormat"].ToString());
                    txt_ToDate.Text = Convert.ToDateTime(strto).ToString(Session["MDateFormat"].ToString());
                    grv_Employees.DataSource = null;
                    grv_Employees.DataBind();
                    grv_Employees.Visible = false;
                    lblLeavePolicy.Text = "";
                }
            }
        }
        catch (Exception ex)
        {
            Message(ex.ToString());
        }
    }
    #endregion
    #region btn_Cancel_Click.
    protected void btn_Cancel_Click(object sender, EventArgs e)
    {
        Session["GPLeavePolicy"] = null;
        objGroupPolicyAllocation.DeleteEmpNameGroupPolicy(gintUserId);
        txt_StartDate.Text = Convert.ToDateTime(strfrom).ToString(Session["MDateFormat"].ToString());
        txt_ToDate.Text = Convert.ToDateTime(strto).ToString(Session["MDateFormat"].ToString());
        Session["EmpDetails"] = null;
        grv_Employees.DataSource = null;
        grv_Employees.DataBind();
        grv_Employees.Visible = false;
        lblLeavePolicy.Text = "";
        ddl_LeavePolicy.SelectedIndex = 0;
    }
    #endregion
    #region grv_Employees_RowDeleting.
    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");
        objGroupPolicyAllocation.DeleteEmpDetails(Convert.ToInt32(lblEmpAutoId.Text), Convert.ToInt32(lblLoginEmployeeId.Text));
        FillEmployee();
    }
    #endregion
    #region grv_Employees_PageIndexChanging.
    protected void grv_Employees_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        grv_Employees.PageIndex = e.NewPageIndex;
        FillEmployee();
    }
    #endregion
    #region Function.
    #region FillEmployee.
    private void FillEmployee()
    {
        Session["previousCompanyId"] = Session["currentSession"];
        ds = objGroupPolicyAllocation.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();
        }
    }
    #endregion
    #region LoadStrings.
    private void LoadStrings(CultureInfo ci)
    {
        lbl_Header.Text = rm.GetString("Transaction_LeavePolicyAllocation_Header", ci);
        lbl_SelectedEmployees.Text = rm.GetString("ShiftAllocation_SelectedEmployees", ci);
        lbl_IndicatesMandatoryFields.Text = rm.GetString("IndicatesMandatoryFields", 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_Cancel", ci);
        grv_Employees.Columns[2].HeaderText = rm.GetString("email_EmployeeId", ci);
        grv_Employees.Columns[3].HeaderText = rm.GetString("email_EmployeeName", ci);
        grv_Employees.Columns[4].HeaderText = rm.GetString("EmployeeMaster_DateOfJoining", ci);
        lbl_ScheduleTo.Text = rm.GetString("OnDuty_OutDate", ci);
        lbl_ScheduleFrom.Text = rm.GetString("OnDuty_InDate", ci);
        lbl_PolicyName1.Text = rm.GetString("Employee_LeavePolicy", ci);
        ddl_LeavePolicy.Items[0].Text = rm.GetString("Select", ci);
        lblLoading.Text = rm.GetString("ProgressBarText", ci);
        lblSelectEmployee.Text = rm.GetString("Shift_SelectEmployee", ci);
    }
    #endregion
    #region FillLeavePolicyddl.
    private void FillLeavePolicyddl()
    {
        if (Session["GPLeavePolicy"] != string.Empty && Session["GPLeavePolicy"] != null)
        {
            if (grv_Employees.Rows.Count > 0)
            {
                lblLeavePolicy.Text = Convert.ToString(Session["GPLeavePolicy"]);
                ddl_LeavePolicy.Items.Add(Convert.ToString(Session["GPLeavePolicy"]));
            }
        }
        else
        {
            DataSet ds_leavepolicy = new DataSet();
            ds_leavepolicy = objLeave.SelectAllLeavePolicy(string.Empty);
            if (ds_leavepolicy != null)
            {
                if (ds_leavepolicy.Tables[0].Rows.Count > 0)
                {
                    ddl_LeavePolicy.DataSource = ds_leavepolicy;
                    ddl_LeavePolicy.DataTextField = "PolicyName";
                    ddl_LeavePolicy.DataValueField = "Policy_Id";
                    ddl_LeavePolicy.DataBind();
                }
                ds_leavepolicy.Dispose();
                foreach (ListItem item in ddl_LeavePolicy.Items)
                {
                    item.Attributes.Add("title", item.Text);
                }
            }
        }
        Session["GroupLeavePolicyAvailable"] = null;
    }
    #endregion
    #region GroupPolicyValidation.
    private bool GroupPolicyValidation()
    {
        try
        {
            cls_Common objCommon = new cls_Common();
            gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
            if (grv_Employees.Rows.Count == 0)
            {
                Message(rm.GetString("Alert_ClickAddButtontoselectEmployees", ci));
                btn_Add.Focus();
                return false;
            }
            else if (txt_StartDate.Text == "")
            {
                Message(rm.GetString("Alert_PolicyFromDatecannotbeEmpty", ci));
                txt_StartDate.Focus();
                return false;
            }
            else if (txt_ToDate.Text == "")
            {
                Message(rm.GetString("Msg_PolicyToDatecannotbeEmpty", ci));
                txt_ToDate.Focus();
                return false;
            }
            else if (txt_StartDate.Text.Length < 10)
            {
                Message(rm.GetString("Msg_InvalidPolicyFromDate", ci));
                txt_StartDate.Focus();
                return false;
            }
            else if (Convert.ToDateTime(objCommon.DateConvertion(gstrDateFormat, txt_StartDate.Text)) < Convert.ToDateTime(strfrom))
            {
                Message(rm.GetString("Alert_PolicyFromDatebemoreLessthanyearstart", ci));
                txt_StartDate.Focus();
                return false;
            }
            else if (txt_ToDate.Text.Length < 10)
            {
                Message(rm.GetString("Msg_InvalidPolicyToDate", ci));
                txt_ToDate.Focus();
                return false;
            }
            else if (Convert.ToDateTime(objCommon.DateConvertion(gstrDateFormat, txt_ToDate.Text)) > Convert.ToDateTime(strto))
            {
                Message(rm.GetString("Msg_PolicyToDatecannotbemorethanyearend", ci));
                txt_StartDate.Focus();
                return false;
            }
            string strStartDate = "", strToDate = "";
            strStartDate = GetFirstDayOfMonth(Convert.ToDateTime(objCommon.DateConvertion(gstrDateFormat, txt_StartDate.Text))).ToString("MM/dd/yyyy");
            strToDate = GetTheLastDayOfMonth(Convert.ToDateTime(objCommon.DateConvertion(gstrDateFormat, txt_ToDate.Text))).ToString("MM/dd/yyyy");
            DateTime dtmStartDate = DateTime.Parse(strStartDate);
            DateTime dtmToDate = DateTime.Parse(strToDate);
            int Days = dtmToDate.CompareTo(dtmStartDate);
            if (Days < 0)
            {
                Message(rm.GetString("Msg_PolicyFromDateshouldbelesserthanthePolicyToDate", ci));
                txt_ToDate.Focus();
                return false;
            }
            if (IsMonthly)
            {
                DataSet dsMaximunClosedMonth = new DataSet();
                DateTime ClosedMonth;
                GetcompanyId();
                dsMaximunClosedMonth = objMonthlyLeaveClosure.SelectMaximunClosedMonthForOrg(companyId);
                if (dsMaximunClosedMonth != null && dsMaximunClosedMonth.Tables.Count > 0 && dsMaximunClosedMonth.Tables[0].Rows.Count > 0)
                {
                    ClosedMonth = Convert.ToDateTime(dsMaximunClosedMonth.Tables[0].Rows[0]["MonthClosure_Month"]);
                    if (dtmStartDate == ClosedMonth)
                    {
                        Message(rm.GetString("Msg_StartDatecannontbeamonthlyclosedDate", ci));
                        txt_ToDate.Focus();
                        return false;
                    }
                }
            }            
        }
        catch (Exception ex)
        {
            Message(ex.ToString());
        }
        return true;
    }
    #endregion
    #region Message.
    private void Message(string messageContent)
    {
        string strScript = "<script language='javascript' type='text/javascript'>";
        strScript += "alert('" + messageContent + "');";
        strScript += " </script>";
        ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", strScript, false);
    }
    #endregion
    #region MessageWithRedirect.
    private void MessageWithRedirect(string messageContent, string ToPage)
    {
        string strScript = "<script language='javascript' type='text/javascript'>";
        strScript += "alert('" + messageContent + "');";
        strScript += "location.href='" + ToPage + "';";
        strScript += " </script>";
        ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", strScript, false);
    }
    #endregion
    #region GroupPolicyMonthly.
    private void GroupPolicyMonthly(int EmpId, DateTime PolicyStartDate, string strToDate, int gintUserId, int intYearSettingsId, int intLevelID)
    {
        try
        {
            int MaxLPID = 0, i = 0;
            objEmployee.delete_EmployeeMonthlyLeavePolicy(EmpId);
            MaxLPID = objMonthlyLeaveClosure.InsertLeavePolicyMonthlyLeaveClosure(EmpId, Convert.ToInt32(ddl_LeavePolicy.SelectedValue), PolicyStartDate.ToString(), strToDate, gintUserId, intYearSettingsId);
            DataSet ds_Leave = new DataSet();
            ds_Leave = objLeave.SelectLeavePolicyDetails(Convert.ToInt32(ddl_LeavePolicy.SelectedValue));
            int Size = ds_Leave.Tables[0].Rows.Count;
            Month1 = new float[Size];
            Month2 = new float[Size];
            Month3 = new float[Size];
            Month4 = new float[Size];
            Month5 = new float[Size];
            Month6 = new float[Size];
            Month7 = new float[Size];
            Month8 = new float[Size];
            Month9 = new float[Size];
            Month10 = new float[Size];
            Month11 = new float[Size];
            Month12 = new float[Size];
            LeaveTypeId = new int[Size];
            foreach (DataRow dr in ds_Leave.Tables[0].Rows)
            {
                LeaveTypeId[i] = Convert.ToInt32(dr["LeaveType_Id"].ToString());
                Month1[i] = Convert.ToSingle(dr["Month1"]);
                Month2[i] = Convert.ToSingle(dr["Month2"]);
                Month3[i] = Convert.ToSingle(dr["Month3"]);
                Month4[i] = Convert.ToSingle(dr["Month4"]);
                Month5[i] = Convert.ToSingle(dr["Month5"]);
                Month6[i] = Convert.ToSingle(dr["Month6"]);
                Month7[i] = Convert.ToSingle(dr["Month7"]);
                Month8[i] = Convert.ToSingle(dr["Month8"]);
                Month9[i] = Convert.ToSingle(dr["Month9"]);
                Month10[i] = Convert.ToSingle(dr["Month10"]);
                Month11[i] = Convert.ToSingle(dr["Month11"]);
                Month12[i] = Convert.ToSingle(dr["Month12"]);
                objEmployee.InsertEmpLeavePolicyDetailsMonthly(EmpId, MaxLPID, Convert.ToInt32(ddl_LeavePolicy.SelectedValue), LeaveTypeId[i], intYearSettingsId, Month1[i], Month2[i], Month3[i], Month4[i], Month5[i], Month6[i], Month7[i], Month8[i], Month9[i], Month10[i], Month11[i], Month12[i], gintUserId);
                i = i + 1;
            }
            for (int t = 0; t < Size; t++)
            {
                decimal CurrentQuota = Convert.ToDecimal(GetMonthQuota(PolicyStartDate.Month, t));
                if (CheckMonthlyLeaveClosureEntryExist(intLevelID.ToString(), EmpId.ToString(), LeaveTypeId[t].ToString(), PolicyStartDate))
                {
                    objEmployee.UpdateMonthlyLeaveClosure(intLevelID, EmpId, LeaveTypeId[t], PolicyStartDate, CurrentQuota, gintUserId);
                }
                else
                {
                    objEmployee.InsertMonthlyLeaveClosure(intLevelID, EmpId, LeaveTypeId[t], PolicyStartDate, CurrentQuota, gintUserId);
                }
            }
        }
        catch (Exception ex)
        {
            Message(ex.ToString());
        }
    }
    #endregion
    #region GetcompanyId.
    private void GetcompanyId()
    {
        if (Session["currentSession"] != null && 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)
                {
                    companyId = Convert.ToInt32(ds_getOrg.Tables[0].Rows[0]["LevelID"].ToString());
                }
            }
        }
    }
    #endregion
    #region CheckMonthlyLeaveClosureEntryExist.
    private bool CheckMonthlyLeaveClosureEntryExist(string LevelID, string Employee_Id, string LeavetypeID, DateTime MonthNumber)
    {
        DataSet ds = new DataSet();
        ds = objMonthlyLeaveClosure.Select_MonthlyLeaveClosure(null, intYearSettingsId.ToString(), LevelID, Employee_Id, LeavetypeID, MonthNumber.ToString());
        if (ds != null)
        {
            if (ds.Tables.Count > 0)
            {
                if (ds.Tables[0].Rows.Count > 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }
        else
        {
            return false;
        }
    }
    #endregion
    #region GetMonthQuota.
    public float GetMonthQuota(int Month, int i)
    {
        float MonthName = 0;
        switch (Month)
        {
            case 1:
                MonthName = Month1[i];
                break;
            case 2:
                MonthName = Month2[i];
                break;
            case 3:
                MonthName = Month3[i];
                break;
            case 4:
                MonthName = Month4[i];
                break;
            case 5:
                MonthName = Month5[i];
                break;
            case 6:
                MonthName = Month6[i];
                break;
            case 7:
                MonthName = Month7[i];
                break;
            case 8:
                MonthName = Month8[i];
                break;
            case 9:
                MonthName = Month9[i];
                break;
            case 10:
                MonthName = Month10[i];
                break;
            case 11:
                MonthName = Month11[i];
                break;
            case 12:
                MonthName = Month12[i];
                break;
        }
        return MonthName;
    }
    #endregion
    #region GetFirstDayOfMonth.
    public static DateTime GetFirstDayOfMonth(DateTime givenDate)
    {
        return new DateTime(givenDate.Year, givenDate.Month, 1);
    }
    #endregion
    #region GetTheLastDayOfMonth.
    public static DateTime GetTheLastDayOfMonth(DateTime givenDate)
    {
        return GetFirstDayOfMonth(givenDate).AddMonths(1).Subtract(new TimeSpan(1, 0, 0, 0, 0));
    }
    #endregion
    #region userrights.
    private void UserRights()
    {
        Cls_CheckUser objCheckUser = new Cls_CheckUser();
        DataSet ds_Checkuser = new DataSet();
        ds_Checkuser = objCheckUser.checkRights(108, Convert.ToInt32(Session["userGroup_Id"]), "");
        if (ds_Checkuser.Tables[0].Rows.Count > 0)
        {
            if (ds_Checkuser.Tables[0].Rows[0]["addPrv"] != DBNull.Value && Convert.ToInt32(ds_Checkuser.Tables[0].Rows[0]["addPrv"]) == 1)
            {
                this.btn_Save.Visible = true;
            }
            else
            {
                this.btn_Save.Visible = false;
            }
        }
        else
        {
            MessageWithRedirect(rm.GetString("Alert_YoudonothavesufficientrightsContactAdministrator", ci), "TransactionLandingPAge.aspx");
        }
    }
    #endregion
    #endregion
    private void GroupPolicyYearly(int EmpId, DateTime PolicyStartDate, string strToDate, int gintUserId, int intYearSettingsId, int intLevelID)
    {
        try
        {
            int MaxLPID = 0, i = 0;
            DateTime PolicyEndDate = Convert.ToDateTime(strToDate);
            int days = DateDiff(PolicyStartDate, PolicyEndDate);
            if (days < 0) days = 0;
            objEmployee.delete_EmployeeLeavePolicy(EmpId);
            string strPolicyDate = objcls_Common.DateConvertion("MM/dd/yyyy", PolicyStartDate.ToString("MM/dd/yyyy"));
            objEmployee.InsertLeavePolicy(EmpId, Convert.ToInt32(Session["PolicyID"]), strPolicyDate, strToDate, gintUserId);
            MaxLPID = objEmployee.select_MaxEmpLeavepolicyIDUpdated(strPolicyDate, strToDate, EmpId);
            DataSet ds_Leave = new DataSet();
            ds_Leave = objLeave.SelectLeavePolicyDetails(Convert.ToInt32(Session["PolicyID"]));
            Session["LeavePolicy"] = ds_Leave.Tables[0];
            int Size = ds_Leave.Tables[0].Rows.Count;
            LeaveTypeId = new int[Size];
            Maxdays = new decimal[Size];
            foreach (DataRow dr in ds_Leave.Tables[0].Rows)
            {
                LeaveTypeId[i] = Convert.ToInt32(dr["LeaveType_Id"].ToString());
                int totLeave = Convert.ToInt32(dr["MaxDays_applicable"]);
                //decimal leaveperday = (Decimal)totLeave / 365;
                //Maxdays[i] = Convert.ToDecimal(Math.Round(days * leaveperday, 0));
                decimal leaveperday = 0;
                if (Convert.ToString(dr["IsProrataRequired"]) == "True")
                {
                    leaveperday = (Decimal)totLeave / 365;
                    Maxdays[i] = Convert.ToDecimal(Math.Round(days * leaveperday, 0));
                }
                else
                {
                    leaveperday = (Decimal)totLeave;
                    Maxdays[i] = Convert.ToDecimal(Math.Round(1 * leaveperday, 0));
                }
                decimal maxDays_month = Convert.ToDecimal(dr["MaxDays_Month"]);
                objEmployee.InsertEmpLeavePolicyDetails(EmpId, MaxLPID, Convert.ToInt32(Session["PolicyID"]), LeaveTypeId[i], Maxdays[i], gintUserId, maxDays_month);
                i = i + 1;
            }
            for (int t = 0; t < Size; t++)
            {
                if (Convert.ToDecimal(GetMaxDays(Convert.ToInt32(LeaveTypeId[t]), Convert.ToDecimal(Maxdays[t]), EmpId, intYearSettingsId)) > -365)
                {
                    objEmployee.InsertYearclosure_Modify(intLevelID, EmpId, LeaveTypeId[t], Convert.ToDecimal(Convert.ToDecimal(GetMaxDays(Convert.ToInt32(LeaveTypeId[t]), Convert.ToDecimal(Maxdays[t]), EmpId, intYearSettingsId))), gintUserId);
                }
                else
                {
                    objEmployee.InsertYearclosure_Modify(intLevelID, EmpId, LeaveTypeId[t], Maxdays[t], gintUserId);
                }
            }
            int UserId = Int32.Parse(Session["EmpAutoID"].ToString());
            obj.DeleteEmpNameGroupPolicy(UserId);
        }
        catch (Exception ex)
        {
            Response.Write(ex.ToString());
        }
    }
    public decimal GetMaxDays(int LeaveTypeId, decimal LeaveTypeCount, int EmployeeId, int YearSettingId)
    {
        decimal CurrentQuota = -365;
        decimal MaxValue = -365;
        decimal intPrevious = 0;
        decimal intNoOfLeave = 0;
        try
        {
            DataTable dt = new DataTable();
            dt = objEmployee.FillLeaveTypesforEmployee(EmployeeId, YearSettingId).Tables[0];
            if (dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Select("Emp_LeaveType_Id='" + LeaveTypeId + "'"))
                {
                    if (Convert.ToString(dr["PreviousYearBalance"]) != string.Empty)
                        intPrevious = Convert.ToDecimal(dr["PreviousYearBalance"]);
                    if (Convert.ToString(dr["NoOffLeaveAvailed"]) != string.Empty)
                        intNoOfLeave = Convert.ToDecimal(dr["NoOffLeaveAvailed"]);
                    MaxValue = Convert.ToDecimal(intPrevious - intNoOfLeave);
                    if (Session["LeavePolicy"] != null)
                    {
                        DataTable dtTemp = (DataTable)Session["LeavePolicy"];
                        foreach (DataRow dtRow in dtTemp.Select("LeaveType_Id=" + Convert.ToInt32(dr["Emp_LeaveType_Id"])))
                        {
                            if (Convert.ToString(dtRow["MaxDays_applicable"]) != string.Empty)
                            {
                                MaxValue = MaxValue + LeaveTypeCount;
                            }
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            Message(ex.ToString());
        }
        CurrentQuota = MaxValue;
        return CurrentQuota;
    }
    private int DateDiff(System.DateTime startDate, System.DateTime endDate)
    {
        System.TimeSpan TS = new System.TimeSpan(endDate.Ticks - startDate.Ticks);
        int diff = Convert.ToInt32(TS.TotalDays);
        return diff;
    }
    #region Grid view row data bound
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            Label lbl = (Label)e.Row.Cells[3].FindControl("lbl_EmpDateOfJoining");
            if (lbl.Text != "")
            {
                lbl.Text = (Convert.ToDateTime(lbl.Text.ToString())).ToString(Session["MDateFormat"].ToString());
                e.Row.Cells[5].Controls.Add(lbl);
            }
        }
    }
    #endregion
    protected void grv_Employees_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            Label lbl = (Label)e.Row.Cells[4].FindControl("lbl_EmpDateOfJoining");
            lbl.Text = (Convert.ToDateTime(lbl.Text.ToString())).ToString(Session["MDateFormat"].ToString());
        }
        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;
        }
    }
    private string[] commaStringToArray(string strComma)
    {
        string[] strArray;
        strArray = strComma.Split(new char[] { ',' });
        string[] intArray = new string[strArray.Length];
        for (int i = 0; i < strArray.Length; i++)
            intArray[i] = Convert.ToString(strArray[i]);
        return intArray;
    }
}
