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.Resources;
using System.Globalization;
using System.Text;
using System.Net;
using System.Net.Mail;
using System.Threading;
public partial class Transactions_TA_UI_Transactions_MultipleLeaveApplicationModifyAdmin : Base.BasePage
{
    ResourceManager rm;
    CultureInfo ci;
    LeaveApplicationEventData_Angler objLeaveApplicationEventData = new LeaveApplicationEventData_Angler();
    cls_Common objcls_Common = new cls_Common();
    DataSet gdsLeaveApplication_Original = new DataSet();
    DataSet dsLeaveTypesData = new DataSet();
    DataSet dsHolidays = new DataSet();
    DataSet dsLeaveTypesLOPDays = new DataSet();
    DataSet ds_EmployeeDetails = new DataSet();
    DataSet dsRemainingNoOfLeaves = new DataSet();
    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, strLeaveAvailedYear, strLeaveAvailedMonth;
    string gstrDateOfJoining = string.Empty;
    string EmployeeCodeId = string.Empty;
    string gstrSwipeCardNo = string.Empty;
    string gstrLeaveStatus = 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 strHtml = string.Empty;
    double fltLeaveTakenInMonth = 0.0;
    double dblNoOfDaysApplied = 0.0;
    int testvalue;
    int gintWeeklyOffHoliday = 0;
    int iLeaveApplication_Id;
    //double dblLeaveAvailedYear = 0.0;
    //double dblLeaveAvailedMonth = 0.0;
    bool blnCheckEmail;
    bool blnModifyStatus = false;
    /// <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 (Session["UserGroupName"].ToString() != "SuperAdmin")
        {
            Response.Redirect("TA_UI_Transactions_LeaveApplication.aspx");
        }
        if (Request.UrlReferrer != null)
        {
            string GetURL = Request.UrlReferrer.ToString();
        }
        else
        {
            Response.Redirect("TA_UI_Transactions_LeaveApplicationAdmin.aspx");
        }
        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;
        }
        //Checking and Convert to Date Format MM/dd/yyyy
        gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
        iLeaveApplication_Id = 0;
        iLeaveApplication_Id = Convert.ToInt32(Request.QueryString["leaveApplicationId"].ToString());
        ViewState["vsLeaveApplicationId"] = iLeaveApplication_Id;
        if (!IsPostBack)
        {
            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.DataTextField = "EmployeeName";
            lstInformTo.DataValueField = "EmployeeName";
            lstInformTo.DataBind();
            ViewState["LeaveAvailedMonth"] = null;
            ViewState["LeaveAvailedYear"] = null;
            bindGridFirstTime();
        }
        CreateControlConversation();
        if (Session["UserGroupName"].ToString() == "SuperAdmin" || Session["HasSpecialRights"].ToString() == "True")
        {
            divIntimationType.Visible = true;
        }
        else
        {
            divIntimationType.Visible = false;
        }
        //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;
        //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();
        }
        //Call to a function to get the display string from the resource file
        LoadStrings(objCultureInfo);
        if (!IsPostBack)
        {
            //ByWhomResend();
        }
    }
    protected void bindGridFirstTime()
    {
        DataSet ds_LeaveApplication = new DataSet();
        ds_LeaveApplication = objLeaveApplicationEventData.SelectLeaveApplication(iLeaveApplication_Id);
        ViewState["levelid"] = ds_LeaveApplication.Tables[0].Rows[0]["levelid"].ToString();
        ViewState["DesignationID"] = ds_LeaveApplication.Tables[0].Rows[0]["DesignationID"].ToString();
        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";
        }
        ViewState["LeaveAvailedMonth"] = strLeaveAvailedMonth;
        ViewState["LeaveAvailedYear"] = strLeaveAvailedYear;
        DataTable dtLeaveSort = new DataTable();
        DataTable dtLeaveTable2 = new DataTable();
        dtLeaveSort = ds_LeaveApplication.Tables[0];
        dtLeaveTable2 = ds_LeaveApplication.Tables[1];
        dtLeaveSort.DefaultView.Sort = "LeaveFrom asc";
        ds_LeaveApplication.Tables.Clear();
        ds_LeaveApplication.Tables.Add(dtLeaveSort.DefaultView.ToTable());
        ds_LeaveApplication.Tables.Add(dtLeaveTable2);
        hdnEmployeeId.Value = ds_LeaveApplication.Tables[0].Rows[0]["Employee_Id"].ToString();
        lblPreviousReason.Text = ds_LeaveApplication.Tables[0].Rows[0]["Reason"].ToString();
        ViewState["vsReason"] = ds_LeaveApplication.Tables[1].Rows[0]["Reason"].ToString();
        ViewState["vsLeaveApplicationDate"] = Convert.ToDateTime(ds_LeaveApplication.Tables[0].Rows[0]["Leave_ApplicationDate"]).ToString(Session["MDateFormat"].ToString());
        lblEmployeeIdData.Text = ds_LeaveApplication.Tables[0].Rows[0]["Employee_Code_Id"].ToString();
        lblEmployeeNameData.Text = ds_LeaveApplication.Tables[0].Rows[0]["Employee_FirstName"].ToString();
        gstrLeaveStatus = ds_LeaveApplication.Tables[0].Rows[0]["Status"].ToString();
        ViewState["vwLeaveStatus"] = gstrLeaveStatus;
        txtApprovalCC.Text = ds_LeaveApplication.Tables[0].Rows[0]["CCMail"].ToString();
        //Intimation Type
        string intimationType = ds_LeaveApplication.Tables[0].Rows[0]["IntimationType"].ToString();
        // get inputs from UI
        if (intimationType == "P")
        {
            rbtnP.Checked = true;
        }
        else if (intimationType == "UP-WI")
        {
            rbtnUPWI.Checked = true;
        }
        else if (intimationType == "UP-WOI")
        {
            rbtnUPWOI.Checked = true;
        }
        //Assign the Original Data set as Backup
        gdsLeaveApplication_Original = ds_LeaveApplication;
        DataColumn dcSLNO = new DataColumn("SLNo", Type.GetType("System.Int64"));
        ds_LeaveApplication.Tables[0].Columns.Add(dcSLNO);
        int intIncrement = 1;
        foreach (DataRow dRow in ds_LeaveApplication.Tables[0].Rows)
        {
            dRow["SLNO"] = intIncrement;
            intIncrement = intIncrement + 1;
        }
        gvTestGrid.DataSource = ds_LeaveApplication;
        gvTestGrid.DataBind();
        LoadComboInGridFirstTime(((DataSet)gvTestGrid.DataSource).Tables[0]);
        ViewState["LeaveDetailsTable"] = ((DataSet)gvTestGrid.DataSource).Tables[0];
        string strInformTo = Convert.ToString(ds_LeaveApplication.Tables[0].Rows[0]["InformTo"]);
        if (strInformTo != string.Empty)
        {
            foreach (string strName in strInformTo.Split(','))
                lstInformTo.Items.FindByText(strName.Trim()).Selected = true;
        }
        lstInformTo.Enabled = intimationType.Contains("UP-WI");
    }
    private void CreateControlConversation()
    {
        // getting leave conversation 
        DataSet dsLeaveConversation = objLeaveApplicationEventData.GetLeaveConversation(iLeaveApplication_Id);
        if (dsLeaveConversation.Tables[0].Rows.Count > 0)
        {
            Table leaveConversation = new Table();
            leaveConversation.BorderWidth = 1;
            leaveConversation.CellPadding = 5;
            leaveConversation.CellSpacing = 0;
            leaveConversation.BorderColor = System.Drawing.Color.White;
            leaveConversation.Width = Unit.Pixel(775);
            leaveConversation.CssClass = "td";
            leaveConversation.Attributes.Add("border", "1");
            TableHeaderRow leaveConversationHr = new TableHeaderRow();
            TableHeaderCell leaveConversationHeading3 = new TableHeaderCell();
            leaveConversationHeading3.Text = rm.GetString("TerminalDataType_Date_And_Time", ci); 
            leaveConversationHeading3.HorizontalAlign = HorizontalAlign.Left;
            leaveConversationHr.Cells.Add(leaveConversationHeading3);
            TableHeaderCell leaveConversationHeading1 = new TableHeaderCell();
            leaveConversationHeading1.Text = rm.GetString("leaveConversationHeading1", ci);
            leaveConversationHeading1.HorizontalAlign = HorizontalAlign.Left;
            leaveConversationHr.Cells.Add(leaveConversationHeading1);
            TableHeaderCell leaveConversationHeading2 = new TableHeaderCell();
            leaveConversationHeading2.Text = rm.GetString("leaveConversationHeading2", ci);
            leaveConversationHeading2.HorizontalAlign = HorizontalAlign.Left;
            leaveConversationHr.Cells.Add(leaveConversationHeading2);
            leaveConversation.Rows.Add(leaveConversationHr);
            if (dsLeaveConversation != null && dsLeaveConversation.Tables.Count > 0)
            {
                if (dsLeaveConversation.Tables[0].Rows.Count > 0)
                {
                    int rowIndex = 0;
                    foreach (DataRow drLeaveConversation in dsLeaveConversation.Tables[0].Rows)
                    {
                        TableRow trLeaveConversation = new TableRow();
                        TableCell tcLeaveConversationRepliedOn = new TableCell();
                        tcLeaveConversationRepliedOn.BorderColor = System.Drawing.Color.White;
                        Label lblLeaveConversationRepliedOn = new Label();
                        tcLeaveConversationRepliedOn.BorderWidth = 1;
                        tcLeaveConversationRepliedOn.Width = 120;
                        lblLeaveConversationRepliedOn.ID = "lblLeaveConversationRepliedOn" + rowIndex;
                        lblLeaveConversationRepliedOn.Text = Convert.ToDateTime(drLeaveConversation["TimeStamp"]).ToString(Session["MDateFormat"].ToString()) + " " + Convert.ToDateTime(drLeaveConversation["TimeStamp"]).ToString(Session["MTimeFormat"].ToString());
                        tcLeaveConversationRepliedOn.Controls.Add(lblLeaveConversationRepliedOn);
                        trLeaveConversation.Cells.Add(tcLeaveConversationRepliedOn);
                        TableCell tcLeaveConversationCommentsBy = new TableCell();
                        tcLeaveConversationCommentsBy.BorderColor = System.Drawing.Color.White;
                        Label lblLeaveConversationCommentsBy = new Label();
                        tcLeaveConversationCommentsBy.BorderWidth = 1;
                        tcLeaveConversationCommentsBy.Width = 153;
                        lblLeaveConversationCommentsBy.ID = "lblLeaveConversationCommentsBy" + rowIndex;
                        if (drLeaveConversation["CommentsBy"].ToString() == "0")
                        {
                            lblLeaveConversationCommentsBy.Text = lblEmployeeNameData.Text;
                        }
                        else if (drLeaveConversation["CommentsBy"].ToString() == "1")
                        {
                            lblLeaveConversationCommentsBy.Text = objLeaveApplicationEventData.GetEmployeeName(Convert.ToInt32(drLeaveConversation["Emp_Id"].ToString()));
                        }
                        else if (drLeaveConversation["CommentsBy"].ToString() == "2")
                        {
                            lblLeaveConversationCommentsBy.Text = objLeaveApplicationEventData.GetEmployeeName(Convert.ToInt32(drLeaveConversation["Emp_Id"].ToString()));
                        }
                        else if (drLeaveConversation["CommentsBy"].ToString() == "3")
                        {
                            lblLeaveConversationCommentsBy.Text = objLeaveApplicationEventData.GetEmployeeName(Convert.ToInt32(drLeaveConversation["Emp_Id"].ToString()));
                        }
                        tcLeaveConversationCommentsBy.Controls.Add(lblLeaveConversationCommentsBy);
                        trLeaveConversation.Cells.Add(tcLeaveConversationCommentsBy);
                        TableCell tcLeaveConversationComments = new TableCell();
                        tcLeaveConversationComments.BorderColor = System.Drawing.Color.White;
                        Label lblLeaveConversationComments = new Label();
                        tcLeaveConversationComments.BorderWidth = 1;
                        tcLeaveConversationComments.ColumnSpan = 2;
                        lblLeaveConversationComments.ID = "lblLeaveConversationComments" + rowIndex;
                        lblLeaveConversationComments.Text = drLeaveConversation["Comments"].ToString();
                        tcLeaveConversationComments.Controls.Add(lblLeaveConversationComments);
                        trLeaveConversation.Cells.Add(tcLeaveConversationComments);
                        leaveConversation.Rows.Add(trLeaveConversation);
                        rowIndex += 1;
                    }
                }
            }
            divLeaveConversation.Controls.Add(leaveConversation);
        }
    }
    #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(EmployeeId);
        //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;
            //}
            //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 = (Convert.ToDateTime(strLeaveFrom)).ToString(Session["MDateFormat"].ToString()); ;
            txtToDate.Text = (Convert.ToDateTime(strLeaveTo)).ToString(Session["MDateFormat"].ToString());
        }
    }
    #endregion
    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();
        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;
            }
            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;
                }
            }
        }
        else
        {
            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;
                    }
                }
            }
        }
        //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();
        }
        //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");
        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;
        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();
            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 Type 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();
            //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();
            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("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;
            #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, Convert.ToInt32(ViewState["vsLeaveApplicationId"])));
            }
            else
            {
                doubleLeaveApplicableDays = Convert.ToDouble(objLeaveApplicationEventData.GetMaxDaysPerMonth((Convert.ToInt32(hdnEmployeeId.Value)), Convert.ToInt32(strLeaveTypeId), strLeaveToDate, true, Convert.ToInt32(ViewState["vsLeaveApplicationId"])));
            }
            #endregion
            //doubleLeaveApplicableDays = Convert.ToDouble(objLeaveApplicationEventData.GetMaxDaysPerMonth((Convert.ToInt32(hdnEmployeeId.Value)), Convert.ToInt32(strLeaveTypeId), strLeaveFromDate));
            //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, Convert.ToInt32(ViewState["vsLeaveApplicationId"]));
            }
            //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;
            }
            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 (intLeaveApplicableDays == 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 + "'";
                    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["LeaveDays"] = Convert.ToString(fltLeaveTakenInMonth + 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() == districtDetails.Rows[0]["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(Convert.ToInt32(ViewState["vsLeaveApplicationId"]), 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;
            }
        }
        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 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
        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;
    }
    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;
            }
        }
    }
    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();
    }
    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") + "')");
            DropDownList ddlLeaveCategory = (DropDownList)e.Row.FindControl("ddlLeaveCategory");
            DropDownList ddlSessionsFrom = (DropDownList)e.Row.FindControl("ddlSessionsFrom");
            DropDownList ddlSessionsTo = (DropDownList)e.Row.FindControl("ddlSessionsTo");
            DropDownList ddlLeaveTypes = (DropDownList)e.Row.FindControl("ddlLeaveTypes");
            Label lblNoOfLeaves = (Label)e.Row.FindControl("lblNoOfLeaves");
            string strNoOfLeaves = string.Empty;
            if (!IsPostBack)
            {
                string strLeaveCategoryValue = string.Empty;
                string strLeaveTypeValue = string.Empty;
                string strLeaveTypeId = string.Empty;
                int i = 0;
                i = Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "SlNo")) - 1;
                strLeaveCategoryValue = gdsLeaveApplication_Original.Tables[0].Rows[i]["Type"].ToString();
                strLeaveTypeValue = gdsLeaveApplication_Original.Tables[0].Rows[i]["LeaveType"].ToString();
                strLeaveTypeId = gdsLeaveApplication_Original.Tables[0].Rows[i]["LeaveType_Id"].ToString();
                strNoOfLeaves = gdsLeaveApplication_Original.Tables[0].Rows[i]["NumberOfDays"].ToString();
                if (strLeaveCategoryValue == "Leave")
                {
                    ddlLeaveCategory.SelectedValue = "1";
                }
                if (strLeaveCategoryValue == "LOP")
                {
                    ddlLeaveCategory.SelectedValue = "2";
                }
                if (strLeaveCategoryValue == "Comp Off")
                {
                    ddlLeaveCategory.SelectedValue = "3";
                }
                if (strLeaveCategoryValue == "Leave")
                {
                    DataSet dsLeaveTypesData = new DataSet();
                    dsLeaveTypesData = objLeaveApplicationEventData.GetLeaveTypesOfEmployees_Angler(Convert.ToInt32(hdnEmployeeId.Value));
                    dsLeaveTypesData.Tables[0].TableName = "Details";
                    if (dsLeaveTypesData.Tables["Details"].Rows.Count > 0)
                    {
                        ddlLeaveTypes.DataSource = dsLeaveTypesData.Tables[0];
                        ddlLeaveTypes.DataTextField = "LeaveType";
                        ddlLeaveTypes.DataValueField = "LeaveType_Id";
                        ddlLeaveTypes.DataBind();
                    }
                }
                else if (strLeaveCategoryValue == "LOP")
                {
                    DataSet dsLeaveTypesLOPDays = new DataSet();
                    dsLeaveTypesLOPDays = objLeaveApplicationEventData.GetLOPLeaveTypeDetails(Convert.ToInt32(hdnEmployeeId.Value));
                    dsLeaveTypesLOPDays.Tables[0].TableName = "Details";
                    if (dsLeaveTypesLOPDays.Tables["Details"].Rows.Count > 0)
                    {
                        ddlLeaveTypes.DataSource = dsLeaveTypesLOPDays.Tables[0];
                        ddlLeaveTypes.DataTextField = "LeaveType";
                        ddlLeaveTypes.DataValueField = "LeaveType_Id";
                        ddlLeaveTypes.DataBind();
                    }
                }
                else if (strLeaveCategoryValue == "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);
                    ddlLeaveTypes.DataSource = dtLeaveCompOff;
                    ddlLeaveTypes.DataTextField = "LeaveType";
                    ddlLeaveTypes.DataValueField = "LeaveType_Id";
                    ddlLeaveTypes.DataBind();
                }
                //ddlLeaveTypes.SelectedItem.Text = strLeaveTypeValue;
                ddlLeaveTypes.SelectedValue = strLeaveTypeId;
                //Leave Sessions Assigning
                if (ddlSessionsFrom != null)
                {
                    if (gdsLeaveApplication_Original.Tables[0].Rows[i]["Leave_SessionFrom"].ToString() == "First Half")
                    {
                        ddlSessionsFrom.SelectedValue = "1";
                    }
                    else
                    {
                        ddlSessionsFrom.SelectedValue = "2";
                    }
                }
                if (ddlSessionsTo != null)
                {
                    if (gdsLeaveApplication_Original.Tables[0].Rows[i]["Leave_SessionTo"].ToString() == "First Half")
                    {
                        ddlSessionsTo.SelectedValue = "1";
                    }
                    else
                    {
                        ddlSessionsTo.SelectedValue = "2";
                    }
                }
                if (lblNoOfLeaves != null)
                {
                    lblNoOfLeaves.Text = strNoOfLeaves;
                }
                i = i + 1;
            }
            if (Page.IsPostBack)
            {
                //DropDownList ddlLeaveCategory = (DropDownList)e.Row.FindControl("ddlLeaveCategory");
                //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;
                    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;
                        }
                    }
                }
            }
        }
    }
    public void ddlLeaveCategory_SelectedIndexChanged(object sender, EventArgs e)
    {
        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[4].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();
            }
        }
    }
    #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 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
            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 (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 LoadRemaining Leaves
    public void LoadRemainingLeaves(string FromDate)
    {
        //Added by Manjula.P on 13-May-2014 for datetime format in general as like in product
        FromDate = objcls_Common.DateConvertion(gstrDateFormat, FromDate);
        dsRemainingNoOfLeaves = objLeaveApplicationEventData.GetRemainingNumberOfLeaves(Convert.ToInt32(hdnEmployeeId.Value), -1, Convert.ToInt32(ViewState["vsLeaveApplicationId"]), 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 btnCancel_Click(object sender, EventArgs e)
    {
        Response.Redirect("TA_UI_Transactions_LeaveApplicationAdmin.aspx?LeaveApplication_Id=" + ViewState["vsLeaveApplicationId"].ToString());
    }
    #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(),lblEmployeeIdData.Text);
            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
        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(),lblEmployeeIdData.Text);
                        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(),lblEmployeeIdData.Text);
                        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" && fltLeaveTakenInMonth > 0)
            //{
            //    if ((dDays + fltLeaveTakenInMonth) > 1)
            //    {
            //        //Message("CL Leave exceeds the limit");
            //        return "MaxLeaveTakenExceedsInMonth";
            //    }
            //}
            //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;
        }
        //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);
        lblEmployeeName.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 = objResourceManager.GetString("btn_Save", ci);
        if (ViewState["vwLeaveStatus"] != null)
        {
            if (ViewState["vwLeaveStatus"].ToString() != "Approved")
            {
                //btnAdd.Enabled = false;
            }
        }
        btnCancel.Text = objResourceManager.GetString("btn_Back", ci);
        //btnSearch.Text = objResourceManager.GetString("btn_Search", ci);
        //btnQuota.Text = objResourceManager.GetString("btn_Leave_Quota", ci);
        //btnQuota.Text = "View Quota";
    }
    #endregion
    #region Split Mail ids
    private string[] SplitCCTo(string CCTo)
    {
        string[] strArrEmailAddressForCC;
        strArrEmailAddressForCC = CCTo.Split(';');
        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)
                //{
                if (strPageTitle == "LeaveDetails")
                {
                    sb.Append("<td><font face='Arial' size='2'>" + Row[Col.ColumnName].ToString() + "</font></td>");
                }
                else
                {
                    if (intWidth == 2)
                    {
                        sb.Append("<td width='60%'><font face='Arial' size='2'>" + Row[Col.ColumnName].ToString() + "</font></td>");
                    }
                    else
                    {
                        sb.Append("<td><font face='Arial' size='2'>" + Row[Col.ColumnName].ToString() + "</font></td>");
                    }
                }
                intWidth = intWidth + 1;
                //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);
    }
    private void ControlCreation()
    {
        //New Data table definition
        DataSet dsLeaveConversation = new DataSet();
        DataTable dtReplyResend = new DataTable();
        dtReplyResend.TableName = "dtReplyResend";
        DataColumn dcDate = new DataColumn("Date");
        DataColumn dcCommentsBy = new DataColumn("Comments By");
        DataColumn dcComments = new DataColumn("Comments");
        dtReplyResend.Columns.Add(dcDate);
        dtReplyResend.Columns.Add(dcCommentsBy);
        dtReplyResend.Columns.Add(dcComments);
        DataRow dRowReplyResend;
        // getting leave conversation 
        dsLeaveConversation = objLeaveApplicationEventData.GetLeaveConversation(Convert.ToInt32(Request.QueryString["leaveApplicationId"].ToString()));
        if (dsLeaveConversation.Tables[0].Rows.Count > 0)
        {
            Table leaveConversation = new Table();
            leaveConversation.BorderWidth = 1;
            leaveConversation.CellPadding = 5;
            leaveConversation.CellSpacing = 0;
            leaveConversation.Width = Unit.Pixel(700);
            leaveConversation.CssClass = "td";
            leaveConversation.Attributes.Add("border", "1");
            TableHeaderRow leaveConversationHr = new TableHeaderRow();
            TableHeaderCell leaveConversationHeading3 = new TableHeaderCell();
            leaveConversationHeading3.Text = rm.GetString("TerminalDataType_Date_And_Time", ci); 
            leaveConversationHeading3.Width = 120;
            leaveConversationHeading3.HorizontalAlign = HorizontalAlign.Left;
            leaveConversationHr.Cells.Add(leaveConversationHeading3);
            TableHeaderCell leaveConversationHeading1 = new TableHeaderCell();
            leaveConversationHeading1.Width = 100;
            leaveConversationHeading1.Text = rm.GetString("leaveConversationHeading1", ci);
            leaveConversationHeading1.HorizontalAlign = HorizontalAlign.Left;
            leaveConversationHr.Cells.Add(leaveConversationHeading1);
            TableHeaderCell leaveConversationHeading2 = new TableHeaderCell();
            leaveConversationHeading2.Text = rm.GetString("leaveConversationHeading2", ci);
            leaveConversationHeading2.Width = 500;
            leaveConversationHeading2.HorizontalAlign = HorizontalAlign.Left;
            leaveConversationHr.Cells.Add(leaveConversationHeading2);
            leaveConversation.Rows.Add(leaveConversationHr);
            if (dsLeaveConversation != null && dsLeaveConversation.Tables.Count > 0)
            {
                if (dsLeaveConversation.Tables[0].Rows.Count > 0)
                {
                    //To find By whom the application is resended  
                    int rowIndex = 0;
                    foreach (DataRow drLeaveConversation in dsLeaveConversation.Tables[0].Rows)
                    {
                        dRowReplyResend = dtReplyResend.NewRow();
                        TableRow trLeaveConversation = new TableRow();
                        TableCell tcLeaveConversationRepliedOn = new TableCell();
                        Label lblLeaveConversationRepliedOn = new Label();
                        tcLeaveConversationRepliedOn.BorderWidth = 1;
                        //tcLeaveConversationRepliedOn.Width = 70;
                        lblLeaveConversationRepliedOn.ID = "lblLeaveConversationRepliedOn" + rowIndex;
                        lblLeaveConversationRepliedOn.Text = Convert.ToDateTime(drLeaveConversation["TimeStamp"]).ToString(Session["MDateFormat"].ToString()) + " " + Convert.ToDateTime(drLeaveConversation["TimeStamp"]).ToString(Session["MTimeFormat"].ToString());
                        dRowReplyResend["Date"] = Convert.ToDateTime(drLeaveConversation["TimeStamp"]).ToString(Session["MDateFormat"].ToString()) + " " + Convert.ToDateTime(drLeaveConversation["TimeStamp"]).ToString(Session["MTimeFormat"].ToString());
                        tcLeaveConversationRepliedOn.Controls.Add(lblLeaveConversationRepliedOn);
                        trLeaveConversation.Cells.Add(tcLeaveConversationRepliedOn);
                        TableCell tcLeaveConversationCommentsBy = new TableCell();
                        Label lblLeaveConversationCommentsBy = new Label();
                        tcLeaveConversationCommentsBy.BorderWidth = 1;
                        //tcLeaveConversationCommentsBy.Width = 107;
                        lblLeaveConversationCommentsBy.ID = "lblLeaveConversationCommentsBy" + rowIndex;
                        if (drLeaveConversation["CommentsBy"].ToString() == "0")
                        {
                            lblLeaveConversationCommentsBy.Text = lblEmployeeNameData.Text;
                            dRowReplyResend["Comments By"] = lblEmployeeNameData.Text;
                        }
                        else if (drLeaveConversation["CommentsBy"].ToString() == "1")
                        {
                            lblLeaveConversationCommentsBy.Text = objLeaveApplicationEventData.GetEmployeeName(Convert.ToInt32(drLeaveConversation["Emp_Id"].ToString()));
                            dRowReplyResend["Comments By"] = objLeaveApplicationEventData.GetEmployeeName(Convert.ToInt32(drLeaveConversation["Emp_Id"].ToString()));
                        }
                        else if (drLeaveConversation["CommentsBy"].ToString() == "2")
                        {
                            lblLeaveConversationCommentsBy.Text = objLeaveApplicationEventData.GetEmployeeName(Convert.ToInt32(drLeaveConversation["Emp_Id"].ToString()));
                            dRowReplyResend["Comments By"] = objLeaveApplicationEventData.GetEmployeeName(Convert.ToInt32(drLeaveConversation["Emp_Id"].ToString()));
                        }
                        else if (drLeaveConversation["CommentsBy"].ToString() == "3")
                        {
                            lblLeaveConversationCommentsBy.Text = objLeaveApplicationEventData.GetEmployeeName(Convert.ToInt32(drLeaveConversation["Emp_Id"].ToString()));
                            dRowReplyResend["Comments By"] = objLeaveApplicationEventData.GetEmployeeName(Convert.ToInt32(drLeaveConversation["Emp_Id"].ToString()));
                        }
                        tcLeaveConversationCommentsBy.Controls.Add(lblLeaveConversationCommentsBy);
                        trLeaveConversation.Cells.Add(tcLeaveConversationCommentsBy);
                        TableCell tcLeaveConversationComments = new TableCell();
                        Label lblLeaveConversationComments = new Label();
                        tcLeaveConversationComments.BorderWidth = 1;
                        //tcLeaveConversationComments.ColumnSpan = 2;
                        lblLeaveConversationComments.ID = "lblLeaveConversationComments" + rowIndex;
                        lblLeaveConversationComments.Text = drLeaveConversation["Comments"].ToString();
                        dRowReplyResend["Comments"] = drLeaveConversation["Comments"].ToString();
                        tcLeaveConversationComments.Controls.Add(lblLeaveConversationComments);
                        trLeaveConversation.Cells.Add(tcLeaveConversationComments);
                        leaveConversation.Rows.Add(trLeaveConversation);
                        rowIndex += 1;
                        dtReplyResend.Rows.Add(dRowReplyResend);
                    }
                }
            }
            //divLeaveConversation.Controls.Add(leaveConversation);
        }
        else
        {
            //divLeaveConversation.Visible = false;
        }
        if (dsLeaveConversation.Tables[0].Rows.Count > 0)
        {
            strHtml = buildPage("ReplyResend", dtReplyResend);
        }
    }
    private void ByWhomResend()
    {
        //New Data table definition
        DataSet dsLeaveConversation = new DataSet();
        // getting leave conversation 
        dsLeaveConversation = objLeaveApplicationEventData.GetLeaveConversation(Convert.ToInt32(Request.QueryString["leaveApplicationId"].ToString()));
        if (dsLeaveConversation.Tables[0].Rows.Count > 0)
        {
            if (dsLeaveConversation != null && dsLeaveConversation.Tables.Count > 0)
            {
                if (dsLeaveConversation.Tables[0].Rows.Count > 0)
                {
                    //To find By whom the application is resended
                    ViewState["ByWhomResended"] = dsLeaveConversation.Tables[0].Rows[0]["CommentsBy"].ToString();
                }
            }
        }
        else
        {
            //divLeaveConversation.Visible = false;
        }
    }
    protected void btnAdd_Click(object sender, EventArgs e)
    {
        if (btnAdd.Text != "REPLY")
        {
            ViewState["vsReason"] = txtReason.Text;
        }
        if (hdnEmployeeId.Value == string.Empty)
        {
            Message("Select Employee");
            return;
        }
        //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();
        districtDetails.TableName = "All Details";
        LoadRemainingLeaves(districtDetails.Rows[0]["LeaveFrom"].ToString());
        LoadCompOffDays();
        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;
            }
            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;
                }
            }
        }
        else
        {
            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;
                    }
                }
            }
        }
        //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;
        //CL for 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");
        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 intRowcount = 0;
        int CurrentYearLeaveCount = 0;
        int NextYearLeaveCount = 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();
            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 Type 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();
            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("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;
            #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, Convert.ToInt32(ViewState["vsLeaveApplicationId"])));
            }
            else
            {
                doubleLeaveApplicableDays = Convert.ToDouble(objLeaveApplicationEventData.GetMaxDaysPerMonth((Convert.ToInt32(hdnEmployeeId.Value)), Convert.ToInt32(strLeaveTypeId), strLeaveToDate, true, Convert.ToInt32(ViewState["vsLeaveApplicationId"])));
            }
            #endregion
            // doubleLeaveApplicableDays = Convert.ToDouble(objLeaveApplicationEventData.GetMaxDaysPerMonth((Convert.ToInt32(hdnEmployeeId.Value)), Convert.ToInt32(strLeaveTypeId), strLeaveFromDate));
            //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, Convert.ToInt32(ViewState["vsLeaveApplicationId"]));
            }
            //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;
            }
            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 (intLeaveApplicableDays == 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 + "'";
                    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["LeaveDays"] = Convert.ToString(fltLeaveTakenInMonth + 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(Convert.ToInt32(ViewState["vsLeaveApplicationId"]), 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;
            }
            intIncrement = intIncrement + 1;
        }
        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 monthName = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(DateTime.Parse(DRowLeaves["LeaveMonth"].ToString()).Month);
                    //Message("CL Leave Exceeds the quota in " + monthName);
                    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 YearSettingIDforSave = string.Empty;
        if (CurrentYearLeaveCount == 1)
        {
            YearSettingIDforSave = ViewState["YearSettings_Id"].ToString();
        }
        else if (NextYearLeaveCount == 1)
        {
            YearSettingIDforSave = ViewState["NextYearSettings_Id"].ToString();
        }
        //Enter Leave Details in Master Table
        //int LeaveApplicationId = objLeaveApplicationEventData.InsertLeaveApplicationMaster(Convert.ToInt32(hdnEmployeeId.Value), DateTime.Now.ToShortDateString(), txtReason.Text.Replace("'", "''"), Session["EmpAutoId"].ToString(), ViewState["YearSettings_Id"].ToString(), "Pending", intimationType);
        //Delete the Existing Leave Details in Leave Application Child Table
        //if (btnAdd.Text == "REPLY")
        //{
        //}
        //else
        //{
        //    objLeaveApplicationEventData.UpdateLeaveApplicationMaster(Convert.ToInt32(ViewState["vsLeaveApplicationId"]), txtReason.Text);
        //}
        objLeaveApplicationEventData.Delete_LeaveApplicationChildDetails(Convert.ToInt32(ViewState["vsLeaveApplicationId"]), Convert.ToInt32(Session["EmpAutoId"]));
        DataSet dsLeaveApplication = new DataSet();
        string strInformTo = GetSelectedEmployee();
        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();
            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 Type 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);
            testvalue = 0;
            string strDays = CalculateNumberOfDaysApplied();
            string[] NumberOfDays = strDays.Split(',');
            string strleaveStatus = string.Empty;
            //if (ViewState["vwLeaveStatus"].ToString() == "Resend")
            //{
            //    strleaveStatus = "Reply";
            //}
            strleaveStatus = ViewState["vwLeaveStatus"].ToString();
            string strCCMail = txtApprovalCC.Text;
            //Save the Leave Application
            //if (ViewState["vwLeaveStatus"].ToString() == "Resend")
            //{
            //    dsLeaveApplication = objLeaveApplicationEventData.InsertLeaveApplication(Convert.ToInt32(ViewState["vsLeaveApplicationId"]), Convert.ToInt32(hdnEmployeeId.Value), Convert.ToString(ViewState["vsLeaveApplicationDate"]), Convert.ToInt32(strLeaveTypeId), strLeaveCategory, strLeaveFromDate, strLeaveToDate, strLeaveFromSession, strLeaveToSession, Decimal.Parse(NumberOfDays[0].ToString()), txtReason.Text.Replace("'", "''"), 0, Session["EmpAutoId"].ToString(), YearSettingIDforSave, strleaveStatus, intimationType, strCCMail);
            //}
            //else
            //{
            dsLeaveApplication = objLeaveApplicationEventData.InsertLeaveApplicationByAdmin(Convert.ToInt32(ViewState["vsLeaveApplicationId"]), 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, strleaveStatus, intimationType, strCCMail, strInformTo);
            //}
            //dsLeaveApplication = objLeaveApplicationEventData.InsertLeaveApplication(Convert.ToInt32(ViewState["vsLeaveApplicationId"]), 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(), ViewState["YearSettings_Id"].ToString(), strleaveStatus, intimationType, strCCMail);
            //dsLeaveApplication = objLeaveApplicationEventData.InsertLeaveApplication(Convert.ToInt32(ViewState["vsLeaveApplicationId"]), Convert.ToInt32(hdnEmployeeId.Value), Convert.ToString(ViewState["vsLeaveApplicationDate"]), Convert.ToInt32(strLeaveTypeId), strLeaveCategory, strLeaveFromDate, strLeaveToDate, strLeaveFromSession, strLeaveToSession, Decimal.Parse(NumberOfDays[0].ToString()), txtReason.Text.Replace("'", "''"), 0, Session["EmpAutoId"].ToString(), ViewState["YearSettings_Id"].ToString(), strleaveStatus, intimationType, strCCMail);
        }
        ////Check Leave table before modify and after modify
        //if (ViewState["vwLeaveStatus"].ToString() == "Resend")
        //{
        //    DataSet dsLeaveDataAfterModify = new DataSet();
        //    dsLeaveDataAfterModify = objLeaveApplicationEventData.SelectLeaveApplication(Convert.ToInt32(dsLeaveApplication.Tables[0].Rows[0]["LeaveApplication_Id"].ToString()));
        //    DataTable dtLeaveDataBeforeModify = new DataTable();
        //    dtLeaveDataBeforeModify = (DataTable)ViewState["LeaveDetailsTable"];
        //    DataTable dtLeaveDataAfterMofify = new DataTable();
        //    dtLeaveDataAfterMofify = dsLeaveDataAfterModify.Tables[0];
        //    if (dtLeaveDataBeforeModify.Rows.Count != dtLeaveDataAfterMofify.Rows.Count)
        //    {
        //        blnModifyStatus = true;
        //    }
        //    else
        //    {
        //        //DataView dvLeaveDataBeforeModify = new DataView();
        //        //dvLeaveDataBeforeModify = (DataView)dtLeaveDataBeforeModify.DefaultView;
        //        //dvLeaveDataBeforeModify.Sort = "LeaveFrom";
        //        //dtLeaveDataBeforeModify = dvLeaveDataBeforeModify.ToTable();
        //        //DataView dvLeaveDataAfterMofify = new DataView();
        //        //dvLeaveDataAfterMofify = (DataView)dtLeaveDataAfterMofify.DefaultView;
        //        //dvLeaveDataAfterMofify.Sort = "LeaveFrom";
        //        //dtLeaveDataAfterMofify = dvLeaveDataAfterMofify.ToTable();
        //        int intRowCount = 0;
        //        for (intRowCount = 0; intRowCount < dtLeaveDataBeforeModify.Rows.Count; intRowCount++)
        //        {
        //            if (dtLeaveDataBeforeModify.Rows[intRowCount]["LeaveFrom"].ToString() != dtLeaveDataAfterMofify.Rows[intRowCount]["LeaveFrom"].ToString())
        //            {
        //                blnModifyStatus = true;
        //            }
        //            if (dtLeaveDataBeforeModify.Rows[intRowCount]["LeaveTo"].ToString() != dtLeaveDataAfterMofify.Rows[intRowCount]["LeaveTo"].ToString())
        //            {
        //                blnModifyStatus = true;
        //            }
        //            if (dtLeaveDataBeforeModify.Rows[intRowCount]["Leave_SessionFrom"].ToString() != dtLeaveDataAfterMofify.Rows[intRowCount]["Leave_SessionFrom"].ToString())
        //            {
        //                blnModifyStatus = true;
        //            }
        //            if (dtLeaveDataBeforeModify.Rows[intRowCount]["Leave_SessionTo"].ToString() != dtLeaveDataAfterMofify.Rows[intRowCount]["Leave_SessionTo"].ToString())
        //            {
        //                blnModifyStatus = true;
        //            }
        //        }
        //    }
        //    if (blnModifyStatus == true)
        //    {
        //        ViewState["blnModifyStatus"] = true;
        //    }
        //    else if (blnModifyStatus == false)
        //    {
        //        ViewState["blnModifyStatus"] = false;
        //    }
        //}
        //if (ViewState["vwLeaveStatus"].ToString() == "Resend")
        //{
        //    objLeaveApplicationEventData.UpdateLeaveApplicationConversation(Convert.ToInt32(ViewState["vsLeaveApplicationId"]), "Reply", 0, txtReason.Text.Replace("'", "''"), Convert.ToInt32(Session["EmpAutoId"]));
        //}
        ControlCreation();
        //Mail Sending
        //buil the Leave details for Email
        //DataTable dtLeaveDetails = new DataTable();
        //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("LeaveDetails", 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();
        //                }
        //                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
        //    {
        //        //
        //    }
        //    //SendMail(Convert.ToInt32(ViewState["vsLeaveApplicationId"]), 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_LeaveApplicationAdmin.aspx');";
        strScript = strScript + "</script>";
        //Dispaly alert messsage.
        Page.RegisterStartupScript("AlertPAdd65507866", strScript);
        //Response.Redirect("TA_UI_Transactions_LeaveApplicationadmin.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_LeaveApplicationAdmin.aspx');";
        //    strScript = strScript + "</script>";
        //    //Dispaly alert messsage.
        //    Page.RegisterStartupScript("AlertPAdd99623866", strScript);
        //}
    }
    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;
    }
}
