using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Globalization;
using System.IO;
using System.Resources;
using System.Text.RegularExpressions;
using System.Threading;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Masters_TA_UI_Master_EmployeeAdd : Base.BasePage
{
    #region VariableDeclaration
    ResourceManager rm;
    EmployeeEventData objEmployee = new EmployeeEventData();
    AttandanceCodeEventData objAttCode = new AttandanceCodeEventData();
    cls_Common objcommon = new cls_Common();
    LeaveEventData objLeave = new LeaveEventData();
    cls_Master_Transportation objRoute = new cls_Master_Transportation();
    PayrollConfigurationEventData objPayrollData = new PayrollConfigurationEventData();
    YearSettingsEventData objYearsetting = new YearSettingsEventData();
    Cls_CheckUser objCheckUser = new Cls_CheckUser();
    DataSet ds_Checkuser = new DataSet();
    CultureInfo ci;
    Table tbLeaveType = new Table();
    int payrollConfig = 0, intYearSettingsId, intLevelID, EmployeeID, intLeaveSancAuthority = 0, intReporting = 0, intCountry = 0, intState = 0, intNativeplace = 0, intDesignation = 0;
    byte[] inputBytes, hashBytes, image;
    DataTable dt_EmpPolicy = new DataTable();
    string strGender = string.Empty, strScript = string.Empty, gstrDateFormat = "";
    bool blnNoError = true;
    string finalCustomefile1 = string.Empty;
    string finalCustomefile2 = string.Empty;
    string finalCustomefile3 = string.Empty;
    string finalCustomefile4 = string.Empty;
    string finalCustomefile5 = string.Empty;
    #endregion
    #region PageLoad
    protected override void Page_Load(object sender, EventArgs e)
    {


        //MariaPrasanth TFS Confirmation

        base.Page_Load(sender, e);
        int otApprovalExists = 0;
        int leaveSanctionExists = 0;
        int manualEntryExists = 0;
        GC.Collect();
        string source_Language;
        source_Language = Convert.ToString(Session["Session_ActiveLanguage"]);
        rm = new ResourceManager(source_Language, System.Reflection.Assembly.Load("App_GlobalResources"));
        ci = Thread.CurrentThread.CurrentCulture;
        site.SiteMapProvider = Convert.ToString(Session["SiteMapProvider"]);
        if (Session.IsNewSession)
        {
            string strScriptSession = "";
            strScriptSession = strScriptSession + "<script language='javascript'>";
            strScriptSession = strScriptSession + "alert('" + rm.GetString("Alert_NewSessionCreated", ci) + "');";
            strScriptSession = strScriptSession + "</script>";
            Page.RegisterStartupScript("AlertShiftAllocationEmployeeAdd", strScriptSession);
        }
        try
        {
            EmployeeID = Convert.ToInt32(Session["EmpAutoID"]);
        }
        catch (Exception ex)
        {
            Response.Redirect("../Index.aspx");
            Response.Write(ex.ToString());
        }
        UserRights();
        txt_UserName.Text = txt_EmpID.Text;
        blnNoError = true;
        DataSet ds_Year = objYearsetting.GetActiveYearSettings();
        string strfrom = string.Empty, strto = string.Empty;
        if (ds_Year.Tables.Count > 0)
        {
            if (ds_Year.Tables[0].Rows.Count > 0)
            {
                strfrom = Convert.ToString(ds_Year.Tables[0].Rows[0]["FromDate"]);
                strto = Convert.ToString(ds_Year.Tables[0].Rows[0]["ToDate"]);
                DateTime dtFrom = Convert.ToDateTime(strfrom);
                DateTime dtTo = Convert.ToDateTime(strto);
                hdf_PolVal.Value = dtFrom.ToShortDateString() + "*" + dtTo.ToShortDateString();
                intYearSettingsId = Convert.ToInt32(ds_Year.Tables[0].Rows[0]["YearSettings_Id"]);
            }
            else
            {
                strScript = "";
                strScript = strScript + "<script language='javascript'>";
                strScript = strScript + "alert('" + rm.GetString("Alert_DefineYearSettinginOrganizationSettings", ci) + "');location.replace('../Organization Settings/Organization_YearSetting.aspx')";
                strScript = strScript + "</script>";
                Page.RegisterStartupScript("AlertYearSetting", strScript);
            }
        }
        else
        {
            strScript = "";
            strScript = strScript + "<script language='javascript'>";
            strScript = strScript + "alert('" + rm.GetString("Alert_DefineYearSettinginOrganizationSettings", ci) + "');location.replace('../Organization Settings/Organization_YearSetting.aspx')";
            strScript = strScript + "</script>";
            Page.RegisterStartupScript("AlertYearSetting", strScript);
        }
        if (!Page.IsPostBack)
        {
            LoadStrings(ci);
            string strSetAlert = "";
            strSetAlert = strSetAlert + "<script language='javascript'>";
            strSetAlert = strSetAlert + "ChMaxLength500Fun('" + rm.GetString("Alert_Maximumlengthis500", ci) + "');";
            strSetAlert = strSetAlert + "SetAlertMessages('" + rm.GetString("Alert_Entervalid") + "','" + rm.GetString("Alert_number") + "','" + rm.GetString("Alert_Enterchildrendetails") + "','" + rm.GetString("Alert_Enterspousedetails") + "','" + rm.GetString("Alert_SelectorganizationlevelsEmployeeMaster") + "','" + rm.GetString("Alert_EnterEmployeeFirstName") + "',";
            strSetAlert = strSetAlert + "'" + rm.GetString("Alert_EnterEmployeeLastName") + "','" + rm.GetString("Alert_SelectDOB") + "','" + rm.GetString("Alert_InvalidDOB") + "','" + rm.GetString("Alert_InvalidDOBRecord") + "','" + rm.GetString("Alert_EnterContactAddress") + "','" + rm.GetString("Alert_EnterValidEmailId") + "',";
            strSetAlert = strSetAlert + "'" + rm.GetString("Alert_EnterEmployeeID") + "','" + rm.GetString("Alert_EmployeeIdshouldnotexceed15digits") + "','" + rm.GetString("Alert_SelectDOJs") + "','" + rm.GetString("Alert_InvalidDOJ") + "','" + rm.GetString("Alert_SelectDesignation") + "','" + rm.GetString("Alert_EnterPassword") + "',";
            strSetAlert = strSetAlert + "'" + rm.GetString("Alert_Passwordshouldbeatleast5character") + "','" + rm.GetString("Req_confirmpassword") + "','" + rm.GetString("ALert_PasswordAndConfirmNotMatch") + "','" + rm.GetString("Alert_EnterCardNo") + "','" + rm.GetString("Alert_SelectEffectiveDateforLevel") + "','" + rm.GetString("Alert_EnterEmployeeBasicSalary") + "',";
            strSetAlert = strSetAlert + "'" + rm.GetString("Alert_BasicSalaryshouldbegreaterthan0") + "','" + rm.GetString("Alert_SelectDesignationEffectiveDate") + "','" + rm.GetString("Alert_SelectBasicSalaryEffectiveDate") + "','" + rm.GetString("Alert_SelectEmployeeCategory") + "','" + rm.GetString("Alert_SelectEmployeeType") + "','" + rm.GetString("Alert_SelectEffectiveDateforCategory") + "',";
            strSetAlert = strSetAlert + "'" + rm.GetString("Alert_SelectEffectiveDateforEmployeeType") + "','" + rm.GetString("Alert_OrgLeveleffdateshouldbeequaltoDOJ") + "','" + rm.GetString("Alert_DesigeffdateshouldbeequaltoDOJ") + "','" + rm.GetString("Alert_BasicsaleffdateshouldbeequaltoDOJ") + "','" + rm.GetString("Alert_EmpCateffdateshouldbeequaltoDOJ") + "','" + rm.GetString("Alert_EmpTypeeffdateshouldbeequaltoDOJ") + "',";
            strSetAlert = strSetAlert + "'" + rm.GetString("Alert_DOJshouldbegreaterthanDOB") + "','" + rm.GetString("Alert_ClickCalculateButtontocalProrata") + "','" + rm.GetString("Alert_InvalidPassportExpiryDate") + "','" + rm.GetString("Alert_InvalidVisaExpiryDate") + "','" + rm.GetString("Alert_InvalidAnniversaryDate") + "','" + rm.GetString("Alert_SelectLeavePolicy") + "',";
            strSetAlert = strSetAlert + "'" + rm.GetString("Alert_SaveEmployeeInformation") + "','" + rm.GetString("Alert_ErrorretrievingdatafromAuthority") + "','" + rm.GetString("Alert_EmployeeIDalreadyexists") + "','" + rm.GetString("Alert_SwipeCardNumberAlreadyExists")
                                                    + "','" + rm.GetString("InactiveDateshouldbegreaterthanDOJ") + "','" + rm.GetString("Alert_SelectInActiveDateinOfficalTab") + "');";
            strSetAlert = strSetAlert + "SetAlertCheckDate('" + rm.GetString("Alert_Validmonthdatefourdigit", ci) + "','" + rm.GetString("Alert_Validdatemonthfourdigit", ci) + "','" + rm.GetString("Alert_Invalidyearentry") + "','" + rm.GetString("Alert_Invalidmonthentry") + "','" + rm.GetString("Alert_Invaliddateentry") + "','" + rm.GetString("Alert_IncorrectdateformatDDMONYYYY") + "','" + rm.GetString("Alert_Entertime") + "','" + rm.GetString("Alert_Invalidvalueforhours") + "','" + rm.GetString("Alert_Invalidvalueforminites") + "','" + rm.GetString("Alert_Invalidtimeformat1") + "','" + rm.GetString("Alert_PleaseentervalidDateandTime") + "','" + rm.GetString("Alert_ValiddatemonthMMDDYYHHMM") + "','" + rm.GetString("Alert_ValiddatemonthMMDDYYHHMMTT") + "','" + rm.GetString("Alert_PleaseentervalidDateandTime") + "','" + rm.GetString("Alert_Invalidvalueforhours") + "','" + rm.GetString("Alert_Invalidvalueforminites") + "');";
            strSetAlert = strSetAlert + "MaxLengthh('" + rm.GetString("Alert_MaximumLengthis", ci) + "');";
            strSetAlert = strSetAlert + "SetAlert_AjaxChild('" + rm.GetString("Alert_EntertheChildrenintherangeof1to10", ci) + "','" + rm.GetString("Alert_NoDetailsfoundinChild", ci) + "','" + rm.GetString("Alert_Errorinretrivingdetails", ci) + "','" + rm.GetString("Alert_InvalidChildDOB", ci) + "');";
            strSetAlert = strSetAlert + "SetAlert_AjaxSpouse('" + rm.GetString("Alert_EntertheSpouseintherangeof1to4", ci) + "','" + rm.GetString("Alert_NoDetailsfoundinspouse", ci) + "','" + rm.GetString("Alert_Errorinretrivingdetailsfromspouse", ci) + "','" + rm.GetString("Alert_InvalidSpouseDOB", ci) + "','" + rm.GetString("Alert_EntertheSpouseintherangeof1to10", ci) + "');";
            strSetAlert = strSetAlert + "SetAlert_LeavePolicy('" + rm.GetString("Alert_FillLeavePolicy") + "','" + rm.GetString("Alert_Leavepolicydurationshouldnotbeempty") + "','" + rm.GetString("ALert_SelectDate") + "','" + rm.GetString("Alert_InValidDate") + "','" + rm.GetString("Alert_PolicyStartDateshouldbegreaterthantheDOJ") + "','" + rm.GetString("Alert_PolicyDatealreadyExists") + "','" + rm.GetString("Alert_FillStartDateandEndDate") + "','" + rm.GetString("Alert_NoDetailsfoundinEmpLeave") + "','" + rm.GetString("Alert_Errorinretrivingdetails") + "','" + rm.GetString("Alert_LeavePolicyNoDetailsfoundinEmpLeave") + "','" + rm.GetString("Alert_LeavePolicyErrorinretrivingdetails") + "','" + rm.GetString("Alert_PolicyDateContinutyMissing") + "');";
            strSetAlert = strSetAlert + "Alert_LookUp('" + rm.GetString("Alert_Errorretrievingdatafromlookup", ci) + "','" + rm.GetString("Alert_NoDetailsfoundinLeavePolicy", ci) + "','" + rm.GetString("Alert_ErrorinretrivingdetailsfromLeavepolicy", ci) + "');";
            strSetAlert = strSetAlert + "</script>";
            Page.RegisterStartupScript("SetAlertMessages", strSetAlert);
            txtInActive.Enabled = false;
            Hidden1.Value = Convert.ToString(Session["IDateFormat"]);
            Page.RegisterStartupScript("divshow", "<script>div_show();</script>");
            txt_EmpFirstName.Focus();
            fillLookupddl();
            fillCategoryddl();
            fillTypeddl();
            GetUserGroupDetails();
            GetRouteDetails();
            fillLeavePolicyddl();
            fillConveyanceAllowvance();
            fillTaxPolicy();
            txt_ChildrenNo.Attributes.Add("onkeypress", "javascript:return number_only(event,this);");
            txt_SpouseNo.Attributes.Add("onkeypress", "javascript:return number_only(event,this);");
            hdf_controlID.Value = "0";
            fillDesignation();
            GetPFESIPolicy();
            /*Added New parameter(Max Days/Month)for Angler. For this we are checking whether the payroll configuration page is exists or not*/
            payrollConfig = objcommon.CheckPageExistsInLicense(185);
            /*Below parameter is used for Angler*/
            if (payrollConfig == 0)
            {
                divlblEntrance.Style.Add("display", "none");
                divddlEntrance.Style.Add("display", "none");
            }
            fillContractor();
            fillEntrance();
            BindingEmployeeCategoryandType();
            Session["country"] = null;
            Session["state"] = null;
            Session["city"] = null;
            Session["parentLevelId"] = null;
            Session["Designation"] = null;
            Session["Reporting"] = null;
            Session["LeaveSanc"] = null;
            Session["EmployeeData"] = null;
            objcommon.menu("EmployeeMaster", "18");
            ddlReligion.SelectedValue = "1";
        }
        this.Page.RegisterStartupScript("pageload", "<script>var checkPageLoad=1;</script>");
        if (IsPostBack)
        {
            try
            {
                Page.RegisterStartupScript("divshow", "<script>div_show_Post();</script>");
                if (Session["country"] != null)
                    intCountry = Convert.ToInt32(Session["country"]);
                if (Session["state"] != null)
                    intState = Convert.ToInt32(Session["state"]);
                if (Session["city"] != null)
                    intNativeplace = Convert.ToInt32(Session["city"]);
                if ((Session["parentLevelId"]) != null)
                {
                    intLevelID = Convert.ToInt32(Convert.ToString(Session["parentLevelId"]).Trim());
                    if (Session["Designation"] != null)
                    {
                        intDesignation = Convert.ToInt32(Convert.ToString(Session["Designation"]).Trim());
                        ddl_Designation.SelectedValue = Convert.ToString(Session["Designation"]);
                        fillReportingddl(intDesignation);
                        if (Convert.ToString(Session["Reporting"]) != null && Convert.ToString(Session["Reporting"]) != "-Select-" && Convert.ToString(Session["Reporting"]) != string.Empty)
                        {
                            intReporting = Convert.ToInt32(Convert.ToString(Session["Reporting"]).Trim());
                            ddl_ReportingTo.SelectedValue = Convert.ToString(intReporting);
                        }
                        if (Convert.ToString(Session["LeaveSanc"]) != null && Convert.ToString(Session["LeaveSanc"]) != "-Select-" && Convert.ToString(Session["LeaveSanc"]) != string.Empty)
                        {
                            intLeaveSancAuthority = Convert.ToInt32(Convert.ToString(Session["LeaveSanc"]).Trim());
                            ddl_LeaveSancAuthority.SelectedValue = Convert.ToString(intLeaveSancAuthority);
                        }
                    }
                }
                if (Session["Emp_Policy"] != null)
                {
                    dt_EmpPolicy = (DataTable)Session["Emp_Policy"];
                }
            }
            catch (Exception ex)
            {
                Message(ex.ToString());
            }
        }
        otApprovalExists = objcommon.CheckPageExistsInLicense(97);
        leaveSanctionExists = objcommon.CheckPageExistsInLicense(248);
        manualEntryExists = objcommon.CheckPageExistsInLicense(98);
        if (otApprovalExists == 0 && leaveSanctionExists == 0 && manualEntryExists == 0)
        {
            trStatus.Style.Add("display", "none");
        }
        if (Session["Demo"] != null && Convert.ToString(Session["Demo"]) == "Express")
        {
            chk_CompOffAndOT.Enabled = false;
            chk_CompOffAndOT.Checked = false;
            chk_OTEligible.Enabled = false;
            chk_OTEligible.Checked = false;
            chk_CompOffEligible.Enabled = false;
            chk_CompOffEligible.Checked = false;
        }
        if (Session["Demo"] != null && Convert.ToString(Session["Demo"]) != "Express" && Convert.ToString(Session["Demo"]) != "Standard")
        {
            LoadLeaveType();
        }
        divPenalty.Style.Add("display", "none");

        int packageId = Convert.ToInt32(Session["packageID"]);

        if (Convert.ToString(Session["packageID"]) != "")
        {
            if (Convert.ToString(Session["packageID"]) == "157")// Sohit admin
                divPenalty.Style.Add("display", "");
            //MTTS and Samsung Client
            else if (Convert.ToInt32(Session["packageID"]) == 169 || Convert.ToInt32(Session["packageID"]) == 168)  //vaigai and future clients
                divMobileSMS.Style.Add("display", "none");
            else if (Convert.ToInt32(Session["packageID"]) < 159 && Convert.ToInt32(Session["packageID"]) != 169 && Convert.ToInt32(Session["packageID"]) == 168)  //vaigai and future clients
                divMobileSMS.Style.Add("display", "none");
        }
        HdnEmployeeMaster.Value = "EmployeeMaster";
    }
    #endregion
    #region UserDefinedFunctions
    /// <summary>
    /// Fill Entrance Details
    /// </summary>
    private void fillEntrance()
    {
        DataSet dsEntrance = new DataSet();
        dsEntrance = objEmployee.LoadInEntrance();
        if (dsEntrance != null && dsEntrance.Tables.Count > 0 && dsEntrance.Tables[0].Rows.Count > 0)
        {
            ddl_EntranceName.DataSource = dsEntrance;
            ddl_EntranceName.DataTextField = "Entrance_Name";
            ddl_EntranceName.DataValueField = "Terminal_ReaderID";
            ddl_EntranceName.DataBind();
        }
        ddl_EntranceName.Items.Insert(0, new ListItem("-Select-", "0"));
        dsEntrance.Dispose();
    }
    /// <summary>
    /// getting maxdays for current quato with its leavetypeid by MAnjula.P on 22-Jul-2013
    /// </summary>
    /// <param name="LeaveTypeId"></param>
    /// <returns></returns>
    public decimal GetMaxDays(int LeaveTypeId)
    {
        decimal CurrentQuota = -1;
        decimal MaxValue = -1;
        if (LeaveTypeId > 0)
        {
            if (ViewState["LeaveTypes"] != null)
            {
                if (tbLeaveType.Rows.Count > 0)
                {
                    DataTable dt = new DataTable();
                    dt = (DataTable)ViewState["LeaveTypes"];
                    TextBox txtPreviousYearBalance = new TextBox();
                    TextBox txtNoOffLeaveAvailed = new TextBox();
                    if (dt.Rows.Count > 0)
                    {
                        int RowCount = dt.Rows.Count;
                        decimal intPrevious = 0;
                        decimal intNoOfLeave = 0;
                        int i = 1;
                        foreach (DataRow dr in dt.Select("Emp_LeaveType_Id='" + LeaveTypeId + "'"))
                        {
                            intPrevious = 0;
                            intNoOfLeave = 0;
                            txtPreviousYearBalance = (TextBox)tbLeaveType.Rows[i].FindControl("txtPreviousYearBalance" + Convert.ToInt32(dr["Emp_LeaveType_Id"]));
                            txtNoOffLeaveAvailed = (TextBox)tbLeaveType.Rows[i].FindControl("txtNoOffLeaveAvailed" + Convert.ToInt32(dr["Emp_LeaveType_Id"]));
                            if (txtPreviousYearBalance != null)
                                if (txtPreviousYearBalance.Text.Trim() != string.Empty)
                                {
                                    intPrevious = Convert.ToDecimal(txtPreviousYearBalance.Text.Trim());
                                    Session["PreviousYearCount"] = "1";
                                }
                            if (txtNoOffLeaveAvailed != null)
                                if (txtNoOffLeaveAvailed.Text.Trim() != string.Empty)
                                    intNoOfLeave = Convert.ToDecimal(txtNoOffLeaveAvailed.Text.Trim());
                            MaxValue = Convert.ToDecimal(intPrevious - intNoOfLeave);
                            if (Session["Emp_Policy"] != null)
                            {
                                DataTable dtTemp = (DataTable)Session["Emp_Policy"];
                                foreach (DataRow dtRow in dtTemp.Select("LeaveTypeId=" + Convert.ToInt32(dr["Emp_LeaveType_Id"])))
                                {
                                    if (Convert.ToString(dtRow["MaxDays"]) != string.Empty)
                                        MaxValue = MaxValue + Convert.ToDecimal(dtRow["MaxDays"]);
                                }
                            }
                        }
                    }
                }
            }
        }
        CurrentQuota = MaxValue;
        return CurrentQuota;
    }
    /// <summary>
    /// adding by Manjula.P on 22-Jul-2013 for getting whole leave type details.
    /// </summary>
    /// <returns></returns>
    
    #region ContractorDetails
    private void fillContractor()
    {
        DataSet dsContractor = new DataSet();
        dsContractor = objEmployee.LoadInContractor();
        if (dsContractor != null && dsContractor.Tables.Count > 0 && dsContractor.Tables[0].Rows.Count > 0)
        {
            ddlContractor.DataSource = dsContractor;
            ddlContractor.DataTextField = "ContractorName";
            ddlContractor.DataValueField = "ID";
            ddlContractor.DataBind();
        }
        ddlContractor.Items.Insert(0, new ListItem("-Select-", "0"));
        dsContractor.Dispose();
    }
    #endregion
    public DataTable GetMaxDaysWithoutLeavePolicy()
    {
        decimal MaxValue = 0;
        DataTable dtWithouLeavePolicy = new DataTable();
        dtWithouLeavePolicy.Columns.Add("LeaveTypeId");
        dtWithouLeavePolicy.Columns.Add("MaxVal");
        if (ViewState["LeaveTypes"] != null)
        {
            if (tbLeaveType.Rows.Count > 0)
            {
                DataTable dt = new DataTable();
                dt = (DataTable)ViewState["LeaveTypes"];
                TextBox txtPreviousYearBalance = new TextBox();
                TextBox txtNoOffLeaveAvailed = new TextBox();
                if (dt.Rows.Count > 0)
                {
                    int RowCount = dt.Rows.Count;
                    decimal intPrevious = 0;
                    decimal intNoOfLeave = 0;
                    int i = 1;
                    foreach (DataRow dr in dt.Rows)
                    {
                        intPrevious = 0;
                        intNoOfLeave = 0;
                        txtPreviousYearBalance = (TextBox)tbLeaveType.Rows[i].FindControl("txtPreviousYearBalance" + Convert.ToInt32(dr["Emp_LeaveType_Id"]));
                        txtNoOffLeaveAvailed = (TextBox)tbLeaveType.Rows[i].FindControl("txtNoOffLeaveAvailed" + Convert.ToInt32(dr["Emp_LeaveType_Id"]));
                        if (txtPreviousYearBalance != null)
                            if (txtPreviousYearBalance.Text.Trim() != string.Empty)
                                intPrevious = Convert.ToDecimal(txtPreviousYearBalance.Text.Trim());
                        if (txtNoOffLeaveAvailed != null)
                            if (txtNoOffLeaveAvailed.Text.Trim() != string.Empty)
                                intNoOfLeave = Convert.ToDecimal(txtNoOffLeaveAvailed.Text.Trim());
                        MaxValue = Convert.ToDecimal(intPrevious - intNoOfLeave);
                        DataRow drWOPolicy = dtWithouLeavePolicy.NewRow();
                        drWOPolicy["LeaveTypeId"] = Convert.ToInt32(dr["Emp_LeaveType_Id"]);
                        drWOPolicy["MaxVal"] = MaxValue;
                        dtWithouLeavePolicy.Rows.Add(drWOPolicy);
                    }
                }
            }
        }
        return dtWithouLeavePolicy;
    }
    /// <summary>
    /// ValidLeaveType if the leave types are entered. by MAnjula.P on 22-Jul-2013
    /// </summary>
    /// <returns></returns>
    public bool ValidLeaveTypes()
    {
        Session["PreviousYearCount"] = "0";
        bool returnValue = true;
        if (ViewState["LeaveTypes"] != null)
        {
            if (tbLeaveType.Rows.Count > 0)
            {
                DataTable dt = new DataTable();
                dt = (DataTable)ViewState["LeaveTypes"];
                TextBox txtPreviousYearBalance = new TextBox();
                TextBox txtNoOffLeaveAvailed = new TextBox();
                if (dt.Rows.Count > 0)
                {
                    int RowCount = dt.Rows.Count;
                    decimal intPrevious = 0;
                    decimal intNoOfLeave = 0;
                    int i = 1;
                    foreach (DataRow dr in dt.Rows)
                    {
                        intPrevious = 0;
                        intNoOfLeave = 0;
                        txtPreviousYearBalance = (TextBox)tbLeaveType.Rows[i].FindControl("txtPreviousYearBalance" + Convert.ToInt32(dr["Emp_LeaveType_Id"]));
                        txtNoOffLeaveAvailed = (TextBox)tbLeaveType.Rows[i].FindControl("txtNoOffLeaveAvailed" + Convert.ToInt32(dr["Emp_LeaveType_Id"]));
                        if (txtPreviousYearBalance != null)
                            if (txtPreviousYearBalance.Text.Trim() != string.Empty)
                            {
                                if (Convert.ToDecimal(txtPreviousYearBalance.Text) > 0)
                                {
                                    intPrevious = Convert.ToDecimal(txtPreviousYearBalance.Text.Trim());
                                    Session["PreviousYearCount"] = "1";
                                }
                            }
                        if (txtNoOffLeaveAvailed != null)
                            if (txtNoOffLeaveAvailed.Text.Trim() != string.Empty)
                                intNoOfLeave = Convert.ToDecimal(txtNoOffLeaveAvailed.Text.Trim());
                        decimal MaxValue = Convert.ToDecimal(intPrevious);
                        string LeavePolicy_data = hdf_Policy.Value;
                        if (Session["Emp_Policy"] != null && LeavePolicy_data != "" && LeavePolicy_data != "undefined")
                        {
                            DataTable dtTemp = (DataTable)Session["Emp_Policy"];
                            foreach (DataRow dtRow in dtTemp.Select("LeaveTypeId=" + Convert.ToInt32(dr["Emp_LeaveType_Id"])))
                            {
                                if (Convert.ToString(dtRow["MaxDays"]) != string.Empty)
                                    MaxValue = MaxValue + Convert.ToDecimal(dtRow["MaxDays"]);
                            }
                        }
                        if (intNoOfLeave > MaxValue)
                            return false;
                        else
                            returnValue = true;
                    }
                }
            }
        }
        return returnValue;
    }
    /// <summary>
    /// for adding fun for checking date of joining 
    /// </summary>
    /// <param name="strDoj"></param>
    /// <returns></returns>
    public string ValidateDOJPreviousYearBalance(string strDoj)
    {
        string Message = "";
        string Alert = rm.GetString("Employee_Master_Alert_DOJGreaterPrevious", ci);
        if (strDoj != "")
        {
            DateTime dateDOJ = Convert.ToDateTime(strDoj);
            if (Session["YearSettingFromDate"] != null && Session["YearSettingToDate"] != null)
            {
                DateTime dateFromDate = DateTime.Parse(Convert.ToString(Session["YearSettingFromDate"]));
                DateTime dateToDate = DateTime.Parse(Convert.ToString(Session["YearSettingToDate"]));
                DateTime dateApproximatePreviouYear = dateToDate.AddYears(-1);
                if (dateDOJ > dateApproximatePreviouYear)
                    Message = Alert;
                else
                    Message = "";
            }
        }
        return Message;
    }
    #region "Insert Employeee Details"
    private bool CheckNoOfEmployeeForLicense()
    {
        DemoVersion objDemoVersion = new DemoVersion();
        bool allowEmployeeAdd = true;
        string[] fileArr = Directory.GetFiles(Server.MapPath("../LicenseFile"), "*.lic");
        int arrCount = fileArr.Length;
        if (arrCount > 0)
        {
            string licenseFileName = Convert.ToString(fileArr[arrCount - 1]);
            FileStream licenseFileStream = new FileStream(licenseFileName, FileMode.Open);
            StreamReader licenseFileStreamReader = new StreamReader(licenseFileStream);
            string encryptedLicFileInfo = licenseFileStreamReader.ReadToEnd();
            licenseFileStreamReader.Close();
            licenseFileStream.Close();
            string decryptedLicFileInfo = string.Empty;
            try
            {
                decryptedLicFileInfo = Encryption.Decrypt(encryptedLicFileInfo, "");
            }
            catch
            {
                string strScript = "<script language='javascript' type='text/javascript'>";
                strScript += "alert('" + rm.GetString("Alert_Licenseinformationarenotcorrect", ci) + "');";
                strScript += "location.href='../Index.aspx';";
                strScript += " </script>";
                ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", strScript, false);
                return false;
            }
            string[] decryptedLicFileInfoArr = decryptedLicFileInfo.Split('#');
            string basicLicInfo = Convert.ToString(decryptedLicFileInfoArr[0]);
            string[] basicLicInfoArr = basicLicInfo.Split(',');
            int noOfEmployeeLicFile = Convert.ToInt32(basicLicInfoArr[4]);
            allowEmployeeAdd = objDemoVersion.DVCheckEmployeeCreation("License", noOfEmployeeLicFile);
            if (allowEmployeeAdd)
            {
                return true;
            }
            else
            {
                string strScript = "<script language='javascript' type='text/javascript'>";
                strScript += "alert('" + rm.GetString("Alert_LicensenotallowtoAddmoreEmployee", ci) + " ');";
                strScript += " </script>";
                ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", strScript, false);
                return false;
            }
        }
        return true;
    }
    #endregion
    #region Bioadminupdate
    private void updateBioAdmin(string strSwipecardNo)
    {
        DataTable dtTerminalDataType = new DataTable();
        DataSet dsTerminalDataType = new DataSet();
        string strBioAdminConnection = string.Empty;
        string strTableName = string.Empty;
        string strSwipeCardFieldName = string.Empty;
        string strRDBMS_MDBFlag = string.Empty;
        TerminalDatatypeEventData objTerminalDatatypeEventData = new TerminalDatatypeEventData();
        dsTerminalDataType = objTerminalDatatypeEventData.Select_TerminalDatatype("AllActive");
        if (dsTerminalDataType.Tables.Count > 0)
        {
            dtTerminalDataType = dsTerminalDataType.Tables[0].Copy();
        }
        if (dtTerminalDataType.Rows.Count > 0)
        {
            foreach (DataRow drTerminalDataType in dtTerminalDataType.Rows)
            {
                if (drTerminalDataType["FileType"] != DBNull.Value)
                {
                    strBioAdminConnection = Encryption.Decrypt(Convert.ToString(drTerminalDataType["ConnectionString"]), "");
                    strTableName = Convert.ToString(drTerminalDataType["TableName"]);
                    strRDBMS_MDBFlag = Convert.ToString(drTerminalDataType["RDBMS_MDB_Flag"]);
                    if (Convert.ToString(drTerminalDataType["FileType"]) == "RDBMS")
                    {
                        strSwipeCardFieldName = Convert.ToString(drTerminalDataType["RDBMS_CardNo"]);
                        objEmployee.BioAdminUpdate(strBioAdminConnection, strTableName, strRDBMS_MDBFlag, strSwipeCardFieldName, strSwipecardNo);
                    }
                    else if (Convert.ToString(drTerminalDataType["FileType"]) == "MDB")
                    {
                        strSwipeCardFieldName = Convert.ToString(drTerminalDataType["MDB_CardNo"]);
                        string[] connectionStringArr = strBioAdminConnection.Split(';');
                        string checkStringSource = "Data Source";
                        checkStringSource = checkStringSource.ToUpper();
                        string connection = string.Empty, strFileName = string.Empty;
                        for (int i = 0; i < connectionStringArr.Length - 1; i++)
                        {
                            string[] initialCatalogPart = connectionStringArr[i].Split('=');
                            string checkStringInput = Convert.ToString(initialCatalogPart[0]);
                            checkStringInput = checkStringInput.ToUpper();
                            if (checkStringSource == checkStringInput)
                            {
                                strFileName = Convert.ToString(initialCatalogPart[1]);
                            }
                        }
                        if (File.Exists(strFileName) == true)
                        {
                            objEmployee.BioAdminUpdate(strBioAdminConnection, strTableName, strRDBMS_MDBFlag, strSwipeCardFieldName, strSwipecardNo);
                        }
                        strFileName = string.Empty;
                    }
                }
            }
        }
    }
    protected void btn_Cancel_Click(object sender, EventArgs e)
    {
        Session["country"] = null;
        Session["state"] = null;
        Session["city"] = null;
        Session["parentLevelId"] = null;
        Session["Designation"] = null;
        Session["Reporting"] = null;
        Session["LeaveSanc"] = null;
        Session["EmployeeData"] = null;
        if (dt_EmpPolicy != null)
        {
            dt_EmpPolicy.Dispose();
        }
        Response.Redirect("TA_UI_Master_Employee.aspx");
    }
    #endregion
    #region "Fills UserGroup dropdown"
    private void GetUserGroupDetails()
    {
        DataSet ds_Usergroup = new DataSet();
        if (ViewState["vw_ds_Usergroup"] != null)
        {
            ds_Usergroup = (DataSet)ViewState["vw_ds_Usergroup"];
        }
        else
        {
            ds_Usergroup = objEmployee.select_Usergroupdetails();
            ViewState["vw_ds_Usergroup"] = ds_Usergroup;
        }
        if (ds_Usergroup != null)
        {
            if (ds_Usergroup.Tables[0].Rows.Count > 0)
            {
                ddl_UserGroup.DataSource = ds_Usergroup;
                ddl_UserGroup.DataTextField = "groupName";
                ddl_UserGroup.DataValueField = "groupId";
                ddl_UserGroup.DataBind();
            }
            ds_Usergroup.Dispose();
        }
        foreach (ListItem item in ddl_UserGroup.Items)
        {
            item.Attributes.Add("title", item.Text);
        }
    }
    #endregion

    #region
    private void GetPFESIPolicy()
    {
        DataSet ds_PFESI = new DataSet();
        if (ViewState["PF_ESI_Policy"] != null)
        {
            ds_PFESI = (DataSet)ViewState["PF_ESI_Policy"];
        }
        else
        {
            Hashtable h_PFESI = new Hashtable();
            h_PFESI.Add("@tag", "S");
            h_PFESI.Add("@LevelID", Convert.ToInt32(Session["parentLevelId"]));
            ds_PFESI = objPayrollData.InsertPFESIPolicyDetails(h_PFESI);
            ViewState["PF_ESI_Policy"] = ds_PFESI;
        }

        if (ds_PFESI != null)
        {
            if (ds_PFESI.Tables[0].Rows.Count > 0)
            {
                ddl_PFESI.DataSource = ds_PFESI;
                ddl_PFESI.DataTextField = "PFESI_PolicyName";
                ddl_PFESI.DataValueField = "PFESI_Id";
                ddl_PFESI.DataBind();
            }
            ds_PFESI.Dispose();
        }
        foreach (ListItem item in ddl_PFESI.Items)
        {
            item.Attributes.Add("title", item.Text);
        }
        //BindTooltip(ddl_PFESI);
    }
    #endregion
    #region "Fills Route dropdown"
    private void GetRouteDetails()
    {
        DataSet ds_Route = new DataSet();
        string usergroupname = string.Empty;
        ds_Route = objRoute.SelectTransportationRouteDetails(usergroupname);
        if (ds_Route != null)
        {
            if (ds_Route.Tables[0].Rows.Count > 0)
            {
                ddl_BusRouteNo.DataSource = ds_Route;
                ddl_BusRouteNo.DataTextField = "Route_Name";
                ddl_BusRouteNo.DataValueField = "Id";
                ddl_BusRouteNo.DataBind();
            }
            ds_Route.Dispose();
        }
        BindTooltip(ddl_BusRouteNo);
    }
    private void BindTooltip(DropDownList ddl)
    {
        foreach (ListItem item in ddl_BusRouteNo.Items)
        {
            item.Attributes.Add("title", item.Text);
        }
    }
    #endregion
    #region "function fills Leave policy ddl"
    private void fillLeavePolicyddl()
    {
        DataSet ds_leavepolicy = new DataSet();
        ds_leavepolicy = objLeave.SelectAllLeavePolicy(string.Empty);
        if (ds_leavepolicy != null)
        {
            if (ds_leavepolicy.Tables[0].Rows.Count > 0)
            {
                ddl_LeavePolicy.DataSource = ds_leavepolicy;
                ddl_LeavePolicy.DataTextField = "PolicyName";
                ddl_LeavePolicy.DataValueField = "Policy_Id";
                ddl_LeavePolicy.DataBind();
            }
            ds_leavepolicy.Dispose();
        }
        BindTooltip(ddl_LeavePolicy);
    }
    #endregion
    #region
    private void fillTaxPolicy()
    {
        DataSet ds_taxPolicy = new DataSet();
        Hashtable htaxpolicy = new Hashtable();
        htaxpolicy.Add("@tag", "SL");
        ds_taxPolicy = objPayrollData.InsertTaxPolicy(htaxpolicy);
        if (ds_taxPolicy != null)
        {
            if (ds_taxPolicy.Tables[0].Rows.Count > 0)
            {
                ddl_TaxPolicy.DataSource = ds_taxPolicy;
                ddl_TaxPolicy.DataValueField = "TaxPolicy_Id";
                ddl_TaxPolicy.DataTextField = "TaxPolicyName";
                ddl_TaxPolicy.DataBind();
            }
            ds_taxPolicy.Dispose();
        }
        BindTooltip(ddl_TaxPolicy);

    }
    #endregion

    #region "Fills Country dropdowns"
    private void fillLookupddl()
    {
        DataSet ds_country = new DataSet();
        ds_country = objEmployee.SelectCountries();
        if (ds_country != null)
        {
            if (ds_country.Tables[0].Rows.Count > 0)
            {
                ddl_Country.DataSource = ds_country;
                ddl_Country.DataTextField = "Title";
                ddl_Country.DataValueField = "ID";
                ddl_Country.DataBind();
            }
            ds_country.Dispose();
        }
        BindTooltip(ddl_Country);
    }
    #endregion
    # region "Fills Category dropdowns"
    private void fillCategoryddl()
    {
        DataSet ds_Category = new DataSet();
        string UserGroupName = "";
        ds_Category = objEmployee.SelectCategoryDetailsEmployee(UserGroupName);
        if (ds_Category != null)
        {
            if (ds_Category.Tables[0].Rows.Count > 0)
            {
                ddlEmpCatagory.DataSource = ds_Category;
                ddlEmpCatagory.DataTextField = "CategoryName";
                ddlEmpCatagory.DataValueField = "CategoryId";
                ddlEmpCatagory.DataBind();
            }
            ds_Category.Dispose();
        }
        ListItem lstItem = new ListItem();
        lstItem.Value = "0";
        lstItem.Text = "Select";
        ddlEmpCatagory.Items.Insert(0, lstItem);
        BindTooltip(ddlEmpCatagory);
    }
    #endregion
    # region "Fills Type dropdowns"
    private void fillTypeddl()
    {
        DataSet ds_Type = new DataSet();
        string UserGroupName = "";
        ds_Type = objEmployee.SelectTypeDetailsEmployee(UserGroupName);
        if (ds_Type != null)
        {
            if (ds_Type.Tables[0].Rows.Count > 0)
            {
                ddlEmpType.DataSource = ds_Type;
                ddlEmpType.DataTextField = "TypeName";
                ddlEmpType.DataValueField = "TypeId";
                ddlEmpType.DataBind();
            }
            ds_Type.Dispose();
        }
        ListItem lstItem = new ListItem();
        lstItem.Value = "0";
        lstItem.Text = "Select";
        ddlEmpType.Items.Insert(0, lstItem);
        BindTooltip(ddlEmpType);
    }
    #endregion
    #region  "Function insert spouse data"
    private void SpouseData(int MaxID)
    {
        string spouse_data = hid_Spouse.Value;
        if (spouse_data != "")
        {
            char[] comma = { ',' };
            char[] star = { '*' };
            string[] spousename = { };
            string[] spouse = spouse_data.Split(star);
            for (int i = 0; i < spouse.Length; i++)
            {
                string data = spouse[i];
                spousename = data.Split(comma);
                objEmployee.InsertSpouseDetails(MaxID, spousename[0], objcommon.DateConvertion(gstrDateFormat, spousename[1]), EmployeeID);
            }
        }
    }
    #endregion
    #region  "Function insert Children data"
    private void ChildrenData(int MaxID)
    {
        string children_data = hid_Children.Value;
        if (children_data != "")
        {
            char[] comma = { ',' };
            char[] star = { '*' };
            string[] childrenname = { };
            string[] children = children_data.Split(star);
            for (int i = 0; i < children.Length; i++)
            {
                string data = children[i];
                childrenname = data.Split(comma);
                objEmployee.InsertChildrenDetails(MaxID, childrenname[0], objcommon.DateConvertion(gstrDateFormat, childrenname[1]), EmployeeID);
            }
        }
    }
    #endregion
    #region
    private void fillConveyanceAllowvance()
    {
        DataSet ds_CA = new DataSet();
        if (ViewState["CA_Policy"] != null)
        {
            ds_CA = (DataSet)ViewState["CA_Policy"];
        }
        else
        {
            Hashtable h_CA = new Hashtable();
            h_CA.Add("@tag", "S");
            h_CA.Add("@LevelID", Convert.ToInt32(Session["parentLevelId"]));
            ds_CA = objPayrollData.InsertandupdateConveyancePolicyDetails(h_CA);
            ViewState["CA_Policy"] = ds_CA;
        }

        if (ds_CA != null)
        {
            if (ds_CA.Tables[0].Rows.Count > 0)
            {
                ddl_CA.DataSource = ds_CA;
                ddl_CA.DataTextField = "ConPolicyName";
                ddl_CA.DataValueField = "C_Id";
                ddl_CA.DataBind();
            }
            ds_CA.Dispose();
        }
        foreach (ListItem item in ddl_PFESI.Items)
        {
            item.Attributes.Add("title", item.Text);
        }
    }
    #endregion
    #region  "Function insert Leave policy data"
    private void LeavePolicyData(int MaxID)
    {
        string LeavePolicy_data = hdf_Policy.Value;
        if (LeavePolicy_data != "" && LeavePolicy_data != "undefined")
        {
            char[] comma = { ',' };
            char[] star = { '*' };
            string[] policy = { };
            string[] policydetails = LeavePolicy_data.Split(star);
            for (int i = 0; i < policydetails.Length; i++)
            {
                string data = policydetails[i];
                policy = data.Split(comma);
                objEmployee.InsertLeavePolicy(MaxID, Convert.ToInt32(policy[2]), objcommon.DateConvertion(gstrDateFormat, policy[0]), objcommon.DateConvertion(gstrDateFormat, policy[1]), EmployeeID);
                int MaxLPID = objEmployee.select_MaxEmpLeavepolicyID();
                if (dt_EmpPolicy.Rows.Count > 0)
                {
                    DataRow[] dr = dt_EmpPolicy.Select("PolicyId=" + Convert.ToInt32(policy[2]));
                    for (int j = 0; j < dr.Length; j++)
                    {
                        int PolicyID = Convert.ToInt32(dr[j]["PolicyId"]);
                        int LeavetypeID = Convert.ToInt32(dr[j]["LeaveTypeId"]);
                        decimal Maxdays = Convert.ToDecimal(dr[j]["MaxDays"]);
                        decimal Maxdays_month = Convert.ToDecimal(dr[j]["MaxDays_month"]);
                        int empID = Convert.ToInt32(dr[j]["EmployeeID"]);
                        objEmployee.InsertEmpLeavePolicyDetails(MaxID, MaxLPID, PolicyID, LeavetypeID, Maxdays, empID, Maxdays_month);
                        if (Session["Demo"] != null && Convert.ToString(Session["Demo"]) != "Express")
                        {
                            if (Convert.ToDecimal(GetMaxDays(LeavetypeID)) > -1)
                                objEmployee.InsertYearclosure(intLevelID, MaxID, LeavetypeID, Convert.ToDecimal(GetMaxDays(LeavetypeID)), empID);
                            else
                                objEmployee.InsertYearclosure(intLevelID, MaxID, LeavetypeID, Maxdays, empID);
                        }
                    }
                }
                else
                {
                    if (Session["Demo"] != null && Convert.ToString(Session["Demo"]) != "Express")
                    {
                        DataTable dtTemp = GetMaxDaysWithoutLeavePolicy();
                        if (dtTemp.Rows.Count > 0)
                        {
                            for (int j = 0; j < dtTemp.Rows.Count; j++)
                            {
                                int LeavetypeID = Convert.ToInt32(dtTemp.Rows[j]["LeaveTypeId"]);
                                decimal Maxdays = Convert.ToDecimal(dtTemp.Rows[j]["MaxVal"]);
                                objEmployee.InsertYearclosure(intLevelID, MaxID, LeavetypeID, Maxdays, MaxID);
                            }
                        }
                    }
                }
            }
        }
        else
        {
            if (Session["Demo"] != null && Convert.ToString(Session["Demo"]) != "Express")
            {
                DataTable dtTemp = GetMaxDaysWithoutLeavePolicy();
                if (dtTemp.Rows.Count > 0)
                {
                    for (int j = 0; j < dtTemp.Rows.Count; j++)
                    {
                        int LeavetypeID = Convert.ToInt32(dtTemp.Rows[j]["LeaveTypeId"]);
                        decimal Maxdays = Convert.ToDecimal(dtTemp.Rows[j]["MaxVal"]);
                        objEmployee.InsertYearclosure(intLevelID, MaxID, LeavetypeID, Maxdays, MaxID);
                    }
                }
            }
        }
    }
    #endregion   
    private void fillDesignation()
    {
        DataSet ds_designation = new DataSet();
        ds_designation = objEmployee.select_CommonDesignation();
        if (ds_designation != null)
        {
            if (ds_designation.Tables[0].Rows.Count > 0)
            {
                ddl_Designation.DataSource = ds_designation;
                ddl_Designation.DataTextField = "TitleName";
                ddl_Designation.DataValueField = "TitleId";
                ddl_Designation.DataBind();
            }
            ds_designation.Dispose();
        }
        foreach (ListItem item in ddl_Designation.Items)
        {
            item.Attributes.Add("title", item.Text);
        }
        BindTooltip(ddl_Designation);
    }
    private void fillReportingddl(int designationID)
    {
        DataSet ds_Reporting = new DataSet();
        ds_Reporting = objEmployee.SelectReportingPerson(designationID);
        if (ds_Reporting != null)
        {
            if (ds_Reporting.Tables[0].Rows.Count > 0)
            {
                if (ddl_ReportingTo.Items.Count > 1)
                    for (int i = ddl_ReportingTo.Items.Count - 1; i > 0; i--)
                    {
                        ddl_ReportingTo.Items.Remove(ddl_ReportingTo.Items[i]);
                    }
                if (ddl_LeaveSancAuthority.Items.Count > 1)
                    for (int i = ddl_LeaveSancAuthority.Items.Count - 1; i > 0; i--)
                    {
                        ddl_LeaveSancAuthority.Items.Remove(ddl_LeaveSancAuthority.Items[i]);
                    }
                ddl_ReportingTo.DataSource = ds_Reporting;
                ddl_ReportingTo.DataTextField = "Employee_FirstName";
                ddl_ReportingTo.DataValueField = "Employee_Id";
                ddl_ReportingTo.DataBind();
                ddl_LeaveSancAuthority.DataSource = ds_Reporting;
                ddl_LeaveSancAuthority.DataTextField = "Employee_FirstName";
                ddl_LeaveSancAuthority.DataValueField = "Employee_Id";
                ddl_LeaveSancAuthority.DataBind();
            }
            ds_Reporting.Dispose();
            BindTooltip(ddl_LeaveSancAuthority);
            BindTooltip(ddl_ReportingTo);
        }
    }
    private void LoadStrings(CultureInfo ci)
    {
        lbl_EntranceName.Text = rm.GetString("lbl_Entrance", ci);
        lblContractor.Text = rm.GetString("lbl_Contractor", ci);
        if (Convert.ToString(Session["packageID"]) != "")
        {
            if (Convert.ToInt32(Session["packageID"]) == 168)  //Samsung
                lbl_HostelWorker.Text = "Blocking is required";
            else
                lbl_HostelWorker.Text = rm.GetString("lbl_EmployeeMaster_HostelWorker", ci);
        }
        else
        {
            lbl_HostelWorker.Text = rm.GetString("lbl_EmployeeMaster_HostelWorker", ci);
        }
        lbl_AnniversaryDate.Text = rm.GetString("EmployeeMaster_AnniversaryDate", ci);
        lbl_BasicSalary.Text = rm.GetString("EmployeeMaster_BasicSalary", ci);
        lbl_BloodGroup.Text = rm.GetString("EmployeeMaster_BloodGroup", ci);
        lbl_CardNo.Text = rm.GetString("TerminalDataType_Card_No", ci);
        lbl_City.Text = rm.GetString("Masters_Generic_City", ci);
        lbl_ConfirmPassword.Text = rm.GetString("EmployeeMaster_ConfirmPassword", ci);
        lbl_ContactAddress.Text = rm.GetString("EmployeeMaster_ContactAddress", ci);
        lbl_Country.Text = rm.GetString("Masters_Generic_Country", ci);
        lbl_DateofBirth.Text = rm.GetString("EmployeeMaster_DateOfBirth", ci);
        lbl_DateofBirthAsPerRec.Text = rm.GetString("EmployeeMaster_DateOfBirthAsPerRecord", ci);
        lbl_DateofJoining.Text = rm.GetString("EmployeeMaster_DateOfJoining", ci);
        lbl_Designation.Text = rm.GetString("EmployeeMaster_Designation", ci);
        lblDesigEffectiveDate.Text = rm.GetString("EmployeeMaster_BasicSal_EffectiveDate", ci);
        lblBasicSalEffectiveDate.Text = rm.GetString("EmployeeMaster_BasicSal_EffectiveDate", ci);
        lbl_District.Text = rm.GetString("EmployeeMaster_District", ci);
        lbl_EmailID.Text = rm.GetString("EmployeeMaster_EmailId", ci);
        lbl_EmployeeFirstName.Text = rm.GetString("email_EmployeeName", ci);
        lbl_EmployeeID.Text = rm.GetString("email_EmployeeId", ci);
        lbl_EmployeeStatus.Text = rm.GetString("EmployeeMaster_EmployeeStatus", ci);
        lbl_FathersName.Text = rm.GetString("EmployeeMaster_FathersName", ci);
        lbl_Gender.Text = rm.GetString("EmployeeMaster_Gender", ci);
        lbl_LastName.Text = rm.GetString("EmployeeMaster_LastName", ci);
        lbl_LeaveSanctioninguthority.Text = rm.GetString("EmployeeMaster_LeaveSanctioningAuthority", ci);
        lbl_Maritalstatus.Text = rm.GetString("EmployeeMaster_MaritalStatus", ci);
        lbl_MiddleName.Text = rm.GetString("EmployeeMaster_MiddleName", ci);
        lbl_MobileNumber.Text = rm.GetString("EmployeeMaster_MobileNumber", ci);
        lbl_MothersName.Text = rm.GetString("EmployeeMaster_MothersName", ci);
        lbl_Nationality.Text = rm.GetString("EmployeeMaster_Nationality", ci);
        lbl_NoofChildren.Text = rm.GetString("EmployeeMaster_NoOfChildren", ci);
        lbl_NoofSpouse.Text = rm.GetString("EmployeeMaster_NoOfSpouse", ci);
        lbl_PassportexpiryDate.Text = rm.GetString("EmployeeMaster_PassportExpiryDate", ci);
        lbl_PassportNo.Text = rm.GetString("EmployeeMaster_PassportNo", ci);
        lbl_Password.Text = rm.GetString("Caption_Password", ci);
        lbl_PermanentAddress.Text = rm.GetString("EmployeeMaster_PermanentAddress", ci);
        lbl_PersonalMailID.Text = rm.GetString("EmployeeMaster_PersionalMailId", ci);
        lbl_PhoneNumber.Text = rm.GetString("EmployeeMaster_PhoneNumber", ci);
        lbl_Photo.Text = rm.GetString("EmployeeMaster_Photo", ci);
        lbl_PolicyName1.Text = rm.GetString("EmployeeMaster_PolicyName1", ci);
        lbl_PreviousExperience.Text = rm.GetString("EmployeeMaster_PreviousExperience", ci);
        lbl_QualifactionattheTimeofJoining.Text = rm.GetString("EmployeeMaster_QualifactionAtTheTimeOfJoining", ci);
        lbl_QualificationduringEmployment.Text = rm.GetString("EmployeeMaster_QualificationDuringEmployment", ci);
        lbl_Religion.Text = rm.GetString("EmployeeMaster_Religion", ci);
        lbl_ReportingTo.Text = rm.GetString("EmployeeMaster_ReportingTo", ci);
        lbl_State.Text = rm.GetString("Masters_Generic_State", ci);
        lbl_Transportation.Text = rm.GetString("EmployeeMaster_Transportation", ci);
        lbl_UserGroup.Text = rm.GetString("EmployeeMaster_UserGroup", ci);
        lbl_UserName.Text = rm.GetString("EmployeeMaster_UserName_AD", ci);
        lbl_VehicleNumber.Text = rm.GetString("EmployeeMaster_VehicleNumber", ci);
        lbl_VehicleType.Text = rm.GetString("EmployeeMaster_VehicleType", ci);
        lbl_VisaExpiryDate.Text = rm.GetString("EmployeeMaster_VisaExpiryDate", ci);
        lbl_VisaNo.Text = rm.GetString("EmployeeMaster_VisaNo", ci);
        lbl_IndicatesMandatoryFields.Text = rm.GetString("IndicatesMandatoryFields", ci);
        CompareValidator1.ErrorMessage = rm.GetString("Validator_EmployeeMaster_Official_ConfirmPassword", ci);
        lbl_HeaderEmployeeMaster.Text = rm.GetString("Masters_Employee_EmployeeMaster", ci);
        lbl_EmployeeMaster.Text = rm.GetString("Masters_Employee_EmployeeMaster", ci);
        lblEmployeeMaster1.Text = rm.GetString("Masters_Employee_EmployeeMaster", ci);
        lblEmployeeMaster2.Text = rm.GetString("Masters_Employee_EmployeeMaster", ci);
        lbl_IndicateMandatoryFields.Text = rm.GetString("IndicatesMandatoryFields", ci);
        rbtn_Active.Text = rm.GetString("rbtn_EmployeeMaster_Active", ci);
        rbtn_Female.Text = rm.GetString("rbtn_EmployeeMaster_Female", ci);
        rbtn_Inactive.Text = rm.GetString("rbtn_EmployeeMaster_InActive", ci);
        rbtn_Male.Text = rm.GetString("rbtn_EmployeeMaster_Male", ci);
        rbtn_Married.Text = rm.GetString("rbtn_EmployeeMaster_Married", ci);
        rbtn_Single.Text = rm.GetString("rbtn_EmployeeMaster_Single", ci);
        chk_CompOffEligible.Text = rm.GetString("chk_EmployeeMaster_CompensationOffEligible", ci);
        chk_EligibleESI.Text = rm.GetString("chk_EmployeeMaster_EligibleForESI", ci);
        chk_EligiblePF.Text = rm.GetString("chk_EmployeeMaster_EligibleForPF", ci);
        chk_OTEligible.Text = rm.GetString("EmployeeMaster_OTEligible", ci);
        chk_OutdoorEmployee.Text = rm.GetString("EmployeeMaster_OutDoorEmployee", ci);
        chk_ReportsExcl.Text = rm.GetString("chk_EmployeeMaster_ExcludeFromReports", ci);
        rbtn_HostelYes.Text = rm.GetString("ShiftSetting_Yes", ci);
        rbtn_HostelNo.Text = rm.GetString("ShiftSetting_No", ci);

        lblIsFlexibleTimings.Text = rm.GetString("FlexibleTimings", ci);
        rbtnFlexibleTimingsYes.Text = rm.GetString("ShiftSetting_Yes", ci);
        rbtnFlexibleTimingsNo.Text = rm.GetString("ShiftSetting_No", ci);
        btn_Next.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Next", ci);
        btn_Cancel1.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Cancel", ci);
        btn_Next2.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Next", ci);
        btn_Back1.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Back", ci);
        btn_Cancel2.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Cancel", ci);
        btn_Next3.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Next", ci);
        btn_Back3.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Back", ci);
        btn_Cancel.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Cancel", ci);
        ButSave.Text = rm.GetString("btn_Save", ci);
        btn_Back4.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Back", ci);
        btn_Back5.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Back", ci);
        btn_Next5.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Next", ci);
        btn_Cancel3.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Cancel", ci);
        btn_Cancel5.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Cancel", ci);
        btn_AddPolicy.ToolTip = rm.GetString("btn_Add", ci);
        btn_AddPolicy.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Add", ci);
        btn_View.ToolTip = rm.GetString("btn_Calculate", ci);
        btn_View.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Calculate", ci);
        lblEmpCategory.Text = rm.GetString("lblEmpCategory", ci);
        lblEmpType.Text = rm.GetString("lblEmpType", ci);
        lblEmpTypEffDate.Text = rm.GetString("EmployeeMaster_BasicSal_EffectiveDate", ci);
        lblEmpCatEffDate.Text = rm.GetString("EmployeeMaster_BasicSal_EffectiveDate", ci);
        lblEffectiveDateLeve.Text = rm.GetString("Caption_EffectiveDateForLevel", ci);
        btn_Personal_main.Text = rm.GetString("Employee_personal", ci);
        btn_Official_blur.Text = rm.GetString("Employee_official", ci);
        btn_LeavePolicy_blur.Text = rm.GetString("Employee_LeavePolicy", ci);
        btn_Others_blur.Text = rm.GetString("Employee_Others", ci);
        btn_Personal_blur.Text = rm.GetString("Employee_personal", ci);
        btn_Official_main.Text = rm.GetString("Employee_official", ci);
        btn_LeavePolicy_blur1.Text = rm.GetString("Employee_LeavePolicy", ci);
        btn_Others_blur1.Text = rm.GetString("Employee_Others", ci);
        btn_Personal_blur1.Text = rm.GetString("Employee_personal", ci);
        btn_Official_blur1.Text = rm.GetString("Employee_official", ci);
        btn_LeavePolicy_main.Text = rm.GetString("Employee_LeavePolicy", ci);
        btn_Others_blur2.Text = rm.GetString("Employee_Others", ci);
        btn_Personal_blur2.Text = rm.GetString("Employee_personal", ci);
        btn_Official_blur2.Text = rm.GetString("Employee_official", ci);
        btn_LeavePolicy_blur2.Text = rm.GetString("Employee_LeavePolicy", ci);
        btn_Others_main.Text = rm.GetString("Employee_Others", ci);
        ddl_VehicleType.Items[0].Text = rm.GetString("Select", ci);
        ddl_VehicleType.Items[1].Text = rm.GetString("VehicleType_TwoWheeler", ci);
        ddl_VehicleType.Items[2].Text = rm.GetString("VehicleType_FourWheeler", ci);
        ddl_Country.Items[0].Text = rm.GetString("Select", ci);
        ddl_State.Items[0].Text = rm.GetString("Select", ci);
        ddl_City.Items[0].Text = rm.GetString("Select", ci);
        ddl_LeavePolicy.Items[0].Text = rm.GetString("Select", ci);
        ddl_Designation.Items[0].Text = rm.GetString("Select", ci);
        ddl_ReportingTo.Items[0].Text = rm.GetString("Select", ci);
        ddl_LeaveSancAuthority.Items[0].Text = rm.GetString("Select", ci);
        ddl_BusRouteNo.Items[0].Text = rm.GetString("Select", ci);
        ddlEmpCatagory.Items[0].Text = rm.GetString("Select", ci);
        ddlEmpType.Items[0].Text = rm.GetString("Select", ci);
        chk_CompOffAndOT.Text = rm.GetString("lblOTCompOffApproval", ci);
        //lblCustomField1.Text = rm.GetString("Employee_CustomField1", ci);
        //lblCustomField2.Text = rm.GetString("Employee_CustomField2", ci);
        //lblCustomField3.Text = rm.GetString("Employee_CustomField3", ci);
        //lblCustomField4.Text = rm.GetString("Employee_CustomField4", ci);
        //lblCustomField5.Text = rm.GetString("Employee_CustomField5", ci);
        lbl_Personal.Text = rm.GetString("Employee_personal", ci);
        lbl_Others.Text = rm.GetString("Employee_Others", ci);
        lbl_Official.Text = rm.GetString("Employee_official", ci);
        lbl_LeavePolicy.Text = rm.GetString("Employee_LeavePolicy", ci);
        lbl_Mandatory.Text = rm.GetString("IndicatesMandatoryFields", ci);
        lblIsActiveDate.Text = rm.GetString("lbl_InActiveDate", ci);

        lblMobileClock.Text = rm.GetString("lblMobileClock", ci);
        rbtnSMSEnable.Text = rbtnMobileClockYes.Text = rm.GetString("rbtnMobileClockYes", ci);
        rbtnSMSDisable.Text = rbtnMobileClockNo.Text = rm.GetString("rbtnMobileClockNo", ci);
        lblSMSEnableDisable.Text = rm.GetString("lblSMSEnableDisable", ci);
        BindCustomizableFieldName();
    }
    private void UserRights()
    {
        ds_Checkuser = objCheckUser.checkRights(18, Convert.ToInt32(Session["userGroup_Id"]), "addPrv");
        if (ds_Checkuser.Tables[0].Rows.Count == 0)
        {
            Response.Redirect("MasterLandingPage.aspx");
        }
    }
    #region Message.
    /// <summary>
    /// Messages the specified message content.
    /// </summary>
    /// <param name="messageContent">Content of the message.</param>
    private void Message(string messageContent)
    {
        string strScript = "<script language='javascript' type='text/javascript'>";
        strScript += "alert('" + messageContent + "');";
        strScript += " </script>";
        ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", strScript, false);
    }
    /// <summary>
    /// Adding this function for getting leave types in placeholder using tables by MAnjula.P on 18-Jul-2013
    /// </summary>
    public void LoadLeaveType()
    {
        try
        {
            string LeaveTypeHeader = rm.GetString("lbl_leavetype", ci);
            string PreviouYearHeader = rm.GetString("Master_Employee_PreviousYearBalance", ci);
            string LeaveTakenHeader = rm.GetString("Master_Employee_NoOffLeaveTaken", ci);
            string LeaveTakenToolTip = rm.GetString("Master_Employee_NoOffLeaveTaken_ToolTip", ci);
            DataSet dsLeaveType = objEmployee.LoadLeaveType(intYearSettingsId);
            if (dsLeaveType != null)
            {
                if (dsLeaveType.Tables[0].Rows.Count > 0)
                {
                    if (Convert.ToString(dsLeaveType.Tables[0].Rows[0]["Emp_LeaveType_Id"]) != string.Empty)
                    {
                        if (Convert.ToInt32(dsLeaveType.Tables[0].Rows[0]["Emp_LeaveType_Id"]) > 0)
                        {
                            ViewState["LeaveTypes"] = dsLeaveType.Tables[0];
                            tbLeaveType.CssClass = "table das-table1 TableWidth";
                            TableHeaderRow trleaveType = new TableHeaderRow();
                            trleaveType.Attributes.Add("class", "row");
                            TableHeaderCell tcLeaveTypeName = new TableHeaderCell();
                            tcLeaveTypeName.Attributes.Add("class", "col-md-4 empheader");
                            tcLeaveTypeName.Wrap = true;
                            tcLeaveTypeName.Text = LeaveTypeHeader;
                            trleaveType.Cells.Add(tcLeaveTypeName);
                            TableHeaderCell tcPreviousYearBalance = new TableHeaderCell();
                            tcPreviousYearBalance.Wrap = true;
                            tcPreviousYearBalance.Attributes.Add("class", "col-md-4 empheader");
                            tcPreviousYearBalance.Text = PreviouYearHeader;
                            trleaveType.Cells.Add(tcPreviousYearBalance);
                            TableHeaderCell tcNoOfLeaveAvailed = new TableHeaderCell();
                            tcNoOfLeaveAvailed.Attributes.Add("class", "col-md-4 empheader");
                            tcNoOfLeaveAvailed.HorizontalAlign = HorizontalAlign.Center;
                            tcNoOfLeaveAvailed.Wrap = true;
                            tcNoOfLeaveAvailed.Text = LeaveTakenHeader;
                            trleaveType.Cells.Add(tcNoOfLeaveAvailed);
                            if (Session["Demo"] != null && Convert.ToString(Session["Demo"]) != "Express")
                            {
                                tbLeaveType.Rows.Add(trleaveType);
                            }
                            phLeaveTypes.Controls.Add(tbLeaveType);
                            int i = 1;
                            foreach (DataRow dr in dsLeaveType.Tables[0].Rows)
                            {
                                TableRow tr = new TableRow();
                                tr.Attributes.Add("class", "row form-group");
                                TableCell tc_LeaveType = new TableCell();
                                tc_LeaveType.Attributes.Add("class", "col-md-4");
                                Label lblLeaveType = new Label();
                                lblLeaveType.ID = Convert.ToString(dr["Emp_LeaveType_Id"]);
                                lblLeaveType.Text = Convert.ToString(dr["LeaveDescription"]);
                                tc_LeaveType.Controls.Add(lblLeaveType);
                                tr.Cells.Add(tc_LeaveType);
                                TableCell tc_PreviousYearBalance = new TableCell();
                                tc_PreviousYearBalance.Attributes.Add("class", "col-md-4");
                                TextBox txtPreviousYearBalance = new TextBox();
                                txtPreviousYearBalance.ID = "txtPreviousYearBalance" + Convert.ToInt32(dr["Emp_LeaveType_Id"]);
                                txtPreviousYearBalance.Attributes.Add("onkeypress", "return number_dot_Without_Dollar(event,this);");
                                txtPreviousYearBalance.Attributes.Add("onchange", "return onChangeHalfDay(this);");
                                txtPreviousYearBalance.Attributes.Add("onpaste", "return false;");
                                txtPreviousYearBalance.Attributes.Add("oncopy", "return false;");
                                txtPreviousYearBalance.Attributes.Add("ondrop", "return false;");
                                txtPreviousYearBalance.Attributes.Add("class", "form-control");
                                txtPreviousYearBalance.MaxLength = 4;
                                txtPreviousYearBalance.Wrap = true;
                                tc_PreviousYearBalance.Controls.Add(txtPreviousYearBalance);
                                tr.Cells.Add(tc_PreviousYearBalance);
                                TableCell tc_NoOffLeaveAvailed = new TableCell();
                                tc_NoOffLeaveAvailed.Attributes.Add("class", "col-md-4");
                                TextBox txtNoOffLeaveAvailed = new TextBox();
                                txtNoOffLeaveAvailed.ID = "txtNoOffLeaveAvailed" + Convert.ToInt32(dr["Emp_LeaveType_Id"]);
                                txtNoOffLeaveAvailed.Attributes.Add("onkeypress", "return number_dot_Without_Dollar(event,this);");
                                txtNoOffLeaveAvailed.Attributes.Add("onchange", "return onChangeHalfDay(this);");
                                txtNoOffLeaveAvailed.Attributes.Add("onpaste", "return false;");
                                txtNoOffLeaveAvailed.Attributes.Add("oncopy", "return false;");
                                txtNoOffLeaveAvailed.Attributes.Add("ondrop", "return false;");
                                txtNoOffLeaveAvailed.Attributes.Add("class", "form-control");
                                txtNoOffLeaveAvailed.Wrap = true;
                                txtNoOffLeaveAvailed.MaxLength = 4;
                                txtNoOffLeaveAvailed.ToolTip = LeaveTakenToolTip;
                                tc_NoOffLeaveAvailed.Controls.Add(txtNoOffLeaveAvailed);
                                tr.Cells.Add(tc_NoOffLeaveAvailed);
                                tbLeaveType.Rows.Add(tr);
                                i = i + 1;
                            }
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            Message(ex.Message);
        }
        finally
        {
        }
    }
    /// <summary>
    /// Adding insert employee type function by MAnjula.P on 18-Jul-2013 
    /// </summary>
    public void InsertLeaveTypeDetails(int EmployeeId)
    {
        try
        {
            if (ViewState["LeaveTypes"] != null)
            {
                DataTable dt = new DataTable();
                dt = (DataTable)ViewState["LeaveTypes"];
                TextBox txtPreviousYearBalance = new TextBox();
                TextBox txtNoOffLeaveAvailed = new TextBox();
                if (dt.Rows.Count > 0)
                {
                    int RowCount = dt.Rows.Count;
                    int i = 1;
                    foreach (DataRow dr in dt.Rows)
                    {
                        txtPreviousYearBalance = (TextBox)tbLeaveType.Rows[i].FindControl("txtPreviousYearBalance" + Convert.ToInt32(dr["Emp_LeaveType_Id"]));
                        txtNoOffLeaveAvailed = (TextBox)tbLeaveType.Rows[i].FindControl("txtNoOffLeaveAvailed" + Convert.ToInt32(dr["Emp_LeaveType_Id"]));
                        if (txtPreviousYearBalance != null)
                            if (txtPreviousYearBalance.Text == string.Empty)
                                txtPreviousYearBalance.Text = "0";
                        if (txtNoOffLeaveAvailed != null)
                            if (txtNoOffLeaveAvailed.Text == string.Empty)
                                txtNoOffLeaveAvailed.Text = "0";
                        objEmployee.InsertLeavetypeDetails(EmployeeId, Convert.ToInt32(dr["Emp_LeaveType_Id"]), Convert.ToDecimal(txtPreviousYearBalance.Text), Convert.ToDecimal(txtNoOffLeaveAvailed.Text), intYearSettingsId);
                        i = i + 1;
                    }
                }
            }
        }
        catch (Exception ex)
        {
            Message(ex.Message);
        }
        finally
        {
        }
    }
    #endregion
    #region MessageWithRedirect.
    /// <summary>
    /// Messages the with redirect.
    /// </summary>
    /// <param name="messageContent">Content of the message.</param>
    /// <param name="ToPage">To page.</param>
    private void MessageWithRedirect(string messageContent, string ToPage)
    {
        string strScript = "<script language='javascript' type='text/javascript'>";
        strScript += "alert('" + messageContent + "');";
        strScript += "location.href='" + ToPage + "';";
        strScript += " </script>";
        ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", strScript, false);
    }
    #endregion
    #region BindingEmployeeCategoryandType.
    /// <summary>
    /// Bindings the employee category and type.
    /// </summary>
    private void BindingEmployeeCategoryandType()
    {
        DataSet dsReligion = new DataSet();
        dsReligion = objEmployee.SelectReligion();
        if (dsReligion != null)
        {
            if (dsReligion.Tables[0].Rows.Count > 0)
            {
                ddlReligion.DataSource = dsReligion;
                ddlReligion.DataTextField = "Name";
                ddlReligion.DataValueField = "Id";
                ddlReligion.DataBind();
            }
            dsReligion.Dispose();
        }
        BindTooltip(ddlReligion);
    }
    #endregion
    #endregion
    #region ButtonEvents
    protected void btn_Save_Click(object sender, EventArgs e)
    {
        string policyid = hdf_PolicyID.Value;
        string strDob = String.Empty;
        if (Convert.ToInt32(Session["parentLevelId"]) != 0)
        {
            gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
            string strDoj = objcommon.DateConvertion(gstrDateFormat, txt_doj.Text.Trim());
            TimeSpan tsYearDifference;
            if (strDob != "" && strDoj != "")
            {
                tsYearDifference = DateTime.Parse(strDoj).Subtract(DateTime.Parse(strDob));
                if (tsYearDifference.Ticks <= 0)
                {
                    blnNoError = false;
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "ShowOffical('" + rm.GetString("Alert_DOJshouldbegreaterthanDOB", ci) + "');", true);
                    return;
                }
            }
            int intEmpCategory = 0, intEmpType = 0, intReligion = 0;
            if (ddlEmpCatagory.SelectedIndex == 0)
            {
                blnNoError = false;
                ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "ShowOffical('" + rm.GetString("Alert_SelectEmployeeCategory", ci) + "');", true);
                return;
            }
            else
            {
                intEmpCategory = Convert.ToInt32(ddlEmpCatagory.SelectedValue);
            }
            intReligion = Convert.ToInt32(ddlReligion.SelectedValue);
            if (ddlEmpType.SelectedIndex == 0)
            {
                blnNoError = false;
                ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "ShowOffical('" + rm.GetString("Alert_SelectEmployeeType", ci) + "');", true);
                return;
            }
            else
            {
                intEmpType = Convert.ToInt32(ddlEmpType.SelectedValue);
            }
            if (intDesignation == 0)
            {
                blnNoError = false;
                ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "ShowOffical('" + rm.GetString("Alert_SelectDesignation", ci) + "');", true);
                return;
            }
            if (fup_Photo.HasFile)
            {
                string strphotofile = fup_Photo.PostedFile.FileName;
                int index = strphotofile.LastIndexOf(".");
                string strFileFormat = strphotofile.Substring(index + 1).ToLower();
                if (strFileFormat == "jpeg" || strFileFormat == "jpg" || strFileFormat == "bmp" || strFileFormat == "gif")
                {
                    image = fup_Photo.FileBytes;
                }
                else
                {
                    blnNoError = false;
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "ShowOffical('" + rm.GetString("Alert_PleaseSelectJPGorGIForBMPFileforPhoto", ci) + "');", true);
                    return;
                }
            }
            int LeavePolicyId;
            strGender = (rbtn_Male.Checked == true) ? "Male" : "Female";
            int Religion = Convert.ToInt32(ddlReligion.SelectedValue);
            int EmpCategory = Convert.ToInt32(ddlEmpCatagory.SelectedValue);
            int EmpType = Convert.ToInt32(ddlEmpType.SelectedValue);
            if (Convert.ToString(ddl_LeavePolicy.SelectedItem.Value) != "-Select-")
            {
                LeavePolicyId = objEmployee.ValidateLeavePolicyByFilters(EmpCategory, EmpType, strGender, Religion, Convert.ToInt32(ddl_LeavePolicy.SelectedItem.Value));
                if (LeavePolicyId == 0)
                {
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "ShowOffical('" + rm.GetString("Alert_SelectVaildLeavePolicy", ci) + "');", true);
                    return;
                }
            }
            if (Session["Demo"] != null && Convert.ToString(Session["Demo"]) != "Express")
            {
                if (ValidLeaveTypes() == false)
                {
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "ShowOffical('" + rm.GetString("Alert_EnterValidLeaveTaken", ci) + "');", true);
                    tbLeaveType.Focus();
                    return;
                }
            }



            if (Session["Demo"] != null && Convert.ToString(Session["Demo"]) != "Express")
            {
                if (Convert.ToString(Session["PreviousYearCount"]) == "1")
                {
                    string strMsg = ValidateDOJPreviousYearBalance(strDoj);
                    if (strMsg != string.Empty)
                    {
                        base.Message(strMsg);
                        phLeaveTypes.Focus();
                        return;
                    }
                }
            }
            string strPexpiry = objcommon.DateConvertion(gstrDateFormat, txt_PExpiry.Text.Trim());

            if (strPexpiry != "" && strDob != "")
            {
                tsYearDifference = DateTime.Parse(strPexpiry).Subtract(DateTime.Parse(strDob));
                if (tsYearDifference.Ticks <= 0)
                {
                    blnNoError = false;
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "ShowOffical('" + rm.GetString("Alert_PassExpiryDateGreaterThanDOB", ci) + "');", true);
                    return;
                }
            }
            string strVexpiry = objcommon.DateConvertion(gstrDateFormat, txt_VExpiry.Text.Trim());
            if (strVexpiry != "" && strDob != "")
            {
                tsYearDifference = DateTime.Parse(strVexpiry).Subtract(DateTime.Parse(strDob));
                if (tsYearDifference.Ticks <= 0)
                {
                    blnNoError = false;
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "ShowOffical('" + rm.GetString("Alert_VisaExpiryDategreaterthanDOB", ci) + "');", true);
                    return;
                }
            }
            string strAnniversarydate = objcommon.DateConvertion(gstrDateFormat, txt_AnniversaryDate.Text.Trim());
            if (strAnniversarydate != "" && strDob != "")
            {
                tsYearDifference = DateTime.Parse(strAnniversarydate).Subtract(DateTime.Parse(strDob));
                if (tsYearDifference.Ticks <= 0)
                {
                    blnNoError = false;
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "ShowOffical('" + rm.GetString("Alert_AnniversaryDategreaterThanDOB", ci) + "');", true);
                    return;
                }
            }


            string strFirstname = txt_EmpFirstName.Text.Trim().Replace("'", "''");
            string strMiddlename = txt_MName.Text.Trim().Replace("'", "''");
            string strLastname = txt_LName.Text.Trim().Replace("'", "''");
            string strFathername = txt_FatherName.Text.Trim().Replace("'", "''");
            string strMothername = txt_MotherName.Text.Trim().Replace("'", "''");
            if (txt_dob.Text != "")
            {
                strDob = objcommon.DateConvertion(gstrDateFormat, txt_dob.Text.Trim());
            }
            string strDobrecord = objcommon.DateConvertion(gstrDateFormat, txt_Recdob.Text.Trim());
            string strBloodgroup = txt_BloodGroup.Text.Trim();
            string strEmailID = txt_EmailID.Text.Trim();
            string strContactaddress = txt_ContactAddress.Text.Trim();
            string strPermanentAddress = txt_PermanentAddress.Text.Trim();
            string strPhoneno = txt_PhoneNo.Text.Trim();
            string strMobileno = txt_MobileNo.Text.Trim();
            string strMstatus = rbtn_Single.Checked == true ? "Single" : "Married";
            string strNationality = txt_Nationality.Text.Trim();
            string strPersonalmailID = txt_PersonalMailID.Text.Trim();
            string strPassportno = txt_Passport.Text.Trim();
            string strVisano = txt_Visa.Text.Trim();
            string strVehicletype = ddl_VehicleType.SelectedValue;
            string strVehicleno = txt_VehicleNo.Text.Trim();
            string strDistrict = txt_District.Text.Trim();
            int intFlexibleTimings = 0;
            intFlexibleTimings = rbtnFlexibleTimingsYes.Checked == true ? 1 : 0;
            int intSpouseno = 0;
            if (txt_SpouseNo.Value.Trim() != "")
            {
                intSpouseno = Convert.ToInt32(txt_SpouseNo.Value.Trim());
            }
            int intChildrenno = 0;
            if (txt_ChildrenNo.Value.Trim() != "")
            {
                intChildrenno = Convert.ToInt32(txt_ChildrenNo.Value.Trim());
            }
            string strEmpcodeID = txt_EmpID.Text.Trim();
            if (Convert.ToString(ddl_EntranceName.SelectedItem.Value) != "-Select-")
            {
                objEmployee.Insert_EmployeeEntranceDetails(strEmpcodeID, Convert.ToInt32(ddl_EntranceName.SelectedItem.Value));
            }
            intLevelID = 0;
            if ((Session["parentLevelId"]) != null)
            {
                intLevelID = Convert.ToInt32(Session["parentLevelId"]);
            }
            int intBusrouteno = 0;
            if (ddl_BusRouteNo.Text != "-Select-")
            {
                intBusrouteno = Convert.ToInt32(ddl_BusRouteNo.SelectedValue);
            }
            string strUsergroup = "";
            for (int i = 1; i < ddl_UserGroup.Items.Count; i++)
            {
                if (ddl_UserGroup.Items[i].Selected == true)
                {
                    if (strUsergroup == "")
                    {
                        strUsergroup = ddl_UserGroup.Items[i].Value;
                    }
                    else
                    {
                        strUsergroup = strUsergroup + "," + ddl_UserGroup.Items[i].Value;
                    }
                }
            }
            if (strUsergroup == "")
            {
                ListItem lstItem = ddl_UserGroup.Items.FindByText("IndividualUsers");
                if (lstItem != null)
                {
                    strUsergroup = lstItem.Value;
                }
            }
            float fltPrevexperience = 0;
            if (txt_PrevExperience.Text.Trim() != "")
            {
                fltPrevexperience = Convert.ToSingle(txt_PrevExperience.Text.Trim());
            }
            float fltBasicsalary = 0;
            if (txt_BasicSalary.Text.Trim() != "")
            {
                fltBasicsalary = Convert.ToSingle(txt_BasicSalary.Text.Trim());
            }
            string strBasicSalEffDate = objcommon.DateConvertion(gstrDateFormat, txtBasicSalEffDate.Text.Trim());
            string strDesigEffDate = objcommon.DateConvertion(gstrDateFormat, txt_DesigEffDate.Text.Trim());
            string strLevelEffDate = objcommon.DateConvertion(gstrDateFormat, txteffDateLevel.Text.Trim());
            string strEmpCatEffDate = objcommon.DateConvertion(gstrDateFormat, txtEmpCatEffDate.Text.Trim());
            string strEmpTypeEffDate = objcommon.DateConvertion(gstrDateFormat, txtEmpTypEffDate.Text.Trim());
            string strEmpContractEffDate = objcommon.DateConvertion(gstrDateFormat, txtConEffectiveDate.Text.Trim());
            string strUsername = txt_UserName.Text.Trim();
            string strEPassword = "QL5OWbmiorXf+5GMDoaz1w==";
            string strQualJoining = txt_QualAtJoiningTime.Text.Trim();
            string strQualEmployment = txt_QualDurEmployment.Text.Trim();
            bool blOutdoorEmployee = (chk_OutdoorEmployee.Checked == true) ? true : false; ;
            bool blOTeligible = (chk_OTEligible.Checked == true) ? true : false;
            bool blCOffeligible = (chk_CompOffEligible.Checked == true) ? true : false;
            bool blESIeligible = (chk_EligibleESI.Checked == true) ? true : false;
            bool blPFeligible = (chk_EligiblePF.Checked == true) ? true : false;
            bool blExclReport = (chk_ReportsExcl.Checked == true) ? true : false;
            bool blActiveness = (rbtn_Active.Checked == true) ? true : false;
            bool blHostelWorker = (rbtn_HostelYes.Checked == true) ? true : false;
            string inActiveDate;
            inActiveDate = rbtn_Inactive.Checked == true ? objcommon.DateConvertion(gstrDateFormat, txtInActive.Text.Trim()) : "";
            string strSwipecardNo = Convert.ToString(txt_SwipeCardNo.Text.Trim());

            int penaltyCat = 0;
            int isMobileClockInOutEnabled = 0;
            int isSMSEnabled = 0;
            if (Convert.ToString(Session["packageID"]) != "")
            {
                //Sohit admin
                if (Convert.ToString(Session["packageID"]) == "157")
                    penaltyCat = (rbtnDisruptive.Checked) ? 1 : 0;
            }
            isMobileClockInOutEnabled = (rbtnMobileClockYes.Checked) ? 1 : 0;
            isSMSEnabled = (rbtnSMSEnable.Checked) ? 1 : 0;

            string strPFESI = "";

            for (int i = 1; i < ddl_PFESI.Items.Count; i++)
            {
                if (ddl_PFESI.Items[i].Selected == true)
                {
                    if (strPFESI == "")
                    {
                        strPFESI = ddl_PFESI.Items[i].Value;
                    }
                    else
                    {
                        strPFESI = strPFESI + "," + ddl_PFESI.Items[i].Value;
                    }
                }
                else
                {
                    strPFESI = "0";
                }
            }


            string strConveyance = "";
            for (int i = 1; i < ddl_CA.Items.Count; i++)
            {
                if (ddl_CA.Items[i].Selected == true)
                {
                    if (strConveyance == "")
                    {
                        strConveyance = ddl_CA.Items[i].Value;

                    }
                    else
                    {
                        strConveyance = strConveyance + "," + ddl_CA.Items[i].Value;
                    }
                }
                else
                {
                    strConveyance = "0";
                }
            }


            // Maria Prasanth Payroll Config
            int hra = 0;
            int Da = 0;
            int PFESI = 0;
            int CA = 0;
            int Medical = 0;
            int ChildAllowance = 0;
            int Tax_policy = 0;
            Int64 CTC = 0;

            if (Convert.ToInt32(dd_HRA.SelectedValue) == 1)
            {
                hra = 1;
            }
            else
            {
                hra = 0;
            }
            Da = 1;

            if (rbtn_CEAYes.Checked)
            {
                ChildAllowance = 1;
            }
            else
            {
                ChildAllowance = 0;
            }

            if (rbtn_MediaclYes.Checked)
            {
                Medical = 1;
            }
            else
            {
                Medical = 0;
            }
            if (Convert.ToString(ddl_TaxPolicy.SelectedValue) == "-Select-" || Convert.ToString(ddl_TaxPolicy.SelectedValue) == string.Empty)
            {
                Tax_policy = ddl_TaxPolicy.SelectedIndex;
            }
            else
            {
                Tax_policy = Convert.ToInt32(ddl_TaxPolicy.SelectedValue);
            }
            if (strPFESI == String.Empty)
            {
                PFESI = 0;
            }
            else
            {
                PFESI = Convert.ToInt32(strPFESI);
            }
            if (strConveyance == String.Empty)
            {
                CA = 0;
            }
            else
            {
                CA = Convert.ToInt32(strConveyance);
            }
            CTC = Convert.ToInt64(Convert.ToString(txt_CTC.Text) == "" ? "0" : txt_CTC.Text);
            //Added by Velumani on Feb 28 for Product
            bool IsPassportReminderRequired = false;
            int PassportRemindDays = 0;
            bool IsVisaReminderRequired = false;
            int VisaRemindDays = 0;
            IsPassportReminderRequired = (chk_IspassportRemindReq.Checked) ? true : false;
            IsVisaReminderRequired = (chk_IsVisaRemindReq.Checked) ? true : false;
            if (txtPassportRemindDayscount.Text.Trim() != "")
            {
                PassportRemindDays = Convert.ToInt32(txtPassportRemindDayscount.Text.Trim());
            }
            if (txtVisaRemindDayscount.Text.Trim() != "")
            {
                VisaRemindDays = Convert.ToInt32(txtVisaRemindDayscount.Text.Trim());
            }
            if (blnNoError == true)
            {
                int count = objEmployee.CheckDuplicateEmployeeCode(strEmpcodeID, intLevelID, Convert.ToBoolean(Session["ApplnMode"]));

                if (count == 0)
                {
                    bool isAllowAdd = CheckNoOfEmployeeForLicense();

                    if (isAllowAdd)
                    {
                        objEmployee.InsertUpdateEmployeeDetails("I", 0, intLevelID, strUsergroup, intDesignation, intBusrouteno, strFirstname, strMiddlename,
                                   strLastname, strFathername, strMothername, strDob, strDobrecord, strBloodgroup, strEmailID,
                                   strContactaddress, strPermanentAddress, strPhoneno, strMobileno, strGender, strMstatus,
                                   strNationality, intReligion, image, strPersonalmailID, strPassportno, strPexpiry,
                                   strVisano, strVexpiry, strVehicletype, strVehicleno, strAnniversarydate, intNativeplace,
                                   strDistrict, intState, intCountry, intSpouseno, intChildrenno, strEmpcodeID, strDoj,
                                   intReporting, intLeaveSancAuthority, fltPrevexperience, fltBasicsalary,
                                   blHostelWorker, strUsername, strEPassword, strQualJoining, strQualEmployment, Convert.ToInt16(blOutdoorEmployee),
                                   Convert.ToInt16(blCOffeligible), Convert.ToInt16(blOTeligible), Convert.ToInt16(blESIeligible), Convert.ToInt16(blPFeligible),
                                   Convert.ToInt16(blExclReport), Convert.ToInt16(blActiveness), strSwipecardNo, intEmpCategory, intEmpType, EmployeeID,
                                   strBasicSalEffDate, strDesigEffDate, intYearSettingsId, strLevelEffDate, strEmpCatEffDate, strEmpTypeEffDate, intFlexibleTimings, inActiveDate, Convert.ToString(txtCustomField1.Text), Convert.ToString(txtCustomField2.Text), Convert.ToString(txtCustomField3.Text),
                                   Convert.ToString(txtCustomField4.Text), Convert.ToString(txtCustomField5.Text), Convert.ToBoolean(Session["ApplnMode"]), penaltyCat
                                   , isMobileClockInOutEnabled, isSMSEnabled, IsPassportReminderRequired, PassportRemindDays, IsVisaReminderRequired, VisaRemindDays, hra, Da, Medical, CA, PFESI, Tax_policy, ChildAllowance, CTC,
                                    Convert.ToInt32(ddlContractor.SelectedValue), strEmpContractEffDate,Convert.ToString(txtCustomField6.Text));

                        int MaxID = objEmployee.select_MaxEmpID();

                        if (intChildrenno > 0)
                        {
                            ChildrenData(MaxID);
                        }
                        if (intSpouseno > 0)
                        {
                            SpouseData(MaxID);
                        }
                        LeavePolicyData(MaxID);
                        if (Session["Demo"] != null && Convert.ToString(Session["Demo"]) != "Express")
                        {
                            InsertLeaveTypeDetails(MaxID);
                        }
                        Session["country"] = null;
                        Session["state"] = null;
                        Session["city"] = null;
                        Session["parentLevelId"] = null;
                        Session["Designation"] = null;
                        Session["Reporting"] = null;
                        Session["LeaveSanc"] = null;
                        if (dt_EmpPolicy != null)
                        {
                            dt_EmpPolicy.Dispose();
                        }
                        updateBioAdmin(strSwipecardNo);
                        string strScript = "";
                        strScript = strScript + "<script language='javascript'>";
                        strScript = strScript + "alert('" + rm.GetString("Alert_Employeeinformaitonsavedsucessfully", ci) + "');";
                        strScript = strScript + "location.replace('TA_UI_Master_Employee.aspx');";
                        strScript = strScript + "</script>";
                        ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", strScript, false);
                    }
                }
                else
                {
                    blnNoError = false;
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "ShowOffical('" + rm.GetString("Alert_EmployeeIDalreadyexists", ci) + "');", true);
                }
            }
        }
        else
        {
            blnNoError = false;
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "ShowOffical('" + rm.GetString("Alert_Selectallorganizationlevels", ci) + "');", true);
        }
    }
    #endregion
    /// <summary>
    /// Get Customizable field name form attendance code screen
    /// Based on the creation there, the label name will be displayed here for display.
    /// </summary>
    private void BindCustomizableFieldName()
    {
        DataSet ds = new DataSet();
        ds = objAttCode.SelectAllAttandance(0, "All", Convert.ToString(Session["UserGroupName"]), "", 0);
        if (ds.Tables.Count > 0)
        {
            if (ds.Tables[0].Rows.Count > 0)
            {
                ds.Tables[0].DefaultView.RowFilter = "AttandanceValue in('Customizable Field1','Customizable Field2','Customizable Field3','Customizable Field4','Customizable Field5','Customizable Field6')";
                DataTable dt = ds.Tables[0].DefaultView.ToTable();
                if (dt.Rows.Count > 0)
                {
                    string customFields = "";
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        customFields = Convert.ToString(dt.Rows[i]["AttandanceValue"]);
                        switch (customFields)
                        {
                            case "Customizable Field1":
                                lblCustomField1.Text = Convert.ToString(dt.Rows[i]["AttandanceCode"]);
                                break;
                            case "Customizable Field2":
                                lblCustomField2.Text = Convert.ToString(dt.Rows[i]["AttandanceCode"]);
                                break;
                            case "Customizable Field3":
                                lblCustomField3.Text = Convert.ToString(dt.Rows[i]["AttandanceCode"]);
                                break;
                            case "Customizable Field4":
                                lblCustomField4.Text = Convert.ToString(dt.Rows[i]["AttandanceCode"]);
                                break;
                            case "Customizable Field5":
                                lblCustomField5.Text = Convert.ToString(dt.Rows[i]["AttandanceCode"]);
                                break;
                            case "Customizable Field6":
                                lblCustomField6.Text = Convert.ToString(dt.Rows[i]["AttandanceCode"]);
                                break;
                        }
                    }
                }
            }
        }
        else
        {
            //lblCustomField1.Text = rm.GetString("Employee_CustomField1", ci);
            //lblCustomField2.Text = rm.GetString("Employee_CustomField2", ci);
            //lblCustomField3.Text = rm.GetString("Employee_CustomField3", ci);
            //lblCustomField4.Text = rm.GetString("Employee_CustomField4", ci);
            //lblCustomField5.Text = rm.GetString("Employee_CustomField5", ci);
        }
    }

    protected void Pop_btn(object sender, EventArgs e)
    {


        ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "ClosePopup();", true);

    }
    protected void btn_Add_Click(object sender, EventArgs e)
    {

    }
    //protected void btnCustomAdd1_Click(object sender, EventArgs e)
    //{
    //    int MaxFileSize = Convert.ToInt32(ConfigurationManager.AppSettings["MaxFileSize"]);
    //    string Ex_JPEG = ConfigurationManager.AppSettings["Ex_JPEG"];
    //    string Ex_JPG = ConfigurationManager.AppSettings["Ex_JPG"];
    //    string Ex_BMP = ConfigurationManager.AppSettings["Ex_BMP"];
    //    string Ex_PNG = ConfigurationManager.AppSettings["Ex_PNG"];
    //    string Ex_PDF = ConfigurationManager.AppSettings["Ex_PDF"];
    //    string Ex_DOC = ConfigurationManager.AppSettings["Ex_DOC"];
    //    string Ex_DOCX = ConfigurationManager.AppSettings["Ex_DOCX"];
    //    string GetCurrentDate = DateTime.Today.ToString("yyyyMMdd");
    //    string GetEmployeeId = Convert.ToString(txt_SwipeCardNo.Text);
    //    string GetLeaveApplicationId = string.Empty;
    //    bool result = false;
    //    string GetDash = "_";
    //    string GetSessionEmployeeID = Convert.ToString(Session["EmployeeCodeId"]);

    //    if (GetCurrentDate != string.Empty && GetEmployeeId != string.Empty && lblCustomField1.Text != string.Empty)
    //    {
    //        string DocumentName = string.Concat(GetEmployeeId, GetDash, GetCurrentDate, GetDash, "CusFd1");
    //        if (txtCustomField1.HasFile)
    //        {
    //            string fileExtension = System.IO.Path.GetExtension(txtCustomField1.FileName);
    //            if (fileExtension != Ex_PDF)
    //            {
    //                ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('Please Upload only PDF extension file format');", true);
    //            }
    //            else
    //            {
    //                int fileSize = txtCustomField1.PostedFile.ContentLength;
    //                if (fileSize == 0 || fileSize > MaxFileSize)
    //                {
    //                    ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('Maximum upload file size is 5MB.');", true);
    //                }
    //                else
    //                {
    //                    try
    //                    {
    //                        string extension = Path.GetExtension(txtCustomField1.PostedFile.FileName);
    //                        DirectoryInfo isDirectExists = new DirectoryInfo(Server.MapPath("~/Masters/EmployeeDocumentUpload"));
    //                        if (!isDirectExists.Exists)
    //                        {
    //                            ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('The Application doest not contain Leave Application Upload Files folder, please create it');", true);
    //                            result = false;
    //                        }
    //                        else
    //                        {
    //                            string serverpath = Server.MapPath("~/Masters/EmployeeDocumentUpload/") + DocumentName + extension;
    //                            finalCustomefile1 = AppendFileNumberIfExists(serverpath, extension);
    //                            txtCustomField1.SaveAs(finalCustomefile1);
    //                            Session["EmployeeCusDoc1"] = finalCustomefile1;
    //                            //ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('File uploaded Sucessfully');", true);
    //                            btnCustomAdd1.Visible = false;
    //                            btnCustomView1.Visible = true;
    //                            hdnpdfViewer1.Value = finalCustomefile1;
    //                            //txtCustomField1.FileName = DocumentName;
    //                        }
    //                    }
    //                    catch (Exception ex)
    //                    {
    //                        ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('File Could not be uploaded');", true);
    //                    }
    //                }
    //            }
    //        }
    //        else
    //        {
    //            ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('Upload the necessary document to avail this leave.');", true);

    //        }
    //    }
    //    else
    //    {
    //        ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('File Could not be uploaded');", true);
    //    }
    //}

    //protected void btnCustomAdd2_Click(object sender, EventArgs e)
    //{
    //    int MaxFileSize = Convert.ToInt32(ConfigurationManager.AppSettings["MaxFileSize"]);
    //    string Ex_JPEG = ConfigurationManager.AppSettings["Ex_JPEG"];
    //    string Ex_JPG = ConfigurationManager.AppSettings["Ex_JPG"];
    //    string Ex_BMP = ConfigurationManager.AppSettings["Ex_BMP"];
    //    string Ex_PNG = ConfigurationManager.AppSettings["Ex_PNG"];
    //    string Ex_PDF = ConfigurationManager.AppSettings["Ex_PDF"];
    //    string Ex_DOC = ConfigurationManager.AppSettings["Ex_DOC"];
    //    string Ex_DOCX = ConfigurationManager.AppSettings["Ex_DOCX"];
    //    string GetCurrentDate = DateTime.Today.ToString("yyyyMMdd");
    //    string GetEmployeeId = Convert.ToString(txt_SwipeCardNo.Text);
    //    string GetLeaveApplicationId = string.Empty;
    //    bool result = false;
    //    string GetDash = "_";
    //    string GetSessionEmployeeID = Convert.ToString(Session["EmployeeCodeId"]);


    //    if (GetCurrentDate != string.Empty && GetEmployeeId != string.Empty && lblCustomField2.Text != string.Empty)
    //    {
    //        string DocumentName = string.Concat(GetEmployeeId, GetDash, GetCurrentDate, GetDash, "CusFd2");
    //        if (txtCustomField2.HasFile)
    //        {
    //            string fileExtension = System.IO.Path.GetExtension(txtCustomField2.FileName);
    //            if (fileExtension != Ex_PDF)
    //            {
    //                ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('Please Upload only PDF extension file format');", true);
    //            }
    //            else
    //            {
    //                int fileSize = txtCustomField2.PostedFile.ContentLength;
    //                if (fileSize == 0 || fileSize > MaxFileSize)
    //                {
    //                    ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('Maximum upload file size is 5MB.');", true);
    //                }
    //                else
    //                {
    //                    try
    //                    {
    //                        string extension = Path.GetExtension(txtCustomField2.PostedFile.FileName);
    //                        DirectoryInfo isDirectExists = new DirectoryInfo(Server.MapPath("~/Masters/EmployeeDocumentUpload"));
    //                        if (!isDirectExists.Exists)
    //                        {
    //                            ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('The Application doest not contain Leave Application Upload Files folder, please create it');", true);
    //                            result = false;
    //                        }
    //                        else
    //                        {
    //                            string serverpath = Server.MapPath("~/Masters/EmployeeDocumentUpload/") + DocumentName + extension;
    //                            finalCustomefile2 = AppendFileNumberIfExists(serverpath, extension);
    //                            txtCustomField2.SaveAs(finalCustomefile2);
    //                            Session["EmployeeCusDoc2"] = finalCustomefile2;
    //                            //ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('File uploaded Sucessfully');", true);
    //                            btnCustomAdd2.Visible = false;
    //                            btnCustomView2.Visible = true;
    //                            hdnpdfViewer2.Value = finalCustomefile2;
    //                            //txtCustomField1.FileName = DocumentName;
    //                        }
    //                    }
    //                    catch (Exception ex)
    //                    {
    //                        ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('File Could not be uploaded');", true);
    //                    }
    //                }
    //            }
    //        }
    //        else
    //        {
    //            ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('Upload the necessary document to avail this leave.');", true);

    //        }
    //    }
    //    else
    //    {
    //        ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('File Could not be uploaded');", true);
    //    }
    //}

    //protected void btnCustomAdd3_Click(object sender, EventArgs e)
    //{
    //    int MaxFileSize = Convert.ToInt32(ConfigurationManager.AppSettings["MaxFileSize"]);
    //    string Ex_JPEG = ConfigurationManager.AppSettings["Ex_JPEG"];
    //    string Ex_JPG = ConfigurationManager.AppSettings["Ex_JPG"];
    //    string Ex_BMP = ConfigurationManager.AppSettings["Ex_BMP"];
    //    string Ex_PNG = ConfigurationManager.AppSettings["Ex_PNG"];
    //    string Ex_PDF = ConfigurationManager.AppSettings["Ex_PDF"];
    //    string Ex_DOC = ConfigurationManager.AppSettings["Ex_DOC"];
    //    string Ex_DOCX = ConfigurationManager.AppSettings["Ex_DOCX"];
    //    string GetCurrentDate = DateTime.Today.ToString("yyyyMMdd");
    //    string GetEmployeeId = Convert.ToString(txt_SwipeCardNo.Text);
    //    string GetLeaveApplicationId = string.Empty;
    //    bool result = false;
    //    string GetDash = "_";
    //    string GetSessionEmployeeID = Convert.ToString(Session["EmployeeCodeId"]);


    //    if (GetCurrentDate != string.Empty && GetEmployeeId != string.Empty && lblCustomField3.Text != string.Empty)
    //    {
    //        string DocumentName = string.Concat(GetEmployeeId, GetDash, GetCurrentDate, GetDash, "CusFd3");
    //        if (txtCustomField3.HasFile)
    //        {
    //            string fileExtension = System.IO.Path.GetExtension(txtCustomField3.FileName);
    //            if (fileExtension != Ex_PDF)
    //            {
    //                ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('Please Upload only PDF extension file format');", true);
    //            }
    //            else
    //            {
    //                int fileSize = txtCustomField3.PostedFile.ContentLength;
    //                if (fileSize == 0 || fileSize > MaxFileSize)
    //                {
    //                    ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('Maximum upload file size is 5MB.');", true);
    //                }
    //                else
    //                {
    //                    try
    //                    {
    //                        string extension = Path.GetExtension(txtCustomField3.PostedFile.FileName);
    //                        DirectoryInfo isDirectExists = new DirectoryInfo(Server.MapPath("~/Masters/EmployeeDocumentUpload"));
    //                        if (!isDirectExists.Exists)
    //                        {
    //                            ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('The Application doest not contain Leave Application Upload Files folder, please create it');", true);
    //                            result = false;
    //                        }
    //                        else
    //                        {
    //                            string serverpath = Server.MapPath("~/Masters/EmployeeDocumentUpload/") + DocumentName + extension;
    //                            finalCustomefile3 = AppendFileNumberIfExists(serverpath, extension);
    //                            txtCustomField3.SaveAs(finalCustomefile3);
    //                            Session["EmployeeCusDoc3"] = finalCustomefile3;
    //                            //ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('File uploaded Sucessfully');", true);
    //                            btnCustomAdd3.Visible = false;
    //                            btnCustomView3.Visible = true;
    //                            hdnpdfViewer3.Value = finalCustomefile3;
    //                            //txtCustomField1.FileName = DocumentName;
    //                        }
    //                    }
    //                    catch (Exception ex)
    //                    {
    //                        ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('File Could not be uploaded');", true);
    //                    }
    //                }
    //            }
    //        }
    //        else
    //        {
    //            ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('Upload the necessary document to avail this leave.');", true);

    //        }
    //    }
    //    else
    //    {
    //        ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('File Could not be uploaded');", true);
    //    }
    //}

    //protected void btnCustomAdd4_Click(object sender, EventArgs e)
    //{
    //    int MaxFileSize = Convert.ToInt32(ConfigurationManager.AppSettings["MaxFileSize"]);
    //    string Ex_JPEG = ConfigurationManager.AppSettings["Ex_JPEG"];
    //    string Ex_JPG = ConfigurationManager.AppSettings["Ex_JPG"];
    //    string Ex_BMP = ConfigurationManager.AppSettings["Ex_BMP"];
    //    string Ex_PNG = ConfigurationManager.AppSettings["Ex_PNG"];
    //    string Ex_PDF = ConfigurationManager.AppSettings["Ex_PDF"];
    //    string Ex_DOC = ConfigurationManager.AppSettings["Ex_DOC"];
    //    string Ex_DOCX = ConfigurationManager.AppSettings["Ex_DOCX"];
    //    string GetCurrentDate = DateTime.Today.ToString("yyyyMMdd");
    //    string GetEmployeeId = Convert.ToString(txt_SwipeCardNo.Text);
    //    string GetLeaveApplicationId = string.Empty;
    //    bool result = false;
    //    string GetDash = "_";
    //    string GetSessionEmployeeID = Convert.ToString(Session["EmployeeCodeId"]);


    //    if (GetCurrentDate != string.Empty && GetEmployeeId != string.Empty && lblCustomField4.Text != string.Empty)
    //    {
    //        string DocumentName = string.Concat(GetEmployeeId, GetDash, GetCurrentDate, GetDash, "CusFd4");
    //        if (txtCustomField4.HasFile)
    //        {
    //            string fileExtension = System.IO.Path.GetExtension(txtCustomField4.FileName);
    //            if (fileExtension != Ex_PDF)
    //            {
    //                ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('Please Upload only PDF extension file format');", true);
    //            }
    //            else
    //            {
    //                int fileSize = txtCustomField4.PostedFile.ContentLength;
    //                if (fileSize == 0 || fileSize > MaxFileSize)
    //                {
    //                    ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('Maximum upload file size is 5MB.');", true);
    //                }
    //                else
    //                {
    //                    try
    //                    {
    //                        string extension = Path.GetExtension(txtCustomField4.PostedFile.FileName);
    //                        DirectoryInfo isDirectExists = new DirectoryInfo(Server.MapPath("~/Masters/EmployeeDocumentUpload"));
    //                        if (!isDirectExists.Exists)
    //                        {
    //                            ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('The Application doest not contain Leave Application Upload Files folder, please create it');", true);
    //                            result = false;
    //                        }
    //                        else
    //                        {
    //                            string serverpath = Server.MapPath("~/Masters/EmployeeDocumentUpload/") + DocumentName + extension;
    //                            finalCustomefile4 = AppendFileNumberIfExists(serverpath, extension);
    //                            txtCustomField4.SaveAs(finalCustomefile4);
    //                            Session["EmployeeCusDoc4"] = finalCustomefile4;
    //                            //ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('File uploaded Sucessfully');", true);
    //                            btnCustomAdd4.Visible = false;
    //                            btnCustomView4.Visible = true;
    //                            hdnpdfViewer4.Value = finalCustomefile4;
    //                            //txtCustomField1.FileName = DocumentName;
    //                        }
    //                    }
    //                    catch (Exception ex)
    //                    {
    //                        ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('File Could not be uploaded');", true);
    //                    }
    //                }
    //            }
    //        }
    //        else
    //        {
    //            ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('Upload the necessary document to avail this leave.');", true);

    //        }
    //    }
    //    else
    //    {
    //        ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('File Could not be uploaded');", true);
    //    }
    //}

    //protected void btnCustomAdd5_Click(object sender, EventArgs e)
    //{
    //    int MaxFileSize = Convert.ToInt32(ConfigurationManager.AppSettings["MaxFileSize"]);
    //    string Ex_JPEG = ConfigurationManager.AppSettings["Ex_JPEG"];
    //    string Ex_JPG = ConfigurationManager.AppSettings["Ex_JPG"];
    //    string Ex_BMP = ConfigurationManager.AppSettings["Ex_BMP"];
    //    string Ex_PNG = ConfigurationManager.AppSettings["Ex_PNG"];
    //    string Ex_PDF = ConfigurationManager.AppSettings["Ex_PDF"];
    //    string Ex_DOC = ConfigurationManager.AppSettings["Ex_DOC"];
    //    string Ex_DOCX = ConfigurationManager.AppSettings["Ex_DOCX"];
    //    string GetCurrentDate = DateTime.Today.ToString("yyyyMMdd");
    //    string GetEmployeeId = Convert.ToString(txt_SwipeCardNo.Text);
    //    string GetLeaveApplicationId = string.Empty;
    //    bool result = false;
    //    string GetDash = "_";
    //    string GetSessionEmployeeID = Convert.ToString(Session["EmployeeCodeId"]);


    //    if (GetCurrentDate != string.Empty && GetEmployeeId != string.Empty && lblCustomField5.Text != string.Empty)
    //    {
    //        string DocumentName = string.Concat(GetEmployeeId, GetDash, GetCurrentDate, GetDash, "CusFd5");
    //        if (txtCustomField5.HasFile)
    //        {
    //            string fileExtension = System.IO.Path.GetExtension(txtCustomField5.FileName);
    //            if (fileExtension != Ex_DOC && fileExtension != Ex_DOCX && fileExtension != Ex_PDF && fileExtension != Ex_JPG && fileExtension != Ex_JPEG)
    //            {
    //                ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('Please Upload only PDF,DOC,JPEG.JPG extension file format');", true);
    //            }
    //            else
    //            {
    //                int fileSize = txtCustomField5.PostedFile.ContentLength;
    //                if (fileSize == 0 || fileSize > MaxFileSize)
    //                {
    //                    ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('Maximum upload file size is 5MB.');", true);
    //                }
    //                else
    //                {
    //                    try
    //                    {
    //                        string extension = Path.GetExtension(txtCustomField5.PostedFile.FileName);
    //                        DirectoryInfo isDirectExists = new DirectoryInfo(Server.MapPath("~/Masters/EmployeeDocumentUpload"));
    //                        if (!isDirectExists.Exists)
    //                        {
    //                            ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('The Application doest not contain Leave Application Upload Files folder, please create it');", true);
    //                            result = false;
    //                        }
    //                        else
    //                        {
    //                            string serverpath = Server.MapPath("~/Masters/EmployeeDocumentUpload/") + DocumentName + extension;
    //                            finalCustomefile5 = AppendFileNumberIfExists(serverpath, extension);
    //                            txtCustomField5.SaveAs(finalCustomefile5);
    //                            Session["EmployeeCusDoc5"] = finalCustomefile5;
    //                            //ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('File uploaded Sucessfully');", true);
    //                            btnCustomAdd5.Visible = false;
    //                            btnCustomView5.Visible = true;
    //                            hdnpdfViewer5.Value = finalCustomefile5;
    //                            //txtCustomField1.FileName = DocumentName;
    //                        }
    //                    }
    //                    catch (Exception ex)
    //                    {
    //                        ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('File Could not be uploaded');", true);
    //                    }
    //                }
    //            }
    //        }
    //        else
    //        {
    //            ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('Upload the necessary document to avail this leave.');", true);

    //        }
    //    }
    //    else
    //    {
    //        ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('File Could not be uploaded');", true);
    //    }
    //}

    private string AppendFileNumberIfExists(string file, string ext)
    {
        // If the file exists, then do stuff. Otherwise, we just return the original file name.
        if (File.Exists(file))
        {
            string folderPath = Path.GetDirectoryName(file); // The path to the file. No sense in dealing with this unecessarily. 
            string fileName = Path.GetFileNameWithoutExtension(file); // The file name with no extension. 
            string extension = string.Empty; // The file extension. 
                                             // This lets us pass in an empty string for the file extension if required. i.e. It just makes this function a bit more versatile. 
            if (ext == string.Empty)
            {
                extension = Path.GetExtension(file);
            }
            else
            {
                extension = ext;
            }
            // at this point, find out if the fileName ends in a number, then get that number.
            int fileNumber = 0; // This stores the number as a number for us. 
                                // need a regex here - \(([0-9]+)\)$
            Regex r = new Regex(@"\(([0-9]+)\)$"); // This matches the pattern we are using, i.e. ~(#).ext
            Match m = r.Match(fileName); // We pass in the file name with no extension.
            string addSpace = " "; // We'll add a space when we don't have our pattern in order to pad the pattern.
            if (m.Success)
            {
                addSpace = string.Empty; // We have the pattern, so we don't add a space - it has already been added. 
                string s = m.Groups[1].Captures[0].Value; // This is the single capture that we are looking for. Stored as a string.
                                                          // set fileNumber to the new number.
                fileNumber = int.Parse(s); // Convert the number to an int.
                                           // remove the numbering from the string as we're constructing it again below.
                fileName = fileName.Replace("(" + s + ")", "");
            }
            if (File.Exists(file))
            {
                File.Delete(file);
            }

            // Start looping. 
            //do
            //{
            //    fileNumber += 1; // Increment the file number that we have above. 
            //    file = Path.Combine(folderPath, // Combine it all.
            //                            String.Format("{0}{3}({1}){2}", // The pattern to combine.
            //                                                      fileName,         // The file name with no extension. 
            //                                                      fileNumber,       // The file number.
            //                                                      extension,        // The file extension.
            //                                                      addSpace));       // A space if needed to pad the initial ~(#).ext pattern.
            //}
            //while (File.Exists(file)); // As long as the file name exists, keep looping. 
        }
        return file;
    }

    //protected void btnDeleteDoc_Click(object sender, EventArgs e)
    //{
    //    if (File.Exists(Convert.ToString(hdnDeleteDocURL.Value)))
    //    {
    //        File.Delete(Convert.ToString(hdnDeleteDocURL.Value));
    //        //Response.Redirect("../Masters/TA_UI_Master_EmployeeModify.aspx?isFileDeleted=Y");
    //        //Proc_TA_EmployeeMasterDocumentUpload

    //        if (hdnpdfViewer1.Value == hdnDeleteDocURL.Value)
    //        {
    //            hdnpdfViewer1.Value = string.Empty;
    //            //objEmployee.updateEmployeeDocument(txt_SwipeCardNo.Text, hdnpdfViewer1.Value, "cusField1");
    //            btnCustomView1.Visible = false;
    //            btnCustomAdd1.Visible = true;
    //        }
    //        if (hdnpdfViewer2.Value == hdnDeleteDocURL.Value)
    //        {
    //            hdnpdfViewer2.Value = string.Empty;
    //            //objEmployee.updateEmployeeDocument(txt_SwipeCardNo.Text, hdnpdfViewer2.Value, "cusField2");
    //            btnCustomView2.Visible = false;
    //            btnCustomAdd2.Visible = true;
    //        }
    //        if (hdnpdfViewer3.Value == hdnDeleteDocURL.Value)
    //        {
    //            hdnpdfViewer3.Value = string.Empty;
    //            //objEmployee.updateEmployeeDocument(txt_SwipeCardNo.Text, hdnpdfViewer3.Value, "cusField3");
    //            btnCustomView3.Visible = false;
    //            btnCustomAdd3.Visible = true;
    //        }
    //        if (hdnpdfViewer4.Value == hdnDeleteDocURL.Value)
    //        {
    //            hdnpdfViewer4.Value = string.Empty;
    //            //objEmployee.updateEmployeeDocument(txt_SwipeCardNo.Text, hdnpdfViewer4.Value, "cusField4");
    //            btnCustomView4.Visible = false;
    //            btnCustomAdd4.Visible = true;
    //        }
    //        if (hdnpdfViewer5.Value == hdnDeleteDocURL.Value)
    //        {
    //            hdnpdfViewer5.Value = string.Empty;
    //            //objEmployee.updateEmployeeDocument(txt_SwipeCardNo.Text, hdnpdfViewer5.Value, "cusField5");
    //            btnCustomView5.Visible = false;
    //            btnCustomAdd5.Visible = true;
    //        }

    //    }

    //}

    //public void Page_init()
    //{
    //    string A = Convert.ToString(Request.QueryString["desgnignationId"]);
    //    if (Convert.ToString(Request.QueryString["desgnignationId"])== "1")
    //    {
    //        ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", " $('#myModal').modal('hide');", true);
    //    }

    //    if(HdnEmpMasterDesignation.Value =="")
    //    {

    //    }
    //}
}