using System;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Globalization;
using System.Threading;
using System.Resources;
/****************************************************************************************************************************
* Project Name    : TimeCheck                              Started Date  : 12-Aug-2007
* Module          : Year Closure                           Last Modified : 14-Aug-2007
* Programmer      : Arun Vinoth.T
* Current Storage : \\Angler56\Projects\Inprogress\SCREEN1206\code\Time_AttendanceApp
* BackUp          : \\Windev\EIT\Projects\Inprogress\SCREEN1206\code\TimecheckAVBackup
 * 
 * Modified By      :   Manjula.P
 * Modified On      :   01-Oct-2013
 * Descriptions     :   Adding Current Quota leave as Available leaves for Calc_Factor  fltquota = fltCurrAvailLeave;
****************************************************************************************************************************/
public partial class Transactions_TA_UI_Transactions_YearClosureAdd : Base.BasePage
{
    ResourceManager rm;
    CultureInfo ci;
    // Cls_Connect cl = new Cls_Connect();
    EmployeeEventData objEmployee = new EmployeeEventData();
    YearClosureEventdata objYearclosure = new YearClosureEventdata();
    YearSettingsEventData objYearSettingsEventData = new YearSettingsEventData();
    Rpt_Common rptcommon = new Rpt_Common();
    cls_Common objcls_Common = new cls_Common();
    DataTable dtYearDetails = new DataTable();
    DataSet dsYeardetails = new DataSet();
    int auEmployeeID;
    int intYear;
    int LevelId;
    string strYear;
    string StrCurrentDate, gstrDateFormat;
    protected override void Page_Load(object sender, EventArgs e)
    {
        // session checking and reset date format
        base.Page_Load(sender, e);
        if (!Page.IsPostBack)
        {
            base.CheckPages(0);
        }
        //Session.LCID = 1033;
        // Get the culture info to set the language
        if (Session["Session_ActiveLanguage"] == null)
        {
            Response.Redirect("../index.aspx");
        }
        else
        {
            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);
        }
        try
        {
            auEmployeeID = Convert.ToInt32(Session["EmpAutoID"]);
        }
        catch
        {
            Response.Redirect("../Index.aspx");
        }
        if (!IsPostBack)
        {
            // Fill Company Dropdown
            objcls_Common.menu("ExportTran", "62");
            CompanyBinding();
            loadyearsettings();
            string strSetAlert = "";
            strSetAlert = strSetAlert + "<script language='javascript'>";
            strSetAlert = strSetAlert + "SetAlertMessages('" + rm.GetString("Alert_SelectSuccessiveYear", ci) + "','" + rm.GetString("Alert_Select_Company", ci) + "');";
            strSetAlert = strSetAlert + "</script>";
            Page.RegisterStartupScript("SetAlertMessages", strSetAlert);
            // SELECT YEAR SETTING DETAILS
            fillYearSettingDetails();
            //StrCurrentDate = DateTime.Now.ToString(Session["MDateFormat"].ToString());
            //lblClosedDate.Text = StrCurrentDate;
            lblClosedDate.Text = DateTime.UtcNow.ToString(Session["MDateFormat"].ToString());// HariHaran J ****16-02-2024*****
            if (Session["parentLevelId"] != null)
            {
                LevelId = Convert.ToInt32(Session["parentLevelId"]);
            }
            btn_Save.Attributes.Add("onclick", "javascript:return confirm('" + rm.GetString("Alert_AreyousuretoclosetheYear", ci) + "')");
        }
        lbl_Error.Text = "";
    }
    // Used to fill all available companies in the Company Dropdown
    private void CompanyBinding()
    {
        DataSet dsCompany = new DataSet();
        ShiftEvenData objShift = new ShiftEvenData();
        dsCompany = objShift.SelectCompany(Convert.ToString(Session["UserGroupName"]), Convert.ToString(Session["LevelRights"]), 0);
        if (dsCompany != null)
        {
            if (dsCompany.Tables[0].Rows.Count > 0)
            {
                ddlCompany.DataSource = dsCompany;
                ddlCompany.DataTextField = "CompanyName";
                ddlCompany.DataValueField = "CompanyId";
                ddlCompany.DataBind();
                ListItem lstItem = new ListItem();
                lstItem.Value = "0";
                //lstItem.Text = "All";
                lstItem.Text = rm.GetString("Select", ci);
                ddlCompany.Items.Insert(0, lstItem);
                foreach (ListItem item in ddlCompany.Items)
                {
                    item.Attributes.Add("title", item.Text);
                }
            }
        }
    }
    private void fillYearSettingDetails()
    {
        //SqlParameter pIsactive = new SqlParameter("@IsActive", 1);
        //SqlParameter[] pParams ={ pIsactive };
        try
        {
            // dtYearDetails = cl.StoredProcedure_ParamterCollection_DT(pParams, "Proc_TA_GetActiveYearSettingDetails");
            dsYeardetails = objYearSettingsEventData.GetActiveYearSettings();
            if (dsYeardetails.Tables.Count > 0)
            {
                dtYearDetails = dsYeardetails.Tables[0];
                ViewState["dsYeardetails"] = dtYearDetails;
            }
        }
        catch (Exception ex)
        {
            throw (ex);
        }
        if (dtYearDetails.Rows.Count > 0)
        {
            strYear = dtYearDetails.Rows[0]["StartMonth"].ToString() + " " + dtYearDetails.Rows[0]["StartYear"].ToString() + " - " + dtYearDetails.Rows[0]["EndMonth"].ToString() + " " + dtYearDetails.Rows[0]["EndYear"].ToString();
            lblYearSetting.Text = strYear;
            intYear = Convert.ToInt32(dtYearDetails.Rows[0]["YearSettings_Id"]);
            ViewState["intYear"] = intYear;
        }
        else
        {
            string strScript = "";
            strScript = strScript + "<script language='javascript'>";
            strScript = strScript + "alert('" + rm.GetString("Msg_DefineYearSettinginOrganizationSettings", ci) + "');location.replace('../Organization Settings/Organization_YearSetting.aspx')";
            strScript = strScript + "</script>";
            Page.RegisterStartupScript("AlertYearClosure", strScript);
        }
    }
    protected void btn_Save_Click(object sender, EventArgs e)
    {
        //Added by MAnjula.P on 07-Feb-2014
        if (ViewState["intYear"] != null)
        {
            intYear = Convert.ToInt32(ViewState["intYear"]);
        }
        CheckYearClosureExistOrNot(true);
        if (Convert.ToString(Session["NotSave"]) == "Yes")
            return;
        //**********************************
        float fltMaxAccumulationDays = 0;
        int successiveYearId = 0;
        int intOrg_LevelId = 0;

        if (ddlCompany.SelectedValue != "0")
        {
            intOrg_LevelId = Convert.ToInt32(ddlCompany.SelectedValue);
        }
        else
        {
            lbl_Error.Text = rm.GetString("Alert_Select_Company", ci);
            return;
        }
        if (Convert.ToInt32(ddl_SuccessiveYear.SelectedValue) == intYear)
        {
            //lbl_Error.Text = "Current Year & Successive Year should not be same";
            base.Message(rm.GetString("Msg_CurrentYearSuccessiveYearshouldnotbesame", ci));
            return;
        }
        //Condition added by Manjula.P on 28-Jan-2014 for checking whether the year having pending or forawrd status in leave alone.
        string strStatus = objYearclosure.SelectLICPendingForwardedRecords_YearClosure(Convert.ToInt32(ddlCompany.SelectedValue), intYear);
        if (strStatus != string.Empty)
        {
            string strScript = "<script language='javascript' type='text/javascript'>";
            strScript += "alert('" + strStatus + "');";
            //strScript += "location.href='TA_UI_Transactions_LeaveSanction.aspx';";
            strScript += " </script>";
            this.RegisterStartupScript("setScript", strScript);
            return;
        }
        //***********************************************************
        else
        {
            successiveYearId = Convert.ToInt32(ddl_SuccessiveYear.SelectedValue);
            DataSet dsSuccessiveYear = objYearSettingsEventData.GetYearSettingsByID(successiveYearId);
            if (dsSuccessiveYear != null && dsSuccessiveYear.Tables.Count > 0)
            {
                if (dsSuccessiveYear.Tables[0].Rows.Count > 0)
                {
                    // check any yearsetting is exist between two (current todate & successive fromdate years)  
                    string yearsettingId = string.Empty;
                    yearsettingId = yearsettingId + successiveYearId.ToString() + "," + intYear.ToString();
                    DateTime dtSuccessiveFromDate = DateTime.Parse(Convert.ToDateTime(dsSuccessiveYear.Tables[0].Rows[0]["fromdate"]).ToShortDateString());
                    DateTime dtCurrentToDate = new DateTime();
                    if (ViewState["dsYeardetails"] != null)
                    {
                        dtYearDetails = (DataTable)ViewState["dsYeardetails"];
                        if (Convert.ToString(dtYearDetails.Rows[0]["ToDate"]) != null)
                            dtCurrentToDate = DateTime.Parse(Convert.ToDateTime(dtYearDetails.Rows[0]["ToDate"]).ToShortDateString());
                    }
                    int existingYearCount = objYearSettingsEventData.CheckYearSettingExistsWhileYearClosing(dtSuccessiveFromDate.ToString(), dtCurrentToDate.ToString(), yearsettingId);
                    if (existingYearCount > 0)
                    {
                        //lbl_Error.Text = "Selected Successive Year is wrong";
                        base.Message(rm.GetString("Msg_SelectedSuccessiveYeariswrong", ci));
                        return;
                    }
                    if (dtSuccessiveFromDate < dtCurrentToDate)
                    {
                        //lbl_Error.Text = "Successive Year should be greater than Current Year";
                        base.Message(rm.GetString("Msg_SuccessiveYearshouldbegreaterthanCurrentYear", ci));
                        return;
                    }
                }
            }
        }
        if (intOrg_LevelId != 0)
        {
            DataSet ds_Year = new DataSet();
            //To get the Actual Leave Types
            DataSet ds_LeaveTypes = new DataSet();
            LeaveEventData objLeaveEventData = new LeaveEventData();
            string UserGroupName = string.Empty;
            string Level = rptcommon.getNodes(intOrg_LevelId, Convert.ToString(Session["LevelRights"]));
            //Check Non-Processed data exists
            DateTime dtmStartDate = new DateTime();
            DateTime dtmEndDate = new DateTime();
            if (ViewState["dsYeardetails"] != null)
            {
                dtYearDetails = (DataTable)ViewState["dsYeardetails"];
                if (Convert.ToString(dtYearDetails.Rows[0]["FromDate"]) != null)
                    dtmStartDate = DateTime.Parse(Convert.ToDateTime(dtYearDetails.Rows[0]["FromDate"]).ToShortDateString());
                if (Convert.ToString(dtYearDetails.Rows[0]["ToDate"]) != null)
                    dtmEndDate = DateTime.Parse(Convert.ToDateTime(dtYearDetails.Rows[0]["ToDate"]).ToShortDateString());
            }
            string strResult = string.Empty;
            if (Convert.ToString(Session["Session_ActiveLanguage"]) == "Resources.Resource_EN")
            {
                strResult = objYearclosure.ProcessDataCountEmployeesYearClsoure(Level, dtmStartDate, dtmEndDate, string.Empty, Convert.ToString(Session["UserGroupName"]), intOrg_LevelId);
            }
            else if (Convert.ToString(Session["Session_ActiveLanguage"]) == "Resources.Resource_AR")
            {
                strResult = objYearclosure.ProcessDataCountEmployeesYearClsoure_Arabic(Level, dtmStartDate, dtmEndDate, string.Empty, Convert.ToString(Session["UserGroupName"]), intOrg_LevelId);
            }
            strResult = string.Empty;
            if (strResult != string.Empty)
            {
                //lbl_Error.Text = strResult;
                base.Message(strResult);
                return;
            }
            ds_LeaveTypes = objLeaveEventData.SelectLeaveTypeDetails(UserGroupName);
            string LeaveTypes = string.Empty;
            string LeaveTypesLeaves = string.Empty;
            if (ds_LeaveTypes.Tables.Count > 0)
            {
                if (ds_LeaveTypes.Tables[0].Rows.Count > 0)
                {
                    foreach (DataRow drLeaveTypes in ds_LeaveTypes.Tables[0].Rows)
                    {
                        if (LeaveTypesLeaves != string.Empty)
                        {
                            LeaveTypesLeaves = LeaveTypesLeaves + ",'" + drLeaveTypes["LeaveType"].ToString();
                        }
                        else
                        {
                            LeaveTypesLeaves = "'" + drLeaveTypes["LeaveType"].ToString();
                        }
                        LeaveTypesLeaves = LeaveTypesLeaves + "'";
                    }
                    LeaveTypesLeaves = LeaveTypesLeaves + "";
                }
            }
            //GETTING THE DETAILS OF YEAR CLOSURE FOR EACH EMPLOYEE AND LEAVE TYPE
            ds_Year = objYearclosure.selectYearClosuredetails(intYear, intOrg_LevelId.ToString(), Convert.ToString(Session["UserGroupName"]));
            DataSet ds_Leave = new DataSet();
            DataTable dt_Year = new DataTable();
            if (ds_Year != null)
            {
                dt_Year = ds_Year.Tables[0];
                if (dt_Year.Rows.Count > 0)
                {
                    bool check = false;
                    foreach (DataRow dr_Year in dt_Year.Rows)
                    {
                        //if (check == false)
                        //{
                        int Empid = Convert.ToInt32(dr_Year["Employee_Id"]);
                        // EMPLOYEE LEAVE POLICY DETAILS
                        //ds_Leave = objYearclosure.selectLeavedetails_Yearclosure(Empid, intYear);
                        //DELETE FROM YEAR CLOSURE FOR ALREADY EXISTING RECORDS WHEN SAME YEAR CLOSED AGAIN
                        //objYearclosure.deleteYearClosure(Convert.ToInt32(ddl_SuccessiveYear.SelectedValue), Empid);
                        //delete Leave Policy & Leave policy details for reinserting
                        //Following code commented by Prabakaran.P for Year closure checking on 15-Feb-08
                        //objEmployee.delete_EmployeeLeavePolicy(Empid, intYear);
                        //we have to change this deletion for the successive year
                        //below line commented for testing
                        objEmployee.delete_EmployeeLeavePolicy(Empid, Convert.ToInt32(ddl_SuccessiveYear.SelectedValue));
                        //}
                        //check = true;
                    }
                    //Added by Manjula.P on 30-Jan-2014 for giving corerect alert message for year closure successed if its closed 
                    bool isthisYearClosed = false;
                    foreach (DataRow dr_Year in dt_Year.Rows)
                    {
                        fltMaxAccumulationDays = 0;
                        int EmpID = Convert.ToInt32(dr_Year["Employee_Id"]);
                        int LeaveID = Convert.ToInt32(dr_Year["LeaveTypeID"]);
                        int orglevel = Convert.ToInt32(dr_Year["OrgLevelID"]);
                        ds_Leave = objYearclosure.selectLeavedetails_Yearclosure(EmpID, intYear);
                        bool blnLeaveTypeExists = false;
                        decimal maxDays_month = 0;

                        decimal maxAccumulationDays = 0;
                        foreach (DataRow dsLeaveRow in ds_Leave.Tables[0].Rows)
                        {
                            if (LeaveID == Convert.ToInt32(dsLeaveRow["LeaveType_Id"]))
                            {
                                blnLeaveTypeExists = true;
                                if (dsLeaveRow["MaxDays_Month"] != null)
                                    maxDays_month = Convert.ToDecimal(dsLeaveRow["MaxDays_Month"]);
                                if (dsLeaveRow["MaxDays_Acc"] != null)
                                    maxAccumulationDays = Convert.ToDecimal((dsLeaveRow["MaxDays_Acc"]));
                            }
                        }
                        if (blnLeaveTypeExists == true)
                        {
                            isthisYearClosed = true;
                            float fltcarry = 0;
                            float fltborrow = 0;
                            float fltcurrentQuota = 0;
                            float fltPrevAvailLeave = 0;
                            float fltCurrAvailLeave = 0;
                            float fltleaveTaken = 0;
                            float fltencash = 0;
                            if (dr_Year["Carry_PrevYear"] == DBNull.Value)
                            {
                                fltcarry = 0;
                            }
                            else
                            {
                                fltcarry = Convert.ToSingle(dr_Year["Carry_PrevYear"].ToString());
                            }
                            if (dr_Year["Borrow_NextYear"] == DBNull.Value)
                            {
                                fltborrow = 0;
                            }
                            else
                            {
                                fltborrow = Convert.ToSingle(dr_Year["Borrow_NextYear"].ToString());
                            }
                            if (dr_Year["Current_Quota"] == DBNull.Value)
                            {
                                fltcurrentQuota = 0;
                            }
                            else
                            {
                                fltcurrentQuota = Convert.ToSingle(dr_Year["Current_Quota"].ToString());
                            }
                            // Get Available Leave from Previous Year
                            if (dr_Year["Available_Leaves"] == DBNull.Value)
                            {
                                fltPrevAvailLeave = 0;
                            }
                            else
                            {
                                fltPrevAvailLeave = Convert.ToSingle(dr_Year["Available_Leaves"].ToString());
                            }
                            if (dr_Year["Leave_Taken"] == DBNull.Value)
                            {
                                fltleaveTaken = 0;
                            }
                            else
                            {
                                fltleaveTaken = Convert.ToSingle(dr_Year["Leave_Taken"].ToString());
                            }
                            if (dr_Year["Encashment"] == DBNull.Value)
                            {
                                fltencash = 0;
                            }
                            else
                            {
                                fltencash = Convert.ToSingle(dr_Year["Encashment"].ToString());
                            }
                            // Calculate the no. of leaves that have to be carried to next year
                            // carry + borrow + current quota -- (1)
                            float flttotal1 = fltcarry + fltborrow + fltcurrentQuota;
                            // leave taken + leave encashed -- (2)
                            float flttotal2 = fltleaveTaken + fltencash;
                            // LEAVE AVAILABLE FOR NEXT YEAR = (1)-(2)
                            float fltnet = flttotal1 - flttotal2;
                            if (fltnet < 0) fltnet = 0;
                            fltPrevAvailLeave = fltnet;
                            //fltPrevAvailLeave = 70;
                            // End Calculation
                            //Checking and Convert to Date Format MM/dd/yyyy
                            gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
                            StrCurrentDate = lblClosedDate.Text;
                            StrCurrentDate = objcls_Common.DateConvertion(gstrDateFormat, StrCurrentDate);
                            // YEAR CLOSURE - UPDATING FOR EACH EMPLOYEE AND LEAVE TYPE
                            //below line commented for testing
                            //if (EmpID == 189 || EmpID == 117)
                            //{
                            //    fltPrevAvailLeave = fltnet;
                            //}
                            objYearclosure.updateYearClosure(orglevel, EmpID, intYear, LeaveID, (fltPrevAvailLeave > (float)maxAccumulationDays) ? (float)maxAccumulationDays : fltPrevAvailLeave, strYear, StrCurrentDate, auEmployeeID, (fltPrevAvailLeave > (float)maxAccumulationDays) ? (fltPrevAvailLeave - (float)maxAccumulationDays) + fltencash : fltencash);
                            float fltquota = 0;
                            DataTable dt_leave = new DataTable();
                            int PolicyId = 0;
                            if (ds_Leave != null)
                            {
                                dt_leave = ds_Leave.Tables[0];
                                // CHECK FOR WHETHER LEAVE CAN BE CARRIED TO NEXT YEAR OR NOT
                                if (dt_leave.Rows.Count > 0)
                                {
                                    foreach (DataRow dr_Leave in dt_leave.Rows)
                                    {
                                        PolicyId = Convert.ToInt32(dr_Leave["Policy_Id"]);
                                        fltMaxAccumulationDays = Convert.ToSingle(dr_Leave["MaxDays_Acc"]);
                                        LeaveTypes = string.Empty;
                                        if (Convert.ToInt32(dr_Leave["LeaveType_Id"]) == LeaveID)
                                        {
                                            if (Convert.ToBoolean(dr_Leave["Carry_ToNextYear"]) == false)
                                            {
                                                fltPrevAvailLeave = 0;
                                            }
                                            //Find the Next year quota Based on the Leave Policy and Actual worked in the Year by a particular employee
                                            if (dr_Leave["Calc_Factor"].ToString() != "0" && dr_Leave["Calc_Factor"].ToString() != "0.0")
                                            {
                                                #region CountFactor
                                                DateTime dtFromDate = DateTime.Parse(dsYeardetails.Tables[0].Rows[0]["Fromdate"].ToString());
                                                DateTime dtToDate = DateTime.Parse(dsYeardetails.Tables[0].Rows[0]["Todate"].ToString());
                                                if (dr_Leave["Leave"].ToString() == "False")
                                                {
                                                    LeaveTypes = string.Empty;
                                                }
                                                else
                                                {
                                                    LeaveTypes = LeaveTypesLeaves;
                                                }
                                                if (dr_Leave["WeekDays"].ToString() != "False")
                                                {
                                                    LeaveTypes = AppendType(LeaveTypes, "Present");
                                                }
                                                if (dr_Leave["WeekOff"].ToString() != "False")
                                                {
                                                    LeaveTypes = AppendType(LeaveTypes, "Weekly Off");
                                                }
                                                if (dr_Leave["Holidays"].ToString() != "False")
                                                {
                                                    LeaveTypes = AppendType(LeaveTypes, "Holiday");
                                                    LeaveTypes = AppendType(LeaveTypes, "RH");
                                                }
                                                Single WorkedDays = objEmployee.GetEmployeeWorkedDays(dr_Year["Employee_Id"].ToString(), LeaveTypes, dtFromDate.ToShortDateString(), dtToDate.ToShortDateString());
                                                //WorkedDays = 300;
                                                if (dr_Leave["MinWorkDays"] != DBNull.Value && dr_Leave["MinWorkDays"].ToString() != string.Empty && dr_Leave["MinWorkDays"].ToString() != "0" && dr_Leave["MinWorkDays"].ToString() != "0.0")
                                                {
                                                    if (WorkedDays >= Convert.ToSingle(dr_Leave["MinWorkDays"]))
                                                    {
                                                        fltquota = WorkedDays / Convert.ToSingle(dr_Leave["Calc_Factor"]);
                                                        if (Convert.ToSingle(dr_Leave["MaxDays_Acc"]) != 0.0)
                                                        {
                                                            if (fltPrevAvailLeave > Convert.ToSingle(dr_Leave["MaxDays_Acc"]))
                                                            {
                                                                fltPrevAvailLeave = Convert.ToSingle(dr_Leave["MaxDays_Acc"]);
                                                            }
                                                        }
                                                        // Available Leave for current = Current Quota + Previous Carry
                                                        //Commeneted + fltPrevAvailLeave; from below line for only checking current quato value with max acc days by Manjula.P on 07-Jan-2014
                                                        fltCurrAvailLeave = fltquota;
                                                        //+ fltPrevAvailLeave;
                                                        if (Convert.ToSingle(dr_Leave["MaxDays_Acc"]) != 0.0)
                                                        {
                                                            if (fltCurrAvailLeave > Convert.ToSingle(dr_Leave["MaxDays_Acc"]))
                                                            {
                                                                //Commented by Manjula.P on 07-Jan-2014 for current avail leave is current quato value alone
                                                                //fltCurrAvailLeave = Convert.ToSingle(dr_Leave["MaxDays_Acc"]);
                                                                fltPrevAvailLeave = Convert.ToSingle(dr_Leave["MaxDays_Acc"]);
                                                                //Here 0 represents the leave type values should be added in quota after reached working days and year closure
                                                                fltCurrAvailLeave = 0;
                                                                //Added by Manjula.P for Current quota
                                                                fltquota = fltCurrAvailLeave;
                                                            }
                                                        }
                                                    }
                                                    else
                                                    {
                                                        fltquota = 0;
                                                    }
                                                }
                                                else
                                                {
                                                    fltquota = 0;
                                                }
                                                #endregion
                                            }
                                            else
                                            {
                                                fltquota = Convert.ToSingle(dr_Leave["MaxDays_applicable"]);
                                                fltCurrAvailLeave = fltquota;
                                                //Check here for Maximum Accumulation days
                                                if (Convert.ToSingle(dr_Leave["MaxDays_Acc"]) != 0.0)
                                                {
                                                    if (fltCurrAvailLeave > Convert.ToSingle(dr_Leave["MaxDays_Acc"]))
                                                    {
                                                        //Commented by Manjula.P on 07-Jan-2014 for current avail leave is current quato value alone
                                                        // fltCurrAvailLeave = Convert.ToSingle(dr_Leave["MaxDays_Acc"]);
                                                        //Previous avail leave is max acc days if the current avail leave is high
                                                        fltPrevAvailLeave = Convert.ToSingle(dr_Leave["MaxDays_Acc"]);
                                                        fltCurrAvailLeave = fltquota;
                                                        //Added by Manjula.P for Current quota
                                                        fltquota = fltCurrAvailLeave;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            DataSet ds_SuccessiveYear = objYearSettingsEventData.GetYearSettingsByID(Convert.ToInt32(ddl_SuccessiveYear.SelectedValue));
                            string from_successive = ds_SuccessiveYear.Tables[0].Rows[0]["Fromdate"].ToString();
                            string to_successive = ds_SuccessiveYear.Tables[0].Rows[0]["Todate"].ToString();
                            //Code modified for successive year addition on 15-Feb-08 by Prabakaran.P
                            //objEmployee.InsertLeavePolicy(EmpID, PolicyId, from_successive, to_successive, auEmployeeID);
                            //Insert Employee Leave Policy 
                            //below line commented for testing
                            objYearclosure.InsertLeavePolicyYearClosure(EmpID, PolicyId, from_successive, to_successive, auEmployeeID, Convert.ToInt32(ddl_SuccessiveYear.SelectedValue));
                            //selecting latest Employee Leave policy inserted
                            int MaxLPID = objEmployee.select_MaxEmpLeavepolicyID();
                            //Convert as days    
                            int intHalfDay = 0;
                            char splitChar = '.';
                            string[] strquota;
                            strquota = Convert.ToString(fltquota).Split(splitChar);
                            if (strquota.Length > 1)
                            {
                                intHalfDay = DecimalChecker(Convert.ToInt32(strquota[1]));
                                if (intHalfDay < 0)
                                {
                                    fltquota = Convert.ToSingle(strquota[0]);
                                }
                                else if (intHalfDay == 0)
                                {
                                    //Quota remains same
                                    int floattemp = Convert.ToInt32(strquota[0]);
                                    if (floattemp < 0)
                                    {
                                        fltquota = (float)(floattemp - 0.5);
                                    }
                                    else
                                    {
                                        fltquota = (float)(floattemp + 0.5);
                                    }
                                }
                                else if (intHalfDay > 0)
                                {
                                    int floattemp = Convert.ToInt32(strquota[0]);
                                    if (floattemp < 0)
                                    {
                                        fltquota = (float)(floattemp - 1.0);
                                    }
                                    else
                                    {
                                        fltquota = (float)(floattemp + 1.0);
                                    }
                                }
                            }
                            //calculation Previously available leaves
                            strquota = Convert.ToString(fltPrevAvailLeave).Split(splitChar);
                            if (strquota.Length > 1)
                            {
                                intHalfDay = DecimalChecker(Convert.ToInt32(strquota[1]));
                                if (intHalfDay < 0)
                                {
                                    fltPrevAvailLeave = Convert.ToSingle(strquota[0]);
                                }
                                else if (intHalfDay == 0)
                                {
                                    //Quota remains same
                                    int floattemp = Convert.ToInt32(strquota[0]);
                                    if (floattemp < 0)
                                    {
                                        fltPrevAvailLeave = (float)(floattemp - 0.5);
                                    }
                                    else
                                    {
                                        fltPrevAvailLeave = (float)(floattemp + 0.5);
                                    }
                                }
                                else if (intHalfDay > 0)
                                {
                                    int floattemp = Convert.ToInt32(strquota[0]);
                                    if (floattemp < 0)
                                    {
                                        fltPrevAvailLeave = (float)(floattemp - 1.0);
                                    }
                                    else
                                    {
                                        fltPrevAvailLeave = (float)(floattemp + 1.0);
                                    }
                                }
                            }
                            //calculation Current AvailLeave available leaves
                            strquota = Convert.ToString(fltCurrAvailLeave).Split(splitChar);
                            if (strquota.Length > 1)
                            {
                                intHalfDay = DecimalChecker(Convert.ToInt32(strquota[1]));
                                if (intHalfDay < 0)
                                {
                                    fltCurrAvailLeave = Convert.ToSingle(strquota[0]);
                                }
                                else if (intHalfDay == 0)
                                {
                                    //Quota remains same
                                    int floattemp = Convert.ToInt32(strquota[0]);
                                    if (floattemp < 0)
                                    {
                                        fltCurrAvailLeave = (float)(floattemp - 0.5);
                                    }
                                    else
                                    {
                                        fltCurrAvailLeave = (float)(floattemp + 0.5);
                                    }
                                }
                                else if (intHalfDay > 0)
                                {
                                    int floattemp = Convert.ToInt32(strquota[0]);
                                    if (floattemp < 0)
                                    {
                                        fltCurrAvailLeave = (float)(floattemp - 1.0);
                                    }
                                    else
                                    {
                                        fltCurrAvailLeave = (float)(floattemp + 1.0);
                                    }
                                }
                            }
                            //insert data in Employee Leave policy details
                            objEmployee.InsertEmpLeavePolicyDetails(EmpID, MaxLPID, PolicyId, LeaveID, Convert.ToDecimal(fltquota), auEmployeeID, maxDays_month);
                            // INSERT YEAR CLOSURE FOR EACH EMPLOYEE AND LEAVE TYPE FOR NEXT YEAR
                            //Insert data in year closure
                            objYearclosure.InsertAfterYearClosure(Convert.ToInt32(ddl_SuccessiveYear.SelectedValue), orglevel, EmpID, LeaveID, (fltPrevAvailLeave > (float)maxAccumulationDays) ? (float)maxAccumulationDays : fltPrevAvailLeave, fltquota, fltCurrAvailLeave, auEmployeeID);
                        }
                    }
                    if (isthisYearClosed == true)
                    {
                        string alert = "<script language='javascript'>";
                        alert += "alert('" + rm.GetString("Alert_YearclosedSuccessfully", ci) + "')";
                        alert += "</script>";
                        Page.RegisterStartupScript("alert", alert);
                        //Added by Manjula.P on 28-Jan-2014 for getting btn_Save button status if the year closure is saved successfully
                        CheckYearClosureExistOrNot(false);
                    }
                    else
                    {
                        string alert = "<script language='javascript'>";
                        alert += "alert('" + rm.GetString("Alert_Theselectedleveldoesnothaveleavedetails", ci) + "')";
                        alert += "</script>";
                        Page.RegisterStartupScript("alert", alert);
                    }
                    //update the Active year bit to true for successive year setting
                    //objYearSettingsEventData.UpdateYearSettingId(Convert.ToInt32(ddl_SuccessiveYear.SelectedValue));
                }
                else
                {
                    string alert = "<script language='javascript'>";
                    alert += "alert('" + rm.GetString("Alert_Theselectedleveldoesnothaveemployeedetails", ci) + "')";
                    alert += "</script>";
                    Page.RegisterStartupScript("alert", alert);
                }
            }
            else
            {
                string alert = "<script language='javascript'>";
                alert += "alert('" + rm.GetString("Alert_Theselectedleveldoesnothaveemployeedetails", ci) + "')";
                alert += "</script>";
                Page.RegisterStartupScript("alert", alert);
            }
        }
        else
        {
            //lbl_Error.Text = "Select Organization Level";
            base.Message(rm.GetString("Alert_Selectallorganizationlevels", ci));
        }
    }
    private int DecimalChecker(int iValue)
    {
        int oValue = -1;
        int cValue = 0;
        if (iValue < 5)
        {
            oValue = -1;
        }
        else
        {
            cValue = iValue % 5;
            if (cValue == 0)
            {
                oValue = 0;
            }
            else if (cValue > 0)
            {
                oValue = 1;
            }
        }
        return oValue;
    }
    private string AppendType(string leaveType, string statusType)
    {
        if (leaveType.IndexOf(statusType) == -1)
        {
            if (leaveType == string.Empty)
            {
                leaveType = leaveType + "'" + statusType + "'";
            }
            else
            {
                leaveType = leaveType + ",'" + statusType + "'";
            }
        }
        return leaveType;
    }
    protected void loadyearsettings()
    {
        try
        {
            DataSet ds = new DataSet();
            ds = objYearSettingsEventData.GetYearsettings();
            ddl_SuccessiveYear.DataTextField = "YearSetting";
            ddl_SuccessiveYear.DataValueField = "YearSettings_Id";
            ddl_SuccessiveYear.DataSource = ds.Tables[0];
            ddl_SuccessiveYear.DataBind();
            //ddl_SuccessiveYear.Items.Insert(0, "-Select-");
            ddl_SuccessiveYear.Items.Insert(0, rm.GetString("Select", ci));
            foreach (ListItem item in ddl_SuccessiveYear.Items)
            {
                item.Attributes.Add("title", item.Text);
            }
        }
        catch
        {
            //
        }
    }
    // Getting Information from resource file and display it in label
    private void LoadStrings(CultureInfo ci)
    {
        lbl_Header.Text = rm.GetString("UserGroups_YearClosure", ci);
        lbl_Year.Text = rm.GetString("PayrollProcess_Year", ci);
        lbl_ClosedDate.Text = rm.GetString("PayrollProcess_ClosedDate", ci);
        btn_Save.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Save", ci);
        btn_Modify.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Modify", ci);
        lbl_IndicatesMandatoryFields.Text = rm.GetString("IndicatesMandatoryFields", ci);
        lbl_SuccessiveYear.Text = rm.GetString("Transaction_SucessiveYear", ci);
        //ddl_SuccessiveYear.Items[0].Text = rm.GetString("Select", ci);
        lblCompany.Text = rm.GetString("EntranceMaster_Company", ci);
    }
    protected void btn_Modify_Click(object sender, EventArgs e)
    {
        Response.Redirect("TA_UI_Transactions_YearClosureModify.aspx");
    }
    /// <summary>
    /// Added by Manjula.P on 28-Jan-2014 for checking whether the yearclosure is already saved for the level and successive year
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void ddl_SuccessiveYear_SelectedIndexChanged(object sender, EventArgs e)
    {
        CheckYearClosureExistOrNot(false);

    }
    /// <summary>
    ///  Added by Manjula.P on 28-Jan-2014 for checking whether the yearclosure is already saved for the level and successive year
    /// </summary>
    public void CheckYearClosureExistOrNot(bool needMessage)
    {
        if (ddlCompany.SelectedValue != string.Empty)
        {
            Session["NotSave"] = "";
            DataSet ds_YearLevel = objYearclosure.selectYearClosuredetails(intYear, Convert.ToString(ddlCompany.SelectedValue), Convert.ToString(Session["UserGroupName"]));
            DataTable dt_Level = ds_YearLevel.Tables[0];
            bool yesCount = false;
            for (int i = 0; i < dt_Level.Rows.Count; i++)
            {
                int intExistCount = Convert.ToInt32(objYearclosure.CheckYearClosureExistOrNot(Convert.ToInt32(dt_Level.Rows[i]["OrgLevelId"]), intYear));
                //I.e means the year closure already done
                if (intExistCount > 0)
                {
                    yesCount = true;
                    break;
                }
            }
            if (yesCount == true)
            {
                if (needMessage == true)
                {
                    base.Message(rm.GetString("YearClosure_Already_Exists", ci));
                    Session["NotSave"] = "Yes";
                }
                else
                    btn_Save.Enabled = false;
            }
            else
            {
                btn_Save.Enabled = true;
            }
        }
    }
    protected void ddlCompany_SelectedIndexChanged(object sender, EventArgs e)
    {
        CheckYearClosureExistOrNot(false);
        ScriptManager.RegisterStartupScript(this, GetType(), "showalert", "LoadDropdown()", true);
    }
}
