using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Globalization;
using System.Resources;
using System.Threading;
using System.Net.Mail;
using System.Net;
using System.Text;
public partial class Transactions_TA_UI_Transactions_MultipleLeaveApplicationAdd : Base.BasePage
{
    DataSet dsLeaveTypesData = new DataSet();
    DataSet dsHolidays = new DataSet();
    DataSet dsLeaveTypesLOPDays = new DataSet();
    DataSet ds_EmployeeDetails = new DataSet();
    DataSet dsRemainingNoOfLeaves = new DataSet();
    DataSet dsYear = new DataSet();
    DataSet ds = new DataSet();
    Base.BasePage objBase = new Base.BasePage();
    LeaveApplicationEventData_Angler objLeaveApplicationEventData = new LeaveApplicationEventData_Angler();
    cls_Common objcls_Common = new cls_Common();
    HolidayEventData objHolidayEventData = new HolidayEventData();
    ShiftExchangeEventData objShiftExchangeEventData = new ShiftExchangeEventData();
    PermissionEventData objPermissionEventData = new PermissionEventData();
    MonthClosureEventData objMonthClosure = new MonthClosureEventData();
    EmployeeEventData objEmployeeEventData = new EmployeeEventData();
    CCGroupEventData_Angler objCCGroup = new CCGroupEventData_Angler();
    string gstrDateFormat = string.Empty;
    string gstrYearSettingStartDate = string.Empty;
    string gstrYearSettingsEndDate = string.Empty;
    string gstrNextYearSettingStartDate = string.Empty;
    string gstrNextYearSettingsEndDate = string.Empty;
    string strEmployeeName, strEmployeeCodeId, strEmpFirstName, strEmpLastName, strlevelName, EmployeeEamilId, strYearSettingsFromdate, strYearSettingsTodate, strLeaveAvailedYear, strLeaveAvailedMonth;
    string gstrDateOfJoining = string.Empty;
    string EmployeeCodeId = string.Empty;
    string gstrSwipeCardNo = string.Empty;
    string strLeaveFromDate = string.Empty;
    string strLeaveToDate = string.Empty;
    string strLeaveCategory = string.Empty;
    string strLeaveTypeId = string.Empty;
    string strLeaveFromSession = string.Empty;
    string strLeaveToSession = string.Empty;
    string strHtmlLeaveDetails = string.Empty;
    string strLeaveAvailed = string.Empty;
    string strCrossDate = string.Empty;
    string strLeaveAvailedInFirstMonth = string.Empty;
    string strLeaveAvailedInSecondMonth = string.Empty;
    string strLeaveAvailedInFirstMonthName = string.Empty;
    string strLeaveAvailedInSecondMonthName = string.Empty;
    DataTable dtLeaveavailedinMonth = new DataTable();
    double fltLeaveTakenInMonth = 0.0;
    double dblNoOfDaysApplied = 0.0;
    int testvalue;
    int gintWeeklyOffHoliday = 0;
    double dblLeaveAvailedYear = 0.0;
    double dblLeaveAvailedMonth = 0.0;
    bool blnCheckEmail;
    bool isValidGrid;
    DataSet dtContinousDB = new DataSet();
    DateTime DatePre = new DateTime();
    DateTime DateNext = new DateTime();
    /// <summary>
    /// Instance of Resource Manager to get Resource file contents
    /// </summary>
    ResourceManager objResourceManager;
    /// <summary>
    /// Instance of Culture Info to set the current culture
    /// </summary>
    CultureInfo objCultureInfo;
    /// <summary>
    /// Instance of the class Cls_CheckUser
    /// </summary>
    Cls_CheckUser objCheckUser = new Cls_CheckUser();
    /// <summary>
    /// Dataset for storing User rights details
    /// </summary>
    DataSet dsCheckuser = new DataSet();
    DataSet dsEmployeeDetails = new DataSet();
    protected override void Page_Load(object sender, EventArgs e)
    {
        // session checking
        base.Page_Load(sender, e);
        if (!Page.IsPostBack)
        {
            objcls_Common.menu("LeaveTransaction", "22");
        }
        //if (Request.UrlReferrer != null)
        //{
        //    string GetURL = Request.UrlReferrer.ToString();
        //}
        //else
        //{
        //    Response.Redirect("TA_UI_Transactions_LeaveApplication.aspx");
        //}
        //get the culture info to set the language               
        string strSourceLanguage;
        strSourceLanguage = Session["Session_ActiveLanguage"].ToString();
        objResourceManager = new ResourceManager(strSourceLanguage, System.Reflection.Assembly.Load("App_GlobalResources"));
        objCultureInfo = Thread.CurrentThread.CurrentCulture;
        site.SiteMapProvider = Convert.ToString(Session["SiteMapProvider"]);
        //Call to a function to get the display string from the resource file
        LoadStrings(objCultureInfo);
        //Call to a function to implement the UserRights
        UserRights();
        //Assign the null value for the session value parent level id
        Session["ParentLevelID"] = null;
        //Clears the Employee Names from drop down list
        ddlEmployeeNames.Items.Clear();
        ddlEmployeeNames.Items.Add("-Select-");
        //Display user Name 
        DateTime dtCurrentDate = Convert.ToDateTime(System.DateTime.Today.Date.ToShortDateString());
        //lblLeaveApplicationDateData.Text = dtCurrentDate.ToString(Session["MDateFormat"].ToString());
        if (Session["User"] == null)
        {
            Response.Redirect("../index.aspx");
        }
        if (Session["User"].ToString() == "")
        {
            Response.Redirect("../index.aspx");
        }
        cls_Common objClassCommon = new cls_Common();
        //Call to a function to get the Year setting details
        dsYear = objClassCommon.GetYearsetting();
        if (dsYear.Tables[0].Rows.Count <= 0)
        {
            string strScript = "";
            strScript = strScript + "<script language='javascript'>";
            strScript = strScript + "alert('Define Year Setting in Organization Settings');location.replace('../Organization Settings/Organization_YearSetting.aspx')";
            strScript = strScript + "</script>";
            Page.RegisterStartupScript("AlertLeavePolicyYear", strScript);
        }
        else
        {
            strYearSettingsFromdate = dsYear.Tables[0].Rows[0]["FromDate"].ToString();
            strYearSettingsTodate = dsYear.Tables[0].Rows[0]["ToDate"].ToString();
            ViewState["YearSettings_Id"] = dsYear.Tables[0].Rows[0]["YearSettings_Id"].ToString();
            dsYear.Dispose();
        }
        if (Session["UserGroupName"].ToString() == "SuperAdmin" || Session["HasSpecialRights"].ToString() == "True")
        {
            divEmployees.Visible = false;
            divAdmin.Visible = true;
            phrLeaveApplicationAdd.Visible = true;
            divIntimationType.Visible = true;
            if (Convert.ToString(hdnEmployeeId.Value) != string.Empty)
            {
                int intEmployeeId = Convert.ToInt32(hdnEmployeeId.Value);
                DataSet ds_EmployeeDetails = new DataSet();
                ds_EmployeeDetails = objEmployeeEventData.Select_EmployeeDetailsNewbyId(intEmployeeId);
                if (ds_EmployeeDetails.Tables[0].Rows.Count > 0)
                {
                    string strEmpFirstName = ds_EmployeeDetails.Tables[0].Rows[0]["Employee_FirstName"].ToString();
                    string strEmpLastName = ds_EmployeeDetails.Tables[0].Rows[0]["Employee_LastName"].ToString();
                    lblEmployeeNameData.Text = strEmpFirstName + " " + strEmpLastName;
                    // lblEmployeeNameData.Style.Add("", "");
                    lblEmployeeIdData.Text = ds_EmployeeDetails.Tables[0].Rows[0]["Employee_Code_Id"].ToString();
                    ddlEmployeeNames.SelectedItem.Text = lblEmployeeIdData.Text + " - " + lblEmployeeNameData.Text;
                    //if (rbtnP.Checked == true)
                    //{
                    //    lstInformTo.Enabled=false;
                    //}
                }
                hdnApplicationYear.Value = ViewState["YearSettings_Id"].ToString();
                ds = objcls_Common.GetSuccessiveYearsetting();
                if (ds.Tables.Count > 0)
                {
                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        hdnSuccessiveYear.Value = ds.Tables[0].Rows[0][0].ToString();
                        //   rbtnSuccessiveYear.Enabled = true;
                    }
                    else
                    {
                        //   rbtnSuccessiveYear.Enabled = false;
                    }
                }
            }
        }
        else
        {
            hdnApplicationYear.Value = ViewState["YearSettings_Id"].ToString();
            ds = objcls_Common.GetSuccessiveYearsetting();
            if (ds.Tables.Count > 0)
            {
                if (ds.Tables[0].Rows.Count > 0)
                {
                    hdnSuccessiveYear.Value = ds.Tables[0].Rows[0][0].ToString();
                    // if (rbtnCurrentYear.Checked == true)
                    // {
                    hdnApplicationYear.Value = ViewState["YearSettings_Id"].ToString();
                    //    }
                    //    else if (rbtnSuccessiveYear.Checked == true)
                    //    {
                    //        hdnSuccessiveYear.Value = ds.Tables[0].Rows[0][0].ToString();
                    //    }
                    //    rbtnSuccessiveYear.Enabled = true;
                }
                //else
                //{
                //    rbtnSuccessiveYear.Enabled = false;
                //}
            }
            else
            {
                //rbtnSuccessiveYear.Enabled = false;
            }
            divEmployees.Visible = true;
            phrLeaveApplicationAdd.Controls.Clear();
            divAdmin.Visible = false;
            divIntimationType.Visible = false;
            hdnEmployeeId.Value = Session["EmpAutoId"].ToString();
            GetEmployeeName();
        }
        btnAdd.Focus();
        //Fill the next Year Settings Detail
        DataSet ds_NextYear = new DataSet();
        ds_NextYear = objcls_Common.GetNextYearsetting_Angler();
        if (ds_NextYear.Tables[0].Rows.Count > 0)
        {
            gstrNextYearSettingStartDate = ds_NextYear.Tables[0].Rows[0]["FromDate"].ToString();
            gstrNextYearSettingsEndDate = ds_NextYear.Tables[0].Rows[0]["ToDate"].ToString();
            ViewState["NextYearSettings_Id"] = ds_NextYear.Tables[0].Rows[0]["YearSettings_Id"].ToString();
            ds_NextYear.Dispose();
        }
        if (!IsPostBack)
        {
            hdnEmployeeId1.Value = Convert.ToString(Session["EmployeeCodeId"]);
            DataTable districtDetails = new DataTable();
            districtDetails = LoadDataFromGridFirstTime();
            DataSet districtData = new DataSet();
            districtData.Tables.Add(districtDetails);
            gvTestGrid.DataSource = districtData;
            gvTestGrid.DataBind();
            int levelId;
            if (Session["ParentLevelID"] == null)
            {
                levelId = Convert.ToInt32(Session["LeaveParentLevelID"]);
                Session["ParentLevelID"] = null;
            }
            else
            {
                levelId = Convert.ToInt32(Session["ParentLevelID"]);
                Session["LeaveParentLevelID"] = Convert.ToInt32(Session["ParentLevelID"]);
                Session["ParentLevelID"] = null;
            }
            #region Code By A.K.T.Moorthi For Get The Inform To(User Name) List
            //string Level = new Rpt_Common().getNodes(Convert.ToInt32(Session["LeaveParentLevelID"]), Convert.ToString(Session["LevelRights"]));
            //lstInformTo.DataSource = objLeaveApplicationEventData.GetEmployeeForLeaveApplication(Level, Session["UserGroupName"].ToString(), Convert.ToString(Session["GradeLevel"]), levelId).Tables[0];
            lstInformTo.DataSource = objLeaveApplicationEventData.GetInformToEmployee();
            lstInformTo.DataTextField = "EmployeeName";
            lstInformTo.DataValueField = "EmployeeName";
            //lstInformTo.DataTextField = "Employee Name";
            //lstInformTo.DataValueField = "Employee Name";
            lstInformTo.DataBind();
            #endregion
            LoadComboInGridFirstTime(districtDetails);
        }
        #region Code By A.K.T.MOORTHI For Pervious Leave Details
        if (Convert.ToString(hdnEmployeeId.Value) != string.Empty)
        {
            DataSet dstLeave = objLeaveApplicationEventData.GetPreviousLeaveDetails(Convert.ToInt16(hdnEmployeeId.Value), string.Empty, "P");
            grdFYLeave.DataSource = dstLeave.Tables[0];
            grdFYLeave.DataBind();
            grdCMLeave.DataSource = dstLeave.Tables[1];
            grdCMLeave.DataBind();
        }
        else
        {
            grdFYLeave.DataSource = null;
            grdFYLeave.DataBind();
            grdCMLeave.DataSource = null;
            grdCMLeave.DataBind();
        }
        string strDisable = "true";
        if (rbtnUPWI.Checked)
        {
            strDisable = "false";
        }
        Page.RegisterStartupScript("Disabled", "<script type=\"text/javascript\"> DisabledInformTo(" + strDisable + ");</script>");
        #endregion
    }
    #region Employee Name.
    /// <summary>
    /// Get Employee Name Based on EmployeeId
    /// </summary>
    public void GetEmployeeName()
    {
        if (Session["user"] == null || Session["user"].ToString() == "")
        {
            Response.Redirect("../Index.aspx");
        }
        else
        {
            lblEmployeeIdData.Text = Convert.ToString(Session["EmployeeCodeId"]);
            int intEmployeeId = Convert.ToInt32(Session["EmpAutoId"]);
            DataSet ds_EmployeeDetails = new DataSet();
            ds_EmployeeDetails = objEmployeeEventData.Select_EmployeeDetailsNewbyId(intEmployeeId);
            if (ds_EmployeeDetails.Tables[0].Rows.Count > 0)
            {
                string strEmpFirstName = ds_EmployeeDetails.Tables[0].Rows[0]["Employee_FirstName"].ToString();
                string strEmpLastName = ds_EmployeeDetails.Tables[0].Rows[0]["Employee_LastName"].ToString();
                lblEmployeeNameData.Text = strEmpFirstName + " " + strEmpLastName;
            }
            //Fill the Year Settings Detail
            DataSet ds_Year = new DataSet();
            ds_Year = objcls_Common.GetYearsetting();
            if (ds_Year.Tables[0].Rows.Count > 0)
            {
                gstrYearSettingStartDate = ds_Year.Tables[0].Rows[0]["FromDate"].ToString();
                gstrYearSettingsEndDate = ds_Year.Tables[0].Rows[0]["ToDate"].ToString();
                ViewState["YearSettings_Id"] = ds_Year.Tables[0].Rows[0]["YearSettings_Id"].ToString();
                ds_Year.Dispose();
            }
            dblLeaveAvailedYear = objLeaveApplicationEventData.GetLeaveSummary(DateTime.Parse(gstrYearSettingStartDate), DateTime.Parse(gstrYearSettingsEndDate), Convert.ToInt32(hdnEmployeeId.Value));
            DateTime startDayOfMonth = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
            DateTime endDayOfMonth = startDayOfMonth.AddMonths(1).AddDays(-1);
            dblLeaveAvailedMonth = objLeaveApplicationEventData.GetLeaveSummary(startDayOfMonth, endDayOfMonth, Convert.ToInt32(hdnEmployeeId.Value));
            lblLeaveAvailedMonthData.Text = dblLeaveAvailedMonth.ToString();
            lblLeaveAvailedYearData.Text = dblLeaveAvailedYear.ToString();
        }
    }
    #endregion
    protected void gvTestGrid_Sorting(object sender, GridViewSortEventArgs e)
    {
    }
    protected void gvTestGrid_RowCreated(object sender, GridViewRowEventArgs e)
    {
    }
    protected void gvTestGrid_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            LinkButton l = (LinkButton)e.Row.FindControl("LinkButton1");
            l.Attributes.Add("onclick", "javascript:return " +
            "confirm('Are you sure you want to delete this record " +
            DataBinder.Eval(e.Row.DataItem, "SlNo") + "')");
            if (Page.IsPostBack)
            {
                DropDownList ddlLeaveCategory = (DropDownList)e.Row.FindControl("ddlLeaveCategory");
                DropDownList ddlLeaveTypes = (DropDownList)e.Row.FindControl("ddlLeaveTypes");
                Label lblNoOfLeaves = (Label)e.Row.FindControl("lblNoOfLeaves");
                // string strLeaveTypes = ddlLeaveTypes.SelectedValue.ToString();
                DropDownList ddlSessionsFrom = (DropDownList)e.Row.FindControl("ddlSessionsFrom");
                DropDownList ddlSessionsTo = (DropDownList)e.Row.FindControl("ddlSessionsTo");
                DataTable dtLeaveCategory = new DataTable();
                if (Session["SessionGridLeaveCategory"] != null)
                {
                    dtLeaveCategory = (DataTable)Session["SessionGridLeaveCategory"];
                    string strSLNO = DataBinder.Eval(e.Row.DataItem, "SlNo").ToString();
                    if (Session["DeletedRowId"] != null)
                    {
                        if (Session["DeletedRowId"].ToString() != string.Empty)
                        {
                            if (Convert.ToInt32(strSLNO) >= Convert.ToInt32(Session["DeletedRowId"]))
                            {
                                strSLNO = Convert.ToString(Convert.ToInt32(strSLNO) + 1);
                            }
                        }
                    }
                    string strLeaveCategoryValue = string.Empty;
                    string strLeaveTypes = string.Empty;
                    string strNoOfLeaves = string.Empty;
                    dtLeaveCategory.DefaultView.RowFilter = "SLNO=" + strSLNO;
                    if (dtLeaveCategory.DefaultView.ToTable().Rows.Count > 0)
                    {
                        strLeaveCategoryValue = dtLeaveCategory.DefaultView.ToTable().Rows[0]["LeaveCategory"].ToString();
                        strLeaveTypes = dtLeaveCategory.DefaultView.ToTable().Rows[0]["LeaveTypes"].ToString();
                        strNoOfLeaves = dtLeaveCategory.DefaultView.ToTable().Rows[0]["NoOfLeaves"].ToString();
                        if (ddlLeaveCategory != null)
                        {
                            ddlLeaveCategory.SelectedValue = strLeaveCategoryValue;
                        }
                        if (ddlLeaveTypes != null)
                        {
                            ddlLeaveTypes.SelectedValue = strLeaveTypes;
                        }
                        if (ddlSessionsFrom != null)
                        {
                            ddlSessionsFrom.SelectedValue = dtLeaveCategory.DefaultView.ToTable().Rows[0]["LeaveSessionsFrom"].ToString();
                        }
                        if (ddlSessionsTo != null)
                        {
                            ddlSessionsTo.SelectedValue = dtLeaveCategory.DefaultView.ToTable().Rows[0]["LeaveSessionsTo"].ToString();
                        }
                        if (lblNoOfLeaves != null)
                        {
                            lblNoOfLeaves.Text = strNoOfLeaves;
                        }
                    }
                }
            }
            else
            {
                DropDownList ddlLeaveCategory = (DropDownList)e.Row.FindControl("ddlLeaveCategory");
                if (ddlLeaveCategory != null)
                {
                    if (hdnEmployeeId.Value == string.Empty)
                    {
                        ddlLeaveCategory.SelectedValue = "3";
                    }
                    else
                    {
                        ddlLeaveCategory.SelectedValue = "1";
                    }
                    //ddlLeaveCategory.SelectedIndexChanged += new EventHandler(ddlLeaveCategory_SelectedIndexChanged);
                }
            }
        }
    }
    /// <summary>
    /// to create a method for checking combined leave with CL and SL/Comp Off in add New row button, By Manjula.P on 24-May-2013
    /// </summary>
    /// <param name="?"></param>
    /// <returns></returns>
    public bool CheckCombinedinAddRow(DataTable dt)
    {
        isValidGrid = true;
        return isValidGrid;
        #region Commented By A.K.T.Moorthi To Remove The Validation As Per HR Requirement(27-Jan-2014)
        //try
        //{
        //    if (dt.Rows.Count > 1)
        //    {
        //        for (int i = 0; i < dt.Rows.Count; i++)
        //        {
        //            DateTime FirstRowDate;
        //            DateTime NextCombinedDate;
        //            string LeaveTpeName;
        //            string LeaveCategoryName;
        //            DateTime NextRowDate;
        //            string LeaveTpeName1 = "";
        //            string LeaveCategoryName1 = "";
        //            string SlNo = "";
        //            if ((i + 1) < dt.Rows.Count)
        //            {
        //                FirstRowDate = Convert.ToDateTime(dt.Rows[i]["LeaveTo"]);
        //                NextCombinedDate = RecursionHoliday(FirstRowDate.AddDays(1), 'P');
        //                //ist row
        //                LeaveTpeName = Convert.ToString(dt.Rows[i]["LeaveTypesName"]);
        //                LeaveCategoryName = Convert.ToString(dt.Rows[i]["LeaveCategoryName"]);
        //                //2nd row
        //                NextRowDate = Convert.ToDateTime(dt.Rows[i + 1]["LeaveFrom"]);
        //                LeaveTpeName1 = Convert.ToString(dt.Rows[i + 1]["LeaveTypesName"]);
        //                LeaveCategoryName1 = Convert.ToString(dt.Rows[i + 1]["LeaveCategoryName"]);
        //                SlNo = "1";
        //                //checking whether the give dates are continoues dates or not.
        //                if (NextRowDate == NextCombinedDate)
        //                {
        //                    //if leavetypename is CL
        //                    if (LeaveTpeName == "CL" && LeaveCategoryName == "Leave")
        //                    {
        //                        if (LeaveTpeName1 == "SL" || LeaveCategoryName1 == "Comp Off")
        //                        {
        //                            Message("CL cannot be combined with Comp Off/SL");
        //                            return false;
        //                        }
        //                    }
        //                    //if leavetype is SL/Comp Off
        //                    else if (LeaveTpeName == "SL" || LeaveCategoryName == "Comp Off")
        //                    {
        //                        if (LeaveTpeName1 == "CL" && LeaveCategoryName1 == "Leave")
        //                        {
        //                            Message("SL/Comp Off cannot be combined with CL");
        //                            return false;
        //                        }
        //                    }
        //                }
        //            }
        //        }
        //    }
        //    else
        //    {
        //        isValidGrid = true;
        //    }
        //    return isValidGrid;
        //}
        //catch (Exception ex)
        //{
        //    return false;
        //}
        //return isValidGrid; 
        #endregion
    }
    /// <summary>
    /// to checking contious leave applied days by Manjula.P on 24-May-2013
    /// </summary>
    /// <param name="dt"></param>
    /// <returns></returns>
    public bool CheckContinousAppliedDays(DataTable dt)
    {
        isValidGrid = true;
        try
        {
            if (dt.Rows.Count > 1)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    if ((i + 1) < dt.Rows.Count)
                    {
                        DateTime FirstRowDate;
                        DateTime NextRowDate;
                        DateTime NextCombinedDate;
                        FirstRowDate = Convert.ToDateTime(dt.Rows[i]["LeaveTo"]);
                        NextCombinedDate = RecursionHoliday(FirstRowDate.AddDays(1), 'P');
                        //2nd row
                        NextRowDate = Convert.ToDateTime(dt.Rows[i + 1]["LeaveFrom"]);
                        if (FirstRowDate == NextRowDate)
                            return false;
                        else if (NextRowDate == NextCombinedDate)
                            return false;
                    }
                }
                return isValidGrid;
            }
            else
            {
                isValidGrid = true;
            }
            return isValidGrid;
        }
        catch (Exception ex)
        {
            return false;
        }
    }
    protected void btnNewRow_Click(object sender, EventArgs e)
    {
        if (hdnEmployeeId.Value == string.Empty)
        {
            Message("Select Employee");
            return;
        }
        //Checking and Convert to Date Format MM/dd/yyyy
        gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
        dsRemainingNoOfLeaves.Clear();
        DataTable districtDetails = LoadDataFromGridWithLeaveCategory();
        if (DateConvertion(gstrDateFormat, districtDetails.Rows[0]["LeaveFrom"].ToString()))
        {
        }
        else
        {
            Message("Invalid Date Format");
            return;
        }
        LoadRemainingLeaves(districtDetails.Rows[0]["LeaveFrom"].ToString());
        LoadCompOffDays();
        Session["SessionGridLeaveCategory"] = districtDetails;
        int iterator = districtDetails.Rows.Count;
        DataTable dtFirstTable = new DataTable();
        DataTable dtSecondTable = new DataTable();
        string strFirstLeaveFrom = string.Empty;
        string strFirstLeaveTo = string.Empty;
        string strFirstSessionFrom = string.Empty;
        string strFirstSessionTo = string.Empty;
        string strSecondLeaveFrom = string.Empty;
        string strSecondLeaveTo = string.Empty;
        string strSecondSessionFrom = string.Empty;
        string strSecondSessionTo = string.Empty;
        string NoOfLeaves = string.Empty;
        int i, j = 0;
        if (iterator == 1)
        {
            strFirstLeaveFrom = districtDetails.Rows[0]["LeaveFrom"].ToString();
            strFirstLeaveTo = districtDetails.Rows[0]["LeaveTo"].ToString();
            strFirstSessionFrom = districtDetails.Rows[0]["LeaveSessionsFrom"].ToString();
            strFirstSessionTo = districtDetails.Rows[0]["LeaveSessionsTo"].ToString();
            if (strFirstLeaveFrom == string.Empty || strFirstLeaveTo == string.Empty)
            {
                Message("Leave Dates should not be empty");
                return;
            }
            if (DateConvertion(gstrDateFormat, strFirstLeaveFrom))
            {
            }
            else
            {
                Message("Invalid Date Format");
                return;
            }
            if (DateConvertion(gstrDateFormat, strFirstLeaveTo))
            {
            }
            else
            {
                Message("Invalid Date Format");
                return;
            }
            //Added by Manjula.P on 13-May-2014 for datetime conversions in dd/mm/yyyy format.
            strFirstLeaveTo = objcls_Common.DateConvertion(gstrDateFormat, strFirstLeaveTo);
            strFirstLeaveFrom = objcls_Common.DateConvertion(gstrDateFormat, strFirstLeaveFrom);
            if (DateDifference(DateTime.Parse(strFirstLeaveFrom), DateTime.Parse(strFirstLeaveTo)) < 0)
            {
                Message("In Leave-1 To Date should be greater than or equal to Leave From Date");
                return;
            }
            if (strFirstLeaveFrom == strFirstLeaveTo)
            {
                if (strFirstSessionFrom == "2" && strFirstSessionTo == "1")
                {
                    Message("Invalid Session Selection in Leave-1");
                    return;
                }
            }
            if (Session["UserGroupName"].ToString() == "SuperAdmin" || Session["HasSpecialRights"].ToString() == "True")
            {
            }
            else
            {
                string strTodaysDate = DateTime.Now.ToString(Session["MDateFormat"].ToString());
                strTodaysDate = objcls_Common.DateConvertion(gstrDateFormat, strTodaysDate);
                if ((Convert.ToDateTime(strFirstLeaveFrom) < Convert.ToDateTime(strTodaysDate)) || (Convert.ToDateTime(strFirstLeaveTo) < Convert.ToDateTime(strTodaysDate)))
                {
                    Message("Leave should not be applied for past days");
                    return;
                }
            }
        }
        else
        {
            //string[] checkDuplicationDate = new string[iterator];
            //for (int ii = 0; ii < checkDuplicationDate.Length; ii++)
            //{
            //    strFirstLeaveFrom = dtFirstTable.Rows[ii]["LeaveFrom"].ToString();
            //    strFirstLeaveTo = dtFirstTable.Rows[ii]["LeaveTo"].ToString();
            //    int iDays = DateDifference(DateTime.Parse(strFirstLeaveFrom), DateTime.Parse(strFirstLeaveTo));
            //    double dsEmpCat = 0.0;
            //    dsEmpCat = objLeaveApplicationEventData.GetEmployeeCategoryDetailForSat(Convert.ToInt32(hdnEmployeeId.Value));
            //    //string dtSat = string.Empty;
            //    DateTime dtLeavestart = Convert.ToDateTime(strFirstLeaveFrom);
            //    DateTime dtLeaveEnd = Convert.ToDateTime(strFirstLeaveTo);
            //    for (int chkdup = 0; chkdup < iDays; chkdup++)
            //    {
            //        string dtSat = string.Empty;
            //        dtLeavestart = Convert.ToDateTime(strLeaveFromDate);
            //        dtLeavestart = dtLeavestart.AddDays(chkdup);
            //        dtSat = dtLeavestart.DayOfWeek.ToString();
            //        if (dtSat == "Saturday")
            //        {
            //            if (dsEmpCat <= 4)
            //            {
            //                checkDuplicationDate[ii] = dtLeavestart.ToString();
            //            }
            //        }
            //    }
            //}
            //for (int jj = 0; j < checkDuplicationDate.Length; j++)
            //{
            //    for (int k = 0; k < checkDuplicationDate.Length; k++)
            //    {
            //        if (checkDuplicationDate.Length > 1)
            //        {
            //            if (checkDuplicationDate[jj] != null && checkDuplicationDate[k] != null && checkDuplicationDate[jj] == checkDuplicationDate[k])
            //            {
            //            }
            //        }
            //    }
            //}
            for (i = 1; i < iterator; i++)
            {
                j = i + 1;
                districtDetails.DefaultView.RowFilter = "SLNO=" + i;
                dtFirstTable = districtDetails.DefaultView.ToTable();
                strFirstLeaveFrom = dtFirstTable.Rows[0]["LeaveFrom"].ToString();
                strFirstLeaveTo = dtFirstTable.Rows[0]["LeaveTo"].ToString();
                strFirstSessionFrom = dtFirstTable.Rows[0]["LeaveSessionsFrom"].ToString();
                strFirstSessionTo = dtFirstTable.Rows[0]["LeaveSessionsTo"].ToString();
                districtDetails.DefaultView.RowFilter = "SLNO=" + j;
                dtSecondTable = districtDetails.DefaultView.ToTable();
                strSecondLeaveFrom = dtSecondTable.Rows[0]["LeaveFrom"].ToString();
                strSecondLeaveTo = dtSecondTable.Rows[0]["LeaveTo"].ToString();
                strSecondSessionFrom = dtSecondTable.Rows[0]["LeaveSessionsFrom"].ToString();
                strSecondSessionTo = dtSecondTable.Rows[0]["LeaveSessionsTo"].ToString();
                if (strFirstLeaveFrom == string.Empty || strFirstLeaveTo == string.Empty || strSecondLeaveFrom == string.Empty || strSecondLeaveTo == string.Empty)
                {
                    Message("Leave Dates should not be empty");
                    return;
                }
                if (DateConvertion(gstrDateFormat, strFirstLeaveFrom))
                {
                }
                else
                {
                    Message("Invalid Date Format");
                    return;
                }
                if (DateConvertion(gstrDateFormat, strFirstLeaveTo))
                {
                }
                else
                {
                    Message("Invalid Date Format");
                    return;
                }
                if (DateConvertion(gstrDateFormat, strSecondLeaveFrom))
                {
                }
                else
                {
                    Message("Invalid Date Format");
                    return;
                }
                if (DateConvertion(gstrDateFormat, strSecondLeaveTo))
                {
                }
                else
                {
                    Message("Invalid Date Format");
                    return;
                }
                if (DateDifference(DateTime.Parse(strFirstLeaveFrom), DateTime.Parse(strFirstLeaveTo)) < 0)
                {
                    Message("In Leave-" + i.ToString() + ", To Date should be greater than or equal to Leave From Date");
                    return;
                }
                if (DateDifference(DateTime.Parse(strSecondLeaveFrom), DateTime.Parse(strSecondLeaveTo)) < 0)
                {
                    Message("In Leave-" + j.ToString() + ", To Date should be greater than or equal to Leave From Date");
                    return;
                }
                if (DateTime.Parse(strFirstLeaveTo) > DateTime.Parse(strSecondLeaveFrom))
                {
                    Message("Leave-" + j.ToString() + " From Date should be greater than Leave-" + i.ToString() + " To Date");
                    return;
                }
                if (DateTime.Parse(strFirstLeaveTo) == DateTime.Parse(strSecondLeaveFrom))
                {
                    if (strFirstSessionTo == "2")
                    {
                        Message("Leave Days/Sessions Over Lapped in Leave-" + i.ToString() + " and Leave-" + j.ToString());
                        return;
                    }
                    if (strSecondSessionFrom == "1")
                    {
                        Message("Leave Days/Sessions Over Lapped in Leave-" + i.ToString() + " and Leave-" + j.ToString());
                        return;
                    }
                }
                if (strFirstLeaveFrom == strFirstLeaveTo)
                {
                    if (strFirstSessionFrom == "2" && strFirstSessionTo == "1")
                    {
                        Message("Invalid Session Selection in Leave-" + i.ToString());
                        return;
                    }
                }
                if (strSecondLeaveFrom == strSecondLeaveTo)
                {
                    if (strSecondSessionFrom == "2" && strSecondSessionTo == "1")
                    {
                        Message("Invalid Session Selection in Leave-" + j.ToString());
                        return;
                    }
                }
                if (Session["UserGroupName"].ToString() == "SuperAdmin" || Session["HasSpecialRights"].ToString() == "True")
                {
                }
                else
                {
                    string strTodaysDate = DateTime.Now.ToString(Session["MDateFormat"].ToString());
                    //Added by Manjula.p on 13-May-2014
                    strTodaysDate = objcls_Common.DateConvertion(gstrDateFormat, strTodaysDate);
                    if ((Convert.ToDateTime(strFirstLeaveFrom) < Convert.ToDateTime(strTodaysDate)) || (Convert.ToDateTime(strFirstLeaveTo) < Convert.ToDateTime(strTodaysDate)))
                    {
                        Message("Leave should not be applied for past days");
                        return;
                    }
                }
            }
        }
        //Days Validation
        //Fill the Year Settings Detail
        DataSet ds_Year = new DataSet();
        ds_Year = objcls_Common.GetYearsetting();
        if (ds_Year.Tables[0].Rows.Count > 0)
        {
            gstrYearSettingStartDate = ds_Year.Tables[0].Rows[0]["FromDate"].ToString();
            gstrYearSettingsEndDate = ds_Year.Tables[0].Rows[0]["ToDate"].ToString();
            ViewState["YearSettings_Id"] = ds_Year.Tables[0].Rows[0]["YearSettings_Id"].ToString();
            ds_Year.Dispose();
        }
        //CL for Each month checking
        DataTable dtLeaveForEachMonth = new DataTable();
        dtLeaveForEachMonth.TableName = "LeaveForEachMonth";
        DataColumn dcLeaveMonth = new DataColumn("LeaveMonth");
        DataColumn dcLeaveCategoryType = new DataColumn("LeaveCategoryType");
        DataColumn dcLeaveType = new DataColumn("LeaveType");
        DataColumn dcLeaveDays = new DataColumn("LeaveDays", typeof(decimal));
        DataColumn dcMaxDaysMonth = new DataColumn("MaxDaysMonth");
        dtLeaveForEachMonth.Columns.Add(dcLeaveMonth);
        dtLeaveForEachMonth.Columns.Add(dcLeaveCategoryType);
        dtLeaveForEachMonth.Columns.Add(dcLeaveType);
        dtLeaveForEachMonth.Columns.Add(dcLeaveDays);
        dtLeaveForEachMonth.Columns.Add(dcMaxDaysMonth);
        DataRow dRowLeaveForEachMonth;
        double doubleLeaveApplicableDays = 0;
        int intcount = 0, intHalfDayCount = 0;
        //dRowLeaveForEachMonth = dtLeaveForEachMonth.NewRow();
        //dRowLeaveForEachMonth["LeaveMonth"] = "First Half";
        //dRowLeaveForEachMonth["LeaveCategoryType"] = "1";
        //dRowLeaveForEachMonth["LeaveDays"] = "1";
        //dRowLeaveForEachMonth.EndEdit();
        //dtLeaveForEachMonth.Rows.Add(dRowLeaveForEachMonth);
        #region checking SL/Comp Off with CL By Manjula on 24-May-2013
        //calling function
        isValidGrid = CheckCombinedinAddRow(districtDetails);
        if (isValidGrid == false)
        {
            //Message("Cant Add the row, because you are entering combined leave of [SL/Comp Off] with [CL]");
            return;
        }
        #endregion
        decimal decCont = 0;
        foreach (DataRow dRow in districtDetails.Rows)
        {
            strLeaveCategory = string.Empty;
            strLeaveFromSession = string.Empty;
            strLeaveToSession = string.Empty;
            strLeaveFromDate = string.Empty;
            strLeaveToDate = string.Empty;
            strLeaveCategory = dRow["LeaveCategory"].ToString();
            //by manju for getting leavetype name
            string strLeaveTypeName = string.Empty;
            strLeaveTypeName = dRow["LeaveTypesName"].ToString();
            //***************************************
            if (strLeaveCategory == "1")
            {
                strLeaveCategory = "Leave";
            }
            else if (strLeaveCategory == "2")
            {
                strLeaveCategory = "LOP";
            }
            else if (strLeaveCategory == "3")
            {
                strLeaveCategory = "Comp Off";
            }
            strLeaveTypeId = dRow["LeaveTypes"].ToString();
            if (strLeaveTypeId == string.Empty)
            {
                Message("Leave Types should not be empty");
                return;
            }
            strLeaveFromSession = dRow["LeaveSessionsFrom"].ToString();
            if (strLeaveFromSession == "1")
            {
                strLeaveFromSession = "First Half";
            }
            else
            {
                strLeaveFromSession = "Second Half";
            }
            strLeaveToSession = dRow["LeaveSessionsTo"].ToString();
            if (strLeaveToSession == "1")
            {
                strLeaveToSession = "First Half";
            }
            else
            {
                strLeaveToSession = "Second Half";
            }
            strLeaveFromDate = dRow["LeaveFrom"].ToString();
            strLeaveToDate = dRow["LeaveTo"].ToString();
            strLeaveFromDate = objcls_Common.DateConvertion(gstrDateFormat, strLeaveFromDate);
            strLeaveToDate = objcls_Common.DateConvertion(gstrDateFormat, strLeaveToDate);
            //Date Comparision
            if (DateDifference(DateTime.Parse(strLeaveFromDate), DateTime.Parse(strLeaveToDate)) < 0)
            {
                Message("To Date should be greater than from date");
                return;
            }
            ////Validate within Year settings
            //if ((DateTime.Parse(strLeaveFromDate) >= DateTime.Parse(gstrYearSettingStartDate) && DateTime.Parse(strLeaveFromDate) <= DateTime.Parse(gstrYearSettingsEndDate)) && (DateTime.Parse(strLeaveToDate) >= DateTime.Parse(gstrYearSettingStartDate) && DateTime.Parse(strLeaveToDate) <= DateTime.Parse(gstrYearSettingsEndDate)))
            //{
            //    //Continue            
            //}
            //else
            //{
            //    Message("Select Leave Dates within current year");
            //    return;
            //}
            //Validate less than Year settings
            if ((DateTime.Parse(strLeaveToDate) < DateTime.Parse(gstrYearSettingStartDate)) || (DateTime.Parse(strLeaveFromDate) < DateTime.Parse(gstrYearSettingStartDate)))
            {
                Message("Leave duration should not be less than the current year");
                return;
            }
            //Validate leave beyond the next year setting
            if (ViewState["NextYearSettings_Id"] != null || ViewState["NextYearSettings_Id"].ToString() != string.Empty)
            {
                if (DateTime.Parse(strLeaveToDate) > DateTime.Parse(gstrNextYearSettingsEndDate))
                {
                    Message("Leave application cannot be raised beyond the next year");
                    return;
                }
                if ((DateTime.Parse(strLeaveFromDate) <= DateTime.Parse(gstrYearSettingsEndDate)) && DateTime.Parse(strLeaveToDate) >= DateTime.Parse(gstrNextYearSettingStartDate))
                {
                    Message("Leave application cannot be applied for cross year, so please enter the leave for next year as a separate leave application");
                    return;
                }
            }
            else
            {
                if (DateTime.Parse(strLeaveToDate) > DateTime.Parse(gstrYearSettingsEndDate))
                {
                    Message("Leave application cannot be raised beyond the current year");
                    return;
                }
            }
            //Date of Joining Validation
            ds_EmployeeDetails = objLeaveApplicationEventData.GetEmployeeDetails(Convert.ToInt32(hdnEmployeeId.Value));
            gstrDateOfJoining = ds_EmployeeDetails.Tables[0].Rows[0]["DateOfJoining"].ToString();
            EmployeeCodeId = ds_EmployeeDetails.Tables[0].Rows[0]["Employee_Code_Id"].ToString();
            gstrSwipeCardNo = ds_EmployeeDetails.Tables[0].Rows[0]["SwipeCardNo"].ToString();
            //Check the Leave lies between any Leave Policy of current year
            //Check Leave From Date and To Date falls between any Leave Policy with current year
            DataSet dsLeavePolicyDatesExists = new DataSet();
            dsLeavePolicyDatesExists = objLeaveApplicationEventData.GetLeavePolicyDatesExists_Angler(Convert.ToInt32(hdnEmployeeId.Value), strLeaveFromDate, strLeaveToDate);
            if (dsLeavePolicyDatesExists.Tables.Count > 0)
            {
                if (dsLeavePolicyDatesExists.Tables[0].Rows.Count > 0)
                {
                    if (Convert.ToInt32(dsLeavePolicyDatesExists.Tables[0].Rows[0]["PolicyCount"]) == 0)
                    {
                        Message("No Policy Defined /Leave dates should be within the Policy period");
                        return;
                    }
                }
            }
            if (DateTime.Parse(gstrDateOfJoining) <= DateTime.Parse(strLeaveFromDate))
            {
                //Leave dates Applicable
                DataSet dsRequiredPeriod = new DataSet();
                if (strLeaveCategory != "Comp Off")
                {
                    dsRequiredPeriod = objLeaveApplicationEventData.GetApplicableAfterDays(Convert.ToInt32(hdnEmployeeId.Value), Convert.ToInt32(strLeaveTypeId), strLeaveFromDate);
                    if (dsRequiredPeriod.Tables.Count > 0)
                    {
                        dsRequiredPeriod.Tables[0].TableName = "Details";
                        if (dsRequiredPeriod.Tables[0].Rows[0]["RemainingNoOfLeaves"].ToString() == "Y")
                        {
                        }
                        else
                        {
                            //Leave dates not applicable
                            Message("Leave dates are not applicable");
                            return;
                        }
                    }
                }
            }
            else
            {
                //Leave dates not applicable
                Message("Leave dates should be greater than Date of Joining");
                return;
            }
            doubleLeaveApplicableDays = 0;
            //doubleLeaveApplicableDays = Convert.ToInt32(ds_EmployeeDetails.Tables[0].Rows[0]["LeaveApplicableDays"]);
            #region getting accumulated days for the month. By MAnjula.P on 27-May-2013
            int EmployeeId = 0;
            decimal SatWorkHrs = 0;
            //if (Session["EmpAutoID"] != null)
            //    EmployeeId = Convert.ToInt32(Session["EmpAutoID"]);
            if (hdnEmployeeId.Value != string.Empty)
                EmployeeId = Convert.ToInt32(hdnEmployeeId.Value);
            DataSet dsSaturdayWorkHrs = objLeaveApplicationEventData.dsGetSaturdayWorkHrs(EmployeeId);
            if (dsSaturdayWorkHrs.Tables[0].Rows.Count > 0)
            {
                if (Convert.ToString(dsSaturdayWorkHrs.Tables[0].Rows[0]["Sat_WorkHrs"]) != string.Empty)
                    SatWorkHrs = Convert.ToInt32(dsSaturdayWorkHrs.Tables[0].Rows[0]["Sat_WorkHrs"]);
            }
            //checking whether the logined employee is cumulative employee or not.
            if (SatWorkHrs >= 8)
            {
                doubleLeaveApplicableDays = Convert.ToDouble(objLeaveApplicationEventData.GetMaxDaysPerMonth((Convert.ToInt32(hdnEmployeeId.Value)), Convert.ToInt32(strLeaveTypeId), strLeaveToDate, false, 0));
            }
            else
            {
                doubleLeaveApplicableDays = Convert.ToDouble(objLeaveApplicationEventData.GetMaxDaysPerMonth((Convert.ToInt32(hdnEmployeeId.Value)), Convert.ToInt32(strLeaveTypeId), strLeaveToDate, true, 0));
            }
            #endregion
            //Check the Shift is allocated or not
            int ShiftCount = CheckShift();
            if (ShiftCount == 0)
            {
                Message("Shift not allocated for these leave days");
                return;
            }
            //Check Leaves already Taken in a month
            if (strLeaveCategory == "Leave")
            {
                fltLeaveTakenInMonth = objLeaveApplicationEventData.GetLeaveTakenInMonth(hdnEmployeeId.Value, strLeaveTypeId, strLeaveFromDate, strLeaveToDate, 0);
            }
            //Calculate Number of Days Applied based on Leave Policy
            testvalue = 0;
            string strDays = CalculateNumberOfDaysApplied();
            if (strDays == "MaxLeaveTakenExceedsInMonth")
            {
                //document.getElementById('ctl00_CP_Transaction_txt_Numberofdays').value="";
                Message("CL Leave Exceeds the Limit");
                return;
            }
            if (strDays == "MaxLeaveTakenInMonth")
            {
                //document.getElementById('ctl00_CP_Transaction_txt_Numberofdays').value="";
                Message("CL already taken in this month");
                return;
            }
            if (strDays == "HalfDayIsDisabled")
            {
                //document.getElementById('ctl00_CP_Transaction_txt_Numberofdays').value="";
                Message("Half day is not allowed");
                return;
            }
            if (strDays == "InvalidYear")
            {
                //document.getElementById('ctl00_CP_Transaction_txt_Numberofdays').value="";
                Message("Select valid year");
                return;
            }
            if (strDays == "FromToDates")
            {
                //document.getElementById('ctl00_CP_Transaction_txt_Numberofdays').value="";
                Message("Leave From Date should not be greater than Leave To Date");
                return;
            }
            if (strDays == "DateOfJoining")
            {
                //document.getElementById('ctl00_CP_Transaction_txt_Numberofdays').value="";
                Message("Leave should not be applied before date of joining");
                return;
            }
            if (strDays == "NoLeavePolicyDates")
            {
                //document.getElementById('ctl00_CP_Transaction_txt_Numberofdays').value="";
                Message("No Leave Policy exists for this Leave From Date or To Date");
                return;
            }
            if (strDays == "ApplicableAfterDays")
            {
                Message("Leave should be applied, applicable after days");
                return;
            }
            if (strDays == "Holiday")
            {
                Message("You are selecting Holiday");
                return;
            }
            if (strDays == "WeeklyOffFromDate")
            {
                Message("You are selecting Weekly Off in From date");
                return;
            }
            if (strDays == "WeeklyOffToDate")
            {
                Message("You are selecting Weekly Off in To date");
                return;
            }
            if (strDays == "WeeklyOff")
            {
                Message("You are selecting Weekly Off");
                return;
            }
            if (strDays == "HolidayWeeklyOff")
            {
                Message("Leave Application cannot be raised during Weekly Off / Global Holiday");
                return;
            }
            if (strDays == "NoLeaveTypeId")
            {
                Message("Select Leave and LeaveTypeId");
                return;
            }
            if (strDays == "ShiftNotAllocated")
            {
                Message("Shift not allocated");
                return;
            }
            if (strDays == "kindly apply half day leave in saturday")
            {
                Message("kindly apply half day leave in saturday");
                return;
            }
            if (strDays == "kindly split up the records and apply half day leave in saturday")
            {
                Message("kindly split up the records and apply half day leave in saturday");
                return;
            }
            if (strDays == "Leave has already applied for these dates")
            {
                Message("Leave has already applied for these dates");
                return;
            }
            string[] NumberOfDays = strDays.Split(',');
            if (Convert.ToDouble(NumberOfDays[0]) < 0)
            {
                Message("Select Valid From Date and To Date");
                return;
            }
            else if (Convert.ToInt32(NumberOfDays[1]) == 0)
            {
                //return;
            }
            else if (Convert.ToInt32(NumberOfDays[1]) == 1)
            {
                //Message("You have choosed after weekly Off, One Day Added");
                //return;
            }
            else if (Convert.ToInt32(NumberOfDays[1]) == 2)
            {
                //Message("You have choosed Before weekly Off, One Day Added");
                //return;
            }
            else if (Convert.ToInt32(NumberOfDays[1]) == 3)
            {
                //Message("You have selected Intervening weekly Off / Global Holiday " + NumberOfDays[2] + " Day(s) Deducted");
                //return;
            }
            else if (Convert.ToInt32(NumberOfDays[1]) == 4)
            {
                //Message("You have selected Intervening weekly Off / Global Holiday " + NumberOfDays[2] + " Day(s) included ");
                //return;
            }
            else if (Convert.ToInt32(NumberOfDays[1]) == -1)
            {
                //return;
            }
            NoOfLeaves = NumberOfDays[0];
            dRow["NoOfLeaves"] = NoOfLeaves;
            //if (doubleLeaveApplicableDays == 0)
            //{
            string strLeaveTypesName = dRow["LeaveTypesName"].ToString();
            if (strLeaveCategory == "Leave")
            {
                DateTime dtmLeaveMonth = new DateTime(DateTime.Parse(strLeaveFromDate).Year, DateTime.Parse(strLeaveFromDate).Month, 1);
                string strMonth = dtmLeaveMonth.ToShortDateString();
                if (dtLeaveForEachMonth.Rows.Count > 0)
                {
                    dtLeaveForEachMonth.DefaultView.RowFilter = "LeaveMonth='" + strMonth + "' and LeaveType='" + strLeaveTypesName + "'";
                }
                if (dtLeaveForEachMonth.DefaultView.ToTable().Rows.Count == 0)
                {
                    dRowLeaveForEachMonth = dtLeaveForEachMonth.NewRow();
                    dRowLeaveForEachMonth["LeaveMonth"] = strMonth;
                    dRowLeaveForEachMonth["LeaveCategoryType"] = strLeaveCategory + "-" + strLeaveTypesName;
                    dRowLeaveForEachMonth["LeaveType"] = strLeaveTypesName;
                    if ((SatWorkHrs >= 8))
                    {
                        dRowLeaveForEachMonth["LeaveDays"] = Convert.ToString(fltLeaveTakenInMonth + Convert.ToDouble(NoOfLeaves));
                    }
                    else
                    {
                        dRowLeaveForEachMonth["LeaveDays"] = Convert.ToString(Convert.ToDouble(NoOfLeaves));
                    }
                    dRowLeaveForEachMonth["MaxDaysMonth"] = doubleLeaveApplicableDays;
                    dRowLeaveForEachMonth.EndEdit();
                    dtLeaveForEachMonth.Rows.Add(dRowLeaveForEachMonth);
                }
                else
                {
                    foreach (DataRow DRowLeaves in dtLeaveForEachMonth.Rows)
                    {
                        if (DRowLeaves["LeaveMonth"].ToString() == strMonth)
                        {
                            DRowLeaves["LeaveCategoryType"] = strLeaveCategory + "-" + strLeaveTypesName;
                            DRowLeaves["LeaveType"] = strLeaveTypesName;
                            string strLeaves = Convert.ToString((Convert.ToDouble(DRowLeaves["LeaveDays"]) + Convert.ToDouble(NoOfLeaves)));
                            DRowLeaves["LeaveDays"] = strLeaves;
                            DRowLeaves["MaxDaysMonth"] = doubleLeaveApplicableDays;
                        }
                    }
                }
            }
            //}
            //Remaining Leave Validation
            if (dRow["LeaveCategoryName"].ToString() == "Leave" || dRow["LeaveCategoryName"].ToString() == "Comp Off")
            {
                foreach (DataRow dRowRemainingLeaves in dsRemainingNoOfLeaves.Tables[0].Rows)
                {
                    if (dRowRemainingLeaves["Leave Type"].ToString() == dRow["LeaveTypesName"].ToString())
                    {
                        dRowRemainingLeaves["Number Of Days"] = (Convert.ToDouble(dRowRemainingLeaves["Number Of Days"]) - Convert.ToDouble(NumberOfDays[0]));
                    }
                }
            }
            //Existing Leave and Permission Validations to be done here
            //Check FromDate and ToDate. Check whether the leave has already applied for a particular Date. 
            intcount = objLeaveApplicationEventData.CheckLeaveApplication(-1, Convert.ToInt32(hdnEmployeeId.Value), strLeaveFromDate, strLeaveToDate, strLeaveFromSession, strLeaveToSession);
            //Check Leave Count for Half Day Leave, if FromDate and Todate are same and SessionFrom and SessionTo are same
            if (strLeaveFromDate == strLeaveToDate && strLeaveFromSession == strLeaveToSession)
            {
                intHalfDayCount = objLeaveApplicationEventData.CheckHalfDayLeave(Convert.ToInt32(hdnEmployeeId.Value), strLeaveFromDate, strLeaveToDate, strLeaveFromSession, strLeaveToSession);
            }
            if (intcount == 0 && intHalfDayCount == 0)
            {
            }
            else
            {
                Message("Leave has already applied for these dates");
                return;
            }
            #region To restrict the CL leave with SL/Comp off By Manjula.P on 23-May-2013 as per the given requirements by manikandan
            //To restrict the CL leave with SL/Comp off
            //calculate the date for leave before of from date.
            DateTime datePreviousFrom = Convert.ToDateTime(strLeaveFromDate).AddDays(-1);
            string previousFromDate = objcls_Common.DateConvertion(gstrDateFormat, datePreviousFrom.ToString(gstrDateFormat));
            //    string previousFromDate = objcls_Common.DateConvertion(gstrDateFormat, datePreviousFromnew);
            //checking previous working days i.e without holiday.
            datePreviousFrom = RecursionHoliday(datePreviousFrom, 'N');
            //next date
            DateTime dateNextFrom = Convert.ToDateTime(strLeaveFromDate).AddDays(1);
            //  string dateNextFromnew = dateNextFrom.ToShortDateString();
            string nextFromDate = objcls_Common.DateConvertion(gstrDateFormat, dateNextFrom.ToString(gstrDateFormat));
            //checking next working days i.e without holiday.
            dateNextFrom = RecursionHoliday(dateNextFrom, 'P');
            //getting continous leave applied date
            Decimal decContinousAppliedDays = 0;
            if (strLeaveCategory != "LOP" && strLeaveTypeName != "SL")
                decContinousAppliedDays = Decimal.Parse(NumberOfDays[0].ToString());
            DatePre = datePreviousFrom;
            DateNext = dateNextFrom;
            //getting from BAL
            #region Commented By A.K.T.Moorthi To Remove The Validation As Per HR Requirement(27-Jan-2014)
            //DataSet dsgetLastLeaveDate = objLeaveApplicationEventData.getNextPreviousLeave(Convert.ToInt32(hdnEmployeeId.Value), datePreviousFrom, dateNextFrom);
            //if (dsgetLastLeaveDate != null)
            //{
            //    if (dsgetLastLeaveDate.Tables[0].Rows.Count > 0)
            //    {
            //        //dtContinousDB = dsgetLastLeaveDate.Tables[0];
            //        //for restrict the leave because of combined previous leave.
            //        foreach (DataRow rowLast in dsgetLastLeaveDate.Tables[0].Rows)
            //        {
            //            //declaring temprary variables for checking leave type
            //            string LeaveTypeDs = rowLast["LeaveType"].ToString();
            //            string LeaveTypeNameDs = rowLast["Type"].ToString();
            //            //getting noof applied leave days from db
            //            if (LeaveTypeDs != "SL" && LeaveTypeNameDs != "LOP")
            //                decContinousAppliedDays = decContinousAppliedDays + Convert.ToDecimal(rowLast["NumberOfDays"]);
            //            //hardcoded because of taking this field from db itself
            //            if (LeaveTypeDs == "CL" && LeaveTypeNameDs == "Leave")
            //            {
            //                //restrict SL and Comp Off
            //                if (strLeaveTypeName == "SL" || strLeaveCategory == "Comp Off")
            //                {
            //                    Message("SL/Comp Off cannot be combined with CL");
            //                    return;
            //                }
            //            }
            //            else if (LeaveTypeDs == "SL" || (LeaveTypeNameDs == "Comp Off"))
            //            {
            //                //restrict CL
            //                if (strLeaveTypeName == "CL" && strLeaveCategory == "Leave")
            //                {
            //                    Message("CL cannot be combined with Comp Off/SL");
            //                    return;
            //                }
            //            }
            //        }
            //    }
            //} 
            #endregion
            if (Convert.ToString(dRow["LeaveCategoryName"]) != "LOP" && Convert.ToString(dRow["LeaveTypesName"]) != "SL")
            {
                int index = districtDetails.Rows.IndexOf(dRow);
                DataRow NextRow = getNextRow(districtDetails, index);
                DataRow PreviousRow = getPreviousRow(districtDetails, index);
                if (NextRow != null)
                {
                    //for checking continous date.
                    DateTime LeaveTo = Convert.ToDateTime(dRow["LeaveTo"]);
                    //RecursionHoliday(Convert.ToDateTime(dRow["LeaveTo"]), 'P');
                    DateTime LeaveNextFrom = RecursionHoliday(Convert.ToDateTime(dRow["LeaveTo"]).AddDays(1), 'P');
                    if (Convert.ToDateTime(NextRow["LeaveFrom"]) == LeaveNextFrom && NextRow["LeaveCategoryName"].ToString() != "LOP")
                    {
                        if (dRow["NoOfLeaves"].ToString() == "0")
                            decCont = decCont + Convert.ToDecimal(dRow["NoOfLeaves"].ToString());
                        else
                            decCont = decCont + Convert.ToDecimal(NoOfLeaves);
                    }
                }
                else if (PreviousRow != null)
                {
                    //for checking continous date.
                    DateTime LeaveFrom = Convert.ToDateTime(dRow["LeaveFrom"]);
                    //RecursionHoliday(Convert.ToDateTime(dRow["LeaveTo"]), 'P');
                    DateTime LeavePreviousTo = RecursionHoliday(Convert.ToDateTime(dRow["LeaveFrom"]).AddDays(-1), 'N');
                    if (Convert.ToDateTime(PreviousRow["LeaveTo"]) == LeavePreviousTo && PreviousRow["LeaveCategoryName"].ToString() != "LOP")
                    {
                        if (dRow["NoOfLeaves"].ToString() == "0")
                            decCont = decCont + Convert.ToDecimal(dRow["NoOfLeaves"].ToString());
                        else
                            decCont = decCont + Convert.ToDecimal(NoOfLeaves);
                    }
                }
                else
                {
                    decCont = 0;
                }
            }
            //checking contious leave applied days. It should allowed for admin group alone by verifying with Thilakraj and Jagadesskumar
            if (Convert.ToString(Session["UserGroupName"]).ToLower() != "superadmin")
            {
                if ((decContinousAppliedDays > 2) && (strLeaveCategory != "LOP" && strLeaveTypeName != "SL"))
                {
                    Message("'" + strLeaveCategory + "-" + strLeaveTypeName + "' Cannot be applied more than 2days continuously");
                    //Message("Cant Applied Leave More Than [2] Days Continously!.");
                    return;
                }
            }
            #endregion
        }
        #region Checking Continous leave applied date in grid By Manjula.P on 24-May-2013
        isValidGrid = CheckContinousAppliedDays(districtDetails);
        dtContinousDB = objLeaveApplicationEventData.RecursionLeaveDays(Convert.ToInt32(hdnEmployeeId.Value), DatePre, DateNext);
        //to checking contious date you are selected.
        if (isValidGrid == false)
        {
            //districtDetails.comp
            //dt.Rows.Select(dr=>(int)dr["Marks"]).Sum();
            decimal decleLeaveApplicableDays = decCont;
            if (decleLeaveApplicableDays > 2)
            {
                Message("Leave cannot be applied more than 2days continuously!.");
                //Message("Cant Applied Leave More Than [2] Days continuously!.");
                return;
            }
        }
        //checking from db for continous date
        else if (dtContinousDB.Tables[0].Rows.Count > 0)
        {
            if (Convert.ToString(dtContinousDB.Tables[0].Compute("Sum(NoOfDays)", "Type<>'LOP' and LeaveType<>'SL'")) != string.Empty)
            {
                decimal decleLeaveApplicableDays = decCont + Convert.ToDecimal(dtContinousDB.Tables[0].Compute("Sum(NoOfDays)", "Type<>'LOP' and LeaveType<>'SL'"));
                if (decleLeaveApplicableDays > 2)
                {
                    Message("Leave cannot be applied more than 2days continuously!.");
                    //Message("Cant Applied Leave More Than [2] Days continuously!.");
                    return;
                }
            }
        }
        #endregion
        foreach (DataRow dRowRemainingLeaves in dsRemainingNoOfLeaves.Tables[0].Rows)
        {
            if (Convert.ToDouble(dRowRemainingLeaves["Number Of Days"]) < 0)
            {
                if (dRowRemainingLeaves["Leave Type"].ToString() == "Others")
                {
                    //Message("Comp Off Leave exceeds the remaining number of leaves");
                    //return;
                }
                else
                {
                    Message(dRowRemainingLeaves["Leave Type"].ToString() + " Leave exceeds the remaining number of leaves");
                    return;
                }
            }
        }
        //Leave Restriction in a month
        foreach (DataRow DRowLeaves in dtLeaveForEachMonth.Rows)
        {
            //int EmployeeId = 0;
            //decimal SatWorkHrs = 0;
            //if (Session["EmpAutoID"] != null)
            //    EmployeeId = Convert.ToInt32(Session["EmpAutoID"]);
            //DataSet dsSaturdayWorkHrs = objLeaveApplicationEventData.dsGetSaturdayWorkHrs(EmployeeId);
            //if (Convert.ToDouble(DRowLeaves["MaxDaysMonth"]) >= 0)
            //{
            //if (dsSaturdayWorkHrs.Tables[0].Rows.Count > 0)
            //{
            //    if (Convert.ToString (dsSaturdayWorkHrs.Tables[0].Rows[0]["Sat_WorkHrs"]) != string.Empty)
            //        SatWorkHrs = Convert.ToInt32(dsSaturdayWorkHrs.Tables[0].Rows[0]["Sat_WorkHrs"]);
            //}
            ////checking whether the logined employee is cumulative employee or not.
            // if(SatWorkHrs>=8)
            string LeaveType = DRowLeaves["LeaveType"].ToString();
            //dv.RowFilter = "LeaveType='" + DRowLeaves["LeaveType"].ToString();  
            decimal MaxLeaves = Convert.ToDecimal(dtLeaveForEachMonth.Compute("Max(MaxDaysMonth)", "LeaveType='" + LeaveType + "'"));
            decimal SumValue = Convert.ToDecimal(dtLeaveForEachMonth.Compute("sum(LeaveDays)", "LeaveType='" + LeaveType + "'"));
            if (Convert.ToDouble(SumValue) > Convert.ToDouble(MaxLeaves))
            {
                string monthName = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(DateTime.Parse(DRowLeaves["LeaveMonth"].ToString()).Month);
                Message(DRowLeaves["LeaveType"].ToString() + " " + "Leave Exceeds the quota in " + monthName);
                return;
            }
            //}
        }
        LoadNumberOfLeavesToGrid(districtDetails);
        //Days Validation Ends here
        //for 
        districtDetails = LoadDataFromGridWithLeaveCategory();
        DataRow dataInGrid;
        dataInGrid = districtDetails.NewRow();
        dataInGrid["SlNo"] = iterator + 1;
        districtDetails.Rows.Add(dataInGrid);
        DataSet districtData = new DataSet();
        districtData.Tables.Add(districtDetails);
        //districtData.Tables[0].Rows[iterator - 1]["NoOfLeaves"] = NoOfLeaves;
        gvTestGrid.DataSource = districtData;
        gvTestGrid.DataBind();
        LoadComboInGrid();
        //TextBox txtTest = gvTestGrid.Rows[gvTestGrid.Rows.Count - 1].Cells[2].FindControl("txtDistrictName") as TextBox;
    }
    #region LoadDataFromGrid
    private DataTable LoadDataFromGrid()
    {
        DataTable districtDetails = new DataTable("District");
        districtDetails.Columns.AddRange(new DataColumn[]{new DataColumn("LeaveTypes"),new DataColumn("LeaveFrom"),new DataColumn("LeaveTo"),new DataColumn("LeaveSessionsFrom"),new DataColumn("LeaveSessionsTo"),new DataColumn("NoOfLeaves"), new DataColumn("SLNo",Type.GetType("System.Int64"))
            });
        int iterator = 0;
        DataRow dataInGrid;
        for (; iterator < gvTestGrid.Rows.Count; iterator++)
        {
            dataInGrid = districtDetails.NewRow();
            TextBox textDataField = new TextBox();
            //DropDownList stateData = new DropDownList();
            Label lblNoOfLeaves = new Label();
            DropDownList ddlLeaveTypesData = new DropDownList();
            DropDownList ddlLeaveSessionsFromData = new DropDownList();
            DropDownList ddlLeaveSessionsToData = new DropDownList();
            TextBox txtFromDate = new TextBox();
            TextBox txtToDate = new TextBox();
            //HiddenField hdnLeaveCategory=new HiddenField();
            //Label lblSlNo = gvTestGrid.Rows[iterator].Cells[0].FindControl("lblSlNo") as Label;
            dataInGrid["SlNo"] = gvTestGrid.Rows[iterator].Cells[0].Text;// lblSlNo.Text;
            //textDataField = gvTestGrid.Rows[iterator].Cells[1].FindControl("txtDistrictName") as TextBox;
            //dataInGrid["DistrictName"] = textDataField.Text;
            ddlLeaveTypesData = gvTestGrid.Rows[iterator].Cells[0].FindControl("ddlLeaveTypes") as DropDownList;
            dataInGrid["LeaveTypes"] = ddlLeaveTypesData.SelectedValue.ToString();
            //stateData = gvTestGrid.Rows[iterator].Cells[0].FindControl("ddlLeaveCategory") as DropDownList;
            //dataInGrid["LeaveCategory"] = stateData.SelectedValue.ToString();
            txtFromDate = gvTestGrid.Rows[iterator].Cells[0].FindControl("txtFromDate") as TextBox;
            dataInGrid["LeaveFrom"] = txtFromDate.Text;
            txtToDate = gvTestGrid.Rows[iterator].Cells[0].FindControl("txtToDate") as TextBox;
            dataInGrid["LeaveTo"] = txtToDate.Text;
            ddlLeaveSessionsFromData = gvTestGrid.Rows[iterator].Cells[0].FindControl("ddlSessionsFrom") as DropDownList;
            dataInGrid["LeaveSessionsFrom"] = ddlLeaveSessionsFromData.SelectedValue.ToString();
            ddlLeaveSessionsToData = gvTestGrid.Rows[iterator].Cells[0].FindControl("ddlSessionsTo") as DropDownList;
            dataInGrid["LeaveSessionsTo"] = ddlLeaveSessionsToData.SelectedValue.ToString();
            //hdnLeaveCategory=gvTestGrid.Rows[iterator].Cells[0].FindControl("hdnLeaveCategory") as HiddenField;
            //dataInGrid["hdnLeaveCategory"]=hdnLeaveCategory.Value ;
            lblNoOfLeaves = gvTestGrid.Rows[iterator].Cells[0].FindControl("lblNoOfLeaves") as Label;
            dataInGrid["NoOfLeaves"] = lblNoOfLeaves.Text;
            //HtmlInputText txtPinCode = new HtmlInputText();
            //txtPinCode = gvTestGrid.Rows[iterator].Cells[2].FindControl("txtPincode") as HtmlInputText;
            //dataInGrid["Pincode"] = txtPinCode.Value.ToString();
            //textDataField = gvTestGrid.Rows[iterator].Cells[3].FindControl("txtPopulation") as TextBox;
            //dataInGrid["Population"] = textDataField.Text;
            districtDetails.Rows.Add(dataInGrid);
        }
        return districtDetails;
    }
    #endregion
    #region LoadDataFromGridWithLeaveCategory
    private DataTable LoadDataFromGridWithLeaveCategory()
    {
        DataTable districtDetails = new DataTable("District");
        districtDetails.Columns.AddRange(new DataColumn[] { new DataColumn("LeaveCategory"), new DataColumn("LeaveCategoryName"), new DataColumn("LeaveTypes"), new DataColumn("LeaveTypesName"), new DataColumn("LeaveFrom"), new DataColumn("LeaveTo"), new DataColumn("LeaveSessionsFrom"), new DataColumn("LeaveSessionsTo"), new DataColumn("NoOfLeaves"), new DataColumn("SLNo", Type.GetType("System.Int64")) });
        int iterator = 0;
        DataRow dataInGrid;
        for (; iterator < gvTestGrid.Rows.Count; iterator++)
        {
            dataInGrid = districtDetails.NewRow();
            TextBox textDataField = new TextBox();
            DropDownList stateData = new DropDownList();
            Label lblNoOfLeaves = new Label();
            DropDownList ddlLeaveTypesData = new DropDownList();
            DropDownList ddlLeaveSessionsFromData = new DropDownList();
            DropDownList ddlLeaveSessionsToData = new DropDownList();
            TextBox txtFromDate = new TextBox();
            TextBox txtToDate = new TextBox();
            //HiddenField hdnLeaveCategory = new HiddenField();
            //Label lblSlNo = gvTestGrid.Rows[iterator].Cells[0].FindControl("lblSlNo") as Label;
            dataInGrid["SlNo"] = gvTestGrid.Rows[iterator].Cells[0].Text;// lblSlNo.Text;
            //textDataField = gvTestGrid.Rows[iterator].Cells[1].FindControl("txtDistrictName") as TextBox;
            //dataInGrid["DistrictName"] = textDataField.Text;
            ddlLeaveTypesData = gvTestGrid.Rows[iterator].Cells[0].FindControl("ddlLeaveTypes") as DropDownList;
            dataInGrid["LeaveTypes"] = ddlLeaveTypesData.SelectedValue.ToString();
            if (ddlLeaveTypesData.SelectedItem != null)
            {
                dataInGrid["LeaveTypesName"] = ddlLeaveTypesData.SelectedItem.Text;
            }
            else
            {
                dataInGrid["LeaveTypesName"] = "";
            }
            stateData = gvTestGrid.Rows[iterator].Cells[0].FindControl("ddlLeaveCategory") as DropDownList;
            dataInGrid["LeaveCategory"] = stateData.SelectedValue.ToString();
            if (stateData.SelectedItem != null)
            {
                dataInGrid["LeaveCategoryName"] = stateData.SelectedItem.Text;
            }
            else
            {
                dataInGrid["LeaveCategoryName"] = "";
            }
            txtFromDate = gvTestGrid.Rows[iterator].Cells[0].FindControl("txtFromDate") as TextBox;
            dataInGrid["LeaveFrom"] = txtFromDate.Text;
            txtToDate = gvTestGrid.Rows[iterator].Cells[0].FindControl("txtToDate") as TextBox;
            dataInGrid["LeaveTo"] = txtToDate.Text;
            ddlLeaveSessionsFromData = gvTestGrid.Rows[iterator].Cells[0].FindControl("ddlSessionsFrom") as DropDownList;
            dataInGrid["LeaveSessionsFrom"] = ddlLeaveSessionsFromData.SelectedValue.ToString();
            ddlLeaveSessionsToData = gvTestGrid.Rows[iterator].Cells[0].FindControl("ddlSessionsTo") as DropDownList;
            dataInGrid["LeaveSessionsTo"] = ddlLeaveSessionsToData.SelectedValue.ToString();
            //hdnLeaveCategory = gvTestGrid.Rows[iterator].Cells[0].FindControl("hdnLeaveCategory") as HiddenField;
            //dataInGrid["hdnLeaveCategory"] = hdnLeaveCategory.Value;
            lblNoOfLeaves = gvTestGrid.Rows[iterator].Cells[0].FindControl("lblNoOfLeaves") as Label;
            dataInGrid["NoOfLeaves"] = lblNoOfLeaves.Text;
            //HtmlInputText txtPinCode = new HtmlInputText();
            //txtPinCode = gvTestGrid.Rows[iterator].Cells[2].FindControl("txtPincode") as HtmlInputText;
            //dataInGrid["Pincode"] = txtPinCode.Value.ToString();
            //textDataField = gvTestGrid.Rows[iterator].Cells[3].FindControl("txtPopulation") as TextBox;
            //dataInGrid["Population"] = textDataField.Text;
            districtDetails.Rows.Add(dataInGrid);
        }
        return districtDetails;
    }
    #endregion
    #region LoadDataFromGridFirstTime
    private DataTable LoadDataFromGridFirstTime()
    {
        DataTable districtDetails = new DataTable("District");
        districtDetails.Columns.AddRange(new DataColumn[]{new DataColumn("LeaveTypes"),new DataColumn("LeaveFrom"),new DataColumn("LeaveTo"),new DataColumn("LeaveSessionsFrom"),new DataColumn("LeaveSessionsTo"),new DataColumn("NoOfLeaves"), new DataColumn("SLNo",Type.GetType("System.Int64"))
            });
        //int iterator = 0;
        DataRow dataInGrid;
        dataInGrid = districtDetails.NewRow();
        dataInGrid["SlNo"] = "1";
        //dataInGrid["hdnLeaveCategory"] = "1";
        dataInGrid["LeaveTypes"] = "Comp Off";
        districtDetails.Rows.Add(dataInGrid);
        return districtDetails;
    }
    #endregion
    protected void gvTestGrid_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Delete")
        {
            // get the categoryID of the clicked row
            int SLNO = Convert.ToInt32(e.CommandArgument);
            // Delete the record 
            if (gvTestGrid.Rows.Count == 1)
            {
                Message("Cannot Delete this row, at lease one row to be maintained");
                return;
            }
            else
            {
                Session["DeletedRowId"] = SLNO.ToString();
                DeleteRecordByID(SLNO);
                Session["DeletedRowId"] = string.Empty;
            }
            // Implement this on your own :) 
        }
    }
    protected void gvTestGrid_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
    }
    private void DeleteRecordByID(int categoryID)
    {
        DataTable districtDetails = LoadDataFromGrid();
        districtDetails.Rows[(categoryID - 1)].Delete();
        DataSet districtData = new DataSet();
        int i = 1;
        foreach (DataRow dRow in districtDetails.Rows)
        {
            dRow["SLNO"] = i;
            i = i + 1;
        }
        Session["SessionGridLeaveCategory"] = LoadDataFromGridWithLeaveCategory();
        districtData.Tables.Add(districtDetails);
        gvTestGrid.DataSource = districtData;
        gvTestGrid.DataBind();
        LoadComboInGrid();
    }
    public void LoadNumberOfLeavesToGrid(DataTable districtDetails)
    {
        for (int index = 0; index < gvTestGrid.Rows.Count; index++)
        {
            Label lblNoOfLeaves = gvTestGrid.Rows[index].Cells[0].FindControl("lblNoOfLeaves") as Label;
            districtDetails.DefaultView.RowFilter = "SLNO=" + (index + 1);
            string strNoOfLeaves = districtDetails.DefaultView.ToTable().Rows[0]["NoOfLeaves"].ToString();
            if (strNoOfLeaves != string.Empty)
            {
                lblNoOfLeaves.Text = strNoOfLeaves;
            }
        }
    }
    private string GetSelectedEmployee()
    {
        string strRet = string.Empty;
        lstInformTo.Enabled = rbtnUPWI.Checked;
        for (int i = 0; i < lstInformTo.Items.Count; i++)
            strRet = lstInformTo.Items[i].Selected ? strRet + (strRet == string.Empty ? string.Empty : ", ") + lstInformTo.Items[i].Text : strRet;
        return strRet;
    }
    #region LoadComboInGrid
    private void LoadComboInGrid()
    {
        DataTable districtDetails = LoadDataFromGridWithLeaveCategory();
        //Leave From Session 
        DataSet dsLeaveSessionsFrom = new DataSet();
        DataTable dtLeaveSessionsFrom = new DataTable();
        dtLeaveSessionsFrom.TableName = "LeaveSessionsFrom";
        DataColumn dcLeaveSessionsFromName = new DataColumn("LeaveSessionsFromName");
        DataColumn dcLeaveSessionsFromValue = new DataColumn("LeaveSessionsFromValue");
        dtLeaveSessionsFrom.Columns.Add(dcLeaveSessionsFromName);
        dtLeaveSessionsFrom.Columns.Add(dcLeaveSessionsFromValue);
        DataRow dRowLeaveSessionsFrom;
        dRowLeaveSessionsFrom = dtLeaveSessionsFrom.NewRow();
        dRowLeaveSessionsFrom["LeaveSessionsFromName"] = "First Half";
        dRowLeaveSessionsFrom["LeaveSessionsFromValue"] = "1";
        dRowLeaveSessionsFrom.EndEdit();
        dtLeaveSessionsFrom.Rows.Add(dRowLeaveSessionsFrom);
        dRowLeaveSessionsFrom = dtLeaveSessionsFrom.NewRow();
        dRowLeaveSessionsFrom["LeaveSessionsFromName"] = "Second Half";
        dRowLeaveSessionsFrom["LeaveSessionsFromValue"] = "2";
        dRowLeaveSessionsFrom.EndEdit();
        dtLeaveSessionsFrom.Rows.Add(dRowLeaveSessionsFrom);
        dsLeaveSessionsFrom.Tables.Add(dtLeaveSessionsFrom);
        //Leave To Session 
        DataSet dsLeaveSessionsTo = new DataSet();
        DataTable dtLeaveSessionsTo = new DataTable();
        dtLeaveSessionsTo.TableName = "LeaveSessionsTo";
        DataColumn dcLeaveSessionsToName = new DataColumn("LeaveSessionsToName");
        DataColumn dcLeaveSessionsToValue = new DataColumn("LeaveSessionsToValue");
        dtLeaveSessionsTo.Columns.Add(dcLeaveSessionsToName);
        dtLeaveSessionsTo.Columns.Add(dcLeaveSessionsToValue);
        DataRow dRowLeaveSessionsTo;
        dRowLeaveSessionsTo = dtLeaveSessionsTo.NewRow();
        dRowLeaveSessionsTo["LeaveSessionsToName"] = "First Half";
        dRowLeaveSessionsTo["LeaveSessionsToValue"] = "1";
        dRowLeaveSessionsTo.EndEdit();
        dtLeaveSessionsTo.Rows.Add(dRowLeaveSessionsTo);
        dRowLeaveSessionsTo = dtLeaveSessionsTo.NewRow();
        dRowLeaveSessionsTo["LeaveSessionsToName"] = "Second Half";
        dRowLeaveSessionsTo["LeaveSessionsToValue"] = "2";
        dRowLeaveSessionsTo.EndEdit();
        dtLeaveSessionsTo.Rows.Add(dRowLeaveSessionsTo);
        dsLeaveSessionsTo.Tables.Add(dtLeaveSessionsTo);
        //Leave Types filled based on Category Id's
        int EmployeeId = Convert.ToInt32(hdnEmployeeId.Value);
        DataSet dsLeaveTypesDataLocal = new DataSet();
        dsLeaveTypesData = objLeaveApplicationEventData.GetLeaveTypesOfEmployees_Angler(EmployeeId);
        dsLeaveTypesData.Tables[0].TableName = "Details";
        if (dsLeaveTypesData.Tables["Details"].Rows.Count > 0)
        {
            Session["sessionLeaveTypes"] = dsLeaveTypesData;
        }
        dsLeaveTypesLOPDays = objLeaveApplicationEventData.GetLOPLeaveTypeDetails(EmployeeId);
        dsLeaveTypesLOPDays.Tables[0].TableName = "Details";
        if (dsLeaveTypesLOPDays.Tables["Details"].Rows.Count > 0)
        {
            Session["sessionLeaveTypes"] = dsLeaveTypesLOPDays;
        }
        //Comp Off Leaves
        DataSet dsLeaveCompOff = new DataSet();
        DataTable dtLeaveCompOff = new DataTable();
        dtLeaveCompOff.TableName = "Details";
        DataColumn dcLeaveCompOffName = new DataColumn("LeaveType");
        DataColumn dcLeaveCompOffValue = new DataColumn("LeaveType_Id");
        dtLeaveCompOff.Columns.Add(dcLeaveCompOffName);
        dtLeaveCompOff.Columns.Add(dcLeaveCompOffValue);
        DataRow dRowLeaveCompOff;
        dRowLeaveCompOff = dtLeaveCompOff.NewRow();
        dRowLeaveCompOff["LeaveType"] = "Others";
        dRowLeaveCompOff["LeaveType_Id"] = "1";
        dRowLeaveCompOff.EndEdit();
        dtLeaveCompOff.Rows.Add(dRowLeaveCompOff);
        dsLeaveCompOff.Tables.Add(dtLeaveCompOff);
        for (int index = 0; index < gvTestGrid.Rows.Count; index++)
        {
            DropDownList ddlLeaveCategory = gvTestGrid.Rows[index].Cells[0].FindControl("ddlLeaveCategory") as DropDownList;
            DropDownList ddlSessionsFrom = gvTestGrid.Rows[index].Cells[0].FindControl("ddlSessionsFrom") as DropDownList;
            DropDownList ddlSessionsTo = gvTestGrid.Rows[index].Cells[0].FindControl("ddlSessionsTo") as DropDownList;
            DropDownList ddlLeaveTypes = gvTestGrid.Rows[index].Cells[0].FindControl("ddlLeaveTypes") as DropDownList;
            districtDetails.DefaultView.RowFilter = "SLNO=" + (index + 1);
            string strLeaveSessionFromValue = districtDetails.DefaultView.ToTable().Rows[0]["LeaveSessionsFrom"].ToString();
            string strLeaveSessionToValue = districtDetails.DefaultView.ToTable().Rows[0]["LeaveSessionsTo"].ToString();
            string strLeaveTypesValue = districtDetails.DefaultView.ToTable().Rows[0]["LeaveTypes"].ToString();
            string strLeaveFrom = districtDetails.DefaultView.ToTable().Rows[0]["LeaveFrom"].ToString();
            string strLeaveTo = districtDetails.DefaultView.ToTable().Rows[0]["LeaveTo"].ToString();
            //Calendar From Date Binding
            TextBox txtFromDate = gvTestGrid.Rows[index].Cells[0].FindControl("txtFromDate") as TextBox;
            TextBox txtToDate = gvTestGrid.Rows[index].Cells[0].FindControl("txtToDate") as TextBox;
            ddlSessionsFrom.DataSource = dsLeaveSessionsFrom.Tables["LeaveSessionsFrom"];
            ddlSessionsFrom.DataTextField = "LeaveSessionsFromName";
            ddlSessionsFrom.DataValueField = "LeaveSessionsFromValue";
            ddlSessionsFrom.DataBind();
            ddlSessionsTo.DataSource = dsLeaveSessionsTo.Tables["LeaveSessionsTo"];
            ddlSessionsTo.DataTextField = "LeaveSessionsToName";
            ddlSessionsTo.DataValueField = "LeaveSessionsToValue";
            ddlSessionsTo.DataBind();
            if (strLeaveSessionFromValue != string.Empty)
            {
                ddlSessionsFrom.SelectedValue = strLeaveSessionFromValue;
            }
            if (strLeaveSessionToValue != string.Empty)
            {
                ddlSessionsTo.SelectedValue = strLeaveSessionToValue;
            }
            if (ddlLeaveCategory.SelectedItem.Text == "Leave")
            {
                dsLeaveTypesDataLocal = dsLeaveTypesData;
            }
            else if (ddlLeaveCategory.SelectedItem.Text == "LOP")
            {
                dsLeaveTypesDataLocal = dsLeaveTypesLOPDays;
            }
            else if (ddlLeaveCategory.SelectedItem.Text == "Comp Off")
            {
                dsLeaveTypesDataLocal = dsLeaveCompOff;
            }
            ddlLeaveTypes.Items.Clear();
            ddlLeaveTypes.DataSource = dsLeaveTypesDataLocal.Tables["Details"];
            ddlLeaveTypes.DataTextField = "LeaveType";
            ddlLeaveTypes.DataValueField = "LeaveType_Id";
            ddlLeaveTypes.DataBind();
            if (strLeaveTypesValue != string.Empty)
            {
                ddlLeaveTypes.SelectedValue = strLeaveTypesValue;
            }
            txtFromDate.Text = strLeaveFrom;
            txtToDate.Text = strLeaveTo;
        }
    }
    #endregion
    #region LoadComboInGridFirstTime
    private void LoadComboInGridFirstTime(DataTable districtDetails)
    {
        //Leave From Session 
        DataSet dsLeaveSessionsFrom = new DataSet();
        DataTable dtLeaveSessionsFrom = new DataTable();
        dtLeaveSessionsFrom.TableName = "LeaveSessionsFrom";
        DataColumn dcLeaveSessionsFromName = new DataColumn("LeaveSessionsFromName");
        DataColumn dcLeaveSessionsFromValue = new DataColumn("LeaveSessionsFromValue");
        dtLeaveSessionsFrom.Columns.Add(dcLeaveSessionsFromName);
        dtLeaveSessionsFrom.Columns.Add(dcLeaveSessionsFromValue);
        DataRow dRowLeaveSessionsFrom;
        dRowLeaveSessionsFrom = dtLeaveSessionsFrom.NewRow();
        dRowLeaveSessionsFrom["LeaveSessionsFromName"] = "First Half";
        dRowLeaveSessionsFrom["LeaveSessionsFromValue"] = "1";
        dRowLeaveSessionsFrom.EndEdit();
        dtLeaveSessionsFrom.Rows.Add(dRowLeaveSessionsFrom);
        dRowLeaveSessionsFrom = dtLeaveSessionsFrom.NewRow();
        dRowLeaveSessionsFrom["LeaveSessionsFromName"] = "Second Half";
        dRowLeaveSessionsFrom["LeaveSessionsFromValue"] = "2";
        dRowLeaveSessionsFrom.EndEdit();
        dtLeaveSessionsFrom.Rows.Add(dRowLeaveSessionsFrom);
        dsLeaveSessionsFrom.Tables.Add(dtLeaveSessionsFrom);
        //Leave To Session 
        DataSet dsLeaveSessionsTo = new DataSet();
        DataTable dtLeaveSessionsTo = new DataTable();
        dtLeaveSessionsTo.TableName = "LeaveSessionsTo";
        DataColumn dcLeaveSessionsToName = new DataColumn("LeaveSessionsToName");
        DataColumn dcLeaveSessionsToValue = new DataColumn("LeaveSessionsToValue");
        dtLeaveSessionsTo.Columns.Add(dcLeaveSessionsToName);
        dtLeaveSessionsTo.Columns.Add(dcLeaveSessionsToValue);
        DataRow dRowLeaveSessionsTo;
        dRowLeaveSessionsTo = dtLeaveSessionsTo.NewRow();
        dRowLeaveSessionsTo["LeaveSessionsToName"] = "First Half";
        dRowLeaveSessionsTo["LeaveSessionsToValue"] = "1";
        dRowLeaveSessionsTo.EndEdit();
        dtLeaveSessionsTo.Rows.Add(dRowLeaveSessionsTo);
        dRowLeaveSessionsTo = dtLeaveSessionsTo.NewRow();
        dRowLeaveSessionsTo["LeaveSessionsToName"] = "Second Half";
        dRowLeaveSessionsTo["LeaveSessionsToValue"] = "2";
        dRowLeaveSessionsTo.EndEdit();
        dtLeaveSessionsTo.Rows.Add(dRowLeaveSessionsTo);
        dsLeaveSessionsTo.Tables.Add(dtLeaveSessionsTo);
        int EmployeeId = 0;
        if (hdnEmployeeId.Value != string.Empty)
        {
            EmployeeId = Convert.ToInt32(hdnEmployeeId.Value);
        }
        dsLeaveTypesData = objLeaveApplicationEventData.GetLeaveTypesOfEmployees_Angler(EmployeeId);
        if (hdnEmployeeId.Value == string.Empty)
        {
            //Comp Off Leaves
            DataSet dsLeaveCompOff = new DataSet();
            DataTable dtLeaveCompOff = new DataTable();
            dtLeaveCompOff.TableName = "Details";
            DataColumn dcLeaveCompOffName = new DataColumn("LeaveType");
            DataColumn dcLeaveCompOffValue = new DataColumn("LeaveType_Id");
            dtLeaveCompOff.Columns.Add(dcLeaveCompOffName);
            dtLeaveCompOff.Columns.Add(dcLeaveCompOffValue);
            DataRow dRowLeaveCompOff;
            dRowLeaveCompOff = dtLeaveCompOff.NewRow();
            dRowLeaveCompOff["LeaveType"] = "Others";
            dRowLeaveCompOff["LeaveType_Id"] = "1";
            dRowLeaveCompOff.EndEdit();
            dtLeaveCompOff.Rows.Add(dRowLeaveCompOff);
            dsLeaveCompOff.Tables.Add(dtLeaveCompOff);
            dsLeaveTypesData = dsLeaveCompOff;
        }
        dsLeaveTypesData.Tables[0].TableName = "Details";
        for (int index = 0; index < gvTestGrid.Rows.Count; index++)
        {
            //DropDownList ddlLeaveCategory = gvTestGrid.Rows[index].Cells[0].FindControl("ddlLeaveCategory") as DropDownList;
            DropDownList ddlSessionsFrom = gvTestGrid.Rows[index].Cells[0].FindControl("ddlSessionsFrom") as DropDownList;
            DropDownList ddlSessionsTo = gvTestGrid.Rows[index].Cells[0].FindControl("ddlSessionsTo") as DropDownList;
            DropDownList ddlLeaveTypes = gvTestGrid.Rows[index].Cells[0].FindControl("ddlLeaveTypes") as DropDownList;
            districtDetails.DefaultView.RowFilter = "SLNO=" + (index + 1);
            string strLeaveSessionFromValue = districtDetails.DefaultView.ToTable().Rows[0]["LeaveSessionsFrom"].ToString();
            string strLeaveSessionToValue = districtDetails.DefaultView.ToTable().Rows[0]["LeaveSessionsTo"].ToString();
            string strLeaveTypesValue = districtDetails.DefaultView.ToTable().Rows[0]["LeaveTypes"].ToString();
            string strLeaveFrom = districtDetails.DefaultView.ToTable().Rows[0]["LeaveFrom"].ToString();
            string strLeaveTo = districtDetails.DefaultView.ToTable().Rows[0]["LeaveTo"].ToString();
            //Calendar From Date Binding
            HtmlGenericControl divLeaveFrom = gvTestGrid.Rows[index].Cells[0].FindControl("LeaveFromDivText") as HtmlGenericControl;
            TextBox txtFromDate = gvTestGrid.Rows[index].Cells[0].FindControl("txtFromDate") as TextBox;
            string strLeaveFromDiv = "<input id='btn_FromDate" + index.ToString() + "' src='../Images/dateicon.gif' type='image' tabindex='6' runat='server' />";
            strLeaveFromDiv += "<script type='text/javascript'>";
            strLeaveFromDiv += "Calendar.setup({";
            strLeaveFromDiv += "inputField     :    '" + txtFromDate.ClientID + "',";      // id of the input field
            strLeaveFromDiv += "ifFormat       :   '" + Session["IDateFormat"].ToString() + "',";       // format of the input field
            strLeaveFromDiv += "showsTime      :    false,";            // will display a time selector
            strLeaveFromDiv += "button         :    'btn_FromDate" + index.ToString() + "',";   // trigger for the calendar (button ID)
            strLeaveFromDiv += "singleClick    :    true,";           // double-click mode
            strLeaveFromDiv += "step           :    1";                // show all years in drop-down boxes (instead of every other year as default)
            strLeaveFromDiv += "});</script>";
            divLeaveFrom.InnerHtml = strLeaveFromDiv;
            //Calendar From Date Binding end here
            //Calendar TO Date Binding Starts here
            HtmlGenericControl divLeaveTo = gvTestGrid.Rows[index].Cells[0].FindControl("LeaveToDivText") as HtmlGenericControl;
            TextBox txtToDate = gvTestGrid.Rows[index].Cells[0].FindControl("txtToDate") as TextBox;
            string strLeaveToDiv = "<input id='btn_ToDate" + index.ToString() + "' src='../Images/dateicon.gif' type='image' tabindex='6' runat='server' />";
            strLeaveToDiv += "<script type='text/javascript'>";
            strLeaveToDiv += "Calendar.setup({";
            strLeaveToDiv += "inputField     :    '" + txtToDate.ClientID + "',";      // id of the input field
            strLeaveToDiv += "ifFormat       :   '" + Session["IDateFormat"].ToString() + "',";       // format of the input field
            strLeaveToDiv += "showsTime      :    false,";            // will display a time selector
            strLeaveToDiv += "button         :    'btn_ToDate" + index.ToString() + "',";   // trigger for the calendar (button ID)
            strLeaveToDiv += "singleClick    :    true,";           // double-click mode
            strLeaveToDiv += "step           :    1";                // show all years in drop-down boxes (instead of every other year as default)
            strLeaveToDiv += "});</script>";
            divLeaveTo.InnerHtml = strLeaveToDiv;
            //Calendar To Date Binding end here
            ddlSessionsFrom.DataSource = dsLeaveSessionsFrom.Tables["LeaveSessionsFrom"];
            ddlSessionsFrom.DataTextField = "LeaveSessionsFromName";
            ddlSessionsFrom.DataValueField = "LeaveSessionsFromValue";
            ddlSessionsFrom.DataBind();
            ddlSessionsTo.DataSource = dsLeaveSessionsTo.Tables["LeaveSessionsTo"];
            ddlSessionsTo.DataTextField = "LeaveSessionsToName";
            ddlSessionsTo.DataValueField = "LeaveSessionsToValue";
            ddlSessionsTo.DataBind();
            if (strLeaveSessionFromValue != string.Empty)
            {
                ddlSessionsFrom.SelectedValue = strLeaveSessionFromValue;
            }
            if (strLeaveSessionToValue != string.Empty)
            {
                ddlSessionsTo.SelectedValue = strLeaveSessionToValue;
            }
            if (dsLeaveTypesData.Tables[0].Rows.Count > 0)
            {
                ddlLeaveTypes.DataSource = dsLeaveTypesData.Tables["Details"];
                ddlLeaveTypes.DataTextField = "LeaveType";
                ddlLeaveTypes.DataValueField = "LeaveType_Id";
                ddlLeaveTypes.DataBind();
            }
            if (strLeaveTypesValue != string.Empty)
            {
                ddlLeaveTypes.SelectedValue = strLeaveTypesValue;
            }
            else
            {
                ddlLeaveTypes.SelectedIndex = 0;
            }
            txtFromDate.Text = strLeaveFrom;
            txtToDate.Text = strLeaveTo;
        }
    }
    #endregion
    public void ddlLeaveCategory_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (hdnEmployeeId.Value == string.Empty)
        {
            Message("Select Employee");
            return;
        }
        DataTable districtDetails = LoadDataFromGrid();
        string strname = ((DropDownList)sender).ClientID.ToString();
        string strSelectedLeaveCategory = ((DropDownList)sender).SelectedItem.Text;
        int EmployeeId = Convert.ToInt32(hdnEmployeeId.Value);
        if (strSelectedLeaveCategory == "Leave")
        {
            dsLeaveTypesData = objLeaveApplicationEventData.GetLeaveTypesOfEmployees_Angler(EmployeeId);
            dsLeaveTypesData.Tables[0].TableName = "Details";
            if (dsLeaveTypesData.Tables["Details"].Rows.Count > 0)
            {
                Session["sessionLeaveTypes"] = dsLeaveTypesData;
            }
            else
            {
            }
        }
        else if (strSelectedLeaveCategory == "LOP")
        {
            dsLeaveTypesLOPDays = objLeaveApplicationEventData.GetLOPLeaveTypeDetails(EmployeeId);
            dsLeaveTypesLOPDays.Tables[0].TableName = "Details";
            if (dsLeaveTypesLOPDays.Tables["Details"].Rows.Count > 0)
            {
                Session["sessionLeaveTypes"] = dsLeaveTypesLOPDays;
                dsLeaveTypesData = dsLeaveTypesLOPDays;
            }
            else
            {
            }
        }
        else if (strSelectedLeaveCategory == "Restricted Holiday")
        {
            string HolidayType = "Y";
            int HolidayId = -1;
            string UserGroupName = string.Empty;
            dsHolidays = objLeaveApplicationEventData.GetRestrictedHoliday(HolidayType, HolidayId, UserGroupName);
            dsHolidays.Tables[0].TableName = "Details";
            if (dsHolidays.Tables["Details"].Rows.Count > 0)
            {
                dsLeaveTypesData = dsHolidays;
                Session["sessionLeaveTypes"] = dsHolidays;
            }
            else
            {
            }
        }
        else if (strSelectedLeaveCategory == "Comp Off")
        {
            //Comp Off Leaves
            DataSet dsLeaveCompOff = new DataSet();
            DataTable dtLeaveCompOff = new DataTable();
            dtLeaveCompOff.TableName = "Details";
            DataColumn dcLeaveCompOffName = new DataColumn("LeaveType");
            DataColumn dcLeaveCompOffValue = new DataColumn("LeaveType_Id");
            dtLeaveCompOff.Columns.Add(dcLeaveCompOffName);
            dtLeaveCompOff.Columns.Add(dcLeaveCompOffValue);
            DataRow dRowLeaveCompOff;
            dRowLeaveCompOff = dtLeaveCompOff.NewRow();
            dRowLeaveCompOff["LeaveType"] = "Others";
            dRowLeaveCompOff["LeaveType_Id"] = "1";
            dRowLeaveCompOff.EndEdit();
            dtLeaveCompOff.Rows.Add(dRowLeaveCompOff);
            dsLeaveCompOff.Tables.Add(dtLeaveCompOff);
            dsLeaveTypesData = dsLeaveCompOff;
        }
        string[] strarry = strname.Split('_');
        int intSLNo = Convert.ToInt32(strarry[3].Replace("ctl", string.Empty).Trim());
        intSLNo = intSLNo - 2;
        for (int index = 0; index < gvTestGrid.Rows.Count; index++)
        {
            if (intSLNo == index)
            {
                DropDownList ddlLeaveTypes = gvTestGrid.Rows[index].Cells[0].FindControl("ddlLeaveTypes") as DropDownList;
                ddlLeaveTypes.Items.Clear();
                ddlLeaveTypes.DataSource = dsLeaveTypesData.Tables["Details"];
                ddlLeaveTypes.DataTextField = "LeaveType";
                ddlLeaveTypes.DataValueField = "LeaveType_Id";
                ddlLeaveTypes.DataBind();
            }
        }
    }
    /// <summary>
    /// Handles the Click event of the btn_add control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void btn_add_Click(object sender, EventArgs e)
    {
        //System.Threading.Thread.Sleep(10);
        string strSelectedLeaveCategory1 = string.Empty;
        if (hdnEmployeeId.Value == string.Empty)
        {
            Message("Select Employee");
            return;
        }
        //Page.RegisterStartupScript("processing", "<script></script>");
        if (txtReason.Text.Trim() == string.Empty)
        {
            Message("Enter Reason");
            return;
        }
        string strLengthCheck = txtReason.Text.Trim().Replace("'", "''");
        if (strLengthCheck.Length > 1000)
        {
            Message("Maximum character for Reason is 1000");
            return;
        }
        //Checking and Convert to Date Format MM/dd/yyyy
        gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
        dsRemainingNoOfLeaves.Clear();
        DataTable districtDetails = LoadDataFromGridWithLeaveCategory();
        if (DateConvertion(gstrDateFormat, districtDetails.Rows[0]["LeaveFrom"].ToString()))
        {
        }
        else
        {
            Message("Invalid Date Format");
            return;
        }
        LoadRemainingLeaves(districtDetails.Rows[0]["LeaveFrom"].ToString());
        LoadCompOffDays();
        districtDetails.TableName = "All Details";
        int iterator = districtDetails.Rows.Count;
        DataTable dtFirstTable = new DataTable();
        DataTable dtSecondTable = new DataTable();
        string strFirstLeaveFrom = string.Empty;
        string strFirstLeaveTo = string.Empty;
        string strFirstSessionFrom = string.Empty;
        string strFirstSessionTo = string.Empty;
        string strSecondLeaveFrom = string.Empty;
        string strSecondLeaveTo = string.Empty;
        string strSecondSessionFrom = string.Empty;
        string strSecondSessionTo = string.Empty;
        string NoOfLeaves = string.Empty;
        int i, j = 0;
        int DaysForSuccessive = 0;
        if (iterator == 1)
        {
            strFirstLeaveFrom = districtDetails.Rows[0]["LeaveFrom"].ToString();
            strFirstLeaveTo = districtDetails.Rows[0]["LeaveTo"].ToString();
            strFirstSessionFrom = districtDetails.Rows[0]["LeaveSessionsFrom"].ToString();
            strFirstSessionTo = districtDetails.Rows[0]["LeaveSessionsTo"].ToString();
            if (strFirstLeaveFrom == string.Empty || strFirstLeaveTo == string.Empty)
            {
                Message("Leave Dates should not be empty");
                return;
            }
            if (DateConvertion(gstrDateFormat, strFirstLeaveFrom))
            {
            }
            else
            {
                Message("Invalid Date Format");
                return;
            }
            if (DateConvertion(gstrDateFormat, strFirstLeaveTo))
            {
            }
            else
            {
                Message("Invalid Date Format");
                return;
            }
            //DateTime FromMonth=new DateTime();
            //FromMonth=Convert.ToDateTime(strFirstLeaveFrom).Month.ToString();
            //Added by Manjula.P on 13-May-2014 for genral datetime format
            strFirstLeaveFrom = objcls_Common.DateConvertion(gstrDateFormat, strFirstLeaveFrom);
            strFirstLeaveTo = objcls_Common.DateConvertion(gstrDateFormat, strFirstLeaveTo);
            if (Convert.ToDateTime(strFirstLeaveFrom).Month.ToString() != Convert.ToDateTime(strFirstLeaveTo).Month.ToString())
            {
                //Message("Cross Month Entries are not allowed kindly Split your Entries");
                Message("Leave entry is crossing the month so split as monthwise,then update");
                return;
            }
            if (DateDifference(DateTime.Parse(strFirstLeaveFrom), DateTime.Parse(strFirstLeaveTo)) < 0)
            {
                Message("In Leave-1 To Date should be greater than or equal to Leave From Date");
                return;
            }
            if (strFirstLeaveFrom == strFirstLeaveTo)
            {
                if (strFirstSessionFrom == "2" && strFirstSessionTo == "1")
                {
                    Message("Invalid Session Selection in Leave-1");
                    return;
                }
            }
            if (Session["UserGroupName"].ToString() == "SuperAdmin" || Session["HasSpecialRights"].ToString() == "True")
            {
            }
            else
            {
                string strTodaysDate = DateTime.Now.ToString(Session["MDateFormat"].ToString());
                //Added by Manjula.P on 13-May-2014 for genral datetime format as like in product
                strTodaysDate = objcls_Common.DateConvertion(gstrDateFormat, strTodaysDate);
                if ((Convert.ToDateTime(strFirstLeaveFrom) < Convert.ToDateTime(strTodaysDate)) || (Convert.ToDateTime(strFirstLeaveTo) < Convert.ToDateTime(strTodaysDate)))
                {
                    Message("Leave should not be applied for past days");
                    return;
                }
            }
        }
        else
        {
            string[] CheckDuplication = new string[iterator];
            double dsEmpCat = 0.0;
            int incrementDup = 0;
            for (int jjj = 0; jjj < iterator; jjj++)
            {
                strFirstLeaveFrom = districtDetails.Rows[jjj]["LeaveFrom"].ToString();
                strFirstLeaveTo = districtDetails.Rows[jjj]["LeaveTo"].ToString();
                if (strFirstLeaveFrom == string.Empty || strFirstLeaveTo == string.Empty)
                {
                    Message("Leave Dates should not be empty");
                    return;
                }
                if (DateConvertion(gstrDateFormat, strFirstLeaveFrom))
                {
                }
                else
                {
                    Message("Invalid Date Format");
                    return;
                }
                if (DateConvertion(gstrDateFormat, strFirstLeaveTo))
                {
                }
                else
                {
                    Message("Invalid Date Format");
                    return;
                }
                //Added by Gopinath.K on 17-May-2014 for genral datetime format as like in product
                strFirstLeaveFrom = objcls_Common.DateConvertion(gstrDateFormat, strFirstLeaveFrom);
                strFirstLeaveTo = objcls_Common.DateConvertion(gstrDateFormat, strFirstLeaveTo);
                int iDays = DateDifference(DateTime.Parse(strFirstLeaveFrom), DateTime.Parse(strFirstLeaveTo));
                DateTime dtLeavestart = Convert.ToDateTime(strFirstLeaveFrom);
                DateTime dtLeaveEnd = Convert.ToDateTime(strFirstLeaveTo);
                dsEmpCat = objLeaveApplicationEventData.GetEmployeeCategoryDetailForSat(Convert.ToInt32(hdnEmployeeId.Value), dtLeaveEnd);
                for (int id = 0; id < iDays; id++)
                {
                    string dtSat = string.Empty;
                    dtLeavestart = Convert.ToDateTime(strFirstLeaveFrom);
                    dtLeavestart = dtLeavestart.AddDays(id);
                    dtSat = dtLeavestart.DayOfWeek.ToString();
                    if (dtSat == "Saturday")
                    {
                        if (dsEmpCat <= 4)
                        {
                            CheckDuplication[incrementDup] = dtLeavestart.ToString();
                            incrementDup += 1;
                        }
                    }
                }
            }
            if (CheckDuplication.Length > 1)
            {
                for (int ii = 0; ii < CheckDuplication.Length; ii++)
                {
                    for (int jj = ii + 1; jj < CheckDuplication.Length; jj++)
                    {
                        if (CheckDuplication[ii] != null && CheckDuplication[jj] != null && CheckDuplication[ii] == CheckDuplication[jj])
                        {
                            Message("kindly apply half day leave in saturday");
                            return;
                        }
                    }
                }
            }
            for (i = 1; i < iterator; i++)
            {
                j = i + 1;
                districtDetails.DefaultView.RowFilter = "SLNO=" + i;
                dtFirstTable = districtDetails.DefaultView.ToTable();
                strFirstLeaveFrom = dtFirstTable.Rows[0]["LeaveFrom"].ToString();
                strFirstLeaveTo = dtFirstTable.Rows[0]["LeaveTo"].ToString();
                strFirstSessionFrom = dtFirstTable.Rows[0]["LeaveSessionsFrom"].ToString();
                strFirstSessionTo = dtFirstTable.Rows[0]["LeaveSessionsTo"].ToString();
                districtDetails.DefaultView.RowFilter = "SLNO=" + j;
                dtSecondTable = districtDetails.DefaultView.ToTable();
                strSecondLeaveFrom = dtSecondTable.Rows[0]["LeaveFrom"].ToString();
                strSecondLeaveTo = dtSecondTable.Rows[0]["LeaveTo"].ToString();
                strSecondSessionFrom = dtSecondTable.Rows[0]["LeaveSessionsFrom"].ToString();
                strSecondSessionTo = dtSecondTable.Rows[0]["LeaveSessionsTo"].ToString();
                if (strFirstLeaveFrom == string.Empty || strFirstLeaveTo == string.Empty || strSecondLeaveFrom == string.Empty || strSecondLeaveTo == string.Empty)
                {
                    Message("Leave Dates should not be empty");
                    return;
                }
                if (DateConvertion(gstrDateFormat, strFirstLeaveFrom))
                {
                }
                else
                {
                    Message("Invalid Date Format");
                    return;
                }
                if (DateConvertion(gstrDateFormat, strFirstLeaveTo))
                {
                }
                else
                {
                    Message("Invalid Date Format");
                    return;
                }
                if (DateConvertion(gstrDateFormat, strSecondLeaveFrom))
                {
                }
                else
                {
                    Message("Invalid Date Format");
                    return;
                }
                if (DateConvertion(gstrDateFormat, strSecondLeaveTo))
                {
                }
                else
                {
                    Message("Invalid Date Format");
                    return;
                }
                //Added by Gopinath.k on 17-May-2014 for genral datetime format
                strFirstLeaveFrom = objcls_Common.DateConvertion(gstrDateFormat, strFirstLeaveFrom);
                strFirstLeaveTo = objcls_Common.DateConvertion(gstrDateFormat, strFirstLeaveTo);
                strSecondLeaveFrom = objcls_Common.DateConvertion(gstrDateFormat, strSecondLeaveFrom);
                strSecondLeaveTo = objcls_Common.DateConvertion(gstrDateFormat, strSecondLeaveTo);
                if (Convert.ToDateTime(strFirstLeaveFrom).Month.ToString() != Convert.ToDateTime(strFirstLeaveTo).Month.ToString())
                {
                    //Message("Cross Month Entries are not allowed kindly Split your Entries");
                    Message("Leave entry is crossing the month so split as monthwise,then update");
                    return;
                }
                if (Convert.ToDateTime(strSecondLeaveFrom).Month.ToString() != Convert.ToDateTime(strSecondLeaveTo).Month.ToString())
                {
                    //Message("Cross Month Entries are not allowed kindly Split your Entries");
                    Message("Leave entry is crossing the month so split as monthwise,then update");
                    return;
                }
                if (DateDifference(DateTime.Parse(strFirstLeaveFrom), DateTime.Parse(strFirstLeaveTo)) < 0)
                {
                    Message("In Leave-" + i.ToString() + ", To Date should be greater than or equal to Leave From Date");
                    return;
                }
                if (DateDifference(DateTime.Parse(strSecondLeaveFrom), DateTime.Parse(strSecondLeaveTo)) < 0)
                {
                    Message("In Leave-" + j.ToString() + ", To Date should be greater than or equal to Leave From Date");
                    return;
                }
                if (DateTime.Parse(strFirstLeaveTo) > DateTime.Parse(strSecondLeaveFrom))
                {
                    Message("Leave-" + j.ToString() + " From Date should be greater than Leave-" + i.ToString() + " To Date");
                    return;
                }
                if (DateTime.Parse(strFirstLeaveTo) == DateTime.Parse(strSecondLeaveFrom))
                {
                    if (strFirstSessionTo == "2")
                    {
                        Message("Leave Days/Sessions Over Lapped in Leave-" + i.ToString() + " and Leave-" + j.ToString());
                        return;
                    }
                    if (strSecondSessionFrom == "1")
                    {
                        Message("Leave Days/Sessions Over Lapped in Leave-" + i.ToString() + " and Leave-" + j.ToString());
                        return;
                    }
                }
                if (strFirstLeaveFrom == strFirstLeaveTo)
                {
                    if (strFirstSessionFrom == "2" && strFirstSessionTo == "1")
                    {
                        Message("Invalid Session Selection in Leave-" + i.ToString());
                        return;
                    }
                }
                if (strSecondLeaveFrom == strSecondLeaveTo)
                {
                    if (strSecondSessionFrom == "2" && strSecondSessionTo == "1")
                    {
                        Message("Invalid Session Selection in Leave-" + j.ToString());
                        return;
                    }
                }
                if (Session["UserGroupName"].ToString() == "SuperAdmin" || Session["HasSpecialRights"].ToString() == "True")
                {
                }
                else
                {
                    string strTodaysDate = DateTime.Now.ToString(Session["MDateFormat"].ToString());
                    //Added by Manjula.P on 13-May-2014 for genral datetime format  as like in product
                    strTodaysDate = objcls_Common.DateConvertion(gstrDateFormat, strTodaysDate);
                    if ((Convert.ToDateTime(strFirstLeaveFrom) < Convert.ToDateTime(strTodaysDate)) || (Convert.ToDateTime(strFirstLeaveTo) < Convert.ToDateTime(strTodaysDate)))
                    {
                        Message("Leave should not be applied for past days");
                        return;
                    }
                }
                ////Validate leave beyond the next year setting
                //if (ViewState["NextYearSettings_Id"] != null || ViewState["NextYearSettings_Id"].ToString() != string.Empty)
                //{
                //    if (DateTime.Parse(strLeaveToDate) > DateTime.Parse(gstrNextYearSettingStartDate))
                //    {
                //        Message("Leave application cannot be raised beyond next year");
                //        return;
                //    }
                //    if ((DateTime.Parse(strLeaveFromDate) <= DateTime.Parse(gstrYearSettingsEndDate)) && DateTime.Parse(strLeaveToDate) >= DateTime.Parse(gstrNextYearSettingStartDate))
                //    {
                //        Message("Leave application cannot be applied for cross year, so please enter the leave for next year as a separate leave application");
                //        return;
                //    }
                //}
            }
        }
        //Days Validation     
        //Fill the Year Settings Detail
        DataSet ds_Year = new DataSet();
        ds_Year = objcls_Common.GetYearsetting();
        if (ds_Year.Tables[0].Rows.Count > 0)
        {
            gstrYearSettingStartDate = ds_Year.Tables[0].Rows[0]["FromDate"].ToString();
            gstrYearSettingsEndDate = ds_Year.Tables[0].Rows[0]["ToDate"].ToString();
            ViewState["YearSettings_Id"] = ds_Year.Tables[0].Rows[0]["YearSettings_Id"].ToString();
            ds_Year.Dispose();
        }
        int intIncrement = 1;
        //Leaves in Each month checking
        DataTable dtLeaveForEachMonth = new DataTable();
        dtLeaveForEachMonth.TableName = "LeaveForEachMonth";
        DataColumn dcLeaveMonth = new DataColumn("LeaveMonth");
        DataColumn dcLeaveCategoryType = new DataColumn("LeaveCategoryType");
        DataColumn dcLeaveDays = new DataColumn("LeaveDays", typeof(decimal));
        DataColumn dcLeaveType = new DataColumn("LeaveType");
        DataColumn dcMaxDaysMonth = new DataColumn("MaxDaysMonth");
        dtLeaveForEachMonth.Columns.Add(dcLeaveMonth);
        dtLeaveForEachMonth.Columns.Add(dcLeaveCategoryType);
        dtLeaveForEachMonth.Columns.Add(dcLeaveDays);
        dtLeaveForEachMonth.Columns.Add(dcLeaveType);
        dtLeaveForEachMonth.Columns.Add(dcMaxDaysMonth);
        DataRow dRowLeaveForEachMonth;
        double doubleLeaveApplicableDays = 0;
        int intcount = 0, intHalfDayCount = 0;
        int CurrentYearLeaveCount = 0;
        int NextYearLeaveCount = 0;
        decimal decCont = 0;
        foreach (DataRow dRow in districtDetails.Rows)
        {
            strLeaveCategory = string.Empty;
            strLeaveFromSession = string.Empty;
            strLeaveToSession = string.Empty;
            strLeaveFromDate = string.Empty;
            strLeaveToDate = string.Empty;
            strLeaveCategory = dRow["LeaveCategory"].ToString();
            string strLeaveTypeName = dRow["LeaveTypesName"].ToString();
            if (strLeaveCategory == "1")
            {
                strLeaveCategory = "Leave";
            }
            else if (strLeaveCategory == "2")
            {
                strLeaveCategory = "LOP";
            }
            else if (strLeaveCategory == "3")
            {
                strLeaveCategory = "Comp Off";
            }
            DataTable dtleavetype = new DataTable();
            if (strLeaveCategory == "Leave")
            {
                dsLeaveTypesData = objLeaveApplicationEventData.GetLeaveTypesOfEmployees_Angler(Convert.ToInt32(hdnEmployeeId.Value));
                dsLeaveTypesData.Tables[0].TableName = "Details";
                if (dsLeaveTypesData.Tables["Details"].Rows.Count > 0)
                {
                    //Session["sessionLeaveTypes"] = dsLeaveTypesData;
                    dtleavetype = dsLeaveTypesData.Tables["Details"];
                    dtleavetype.DefaultView.RowFilter = "LeaveType ='" + dRow["LeaveTypesName"].ToString() + "'";
                    dtleavetype = dtleavetype.DefaultView.ToTable();
                    if (dtleavetype.Rows.Count == 0)
                    {
                        Message("Select valid Leave type");
                        return;
                    }
                }
                else
                {
                }
            }
            else if (strLeaveCategory == "LOP")
            {
                dsLeaveTypesLOPDays = objLeaveApplicationEventData.GetLOPLeaveTypeDetails(Convert.ToInt32(hdnEmployeeId.Value));
                dsLeaveTypesLOPDays.Tables[0].TableName = "Details";
                if (dsLeaveTypesLOPDays.Tables["Details"].Rows.Count > 0)
                {
                    dtleavetype = dsLeaveTypesLOPDays.Tables["Details"];
                    dtleavetype.DefaultView.RowFilter = "LeaveType ='" + dRow["LeaveTypesName"].ToString() + "'";
                    dtleavetype = dtleavetype.DefaultView.ToTable();
                    if (dtleavetype.Rows.Count == 0)
                    {
                        Message("Select valid Leave type");
                        return;
                    }
                }
                else
                {
                }
            }
            else if (strLeaveCategory == "Restricted Holiday")
            {
                string HolidayType = "Y";
                int HolidayId = -1;
                string UserGroupName = string.Empty;
                dsHolidays = objLeaveApplicationEventData.GetRestrictedHoliday(HolidayType, HolidayId, UserGroupName);
                dsHolidays.Tables[0].TableName = "Details";
                if (dsHolidays.Tables["Details"].Rows.Count > 0)
                {
                    dtleavetype = dsHolidays.Tables["Details"];
                    dtleavetype.DefaultView.RowFilter = "LeaveType ='" + dRow["LeaveTypesName"].ToString() + "'";
                    dtleavetype = dtleavetype.DefaultView.ToTable();
                    if (dtleavetype.Rows.Count == 0)
                    {
                        Message("Select valid Leave type");
                        return;
                    }
                }
                else
                {
                }
            }
            else if (strLeaveCategory == "Comp Off")
            {
                //Comp Off Leaves
                DataSet dsLeaveCompOff = new DataSet();
                DataTable dtLeaveCompOff = new DataTable();
                dtLeaveCompOff.TableName = "Details";
                DataColumn dcLeaveCompOffName = new DataColumn("LeaveType");
                DataColumn dcLeaveCompOffValue = new DataColumn("LeaveType_Id");
                dtLeaveCompOff.Columns.Add(dcLeaveCompOffName);
                dtLeaveCompOff.Columns.Add(dcLeaveCompOffValue);
                DataRow dRowLeaveCompOff;
                dRowLeaveCompOff = dtLeaveCompOff.NewRow();
                dRowLeaveCompOff["LeaveType"] = "Others";
                dRowLeaveCompOff["LeaveType_Id"] = "1";
                dRowLeaveCompOff.EndEdit();
                dtLeaveCompOff.Rows.Add(dRowLeaveCompOff);
                dsLeaveCompOff.Tables.Add(dtLeaveCompOff);
                dsLeaveTypesData = dsLeaveCompOff;
            }
            strLeaveTypeId = dRow["LeaveTypes"].ToString();
            if (strLeaveTypeId == string.Empty)
            {
                Message("Leave Types should not be empty");
                return;
            }
            strLeaveFromSession = dRow["LeaveSessionsFrom"].ToString();
            if (strLeaveFromSession == "1")
            {
                strLeaveFromSession = "First Half";
            }
            else
            {
                strLeaveFromSession = "Second Half";
            }
            strLeaveToSession = dRow["LeaveSessionsTo"].ToString();
            if (strLeaveToSession == "1")
            {
                strLeaveToSession = "First Half";
            }
            else
            {
                strLeaveToSession = "Second Half";
            }
            strLeaveFromDate = dRow["LeaveFrom"].ToString();
            strLeaveToDate = dRow["LeaveTo"].ToString();
            strLeaveFromDate = objcls_Common.DateConvertion(gstrDateFormat, strLeaveFromDate);
            strLeaveToDate = objcls_Common.DateConvertion(gstrDateFormat, strLeaveToDate);
            //Date Comparision
            if (DateDifference(DateTime.Parse(strLeaveFromDate), DateTime.Parse(strLeaveToDate)) < 0)
            {
                Message("To Date should be greater than from date");
                return;
            }
            ////Validate within Year settings
            //if ((DateTime.Parse(strLeaveFromDate) >= DateTime.Parse(gstrYearSettingStartDate) && DateTime.Parse(strLeaveFromDate) <= DateTime.Parse(gstrYearSettingsEndDate)) && (DateTime.Parse(strLeaveToDate) >= DateTime.Parse(gstrYearSettingStartDate) && DateTime.Parse(strLeaveToDate) <= DateTime.Parse(gstrYearSettingsEndDate)))
            //{
            //    //Continue            
            //}
            //else
            //{
            //    Message("Select Leave Dates within current year");
            //    return;
            //}
            //Validate less than Year settings
            if ((DateTime.Parse(strLeaveToDate) < DateTime.Parse(gstrYearSettingStartDate)) || (DateTime.Parse(strLeaveFromDate) < DateTime.Parse(gstrYearSettingStartDate)))
            {
                Message("Leave duration should not be less than the current year");
                return;
            }
            //Validate leave beyond the next year setting
            if (ViewState["NextYearSettings_Id"] != null || ViewState["NextYearSettings_Id"].ToString() != string.Empty)
            {
                if (DateTime.Parse(strLeaveToDate) > DateTime.Parse(gstrNextYearSettingsEndDate))
                {
                    Message("Leave application cannot be raised beyond the next year");
                    return;
                }
                if ((DateTime.Parse(strLeaveFromDate) <= DateTime.Parse(gstrYearSettingsEndDate)) && DateTime.Parse(strLeaveToDate) >= DateTime.Parse(gstrNextYearSettingStartDate))
                {
                    Message("Leave application cannot be applied for cross year, so please enter the leave for next year as a separate leave application");
                    return;
                }
                if (DateTime.Parse(strLeaveToDate) <= DateTime.Parse(gstrYearSettingsEndDate))
                {
                    CurrentYearLeaveCount = 1;
                }
                else if (DateTime.Parse(strLeaveFromDate) >= DateTime.Parse(gstrNextYearSettingStartDate))
                {
                    NextYearLeaveCount = 1;
                }
            }
            else
            {
                if (DateTime.Parse(strLeaveToDate) > DateTime.Parse(gstrYearSettingsEndDate))
                {
                    Message("Leave application cannot be raised beyond the current year");
                    return;
                }
            }
            //Date of Joining Validation
            ds_EmployeeDetails = objLeaveApplicationEventData.GetEmployeeDetails(Convert.ToInt32(hdnEmployeeId.Value));
            gstrDateOfJoining = ds_EmployeeDetails.Tables[0].Rows[0]["DateOfJoining"].ToString();
            EmployeeCodeId = ds_EmployeeDetails.Tables[0].Rows[0]["Employee_Code_Id"].ToString();
            gstrSwipeCardNo = ds_EmployeeDetails.Tables[0].Rows[0]["SwipeCardNo"].ToString();
            //intLeaveApplicableDays = Convert.ToInt32(ds_EmployeeDetails.Tables[0].Rows[0]["LeaveApplicableDays"]);
            //Check the Leave lies between any Leave Policy of current year
            //Check Leave From Date and To Date falls between any Leave Policy with current year
            DataSet dsLeavePolicyDatesExists = new DataSet();
            DataSet dsEmployees = new DataSet();
            //FromDate = objcls_Common.DateConvertion(gstrDateFormat, Convert.ToString(Request.QueryString["FromDate"]));
            //ToDate = objcls_Common.DateConvertion(gstrDateFormat, Convert.ToString(Convert.ToString(Request.QueryString["ToDate"])));
            //YearSettingFromDate = Convert.ToDateTime(ds_Year.Tables[0].Rows[0]["YearSettingFromDate"]);
            //YearSettingToDate = Convert.ToDateTime(ds_Year.Tables[0].Rows[0]["YearSettingToDate"]);
            dsLeavePolicyDatesExists = objLeaveApplicationEventData.GetLeavePolicyDatesExists_Angler(Convert.ToInt32(hdnEmployeeId.Value), strLeaveFromDate, strLeaveToDate);
            if (dsLeavePolicyDatesExists.Tables.Count > 0)
            {
                if (dsLeavePolicyDatesExists.Tables[0].Rows.Count > 0)
                {
                    if (Convert.ToInt32(dsLeavePolicyDatesExists.Tables[0].Rows[0]["PolicyCount"]) == 0)
                    {
                        DaysForSuccessive = objLeaveApplicationEventData.GetSuccessiveDaysCount(Convert.ToInt32(Session["ParentLevelID"]));
                        //if (dsEmployees.Tables.Count > 0)
                        // {
                        if (DaysForSuccessive > 0 && DaysForSuccessive != null)
                        {
                            Session["DaysForSuccessive"] = DaysForSuccessive;
                            strYearSettingsTodate = Convert.ToDateTime(strYearSettingsTodate).AddDays(DaysForSuccessive).ToString();
                            if ((DateTime.Parse(strLeaveFromDate) >= DateTime.Parse(strYearSettingsFromdate)) && (DateTime.Parse(strLeaveToDate) <= DateTime.Parse(strYearSettingsTodate)))
                            {
                            }
                            else
                            {
                                Message("Leave dates should be within the Policy period");
                                return;
                            }
                        }
                        else
                        {
                            Message("No Policy Defined / Leave dates should be within the Policy period");
                            return;
                        }
                    }
                }
            }
            if (DateTime.Parse(gstrDateOfJoining) <= DateTime.Parse(strLeaveFromDate))
            {
                //Leave dates Applicable
                DataSet dsRequiredPeriod = new DataSet();
                if (strLeaveCategory != "Comp Off" && DaysForSuccessive == 0)
                {
                    dsRequiredPeriod = objLeaveApplicationEventData.GetApplicableAfterDays(Convert.ToInt32(hdnEmployeeId.Value), Convert.ToInt32(strLeaveTypeId), strLeaveFromDate);
                    if (dsRequiredPeriod.Tables.Count > 0)
                    {
                        dsRequiredPeriod.Tables[0].TableName = "Details";
                        if (dsRequiredPeriod.Tables[0].Rows[0]["RemainingNoOfLeaves"].ToString() == "Y")
                        {
                        }
                        else
                        {
                            //Leave dates not applicable
                            Message("Leave dates are not applicable");
                            return;
                        }
                    }
                }
            }
            else
            {
                //Leave dates not applicable
                Message("Leave dates should be greater than Date of Joining");
                return;
            }
            doubleLeaveApplicableDays = 0;
            int EmployeeId = 0;
            decimal SatWorkHrs = 0;
            if (hdnEmployeeId.Value != string.Empty)
                EmployeeId = Convert.ToInt32(hdnEmployeeId.Value);
            DataSet dsSaturdayWorkHrs = objLeaveApplicationEventData.dsGetSaturdayWorkHrs(EmployeeId);
            if (dsSaturdayWorkHrs.Tables[0].Rows.Count > 0)
            {
                if (Convert.ToString(dsSaturdayWorkHrs.Tables[0].Rows[0]["Sat_WorkHrs"]) != string.Empty)
                    SatWorkHrs = Convert.ToInt32(dsSaturdayWorkHrs.Tables[0].Rows[0]["Sat_WorkHrs"]);
            }
            //checking whether the logined employee is cumulative employee or not.
            if (SatWorkHrs >= 8)
            {
                doubleLeaveApplicableDays = Convert.ToDouble(objLeaveApplicationEventData.GetMaxDaysPerMonth((Convert.ToInt32(hdnEmployeeId.Value)), Convert.ToInt32(strLeaveTypeId), strLeaveFromDate, false, 0));
            }
            else
            {
                doubleLeaveApplicableDays = Convert.ToDouble(objLeaveApplicationEventData.GetMaxDaysPerMonth((Convert.ToInt32(hdnEmployeeId.Value)), Convert.ToInt32(strLeaveTypeId), strLeaveFromDate, true, 0));
            }
            //Check the Shift is allocated or not
            int ShiftCount = CheckShift();
            if (ShiftCount == 0)
            {
                Message("Shift not allocated for these leave days");
                return;
            }
            //Check Leaves already Taken in a month
            if (strLeaveCategory == "Leave")
            {
                fltLeaveTakenInMonth = objLeaveApplicationEventData.GetLeaveTakenInMonth(hdnEmployeeId.Value, strLeaveTypeId, strLeaveFromDate, strLeaveToDate, 0);
            }
            //Calculate Number of Days Applied based on Leave Policy
            testvalue = 0;
            string strDays = CalculateNumberOfDaysApplied();
            if (strDays == "MaxLeaveTakenExceedsInMonth")
            {
                //document.getElementById('ctl00_CP_Transaction_txt_Numberofdays').value="";
                Message("CL Leave Exceeds the Limit");
                return;
            }
            else if (strDays == "MaxLeaveTakenInMonth")
            {
                //document.getElementById('ctl00_CP_Transaction_txt_Numberofdays').value="";
                Message("CL already taken in this month");
                return;
            }
            else if (strDays == "HalfDayIsDisabled")
            {
                //document.getElementById('ctl00_CP_Transaction_txt_Numberofdays').value="";
                Message("Half day is not allowed");
                return;
            }
            else if (strDays == "InvalidYear")
            {
                //document.getElementById('ctl00_CP_Transaction_txt_Numberofdays').value="";
                Message("Select valid year");
                return;
            }
            else if (strDays == "FromToDates")
            {
                //document.getElementById('ctl00_CP_Transaction_txt_Numberofdays').value="";
                Message("Leave From Date should not be greater than Leave To Date");
                return;
            }
            else if (strDays == "DateOfJoining")
            {
                //document.getElementById('ctl00_CP_Transaction_txt_Numberofdays').value="";
                Message("Leave should not be applied before date of joining");
                return;
            }
            else if (strDays == "NoLeavePolicyDates")
            {
                //document.getElementById('ctl00_CP_Transaction_txt_Numberofdays').value="";
                Message("No Leave Policy exists for this Leave From Date or To Date");
                return;
            }
            else if (strDays == "ApplicableAfterDays")
            {
                Message("Leave should be applied, applicable after days");
                return;
            }
            else if (strDays == "Holiday")
            {
                Message("You are selecting Holiday");
                return;
            }
            else if (strDays == "WeeklyOffFromDate")
            {
                Message("You are selecting Weekly Off in From date");
                return;
            }
            else if (strDays == "WeeklyOffToDate")
            {
                Message("You are selecting Weekly Off in To date");
                return;
            }
            else if (strDays == "WeeklyOff")
            {
                Message("You are selecting Weekly Off");
                return;
            }
            else if (strDays == "HolidayWeeklyOff")
            {
                Message("Leave Application cannot be raised during Weekly Off / Global Holiday");
                return;
            }
            else if (strDays == "NoLeaveTypeId")
            {
                Message("Select Leave and LeaveTypeId");
                return;
            }
            else if (strDays == "ShiftNotAllocated")
            {
                Message("Shift not allocated");
                return;
            }
            else if (strDays == "kindly apply half day leave in saturday")
            {
                Message("kindly apply half day leave in saturday");
                return;
            }
            else if (strDays == "kindly split up the records and apply half day leave in saturday")
            {
                Message("kindly split up the records and apply half day leave in saturday");
                return;
            }
            else if (strDays == "Leave has already applied for these dates")
            {
                Message("Leave has already applied for these dates");
                return;
            }
            string[] NumberOfDays = strDays.Split(',');
            if (Convert.ToDouble(NumberOfDays[0]) < 0)
            {
                Message("Select Valid From Date and To Date");
                return;
            }
            else if (Convert.ToInt32(NumberOfDays[1]) == 0)
            {
                //return;
            }
            else if (Convert.ToInt32(NumberOfDays[1]) == 1)
            {
                //Message("You have choosed after weekly Off, One Day Added");
                //return;
            }
            else if (Convert.ToInt32(NumberOfDays[1]) == 2)
            {
                //Message("You have choosed Before weekly Off, One Day Added");
                //return;
            }
            else if (Convert.ToInt32(NumberOfDays[1]) == 3)
            {
                //Message("You have selected Intervening weekly Off / Global Holiday " + NumberOfDays[2] + " Day(s) Deducted");
                //return;
            }
            else if (Convert.ToInt32(NumberOfDays[1]) == 4)
            {
                //Message("You have selected Intervening weekly Off / Global Holiday " + NumberOfDays[2] + " Day(s) included ");
                //return;
            }
            else if (Convert.ToInt32(NumberOfDays[1]) == -1)
            {
                //return;
            }
            NoOfLeaves = NumberOfDays[0];
            dRow["NoOfLeaves"] = NoOfLeaves;
            //if (doubleLeaveApplicableDays == 0)
            //{
            #region To restrict continous more than 2 days by Manjula.P on 24-May-2013
            if (Convert.ToDecimal(NoOfLeaves) > 2 && strLeaveCategory != "LOP" && strLeaveTypeName != "SL")
            {
                Message("Cant Applied Leave More Than [2] Days Continously!.");
                return;
            }
            #endregion
            string strLeaveTypesName = dRow["LeaveTypesName"].ToString();
            if (strLeaveCategory == "Leave")
            {
                DateTime dtmLeaveMonth = new DateTime(DateTime.Parse(strLeaveFromDate).Year, DateTime.Parse(strLeaveFromDate).Month, 1);
                string strMonth = dtmLeaveMonth.ToShortDateString();
                if (dtLeaveForEachMonth.Rows.Count > 0)
                {
                    dtLeaveForEachMonth.DefaultView.RowFilter = "LeaveMonth='" + strMonth + "' and LeaveType='" + strLeaveTypesName + "'";
                }
                if (dtLeaveForEachMonth.DefaultView.ToTable().Rows.Count == 0)
                {
                    dRowLeaveForEachMonth = dtLeaveForEachMonth.NewRow();
                    dRowLeaveForEachMonth["LeaveMonth"] = strMonth;
                    dRowLeaveForEachMonth["LeaveCategoryType"] = strLeaveCategory + "-" + strLeaveTypesName;
                    if ((SatWorkHrs >= 8))
                    {
                        dRowLeaveForEachMonth["LeaveDays"] = Convert.ToString(fltLeaveTakenInMonth + Convert.ToDouble(NoOfLeaves));
                    }
                    else
                    {
                        dRowLeaveForEachMonth["LeaveDays"] = Convert.ToString(Convert.ToDouble(NoOfLeaves));
                    }
                    dRowLeaveForEachMonth["LeaveType"] = strLeaveTypesName;
                    dRowLeaveForEachMonth["MaxDaysMonth"] = doubleLeaveApplicableDays;
                    dRowLeaveForEachMonth.EndEdit();
                    dtLeaveForEachMonth.Rows.Add(dRowLeaveForEachMonth);
                }
                else
                {
                    foreach (DataRow DRowLeaves in dtLeaveForEachMonth.Rows)
                    {
                        if (DRowLeaves["LeaveMonth"].ToString() == strMonth)
                        {
                            DRowLeaves["LeaveCategoryType"] = strLeaveCategory + "-" + strLeaveTypesName;
                            string strLeaves = Convert.ToString((Convert.ToDouble(DRowLeaves["LeaveDays"]) + Convert.ToDouble(NoOfLeaves)));
                            DRowLeaves["LeaveDays"] = strLeaves;
                            DRowLeaves["LeaveType"] = strLeaveTypesName;
                            DRowLeaves["MaxDaysMonth"] = doubleLeaveApplicableDays;
                        }
                    }
                }
            }
            //}
            //Remaining Leave Validation
            if (dRow["LeaveCategoryName"].ToString() == "Leave" || dRow["LeaveCategoryName"].ToString() == "Comp Off")
            {
                foreach (DataRow dRowRemainingLeaves in dsRemainingNoOfLeaves.Tables[0].Rows)
                {
                    if (dRowRemainingLeaves["Leave Type"].ToString() == dRow["LeaveTypesName"].ToString())
                    {
                        dRowRemainingLeaves["Number Of Days"] = (Convert.ToDouble(dRowRemainingLeaves["Number Of Days"]) - Convert.ToDouble(NumberOfDays[0]));
                    }
                }
            }
            //Existing Leave and Permission Validations to be done here
            //Check FromDate and ToDate. Check whether the leave has already applied for a particular Date. 
            intcount = objLeaveApplicationEventData.CheckLeaveApplication(-1, Convert.ToInt32(hdnEmployeeId.Value), strLeaveFromDate, strLeaveToDate, strLeaveFromSession, strLeaveToSession);
            //Check Leave Count for Half Day Leave, if FromDate and Todate are same and SessionFrom and SessionTo are same
            if (strLeaveFromDate == strLeaveToDate && strLeaveFromSession == strLeaveToSession)
            {
                intHalfDayCount = objLeaveApplicationEventData.CheckHalfDayLeave(Convert.ToInt32(hdnEmployeeId.Value), strLeaveFromDate, strLeaveToDate, strLeaveFromSession, strLeaveToSession);
            }
            if (intcount == 0 && intHalfDayCount == 0)
            {
            }
            else
            {
                Message("Leave has already applied for these dates");
                return;
            }
            DataSet dsPermissionOnSameDay = new DataSet();
            dsPermissionOnSameDay = objLeaveApplicationEventData.CheckLeavePermissionOnSameDate(Convert.ToInt32(hdnEmployeeId.Value), strLeaveFromDate, strLeaveToDate);
            if (dsPermissionOnSameDay.Tables[0].Rows.Count > 0)
            {
                DateTime dtPermissionDate = new DateTime();
                dtPermissionDate = Convert.ToDateTime(dsPermissionOnSameDay.Tables[0].Rows[0]["Permission_Date"].ToString());
                string strPermissionDate = dtPermissionDate.ToString(Session["MDateFormat"].ToString());
                Message("Permission has applied for the Date" + " " + strPermissionDate);
                return;
            }
            intIncrement = intIncrement + 1;
            if (Convert.ToString(dRow["LeaveCategoryName"]) != "LOP" && Convert.ToString(dRow["LeaveTypesName"]) != "SL")
            {
                int index = districtDetails.Rows.IndexOf(dRow);
                DataRow NextRow = getNextRow(districtDetails, index);
                DataRow PreviousRow = getPreviousRow(districtDetails, index);
                if (NextRow != null)
                {
                    //for checking continous date.
                    DateTime LeaveTo = Convert.ToDateTime(dRow["LeaveTo"]);
                    //RecursionHoliday(Convert.ToDateTime(dRow["LeaveTo"]), 'P');
                    DateTime LeaveNextFrom = RecursionHoliday(Convert.ToDateTime(dRow["LeaveTo"]).AddDays(1), 'P');
                    if (Convert.ToDateTime(NextRow["LeaveFrom"]) == LeaveNextFrom && NextRow["LeaveCategoryName"].ToString() != "LOP")
                    {
                        if (dRow["NoOfLeaves"].ToString() == "0")
                            decCont = decCont + Convert.ToDecimal(dRow["NoOfLeaves"].ToString());
                        else
                            decCont = decCont + Convert.ToDecimal(NoOfLeaves);
                    }
                }
                else if (PreviousRow != null)
                {
                    //for checking continous date.
                    DateTime LeaveFrom = Convert.ToDateTime(dRow["LeaveFrom"]);
                    //RecursionHoliday(Convert.ToDateTime(dRow["LeaveTo"]), 'P');
                    DateTime LeavePreviousTo = RecursionHoliday(Convert.ToDateTime(dRow["LeaveFrom"]).AddDays(-1), 'N');
                    if (Convert.ToDateTime(PreviousRow["LeaveTo"]) == LeavePreviousTo && PreviousRow["LeaveCategoryName"].ToString() != "LOP")
                    {
                        if (dRow["NoOfLeaves"].ToString() == "0")
                            decCont = decCont + Convert.ToDecimal(dRow["NoOfLeaves"].ToString());
                        else
                            decCont = decCont + Convert.ToDecimal(NoOfLeaves);
                    }
                }
                else
                {
                    decCont = 0;
                }
            }
            //checking continoues with rows data dates. getting decCount
            #region Comeented by A.K.T.Moorthi 03-Feb-2014
            //if (Convert.ToString(dRow["LeaveCategoryName"]) != "LOP")
            //{
            //    int index = districtDetails.Rows.IndexOf(dRow);
            //    DataRow NextRow = getNextRow(districtDetails, index);
            //    DataRow PreviousRow = getPreviousRow(districtDetails, index);
            //    if (NextRow != null)
            //    {
            //        //for checking continous date.
            //        DateTime LeaveTo = Convert.ToDateTime(dRow["LeaveTo"]);
            //        //RecursionHoliday(Convert.ToDateTime(dRow["LeaveTo"]), 'P');
            //        DateTime LeaveNextFrom = RecursionHoliday(Convert.ToDateTime(dRow["LeaveTo"]).AddDays(1), 'P');
            //        if (Convert.ToDateTime(NextRow["LeaveFrom"]) == LeaveNextFrom && NextRow["LeaveCategoryName"].ToString() != "LOP")
            //        {
            //            if (dRow["NoOfLeaves"].ToString() == "0")
            //                decCont = decCont + Convert.ToDecimal(dRow["NoOfLeaves"].ToString());
            //            else
            //                decCont = decCont + Convert.ToDecimal(NoOfLeaves);
            //        }
            //    }
            //    else if (PreviousRow != null)
            //    {
            //        //for checking continous date.
            //        DateTime LeaveFrom = Convert.ToDateTime(dRow["LeaveFrom"]);
            //        //RecursionHoliday(Convert.ToDateTime(dRow["LeaveTo"]), 'P');
            //        DateTime LeavePreviousTo = RecursionHoliday(Convert.ToDateTime(dRow["LeaveFrom"]).AddDays(-1), 'N');
            //        if (Convert.ToDateTime(PreviousRow["LeaveTo"]) == LeavePreviousTo && PreviousRow["LeaveCategoryName"].ToString() != "LOP")
            //        {
            //            if (dRow["NoOfLeaves"].ToString() == "0")
            //                decCont = decCont + Convert.ToDecimal(dRow["NoOfLeaves"].ToString());
            //            else
            //                decCont = decCont + Convert.ToDecimal(NoOfLeaves);
            //        }
            //    }
            //    else
            //    {
            //        decCont = 0;
            //    }
            //} 
            #endregion
        }
        if (CurrentYearLeaveCount == 1 && NextYearLeaveCount == 1)
        {
            Message("Leave application cannot be applied for cross year, so please enter the leave for next year as a separate leave application");
            return;
        }
        foreach (DataRow dRowRemainingLeaves in dsRemainingNoOfLeaves.Tables[0].Rows)
        {
            if (Convert.ToDouble(dRowRemainingLeaves["Number Of Days"]) < 0)
            {
                if (dRowRemainingLeaves["Leave Type"].ToString() == "Others")
                {
                    //Message("Comp Off Leave exceeds the remaining number of leaves");
                    //return;
                }
                else
                {
                    Message(dRowRemainingLeaves["Leave Type"].ToString() + " Leave exceeds the remaining number of leaves");
                    return;
                }
            }
        }
        //Leave Restriction in a month
        foreach (DataRow DRowLeaves in dtLeaveForEachMonth.Rows)
        {
            //if (Convert.ToDouble(DRowLeaves["MaxDaysMonth"]) != 0)
            //{
            //if (Convert.ToDouble(DRowLeaves["LeaveDays"]) > Convert.ToDouble(DRowLeaves["MaxDaysMonth"]))
            //{
            string LeaveType = DRowLeaves["LeaveType"].ToString();
            //dv.RowFilter = "LeaveType='" + DRowLeaves["LeaveType"].ToString();  
            decimal MaxLeaves = Convert.ToDecimal(dtLeaveForEachMonth.Compute("Max(MaxDaysMonth)", "LeaveType='" + LeaveType + "'"));
            decimal SumValue = Convert.ToDecimal(dtLeaveForEachMonth.Compute("sum(LeaveDays)", "LeaveType='" + LeaveType + "'"));
            if (Convert.ToDouble(SumValue) > Convert.ToDouble(MaxLeaves))
            {
                if ((DateTime.Parse(strLeaveFromDate) >= DateTime.Parse(strYearSettingsFromdate)) && (DateTime.Parse(strLeaveToDate) <= DateTime.Parse(strYearSettingsTodate)) && DaysForSuccessive > 0)
                {
                }
                else
                {
                    string monthName = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(DateTime.Parse(DRowLeaves["LeaveMonth"].ToString()).Month);
                    Message(DRowLeaves["LeaveType"].ToString() + " " + "Leave Exceeds the quota in " + monthName);
                    return;
                }
            }
            //}
        }
        //Intimation Type
        string intimationType = string.Empty;
        // get inputs from UI
        if (rbtnP.Checked)
        {
            intimationType = rbtnP.Text;
        }
        else if (rbtnUPWI.Checked)
        {
            intimationType = rbtnUPWI.Text;
        }
        else if (rbtnUPWOI.Checked)
        {
            intimationType = rbtnUPWOI.Text;
        }
        string strCCMail = txtApprovalCC.Text;
        dblLeaveAvailedYear = objLeaveApplicationEventData.GetLeaveSummary(DateTime.Parse(strYearSettingsFromdate), DateTime.Parse(strYearSettingsTodate), Convert.ToInt32(hdnEmployeeId.Value));
        int LeaveApplicationId = 0;
        string YearSettingIDforSave = string.Empty;
        //strMonth1 = Convert.ToDateTime(strLeaveToDate).ToString("MMMM");
        string CurrentDate = DateTime.Now.ToString();
        DateTime startDayOfMonth = new DateTime(DateTime.Parse(CurrentDate).Year, DateTime.Parse(CurrentDate).Month, 1);
        DateTime endDayOfMonth = startDayOfMonth.AddMonths(1).AddDays(-1);
        dblLeaveAvailedMonth = objLeaveApplicationEventData.GetLeaveSummary(startDayOfMonth, endDayOfMonth, Convert.ToInt32(hdnEmployeeId.Value));
        string strLeaveAvailedYear = dblLeaveAvailedYear.ToString();
        string strLeaveAvailedMonth = string.Empty;
        if (strCrossDate != "Yes")
        {
            strLeaveAvailedMonth = dblLeaveAvailedMonth.ToString();
        }
        //string strLeaveAvailedYear = dblLeaveAvailedYear.ToString();
        //string strLeaveAvailedMonth = dblLeaveAvailedMonth.ToString();
        if (CurrentYearLeaveCount == 1)
        {
            YearSettingIDforSave = ViewState["YearSettings_Id"].ToString();
        }
        else if (NextYearLeaveCount == 1)
        {
            YearSettingIDforSave = ViewState["NextYearSettings_Id"].ToString();
        }
        #region checking SL/Comp Off with CL By Manjula on 24-May-2013
        //calling function
        isValidGrid = CheckCombinedinAddRow(districtDetails);
        if (isValidGrid == false)
        {
            //Message("Cant Add the row, because you are entering combined leave of [SL/Comp Off] with [CL]");
            return;
        }
        #endregion
        //Enter Leave Details in Master Table
        LeaveApplicationId = objLeaveApplicationEventData.InsertLeaveApplicationMaster(Convert.ToInt32(hdnEmployeeId.Value), DateTime.Now.ToShortDateString(), txtReason.Text.Replace("'", "''"), Session["EmpAutoId"].ToString(), YearSettingIDforSave, "Pending", intimationType, strCCMail, Decimal.Parse(strLeaveAvailedYear.ToString()), Decimal.Parse(strLeaveAvailedMonth.ToString()));
        string strMonth1 = string.Empty;
        DataSet dsLeaveApplication = new DataSet();
        string MonthValue = string.Empty;
        string strInformTo = GetSelectedEmployee();
        foreach (DataRow dRow in districtDetails.Rows)
        {
            strLeaveCategory = string.Empty;
            strLeaveFromSession = string.Empty;
            strLeaveToSession = string.Empty;
            strLeaveFromDate = string.Empty;
            strLeaveToDate = string.Empty;
            strLeaveTypeId = string.Empty;
            strLeaveCategory = dRow["LeaveCategory"].ToString();
            //by manju for getting leavetype name
            string strLeaveTypeName = string.Empty;
            strLeaveTypeName = dRow["LeaveTypesName"].ToString();
            if (strLeaveCategory == "1")
            {
                strLeaveCategory = "Leave";
            }
            else if (strLeaveCategory == "2")
            {
                strLeaveCategory = "LOP";
            }
            else if (strLeaveCategory == "3")
            {
                strLeaveCategory = "Comp Off";
            }
            strLeaveTypeId = dRow["LeaveTypes"].ToString();
            if (strLeaveTypeId == string.Empty)
            {
                Message("Leave Types should not be empty");
                return;
            }
            strLeaveFromSession = dRow["LeaveSessionsFrom"].ToString();
            if (strLeaveFromSession == "1")
            {
                strLeaveFromSession = "First Half";
            }
            else
            {
                strLeaveFromSession = "Second Half";
            }
            strLeaveToSession = dRow["LeaveSessionsTo"].ToString();
            if (strLeaveToSession == "1")
            {
                strLeaveToSession = "First Half";
            }
            else
            {
                strLeaveToSession = "Second Half";
            }
            strLeaveFromDate = dRow["LeaveFrom"].ToString();
            strLeaveToDate = dRow["LeaveTo"].ToString();
            //Added by Manjula.P on 13-May-2014
            strLeaveFromDate = objcls_Common.DateConvertion(gstrDateFormat, strLeaveFromDate);
            strLeaveToDate = objcls_Common.DateConvertion(gstrDateFormat, strLeaveToDate);
            if (MonthValue == "")
            {
                MonthValue = Convert.ToDateTime(strLeaveFromDate).Month.ToString();
            }
            else if (MonthValue != "")
            {
                if (MonthValue != Convert.ToDateTime(strLeaveFromDate).Month.ToString())
                {
                    strCrossDate = "Yes";
                }
            }
            //strLeaveFromDate = objcls_Common.DateConvertion(gstrDateFormat, strLeaveFromDate);
            //strLeaveToDate = objcls_Common.DateConvertion(gstrDateFormat, strLeaveToDate);
            testvalue = 0;
            string strDays = CalculateNumberOfDaysApplied();
            string[] NumberOfDays = strDays.Split(',');
            #region To restrict the CL leave with SL/Comp off By Manjula.P on 23-May-2013 as per the given requirements by manikandan
            //To restrict the CL leave with SL/Comp off
            //calculate the date for leave before of from date.
            DateTime datePreviousFrom = Convert.ToDateTime(strLeaveFromDate).AddDays(-1);
            string previousFromDate = objcls_Common.DateConvertion(gstrDateFormat, datePreviousFrom.ToString(gstrDateFormat));
            //  string previousFromDate = objcls_Common.DateConvertion(gstrDateFormat, datePreviousFrom);
            //checking previous working days i.e without holiday.
            datePreviousFrom = RecursionHoliday(datePreviousFrom, 'N');
            //next date
            DateTime dateNextFrom = Convert.ToDateTime(strLeaveFromDate).AddDays(1);
            string nextFromDate = objcls_Common.DateConvertion(gstrDateFormat, dateNextFrom.ToString(gstrDateFormat));
            //  string nextFromDate = objcls_Common.DateConvertion(gstrDateFormat, dateNextFrom);
            //checking next working days i.e without holiday.
            dateNextFrom = RecursionHoliday(dateNextFrom, 'P');
            DatePre = datePreviousFrom;
            DateNext = dateNextFrom;
            Decimal decContinousAppliedDays = 0;
            //getting continous leave applied date
            if (strLeaveCategory != "LOP" && strLeaveTypeName != "SL")
                decContinousAppliedDays = Decimal.Parse(NumberOfDays[0].ToString());
            //getting from BAL
            #region Commented By A.K.T.Moorthi To Remove The Validation As Per HR Requirement(27-Jan-2014)
            //DataSet dsgetLastLeaveDate = objLeaveApplicationEventData.getNextPreviousLeave(Convert.ToInt32(hdnEmployeeId.Value), datePreviousFrom, dateNextFrom);
            //if (dsgetLastLeaveDate != null)
            //{
            //    if (dsgetLastLeaveDate.Tables[0].Rows.Count > 0)
            //    {
            //        //for restrict the leave because of combined previous leave.
            //        foreach (DataRow rowLast in dsgetLastLeaveDate.Tables[0].Rows)
            //        {
            //            //declaring temprary variables for checking leave type
            //            string LeaveTypeDs = rowLast["LeaveType"].ToString();
            //            string LeaveTypeNameDs = rowLast["Type"].ToString();
            //            //getting noof applied leave days from db
            //            //to restrict SL
            //            if (LeaveTypeNameDs != "LOP" && LeaveTypeDs != "SL")
            //                decContinousAppliedDays = decContinousAppliedDays + Convert.ToDecimal(rowLast["NumberOfDays"]);
            //            //hardcoded because of taking this field from db itself
            //            if (LeaveTypeDs == "CL" && LeaveTypeNameDs == "Leave")
            //            {
            //                //restrict SL and Comp Off
            //                if (strLeaveTypeName == "SL" || strLeaveCategory == "Comp Off")
            //                {
            //                    Message("SL/Comp Off cannot be combined with CL");
            //                    return;
            //                }
            //            }
            //            else if (LeaveTypeDs == "SL" || LeaveTypeNameDs == "Comp Off")
            //            {
            //                //restrict CL
            //                if (strLeaveTypeName == "CL" && strLeaveCategory == "Leave")
            //                {
            //                    Message("CL cannot be combined with Comp Off/SL");
            //                    return;
            //                }
            //            }
            //        }
            //    }
            //} 
            #endregion
            //checking contious leave applied days It should allowed for admin group alone by verifying with Thilakraj and Jagadesskumar
            if (Convert.ToString(Session["UserGroupName"]).ToLower() != "superadmin")
            {
                if (decContinousAppliedDays > 2 && (strLeaveCategory != "LOP" && strLeaveTypeName != "SL"))
                {
                    Message("'" + strLeaveCategory + "-" + strLeaveTypeName + "' Cannot be applied more than 2days continuously");
                    //Message("Cant Applied Leave More Than [2] Days Continously!.");
                    return;
                }
            }
            #endregion
            //#region Checking Continous leave applied date in grid By Manjula.P on 24-May-2013
            //isValidGrid = CheckContinousAppliedDays(districtDetails);
            //dtContinousDB = objLeaveApplicationEventData.RecursionLeaveDays(Convert.ToInt32(hdnEmployeeId.Value), DatePre, DateNext);
            ////to checking contious date you are selected.
            //if (isValidGrid == false)
            //{
            //    //districtDetails.comp
            //    //dt.Rows.Select(dr=>(int)dr["Marks"]).Sum();
            //    decimal decleLeaveApplicableDays = decCont;
            //    if (decleLeaveApplicableDays > 2 && (strLeaveCategory != "LOP" && strLeaveTypeName != "SL"))
            //    {
            //        Message("Leave cannot be applied more than 2days continuously!.");
            //        //Message("Cant Applied Leave More Than [2] Days continuously!.");
            //        return;
            //    }
            //}
            ////checking from db for continous date
            //else if (dtContinousDB.Tables[0].Rows.Count > 0)
            //{
            //    if (Convert.ToString(dtContinousDB.Tables[0].Compute("Sum(NoOfDays)", "Type<>'LOP' and LeaveType<>'SL'")) != string.Empty)
            //    {
            //        decimal decleLeaveApplicableDays = decCont + Convert.ToDecimal(dtContinousDB.Tables[0].Compute("Sum(NoOfDays)", "Type<>'LOP' and LeaveType<>'SL'"));
            //        if (decleLeaveApplicableDays > 2)
            //        {
            //            Message("Leave cannot be applied more than 2days continuously!.");
            //            //Message("Cant Applied Leave More Than [2] Days continuously!.");
            //            return;
            //        }
            //    }
            //}
            //#endregion
            #region Checking Continous leave applied date in grid By Manjula.P on 24-May-2013
            isValidGrid = CheckContinousAppliedDays(districtDetails);
            dtContinousDB = objLeaveApplicationEventData.RecursionLeaveDays(Convert.ToInt32(hdnEmployeeId.Value), DatePre, DateNext);
            //to checking contious date you are selected.
            if (isValidGrid == false)
            {
                //districtDetails.comp
                //dt.Rows.Select(dr=>(int)dr["Marks"]).Sum();
                decimal decleLeaveApplicableDays = decCont;
                if (decleLeaveApplicableDays > 2)
                {
                    Message("Leave cannot be applied more than 2days continuously!.");
                    //Message("Cant Applied Leave More Than [2] Days continuously!.");
                    return;
                }
            }
            //checking from db for continous date
            else if (dtContinousDB.Tables[0].Rows.Count > 0)
            {
                if (Convert.ToString(dtContinousDB.Tables[0].Compute("Sum(NoOfDays)", "Type<>'LOP' and LeaveType<>'SL'")) != string.Empty)
                {
                    decimal decleLeaveApplicableDays = decCont + Convert.ToDecimal(dtContinousDB.Tables[0].Compute("Sum(NoOfDays)", "Type<>'LOP' and LeaveType<>'SL'"));
                    if (decleLeaveApplicableDays > 2)
                    {
                        Message("Leave cannot be applied more than 2days continuously!.");
                        //Message("Cant Applied Leave More Than [2] Days continuously!.");
                        return;
                    }
                }
            }
            #endregion
            //Save the Leave Application
            dsLeaveApplication = objLeaveApplicationEventData.InsertLeaveApplication(LeaveApplicationId, Convert.ToInt32(hdnEmployeeId.Value), DateTime.Now.ToShortDateString(), Convert.ToInt32(strLeaveTypeId), strLeaveCategory, strLeaveFromDate, strLeaveToDate, strLeaveFromSession, strLeaveToSession, Decimal.Parse(NumberOfDays[0].ToString()), txtReason.Text.Replace("'", "''"), 0, Session["EmpAutoId"].ToString(), YearSettingIDforSave, string.Empty, intimationType, strCCMail, strInformTo);
        }
        //Mail Sending
        //buil the Leave details for Email
        DataTable dtLeaveDetails = new DataTable();
        dtLeaveavailedinMonth = objLeaveApplicationEventData.LoadEmployeeLeaveAvailedinMonth(LeaveApplicationId);
        if (dtLeaveavailedinMonth.Rows.Count > 0)
        {
            if (strCrossDate == "Yes")
            {
                strLeaveAvailedInFirstMonth = dtLeaveavailedinMonth.Rows[0]["NumberofDays"].ToString();
                strLeaveAvailedInSecondMonth = dtLeaveavailedinMonth.Rows[1]["NumberofDays"].ToString();
                strLeaveAvailedInFirstMonthName = dtLeaveavailedinMonth.Rows[0]["MonthName"].ToString();
                strLeaveAvailedInSecondMonthName = dtLeaveavailedinMonth.Rows[1]["MonthName"].ToString();
            }
            else
            {
                strLeaveAvailedInFirstMonth = dtLeaveavailedinMonth.Rows[0]["NumberofDays"].ToString();
                strLeaveAvailedInFirstMonthName = dtLeaveavailedinMonth.Rows[0]["MonthName"].ToString();
            }
        }
        dtLeaveDetails = districtDetails.Copy();
        dtLeaveDetails.TableName = "Leave Details";
        foreach (DataRow dRowLeave in dtLeaveDetails.Rows)
        {
            if (dRowLeave["LeaveSessionsFrom"].ToString() == "1")
            {
                dRowLeave["LeaveSessionsFrom"] = "First Half";
            }
            else
            {
                dRowLeave["LeaveSessionsFrom"] = "Second Half";
            }
            if (dRowLeave["LeaveSessionsTo"].ToString() == "1")
            {
                dRowLeave["LeaveSessionsTo"] = "First Half";
            }
            else
            {
                dRowLeave["LeaveSessionsTo"] = "Second Half";
            }
        }
        dtLeaveDetails.Columns.Remove("LeaveCategory");
        dtLeaveDetails.Columns.Remove("LeaveTypes");
        //dtLeaveDetails.Columns.Remove("NoOfLeaves");
        dtLeaveDetails.Columns.Remove("SlNo");
        dtLeaveDetails.Columns[0].ColumnName = "Leave Category";
        dtLeaveDetails.Columns[1].ColumnName = "Leave Type";
        dtLeaveDetails.Columns[2].ColumnName = "From";
        dtLeaveDetails.Columns[3].ColumnName = "To";
        dtLeaveDetails.Columns[4].ColumnName = "Session From";
        dtLeaveDetails.Columns[5].ColumnName = "Session To";
        dtLeaveDetails.Columns[6].ColumnName = "No. of Days";
        DataRow[] rowList = dtLeaveDetails.Select("[Leave Category] = 'LOP'");
        foreach (DataRow dr in rowList)
        {
            dr["Leave Type"] = "-";
        }
        strHtmlLeaveDetails = buildPage("Leave Details", dtLeaveDetails);
        Int64 intLevelId = 0;
        blnCheckEmail = true;
        int intFirstLevelAuthorityId = 0;
        int intSecondLevelAuthorityId = 0;
        string strEmailIdReportingTo = string.Empty;
        string strEmailIdSanctionAuthority = string.Empty;
        if (dsLeaveApplication.Tables[0].Rows.Count > 0)
        {
            if (dsLeaveApplication.Tables[0].Rows[0]["LevelId"] != DBNull.Value && dsLeaveApplication.Tables[0].Rows[0]["LevelId"].ToString() != string.Empty)
            {
                intLevelId = Convert.ToInt64(dsLeaveApplication.Tables[0].Rows[0]["LevelId"].ToString());
            }
        }
        //To find Leave Sanction Authorities Email_ID
        DataSet dsEmailIdOfReportingTo = objPermissionEventData.SelectMailIdOfReportingTo(Convert.ToInt32(hdnEmployeeId.Value));
        if (dsEmailIdOfReportingTo != null)
        {
            if (dsEmailIdOfReportingTo.Tables.Count > 0)
            {
                if (dsEmailIdOfReportingTo.Tables[0].Rows.Count > 0)
                {
                    if (dsEmailIdOfReportingTo.Tables[0].Rows[0]["EmailId"] != DBNull.Value)
                    {
                        if (dsEmailIdOfReportingTo.Tables[0].Rows[0]["EmailId"].ToString() != "")
                        {
                            intFirstLevelAuthorityId = int.Parse(dsEmailIdOfReportingTo.Tables[0].Rows[0]["Employee_Id"].ToString());
                            strEmailIdReportingTo = dsEmailIdOfReportingTo.Tables[0].Rows[0]["EmailId"].ToString();
                            //strEmailIdReportingTo = "angeswaran@angleritech.com";
                        }
                        else
                        {
                            blnCheckEmail = false;
                        }
                    }
                    else
                    {
                        blnCheckEmail = false;
                    }
                }
                else
                {
                    blnCheckEmail = false;
                }
            }
        }
        // Gets the Sanctioning Authority Id and Email Id
        DataSet ds_EmailIdOfSanctionAuthority = objPermissionEventData.SelectMailIdOfSanctionAuthority(Convert.ToInt32(hdnEmployeeId.Value));
        if (ds_EmailIdOfSanctionAuthority.Tables[0].Rows.Count > 0)
        {
            if (ds_EmailIdOfSanctionAuthority.Tables[0].Rows[0]["EmailId"] != DBNull.Value && ds_EmailIdOfSanctionAuthority.Tables[0].Rows[0]["EmailId"].ToString() != string.Empty)
            {
                intSecondLevelAuthorityId = int.Parse(ds_EmailIdOfSanctionAuthority.Tables[0].Rows[0]["Employee_Id"].ToString());
                strEmailIdSanctionAuthority = ds_EmailIdOfSanctionAuthority.Tables[0].Rows[0]["EmailId"].ToString();
            }
        }
        if (strEmailIdSanctionAuthority == null)
        {
            strEmailIdSanctionAuthority = string.Empty;
        }
        if (strEmailIdReportingTo == null)
        {
            strEmailIdReportingTo = string.Empty;
        }
        if (strEmailIdSanctionAuthority == string.Empty && strEmailIdReportingTo == string.Empty && txtApprovalCC.Text == string.Empty)
        {
            blnCheckEmail = false;
        }
        if (blnCheckEmail == true)
        {
            //dblLeaveAvailedYear = objLeaveApplicationEventData.GetLeaveSummary(DateTime.Parse(gstrYearSettingStartDate), DateTime.Parse(gstrYearSettingsEndDate), Convert.ToInt32(hdnEmployeeId.Value));
            //DateTime startDayOfMonth = new DateTime(DateTime.Parse(districtDetails.Rows[0]["LeaveFrom"].ToString()).Year, DateTime.Parse(districtDetails.Rows[0]["LeaveFrom"].ToString()).Month, 1);
            //DateTime endDayOfMonth = startDayOfMonth.AddMonths(1).AddDays(-1);
            //dblLeaveAvailedMonth = objLeaveApplicationEventData.GetLeaveSummary(startDayOfMonth, endDayOfMonth, Convert.ToInt32(hdnEmployeeId.Value));
            //Get the employee details based on the employeee auto id using the hidden field value
            dsEmployeeDetails = objLeaveApplicationEventData.GetEmployeeDetails(Convert.ToInt32(hdnEmployeeId.Value));
            if (dsEmployeeDetails.Tables[0].Rows.Count > 0)
            {
                strEmpFirstName = dsEmployeeDetails.Tables[0].Rows[0]["Employee_FirstName"].ToString();
                strEmpLastName = dsEmployeeDetails.Tables[0].Rows[0]["Employee_LastName"].ToString();
                strEmployeeCodeId = dsEmployeeDetails.Tables[0].Rows[0]["Employee_Code_Id"].ToString();
                strEmployeeName = strEmpFirstName + " " + strEmpLastName;
                strlevelName = dsEmployeeDetails.Tables[0].Rows[0]["levelName"].ToString();
                EmployeeEamilId = dsEmployeeDetails.Tables[0].Rows[0]["EmailId"].ToString();
            }
            else
            {
                //
            }
            if (Convert.ToInt32(ConfigurationManager.AppSettings.Get("isRequiredEmail")) == 1)
            {
                SendMail(LeaveApplicationId, intLevelId, intFirstLevelAuthorityId, intSecondLevelAuthorityId, strEmailIdReportingTo, strEmailIdSanctionAuthority, intimationType);
            }
        }
        if (blnCheckEmail == true)
        {
            string strScript = "";
            strScript = strScript + "<script language='javascript'>";
            strScript = strScript + "alert('Leave Application Saved');";
            strScript = strScript + "location.replace('TA_UI_Transactions_LeaveApplication.aspx');";
            strScript = strScript + "</script>";
            //Dispaly alert messsage.
            Page.RegisterStartupScript("AlertPAdd65507866", strScript);
            //Response.Redirect("TA_UI_Transactions_LeaveApplication.aspx");
        }
        else
        {
            string strScript = "";
            strScript = strScript + "<script language='javascript'>";
            strScript = strScript + "alert('Leave Application Saved, Email not sent');";
            strScript = strScript + "location.replace('TA_UI_Transactions_LeaveApplication.aspx');";
            strScript = strScript + "</script>";
            //Dispaly alert messsage.
            Page.RegisterStartupScript("AlertPAdd99623866", strScript);
        }
    }
    //getting next row from current row of the grid for continous date validation in both add and newrow button
    public DataRow getNextRow(DataTable dt, int index)
    {
        if (dt.Rows.Count > 1)
        {
            if (dt.Rows.Count > index + 1)
            {
                DataRow dr = dt.Rows[index + 1];
                return dr;
            }
            else
            {
                //DataRow dr = dt.Rows[index - 1];
                //return dr;
                return null;
            }
        }
        else
        {
            return null;
        }
    }
    public DataRow getPreviousRow(DataTable dt, int index)
    {
        if (dt.Rows.Count > 1)
        {
            if (index == (dt.Rows.Count - 1))
            {
                DataRow dr = dt.Rows[index - 1];
                return dr;
            }
            else
            {
                //DataRow dr = dt.Rows[index - 1];
                //return dr;
                return null;
            }
        }
        else
        {
            return null;
        }
    }
    //for checking the date value whether it holiday / weekly off
    public DateTime RecursionHoliday(DateTime date, char symbol)
    {
        DateTime dateTemp = date;
        DataSet dsHoliday = objLeaveApplicationEventData.HolidayRecursion(date);
        //for checking holiday with passing date
        if (dsHoliday.Tables[0].Rows.Count > 0)
        {
            //positive P and N for negetive
            if (symbol == 'P')
            {
                dateTemp = dateTemp.AddDays(1);
            }
            else if (symbol == 'N')
            {
                dateTemp = dateTemp.AddDays(-1);
            }
            dateTemp = RecursionHoliday(dateTemp, symbol);
        }
        //checking sunday (Weekly Off) with passing date. This is hardcoded for angler. 
        //If you want take real weekly off for the employee go to 
        // TA_Tbl_PermanentShiftAllocation
        else if (dateTemp.DayOfWeek == DayOfWeek.Sunday)
        {
            //positive P and N for negetive
            if (symbol == 'P')
            {
                dateTemp = dateTemp.AddDays(1);
            }
            else if (symbol == 'N')
            {
                dateTemp = dateTemp.AddDays(-1);
            }
            dateTemp = RecursionHoliday(dateTemp, symbol);
        }
        return dateTemp;
    }
    #region LoadRemaining Leaves
    public void LoadRemainingLeaves(string FromDate)
    {
        //Added by Manjula.P on 13-May-2014 
        FromDate = objcls_Common.DateConvertion(gstrDateFormat, FromDate);
        dsRemainingNoOfLeaves = objLeaveApplicationEventData.GetRemainingNumberOfLeaves(Convert.ToInt32(hdnEmployeeId.Value), -1, 0, FromDate);
        if (dsRemainingNoOfLeaves.Tables.Count > 0)
        {
            if (dsRemainingNoOfLeaves.Tables[0].Rows.Count > 0)
            {
            }
        }
    }
    #endregion
    #region LoadCompOffDays
    public void LoadCompOffDays()
    {
        DataSet dsRemainingNoOfCompOffDays = new DataSet();
        dsRemainingNoOfCompOffDays = objLeaveApplicationEventData.GetCompOffDays_Angler(Convert.ToInt32(hdnEmployeeId.Value));
        if (dsRemainingNoOfCompOffDays.Tables.Count > 0)
        {
            if (dsRemainingNoOfCompOffDays.Tables[0].Rows.Count > 0)
            {
                DataRow dRow = dsRemainingNoOfLeaves.Tables[0].NewRow();
                dRow["Leave Type"] = "Others";
                dRow["Number Of Days"] = dsRemainingNoOfCompOffDays.Tables[0].Rows[0]["CompOffDays"].ToString();
                dRow.EndEdit();
                dsRemainingNoOfLeaves.Tables[0].Rows.Add(dRow);
            }
        }
    }
    #endregion
    protected void btn_cancel_Click(object sender, EventArgs e)
    {
        Response.Redirect("TA_UI_Transactions_LeaveApplication.aspx");
    }
    #region DateDifference
    public int DateDifference(DateTime d1, DateTime d2)
    {
        int Days;
        TimeSpan ts = d2.Subtract(d1);
        if (ts.Days >= 0)
        {
            Days = (ts.Days) + 1;
        }
        else
        {
            Days = ts.Days;
        }
        return Days;
    }
    #endregion
    #region Message.
    /// <summary>
    /// Messages the specified message content.
    /// </summary>
    /// <param name="messageContent">Content of the message.</param>
    public void Message(string messageContent)
    {
        //ClientScript.RegisterClientScriptBlock(this.GetType(), "addLoadEvent", "function addLoadEvent(func) { var oldonload = window.onload; if (typeof window.onload != 'function') { window.onload = func; } else { window.onload= function() { if (oldonload) { oldonload(); } func(); } } }", true);
        string strScript = "<script language='javascript' type='text/javascript'>";
        strScript += "alert('" + messageContent.Replace("'", " ").Replace("\n", "").Replace("\r", "") + "');";
        strScript += " </script>";
        this.RegisterStartupScript("setScript", strScript);
    }
    #endregion
    #region HolidayChecking
    public int HolidayChecking(DateTime Fromdate, DateTime ToDate)
    {
        //Check Whether the date is holiday
        DataTable dtHoliday = new DataTable();
        int intHolidayCount = 0;
        for (DateTime dtmDate = Fromdate; dtmDate <= ToDate; dtmDate = dtmDate.AddDays(1))
        {
            dtHoliday = objHolidayEventData.CheckDateForHoliday(dtmDate.ToShortDateString(), Convert.ToString(hdnEmployeeId1.Value));
            if (dtHoliday.Rows.Count > 0)
            {
                intHolidayCount = 1;
            }
            dtHoliday.Clear();
        }
        return intHolidayCount;
    }
    #endregion
    #region WeeklyOffChecking
    public int WeeklyOffChecking(DateTime Fromdate, DateTime ToDate, string EmployeeCodeId)
    {
        // Intervening weekly off Temporary Table
        DateTime dtmFromDate = Fromdate;
        DateTime dtmToDate = ToDate;
        //DataTable declaration for Temporary and Actual Shifts
        DataTable dtTempShift = new DataTable();
        DataTable dtActualShift = new DataTable();
        int intWeeklyOffCount = 0;
        for (DateTime dtmDate = dtmFromDate; dtmDate <= dtmToDate; dtmDate = dtmDate.AddDays(1))
        {
            int intShiftId = 0;
            try
            {
                dtTempShift = objShiftExchangeEventData.SelectTemporaryShiftId(EmployeeCodeId, dtmDate.Year.ToString(), dtmDate.Month.ToString(), dtmDate.Day.ToString());
            }
            catch
            {
                //
            }
            try
            {
                dtActualShift = objShiftExchangeEventData.SelectPermanentShiftId(EmployeeCodeId, dtmDate.Year.ToString(), dtmDate.Month.ToString(), dtmDate.Day.ToString());
            }
            catch
            {
                //
            }
            if (dtTempShift.Rows.Count > 0)
            {
                if (dtTempShift.Rows[0][0] != DBNull.Value)
                {
                    intShiftId = int.Parse(dtTempShift.Rows[0][0].ToString());
                }
            }
            if (intShiftId == 0)
            {
                if (dtActualShift.Rows.Count > 0)
                {
                    if (dtActualShift.Rows[0][0] != DBNull.Value)
                    {
                        intShiftId = int.Parse(dtActualShift.Rows[0][0].ToString());
                    }
                }
            }
            int count = 0;
            count = CheckAdditionalWeekOff(dtmDate, gstrSwipeCardNo);
            if (count == 1)
            {
                intShiftId = -1;
            }
            if (intShiftId == -1)
            {
                intWeeklyOffCount = 1;
            }
        }
        return intWeeklyOffCount;
    }
    #endregion
    #region CheckAdditionalWeekOff
    // Function to check Additional Weekly Off
    public int CheckAdditionalWeekOff(DateTime dtmDate, string EmployeeId)
    {
        DateTime startOfMonth;
        string strStartOfMonth;
        int DaysToAdd, NthWeek = 0, TargetDayOfWeek = 0;
        string flag = "NE";
        try
        {
            DataTable dtAdditionalWeekOff = new DataTable();
            dtAdditionalWeekOff = objMonthClosure.GetAdditionalWeekOff(EmployeeId, dtmDate.ToShortDateString());
            if (dtAdditionalWeekOff.Rows.Count > 0)
            {
                if (dtAdditionalWeekOff.Rows[0]["Addl_WeekOff_Day"] != DBNull.Value && dtAdditionalWeekOff.Rows[0]["Addl_WeekOff_Day"].ToString() != string.Empty)
                {
                    TargetDayOfWeek = GetWeekDay(dtAdditionalWeekOff.Rows[0]["Addl_WeekOff_Day"].ToString());
                }
                if (dtAdditionalWeekOff.Rows[0]["Addl_WeekOff_Week"] != DBNull.Value && dtAdditionalWeekOff.Rows[0]["Addl_WeekOff_Week"].ToString() != string.Empty)
                {
                    string strTargetDayOfWeek = dtAdditionalWeekOff.Rows[0]["Addl_WeekOff_Week"].ToString();
                    if (strTargetDayOfWeek == "First Week")
                    {
                        NthWeek = 1;
                    }
                    else if (strTargetDayOfWeek == "Second Week")
                    {
                        NthWeek = 2;
                    }
                    else if (strTargetDayOfWeek == "Third Week")
                    {
                        NthWeek = 3;
                    }
                    else if (strTargetDayOfWeek == "Fourth Week")
                    {
                        NthWeek = 4;
                    }
                    else if (strTargetDayOfWeek == "Fifth Week")
                    {
                        NthWeek = 5;
                    }
                }
                if (NthWeek != 0 && TargetDayOfWeek != 0)
                {
                    strStartOfMonth = dtmDate.Month + "/01/" + dtmDate.Year;
                    startOfMonth = DateTime.Parse(strStartOfMonth);
                    string WeekDayName = startOfMonth.DayOfWeek.ToString();
                    int WeekDay = GetWeekDay(WeekDayName);
                    DaysToAdd = (7 - (WeekDay + (7 - TargetDayOfWeek)) % 7) % 7;
                    DateTime dtmResult = startOfMonth.AddDays(DaysToAdd + ((NthWeek - 1) * 7));
                    if (dtmResult == dtmDate)
                    {
                        flag = "E";
                    }
                }
            }
            if (flag == "E")
            {
                return (1);
            }
            else
            {
                return (0);
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    #endregion
    #region GetWeekDay
    public int GetWeekDay(string WeekDayName)
    {
        int intWeekDay = 0;
        switch (WeekDayName)
        {
            case "Sunday":
                intWeekDay = 1;
                break;
            case "Monday":
                intWeekDay = 2;
                break;
            case "Tuesday":
                intWeekDay = 3;
                break;
            case "Wednesday":
                intWeekDay = 4;
                break;
            case "Thursday":
                intWeekDay = 5;
                break;
            case "Friday":
                intWeekDay = 6;
                break;
            case "Saturday":
                intWeekDay = 7;
                break;
        }
        return (intWeekDay);
    }
    #endregion
    #region CheckShift
    public int CheckShift()
    {
        DataSet dsShift = new DataSet();
        DateTime dtmFromDate = DateTime.Parse(strLeaveFromDate);
        DateTime dtmToDate = DateTime.Parse(strLeaveToDate);
        //intShiftCount 1-Shift Allocated 0-Not Allocated 
        int intShiftCount = 1;
        for (DateTime dtmDate = dtmFromDate; dtmDate <= dtmToDate; dtmDate = dtmDate.AddDays(1))
        {
            int mon = dtmDate.Month;
            int dat = dtmDate.Day;
            int yea = dtmDate.Year;
            dsShift = objPermissionEventData.GetShiftID(Convert.ToString(EmployeeCodeId), yea, mon, dat);
            if (dsShift != null)
            {
                if (dsShift.Tables.Count > 0)
                {
                    if (dsShift.Tables[0].Rows.Count > 0)
                    {
                        if (dsShift.Tables[0].Rows[0][0] != DBNull.Value)
                        {
                            if (Convert.ToInt16(dsShift.Tables[0].Rows[0][0]) == 0)
                            {
                                intShiftCount = 0;
                            }
                        }
                        else
                        {
                            intShiftCount = 0;
                        }
                    }
                }
            }
        }
        return intShiftCount;
    }
    #endregion
    #region CalculateNumberOfDaysApplied
    public string CalculateNumberOfDaysApplied()
    {
        double dDays = 0.0, dTempDays = 0.0;
        gintWeeklyOffHoliday = 0;
        int iDays = DateDifference(DateTime.Parse(strLeaveFromDate), DateTime.Parse(strLeaveToDate));
        DataSet dsEmp = new DataSet();
        dsEmp = objLeaveApplicationEventData.GetEmployeeLevel(Convert.ToInt32(hdnEmployeeId.Value));
        int iEmployeeLevelID = 0;
        if (dsEmp != null && dsEmp.Tables.Count != 0 && dsEmp.Tables[0].Rows.Count != 0)
        {
            if (dsEmp.Tables[0].Rows[0]["levelID"] != DBNull.Value)
            {
                iEmployeeLevelID = Convert.ToInt32(dsEmp.Tables[0].Rows[0]["levelID"]);
            }
        }
        //Select Company
        org_levelsEventData getOrg = new org_levelsEventData();
        getOrg.GetOrgParentLevels_FromID(iEmployeeLevelID);
        DataSet ds_getOrg = new DataSet();
        ds_getOrg = getOrg.GetOrgParentLevels();
        int iCompanyID = 0;
        if (ds_getOrg != null)
        {
            if (ds_getOrg.Tables[0].Rows.Count > 0)
            {
                iCompanyID = Convert.ToInt32(ds_getOrg.Tables[0].Rows[0]["LevelID"].ToString());
            }
        }
        ShiftSettingsEventData getShift = new ShiftSettingsEventData();
        DataSet dsShiftSett = new DataSet();
        dsShiftSett = getShift.GetShiftSettingsByComId(iCompanyID);
        int iHalfDayFlag = 0;
        if (dsShiftSett != null)
        {
            if (dsShiftSett.Tables[0].Rows.Count > 0)
            {
                if (dsShiftSett.Tables[0].Rows[0]["IsFlexible"] != DBNull.Value)
                {
                    if (Convert.ToString(dsShiftSett.Tables[0].Rows[0]["IsFlexible"]) != "False")
                    {
                        if (dsShiftSett.Tables[0].Rows[0]["halfdayAttendance"] != DBNull.Value)
                        {
                            if (Convert.ToString(dsShiftSett.Tables[0].Rows[0]["halfdayAttendance"]) != "False")
                            {
                                iHalfDayFlag = 1;  // half day is enabled
                            }
                            else
                            {
                                iHalfDayFlag = 0; // half day is disabled
                                if ((strLeaveFromSession != "First half") || (strLeaveToSession != "Second half"))
                                {
                                    //Message("Half Day is disabled");
                                    return "HalfDayIsDisabled";
                                }
                            }
                        }
                    }
                }
            }
        }
        //if (iHalfDayFlag==0)
        //{
        //if ((Fromsession != "First half") && (Tosession != "Second half"))
        //{
        //    Response.Clear();
        //    Response.Write("HalfDayIsDisabled");
        //    Response.End();
        //    return;
        //}
        //}
        //End of select Company
        double dsEmpCat = 0.0;
        //string dtSat = string.Empty;
        DateTime dtLeavestart = Convert.ToDateTime(strLeaveFromDate);
        DateTime dtLeaveEnd = Convert.ToDateTime(strLeaveToDate);
        dsEmpCat = objLeaveApplicationEventData.GetEmployeeCategoryDetailForSat(Convert.ToInt32(hdnEmployeeId.Value), dtLeaveEnd);
        int intcount = 0;
        if (dtLeavestart == dtLeaveEnd)
        {
            if (dtLeavestart.DayOfWeek.ToString() == "Saturday")
            {
                if (dsEmpCat <= 4)
                {
                    if (strLeaveFromSession.ToLower() == "first half" && strLeaveToSession.ToLower() == "second half")
                    {
                        return "kindly apply half day leave in saturday";
                    }
                    intcount = objLeaveApplicationEventData.CheckLeaveApplicationAlreadyExistsOnSat(-1, Convert.ToInt32(hdnEmployeeId.Value), strLeaveFromDate, strLeaveToDate, strLeaveFromSession, strLeaveToSession);
                    if (intcount > 0)
                    {
                        return "Leave has already applied for these dates";
                    }
                }
            }
        }
        else
        {
            if (dtLeavestart.DayOfWeek.ToString() == "Saturday")
            {
                if (dsEmpCat <= 4)
                {
                    if (strLeaveFromSession.ToLower() == "first half" && strLeaveToSession.ToLower() == "second half")
                    {
                        return "kindly split up the records and apply half day leave in saturday";
                    }
                    if (strLeaveFromSession.ToLower() == "first half" && strLeaveToSession.ToLower() == "first half")
                    {
                        return "kindly split up the records and apply half day leave in saturday";
                    }
                    intcount = objLeaveApplicationEventData.CheckLeaveApplicationAlreadyExistsOnSat(-1, Convert.ToInt32(hdnEmployeeId.Value), strLeaveFromDate, strLeaveFromDate, strLeaveFromSession, strLeaveToSession);
                    if (intcount > 0)
                    {
                        return "Leave has already applied for these dates";
                    }
                }
            }
            else if (dtLeaveEnd.DayOfWeek.ToString() == "Saturday")
            {
                if (dsEmpCat <= 4)
                {
                    if (strLeaveFromSession.ToLower() == "first half" && strLeaveToSession.ToLower() == "second half")
                    {
                        return "kindly split up the records and apply half day leave in saturday";
                    }
                    if (strLeaveFromSession.ToLower() == "second half" && strLeaveToSession.ToLower() == "second half")
                    {
                        return "kindly split up the records and apply half day leave in saturday";
                    }
                    intcount = objLeaveApplicationEventData.CheckLeaveApplicationAlreadyExistsOnSat(-1, Convert.ToInt32(hdnEmployeeId.Value), strLeaveToDate, strLeaveToDate, strLeaveFromSession, strLeaveToSession);
                    if (intcount > 0)
                    {
                        return "Leave has already applied for these dates";
                    }
                }
            }
            else
            {
                for (int i = 0; i < iDays; i++)
                {
                    string dtSat = string.Empty;
                    dtLeavestart = Convert.ToDateTime(strLeaveFromDate);
                    dtLeavestart = dtLeavestart.AddDays(i);
                    dtSat = dtLeavestart.DayOfWeek.ToString();
                    if (dtSat == "Saturday")
                    {
                        if (dsEmpCat <= 4)
                        {
                            return "kindly split up the records and apply half day leave in saturday";
                        }
                    }
                }
            }
        }
        if (iDays > 0)
        {
            dDays = Double.Parse(iDays.ToString());
            if ((strLeaveFromSession.ToLower() == "full day") && (strLeaveToSession.ToLower() == "first half"))
            {
                dDays = dDays - 0.5;
            }
            else if ((strLeaveFromSession.ToLower() == "first half") && (strLeaveToSession.ToLower() == "first half"))
            {
                dDays = dDays - 0.5;
            }
            else if ((strLeaveFromSession.ToLower() == "first half") && (strLeaveToSession == "-Select-"))
            {
                dDays = dDays - 0.5;
            }
            else if ((strLeaveFromSession.ToLower() == "second half") && (strLeaveToSession.ToLower() == "full day"))
            {
                dDays = dDays - 0.5;
            }
            else if ((strLeaveFromSession.ToLower() == "second half") && (strLeaveToSession == "-Select-"))
            {
                dDays = dDays - 0.5;
            }
            else if ((strLeaveFromSession.ToLower() == "second half") && (strLeaveToSession.ToLower() == "first half"))
            {
                if (strLeaveFromDate != strLeaveToDate)
                {
                    dDays = dDays - 1;
                }
                else
                {
                    dDays = dDays - 0.5;
                }
            }
            else if ((strLeaveFromSession.ToLower() == "second half") && (strLeaveToSession.ToLower() == "second half"))
            {
                dDays = dDays - 0.5;
            }
        }
        else
        {
            dDays = Double.Parse(iDays.ToString());
        }
        dTempDays = dDays;
        //Check the given From Date or To Data falls on Weekly Off
        int WeeklyOffCountFromDate = 0;
        int WeeklyOffCountToDate = 0;
        WeeklyOffCountFromDate = WeeklyOffChecking(DateTime.Parse(strLeaveFromDate), DateTime.Parse(strLeaveFromDate), EmployeeCodeId);
        WeeklyOffCountToDate = WeeklyOffChecking(DateTime.Parse(strLeaveToDate), DateTime.Parse(strLeaveToDate), EmployeeCodeId);
        if (WeeklyOffCountFromDate > 0)
        {
            //Message("Leave From Date should not be weekly off");
            return "WeeklyOffFromDate";
        }
        if (WeeklyOffCountToDate > 0)
        {
            //Message("Leave To Date should not be weekly off");
            return "WeeklyOffToDate";
        }
        if (strLeaveCategory == "ESI")
        {
            return dDays.ToString() + "," + "-1";
        }
        if (strLeaveCategory == "Comp Off")
        {
            //Check the Given date range have holidays
            int HolidayCount = HolidayChecking(DateTime.Parse(strLeaveFromDate), DateTime.Parse(strLeaveToDate));
            if (HolidayCount > 0)
            {
                //Message("Holidays exists between leave dates");
                return "Holiday";
            }
            //Check the Given date range have Weekly Off
            int WeeklyOffCount = WeeklyOffChecking(DateTime.Parse(strLeaveFromDate), DateTime.Parse(strLeaveToDate), EmployeeCodeId);
            if (WeeklyOffCount > 0)
            {
                //Message("Weekly Off exists between leave dates");
                return "WeeklyOff";
            }
            return dDays.ToString() + "," + "-1";
        }
        if (strLeaveCategory != "Comp Off")
        {
            //To get the Leave Policy Details Based on EmployeeId and Leave Type Id
            DataSet ds_LeavePolicyDetails = new DataSet();
            DataSet ds_WeeklyOff = new DataSet();
            ds_LeavePolicyDetails = objLeaveApplicationEventData.GetLeavePolicyDetailsLeaveApplication(Convert.ToInt32(hdnEmployeeId.Value), Convert.ToInt32(strLeaveTypeId), DateTime.Parse(strLeaveFromDate), DateTime.Parse(strLeaveToDate));
            if (ds_LeavePolicyDetails.Tables[0].Rows.Count > 0)
            {
                //  declaration for After weekly off
                if (ds_LeavePolicyDetails.Tables[0].Rows[0]["Count_AfterWeeklyOff"].ToString() == "True")
                {
                    string Type = "A";
                    ds_WeeklyOff = objLeaveApplicationEventData.GetShiftIdBeforeAfterWeekOff(Convert.ToInt32(hdnEmployeeId.Value), DateTime.Parse(strLeaveFromDate), DateTime.Parse(strLeaveToDate), Type);
                    if (ds_WeeklyOff.Tables[0].Rows.Count > 0)
                    {
                        if (ds_WeeklyOff.Tables[0].Rows[0]["ShiftId"] != DBNull.Value)
                        {
                            if (Convert.ToString(ds_WeeklyOff.Tables[0].Rows[0]["ShiftId"]) == "-1")
                            {
                                if (strLeaveFromSession == "First half")
                                {
                                    dDays = dDays + 1;
                                    testvalue = 1;
                                }
                            }
                        }
                    }
                }
                // declaration for Before weekly off
                if (ds_LeavePolicyDetails.Tables[0].Rows[0]["Count_BeforeWeeklyOff"].ToString() == "True")
                {
                    string Type = "B";
                    ds_WeeklyOff = objLeaveApplicationEventData.GetShiftIdBeforeAfterWeekOff(Convert.ToInt32(hdnEmployeeId.Value), DateTime.Parse(strLeaveFromDate), DateTime.Parse(strLeaveToDate), Type);
                    if (ds_WeeklyOff.Tables[0].Rows.Count > 0)
                    {
                        if (ds_WeeklyOff.Tables[0].Rows[0]["ShiftId"] != DBNull.Value)
                        {
                            if (Convert.ToString(ds_WeeklyOff.Tables[0].Rows[0]["ShiftId"]) == "-1")
                            {
                                if (strLeaveToSession == "Second half")
                                {
                                    dDays = dDays + 1;
                                    testvalue = 2;
                                }
                            }
                        }
                    }
                }
                if (ds_LeavePolicyDetails.Tables[0].Rows[0]["Count_Intervening"].ToString() == "True")
                {
                    //test value 4 for Intervening yes
                    DateTime dtmFromDate = DateTime.Parse(strLeaveFromDate);
                    DateTime dtmToDate = DateTime.Parse(strLeaveToDate);
                    for (DateTime dtmDate = dtmFromDate; dtmDate <= dtmToDate; dtmDate = dtmDate.AddDays(1))
                    {
                        int intShiftId = 0;
                        DataTable dtTempShift = new DataTable();
                        dtTempShift = objShiftExchangeEventData.SelectTemporaryShiftId(EmployeeCodeId, dtmDate.Year.ToString(), dtmDate.Month.ToString(), dtmDate.Day.ToString());
                        DataTable dtActualShift = new DataTable();
                        dtActualShift = objShiftExchangeEventData.SelectPermanentShiftId(EmployeeCodeId, dtmDate.Year.ToString(), dtmDate.Month.ToString(), dtmDate.Day.ToString());
                        if (dtTempShift.Rows.Count > 0)
                        {
                            if (dtTempShift.Rows[0][0] != DBNull.Value)
                            {
                                intShiftId = int.Parse(dtTempShift.Rows[0][0].ToString());
                            }
                        }
                        if (intShiftId == 0)
                        {
                            if (dtActualShift.Rows.Count > 0)
                            {
                                if (dtActualShift.Rows[0][0] != DBNull.Value)
                                {
                                    intShiftId = int.Parse(dtActualShift.Rows[0][0].ToString());
                                }
                            }
                        }
                        int count = 0;
                        count = CheckAdditionalWeekOff(dtmDate, gstrSwipeCardNo);
                        if (count == 1)
                        {
                            intShiftId = -1;
                        }
                        //Check Whether the date is holiday
                        DataTable dtHoliday = new DataTable();
                        dtHoliday = objHolidayEventData.CheckDateForHoliday(dtmDate.ToShortDateString(), Convert.ToString(hdnEmployeeId1.Value));
                        if (dtHoliday.Rows.Count > 0 || intShiftId == -1)
                        {
                            testvalue = 4;
                            gintWeeklyOffHoliday = gintWeeklyOffHoliday + 1;
                        }
                    }
                }
                else
                {
                    // Intervening weekly off Temporary Table
                    DateTime dtmFromDate = DateTime.Parse(strLeaveFromDate);
                    DateTime dtmToDate = DateTime.Parse(strLeaveToDate);
                    for (DateTime dtmDate = dtmFromDate; dtmDate <= dtmToDate; dtmDate = dtmDate.AddDays(1))
                    {
                        int intShiftId = 0;
                        DataTable dtTempShift = new DataTable();
                        dtTempShift = objShiftExchangeEventData.SelectTemporaryShiftId(EmployeeCodeId, dtmDate.Year.ToString(), dtmDate.Month.ToString(), dtmDate.Day.ToString());
                        DataTable dtActualShift = new DataTable();
                        dtActualShift = objShiftExchangeEventData.SelectPermanentShiftId(EmployeeCodeId, dtmDate.Year.ToString(), dtmDate.Month.ToString(), dtmDate.Day.ToString());
                        if (dtTempShift.Rows.Count > 0)
                        {
                            if (dtTempShift.Rows[0][0] != DBNull.Value)
                            {
                                intShiftId = int.Parse(dtTempShift.Rows[0][0].ToString());
                            }
                        }
                        if (intShiftId == 0)
                        {
                            if (dtActualShift.Rows.Count > 0)
                            {
                                if (dtActualShift.Rows[0][0] != DBNull.Value)
                                {
                                    intShiftId = int.Parse(dtActualShift.Rows[0][0].ToString());
                                }
                            }
                        }
                        int count = 0;
                        count = CheckAdditionalWeekOff(dtmDate, gstrSwipeCardNo);
                        if (count == 1)
                        {
                            intShiftId = -1;
                        }
                        //Check Whether the date is holiday
                        DataTable dtHoliday = new DataTable();
                        dtHoliday = objHolidayEventData.CheckDateForHoliday(dtmDate.ToShortDateString(), Convert.ToString(hdnEmployeeId1.Value));
                        if (dtHoliday.Rows.Count > 0 || intShiftId == -1)
                        {
                            dDays = dDays - 1;
                            gintWeeklyOffHoliday = gintWeeklyOffHoliday + 1;
                            testvalue = 3;
                        }
                    }
                }
            }
        }
        // Finally write as Text
        if (gintWeeklyOffHoliday < dTempDays)
        {
            //if (strLeaveCategory == "Leave")
            //{
            //    //if ((dDays + fltLeaveTakenInMonth) > 1)
            //    //{
            //    //    //Message("CL Leave exceeds the limit");
            //    //    return "MaxLeaveTakenExceedsInMonth";
            //    //}
            //    return dDays.ToString();
            //}
            //Response.Clear();
            //Response.Write(dDays + "," + testvalue + "," + gintWeeklyOffHoliday);
            //Response.End();
            return dDays.ToString() + "," + testvalue.ToString() + "," + gintWeeklyOffHoliday.ToString();
        }
        else
        {
            //Message("Leave Application cannot be raised during Weekly Off / Global Holiday");
            return "HolidayWeeklyOff";
        }
    }
    #endregion
    #region DataChangedValidation
    protected string DataChangedValidation()
    {
        string LeaveStatus = string.Empty;
        //Checking and Convert to Date Format MM/dd/yyyy
        gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
        //Fill the Year Settings Detail
        DataSet ds_Year = new DataSet();
        ds_Year = objcls_Common.GetYearsetting();
        if (ds_Year.Tables[0].Rows.Count > 0)
        {
            gstrYearSettingStartDate = ds_Year.Tables[0].Rows[0]["FromDate"].ToString();
            gstrYearSettingsEndDate = ds_Year.Tables[0].Rows[0]["ToDate"].ToString();
            ViewState["YearSettings_Id"] = ds_Year.Tables[0].Rows[0]["YearSettings_Id"].ToString();
            ds_Year.Dispose();
        }
        if (strLeaveCategory == "1")
        {
            strLeaveCategory = "Leave";
        }
        else if (strLeaveCategory == "2")
        {
            strLeaveCategory = "LOP";
        }
        else if (strLeaveCategory == "3")
        {
            strLeaveCategory = "Comp Off";
        }
        if (strLeaveFromSession == "1")
        {
            strLeaveFromSession = "First Half";
        }
        else
        {
            strLeaveFromSession = "Second Half";
        }
        if (strLeaveToSession == "1")
        {
            strLeaveToSession = "First Half";
        }
        else
        {
            strLeaveToSession = "Second Half";
        }
        strLeaveFromDate = objcls_Common.DateConvertion(gstrDateFormat, strLeaveFromDate);
        strLeaveToDate = objcls_Common.DateConvertion(gstrDateFormat, strLeaveToDate);
        //Date Comparision
        if (DateDifference(DateTime.Parse(strLeaveFromDate), DateTime.Parse(strLeaveToDate)) < 0)
        {
            LeaveStatus = "To Date should be greater than from date";
            return LeaveStatus;
        }
        ////Validate within Year settings
        //if ((DateTime.Parse(strLeaveFromDate) >= DateTime.Parse(gstrYearSettingStartDate) && DateTime.Parse(strLeaveFromDate) <= DateTime.Parse(gstrYearSettingsEndDate)) && (DateTime.Parse(strLeaveToDate) >= DateTime.Parse(gstrYearSettingStartDate) && DateTime.Parse(strLeaveToDate) <= DateTime.Parse(gstrYearSettingsEndDate)))
        //{
        //    //Continue            
        //}
        //else
        //{
        //    LeaveStatus = "Select Leave Dates within current year";
        //    return LeaveStatus;
        //}
        ////Validate less than Year settings
        //if (DateTime.Parse(strLeaveToDate) < DateTime.Parse(gstrYearSettingStartDate))
        //{
        //    Message("Leave duration should not be less than the current year");
        //    return;
        //}
        ////Validate leave beyond the next year setting
        //if (ViewState["NextYearSettings_Id"] != null || ViewState["NextYearSettings_Id"] != string.Empty)
        //{
        //    if (DateTime.Parse(strLeaveToDate) >= DateTime.Parse(gstrNextYearSettingEndDate))
        //    {
        //        Message("Leave application cannot be raised beyond the next year");
        //        return;
        //    }
        //}
        //else
        //{
        //    if (DateTime.Parse(strLeaveToDate) > DateTime.Parse(gstrYearSettingEndDate))
        //    {
        //        Message("Leave application cannot be raised beyond the current year");
        //        return;
        //    }
        //}
        //Date of Joining Validation
        ds_EmployeeDetails = objLeaveApplicationEventData.GetEmployeeDetails(Convert.ToInt32(hdnEmployeeId.Value));
        gstrDateOfJoining = ds_EmployeeDetails.Tables[0].Rows[0]["DateOfJoining"].ToString();
        EmployeeCodeId = ds_EmployeeDetails.Tables[0].Rows[0]["Employee_Code_Id"].ToString();
        gstrSwipeCardNo = ds_EmployeeDetails.Tables[0].Rows[0]["SwipeCardNo"].ToString();
        if (DateTime.Parse(gstrDateOfJoining) <= DateTime.Parse(strLeaveFromDate))
        {
            //Leave dates Applicable
            DataSet dsRequiredPeriod = new DataSet();
            if (strLeaveCategory != "Comp Off")
            {
                dsRequiredPeriod = objLeaveApplicationEventData.GetApplicableAfterDays(Convert.ToInt32(hdnEmployeeId.Value), Convert.ToInt32(strLeaveTypeId), strLeaveFromDate);
                if (dsRequiredPeriod.Tables.Count > 0)
                {
                    dsRequiredPeriod.Tables[0].TableName = "Details";
                    if (dsRequiredPeriod.Tables[0].Rows[0]["RemainingNoOfLeaves"].ToString() == "Y")
                    {
                    }
                    else
                    {
                        //Leave dates not applicable
                        return "Leave dates are not applicable";
                        return LeaveStatus;
                    }
                }
            }
        }
        else
        {
            //Leave dates not applicable
            LeaveStatus = "Leave dates should be greater than Date of Joining";
            return LeaveStatus;
        }
        //Check the Leave lies between any Leave Policy of current year
        //Check Leave From Date and To Date falls between any Leave Policy with current year
        DataSet dsLeavePolicyDatesExists = new DataSet();
        dsLeavePolicyDatesExists = objLeaveApplicationEventData.GetLeavePolicyDatesExists_Angler(Convert.ToInt32(hdnEmployeeId.Value), strLeaveFromDate, strLeaveToDate);
        if (dsLeavePolicyDatesExists.Tables.Count > 0)
        {
            if (dsLeavePolicyDatesExists.Tables[0].Rows.Count > 0)
            {
                if (Convert.ToInt32(dsLeavePolicyDatesExists.Tables[0].Rows[0]["PolicyCount"]) == 0)
                {
                    LeaveStatus = "Leave dates should be within the Policy period";
                    return LeaveStatus;
                }
            }
        }
        //Check the Shift is allocated or not
        int ShiftCount = CheckShift();
        if (ShiftCount == 0)
        {
            LeaveStatus = "Shift not allocated for these leave days";
            return LeaveStatus;
        }
        //Check CL already Taken in a month
        if (strLeaveCategory == "Leave")
        {
            fltLeaveTakenInMonth = objLeaveApplicationEventData.GetLeaveTakenInMonth(hdnEmployeeId.Value, strLeaveTypeId, strLeaveFromDate, strLeaveToDate, 0);
        }
        if (fltLeaveTakenInMonth >= 1)
        {
            LeaveStatus = "CL Leave Exceeds the Limit";
            return LeaveStatus;
        }
        //Calculate Number of Days Applied based on Leave Policy
        testvalue = 0;
        string strDays = CalculateNumberOfDaysApplied();
        if (strDays == "MaxLeaveTakenExceedsInMonth")
        {
            //document.getElementById('ctl00_CP_Transaction_txt_Numberofdays').value="";
            LeaveStatus = "CL Leave Exceeds the Limit";
            return LeaveStatus;
        }
        if (strDays == "MaxLeaveTakenInMonth")
        {
            //document.getElementById('ctl00_CP_Transaction_txt_Numberofdays').value="";
            LeaveStatus = "CL already taken in this month";
            return LeaveStatus;
        }
        if (strDays == "HalfDayIsDisabled")
        {
            //document.getElementById('ctl00_CP_Transaction_txt_Numberofdays').value="";
            LeaveStatus = "Half day is not allowed";
            return LeaveStatus;
        }
        if (strDays == "InvalidYear")
        {
            //document.getElementById('ctl00_CP_Transaction_txt_Numberofdays').value="";
            LeaveStatus = "Select valid year";
            return LeaveStatus;
        }
        if (strDays == "FromToDates")
        {
            //document.getElementById('ctl00_CP_Transaction_txt_Numberofdays').value="";
            LeaveStatus = "Leave From Date should not be greater than Leave To Date";
            return LeaveStatus;
        }
        if (strDays == "DateOfJoining")
        {
            //document.getElementById('ctl00_CP_Transaction_txt_Numberofdays').value="";
            LeaveStatus = "Leave should not be applied before date of joining";
            return LeaveStatus;
        }
        if (strDays == "NoLeavePolicyDates")
        {
            //document.getElementById('ctl00_CP_Transaction_txt_Numberofdays').value="";
            LeaveStatus = "No Leave Policy exists for this Leave From Date or To Date";
            return LeaveStatus;
        }
        if (strDays == "ApplicableAfterDays")
        {
            LeaveStatus = "Leave should be applied, applicable after days";
            return LeaveStatus;
        }
        if (strDays == "Holiday")
        {
            LeaveStatus = "You are selecting Holiday";
            return LeaveStatus;
        }
        if (strDays == "WeeklyOffFromDate")
        {
            LeaveStatus = "You are selecting Weekly Off in From date";
            return LeaveStatus;
        }
        if (strDays == "WeeklyOffToDate")
        {
            LeaveStatus = "You are selecting Weekly Off in To date";
            return LeaveStatus;
        }
        if (strDays == "WeeklyOff")
        {
            LeaveStatus = "You are selecting Weekly Off";
            return LeaveStatus;
        }
        if (strDays == "HolidayWeeklyOff")
        {
            LeaveStatus = "Leave Application cannot be raised during Weekly Off / Global Holiday";
            return LeaveStatus;
        }
        if (strDays == "NoLeaveTypeId")
        {
            LeaveStatus = "Select Leave and LeaveTypeId";
            return LeaveStatus;
        }
        if (strDays == "ShiftNotAllocated")
        {
            LeaveStatus = "Shift not allocated";
            return LeaveStatus;
        }
        string[] NumberOfDays = strDays.Split(',');
        if (Convert.ToInt32(NumberOfDays[0]) < 0)
        {
            LeaveStatus = "Select Valid From Date and To Date";
            return LeaveStatus;
        }
        //else if (Convert.ToInt32(NumberOfDays[1]) == 0)
        //{
        //    //return;
        //}
        //else if (Convert.ToInt32(NumberOfDays[1]) == 1)
        //{
        //    //Message("You have choosed after weekly Off, One Day Added");
        //    //return;
        //}
        //else if (Convert.ToInt32(NumberOfDays[1]) == 2)
        //{
        //    //Message("You have choosed Before weekly Off, One Day Added");
        //    //return;
        //}
        //else if (Convert.ToInt32(NumberOfDays[1]) == 3)
        //{
        //    //Message("You have selected Intervening weekly Off / Global Holiday " + NumberOfDays[2] + " Day(s) Deducted");
        //    //return;
        //}
        //else if (Convert.ToInt32(NumberOfDays[1]) == 4)
        //{
        //    //Message("You have selected Intervening weekly Off / Global Holiday " + NumberOfDays[2] + " Day(s) included ");
        //    //return;
        //}
        //else if (Convert.ToInt32(NumberOfDays[1]) == -1)
        //{
        //    //return;
        //}
        dblNoOfDaysApplied = Convert.ToDouble(NumberOfDays[1]);
        return LeaveStatus;
    }
    #endregion
    #region Users rights.
    /// <summary>
    /// Checking the Users rights.
    /// </summary>
    private void UserRights()
    {
        dsCheckuser = objCheckUser.checkRights(22, Convert.ToInt32(Session["userGroup_Id"]), "addPrv");
        if (dsCheckuser.Tables[0].Rows.Count == 0)
        {
            Response.Redirect("TransactionLandingPage.aspx");
        }
    }
    #endregion
    #region Getting Information from resource file and display it in label.
    /// <summary>
    ///  Getting Information from resource file and display it in label.
    /// </summary>
    /// <param name="ci">The ci.</param>
    private void LoadStrings(CultureInfo ci)
    {
        lblEmployeeId.Text = objResourceManager.GetString("email_EmployeeId", ci);
        lblEmployeeName.Text = objResourceManager.GetString("email_EmployeeName", ci);
        lblEmployeeNames.Text = objResourceManager.GetString("email_EmployeeName", ci);
        //lblFromDate.Text = objResourceManager.GetString("email_FromDate", ci);
        //lblLeave.Text = objResourceManager.GetString("LeaveApplication_Leave", ci);
        //lblLeaveApplicationDate.Text = objResourceManager.GetString("LeaveApplication_LeaveApplicationDate", ci);
        //lblLeaveRestrictedHoliday.Text = objResourceManager.GetString("LeaveApplication_LeaveRestrictedHoliday", ci);
        //lblLeaveType.Text = objResourceManager.GetString("lbl_leavetype", ci);
        //lblNumberofdaysapplied.Text = objResourceManager.GetString("LeaveApplication_NumberOfDaysApplied", ci);
        lblReason.Text = objResourceManager.GetString("email_Reason", ci);
        //lblRemainingNumberofLeave.Text = objResourceManager.GetString("LeaveApplication_RemainingNumberOfLeave", ci);
        //lblToDate.Text = objResourceManager.GetString("email_ToDate", ci);
        lblIndicatesMandatoryFields.Text = objResourceManager.GetString("IndicatesMandatoryFields", ci);
        //CustomValidator1.ErrorMessage = objResourceManager.GetString("Alert_SelectvalidFromDate", ci);
        //CustomValidator1.ErrorMessage = "Select future date";
        //cus_ComDate.ErrorMessage = objResourceManager.GetString("Msg_GrearterThanFrmDate", ci);
        //CustomValidator2.ErrorMessage = objResourceManager.GetString("Alert_SelectvalidToDate", ci);
        //CustomValidator2.ErrorMessage = "Select future date";
        lbl_HeaderLeaveApplication.Text = objResourceManager.GetString("Transactions_LeaveApplication", ci);
        //chkBorrowLeave.Text = objResourceManager.GetString("Transactions_LeaveBorrow", ci);
        btnAdd.Text = "&nbsp;&nbsp;" + objResourceManager.GetString("btn_Save", ci);
        btnCancel.Text = "&nbsp;&nbsp;" + objResourceManager.GetString("btn_Back", ci);
        btnSearch.Text = "&nbsp;&nbsp;" + objResourceManager.GetString("btn_Search", ci);
        //btnQuota.Text = objResourceManager.GetString("btn_Leave_Quota", ci);
        //btnQuota.Text = "View Quota";
    }
    #endregion
    private void SendMail(Int64 LeaveApplicationId, Int64 LevelId, int intFirstLevelAuthorityId, int intSecondLevelAuthorityId, string strEmailIdReportingTo, string strEmailIdSanctionAuthority, string intimationType)
    {
        DataSet ds_LeaveApplication = new DataSet();
        ds_LeaveApplication = objLeaveApplicationEventData.SelectLeaveApplication(Convert.ToInt32(LeaveApplicationId));
        DataSet dsCCEmailIds = new DataSet();
        bool blnMailToSecondLevel = false;
        //For planned leave
        if (intimationType == "P")
        {
            dsCCEmailIds = objCCGroup.GetCCEmailIds(Convert.ToInt16(ds_EmployeeDetails.Tables[0].Rows[0]["LevelId"].ToString()), Convert.ToInt16(ds_EmployeeDetails.Tables[0].Rows[0]["Designation_Id"].ToString()), "P");
            if (dsCCEmailIds != null)
            {
                if (dsCCEmailIds.Tables[1].Rows.Count > 0)
                {
                    if (Convert.ToBoolean(dsCCEmailIds.Tables[1].Rows[0]["MailTo_SecondLevel_Planned"].ToString()) == true)
                    {
                        blnMailToSecondLevel = true;
                    }
                }
            }
        }
        //For UnPlanned leave
        else
        {
            dsCCEmailIds = objCCGroup.GetCCEmailIds(Convert.ToInt16(ds_EmployeeDetails.Tables[0].Rows[0]["LevelId"].ToString()), Convert.ToInt16(ds_EmployeeDetails.Tables[0].Rows[0]["Designation_Id"].ToString()), "U");
            if (dsCCEmailIds != null)
            {
                if (dsCCEmailIds.Tables[1].Rows.Count > 0)
                {
                    if (Convert.ToBoolean(dsCCEmailIds.Tables[1].Rows[0]["MailTo_SecondLevel_UnPlanned"].ToString()) == true)
                    {
                        blnMailToSecondLevel = true;
                    }
                }
            }
        }
        if (ds_LeaveApplication.Tables[0].Rows[0]["LeaveAvailedMonth"].ToString() != string.Empty)
        {
            strLeaveAvailedMonth = ds_LeaveApplication.Tables[0].Rows[0]["LeaveAvailedMonth"].ToString();
        }
        else
        {
            strLeaveAvailedMonth = "0.0";
        }
        if (ds_LeaveApplication.Tables[0].Rows[0]["LeaveAvailedYear"].ToString() != string.Empty)
        {
            strLeaveAvailedYear = ds_LeaveApplication.Tables[0].Rows[0]["LeaveAvailedYear"].ToString();
        }
        else
        {
            strLeaveAvailedYear = "0.0";
        }
        string FromDate = string.Empty, ToDate = string.Empty;
        double NumberOfDaysApplied = 0.0;
        try
        {
            // Get the Application Root Path
            string strApplicationPath = Request.UrlReferrer.ToString();
            int intLastIndex = strApplicationPath.LastIndexOf('/');
            strApplicationPath = strApplicationPath.Substring(0, (intLastIndex - 1));
            intLastIndex = strApplicationPath.LastIndexOf('/');
            strApplicationPath = strApplicationPath.Substring(0, (intLastIndex + 1));
            string[] strSysName;
            strSysName = strApplicationPath.Split('/');
            string strServerIP = string.Empty;
            //= GetIPAddress();
            strServerIP = System.Configuration.ConfigurationManager.AppSettings["ServerIP"].ToString();
            strApplicationPath = strApplicationPath.Replace(strSysName[2].ToString(), strServerIP);
            MailMessage mailMessage = new MailMessage();
            SmtpClient loSMTPServer = new SmtpClient();
            System.Net.Mime.ContentType loTextType = new System.Net.Mime.ContentType("text/plain");
            System.Net.Mime.ContentType loHTMLType = new System.Net.Mime.ContentType("text/html");
            AlternateView loTextView = null;
            AlternateView loHTMLView = null;
            string scriptText, status;
            DataTable dtTableScript = new DataTable();
            string ScriptType = string.Empty;
            if (strCrossDate == "Yes")
            {
                ScriptType = "New Cross date Leave Application Form";
            }
            else
            {
                ScriptType = "New Leave Application Form";
            }
            dtTableScript = objLeaveApplicationEventData.GetEmailScripts(ScriptType);
            scriptText = dtTableScript.Rows[0]["ScriptText"].ToString();
            #region Code By A.K.T.MOORTHI For Pervious Leave Details
            string strLeaveDetails = string.Empty;
            if (Convert.ToString(hdnEmployeeId.Value) != string.Empty)
            {
                DataSet dstLeave = objLeaveApplicationEventData.GetPreviousLeaveDetails(Convert.ToInt16(hdnEmployeeId.Value), string.Empty, "M");
                strLeaveDetails = dstLeave.Tables.Count > 0 ? dstLeave.Tables[0].Rows.Count > 0 ? Convert.ToString(dstLeave.Tables[0].Rows[0][0]) : string.Empty : string.Empty;
            }
            #endregion
            if (Session["loginEmailId"].ToString() != string.Empty || Session["loginEmailId"] != null)
            {
                if (Session["loginEmailId"].ToString() != EmployeeEamilId)
                {
                    mailMessage.From = new MailAddress(Session["loginEmailId"].ToString());
                    //mailMessage.CC.Add(new MailAddress(EmployeeEamilId));
                }
                else if (EmployeeEamilId != string.Empty)
                {
                    mailMessage.From = new MailAddress(EmployeeEamilId);
                }
                else
                {
                    mailMessage.From = new MailAddress(ConfigurationManager.AppSettings.Get("FromId"));
                }
            }
            else
            {
                mailMessage.From = new MailAddress(ConfigurationManager.AppSettings.Get("FromId"));
            }
            if (intimationType == "P")
            {
                intimationType = "Planned";
            }
            //commenting this only for avoiding empty EmployeeEmailId by manjula.p on 23-May-2013. For that adding next four line (if condition)
            //mailMessage.CC.Add(new MailAddress(EmployeeEamilId));
            if (EmployeeEamilId != string.Empty)
                mailMessage.CC.Add(new MailAddress(EmployeeEamilId));
            else
                mailMessage.CC.Add(new MailAddress(mailMessage.From.ToString()));
            if (strEmailIdReportingTo == strEmailIdSanctionAuthority)
            {
                status = "Forwarded";
                mailMessage.To.Add(new MailAddress(strEmailIdReportingTo));
                mailMessage.Subject = "TimeCheck : " + strlevelName + " | " + strEmployeeName + " - " + strEmployeeCodeId + " | Leave  - " + " Forwarded" + " | " + intimationType;
                //mailMessage.Subject = objResourceManager.GetString("email_LeaveApplicationForm", objCultureInfo) + " - " + ApplicationDate + " | " + Employee_Code_Id + " | " + EmployeeName + " - " + strlevelName + " - " + "Forwarded";
            }
            else
            {
                status = "Pending";
                mailMessage.To.Add(new MailAddress(strEmailIdReportingTo));
                if (blnMailToSecondLevel == true)
                {
                    mailMessage.CC.Add(new MailAddress(strEmailIdSanctionAuthority));
                }
                mailMessage.Subject = "TimeCheck : " + strlevelName + " | " + strEmployeeName + " - " + strEmployeeCodeId + " | Leave  - " + " Pending" + " | " + intimationType;
                //mailMessage.Subject = objResourceManager.GetString("email_LeaveApplicationForm", objCultureInfo) + " - " + ApplicationDate + " | " + Employee_Code_Id + " | " + EmployeeName + " - " + strlevelName + " - " + "Pending";
            }
            //CC mails from CC group
            if (dsCCEmailIds != null)
            {
                if (dsCCEmailIds.Tables[0].Rows.Count > 0)
                {
                    foreach (DataRow drCcEmailId in dsCCEmailIds.Tables[0].Rows)
                    {
                        MailAddressCollection MailAddrCollectionCC = mailMessage.CC;
                        // added by Gopinath.k for Mantis Bug no.24059 & 24098
                        if (drCcEmailId["EmailId"].ToString() != string.Empty)
                        {
                            MailAddress newCC = new MailAddress(drCcEmailId["EmailId"].ToString());
                            MailAddrCollectionCC.Add(newCC);
                        }
                    }
                }
            }
            //check for duplicate mail Ids
            //included by sashma on 20-Oct-2010
            Hashtable htToMails = new Hashtable();
            Hashtable htCCMails = new Hashtable();
            int intToMailCount = 0;
            int intCCMailCount = 0;
            //inserts the TO mailIds in the hashtable
            foreach (MailAddress ToMail in mailMessage.To)
            {
                if (htToMails.ContainsValue(ToMail) == false)
                {
                    htToMails.Add(intToMailCount++, ToMail);
                }
            }
            //inserts the CC mailIds in the hashtable
            foreach (MailAddress CCMail in mailMessage.CC)
            {
                //check whether the mail alredy exists in CC mails.
                if (htCCMails.ContainsValue(CCMail) == false)
                {
                    //check whether the mail alredy exists in TO mails.
                    if (htToMails.ContainsValue(CCMail) == false)
                    {
                        htCCMails.Add(intCCMailCount++, CCMail);
                    }
                }
            }
            mailMessage.To.Clear();
            mailMessage.CC.Clear();
            //Adds the TO mails from the hastable.
            foreach (DictionaryEntry ToMails in htToMails)
            {
                mailMessage.To.Add(ToMails.Value.ToString());
            }
            //Adds the CC mails from the hastable.
            foreach (DictionaryEntry CCMails in htCCMails)
            {
                mailMessage.CC.Add(CCMails.Value.ToString());
            }
            mailMessage.Body = scriptText.Replace("<<lblLeaveApplicationForm>>", objResourceManager.GetString("email_LeaveApplicationForm", objCultureInfo));
            mailMessage.Body = mailMessage.Body.Replace("<<ltr_rtl>>", objResourceManager.GetString("Direction", objCultureInfo));
            mailMessage.Body = mailMessage.Body.Replace("<<lblEmployeeId>>", objResourceManager.GetString("email_EmployeeId", objCultureInfo));
            mailMessage.Body = mailMessage.Body.Replace("<<EmployeeId>>", strEmployeeCodeId);
            mailMessage.Body = mailMessage.Body.Replace("<<lblDepartment>>", "Department");
            mailMessage.Body = mailMessage.Body.Replace("<<Department>>", strlevelName);
            mailMessage.Body = mailMessage.Body.Replace("<<EmployeeName>>", strEmployeeName);
            mailMessage.Body = mailMessage.Body.Replace("<<lblEmployeeName>>", objResourceManager.GetString("email_EmployeeName", objCultureInfo));
            if (strCrossDate == "Yes")
            {
                mailMessage.Body = mailMessage.Body.Replace("<<NoOfLeaveAvailedinFirstMonth>>", strLeaveAvailedInFirstMonth);
                mailMessage.Body = mailMessage.Body.Replace("<<lblNoOfLeaveAvailedinFirstMonth>>", "Leave availed in " + strLeaveAvailedInFirstMonthName);
                mailMessage.Body = mailMessage.Body.Replace("<<NoOfLeaveAvailedinsecondMonth>>", strLeaveAvailedInSecondMonth);
                mailMessage.Body = mailMessage.Body.Replace("<<lblNoOfLeaveAvailedinsecondMonth>>", "Leave availed in " + strLeaveAvailedInSecondMonthName);
            }
            else
            {
                //mailMessage.Body = mailMessage.Body.Replace("<<NoOfLeaveAvailedMonth>>", strLeaveAvailedMonth);
                mailMessage.Body = mailMessage.Body.Replace("<<NoOfLeaveAvailedMonth>>", strLeaveAvailedInFirstMonth);
                mailMessage.Body = mailMessage.Body.Replace("<<lblNoOfLeaveAvailedMonth>>", "Leave availed in " + strLeaveAvailedInFirstMonthName);
            }
            //mailMessage.Body = mailMessage.Body.Replace("<<NoOfLeaveAvailedMonth>>", dblLeaveAvailedMonth.ToString());
            //mailMessage.Body = mailMessage.Body.Replace("<<NoOfLeaveAvailedYear>>", dblLeaveAvailedYear.ToString());
            //mailMessage.Body = mailMessage.Body.Replace("<<NoOfLeaveAvailedYear>>", strLeaveAvailedYear);
            //mailMessage.Body = mailMessage.Body.Replace("<<lblNoOfLeaveAvailedYear>>", "Leave availed in this Year");
            DateTime dtmTodaysDate = Convert.ToDateTime(DateTime.Now.ToShortDateString());
            mailMessage.Body = mailMessage.Body.Replace("<<ApplicationDate>>", dtmTodaysDate.ToString(Session["MDateFormat"].ToString()));
            mailMessage.Body = mailMessage.Body.Replace("<<lblApplicationDate>>", objResourceManager.GetString("email_LeaveApplicationDate", objCultureInfo));
            //mailMessage.Body = mailMessage.Body.Replace("<<LeaveType>>", strLeaveCategory + " / " + strLeaveType);
            //mailMessage.Body = mailMessage.Body.Replace("<<lblLeaveType>>", objResourceManager.GetString("lbl_leavetype", objCultureInfo));
            mailMessage.Body = mailMessage.Body.Replace("<<NumberDaysApplied>>", Convert.ToString(NumberOfDaysApplied));
            mailMessage.Body = mailMessage.Body.Replace("<<lblNumberDaysApplied>>", objResourceManager.GetString("email_NumberOfDaysApplied", objCultureInfo));
            mailMessage.Body = mailMessage.Body.Replace("<<lblLeaveDate>>", objResourceManager.GetString("email_LeaveDate", objCultureInfo));
            mailMessage.Body = mailMessage.Body.Replace("<<FromDate>>", FromDate);
            mailMessage.Body = mailMessage.Body.Replace("<<lblFromDate>>", objResourceManager.GetString("email_FromDate", objCultureInfo));
            mailMessage.Body = mailMessage.Body.Replace("<<ToDate>>", ToDate);
            mailMessage.Body = mailMessage.Body.Replace("<<lblToDate>>", objResourceManager.GetString("email_ToDate", objCultureInfo));
            mailMessage.Body = mailMessage.Body.Replace("<<lblSession>>", objResourceManager.GetString("email_Session", objCultureInfo));
            mailMessage.Body = mailMessage.Body.Replace("<<FromSession>>", "First Half");
            mailMessage.Body = mailMessage.Body.Replace("<<lblFromSession>>", objResourceManager.GetString("email_FromDate", objCultureInfo));
            mailMessage.Body = mailMessage.Body.Replace("<<ToSession>>", "Second Half");
            mailMessage.Body = mailMessage.Body.Replace("<<lblToSession>>", objResourceManager.GetString("email_ToDate", objCultureInfo));
            mailMessage.Body = mailMessage.Body.Replace("<<lblStatus>>", objResourceManager.GetString("email_Status", objCultureInfo));
            mailMessage.Body = mailMessage.Body.Replace("<<Status>>", status);
            mailMessage.Body = mailMessage.Body.Replace("<<Reason>>", txtReason.Text.Replace("'", "''"));
            mailMessage.Body = mailMessage.Body.Replace("<<lblReason>>", objResourceManager.GetString("email_Reason", objCultureInfo));
            mailMessage.Body = mailMessage.Body.Replace("<<divMailThread>>", strHtmlLeaveDetails);
            //Added By A.K.T.MOORTHI
            mailMessage.Body = mailMessage.Body.Replace("<<divLeaveThread>>", strLeaveDetails);
            //mailMessage.Body = mailMessage.Body.Replace("<<LinkData>>", strServerIP + "Index.aspx?LeaveApplication_Id=" + LeaveApplicationId + "&LevelId=" + LevelId + "&ApprovalType=Leave");
            mailMessage.Body = mailMessage.Body.Replace("<<LinkData>>", Convert.ToString(Session["HostServerURL"]) + "?LeaveApplication_Id=" + LeaveApplicationId + "&LevelId=" + LevelId + "&ApprovalType=Leave&Status=All&From_Date=&To_Date=&strSwipeCardNo=&strEmployeeName=&strEmployeeCodeId=&Angler=1");
            loHTMLView = AlternateView.CreateAlternateViewFromString(mailMessage.Body, loHTMLType);
            mailMessage.AlternateViews.Add(loHTMLView);
            objcls_Common.SendMail(mailMessage);
        }
        catch
        {
            blnCheckEmail = false;
        }
    }
    #region Split Mail ids
    private string[] SplitCCTo(string CCTo)
    {
        string[] strArrEmailAddressForCC;
        strArrEmailAddressForCC = CCTo.Split(';');
        //for (int i = 0; i < strArrEmailAddressForCC.Length; i++)
        //{
        //    strArrEmailAddressForCC[i] = strArrEmailAddressForCC[i].Replace(strArrEmailAddressForCC[i], "zz");
        //}
        return (strArrEmailAddressForCC);
    }
    #endregion
    #region ServerIPAddress
    /// <summary>
    /// 
    /// </summary>
    /// <returns></returns>
    public string GetIPAddress()
    {
        string strHostName = System.Net.Dns.GetHostName();
        IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
        IPAddress ipAddress = ipHostInfo.AddressList[0];
        return ipAddress.ToString();
    }
    #endregion
    public string buildPage(string strPageTitle, DataTable myDT)
    {
        StringBuilder sb = new StringBuilder();
        //HTML header
        sb.Append("<html>");
        sb.Append("<head>");
        sb.Append("<title>");
        sb.Append(strPageTitle);
        sb.Append("</title>");
        sb.Append("<style type='text/css'>");
        sb.Append(".Header {color: #FFFFFF; font-family: Arial;font-size: x-small;font-weight: bold;}");
        sb.Append(".rows {font-family: Arial; font-size: x-small;background-color:#FFE3B9}");
        sb.Append(".rowsNew {font-family: Arial; font-size: x-small;background-color:#FFEED5}");
        sb.Append("</style>");
        sb.Append("</head>");
        sb.Append("<body>");
        sb.Append("<table border='1' cellpadding='2' style='border-collapse: collapse' bordercolor='#666666' width='700'>");
        sb.Append("  <tr bgcolor='#003466' >");
        //Table header       
        foreach (DataColumn Col in myDT.Columns)
        {
            sb.Append("<td><span class='Header'>" + Col.ColumnName.ToString() + "</span></td>");
        }
        sb.Append("  </tr>");
        //add rows to the table for the length of the dataset
        int intWidth = 0;
        int intIncrement = 0;
        foreach (DataRow Row in myDT.Rows)
        {
            //intWidth = 0;
            if (intIncrement % 2 == 0)
            {
                sb.Append("<tr>");
            }
            else
            {
                sb.Append("<tr>");
            }
            foreach (DataColumn Col in myDT.Columns)
            {
                //if (intWidth == 0)
                //{
                sb.Append("<td><font face='Arial' size='2'>" + Row[Col.ColumnName].ToString() + "</font></td>");
                //intWidth = 1;
                //}
                //else if (intWidth != 0)
                //{
                //    sb.Append("<td width='70%'>" + Row[Col.ColumnName].ToString() + "</td>");
                //    intWidth = 0;
                //}
            }
            sb.Append("  </tr>");
            intIncrement = intIncrement + 1;
        }
        //Close the html string
        sb.Append("</table>");
        sb.Append("</body>");
        sb.Append("</html>");
        return sb.ToString();
    }
    //Converts the Date from any Date Format to MM/DD/YYYY
    public bool DateConvertion(string Format, string strDateTime)
    {
        bool blnDate = true;
        // Getting Month
        try
        {
            int indexMonth = -2;
            int intMonthNoOfChars = 0;
            string strMonth = "";
            int indexMMM = Format.IndexOf(@"MMM");
            if (indexMMM == -1)
            {
                int indexMM = Format.IndexOf(@"MM");
                if (indexMM >= 0)
                {
                    indexMonth = indexMM;
                    intMonthNoOfChars = 2;
                }
            }
            else
            {
                indexMonth = indexMMM;
                intMonthNoOfChars = 3;
            }
            if (indexMonth != -2)
            {
                strMonth = strDateTime.Substring(indexMonth, intMonthNoOfChars);
            }
            // Getting Date
            int indexDate = -2;
            int intDateNoOfChars = 0;
            string strDate = "";
            int indexDD = Format.IndexOf(@"dd");
            if (indexDD >= 0)
            {
                indexDate = indexDD;
                intDateNoOfChars = 2;
            }
            if (indexDate != -2)
            {
                strDate = strDateTime.Substring(indexDate, intDateNoOfChars);
            }
            // Getting Year
            int indexYear = -2;
            int intYearNoOfChars = 0;
            string strYear = "";
            int indexYYYY = Format.IndexOf(@"yyyy");
            if (indexYYYY == -1)
            {
                int indexYY = Format.IndexOf(@"yy");
                if (indexYY >= 0)
                {
                    indexYear = indexYY;
                    intYearNoOfChars = 2;
                }
            }
            else
            {
                indexYear = indexYYYY;
                intYearNoOfChars = 4;
            }
            if (indexYear != -2)
            {
                strYear = strDateTime.Substring(indexYear, intYearNoOfChars);
            }
            string strFinalDate = "";
            if (indexMMM >= 0)
            {
                strFinalDate = strDate + "/" + strMonth + "/" + strYear;
            }
            else
            {
                // strFinalDate = strMonth + "/" + strDate + "/" + strYear;
                strFinalDate = strYear + "/" + strMonth + "/" + strDate;
            }
            DateTime dtmFinalDate = new DateTime();
            dtmFinalDate = DateTime.Parse(strFinalDate);
        }
        catch (Exception ex)
        {
            //throw ex;
            blnDate = false;
        }
        return (blnDate);
    }
}
